TutorialFlexBison PDF
TutorialFlexBison PDF
To implement a scanner for calculator, we can write the file “cal1.l” as To implement a parser for calculator, we can write the file “cal.y” as below:
below:
%{
/* this is only for scanner, not link with parser yet */ #include <stdio.h>
%{ #include <ctype.h>
int lineNum = 0; int lineNum = 1;
%} void yyerror(char *ps, ...) { /* need this to avoid
link problem */
%% printf("%s\n", ps);
}
"(" { printf("(\n"); } %}
")" { printf(")\n"); }
"+" { printf("+\n"); } %union {
"*" { printf("*\n"); } int d;
\n { lineNum++; } }
[ \t]+ { } // need to choose token type from union above
[0-9]+ { printf("%s\n", yytext); } %token <d> NUMBER
%token '(' ')'
%% %left '+'
%left '*'
int yywrap() { %type <d> exp factor term
return 1;
} %start cal
int main () { %%
yylex();
return 0; cal
} : exp
{ printf("The result is %d\n", $1); }
Here is the Makefile used to build the scanner: ;