依托Bison强大的工具, 写编译器,先用编译原理搞个计算器玩玩。如下:
Bison工具:
http://coolshell.cn/articles/1547.html
http://www.gnu.org/software/bison/manual/index.html
http://baike.baidu.com/view/1137652.htm
1.1 Languages and Context-Free Grammars
文件:first.y
%{ #define YYSTYPE double #include <math.h> int yylex (void); void yyerror (char const *); %} %token NUM %% input: |input line ; line: '\n' | exp '\n' {printf("\t%.10g\n", $1);} ; exp: NUM { $$ = $1; } | exp exp '+' { $$ = $1 + $2; } | exp exp '-' { $$ = $1 - $2; } | exp exp '*' { $$ = $1 * $2; } | exp exp '/' { $$ = $1 / $2; } /* Unary minus */ | exp 'n' { $$ = -$1; } ; %% #include <stdio.h> int yylex (void) { int c; /* Skip white space. */ while ((c = getchar ()) == ' ' || c == '\t') ; /* Process numbers. */ if (c == '.' || isdigit (c)) { ungetc (c, stdin); scanf ("%lf", &yylval); return NUM; } /* Return end-of-input. */ if (c == EOF) return 0; /* Return a single char. */ return c; } void yyerror (char const * error) { } int main() { return yyparse (); }
在Ubuntu的linux下安装Bison2.5,运行:
bison first.y
gcc -o first first.tab.c
运行
./fisrt
1 4 +
5
3 10 *
30
OK。