1   // Copyright 2012- Bill Campbell, Swami Iyer and Bahar Akbal-Delibas
2   
3   package jminusminus;
4   
5   import java.util.ArrayList;
6   
7   /**
8    * The AST node for a block, which delimits a nested level of scope.
9    */
10  class JBlock extends JStatement {
11      // List of statements forming the block body.
12      private ArrayList<JStatement> statements;
13  
14      // The new context (built in analyze()) represented by this block.
15      private LocalContext context;
16  
17      /**
18       * Constructs an AST node for a block.
19       *
20       * @param line       line in which the block occurs in the source file.
21       * @param statements list of statements forming the block body.
22       */
23      public JBlock(int line, ArrayList<JStatement> statements) {
24          super(line);
25          this.statements = statements;
26      }
27  
28      /**
29       * Returns the list of statements comprising this block.
30       *
31       * @return the list of statements comprising this block.
32       */
33      public ArrayList<JStatement> statements() {
34          return statements;
35      }
36  
37      /**
38       * {@inheritDoc}
39       */
40      public JBlock analyze(Context context) {
41          // { ... } defines a new level of scope.
42          this.context = new LocalContext(context);
43  
44          for (int i = 0; i < statements.size(); i++) {
45              statements.set(i, (JStatement) statements.get(i).analyze(this.context));
46          }
47          return this;
48      }
49  
50      /**
51       * {@inheritDoc}
52       */
53      public void codegen(CLEmitter output) {
54          for (JStatement statement : statements) {
55              statement.codegen(output);
56          }
57      }
58  
59      /**
60       * {@inheritDoc}
61       */
62      public void toJSON(JSONElement json) {
63          JSONElement e = new JSONElement();
64          json.addChild("JBlock:" + line, e);
65          if (context != null) {
66              context.toJSON(e);
67          }
68          for (JStatement statement : statements) {
69              statement.toJSON(e);
70          }
71      }
72  }
73