ASTStructMemberRefExpression.java

package edu.udel.cis.vsl.tass.front.minimp.ast.expression;

import edu.udel.cis.vsl.tass.front.minimp.ast.type.ASTPointerType;
import edu.udel.cis.vsl.tass.front.minimp.ast.type.ASTStructType;
import edu.udel.cis.vsl.tass.front.minimp.ast.type.ASTTypeIF;
import edu.udel.cis.vsl.tass.model.IF.SyntaxException;

public class ASTStructMemberRefExpression extends ASTExpression implements
		ASTExpressionIF {
	private ASTExpressionIF baseExpr;
	private String fieldName;
	private boolean isPointerRef = false;

	public ASTStructMemberRefExpression(ASTExpressionIF baseExpr,
			String fieldName) throws SyntaxException {
		super(null);
		if (baseExpr.getType() instanceof ASTPointerType) {
			ASTTypeIF baseType = ((ASTPointerType) (baseExpr.getType()))
					.getBaseType();
			if (!(baseType instanceof ASTStructType)) {
				throw new SyntaxException(
						baseExpr.getSource(),
						"Type error in struct member reference expression. Expected struct type but got "
								+ baseType);
			}
			if (!((ASTStructType) baseType).hasField(fieldName)) {
				throw new SyntaxException(baseExpr.getSource(),
						"The struct type " + baseType
								+ " doesn't have a field named " + fieldName);
			}
			this.exprType = ((ASTStructType) baseType).getFieldType(fieldName);
			this.isPointerRef = true;
			this.baseExpr = new ASTDereferenceExpression(baseExpr);
		} else {
			if (!(baseExpr.getType() instanceof ASTStructType)) {
				throw new SyntaxException(
						baseExpr.getSource(),
						"Type error in struct member reference expression. Expected struct type but got "
								+ baseExpr.getType());
			}
			if (!((ASTStructType) (baseExpr.getType())).hasField(fieldName)) {
				throw new SyntaxException(baseExpr.getSource(),
						"The struct type " + baseExpr.getType()
								+ " doesn't have a field named " + fieldName);
			}
			this.exprType = ((ASTStructType) (baseExpr.getType()))
					.getFieldType(fieldName);
			this.baseExpr = baseExpr;
		}
		this.fieldName = fieldName;
	}

	public ASTExpressionIF getBaseExpr() {
		return this.baseExpr;
	}

	public String getFieldName() {
		return this.fieldName;
	}

	public String toString() {
		if (this.isPointerRef) {
			return this.baseExpr.toString() + "->" + this.fieldName;
		} else {
			return this.baseExpr.toString() + "." + this.fieldName;
		}
	}

	public boolean isPointerRef() {
		return this.isPointerRef;
	}
}