1
3 package jminusminus;
4
5 import java.util.ArrayList;
6 import static jminusminus.CLConstants.*;
7
8
12
13 class JArrayInitializer extends JExpression {
14
15
16 private ArrayList<JExpression> initials;
17
18
30
31 public JArrayInitializer(int line, Type expected,
32 ArrayList<JExpression> initials) {
33 super(line);
34 type = expected;
35 this.initials = initials;
36 }
37
38
46
47 public JExpression analyze(Context context) {
48 type = type.resolve(context);
49 if (!type.isArray()) {
50 JAST.compilationUnit.reportSemanticError(line,
51 "Cannot initialize a " + type.toString()
52 + " with an array sequence {...}");
53 return this; }
55 Type componentType = type.componentType();
56 for (int i = 0; i < initials.size(); i++) {
57 JExpression component = initials.get(i);
58 initials.set(i, component = component.analyze(context));
59 if (!(component instanceof JArrayInitializer)) {
60 component.type().mustMatchExpected(line, componentType);
61 }
62 }
63 return this;
64 }
65
66
74
75 public void codegen(CLEmitter output) {
76 Type componentType = type.componentType();
77
78 new JLiteralInt(line, String.valueOf(initials.size())).codegen(output);
80
81 output.addArrayInstruction(componentType.isReference() ? ANEWARRAY
83 : NEWARRAY, componentType.jvmName());
84
85 for (int i = 0; i < initials.size(); i++) {
88 JExpression initExpr = initials.get(i);
89
90 output.addNoArgInstruction(DUP);
92
93 new JLiteralInt(line, String.valueOf(i)).codegen(output);
95
96 initExpr.codegen(output);
98
99 output.addNoArgInstruction(componentType.isReference() ? AASTORE
101 : IASTORE);
102 }
103 }
104
105
108
109 public void writeToStdOut(PrettyPrinter p) {
110 p.println("<JArrayInitializer>");
111 if (initials != null) {
112 for (JAST initial : initials) {
113 p.indentRight();
114 initial.writeToStdOut(p);
115 p.indentLeft();
116 }
117 }
118 p.println("</JArrayInitializer>");
119 }
120
121 }
122