-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
322 lines (294 loc) · 10.5 KB
/
Calculator.java
File metadata and controls
322 lines (294 loc) · 10.5 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class Calculator {
private String input;
private double output;
private String error;
public Calculator() {
input = "";
output = 0.;
error = "";
}
private BufferedWriter bw = null;
private void evaluate() {
String tempvar;
File file = new File("./Instructions.java");
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(
"public class Instructions {\n" +
" public static double calculate() {\n" +
" double t0, t1, t2, t3, t4, t5, t6, t7,\n" +
" t8, t9,t10,t11,t12,t13,t14,t15,\n" +
" t16,t17,t18,t19,t20,t21,t22,t23,\n" +
" t24,t25,t26,t27,t28,t29,t30,t31;\n");
} catch (IOException e) {
e.printStackTrace();
}
len = offset = wordno = 0;
lookahead = TokenType.INVALID;
tempvar = expression();
try {
bw.write(
" return " + tempvar + " ;\n" +
" }\n" +
"}\n");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
freename(tempvar);
// compile source in Instructions.java
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int status = compiler.run(null, null, null, "-g", file.getPath());
if (status == 0) { //compilation success
// load the binary and invoke the calculate() method
try {
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { new URL("file:///" + file.getPath()) },
new FailLoader(this.getClass().getClassLoader()));
Class<?> clazz = Class.forName("Instructions", true, loader);
Method calculate =
clazz.getDeclaredMethod("calculate", (Class<?>[]) null);
output = (Double) calculate.invoke(null, (Object[]) null);
} catch (MalformedURLException e) { e.printStackTrace();
} catch (ClassNotFoundException e) { e.printStackTrace();
} catch (NoSuchMethodException e) { e.printStackTrace();
} catch (IllegalAccessException e) { e.printStackTrace();
} catch (IllegalArgumentException e) { e.printStackTrace();
} catch (InvocationTargetException e) { e.printStackTrace();
}
}
}
// lexer
// TokenType lex()
// boolean match(TokenType)
// void advance()
private final int MAX_CHARS = 50;
private char[] text = new char[MAX_CHARS];
private int len = 0;
private int offset = 0;
private int wordno = 0;
private TokenType lex() {
int current = offset + len;
for (; current != input.length(); ++current) {
try {
text[current] = input.charAt(current);
} catch (Exception e) {
// end of input
return TokenType.EOI;
}
offset = current;
len = 1;
if (input.length() - current > 1) {
text[current + 1] = input.charAt(current + 1);
if (Character.isWhitespace(text[current])
&& !Character.isWhitespace(text[current + 1])) {
++wordno;
}
}
if ((text[current] == 's' || text[current] == 'c' || text[current] == 't') && input.length() >= 4)
{
text[current + 2] = input.charAt(current + 2);
text[current + 3] = input.charAt(current + 3);
len = 4;
if (text[current] == 's' && text[current + 1] == 'i' && text[current + 2] == 'n' && text[current + 3] == '(')
{ return TokenType.SIN; }
else if (text[current] == 'c' && text[current + 1] == 'o' && text[current + 2] == 's' && text[current + 3] == '(')
{ return TokenType.COS; }
else if (text[current] == 't' && text[current + 1] == 'a' && text[current + 2] == 'n' && text[current + 3] == '(')
{ return TokenType.TAN; }
}
switch (text[current]) {
case '+': return TokenType.PLUS;
case '-': return TokenType.MINUS;
case '*': return TokenType.TIMES;
case '/': return TokenType.DIVIDE;
case '(': return TokenType.LPAREN;
case ')': return TokenType.RPAREN;
case '\n':
case '\t':
case ' ' : break;
default:
{
if (!Character.isDigit(input.charAt(current))) {
error += "Invalid character " + input.charAt(current) + " at word number " + wordno + "\n\n";
}
else {
while(current < input.length() &&
(Character.isDigit(input.charAt(current)) ||
'.' == input.charAt(current) ||
'+' == input.charAt(current) ||
'-' == input.charAt(current) ||
'e' == input.charAt(current))) {
if (current - offset >= MAX_CHARS) {
error += "Truncating numeric value at word number " + wordno + ".\n" +
" Limit 50 decimal digits.\n\n";
break;
}
text[current] = input.charAt(current);
++current;
}
len = current - offset;
return TokenType.NUM;
}
break;
}
}
}
return TokenType.EOI;
}
private TokenType lookahead = TokenType.INVALID;
private boolean match(TokenType token) {
if (lookahead == TokenType.INVALID) {
lookahead = lex();
}
return token == lookahead;
}
private void advance() {
lookahead = lex();
}
// temporary name pool
// String newname()
// freename(String)
private String names[] = { "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
"t8", "t9","t10","t11","t12","t13","t14","t15",
"t16","t17","t18","t19","t20","t21","t22","t23",
"t24","t25","t26","t27","t28","t29","t30","t31" };
private int nameidx = 0;
private String newname() {
if (nameidx >= names.length) {
error += wordno + ": Expression too complex\n\n";
return "---";
}
return names[nameidx++];
}
private void freename(String s) {
if (nameidx > 0) {
--nameidx;
} else {
error += wordno + ": (Internal error) Name stack underflow";
}
}
// parser
// expression()
// term()
// factor()
private String expression() {
if (match(TokenType.EOI)) {
error += wordno + ": expression incomplete";
return "---";
}
String tempvar, tempvar2;
tempvar = term();
while (match(TokenType.PLUS) || match(TokenType.MINUS)) {
String op = match(TokenType.PLUS) ? " += " : " -= ";
advance();
tempvar2 = term();
try {
bw.write(tempvar + op + tempvar2 + ";\n");
} catch (IOException e) {
e.printStackTrace();
}
freename(tempvar2);
}
return tempvar;
}
private String term() {
String tempvar, tempvar2;
tempvar = factor();
while (match(TokenType.TIMES) || match(TokenType.DIVIDE)) {
String op = match(TokenType.TIMES) ? " *= " : " /= ";
advance();
tempvar2 = factor();
try {
bw.write(tempvar + op + tempvar2 + ";\n");
} catch (IOException e) {
e.printStackTrace();
}
freename(tempvar2);
}
return tempvar;
}
private String factor() {
String tempvar = "";
if (match(TokenType.NUM)) {
tempvar = newname();
try {
StringBuilder sb = new StringBuilder();
for (int i = offset; i < offset + len; ++i) {
sb.append(text[i]);
}
bw.write(tempvar + " = " + sb.toString() + ";\n");
} catch (IOException e) {
e.printStackTrace();
}
advance();
} else if (match(TokenType.SIN) || match(TokenType.COS) ||
match(TokenType.TAN) || match(TokenType.LPAREN)) {
String op = match(TokenType.SIN) ? " = Math.sin(" :
match(TokenType.COS) ? " = Math.cos(" :
match(TokenType.TAN) ? " = Math.tan(" : "";
advance();
tempvar = expression();
try {
if (op != "") {
bw.write(tempvar + op + tempvar + ");\n");
}
} catch (IOException e) {
e.printStackTrace();
}
if (match(TokenType.RPAREN)) {
advance();
} else {
error += wordno + ": Mismatched parenthesis\n\n";
}
} else {
error += wordno + ": Number expected\n\n";
}
return tempvar;
}
// Field modifiers
// setInput(String)
// double getOutput()
// String getError()
public void setInput(String s) {
input = s;
evaluate();
}
public double getOutput() {
return output;
}
public String getError() {
return error;
}
public void clearError() {
error = "";
}
// for lexer, parser
private enum TokenType {
// Do not change the order
EOI,
INVALID,
NUM,
PLUS,
MINUS,
TIMES,
DIVIDE,
SIN,
COS,
TAN,
INV,
LPAREN,
RPAREN;
}
}