ASTArrayLiteral.java
package edu.udel.cis.vsl.tass.front.minimp.ast.expression;
import edu.udel.cis.vsl.tass.front.minimp.ast.type.ASTArrayType;
import edu.udel.cis.vsl.tass.front.minimp.ast.type.ASTTypeIF;
import edu.udel.cis.vsl.tass.model.IF.SyntaxException;
public class ASTArrayLiteral extends ASTLiteralExpression {
private ASTExpressionIF[] literalArray;
public ASTArrayLiteral(ASTTypeIF type, ASTExpressionIF[] literalArray) {
super(type);
this.literalArray = literalArray;
}
// Create an array literal with null elements. for example, a int[2][2]
// array will have a literal
// like {{null, null}, {null, null}}
public ASTArrayLiteral(ASTTypeIF type, Integer[] dimensions) {
super(type);
this.literalArray = new ASTExpressionIF[dimensions[0]];
if (dimensions.length > 1) {
Integer[] newDimensions = new Integer[dimensions.length - 1];
for (int j = 1; j < dimensions.length; j++) {
newDimensions[j - 1] = dimensions[j];
}
for (int i = 0; i < dimensions[0]; i++) {
this.literalArray[i] = new ASTArrayLiteral(
((ASTArrayType) type).getBaseType(), newDimensions);
}
} else {
for (int i = 0; i < dimensions[0]; i++) {
this.literalArray[i] = null;
}
}
}
public int numLiteral() {
return this.literalArray.length;
}
public ASTExpressionIF getLiteral(int index) {
return this.literalArray[index];
}
public void setLiteral(Integer[] indices, ASTExpressionIF value)
throws SyntaxException {
if (indices.length > 1) {
Integer[] newIndices = new Integer[indices.length - 1];
for (int i = 1; i < indices.length; i++) {
newIndices[i - 1] = indices[i];
}
if (this.literalArray[indices[0]] instanceof ASTArrayLiteral) {
((ASTArrayLiteral) (this.literalArray[indices[0]])).setLiteral(
newIndices, value);
} else {
throw new SyntaxException(value,
"Array literal expected instead of "
+ this.literalArray[indices[0]].getClass()
.getName());
}
} else {
if (((ASTArrayType) (this.exprType)).getBaseType().equals(
value.getType())) {
this.literalArray[indices[0]] = value;
} else {
throw new SyntaxException(value,
"Type inconsistency in array literal: "
+ ((ASTArrayType) (this.exprType))
.getBaseType() + " and "
+ value.getType());
}
}
}
public void setLiteral(Integer index, ASTExpressionIF value)
throws SyntaxException {
if (!((ASTArrayType) exprType).getBaseType().equals(value.getType())) {
throw new SyntaxException(value, "Type inconsistency: " + exprType
+ " and " + value.getType());
} else {
this.literalArray[index] = value;
}
}
public String toString() {
String result = "(";
if (this.literalArray != null) {
for (int i = 0; i < this.literalArray.length; i++) {
if (this.literalArray[i] != null) {
result += this.literalArray[i].toString();
} else {
result += "null";
}
if (i < this.literalArray.length - 1) {
result += ", ";
}
}
}
result += ")";
return result;
}
}