-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcalc.y
93 lines (79 loc) · 2.2 KB
/
calc.y
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
%{
void yyerror (char *s);
int yylex();
#include <stdio.h> /* C declarations used in actions */
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int symbols[52];
int symbolVal(char symbol); // check symbol table
void updateSymbolVal(char symbol, int val);
%}
%union {int num; char id;} /* Yacc definitions, specify what types can be returned from our language */
%start line
%token print
%token exit_command
%token pow_command
%token sqrt_command
%token <num> number
%token <id> ID
%type <num> line exp term
%type <id> assignment
%%
/* descriptions of expected inputs corresponding actions (in C) */
line : assignment ';' {;}
| exit_command ';' {exit(EXIT_SUCCESS);}
| print exp ';' {printf("Printing %d\n", $2);}
| line assignment ';' {;}
| line print exp ';' {printf("Printing %d\n", $3);}
| line exit_command ';' {exit(EXIT_SUCCESS);}
;
assignment : ID '=' exp { updateSymbolVal($1,$3); }
;
exp : term {$$ = $1;}
| exp '+' term {$$ = $1 + $3;}
| exp '-' term {$$ = $1 - $3;}
| exp '*' term {$$ = $1 * $3;}
| exp '/' term {$$ = $1 / $3;}
| exp pow_command term {$$ = pow($1, $3);}
| exp '+' sqrt_command term {$$ = $1 + sqrt($4);}
| exp '-' sqrt_command term {$$ = $1 - sqrt($4);}
| exp '*' sqrt_command term {$$ = $1 * sqrt($4);}
| exp '/' sqrt_command term {$$ = $1 / sqrt($4);}
| sqrt_command term {$$ = sqrt($2);}
;
term : number {$$ = $1;}
| ID {$$ = symbolVal($1);}
;
%% /* C code */
int computeSymbolIndex(char token)
{
int idx = -1;
if(islower(token)) {
idx = token - 'a' + 26;
} else if(isupper(token)) {
idx = token - 'A';
}
return idx;
}
/* returns the value of a given symbol */
int symbolVal(char symbol)
{
int bucket = computeSymbolIndex(symbol);
return symbols[bucket];
}
/* updates the value of a given symbol */
void updateSymbolVal(char symbol, int val)
{
int bucket = computeSymbolIndex(symbol);
symbols[bucket] = val;
}
int main (void) {
/* init symbol table */
int i;
for(i=0; i<52; i++) {
symbols[i] = 0;
}
return yyparse ( );
}
void yyerror (char *s) {fprintf (stderr, "%s\n", s);}