Skip to content

About

Fast & thread-safe Java expression library

Resources

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

Sparrow Expression

English | 简体中文

Sparrow Expression is a small, dependency-free engine built specifically for numerical evaluation in games. An expression is parsed, optimized, and bound before it enters the hot path. Evaluation receives only a typed context object: it performs no parameter-name lookup and creates no parameter map. Compiled expressions are immutable and thread-safe; they can be shared across threads when bound accessors, custom functions, and context data are also safe for concurrent access.

Highlights

Capability Description
Precompiled expressions Parse once, evaluate repeatedly with different contexts
Compile-time parameter binding Each distinct identifier is converted directly into a typed accessor
Compile-time constant binding Host constants become foldable constant nodes and disappear from the hot path
Primitive numeric evaluation Numeric values and all expression results use primitive double; strings are isolated to dedicated string nodes
Constant folding Constant subtrees are evaluated during compilation
Specialized hot paths Common parameter-to-constant and parameter-to-parameter operations avoid generic tree dispatch
Lazy control flow IF, SWITCH, AND, and OR evaluate only the required result or branch
Reusable compiled programs CompiledExpression<C> is immutable and can be shared when its collaborators are thread-safe
Extensible functions Custom functions are resolved during compilation and receive allocation-free compiled arguments

Gradle Kotlin DSL

repositories {
    maven("https://repo.momirealms.net/releases")
}

dependencies {
    implementation("net.momirealms:sparrow-expr:{version}")
}

Benchmarks

JMH 1.37 results on an Intel Core i7-13700K, Windows 11, and JDK 21.0.11. Each result uses two forks, five 500 ms warmup iterations, and eight 500 ms measurement iterations. Tables report the mean score; lower is better.

Evaluation measures only calls to an already parsed and compiled expression. Parameter declaration, accessor binding, and initial third-party variable values are prepared outside the measured evaluation path. Each benchmark thread owns its third-party expression instances. GC profiling is enabled; ≈0 denotes no measurable per-evaluation heap allocation.

Expression Sparrow, ns/op / B/op Crunch 2.0.3, ns/op / B/op exp4j 0.4.8, ns/op / B/op EvalEx 3.7.0, ns/op / B/op
x > 100 1.010 / ≈0 1.725 / ≈0 11.499 / 56 49.127 / 112
(x - y) * 2 1.934 / ≈0 2.710 / ≈0 18.443 / 56 87.239 / 264
SIN(x) 6.079 / ≈0 7.500 / ≈0 17.141 / 80 242.799 / 800
IF(x > y, (x - y) * 2, 0) 3.036 / ≈0 12.656 / ≈0 40.679 / 192 219.239 / 464
Complex expression below 408.547 / ≈0 495.444 / ≈0 930.543 / 2,976 24,834.705 / 74,538

Compilation creates a fresh compiled expression on every operation. The EvalEx case calls validate() so its lazy parser must build the AST during the measured operation. Compiler configuration and custom operator/function registration are prepared outside the measured path.

Expression Sparrow, μs/op Crunch 2.0.3, μs/op exp4j 0.4.8, μs/op EvalEx 3.7.0, μs/op
x > 100 0.136 0.047 0.239 11.032
(x - y) * 2 0.258 0.148 0.290 11.220
SIN(x) 0.154 0.042 0.253 11.133
IF(x > y, (x - y) * 2, 0) 0.662 0.288 0.485 12.155
Complex expression below 6.773 4.066 5.232 24.390

The complex case uses x = 101, y = 100, z = 3.5, and w = 2.25:

((x-y)^2 + SQRT(ABS(z)) + SIN(x)*COS(y) + LOG(ABS(z)+1))
* ((x+z)/(ABS(y)+1) + SQRT(x^2+y^2+z^2))
+ ((x*0.75+y*1.25-z*0.5)^2)/(ABS(x-y)+1)
+ ((z-w)^2 + SQRT(ABS(x*w)+1) + SIN(z)*COS(w) + LOG(ABS(x+y)+1))
* ((z+x)/(ABS(w)+1) + SQRT(w^2+z^2+x^2))
+ ((w*1.5-z*0.25+x*0.125)^3)/(ABS(z-w)+1)
+ ((x+y+z+w)^2 + (x*y-z*w)^2)/(SQRT(ABS(x*y*z*w)+1)+1)

