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 a while-statement.
9    */
10  class JWhileStatement extends JStatement {
11      // Test expression.
12      private JExpression condition;
13  
14      // Body.
15      private JStatement body;
16  
17      /**
18       * Constructs an AST node for a while-statement.
19       *
20       * @param line      line in which the while-statement occurs in the source file.
21       * @param condition test expression.
22       * @param body      the body.
23       */
24      public JWhileStatement(int line, JExpression condition, JStatement body) {
25          super(line);
26          this.condition = condition;
27          this.body = body;
28      }
29  
30      /**
31       * {@inheritDoc}
32       */
33      public JWhileStatement analyze(Context context) {
34          condition = condition.analyze(context);
35          condition.type().mustMatchExpected(line(), Type.BOOLEAN);
36          body = (JStatement) body.analyze(context);
37          return this;
38      }
39  
40      /**
41       * {@inheritDoc}
42       */
43      public void codegen(CLEmitter output) {
44          String test = output.createLabel();
45          String out = output.createLabel();
46          output.addLabel(test);
47          condition.codegen(output, out, false);
48          body.codegen(output);
49          output.addBranchInstruction(GOTO, test);
50          output.addLabel(out);
51      }
52  
53      /**
54       * {@inheritDoc}
55       */
56      public void toJSON(JSONElement json) {
57          JSONElement e = new JSONElement();
58          json.addChild("JWhileStatement:" + line, e);
59          JSONElement e1 = new JSONElement();
60          e.addChild("Condition", e1);
61          condition.toJSON(e1);
62          JSONElement e2 = new JSONElement();
63          e.addChild("Body", e2);
64          body.toJSON(e2);
65      }
66  }
67