/* file name : calc3.y */ /* Calculator grammar with variables and float values. */ /* Variables are single letters and symbol table is a */ /* simple array of double, indexed by variable names. */ /* Associativity and precedence declarations used to */ /* disambiguate the grammar. */ /* Derived from "lex and yacc" ch3-03.y (page 64) */ %{ #include double vbltable[26]; %} %union { double dval; int vblno; } %token NAME %token NUMBER %type expression %type term %type factor %% input : /* empty */ | input line ; line : '\n' | NAME '=' expression '\n' { vbltable[$1] = $3; } | expression '\n' { printf ("\t= %.2f\n", $1); } ; expression : expression '+' term { $$ = $1 + $3; } | expression '-' term { $$ = $1 - $3; } | term { $$ = $1; } ; term : term '*' factor { $$ = $1 * $3; } | term '/' factor { if ($3 == 0.0) yyerror("divide by zero"); else $$ = $1 / $3; } | factor { $$ = $1; } ; factor : '-' factor { $$ = - $2; } | '(' expression ')' { $$ = $2; } | NUMBER { $$ = $1; } | NAME { $$ = vbltable[$1]; } ; %% main () { yyparse (); } yyerror (char *s) /* Called by yyparse on error */ { printf ("\terror: %s\n", s); }