0
|
1 /*
|
|
2 Very Simple Calculator
|
|
3 $Id$
|
|
4 */
|
|
5
|
|
6 #include "s-compile.h"
|
|
7
|
|
8 int variable[48];
|
|
9
|
|
10 static int expr();
|
|
11 static int aexpr();
|
|
12 static int mexpr();
|
|
13 static int term();
|
|
14
|
|
15
|
|
16 static int
|
|
17 expr()
|
|
18 {
|
|
19 int d,assign;
|
|
20
|
|
21 d = aexpr();
|
|
22 assign = lvalue;
|
|
23 while(last_token!=EOF) {
|
|
24 switch(last_token) {
|
|
25 case '>':
|
|
26 d = (d > aexpr());
|
|
27 break;
|
|
28 case '=':
|
|
29 if(assign>=0) {
|
|
30 d = expr();
|
|
31 variable[assign] = d;
|
|
32 break;
|
|
33 } else {
|
|
34 error("Bad assignment");
|
|
35 break;
|
|
36 }
|
|
37 case ')':
|
|
38 return d;
|
|
39 default:
|
|
40 error("Bad expression");
|
|
41 return d;
|
|
42 }
|
|
43 }
|
|
44 return d;
|
|
45 }
|
|
46
|
|
47 static int
|
|
48 aexpr()
|
|
49 {
|
|
50 int d;
|
|
51
|
|
52 d = mexpr();
|
|
53 while(last_token!=EOF) {
|
|
54 switch(last_token) {
|
|
55 case '-':
|
|
56 d -= mexpr();
|
|
57 break;
|
|
58 case '+':
|
|
59 d += mexpr();
|
|
60 break;
|
|
61 default:
|
|
62 return d;
|
|
63 }
|
|
64 }
|
|
65 return d;
|
|
66 }
|
|
67
|
|
68 static int
|
|
69 mexpr()
|
|
70 {
|
|
71 int d;
|
|
72
|
|
73 d = term();
|
|
74 while(last_token!=EOF) {
|
|
75 switch(last_token) {
|
|
76 case '*':
|
|
77 d *= term();
|
|
78 break;
|
|
79 case '/':
|
|
80 d /= term();
|
|
81 break;
|
|
82 default:
|
|
83 return d;
|
|
84 }
|
|
85 }
|
|
86 return d;
|
|
87 }
|
|
88
|
|
89 static int
|
|
90 term()
|
|
91 {
|
|
92 int d;
|
|
93
|
|
94 lvalue= -1;
|
|
95 token();
|
|
96 if(last_token==EOF) {
|
|
97 error("Term expected");
|
|
98 }
|
|
99 switch(last_token) {
|
|
100 case '0':
|
|
101 d = value;
|
|
102 token();
|
|
103 return d;
|
|
104 case 'v':
|
|
105 d = lvalue = value;
|
|
106 token();
|
|
107 return variable[d];
|
|
108 case '(':
|
|
109 d = expr();
|
|
110 if(last_token != ')') {
|
|
111 error("Unbalanced parenthsis");
|
|
112 }
|
|
113 token();
|
|
114 return d;
|
|
115 default:
|
|
116 token();
|
|
117 error("Unknown term");
|
|
118 return 0;
|
|
119 }
|
|
120 }
|
|
121
|
|
122 int
|
|
123 main()
|
|
124 {
|
|
125 int d;
|
|
126 char buf[BUFSIZ];
|
|
127
|
|
128 while (fgets(buf,BUFSIZ,stdin)) {
|
|
129 ptr = buf;
|
|
130 d = expr();
|
|
131 printf("%s = 0x%08x = %d\n",buf,d,d);
|
|
132 fflush(stdout);
|
|
133 }
|
|
134 return 0;
|
|
135 }
|
|
136
|
|
137 /* end */
|