/* file name : calc2.y */ /* Calculator grammar for arithmetic expressions. */ /* Associativity and precedence declarations used to */ /* disambiguate the grammar. */ %{ #define YYSTYPE double #include %} %token NUMBER %left '-' '+' %left '*' '/' %nonassoc UMINUS %% input : /* empty */ | input line ; line : '\n' | expression '\n' { printf ("\t= %.2f\n", $1); } ; expression : expression '+' expression { $$ = $1 + $3; } | expression '-' expression { $$ = $1 - $3; } | expression '*' expression { $$ = $1 * $3; } | expression '/' expression { if ($3 == 0.0) yyerror("divide by zero"); else $$ = $1 / $3; } | '-' expression %prec UMINUS { $$ = - $2; } | '(' expression ')' { $$ = $2; } | NUMBER { $$ = $1; } ; %% main () { yyparse (); } yyerror (char *s) /* Called by yyparse on error */ { printf ("\terror: %s\n", s); }