/* * The file "calc.y": Parser definitions * Contains the grammar rules and semantic actions. * Used by bison as an input file. */ /*========== 1. The Definition Section ==============================*/ %{ #include #include #include #include /* The file "parser.h" contains the definition of YYSTYPE: */ /* the type of values in the semantic stack of parser */ #include "parser.h" /* Any C++ code may be added here... */ %} %term INT_CONST DOUBLE_CONST %term ENDL LPAR RPAR ILLEGAL %left PLUS MINUS %left MULT DIV %nonassoc UMINUS /* Fictive lexeme for unary minus */ %% /*========== 2. The Grammar Section =========================================*/ /* Program is a sequence of lines containing expressions */ program : line | program line ; /* Line is an expression followed by the "end line" character */ line : e ENDL { /* print the value of expression */ printf("= %lf\n", $1); } | ENDL { return 0; } /* exit on empty line */ | error ENDL {} /* error recovery on end line */ ; /* Expression */ e : e PLUS e { $$ = $1 + $3; } | e MINUS e { $$ = $1 - $3; } | e MULT e { $$ = $1 * $3; } | e DIV e { $$ = $1 / $3; } | MINUS e %prec UMINUS { $$ = (-$2); } | PLUS e { $$ = $2; } | LPAR e RPAR { $$ = $2; } | INT_CONST { $$ = $1; } | DOUBLE_CONST { $$ = $1; } ; %% /*================ 3. The Program Section ================================*/ int main() { printf("Enter an expression to evaluate (empty line for quit):\n"); yyparse(); return 0; } /* Parse error diagnostics */ int yyerror(const char *s) { printf("%s\n", s); return 0; }