Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package studio.magemonkey.codex.util.eval;

import lombok.Getter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* A math expression that was parsed once and can be evaluated many times with different variable values.
* <p>
* Get one from {@link Evaluator#compile(String, String...)}:
* <pre>{@code
* CompiledExpression ce = Evaluator.compile("max(d / 5, d - 4 * x / max(1, t + 8))", "d", "x", "t");
* double v = ce.eval(def, dmg, toughness);
* }</pre>
* The syntax, operators, functions and constants are those of the bundled Javaluator
* {@link studio.magemonkey.codex.util.eval.javaluator.DoubleEvaluator}, and for any expression both accept the
* result is the same double, bit for bit. The differences:
* <ul>
* <li>{@code NaN} and infinities are returned as they are. {@code DoubleEvaluator} throws when a <i>function</i>
* returns NaN (for example {@code sqrt(-1)}); here that is the caller's check.</li>
* <li>{@code random()} gives a new random number on every call, as it does there.</li>
* </ul>
* An instance is immutable and may be shared and evaluated from any number of threads at once.
*/
@ToString(onlyExplicitlyIncluded = true)
public final class CompiledExpression {
private static final ExpressionCompiler COMPILER = new ExpressionCompiler();

/** The expression as it was given to {@link Evaluator#compile(String, String...)}. */
@Getter
@ToString.Include
private final String source;
/** The variable names, in the order {@link #eval(double...)} expects their values. Unmodifiable. */
@Getter
@ToString.Include
private final List<String> variableNames;
private final ExpressionNode root;

private CompiledExpression(String source, List<String> variableNames, ExpressionNode root) {
this.source = source;
this.variableNames = variableNames;
this.root = root;
}

/**
* @see Evaluator#compile(String, String...)
*/
static CompiledExpression compile(String expression, String... variables) {
if (expression == null) {
throw new IllegalArgumentException("Cannot compile a null expression");
}
if (variables == null) {
throw new IllegalArgumentException("Cannot compile '" + expression + "': variable names are null");
}
List<String> names = new ArrayList<>(variables.length);
Set<String> seen = new HashSet<>();
for (String name : variables) {
String problem = COMPILER.checkVariableName(name);
if (problem == null && !seen.add(name)) {
problem = "variable name '" + name + "' is given twice";
}
if (problem != null) {
throw new IllegalArgumentException("Cannot compile '" + expression + "': " + problem);
}
names.add(name);
}
return new CompiledExpression(expression,
Collections.unmodifiableList(names),
COMPILER.compile(expression, names));
}

/**
* Evaluates the expression. Does not parse, does not allocate, and does not modify {@code values}.
*
* @param values one value for each variable name, in the order the names were given to {@code compile}
* @return the result. May be NaN or infinite; checking is up to the caller.
* @throws IllegalArgumentException if the number of values differs from the number of variable names
*/
public double eval(double... values) {
if (values.length != variableNames.size()) {
throw new IllegalArgumentException("Expression '" + source + "' takes " + variableNames.size()
+ " value(s) " + variableNames + " but got " + values.length);
}
return root.eval(values);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,27 @@ public static double eval(String exp, int method) {
}
}

/**
* Parses a math expression once, so it can be evaluated many times with different values for its variables.
* Use this instead of {@link #eval(String, int)} when the same formula runs repeatedly.
* <p>
* The syntax is that of the Javaluator evaluator ({@code + - * / ^ %}, unary minus, brackets, {@code min},
* {@code max}, {@code abs}, {@code sqrt}, the constants {@code pi} and {@code e} and so on).
*
* @param expression the expression, such as {@code max(d / 5, d - 4 * x / max(1, t + 8))}
* @param variables the names of the variables the expression may use. Their values are later given to
* {@link CompiledExpression#eval(double...)} in this order. A name cannot be a function, a
* constant or a number, cannot contain an operator, bracket, comma or whitespace, and cannot
* be repeated.
* @return the compiled expression, which is immutable and thread safe
* @throws IllegalArgumentException with a message naming the expression, if it has a syntax error, mismatched
* brackets, an unknown variable or function, a function with the wrong number
* of arguments, or if a variable name is not usable
*/
public static CompiledExpression compile(String expression, String... variables) {
return CompiledExpression.compile(expression, variables);
}

private static double javaluator(String exp) {
try {
return jl.evaluate(exp);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package studio.magemonkey.codex.util.eval;

import studio.magemonkey.codex.util.eval.javaluator.*;

import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.*;
import java.util.function.DoubleUnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Turns an expression into an {@link ExpressionNode} tree using the grammar of {@link DoubleEvaluator}.
* <p>
* This is an {@link AbstractEvaluator} whose values are tree nodes instead of numbers, so the tokenizer, the
* operator precedence and associativity, the unary minus handling, the bracket and argument-count checks are all
* the ones {@link DoubleEvaluator} runs. Only the meaning given to each operator and function lives here.
*/
final class ExpressionCompiler extends AbstractEvaluator<ExpressionNode> {
private static final Pattern POSITION = Pattern.compile("At position (\\d+)");

private static final ThreadLocal<NumberFormat> FORMATTER =
ThreadLocal.withInitial(() -> NumberFormat.getNumberInstance(Locale.US));

private static final Map<Function, DoubleUnaryOperator> UNARY = new IdentityHashMap<>();

static {
UNARY.put(DoubleEvaluator.ABS, Math::abs);
UNARY.put(DoubleEvaluator.CEIL, Math::ceil);
UNARY.put(DoubleEvaluator.FLOOR, Math::floor);
UNARY.put(DoubleEvaluator.ROUND, d -> d == Double.NEGATIVE_INFINITY || d == Double.POSITIVE_INFINITY
? d
: (double) Math.round(d));
UNARY.put(DoubleEvaluator.SINEH, Math::sinh);
UNARY.put(DoubleEvaluator.COSINEH, Math::cosh);
UNARY.put(DoubleEvaluator.TANGENTH, Math::tanh);
UNARY.put(DoubleEvaluator.SINE, Math::sin);
UNARY.put(DoubleEvaluator.COSINE, Math::cos);
UNARY.put(DoubleEvaluator.TANGENT, Math::tan);
UNARY.put(DoubleEvaluator.ACOSINE, Math::acos);
UNARY.put(DoubleEvaluator.ASINE, Math::asin);
UNARY.put(DoubleEvaluator.ATAN, Math::atan);
UNARY.put(DoubleEvaluator.LN, Math::log);
UNARY.put(DoubleEvaluator.LOG, Math::log10);
UNARY.put(DoubleEvaluator.SQRT, Math::sqrt);
}

/** The variables of one compilation, as the evaluation context the shared parser asks for values. */
private static final class Variables implements AbstractVariableSet<ExpressionNode> {
private final Map<String, ExpressionNode> byName = new HashMap<>();

@Override
public ExpressionNode get(String variableName) {
return byName.get(variableName);
}
}

ExpressionCompiler() {
super(DoubleEvaluator.getDefaultParameters());
}

/**
* @param expression the expression to compile
* @param names the variable names, already checked for duplicates
* @return the tree
* @throws IllegalArgumentException if the expression is not valid
*/
ExpressionNode compile(String expression, List<String> names) {
Variables variables = new Variables();
for (int i = 0; i < names.size(); i++) {
variables.byName.put(names.get(i), new ExpressionNode.Variable(i));
}
try {
return evaluate(expression, variables);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(describe(expression, e.getMessage()), e);
} catch (RuntimeException e) {
// The shared parser reports some malformed input (a lone ",", a missing operand) as an NPE or similar.
throw new IllegalArgumentException(describe(expression, "malformed expression"), e);
}
}

/**
* Checks that a variable name would be read back as a single variable: not blank, no whitespace, no operator or
* bracket in it, not a function, a constant or a number.
*
* @return why the name is not usable, or null if it is
*/
String checkVariableName(String name) {
if (name == null) {
return "variable name is null";
}
if (name.isEmpty() || name.chars().anyMatch(Character::isWhitespace)) {
return "variable name '" + name + "' is empty or contains whitespace";
}
if (functions.containsKey(name)) {
return "variable name '" + name + "' is already a function";
}
if (constants.containsKey(name)) {
return "variable name '" + name + "' is already a constant";
}
Collection<Token> tokens = tokenizer.tokenize(name);
if (tokens.size() != 1 || !tokens.iterator().next().isLiteral()) {
return "variable name '" + name + "' contains an operator, bracket, separator or whitespace";
}
if (parseNumber(name) != null) {
return "variable name '" + name + "' is a number";
}
return null;
}

private static String describe(String expression, String cause) {
String message = cause == null || cause.isEmpty() ? "malformed expression" : cause;
// The shared parser adds a three-line "At position N of line L" excerpt; keep the position, on one line.
int newline = message.indexOf('\n');
String first = newline < 0 ? message : message.substring(0, newline);
Matcher m = POSITION.matcher(message);
String where = m.find() ? " (at position " + m.group(1) + ")" : "";
return "Cannot compile '" + expression + "': " + first + where;
}

private static Double parseNumber(String literal) {
ParsePosition p = new ParsePosition(0);
Number result = FORMATTER.get().parse(literal, p);
if (p.getIndex() == 0 || p.getIndex() != literal.length()) {
return null;
}
return result.doubleValue();
}

@Override
protected ExpressionNode toValue(Token literalTok, EvaluationContext context) {
String literal = literalTok.getString();
// Same parse as DoubleEvaluator.toValue, so a number compiles to the exact double the string evaluator gets.
Double number = parseNumber(literal);
if (number != null) {
return new ExpressionNode.Constant(number);
}
char first = literal.charAt(0);
if ((first >= '0' && first <= '9') || first == '.') {
throw context.getError("invalid number '" + literal + "'", literalTok);
}
throw context.getError("unknown variable or function '" + literal + "'", literalTok);
}

@Override
protected ExpressionNode evaluate(Constant constant, EvaluationContext context) {
if (DoubleEvaluator.PI == constant) {
return new ExpressionNode.Constant(Math.PI);
} else if (DoubleEvaluator.E == constant) {
return new ExpressionNode.Constant(Math.E);
}
throw new IllegalArgumentException("unsupported constant '" + constant.getName() + "'");
}

@Override
protected ExpressionNode evaluate(Operator operator, Iterator<ExpressionNode> operands, EvaluationContext context) {
if (DoubleEvaluator.NEGATE == operator || DoubleEvaluator.NEGATE_HIGH == operator) {
return new ExpressionNode.Unary(d -> -d, operands.next());
}
ExpressionNode left = operands.next();
ExpressionNode right = operands.next();
if (DoubleEvaluator.MINUS == operator) {
return new ExpressionNode.Binary((a, b) -> a - b, left, right);
} else if (DoubleEvaluator.PLUS == operator) {
return new ExpressionNode.Binary((a, b) -> a + b, left, right);
} else if (DoubleEvaluator.MULTIPLY == operator) {
return new ExpressionNode.Binary((a, b) -> a * b, left, right);
} else if (DoubleEvaluator.DIVIDE == operator) {
return new ExpressionNode.Binary((a, b) -> a / b, left, right);
} else if (DoubleEvaluator.EXPONENT == operator) {
return new ExpressionNode.Binary(Math::pow, left, right);
} else if (DoubleEvaluator.MODULO == operator) {
return new ExpressionNode.Binary((a, b) -> a % b, left, right);
}
throw new IllegalArgumentException("unsupported operator '" + operator.getSymbol() + "'");
}

@Override
protected void doFunction(Deque<ExpressionNode> values, Token functionTok, int argCount, EvaluationContext context) {
Function f = functionTok.getFunction();
if (argCount < f.getMinimumArgumentCount() || argCount > f.getMaximumArgumentCount()) {
String expected = f.getMaximumArgumentCount() == Integer.MAX_VALUE
? "at least " + f.getMinimumArgumentCount()
: f.getMinimumArgumentCount() == f.getMaximumArgumentCount()
? String.valueOf(f.getMinimumArgumentCount())
: f.getMinimumArgumentCount() + " to " + f.getMaximumArgumentCount();
throw context.getError(
"wrong number of arguments for " + f.getName() + ": expected " + expected + " but got " + argCount,
functionTok);
}
super.doFunction(values, functionTok, argCount, context);
}

@Override
protected ExpressionNode evaluate(Function function, Iterator<ExpressionNode> arguments, EvaluationContext context) {
DoubleUnaryOperator unary = UNARY.get(function);
if (unary != null) {
return new ExpressionNode.Unary(unary, arguments.next());
}
if (DoubleEvaluator.RANDOM == function) {
return new ExpressionNode.Random();
}
List<ExpressionNode> list = new ArrayList<>();
while (arguments.hasNext()) {
list.add(arguments.next());
}
ExpressionNode[] args = list.toArray(new ExpressionNode[0]);
if (DoubleEvaluator.MIN == function) {
return new ExpressionNode.Fold(Math::min, false, false, args);
} else if (DoubleEvaluator.MAX == function) {
return new ExpressionNode.Fold(Math::max, false, false, args);
} else if (DoubleEvaluator.SUM == function) {
return new ExpressionNode.Fold((a, b) -> a + b, true, false, args);
} else if (DoubleEvaluator.AVERAGE == function) {
return new ExpressionNode.Fold((a, b) -> a + b, true, true, args);
}
throw new IllegalArgumentException("unsupported function '" + function.getName() + "'");
}
}
Loading
Loading