C代碼
%{
#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。