%{ /* C declarations */ #define YYSTYPE double #include #include #include void yyerror(char* s) { printf("%s\n", s); } int yylex(void); %} /* Bison declarations */ %token NUMBER %left '+' '-' %left '*' '/' %% /* grammar rules */ input : {} | input line {} ; line : '\n' { exit(0); } | expr '\n' { printf("\t%g\n", $1); } ; expr : NUMBER { $$ = $1; } | expr '+' expr { $$ = $1 + $3; } | expr '-' expr { $$ = $1 - $3; } | expr '*' expr { $$ = $1 * $3; } | expr '/' expr { $$ = $1 / $3; } | '(' expr ')' { $$ = $2; } ; %% /* additional C code */ int yylex(void) { int c; do { c = getchar(); } while (c == ' ' || c == '\t'); if (isdigit(c) || c == '.') { ungetc(c, stdin); scanf("%lf", &yylval); return NUMBER; } else if (c == EOF) { return 0; } return c; } int main(void) { printf("Exit with Ctrl-c\n"); yyparse(); return 0; }