|
用Lex(flex)和yacc(bison)写的简单计算器(2) {rp} { return RP;} {nl} { return NL;} . { return yytext[0];} 以上是Lex文件的代码(cal.l),lex是用来得到token。有了token之后呢,就用yacc(本人用的是GNU的可以在windows下面运行的bison)才处理这些符号。也就是写出一个个的状态,最后得到分析结果。
下面是yacc文件的代码(cal.y): %{ #include <stdio.h> #include <math.h> %} %union{ double real; /* real value */ int integer; /* integer value */ } %token <real> REAL %token <integer> INTEGER
%start lines %token NUMBER NL %token PLUS MINUS TIMES DIVIDE MODULE POWER LP RP %type <real> reXPr %type <integer> iexpr %left PLUS MINUS /*left associative */ %left TIMES DIVIDE MODULE /*left associative */ %left POWER %left UNARYMINUS
%% lines: /* nothing */ lines line NL lines error NL { yyerror();yyerrok; } ; line : iexpr {printf("%d\n",$1);} rexpr {printf("%lf\n",$1);} ; iexpr: INTEGER { $$ = $1; }
|