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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* SI 413 Fall 2013
 * Lab 4
 * Bison file specifying the calculator program parser
 * YOUR NAME(S) HERE
 */
 
  /* Everything in this block goes in the header file calc.tab.hpp. */
%code requires {
#include <cstdlib> // for atoi
#include <iostream>
#include <string>
#include <map>
#include "colorout.hpp"
using namespace std;
 
//-- Lexer prototype required by bison
int yylex(); 
 
// Global variables for printing in pretty colors
extern colorout resout;
extern colorout errout;
}
 
  /* Everything in this block only goes in the bison file. */
%code {
 
// Error function that bison will call
void yyerror(const char *description) { 
  errout << description << endl; 
}
 
// Global variable to indicate done-ness
bool keepgoing = true;
 
// For Ex 2
// prints n as a signed binary number
void printbin(int n);
 
}
 
  /* Tell bison to give descriptive error messages. */
%error-verbose
 
  /* These are the different "semantic values" that a token can have. */
%union {
  int val; 
  char sym;
};
 
  /* These are the basic token types, organized by what kind
   * of semantic value they can have. */
%token <val> NUM
%token <sym> OPA OPM 
%token LP RP STOP 
 
  /* These are the non-terminal names that have values. */
%type <val> exp term sfactor factor
 
//-- GRAMMAR RULES ---------------------------------------
%%
  /* Note: YYACCEPT is a macro that tells bison to stop parsing. */
S: stmt { YYACCEPT; }
|       { keepgoing = false; }
 
stmt: exp STOP { resout << $1 << endl; }
 
exp: exp OPA term      { $$ = ($2 == '+' ? $1 + $3 : $1 - $3); }
| term                 { $$ = $1; }
 
term: term OPM sfactor { $$ = ($2 == '*' ? $1 * $3 : $1 / $3); }
| sfactor              { $$ = $1; }
 
sfactor: OPA factor    { $$ = ($1 == '+' ? $2 : -$2); }
| factor               { $$ = $1; }
 
factor: NUM            { $$ = $1; }
| LP exp RP            { $$ = $2; }
 
%%
// These are the colored output streams to make things all pretty.
colorout resout(1, 'u');
colorout errout(2, 'r');
 
//-- FUNCTION DEFINITIONS ---------------------------------
int main()
{
  // This checks whether the output is a terminal.
  bool tty = isatty(0) && isatty(2);
 
  while (keepgoing) {
    if (tty) cerr << "> " << flush;
    yyparse();
  }
  if (tty) cerr << "Goodbye" << endl;
  return 0;
}
 
void printbin(int n) {
  if (n < 0) { 
    resout << '-'; 
    n = -n; 
  }
  int bit = 1;
  while (bit > 0 && bit*2 <= n) bit *= 2;
  while (bit > 0) {
    if (bit <= n) {
      n -= bit;
      resout << '1';
    }
    else resout << '0';
    bit /= 2;
  }
  return;
}