宗小宗-PHP程序猿

欢迎各位朋友前来,如果我的文章中有不对的地方,还望指正;如需转载,请注明原处

bison实例

逆波兰记号计算器【文件名rpcalc.y】

%{ #define YYSTYPE double #include <stdio.h> #include <math.h> #include <ctype.h> int yylex (void); void yyerror (char const *); %} %token NUM %% input: /* empty */ | 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; } /* Exponentiation */ | exp exp '^' { $$ = pow($1, $2); } /* Unary minus */ | exp 'n' { $$ = -$1; } ; %% #include <ctype.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 *s) { fprintf (stderr, "%s\n", s); } int main (void) { return yyparse (); }

------------------运行----------------------
bison rpcalc.y
gcc -o rpcalc -lm rpcalc.tab.c
./rpcalc
4 9 +
     13
 

 

中辍符号计算器【文件名calc.y】

%{ #define YYSTYPE double #include <math.h> #include <stdio.h> int yylex (void); void yyerror (char const *); %} /* Bison declarations. */ %token NUM %left '-' '+' %left '*' '/' %right '^' /* exponentiation */ %% /* The grammar follows. */ input: | input line ; line: '\n' | exp '\n' { printf ("\t%.10g\n", $1); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = $1 + $3; } | exp '-' exp { $$ = $1 - $3; } | exp '*' exp { $$ = $1 * $3; } | exp '/' exp { $$ = $1 / $3; } | '-' exp { $$ = -$2; } | exp '^' exp { $$ = pow ($1, $3); } | '(' exp ')' { $$ = $2; } ; %% #include <ctype.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 *s) { fprintf (stderr, "%s\n", s); } int main (void) { return yyparse (); }

------------------运行----------------------
bison calc.y
gcc -o calc -lm calc.tab.c
./calc
8*(1+3)
     32

 

posted @ 2017-01-16 15:25  宗小宗  阅读(712)  评论(0编辑  收藏  举报