/******************************************************** * Here is a simple int calculator based on bison, with * a hand-coded scanner. It is based explicity on the * finite automaton pictured in simple.ps. ********************************************************/ %{ #include <iostream> using namespace std; //-- Lexer prototype required by bison, aka getNextToken() int yylex(); int yyerror(const char *p) { cerr << "Error!" << endl; } %} //-- GRAMMAR SYMBOL DECLARATIONS %union { int val; char sym; }; %token <val> NUM %token <sym> OPA OPM LP RP STOP %type <val> exp term sfactor factor res //-- GRAMMAR RULES %% res: exp STOP { cout << $1 << endl; } exp: exp OPA term { $$ = ($2 == '+' ? $1 + $3 : $1 - $3); } | term { $$ = $1; } term: term OPM factor { $$ = ($2 == '*' ? $1 * $3 : $1 / $3); } | sfactor { $$ = $1; } sfactor: OPA factor { $$ = ($1 == '+' ? $2 : -$2); } | factor { $$ = $1; } factor: NUM { $$ = $1; } | LP exp RP { $$ = $2; } %% //-- FUNCTION DEFINITIONS int main() { while(1) yyparse(); return 0; }