ExpressionConversions.java

package org.sterling.runtime.expression;

import static org.sterling.runtime.expression.ExpressionFactory.access;
import static org.sterling.runtime.expression.ExpressionFactory.symbol;

import org.sterling.SterlingException;

public final class ExpressionConversions {

    public static BooleanConstant convertBoolean(Expression expression) throws SterlingException {
        return (BooleanConstant) access(expression.evaluate(), symbol("toBoolean")).evaluate();
    }

    public static DoubleConstant convertDouble(Expression expression) throws SterlingException {
        return (DoubleConstant) access(expression.evaluate(), symbol("toDouble")).evaluate();
    }

    public static IntegerConstant convertInteger(Expression expression) throws SterlingException {
        return (IntegerConstant) access(expression.evaluate(), symbol("toInteger")).evaluate();
    }

    public static StringConstant convertString(Expression expression) throws SterlingException {
        return (StringConstant) access(expression.evaluate(), symbol("toString")).evaluate();
    }

    public static Symbol convertSymbol(Expression expression) throws SterlingException {
        if (expression instanceof Symbol) {
            return (Symbol) expression;
        } else {
            return (Symbol) access(expression.evaluate(), symbol("toSymbol")).evaluate();
        }
    }

    public static boolean isNothing(Expression expression) throws SterlingException {
        return convertBoolean(access(expression.evaluate(), symbol("isNothing")).evaluate()).isTrue();
    }

    private ExpressionConversions() {
        // intentionally empty
    }
}