package calculator.interpreter.ast.logic; import net.sf.etl.parsers.TermToken; import net.sf.etl.parsers.beans.TokenCollector; import calculator.interpreter.Cell; import calculator.interpreter.Environment; import calculator.interpreter.EvalException; import calculator.interpreter.ast.Expression; import calculator.interpreter.ast.Statement; /** * The assert statement */ public class AssertStatement extends Statement implements TokenCollector { /** The condition to assert */ public Expression condition; /** The message to use in case of assertion failure */ public Expression message; /** The text of the assert statement */ private StringBuilder textBuilder = new StringBuilder(); /** The text of the condition */ private String conditionText; @Override public Environment eval(Environment env, Cell result) { Object c = condition.eval(env); if (!(c instanceof Boolean)) { throw new EvalException(this, "The condition " + conditionText() + " at " + condition.location.toShortString() + " did not evaluated to the boolean: " + c); } if (!(Boolean) c) { throw new EvalException(this, "The assertion " + conditionText() + " failed" + (message == null ? "." : ": " + message.eval(env))); } return env; } /** * @return the text of condition */ private String conditionText() { if (conditionText == null) { int start = (int) (condition.location.start().offset() - location.start() .offset()); int end = (int) (condition.location.end().offset() - location.start() .offset()); conditionText = textBuilder.substring(start, end); textBuilder = null; } return conditionText; } /** {@inheritDoc} */ public void collect(TermToken token) { if (token.hasLexicalToken()) { textBuilder.append(token.token().token().text()); } } }