Quick start

Define the runtime context, bind expression identifiers to context accessors, and compile the expression once:

import net.momirealms.sparrow.expr.CompiledExpression;
import net.momirealms.sparrow.expr.ExpressionCompiler;
import net.momirealms.sparrow.expr.binding.ParameterBinding;

record CombatContext(double health, double limit, double damage) {}

ExpressionCompiler<CombatContext> compiler = new ExpressionCompiler<>(
        name -> switch (name) {
            case "health" -> ParameterBinding.number(CombatContext::health);
            case "limit" -> ParameterBinding.number(CombatContext::limit);
            case "damage" -> ParameterBinding.number(CombatContext::damage);
            default -> throw new IllegalArgumentException("Unknown parameter: " + name);
        }
);

CompiledExpression<CombatContext> expression =
        compiler.compile("IF(health <= limit, damage * 1.5, damage)");

double value = expression.evaluate(new CombatContext(80, 100, 12)); // 18.0
boolean matched = expression.test(new CombatContext(80, 100, 12));  // true

ExpressionCompiler<C> and CompiledExpression<C> keep the context type. Passing a wrong context type is therefore rejected by the Java compiler rather than discovered in the evaluation loop.

String values

Use typed parameter bindings when an expression needs both numbers and strings:

import net.momirealms.sparrow.expr.binding.ParameterBinding;

record DamageContext(double damage, String type) {}

ExpressionCompiler<DamageContext> compiler = new ExpressionCompiler<>(
        name -> switch (name) {
            case "damage" -> ParameterBinding.number(DamageContext::damage);
            case "type" -> ParameterBinding.string(DamageContext::type);
            default -> throw new IllegalArgumentException("Unknown parameter: " + name);
        }
);

CompiledExpression<DamageContext> expression = compiler.compile(
        "SWITCH(type, \"fire\", damage * 1.5, \"ice\", damage * 0.75, damage)"
);

double value = expression.evaluate(new DamageContext(20, "fire")); // 30.0
Form Example Notes
Equality type == "fire" Both operands must be strings; comparison is case-sensitive
Inequality type != "ice" Returns numeric 1.0 or 0.0
Conditional IF(type == "fire", damage * 2, damage) Result branches remain numeric and lazy
Selection SWITCH(type, "fire", 20, "ice", 10, 0) Selector and matches use one type; results remain numeric and lazy

String literals use double quotes and support \", \\, \n, \r, \t, \b, \f, and \uFFFF escapes. Strings may be used by equality, SWITCH, and the built-in string functions. They are not accepted by arithmetic, ordering comparisons, numeric functions, result branches, or the final expression result. String parameters may resolve to null; two null string parameters compare equal, while a literal never matches null. String transformations, slices, and concatenation preserve or propagate null, STR_LENGTH(null) returns 0, and string predicates return false when either argument is null.

TO_STRING uses Java's canonical double representation. FORMAT_NUMBER always emits the requested number of decimal places using half-even rounding; its scale must be a compile-time constant from 0 through 308. PARSE_NUMBER accepts Java double text, including decimal and scientific notation. Its optional fallback is evaluated only when the input is null or invalid.

String indices and counts are zero-based, non-negative integers measured in Java UTF-16 code units. They must stay within the string bounds; an invalid value throws ArithmeticException.

For an object-backed parameter source whose type is not known in advance, provide both conversions with ParameterBinding.auto:

case "value" -> ParameterBinding.auto(
        context -> toDouble(resolveValue(context)),
        context -> toStringValue(resolveValue(context))
);
AUTO usage Inferred type
value + 1, value > 0, IF(value, 1, 0) Number
value == 1, SWITCH(value, 1, 10, 2, 20, 0) Number
value == "fire", IF(value == "fire", 1, 0) String
SWITCH(value, "fire", 10, "ice", 20, 0) String

