IfThenElseExpression.java

package edu.udel.cis.vsl.tass.model.impl.expression;

import edu.udel.cis.vsl.tass.model.IF.ModelFactoryIF;
import edu.udel.cis.vsl.tass.model.IF.SyntaxException;
import edu.udel.cis.vsl.tass.model.IF.expression.ExpressionIF;
import edu.udel.cis.vsl.tass.model.IF.expression.IfThenElseExpressionIF;
import edu.udel.cis.vsl.tass.model.IF.type.TypeIF;
import edu.udel.cis.vsl.tass.model.IF.type.TypeIF.TypeKind;

public class IfThenElseExpression extends Expression implements
		IfThenElseExpressionIF {

	private ExpressionIF condition;

	private ExpressionIF falseValue;

	private ExpressionIF trueValue;

	public IfThenElseExpression(ModelFactoryIF factory, ExpressionIF condition,
			ExpressionIF trueValue, ExpressionIF falseValue)
			throws SyntaxException {
		super(factory, ExpressionKind.IF_THEN_ELSE);

		if (condition == null)
			throw new NullPointerException("null condition");
		this.condition = condition;
		if (trueValue == null)
			throw new NullPointerException("null true value");
		this.trueValue = trueValue;
		if (falseValue == null)
			throw new NullPointerException("null false value");
		this.falseValue = falseValue;

		TypeIF falseType = falseValue.type();
		TypeIF trueType = trueValue.type();

		if (trueType.equals(falseType)) {
			type = trueType;
		} else if (trueType.kind() == TypeKind.INTEGER
				&& falseType.kind() == TypeKind.RATIONAL
				|| trueType.kind() == TypeKind.RATIONAL
				&& falseType.kind() == TypeKind.INTEGER) {
			type = factory.rationalType();
		} else {
			throw new SyntaxException(falseValue,
					"False value of if-then-else expression has incompatible type: "
							+ falseType);
		}
		freeVariables.addAll(condition.freeVariables());
		freeVariables.addAll(trueValue.freeVariables());
		freeVariables.addAll(falseValue.freeVariables());
	}

	public ExpressionIF condition() {
		return condition;
	}

	public ExpressionIF falseValue() {
		return falseValue;
	}

	public ExpressionIF trueValue() {
		return trueValue;
	}

	public String atomString() {
		return toString();
	}

	public String toString() {
		return "(" + condition + " ? " + trueValue + " : " + falseValue + ")";
	}

}