expression

Garnet Expression

garnet-expression is a small, closed, typed expression language for game data: Data formulas, Narrative conditions, Logic arguments, AI blackboard conditions, Balance Lab curves and World Atlas gates all use it.

It is not a scripting language. Game logic stays compiled Crystal. An expression is data: it has no loops, no assignments, no user-defined functions and no I/O. It can only use the operators below and the functions a host registers from Crystal. Source text is parsed and type-checked in the editor (or importer), then run by a compiled evaluator, or lowered to Crystal source for release builds.

source ──Lexer/Parser──▶ AST (spans) ──Checker + Schema──▶ typed IR ──Folder──▶ IR
                                                                         ├─ Compiler ──▶ closures (Program#evaluate)
                                                                         └─ CrystalEmitter ──▶ Crystal source

Installation

dependencies:
  garnet-expression:
    github: garnet-engine/expression
    branch: main
require "garnet-expression"

It depends only on garnet-math (Vec2, Vec3) and garnet-color (Color).

Quick start

alias E = Garnet::Expression

schema = E::Schema.new # holds its own registry of built-in functions
schema.variable "gold", "Int"
schema.variable "met_aria", "Bool"
schema.variable "hp", "Int?"

program = E.compile("gold >= 50 and not met_aria", schema, expected: E::Type::BOOL)

env = E::HashEnvironment.new
env["gold"] = 80
env["met_aria"] = false
program.bool(env)      # => true
program.dependencies   # => [gold, met_aria]
program.to_source      # => "gold >= 50 and not met_aria"

E.check collects every error instead of raising:

result = E.check("gold + \"x\" + gld", schema)
result.errors.each { |error| puts error.excerpt("gold + \"x\" + gld") }
# 1:1: Can't apply `+` to Int and String
#   gold + "x" + gld
#   ^^^^^^^^^^
# 1:14: Unknown variable `gld`; did you mean `gold`?
#   gold + "x" + gld
#                ^^^

Types

Type Values Literal
Bool true, false true
Int 64-bit signed integers 42, 1_000
Float 64-bit floats 2.5, 1e3, 1.5E-2
String UTF-8 text "a\n", 'it\'s'
Vec2, Vec3 Garnet::Math::Vec2/Vec3 vec2(1, 2), vec3(1, 2, 3)
Color Garnet::Color (linear) #ff8800, #f80, #ff880080 (sRGB, like CSS)
Enum(name) one option of an enum the schema declares damage::fire, or a string literal where an enum is expected
List(T) lists of one element type [1, 2, 3], []
T? T or null null

Types print and parse as text (Type.parse("List(Float)?")), which is how schemas, .vars.json files and Data fields store them. At runtime a value is an E::Value: Nil | Bool | Int64 | Float64 | String | Vec2 | Vec3 | Color | EnumValue | Array(Value).

Conversions are implicit only where nothing is lost: Int to Float, a string literal to an enum option (checked against the options), a list literal element by element, and T to T?.

Grammar

expression  = ternary EOF ;
ternary     = coalesce [ "?" ternary ":" ternary ] ;           (* right-assoc *)
coalesce    = or [ "??" coalesce ] ;                           (* right-assoc *)
or          = and { ( "or" | "||" ) and } ;
and         = not { ( "and" | "&&" ) not } ;
not         = ( "not" | "!" ) not | comparison ;
comparison  = additive [ ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) additive ] ;  (* no chaining *)
additive    = multiply { ( "+" | "-" ) multiply } ;
multiply    = unary { ( "*" | "/" | "//" | "%" ) unary } ;
unary       = "-" unary | power ;
power       = postfix [ "^" unary ] ;                          (* right-assoc, binds tighter than unary - *)
postfix     = primary { "." name | "[" ternary "]" | "(" [ ternary { "," ternary } ] ")" } ;
primary     = INT | FLOAT | STRING | COLOR | "true" | "false" | "null"
            | name "::" name                                   (* enum option *)
            | name
            | "(" ternary ")"
            | "[" [ ternary { "," ternary } [ "," ] ] "]" ;
