BooleanConstant.java

package org.sterling.runtime.expression;

import static org.sterling.runtime.expression.ExpressionConversions.convertSymbol;
import static org.sterling.runtime.expression.ExpressionFactory.constant;
import static org.sterling.util.StringUtil.stringify;

import org.sterling.SterlingException;

public class BooleanConstant extends Expression {

    public static BooleanConstant TRUE = new BooleanConstant(true);
    public static BooleanConstant FALSE = new BooleanConstant(false);

    private final boolean value;
    private final StringConstant stringValue;
    private final IntegerConstant integerValue;

    private BooleanConstant(boolean value) {
        this.value = value;
        this.stringValue = constant(value ? "True" : "False");
        this.integerValue = constant(value ? 1 : 0);
    }

    @Override
    public Expression access(Expression member) throws SterlingException {
        switch (convertSymbol(member).getValue()) {
            case "toBoolean": return this;
            case "toString": return stringValue;
            case "toInteger": return integerValue;
            default: return super.access(member);
        }
    }

    public boolean isFalse() {
        return !isTrue();
    }

    public boolean isTrue() {
        return value;
    }

    @Override
    public String toString() {
        return stringify(this, stringValue.getValue());
    }
}