All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.davidbracewell.parsing.Evaluator Maven / Gradle / Ivy

There is a newer version: 0.5
Show newest version
package com.davidbracewell.parsing;

import com.davidbracewell.Switch;
import com.davidbracewell.conversion.Cast;
import com.davidbracewell.function.CheckedFunction;
import com.davidbracewell.parsing.expressions.Expression;
import lombok.NonNull;

/**
 * 

An evaluator provides a switch-like interface for evaluating expressions. Custom evaluators can be created as * follows: * * Evaluator eval = new Evaluator() { * { * $(BinaryOperatorExpression.class, CommonTypes.PLUS, e -> eval(e.left) + eval(e.right)); * $(ValueExpression.class, e -> Double.valueOf(e.toString())); * } * } * * The various $ methods allow easily adding if-like predicates and then-like functions. The {@link * #eval(Expression)} method can be used to make recursive evaluation calls. *

* * @param the type parameter * @author David B. Bracewell */ public abstract class Evaluator extends Switch { private static final long serialVersionUID = 1L; /** * Instantiates a new Evaluator. */ protected Evaluator() { this.defaultStmt = exp -> { throw new ParseException("Unknown Expression [" + exp + " : " + exp.getTokenType() + "]"); }; } /** * Evaluates the given expression * * @param expression the expression to evaluate * @return the result of evaluation * @throws Exception Something went wrong during evaluation */ public O eval(Expression expression) throws Exception { if (expression == null) { return null; } return switchOn(expression); } /** * Adds a switch statement where the condition is that the expression is of type expressionClass and the * expressions's token type is an instance of type. When the condition is met the expression is cast as * the given expression class and the given function is applied. * * @param the type of expression * @param expressionClass the expression class * @param type the token type * @param function the function to apply when the condition is met. */ protected final void $(@NonNull Class expressionClass, @NonNull ParserTokenType type, @NonNull CheckedFunction function) { $( e -> e.match(expressionClass, type), e -> Cast.as(e, expressionClass), function ); } /** * Adds a switch statement where the condition is that the expression is of type expressionClass. When * the condition is met the expression is cast as the given expression class and the given function is applied. * * @param the type of expression * @param expressionClass the expression class * @param function the function to apply when the condition is met. */ protected final void $(@NonNull Class expressionClass, @NonNull CheckedFunction function) { $( e -> e.isInstance(expressionClass), e -> Cast.as(e, expressionClass), function ); } }// END OF Evaluator




© 2015 - 2025 Weber Informatics LLC | Privacy Policy