-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpn.l
51 lines (43 loc) · 890 Bytes
/
rpn.l
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
%prefix Calc
%top {
#include <stdio.h>
#include <stdlib.h>
#define STK_SZ 20
long stack[STK_SZ];
int i = 0;
void err(const char *s)
{
fputs(s, stderr);
exit(1);
}
int main()
{
int c; char x;
Calc_state *r = CalcInit(malloc, free);
while((c = getchar()) != EOF) {
x = c;
if(!CalcRead(r, &x, 1)) err("bad input\n");
}
if(!CalcRead(r, NULL, 0)) err("bad input\n");
CalcDestroy(r);
return 0;
}
#define op(x) if(i < 2) err("stack underflow"); \
stack[i-2] = stack[i-2] x stack[i-1]; \
i -= 1
}
[0123456789]+ {
long n = 0; size_t j;
for(j = 0; j < yylen; ++j)
n = (n * 10) + (yytext[j] - '0');
if(i >= STK_SZ) err("stack overflow\n");
stack[i++] = n;
}
\+ { op(+); }
- { op(-); }
[*] { op(*); }
/ { op(/); }
p { printf("%ld\n", stack[i-1]); }
pop { if(i > 0) --i; }
// Skip over whitespace
[ \t\n] { ; }