1   // Copyright 2012- Bill Campbell, Swami Iyer and Bahar Akbal-Delibas
2   
3   package jminusminus;
4   
5   import static jminusminus.CLConstants.*;
6   
7   /**
8    * The AST node for an if-statement.
9    */
10  class JIfStatement extends JStatement {
11      // Test expression.
12      private JExpression condition;
13  
14      // Then part.
15      private JStatement thenPart;
16  
17      // Else part.
18      private JStatement elsePart;
19  
20      /**
21       * Constructs an AST node for an if-statement.
22       *
23       * @param line      line in which the if-statement occurs in the source file.
24       * @param condition test expression.
25       * @param thenPart  then part.
26       * @param elsePart  else part.
27       */
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      /**
36       * {@inheritDoc}
37       */
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      /**
49       * {@inheritDoc}
50       */
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      /**
67       * {@inheritDoc}
68       */
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