1
3 package jminusminus;
4
5 import static jminusminus.CLConstants.*;
6
7
11
12 class JArrayExpression extends JExpression implements JLhs {
13
14
15 private JExpression theArray;
16
17
18 private JExpression indexExpr;
19
20
30
31 public JArrayExpression(int line, JExpression theArray,
32 JExpression indexExpr) {
33 super(line);
34 this.theArray = theArray;
35 this.indexExpr = indexExpr;
36 }
37
38
45
46 public JExpression analyze(Context context) {
47 theArray = (JExpression) theArray.analyze(context);
48 indexExpr = (JExpression) indexExpr.analyze(context);
49 if (!(theArray.type().isArray())) {
50 JAST.compilationUnit.reportSemanticError(line(),
51 "attempt to index a non-array object");
52 this.type = Type.ANY;
53 } else {
54 this.type = theArray.type().componentType();
55 }
56 indexExpr.type().mustMatchExpected(line(), Type.INT);
57 return this;
58 }
59
60
67
68 public JExpression analyzeLhs(Context context) {
69 analyze(context);
70 return this;
71 }
72
73
81
82 public void codegen(CLEmitter output) {
83 theArray.codegen(output);
84 indexExpr.codegen(output);
85 if (type == Type.INT || type == Type.BOOLEAN || type == Type.CHAR) {
86 output.addNoArgInstruction(IALOAD);
87 } else if (!type.isPrimitive()) {
88 output.addNoArgInstruction(AALOAD);
89 }
90 }
91
92
100
101 public void codegenLoadLhsLvalue(CLEmitter output) {
102 theArray.codegen(output);
105 indexExpr.codegen(output);
106 }
107
108
117
118 public void codegenLoadLhsRvalue(CLEmitter output) {
119 if (type == Type.STRING) {
122 output.addNoArgInstruction(DUP2_X1);
123 } else {
124 output.addNoArgInstruction(DUP2);
125 }
126 if (type == Type.INT || type == Type.BOOLEAN || type == Type.CHAR) {
127 output.addNoArgInstruction(IALOAD);
128 } else if (!type.isPrimitive()) {
129 output.addNoArgInstruction(AALOAD);
130 }
131 }
132
133
143
144 public void codegenDuplicateRvalue(CLEmitter output) {
145 output.addNoArgInstruction(DUP_X2);
147 }
148
149
157
158 public void codegenStore(CLEmitter output) {
159 if (type == Type.INT || type == Type.BOOLEAN || type == Type.CHAR) {
160 output.addNoArgInstruction(IASTORE);
161 } else if (!type.isPrimitive()) {
162 output.addNoArgInstruction(AASTORE);
163 }
164 }
165
166
169
170 public void writeToStdOut(PrettyPrinter p) {
171 p.println("<JArrayExpression>");
172 p.indentRight();
173 if (theArray != null) {
174 p.println("<TheArray>");
175 p.indentRight();
176 theArray.writeToStdOut(p);
177 p.indentLeft();
178 p.println("</TheArray>");
179 }
180 if (indexExpr != null) {
181 p.println("<IndexExpression>");
182 p.indentRight();
183 indexExpr.writeToStdOut(p);
184 p.indentLeft();
185 p.println("</IndexExpression>");
186 }
187 p.indentLeft();
188 p.println("</JArrayExpression>");
189 }
190
191 }
192