1   // Copyright 2012- Bill Campbell, Swami Iyer and Bahar Akbal-Delibas
2   
3   package jminusminus;
4   
5   import java.util.ArrayList;
6   
7   import static jminusminus.CLConstants.*;
8   
9   /**
10   * The AST node for a "new" array operation. It keeps track of its base type and a list of its
11   * dimensions.
12   */
13  class JNewArrayOp extends JExpression {
14      // The base (component) type of the array.
15      private Type typeSpec;
16  
17      // Dimensions of the array.
18      private ArrayList<JExpression> dimExprs;
19  
20      /**
21       * Constructs an AST node for a "new" array operation.
22       *
23       * @param line     the line in which the operation occurs in the source file.
24       * @param typeSpec the type of the array being created.
25       * @param dimExprs a list of dimension expressions.
26       */
27      public JNewArrayOp(int line, Type typeSpec, ArrayList<JExpression> dimExprs) {
28          super(line);
29          this.typeSpec = typeSpec;
30          this.dimExprs = dimExprs;
31      }
32  
33      /**
34       * {@inheritDoc}
35       */
36      public JExpression analyze(Context context) {
37          type = typeSpec.resolve(context);
38          for (int i = 0; i < dimExprs.size(); i++) {
39              dimExprs.set(i, dimExprs.get(i).analyze(context));
40              dimExprs.get(i).type().mustMatchExpected(line, Type.INT);
41          }
42          return this;
43      }
44  
45      /**
46       * {@inheritDoc}
47       */
48      public void codegen(CLEmitter output) {
49          // Code to push diemension exprs on to the stack.
50          for (JExpression dimExpr : dimExprs) {
51              dimExpr.codegen(output);
52          }
53  
54          // Generates the appropriate array creation instruction.
55          if (dimExprs.size() == 1) {
56              output.addArrayInstruction(type.componentType().isReference() ?
57                      ANEWARRAY : NEWARRAY, type.componentType().jvmName());
58          } else {
59              output.addMULTIANEWARRAYInstruction(type.toDescriptor(), dimExprs.size());
60          }
61      }
62  
63      /**
64       * {@inheritDoc}
65       */
66      public void toJSON(JSONElement json) {
67          JSONElement e = new JSONElement();
68          json.addChild("JNewArrayOp:" + line, e);
69          e.addAttribute("type", type == null ? "" : type.toString());
70          if (dimExprs != null) {
71              for (JExpression dimExpr : dimExprs) {
72                  JSONElement e1 = new JSONElement();
73                  e.addChild("Dimension", e1);
74                  dimExpr.toJSON(e1);
75              }
76          }
77      }
78  }
79