-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInterpret.java
More file actions
65 lines (56 loc) · 1.44 KB
/
Copy pathInterpret.java
File metadata and controls
65 lines (56 loc) · 1.44 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
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
class Interpreter {
private Stack<Integer> evalStack = new Stack<Integer>();
public int interpret(ByteCode[] byteCodes) {
for(ByteCode byteCode : byteCodes) {
byteCode.exec(evalStack);
}
return evalStack.pop();
}
}
abstract class ByteCode {
abstract public void exec(Stack<Integer> execStack);
}
class ILOAD extends ByteCode {
int val;
public ILOAD(int arg) {
val = arg;
}
public void exec(Stack<Integer> execStack) {
execStack.push(val);
}
}
class IADD extends ByteCode {
public void exec(Stack<Integer> execStack) {
execStack.push(execStack.pop() + execStack.pop());
}
}
class IMUL extends ByteCode {
public void exec(Stack<Integer> execStack) {
execStack.push(execStack.pop() * execStack.pop());
}
}
class ISUB extends ByteCode {
public void exec(Stack<Integer> execStack) {
int rval = execStack.pop();
int lval = execStack.pop();
execStack.push(lval - rval);
}
}
class IDIV extends ByteCode {
public void exec(Stack<Integer> execStack) {
int rval = execStack.pop();
int lval = execStack.pop();
execStack.push(lval / rval);
}
}
class Interpret {
public static void main(String []args) {
// ((10 * 20) + 30)
ByteCode []byteCodes = { new ILOAD(0x0A), new ILOAD(0x14), new IMUL(), new ILOAD(0x1E), new IADD() };
Interpreter interpreter = new Interpreter();
System.out.println(interpreter.interpret(byteCodes));
}
}