name        = IDENT | "`" any text but ` and newline "`" ;
  • Identifiers are ASCII letters, digits and _, not starting with a digit. Backticks quote anything else, including keywords: items.`iron-sword`.price, `not`.
  • A call's callee must be a name or a dotted chain of names (quest.stage("intro")), never a computed value.
  • Strings take " or ', with escapes \n \t \r \0 \\ \" \' \u{1F600}.
  • not binds more loosely than comparisons, as in Python: not a == b is not (a == b). ! is the same operator.
  • -2 ^ 2 is -(2 ^ 2), and 2 ^ 3 ^ 2 is 2 ^ (3 ^ 2).
  • Comparisons don't chain: 1 < x < 3 is a syntax error; write 1 < x and x < 3.
  • Nesting deeper than 200 levels is a too_complex error.

Every AST node carries the Span of its source (byte offset, size, line, column).

Canonical source

node.to_source (and E.format(source)) prints canonical text: one space around binary operators, and/or/not, double-quoted strings, lowercase #rrggbb[aa], backticks only where needed, and parentheses only where precedence needs them. E.parse(node.to_source) == node for any parsed tree (equality ignores spans), and printing is idempotent. Store expressions as source strings; format them on save if you want stable diffs.

Operators

Operator Operands Result
+ - * Int, Int Int (an overflow error past 64 bits)
+ - * numbers with a Float Float
/ numbers Float (always; 7 / 2 is 3.5)
// Int, Int / numbers floor division: Int / Float
% Int, Int / numbers floored modulo (sign of the divisor)
^ numbers Float power
+ String, String concatenation
+ - Vec2, Vec2 / Vec3, Vec3 vector
* / vector and number (v * 2, 2 * v, v / 2) vector
unary - Int, Float, Vec2, Vec3 same
== != any two values of compatible types, including optionals Bool
< <= > >= two numbers or two strings Bool
and or not Bool Bool, short-circuiting
a ? b : c Bool condition, branches of compatible types the branches' type
a ?? b optional a a unless it's null, else b
.x .y .z Vec2, Vec3 Float
.r .g .b .a Color (linear channels) Float
list[i] List(T), Int T (an index_out_of_range error outside it)

Division and modulo by zero are division_by_zero errors, for floats too. == on floats treats numbers within 1e-6 as equal, matching AI::Blackboard; Int and Float compare by value.

Names, paths and schemas

A Schema declares what an expression may read:

schema = E::Schema.new
schema.variable "gold", E::Type::INT
schema.variable "target", "Vec3?"
damage = schema.enum "damage", %w(fire ice poison)
schema.variable "weakness", damage
# A family of paths, typed on demand (a Data table, say):
schema.resolver do |path|
  E::Type::INT if path.size == 3 && path.segments[0] == "items" && path.segments[2] == "price"
end

A dotted chain a.b.c resolves to the longest prefix the schema knows (a.b.c, then a.b, then a); the rest are members of that value. So player.position.y reads the variable player.position and takes .y. program.dependencies lists the resolved variables as Paths, whose #key is canonical dotted text (items.`iron-sword`.price).

Optional values

A T? value may be null and can't be used as a T until null is handled, or the checker reports optional_not_handled:

hp ?? 10                          # a default
hp != null and hp > 3             # narrowed in the right side of `and`
hp == null or hp > 3              # narrowed in the right side of `or`
target != null ? target.x : 0     # narrowed in the `then` branch
target == null ? 0 : target.x     # narrowed in the `else` branch

Narrowing applies to variables (not arbitrary expressions) and follows and, or, not and ?:. Comparing a value that can't be null with null is allowed and folds to a constant.

Functions

