Conditional.java

package org.sterling.runtime.expression;

import static org.sterling.runtime.expression.ExpressionConversions.convertBoolean;

import org.sterling.SterlingException;

public class Conditional extends Expression {

    public static final Conditional INSTANCE = new Conditional();

    private Conditional() {
        // intentionally empty
    }

    @Override
    public Expression apply(Expression argument) throws SterlingException {
        if (convertBoolean(argument.evaluate()).isTrue()) {
            return new TruePick();
        } else {
            return new SkipPick(new FalsePick());
        }
    }

    private static final class TruePick extends Expression {

        @Override
        public Expression apply(Expression argument) throws SterlingException {
            return new SkipPick(argument);
        }
    }

    private static final class FalsePick extends Expression {

        @Override
        public Expression apply(Expression argument) throws SterlingException {
            return argument.reduce();
        }
    }

    private static final class SkipPick extends Expression {

        private final Expression expression;

        public SkipPick(Expression expression) {
            this.expression = expression;
        }

        @Override
        public Expression apply(Expression argument) throws SterlingException {
            return expression;
        }
    }
}