-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsimcalc.y
52 lines (48 loc) · 1.14 KB
/
simcalc.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
%{ /* simcalc.y -- Simple Desk Calculator 25 Feb 91 */
/* To use: yacc simcalc.y
cc y.tab.c
./a.out
3+4*5 single-character numbers, +, *, ()
^D must have EOF between entries
3*7+5*6
^D
(3+4)*(5+6)
^C to stop. */
#include <ctype.h>
#include <stdio.h>
%}
%token DIGIT
%%
line : expr '\n' { printf("%d\n", $1); }
;
expr : expr '+' term { $$ = $1 + $3; }
| term
;
term : term '*' factor { $$ = $1 * $3; }
| factor
;
factor : '(' expr ')' { $$ = $2; }
| DIGIT
;
%%
yylex() {
int c;
c = getchar();
if (isdigit(c)) {
yylval = c - '0' ;
return DIGIT;
}
return c;
}
yyerror(s)
char * s;
{
fputs(s,stderr), putc('\n',stderr);
}
main() /* Call yylex repeatedly to test */
{ int res;
while (1)
{ res = yyparse();
/* printf("yyparse result = %8d\n", res); */
}
}