1
3 package jminusminus;
4
5 import java.util.ArrayList;
6 import static jminusminus.CLConstants.*;
7
8
12
13 class JArrayInitializer
14 extends JExpression {
15
16
17 private ArrayList<JExpression> initials;
18
19
31
32 public JArrayInitializer(int line, Type expected,
33 ArrayList<JExpression> initials) {
34 super(line);
35 type = expected;
36 this.initials = initials;
37 }
38
39
48
49 public JExpression analyze(Context context) {
50 type = type.resolve(context);
51 if (!type.isArray()) {
52 JAST.compilationUnit.reportSemanticError(line,
53 "Cannot initialize a " + type.toString()
54 + " with an array sequence {...}");
55 return this; }
57 Type componentType = type.componentType();
58 for (int i = 0; i < initials.size(); i++) {
59 JExpression component = initials.get(i);
60 initials.set(i, component = component.analyze(context));
61 if (!(component instanceof JArrayInitializer)) {
62 component.type().mustMatchExpected(line,
63 componentType);
64 }
65 }
66 return this;
67 }
68
69
77
78 public void codegen(CLEmitter output) {
79 Type componentType = type.componentType();
80
81 new JLiteralInt(line, String.valueOf(initials.size()))
83 .codegen(output);
84
85 output.addArrayInstruction(componentType.isReference()
87 ? ANEWARRAY
88 : NEWARRAY, componentType.jvmName());
89
90 for (int i = 0; i < initials.size(); i++) {
93 JExpression initExpr = initials.get(i);
94
95 output.addNoArgInstruction(DUP);
97
98 new JLiteralInt(line, String.valueOf(i)).codegen(output);
100
101 initExpr.codegen(output);
103
104 if (componentType == Type.INT) {
106 output.addNoArgInstruction(IASTORE);
107 } else if (componentType == Type.BOOLEAN) {
108 output.addNoArgInstruction(BASTORE);
109 } else if (componentType == Type.CHAR) {
110 output.addNoArgInstruction(CASTORE);
111 } else if (!componentType.isPrimitive()) {
112 output.addNoArgInstruction(AASTORE);
113 }
114 }
115 }
116
117
120
121 public void writeToStdOut(PrettyPrinter p) {
122 p.println("<JArrayInitializer>");
123 if (initials != null) {
124 for (JAST initial : initials) {
125 p.indentRight();
126 initial.writeToStdOut(p);
127 p.indentLeft();
128 }
129 }
130 p.println("</JArrayInitializer>");
131 }
132 }
133