/* * Simple Calculator * Author: Jia Yu, * School: Univ of California Riverside * Date: April 9, 2003 */ /* Infix notation calculator--calc */ /* Everything up to "%}" is copied verbatim to the top of yac.c. (output file)*/ %{ #include #include #include #include #include "tok.h" using namespace std; void yyerror (const char *s); int yylex(void); %} // Here we define the types and names of the components of YYSTYPE, which // is the type of the semantic portion of parse-stack entries. // union members for lexical values of tokens %union{ int int_val; } // Specify in order of increasing precedence the names of the tokens, // their associativity, and which components of the union YYSTYPE // their lexical values will occupy. %token NUM %type exp %left MINUS PLUS %left MULT DIV %left NEG /* negation--unary minus */ // Specify the start symbol of the grammar. %start input %% // Specify the grammar rules and their associated semantic actions. input: | exp { printf("= %d \n ", $1); } | error { printf("error \n");} ; exp: NUM { $$=$1; } | exp PLUS exp { $$=$1+$3; } | exp MINUS exp { $$=$1-$3; } | exp MULT exp { $$ = $1 * $3; } | exp DIV exp { $$ = $1 / $3; } | '(' exp ')' { $$ = $2; } ; %% /* Called by yyparse on error */ void yyerror (string s) { extern int yylineno; extern char* yytext; cerr<<"ERROR: "<