-
Notifications
You must be signed in to change notification settings - Fork 14
/
calc.y
91 lines (72 loc) · 1.23 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
/*
* integer calculator
*/
%{
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
%}
%pure_parser
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
start: lines;
lines: /* empty */
| lines line
;
line : expr '\n' { printf("%d\n", $1); }
| '\n' { printf("(empty line ignored)\n"); }
| error '\n'
;
expr : expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
| NUMBER { $$ = $1; }
;
%%
#if YYPURE
#define YYLEXARGS YYSTYPE *yylvalp
#define YYLVAL (*yylvalp)
#endif /* YYPURE */
#if !YYPURE
#define YYLEXARGS
#define YYLVAL yylval
#endif
int yylex(YYLEXARGS)
{
int c;
char *p;
char buf[100];
again:
c = getc(stdin);
if (c == EOF)
return 0;
else if (c == ' ' || c == '\t')
goto again;
else if (isdigit(c)) {
for (p = buf; isdigit(c); ) {
*p++ = c;
c = getc(stdin);
}
*p = '\0';
ungetc(c, stdin);
YYLVAL = atoi(buf);
return NUMBER;
} else
return c;
}
int yyerror(s)
char *s;
{
fprintf(stderr, "%s\n", s);
}
int main()
{
#ifdef YYDEBUG
yydebug = 1;
#endif
return yyparse();
}