1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* SI 413 Fall 2013
 * This is a bison file that will use the hand-coded scanner to
 * make a parser and interpreter for the simple calculator language.
 */
%{
#include <iostream>
#include <cstdlib>
using namespace std;
 
// Prototype for our scanner function, aka getNextToken()
int yylex(); 
 
int yyerror(const char *p) { 
  cerr << "Parser error!" << endl; 
  exit(2);
}
%}
 
//-- GRAMMAR SYMBOL DECLARATIONS
%union {
  int val; 
  char sym;
};
%token<val> NUM
%token<sym> OPA OPM 
%token LP RP STOP
%type<val> exp term factor
 
//-- GRAMMAR RULES 
%%
res: exp STOP         { cout << $1 << endl; YYACCEPT; }
|                     { cout << endl; exit(0); }
 
exp: exp OPA term     { $$ = ($2 == '+' ? $1 + $3 : $1 - $3); }
|    term             { $$ = $1; }
 
term: term OPM factor { $$ = ($2 == '*' ? $1 * $3 : $1 / $3); }
|     factor          { $$ = $1; }
 
factor: NUM           { $$ = $1; }
|       LP exp RP     { $$ = $2; }
 
%%
 
int main() {
  while(1) {
    cout << "> " << flush;
    yyparse();
  }
  return 0;
}