AUTO exists only while the expression is compiled. The final tree contains the same specialized numeric or string parameter node as an explicitly typed binding. Two unresolved AUTO equality operands are rejected because neither side supplies a type. A SWITCH whose selector and every match are unresolved AUTO parameters is rejected for the same reason. The same AUTO parameter may be used in numeric and string positions; each occurrence is specialized independently. Both accessors may therefore be called during one evaluation, so conversions should be stable and free of side effects for a given context.

Values, identifiers, and constants

Syntax Example Notes
Decimal 12, 3.5, .25 Stored as double
Scientific notation 1.5e2, 2E-3 Optional signed exponent
Numeric separators 1_000_000 Underscores must separate digits
Hexadecimal 0xFF, 0xFF_FF Converted to double
String "fire", "ice" Case-sensitive value for equality, selection, and string functions
Parameter x, health, type Case-sensitive ordinary Java-style identifier; binding declares or infers number/string type
Constants TRUE, FALSE, PI, E Case-insensitive; TRUE is 1.0, FALSE is 0.0
Grouping (x + 2) * 3 Parentheses may be nested

Function names and built-in constants are case-insensitive. Parameters and host-defined constants are case-sensitive. Template markers are deliberately outside the grammar; preprocess them into ordinary identifiers before compilation.

Operators and precedence

The default precedence is listed from highest to lowest:

