/* * Complete yacc input file for a simple expression evaluator. * Adapted from Louden, p. 229. */ %{ #include #include #define YYSTYPE float %} %token NUMBER %% commands : commands command | command ; command : exp '\n' { printf("%f\n", $1); } | '\n' { } ; exp : exp '+' term { $$ = $1 + $3; } | exp '-' term { $$ = $1 - $3; } | term { $$ = $1; } ; term : term '*' factor { $$ = $1 * $3; } | term '/' factor { $$ = $1 / $3; } | factor { $$ = $1; } ; factor : NUMBER { $$ = $1; } | '(' exp ')' { $$ = $2; } ; %% int main(void) { return yyparse(); } /* lexical analyser */ int yylex(void) { int c; /* skip blanks */ while ((c = getchar()) == ' '); /* get number */ if (isdigit(c)) { ungetc(c, stdin); scanf("%f", &yylval); return NUMBER; } /* else return character */ return c; } /* report errors */ int yyerror(char *s) { fprintf(stderr, "%s\n", s); }