Functions.standard returns a new registry holding the built-ins below; Functions.new returns an empty one, for languages that allow no calls (Narrative may want that). Schema.new uses Functions.standard unless given another registry. There is no shared registry: each schema owns its own instance, so several worlds or editors in one process never see each other's functions.

Function Signature
min, max (Int, ...) -> Int, (Float, ...) -> Float, (List(Int)) -> Int, (List(Float)) -> Float
clamp (Int, Int, Int) -> Int, (Float, Float, Float) -> Float
lerp (Float, Float, Float), (Vec2, Vec2, Float), (Vec3, Vec3, Float), (Color, Color, Float)
round (Float) -> Int (half away from zero), (Float, Int) -> Float (digits)
floor, ceil, int (Float) -> Int (int truncates)
float (Float) -> Float (converts an Int)
abs, sign (Int) -> Int, (Float) -> Float
pow, atan2 (Float, Float) -> Float
sqrt, exp, log, sin, cos, tan (Float) -> Float
len (String) -> Int, (List(T)) -> Int
contains (List(T), T) -> Bool, (String, String) -> Bool
lower, upper, trim (String) -> String
starts_with, ends_with (String, String) -> Bool
sum (List(Int)) -> Int, (List(Float)) -> Float
str (any) -> String
format (String, any...) -> String: {} is the next argument, {1} argument 1, {{/}} braces
vec2, vec3 (Float, Float) -> Vec2, (Float, Float, Float) -> Vec3
rgb, rgba sRGB channels in 0..1 -> Color
length, normalize (Vec2), (Vec3)
distance, dot (Vec2, Vec2), (Vec3, Vec3)
if if(Bool, T, T) -> T, a lazy conditional (same as ?:)

Hosts register their own functions with typed signatures. Names may be dotted to namespace them:

schema.functions.register("damage", [E::Type::INT, E::Type::FLOAT], E::Type::FLOAT,
  crystal: ->(args : Array(String)) { "Combat.damage(#{args.join(", ")})" }) do |args|
  Combat.damage(args[0].as(Int64), args[1].as(Float64))
end
schema.functions.register("quest.stage", [E::Type::STRING], E::Type::INT.or_null, pure: false) do |args|
  quests.stage(args[0].as(String))
end

Arguments arrive converted to the declared parameter types. Overloads are tried in registration order. For generic signatures, register an E::Function with a custom typer. Functions are pure by default, so calls with constant arguments fold at compile time; pass pure: false for functions that read game state.

Evaluating

Program#evaluate(env) returns a Value; #bool, #int, #float and #string return typed results. An Environment supplies variable values by Path:

  • HashEnvironment: values by dotted text, with a revision per path.
  • ProcEnvironment: a block from Path to Value.
  • EmptyEnvironment: no variables.
  • Subclass Environment to read straight from game state.

Values are checked against the schema as they're read: a missing value for a variable that isn't optional is a null_value error, and a value of the wrong type is invalid_value. An Int is accepted for a Float, and an option name (String) for an enum.

