/* file name calc4.y */ /* Calculator with variable identifiers */ /* Bison specification */ %{ #include /* for pow() function */ #include "symtab4.h" %} %union { double val; /* values of expressions */ symrec *tptr; /* symbol table pointer for variables */ } %token NUM %token VAR %type expr %left '-' '+' %left '*' '/' %nonassoc UMINUS %right '^' %% input : /* empty */ | input line ; line : '\n' | VAR '=' expr '\n' { $1->value = $3; } | expr '\n' { printf ("\t= %.2f\n", $1); } | error '\n' { yyerrok; } ; expr : expr '+' expr { $$ = $1 + $3; } | expr '-' expr { $$ = $1 - $3; } | expr '*' expr { $$ = $1 * $3; } | expr '/' expr { if ($3 == 0.0) yyerror("divide by zero"); else $$ = $1 / $3; } | '-' expr %prec UMINUS { $$ = - $2; } | expr '^' expr { $$ = pow($1,$3); } | '(' expr ')' { $$ = $2; } | NUM { $$ = $1; } | VAR { $$ = $1->value; } ; %% symrec *sym_table = (symrec *)0; main () { yyparse (); } yyerror (char *s) /* Called by yyparse on error */ { printf ("\terror: %s\n", s); }