-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCompiler.java
More file actions
78 lines (72 loc) · 1.39 KB
/
Copy pathCompiler.java
File metadata and controls
78 lines (72 loc) · 1.39 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
// This code targets two platforms: JVM and DOTNET
// Use visitor pattern to refactor the conditional checks
enum Target {
JVM, DOTNET
}
abstract class Expr {
public static Target t = Target.JVM;
public static void setTarget(Target target) {
t = target;
}
public abstract void genCode();
}
class Constant extends Expr {
int val;
public Constant(int arg) {
val = arg;
}
public void genCode() {
if(t == Target.JVM) {
System.out.println("bipush " + val);
}
else { // DOTNET
System.out.println("ldarg " + val);
}
}
}
class Plus extends Expr {
private Expr left, right;
public Plus(Expr arg1, Expr arg2) {
left = arg1;
right = arg2;
}
public void genCode() {
left.genCode();
right.genCode();
if(t == Target.JVM) {
System.out.println("iadd");
}
else { // DOTNET
System.out.println("add");
}
}
}
class Sub extends Expr {
private Expr left, right;
public Sub(Expr arg1, Expr arg2) {
left = arg1;
right = arg2;
}
public void genCode() {
left.genCode();
right.genCode();
if(t == Target.JVM) {
System.out.println("isub");
}
else { // DOTNET
System.out.println("sub");
}
}
}
class Compiler {
public static void main(String []args) {
Expr.setTarget(Target.JVM);
// (10 + (20 - 30))
Expr expr = new Plus(
new Constant(10),
new Sub(
new Constant(20),
new Constant(30)));
expr.genCode();
}
}