1
3 package jminusminus;
4
5 import static jminusminus.CLConstants.*;
6
7
10 class JIfStatement extends JStatement {
11 private JExpression condition;
13
14 private JStatement thenPart;
16
17 private JStatement elsePart;
19
20
28 public JIfStatement(int line, JExpression condition, JStatement thenPart, JStatement elsePart) {
29 super(line);
30 this.condition = condition;
31 this.thenPart = thenPart;
32 this.elsePart = elsePart;
33 }
34
35
38 public JStatement analyze(Context context) {
39 condition = (JExpression) condition.analyze(context);
40 condition.type().mustMatchExpected(line(), Type.BOOLEAN);
41 thenPart = (JStatement) thenPart.analyze(context);
42 if (elsePart != null) {
43 elsePart = (JStatement) elsePart.analyze(context);
44 }
45 return this;
46 }
47
48
51 public void codegen(CLEmitter output) {
52 String elseLabel = output.createLabel();
53 String endLabel = output.createLabel();
54 condition.codegen(output, elseLabel, false);
55 thenPart.codegen(output);
56 if (elsePart != null) {
57 output.addBranchInstruction(GOTO, endLabel);
58 }
59 output.addLabel(elseLabel);
60 if (elsePart != null) {
61 elsePart.codegen(output);
62 output.addLabel(endLabel);
63 }
64 }
65
66
69 public void toJSON(JSONElement json) {
70 JSONElement e = new JSONElement();
71 json.addChild("JIfStatement:" + line, e);
72 JSONElement e1 = new JSONElement();
73 e.addChild("Condition", e1);
74 condition.toJSON(e1);
75 JSONElement e2 = new JSONElement();
76 e.addChild("ThenPart", e2);
77 thenPart.toJSON(e2);
78 if (elsePart != null) {
79 JSONElement e3 = new JSONElement();
80 e.addChild("ElsePart", e3);
81 elsePart.toJSON(e3);
82 }
83 }
84 }
85