The compiled form is a tree of closures, each specialized for its operator and operand types (an Int addition doesn't check for strings). Programs are immutable, hold no global state, and can be evaluated any number of times against different environments.

Constant folding

After checking, the Folder evaluates every operator and pure function call whose operands are constant (price * (2 + 3) becomes price * 5), and short-circuit forms with constant sides (false and x is false, true ? a : b is a, null ?? x is x, x != null is true when x can't be null). Branches proven dead are dropped, so they neither run nor count as dependencies. An error in live constant code, like price + 1 // 0, is reported at compile time. program.folded_source shows the result, and program.constant? says whether nothing was left to read.

Dependencies and recompute

program.dependencies lists the variables an expression reads after folding; AST::Node#references lists candidate a.b.c chains without a schema (for an expression that doesn't check yet).

DependencyGraph turns those lists into spreadsheet recompute:

graph = E::DependencyGraph.new
graph.set("sell_price", ["price"])
graph.set("profit", ["sell_price", "cost"])
graph.order                                # => ["sell_price", "profit"]
graph.affected(["price"])                  # => ["sell_price", "profit"]
graph.cycle_with("sell_price", ["profit"]) # => ["sell_price", "profit", "sell_price"]
graph.cycles                               # each strongly connected group, and self-loops

order and affected raise a cycle error naming the loop; cycle_with checks a new formula before it's committed.

Memo caches one program's result and re-evaluates only when a dependency's Environment#revision changed: pull-based recompute with no subscriptions. An environment that returns nil revisions disables caching.

Errors

E::Error follows Garnet::SceneData::Error: a stable code, a message, expected and actual where they apply, plus the span of the source and the path of a variable. #to_json writes them all and #excerpt(source) underlines the span.

Code Meaning
unexpected_character, unterminated_string, invalid_escape, invalid_number, unexpected_token, unexpected_end, too_complex syntax
unknown_variable, unknown_function, unknown_member, unknown_enum, unknown_option, invalid_type names (with "did you mean" hints)
type_mismatch, invalid_arguments, optional_not_handled, not_comparable types
division_by_zero, index_out_of_range, empty_list, overflow, null_value, invalid_value evaluation (or folding)
cycle DependencyGraph
not_lowerable a function without a Crystal lowering

Lowering to Crystal

Release builds can compile expressions in instead of evaluating data:

program.to_crystal_method("can_open")
# def can_open(env : ::Garnet::Expression::Environment) : Bool
#   ((::Garnet::Expression::Runtime.present(env.fetch(...), "keys")).as(Int64) >= 1_i64)
# end

ref = E::CrystalEmitter::RefLowering.new { |path, type| "state.#{path.segments.join('_')}" }
program.to_crystal(ref: ref) # variables read straight from game state

The generated code calls Garnet::Expression::Runtime, the same typed operations the evaluator uses, so both behave identically (overflow, division by zero, float equality, formatting). The specs compile ~100 generated expressions and compare them with the evaluator.

JSON values

E.from_json(json, type) and E.to_json_any(value) read and write values in the encodings SceneData documents use: [x, y], [x, y, z], [r, g, b, a] (linear), the option name for an enum, arrays for lists.

Compatibility with AI blackboard conditions

AI::Blackboard#matches?(key, op, value) evaluates declarative conditions (eq, neq, gt, gte, lt, lte, exists, missing). Every one of them can be written as an expression, and E::Conditions.from_blackboard(key, op, value) converts them:

Blackboard Expression
{"key": "health", "op": "lt", "value": 30} health != null and health < 30
{"key": "target", "op": "exists"} target != null
{"key": "target", "op": "missing"} target == null

Numeric equality uses the same 1e-6 tolerance. Differences:

  • Blackboard keys are untyped; an expression needs a schema. A blackboard comparison between mismatched types (a string against a number) is just false, while an expression rejects it at check time.
  • A blackboard comparison on a missing key is false. Converted conditions keep that with a != null guard, which folds away when the schema declares the key as not optional.
  • Blackboard Int32 values are Int (64-bit) here.
  • Keys that aren't identifiers (including dotted keys) are quoted: `enemy.pos` != null.

Design rules

  • Closed: no loops, assignments, user-defined functions or I/O. Expressions only call functions registered from Crystal.
  • No global state: registries, schemas, programs and environments are instances passed explicitly. Constants (Type::INT and friends) are immutable.
  • Pull-based: dependency lists and revisions, never subscriptions.

Development

shards install
crystal spec
crystal tool format --check src spec
ameba
Repository

expression

Owner
Statistic
  • 0
  • 0
  • 0
  • 1
  • 3
  • about 4 hours ago
  • December 3, 2026
License

MIT License

Links
Synced at

Sat, 05 Dec 2026 22:43:10 GMT

Languages