1+(2*3), such a formula is in the form of infix
calc.y
%{
#include <stdio.h>
void yyerror(const char* msg) {}
%}
%token T_NUM T_WS
%left '+' '-'
%left '*' '/'
%%
S : S E '\n' { printf(" ans = %d\n", $2); }
| /* empty */ { /* empty */ }
;
E : E E '+' { $$ = $1 + $3; }
| E E '-' { $$ = $1 - $3; }
| E E '*' { $$ = $1 * $3; }
| E E '/' { $$ = $1 / $3; }
| T_NUM { $$ = $1; printf("数字是:%d",$1); }
| '(' E ')' { $$ = $2; printf("括号中%d间数字:%d\n",$1,$2); }
;
%%
int main() {
return yyparse();
}
calc.l
%{
#include "y.tab.h"
%}
WHITESPACE ([ \t]*)
%%
[0-9]+ { yylval = atoi(yytext); return T_NUM; }
[-/+*()@\n] { return yytext[0]; }
{WHITESPACE} {return T_WS;}
. { return 0; /* end when meet everything else */ }
%%
int yywrap(void) {
return 1;
}