Precedence Operators Associativity Example
1 Parentheses and function calls — (x + 1), MAX(x, 0)
2 ^ Right 2 ^ 3 ^ 2 = 512
3 Unary +, -, !, NOT Right -2 ^ 2 is parsed as -(2 ^ 2) and evaluates to -4
4 *, /, % Left 10 % 4 = 2
5 +, - Left 2 + 3 * 4 = 14
6 >, >=, <, <= Left health <= limit
7 =, ==, !=, <> Left type == "fire"
8 &, &&, AND Left, short-circuiting x > 0 AND y > 0
9 ` ,

Comparison and logical operators return 1.0 or 0.0. Equality operators accept two numbers or two strings; ordering operators remain numeric. Zero is false; every non-zero value is true.

compiler.compile("3 > 2").evaluate(null);          // 1.0
compiler.compile("3 > 2 AND 2 > 1").test(null);   // true
compiler.compile("FALSE AND RANDOM() > 0");       // right side is skipped

Built-in functions

All trigonometric input and output angles use radians. DEG and RAD are explicit conversion helpers.

Function Arity Meaning Example
IF(condition, yes, no) 3 Evaluates exactly one result branch IF(x > 0, x, -x)
SWITCH(value, match, result, ..., default) 4+ even Matches numbers or strings and returns the first matching numeric result, otherwise the default SWITCH(type, "fire", 20, "ice", 10, 0)
STR_LENGTH(value) 1 String length; null is 0 STR_LENGTH(type) > 5
STR_CONTAINS(value, search) 2 Case-insensitive substring test STR_CONTAINS(type, "fire")
STR_STARTS_WITH(value, prefix) 2 Case-sensitive prefix test STR_STARTS_WITH(id, "minecraft:")
STR_ENDS_WITH(value, suffix) 2 Case-sensitive suffix test STR_ENDS_WITH(file, ".json")
STR_LOWER(value) 1 Lowercase using the root locale STR_LOWER(type) == "fire"
STR_UPPER(value) 1 Uppercase using the root locale STR_UPPER(type) == "FIRE"
STR_TRIM(value) 1 Remove leading and trailing characters at or below U+0020 STR_TRIM(type) == "fire"
STR_CONCAT(value, ...) 1+ Concatenate strings; null propagates STR_CONCAT(namespace, ":", path) == id
TO_STRING(value) 1 Convert a number to its canonical double string TO_STRING(2.5) == "2.5"
FORMAT_NUMBER(value, scale) 2 Format with a compile-time fixed number of decimal places FORMAT_NUMBER(2.5, 2) == "2.50"
PARSE_NUMBER(value) 1 Parse a string as a double; invalid input throws PARSE_NUMBER("2.5") = 2.5
PARSE_NUMBER(value, fallback) 2 Parse a string, lazily using the numeric fallback when invalid PARSE_NUMBER(text, 0)
IS_NUMBER(value) 1 Return 1 when a string can be parsed as a double IS_NUMBER("2.5") = 1
STR_LEFT(value, count) 2 First count characters STR_LEFT(id, 9) == "minecraft"
STR_RIGHT(value, count) 2 Last count characters STR_RIGHT(id, 5) == "stone"
STR_SUBSTRING(value, start) 2 Characters from start to the end STR_SUBSTRING(id, 10) == "stone"
STR_SUBSTRING(value, start, end) 3 Characters from start inclusive to end exclusive STR_SUBSTRING(id, 0, 9) == "minecraft"
RANDOM() 0 Uniform value in [0, 1) RANDOM() * 10
RANDOM(min, max) 2 Uniform value in [min, max) RANDOM(5, 15)
RANDOM_INT(min, max) 2 Uniform integer in [min, max), returned as double RANDOM_INT(1, 7)
CHANCE(probability) 1 Returns 1 with the given probability, otherwise 0 IF(CHANCE(0.25), 2, 1)
RANDOM_TRIANGLE(min, max) 2 Bounded triangular distribution with a midpoint mode RANDOM_TRIANGLE(5, 15)
RANDOM_TRIANGLE(min, max, mode) 3 Bounded triangular distribution with an explicit mode RANDOM_TRIANGLE(5, 15, 8)
RANDOM_GAUSSIAN(mean, stdDev), RANDOM_NORMAL(mean, stdDev) 2 Unbounded Gaussian distribution RANDOM_GAUSSIAN(10, 2)
RANDOM_GAUSSIAN(min, max, mean, stdDev), RANDOM_NORMAL(...) 4 Bounded Gaussian distribution with up to 64 attempts RANDOM_GAUSSIAN(0, 20, 10, 2)
RANDOM_GAUSSIAN(min, max, mean, stdDev, attempts), RANDOM_NORMAL(...) 5 Bounded Gaussian distribution with a custom attempt limit RANDOM_GAUSSIAN(0, 20, 10, 2, 16)
SUM(a, ...) 1+ Sum SUM(1, 2, 3) = 6
AVERAGE(a, ...), AVG(a, ...) 1+ Arithmetic mean AVG(2, 4, 6) = 4
MIN(a, ...) 1+ Minimum MIN(8, 3, 5) = 3
MAX(a, ...) 1+ Maximum MAX(8, 3, 5) = 8
ABS(x) 1 Absolute value ABS(-3) = 3
SQRT(x) 1 Square root SQRT(16) = 4
CBRT(x) 1 Cube root CBRT(27) = 3
FLOOR(x) 1 Round toward negative infinity FLOOR(3.9) = 3
CEIL(x), CEILING(x) 1 Round toward positive infinity CEIL(3.1) = 4
ROUND(x) 1 Round to an integer ROUND(3.6) = 4
ROUND(x, scale) 2 Round at a decimal scale ROUND(12.36, 1) = 12.4
SIGN(x), SIGNUM(x) 1 Sign of a value SIGN(-8) = -1
EXP(x) 1 Euler's number raised to x EXP(1) = E
LOG(x), LN(x) 1 Natural logarithm LN(E) = 1
LOG10(x) 1 Base-10 logarithm LOG10(100) = 2
POW(x, y) 2 Power POW(2, 3) = 8
CLAMP(x, min, max) 3 Restrict a value to an interval CLAMP(12, 0, 10) = 10
FACT(x), FACTORIAL(x) 1 Factorial for integers from 0 through 170 FACT(5) = 120
NOT(x) 1 Numeric logical negation NOT(0) = 1
LERP(start, end, amount) 3 Unclamped linear interpolation LERP(10, 20, 0.25) = 12.5
INVERSE_LERP(start, end, value) 3 Unclamped position of a value in an interval INVERSE_LERP(10, 20, 12.5) = 0.25
SMOOTHSTEP(edge0, edge1, value) 3 Clamped smooth Hermite interpolation SMOOTHSTEP(0, 10, 5) = 0.5
HYPOT(x, y) 2 Stable sqrt(x² + y²) HYPOT(3, 4) = 5
FMA(a, b, c) 3 Fused multiply-add FMA(2, 3, 4) = 10
APPROX_EQ(a, b, epsilon) 3 Absolute-tolerance comparison APPROX_EQ(0.1 + 0.2, 0.3, 1e-12) = 1
IS_FINITE(x) 1 Tests whether a value is finite IS_FINITE(1 / 0) = 0
IS_NAN(x) 1 Tests whether a value is NaN IS_NAN(0 / 0) = 1
SIN(x) 1 Sine SIN(PI / 2) = 1
COS(x) 1 Cosine COS(PI) = -1
TAN(x) 1 Tangent TAN(PI / 4) = 1
ASIN(x) 1 Arc sine, result in radians ASIN(1) = PI / 2
ACOS(x) 1 Arc cosine, result in radians ACOS(0) = PI / 2
ATAN(x) 1 Arc tangent, result in radians ATAN(1) = PI / 4
ATAN2(y, x) 2 Two-argument arc tangent, result in radians ATAN2(1, 0) = PI / 2
COT(x) 1 Cotangent COT(PI / 4) = 1
CSC(x) 1 Cosecant CSC(PI / 6) = 2
SEC(x) 1 Secant SEC(PI / 3) = 2
ACOT(x) 1 Inverse cotangent, result in radians ACOT(1) = PI / 4
DEG(x) 1 Convert radians to degrees DEG(PI) = 180
RAD(x) 1 Convert degrees to radians RAD(180) = PI
SINH(x) 1 Hyperbolic sine SINH(0) = 0
COSH(x) 1 Hyperbolic cosine COSH(0) = 1
TANH(x) 1 Hyperbolic tangent TANH(0) = 0
ASINH(x) 1 Inverse hyperbolic sine ASINH(SINH(1)) = 1
ACOSH(x) 1 Inverse hyperbolic cosine ACOSH(1) = 0
ATANH(x) 1 Inverse hyperbolic tangent ATANH(0) = 0
COTH(x) 1 Hyperbolic cotangent COTH(2)
CSCH(x) 1 Hyperbolic cosecant CSCH(1)
SECH(x) 1 Hyperbolic secant SECH(0) = 1
ACOTH(x) 1 Inverse hyperbolic cotangent ACOTH(COTH(2)) = 2

Numerical domain errors follow Java double behavior unless a function documents a stricter range. For example, division by zero may produce infinity and an invalid square root produces NaN. Invalid factorial input and invalid ROUND scale throw ArithmeticException. Random ranges must be finite and increasing. Random integer bounds must be exact integers between -2^53 and 2^53. Gaussian attempt limits must be integers from 1 through 1,000,000; a bounded Gaussian that exhausts its attempts returns the mean clamped to the requested range.

Compile-time options

Options affect parsing only. The evaluator does not inspect them.

Option Default Effect
implicitMultiplication false Allows adjacency such as 2x, 2(x + 1), and 2SIN(x)

Create explicit options when non-default syntax is needed:

import net.momirealms.sparrow.expr.ExpressionOptions;
import net.momirealms.sparrow.expr.binding.ConstantBinder;
import net.momirealms.sparrow.expr.binding.FunctionBinder;

ExpressionOptions options = new ExpressionOptions(true);

ExpressionCompiler<CombatContext> compactCompiler =
        new ExpressionCompiler<>(
                parameterBinder,
                options,
                ConstantBinder.none(),
                FunctionBinder.none()
        );

compactCompiler.compile("2health + 3(limit - health)");

Power precedence is fixed above unary signs, so -2^2 is interpreted as -(2^2). Power remains right-associative, so 2^3^2 is interpreted as 2^(3^2).

Parameter binding

ParameterBinder<C> runs once for each distinct parameter in each compiled expression. It returns a numeric, string, or automatically inferred ParameterBinding<C>. The selected accessor is stored directly in the expression tree.

import net.momirealms.sparrow.expr.binding.ParameterBinder;
import net.momirealms.sparrow.expr.binding.ParameterBinding;

ParameterBinder<CombatContext> parameterBinder = name -> switch (name) {
    case "health" -> ParameterBinding.number(CombatContext::health);
    case "limit" -> ParameterBinding.number(CombatContext::limit);
    case "damage" -> ParameterBinding.number(CombatContext::damage);
    default -> throw new IllegalArgumentException("Unknown parameter: " + name);
};

The same parameter is bound only once inside one expression. A CompiledExpression retains only its optimized execution tree, not the source text or parameter-name metadata:

CompiledExpression<CombatContext> expression =
        compiler.compile("health + health * health");

If a host application uses markers such as angle-bracket placeholders, normalize them before calling compile:

host input:       <arg:health> <= <arg:limit>
normalized form: var1 <= var2
bindings:         var1 -> health accessor, var2 -> limit accessor

This keeps template parsing outside the numerical evaluator.

Compile-time constants

ConstantBinder is queried before parameter binding. A non-null value becomes a ConstantNode, participates in constant folding, and requires no runtime lookup. Return null when the identifier is not a host constant.

import net.momirealms.sparrow.expr.ExpressionOptions;
import net.momirealms.sparrow.expr.binding.ConstantBinder;
import net.momirealms.sparrow.expr.binding.FunctionBinder;

ConstantBinder constants = name -> switch (name) {
    case "TICKS_PER_SECOND" -> 20D;
    case "MAX_LEVEL" -> 100D;
    default -> null;
};

ExpressionCompiler<CombatContext> compilerWithConstants =
        new ExpressionCompiler<>(
                parameterBinder,
                ExpressionOptions.defaults(),
                constants,
                FunctionBinder.none()
        );

CompiledExpression<CombatContext> expression =
        compilerWithConstants.compile("damage * TICKS_PER_SECOND");
Constant-binding rule Detail
Name matching Host-defined names are case-sensitive
Unknown name Return null; parameter binding is attempted next
Repeated name Bound once per distinct name in one expression
Built-in constants TRUE, FALSE, PI, and E are resolved first
Runtime cost None; only the primitive value remains in the compiled tree

Custom functions

Custom functions are selected by uppercase name and argument count during compilation. Their arguments remain compiled expressions and are evaluated only when value is called, so a custom function may implement either eager or lazy behavior.

import net.momirealms.sparrow.expr.ExpressionOptions;
import net.momirealms.sparrow.expr.binding.ConstantBinder;
import net.momirealms.sparrow.expr.binding.FunctionBinder;

FunctionBinder<CombatContext> functions = (name, argumentCount) ->
        name.equals("MUL_ADD") && argumentCount == 3
                ? (context, arguments) -> arguments.value(0, context)
                        * arguments.value(1, context) + arguments.value(2, context)
                : null;

ExpressionCompiler<CombatContext> customCompiler = new ExpressionCompiler<>(
        parameterBinder,
        ExpressionOptions.defaults(),
        ConstantBinder.none(),
        functions
);

CompiledExpression<CombatContext> expression =
        customCompiler.compile("MUL_ADD(damage, 1.5, 2)");
Custom-function rule Detail
Name Supplied to the binder in uppercase
Overloads The binder also receives the parsed argument count
Unknown function Return null; compilation then reports an error
Arguments Access with arguments.value(index, context)
Allocation The argument container is created during compilation, not per evaluation

About

Fast & thread-safe Java expression library

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages