This commit is contained in:
corey 2024-02-16 14:16:47 -06:00
parent 97dd8f8004
commit 25a7b60305
5 changed files with 82 additions and 20 deletions

6
incdemo/Makefile Normal file
View File

@ -0,0 +1,6 @@
all: inc
inc: incdemo.c inc.l
lex inc.l
cc incdemo.c lex.yy.c -o incdemo
clean:
rm incdemo lex.yy.c

55
incdemo/inc.l Normal file
View File

@ -0,0 +1,55 @@
/*****
*
* How to include files using flex
*
*****/
/* the "incl" state is used for picking up the name
* of an include file
*/
%x incl
%{
#define MAX_INCLUDE_DEPTH 10
YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
int include_stack_ptr = 0;
%}
%%
include BEGIN(incl);
[a-z]+ ECHO;
[^a-z\n]*\n? ECHO;
<incl>[ \t]* /* eat the whitespace */
<incl>[^ \t\n]+ { /* got the include file name */
if ( include_stack_ptr >= MAX_INCLUDE_DEPTH )
{
fprintf( stderr, "Includes nested too deeply" );
exit( 1 );
}
include_stack[include_stack_ptr++] =
YY_CURRENT_BUFFER;
yyin = fopen( yytext, "r" );
if ( ! yyin )
error( "" );
yy_switch_to_buffer(
yy_create_buffer( yyin, YY_BUF_SIZE ) );
BEGIN(INITIAL);
}
<<EOF>> {
if ( --include_stack_ptr < 0 )
{
yyterminate();
}
else
yy_switch_to_buffer(
include_stack[include_stack_ptr] );
}

5
incdemo/incdemo.c Normal file
View File

@ -0,0 +1,5 @@
void yywrap(){}
int main()
{
while(yylex());
}

20
l.l
View File

@ -8,16 +8,14 @@
%%
[ \t] ; // ignore all whitespace
[0-9]+ {yylval = atoi(yytext); return T_INT;}
\n {return T_NEWLINE;}
"+" {return T_PLUS;}
"-" {return T_MINUS;}
"*" {return T_MULTIPLY;}
"/" {return T_DIVIDE;}
"(" {return T_LEFT;}
")" {return T_RIGHT;}
"exit" {return T_QUIT;}
"quit" {return T_QUIT;}
[ \t\n] ; // ignore all whitespace
[0-9]+ {yylval = atoi(yytext); return T_INT;}
"+" {return T_PLUS;}
"-" {return T_MINUS;}
"*" {return T_MULTIPLY;}
"/" {return T_DIVIDE;}
"(" {return T_LPAREN;}
")" {return T_RPAREN;}
"quit" {return T_QUIT;}
%%

16
l.y
View File

@ -9,31 +9,29 @@ extern FILE* yyin;
void yyerror(const char* s);
%}
%token T_PLUS T_MINUS T_MULTIPLY T_DIVIDE T_LEFT T_RIGHT
%token T_PLUS T_MINUS T_MULTIPLY T_DIVIDE T_LPAREN T_RPAREN
%token T_NEWLINE T_QUIT T_INT
%start translation_unit
%%
translation_unit: line
| translation_unit line
translation_unit: expression {printf("%d\n",$1);}
| translation_unit expression
;
line: T_INT T_NEWLINE {printf("%d\n",$1);}
expression: T_INT {$$=$1;}
| expression T_PLUS T_INT {$$=$1+$3;}
;
%%
int main()
{
yyin = stdin;
do yyparse();
while(!feof(yyin));
yyparse();
}
void yyerror(const char*s)
{
fprintf(stderr, "Parse error: %s\n", s);
fprintf(stderr,"error: %s\n",s);
exit(1);
}