# rust-s-feel — a multi-target (S-)FEEL engine slice

A deliberately thin vertical slice of an (S-)FEEL expression engine in Rust. The
point is **not** FEEL completeness — it is to prove a multi-target architecture:
one pure core crate compiled into **four** targets (PostgreSQL via pgrx, WASM via
wasm-bindgen, Python via PyO3, Lua via mlua) that produce the **same result** for
the same expression, plus a closed ingestion loop from the official DMN-TCK test
suite into core unit tests.

```text
crates/feel-core   pure engine (lalrpop grammar + AST + evaluator); no target deps
crates/feel-pg     pgrx wrapper:  feel_eval / feel_eval_immutable (text, jsonb) RETURNS jsonb
crates/feel-wasm   wasm-bindgen wrapper:  evaluate(expr, context) -> JS value
crates/feel-py     PyO3 wrapper:  evaluate(expr, context) -> Python value
crates/feel-lua    mlua wrapper:  feel.evaluate(expr, context) -> Lua value
tools/ingest_tck.py  DMN-TCK literal-expression -> feel-core fixture (with deviations)
```

What the slice can evaluate — the FEEL **core language**
([learn-dmn-in-15-minutes](https://learn-dmn-in-15-minutes.com/learn/the-feel-language)):

- **Literals:** number, string, boolean, `null`, list (`[1, 2, 3]`, `[]`).
- **Arithmetic:** `+ - * /`, `**` (left-associative), unary `-`. Division by
  zero / type errors → `null`.
- **Comparison:** `< <= > >= = !=`, `between … and …`, and membership `in`
  with a positive unary test (DMN §10.3.2.6) — an interval (`[a..b]`, `(a..b]`,
  `[a..b)`, `(a..b)`) or a comparison (`x in < 10`, `x in = e`, `x in != e`) over
  numbers, strings, and temporals. (The comma-list forms `x in [1,2,3]` /
  `x in (a, < b)` are deferred — see ROADMAP.)
- **Type predicate (§10.3.2.9):** `value instance of type` over the built-in
  types (`number`, `string`, `date and time`, …, `Any`, `Null`) and inline
  generics `list<T>`, `context<k: T, …>`, `function<…> -> T`; an unmappable type
  (e.g. a model-defined name) → `null` (ADR-26).
- **Logic:** `and` / `or` / `not(…)` with three-valued (Kleene) semantics.
- **Control flow:** `if … then … else …`, `for v in src return …`,
  `some/every v in src satisfies …` (over list literals and integer ranges
  `a..b`), and variable references. `for`/`some`/`every` also take multiple
  comma-separated iteration contexts (`for i in a, j in b return …`; ADR-25) —
  the Cartesian product of the sources, rightmost context varying fastest, with
  each source scoped by the contexts to its left.
- **Lists & filters (§10.3.2.5):** member / path access `a.b`; the postfix
  `[…]` operator — 1-based index `list[1]` / `list[-1]` (negative-from-end,
  out-of-range → `null`) and Boolean filter `list[item > 5]` (the element is
  `item`; a context element's entries read without the `item.` prefix); and
  `.field` projection over a list of contexts (`[{x:1},{x:2}].x = [1, 2]`;
  ADR-24).
- **Built-in functions:** single- and multi-word string / list / numeric /
  context / boolean functions (`abs`, `string length`, `distinct values`,
  `get value`, `is`, …; ADR-15/ADR-17), callable positionally or with named
  arguments (`substring(string: "foobar", start position: 3)`; ADR-23).
- **String literals** decode the FEEL escapes (`\n \r \t \" \' \\`, `\uXXXX`
  incl. UTF-16 surrogate pairs, `\UXXXXXX`); an unrecognised escape (e.g. a regex
  `\d`) is preserved verbatim so it reaches the regex provider untouched.
- **Special-character names (§10.3.1.6, ADR-47/48):** a name may contain the
  additional name symbols `- + * / .` (`a-b`, `Date-Time`, `x.y` — including
  reserved words as non-initial parts, `x-in`; a name never starts with one).
  The ambiguity against arithmetic and path access is resolved against the
  **scope**: longest in-scope match preferred, left to right; spaces are not
  part of the name (`a - b` is the same candidate as `a-b`); `(a)-(b)` forces
  the operator reading. On a static path the navigated value is the scope
  (`applicant.first-name`). This is the **opt-in** `"symbols"` mode; both
  `evaluate` and `compile` then resolve per context — a compiled program
  caches one parse per distinct scope reading.
- **Backtick-quoted names** (`` `a-b` ``, `` `Profit and loss` ``,
  `` applicant.`first-name` `` — a non-standard extension with feel-scala's
  syntax, so Camunda expressions run unchanged): one name, decided by the text,
  in every name slot. A `names` option selects `"quoted"` (**the default** —
  backticks only, `a-b` always subtraction, Camunda semantics) or `"symbols"`
  (the DMN spec's scope-dependent reading); feel-pg takes it as the
  `name_resolution` argument (ADR-48). Inside
  backticks every character counts, spaces included: `` `a  b` `` is the key
  with two spaces, `` ` a` `` the one with a leading space — unlike unquoted
  multi-word names, whose spaces collapse to one.

  **Which to use?** If you read FEEL like a programming language, write every
  name that contains `- + * / .` (or a keyword) in **backticks** — the meaning
  then comes from the text alone, never from the data, and it runs the same in
  Camunda. Under the spec's own rule (`"symbols"`), spaces do *not* separate:
  with `unit`, `price` and `unit-price` all in the context, both `unit-price`
  and `unit - price` read the key `unit-price`, so adding that key to a row
  silently turns a subtraction into a lookup; `(unit)-(price)` forces the
  subtraction. That is why `"quoted"` is the default: `-` always means minus,
  whatever the data; choose `"symbols"` for third-party DMN models written
  with unquoted special names.

  | context `unit`, `price`, `unit-price` | `"symbols"` | `"quoted"` |
  |---|---|---|
  | `unit-price`, `unit - price` | key `unit-price` | `unit` − `price` |
  | `(unit)-(price)` | `unit` − `price` | `unit` − `price` |
  | `` `unit-price` `` | key `unit-price` | key `unit-price` |
- **User-defined functions:** FEEL `function(a, b) a + b` closures, and
  host-provided functions — a Python callable, JS function or Lua function passed in
  the context (or an ambient `functions` registry) and invoked from the expression,
  with positional / named / mixed arguments (Python kwargs, JS/Lua options object;
  ADR-23).
- **Temporal types:** `date`, `time`, `date and time`, and the two durations,
  with `@"…"` literals, arithmetic / comparison / component access (`.year`,
  `.time offset`, …), the temporal constructor and component built-ins
  (`date(…)`, `day of week(…)`, …), and `now()` / `today()` (ADR-18). Values
  cross the boundary as canonical ISO-8601 (native PostgreSQL `date`/`timestamptz`/
  `interval` casts; WASM `Date` objects; Python `datetime`/`dateutil` types). Named zones (`@Europe/Paris`) need the
  IANA tzdb: bundled on native / feel-pg, and in WASM via an opt-in feature —
  `wasm-pack build crates/feel-wasm --target nodejs -- --features iana-tz` (~723 KB
  vs the ~479 KB offset-only default, where a named zone evaluates to null).

Still out of scope: unary tests (the non-interval `in` forms); *unquoted*
special-character names in declaration slots (`for a-b in …`, formal
parameters, context keys), on dynamic path bases (`f(x).a-b`) and as
filter-element keys, *unquoted* space-joined reserved-word names
(`Profit and loss`) and `?`/non-XID name starts (`what if?`) — all reachable
with backticks (ADR-48); typed
function parameters, and general invocation on an arbitrary
expression that *holds* a function (`var(args)`, imported `lib.fn(args)`) — invoking
a non-function literal yields null per spec (ADR-38). See [DECISIONS.md](DECISIONS.md) for the
architecture decisions, the deferred-scope roadmap, and accepted deviations
(notably: numbers are `f64`, not spec `decimal128`; type errors evaluate to
`null`; temporal values outside jiff's range are skipped) — plus the
"Adding a wrapper — the host-binding contract" section for porting the engine to a
new target.

## Architecture invariant (Cardinal Rule)

`feel-core` must never depend on pgrx, wasm-bindgen, pyo3 or mlua. Verify:

```sh
cargo tree -p feel-core --edges normal,build | grep -E 'pgrx|wasm-bindgen|pyo3|mlua' && echo VIOLATION || echo OK
```

## Toolchain

- Rust **1.88+** (the pgrx 0.18 dependency tree uses `let`-chains). This repo was
  validated on rustc 1.96. Update with `rustup update stable` if needed.
- Python 3 (standard library only) for the ingestion script.
- For the WASM target: `rustup target add wasm32-unknown-unknown` and `wasm-pack`.
- For the Python target: a Python ≥ 3.9 (virtual) environment and `maturin`
  (PyO3 builds the extension module; one abi3 wheel covers all CPython ≥ 3.9).
- For the PostgreSQL target: PostgreSQL 13–18 with `pg_config`, plus `libclang`
  (pgrx uses bindgen), and `cargo-pgrx`.
- For the Lua target: nothing extra to run the Rust tests (Lua 5.4 is compiled in via
  mlua's `vendored` feature). To build the loadable `.so` and run `smoke.lua`, a Lua
  5.4 interpreter + dev headers (`lua5.4`, `pkg-config`).

## Build everything

```sh
# Portable members (always works on the host toolchain):
cargo build -p feel-core -p feel-wasm

# Whole workspace including feel-pg (requires the pgrx toolchain set up below):
cargo build
```

## core — engine + fixture test

```sh
cargo test -p feel-core
```

Runs the acceptance unit tests (`1 + 1` → 2, interval inclusivity, …) and the
fixture-driven test that loads every `crates/feel-core/tests/fixtures/*.json`
produced by the ingestion script and asserts each case in its declared
comparison mode (`exact` or `f64_epsilon`).

## ingestion — DMN-TCK → fixture

```sh
python tools/ingest_tck.py <path-to-tck-test> -o crates/feel-core/tests/fixtures/<name>.json
```

`<path-to-tck-test>` is a TCK test directory (or its `.dmn` file). The script
extracts each decision's literal expression and expected value, keeps only the
expressions that fit the current grammar slice, applies the deviation registry
(the `decimal-vs-f64` rule switches numeric results to epsilon comparison), and
prints a summary of processed / skipped cases and which deviation rules fired.
Built-in calls are kept whether positional or named (`abs(n: -1)`,
`substring(string: "foobar", start position: 3)`; ADR-23) — the two named forms
feel-core's parameter tables cannot bind stay out: a named call to a variadic
aggregate / varargs builder (`sum(list: …)`, no named form) and the temporal /
`context put` *overloads* whose name is absent from the single-row table
(`date(from: …)`, `context put(…, keys: …)`; see `NAMED_ARG_OVERLOAD_SKIPS`).

The fixtures used by the test (111 files, ~3153 self-contained cases) are
regenerated by pointing the script at each TCK dir, e.g.:

```sh
# numeric arithmetic -> f64_epsilon (decimal128 vs f64); type errors -> null
python tools/ingest_tck.py tests/tck/TestCases/compliance-level-3/0100-arithmetic \
  -o crates/feel-core/tests/fixtures/0100-arithmetic.json

# range 'in' cases -> exact (cross-checks interval inclusivity vs TCK)
python tools/ingest_tck.py tests/tck/TestCases/compliance-level-3/0072-feel-in \
  -o crates/feel-core/tests/fixtures/0072-feel-in.json

# for-loops -> list results
python tools/ingest_tck.py tests/tck/TestCases/compliance-level-3/0084-feel-for-loops \
  -o crates/feel-core/tests/fixtures/0084-feel-for-loops.json

# `instance of` type predicate -> boolean (built-in types + inline generics)
python tools/ingest_tck.py tests/tck/TestCases/compliance-level-3/0070-feel-instance-of \
  -o crates/feel-core/tests/fixtures/0070-instance-of.json
```

The other ingested dirs include `0005-literal-invocation`, `0016-some-every`,
`0032-conditionals`, `0034-drg-scopes`, and `0070-feel-instance-of`
(compliance-level-3, deferred quick-wins; ADR-45),
`1150-boxed-conditional`, `1151-boxed-filter`,
`1152-boxed-for`, `1153-boxed-some`, `1154-boxed-every`, and
`1161-boxed-list-expression` (compliance-level-3, DMN 1.5 boxed-expression
element forms — `<conditional>/<filter>/<for>/<some>/<every>/<list>`; ADR-44),
`0106-feel-ternary-logic` and
`0107-feel-ternary-logic-not` (compliance-level-2, context-bound three-valued
and/or/not; ADR-43), `0009-invocation-arithmetic` (compliance-level-2, BKM
invocation + arithmetic, canonical §10.6.5 calculation pattern; ADR-42),
`0008-LX-arithmetic` (compliance-level-2, structured-input loan payment formula; ADR-41),
`0100/0101/0102-feel-constants` (compliance-level-2,
boolean/number/string literal constants; ADR-40), `0105-feel-math` (compliance-level-2),
`0064`/`0065`/`0066` (and/or/not), `0071-feel-between`, `0075-feel-exponent`,
`0099-arithmetic-negation`, the single-word `feel-*-function` dirs (ADR-15), and
the multi-word string/list/context dirs reached via the lexer name-join (ADR-17:
`1104`-`1108`/`1140`, `0011`/`1155`/`0012`, `0080`/`0081`); `0057-feel-context`,
`0068-feel-equality`, `0074-feel-properties` and `1148-feel-now-function`; and the
round and context-manipulation built-ins (ADR-19: `1141`-`1144`, `1145`-`1147`).
The script reports the self-contained cases it kept and the out-of-scope ones it
skipped.

(The `tests/tck` submodule must be checked out: `git submodule update --init`.)

## pg — PostgreSQL extension (pgrx)

One-time setup:

```sh
cargo install cargo-pgrx --version 0.18.1 --locked
```

Then pick a PostgreSQL for pgrx to use:

```sh
# Option A (recommended for `cargo pgrx test`): a user-owned PG that pgrx builds
# and installs under ~/.pgrx, so the extension can be installed without root.
cargo pgrx init --pg18 download

# Option B: register an already-installed PostgreSQL 18 by its pg_config.
# This is fine for `cargo build` / `cargo pgrx run`, but `cargo pgrx test`
# needs write access to that install's extension dirs — a system package
# (root-owned /usr/lib|share/postgresql) will fail the test install step.
cargo pgrx init --pg18 $(which pg_config)
```

Run the in-process pgrx tests — `1 + 1`, range membership, the defaulted
`context` case, plus `if/then/else`, a `for` loop returning a jsonb array, and
string comparison:

```sh
cargo pgrx test -p feel-pg pg18
# test result: ok. 6 passed; 0 failed
```

Compile-only against system PG headers (no pgrx init needed):

```sh
PGRX_PG_CONFIG_PATH=$(which pg_config) cargo build -p feel-pg --no-default-features --features pg18
```

Run interactively against a pgrx-managed PG:

```sh
cargo pgrx run -p feel-pg pg18
# then in psql:
#   CREATE EXTENSION feel_pg;
#   SELECT feel_eval('1 + 1');                          -- 2
#   SELECT feel_eval('5 in [1..10]', '{}');             -- true
#   SELECT feel_eval('if 1 < 2 then 10 else 20');       -- 10
#   SELECT feel_eval('for i in [1,2,3] return i + 1');  -- [2, 3, 4]
#
#   -- feel_eval is STABLE PARALLEL SAFE; feel_eval_immutable is the IMMUTABLE,
#   -- deterministic subset (no now()/today(), no named time zones) for indexing:
#   CREATE INDEX ON applications
#     ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data)));
```

The jsonb boundary uses PostgreSQL's binary jsonb C API directly (no `serde_json`)
and reads the context lazily — nested objects are navigated on demand (ADR-21), so
reading one deep path out of a large context is cheap. A parse-cached `feel_eval` of
a low-to-medium expression runs ~2.3 µs/call on pg18, on par with the WASM build
(`COST 100`; RD-11).

Note: the pgrx extension name is `feel_pg` (underscored) — see
`crates/feel-pg/feel_pg.control`.

## wasm — Node module (wasm-bindgen)

```sh
rustup target add wasm32-unknown-unknown
cargo install wasm-pack --locked       # if not already installed
wasm-pack build crates/feel-wasm --target nodejs
node crates/feel-wasm/smoke.mjs        # one line per case, then "smoke test passed"
```

The context is a native JS object and the result is a native JS value (no JSON
strings). Parse/eval errors throw; `evaluate_strict` also throws on a null that
arose from a type/domain error.

```js
import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js";

evaluate("1 + 1", {});                         // => 2
evaluate("person.age", { person: { age: 42 } }); // => 42
evaluate("{a: 1, b: a + 1}", {});              // => { a: 1, b: 2 }
evaluate("1 + true", {});                      // => null  (lenient)
evaluate_strict("1 + true", {});               // throws   (strict)

// Parse once, evaluate many times (e.g. one expression over many rows):
const prog = compile("a + 1");
prog.evaluate({ a: 1 });                        // => 2
prog.evaluate({ a: 41 });                       // => 42
prog.free();                                    // optional; else GC reclaims it
```

The `matches`/`replace`/`split` builtins run on the **host** regex engine, so in
WASM the JS `RegExp` (ECMAScript) dialect applies (DECISIONS.md ADR-16). This
keeps the Rust regex stack out of the bundle (`feel_wasm_bg.wasm` is **272 KB**,
down from **1.29 MB**). Every other result is identical across targets; only
these three builtins are dialect-dependent. For byte-identical regex results
everywhere, build with `--features xpath-regex` to re-bundle the Rust engine:

```sh
wasm-pack build crates/feel-wasm --target nodejs -- --features xpath-regex
```

Compile-only check without wasm-pack:

```sh
cargo build -p feel-wasm --target wasm32-unknown-unknown
```

## python — module (PyO3 / maturin)

```sh
pip install maturin
cd crates/feel-py && maturin develop      # builds + installs into the active venv
pytest tests                              # 41 smoke tests
```

The context is a native Python value and the result is a native Python value.
Parse/eval errors raise `feel.FeelError`; `evaluate_strict` also raises on a null
that arose from a type/domain error.

```python
import feel

feel.evaluate("1 + 1")                          # => 2  (int, not 2.0)
feel.evaluate("person.age", {"person": {"age": 42}})  # => 42
feel.evaluate("{a: 1, b: a + 1}")               # => {"a": 1, "b": 2}
feel.evaluate("1 + true")                       # => None   (lenient)
feel.evaluate_strict("1 + true")                # raises    (strict)

# Parse once, evaluate many times:
prog = feel.compile("a + 1")
prog.evaluate({"a": 1})                          # => 2
prog.evaluate({"a": 41})                         # => 42
```

Besides `dict`s, a context may be any object, mapped **lazily** (DECISIONS.md
ADR-21): `order.customer.address` resolves one hop at a time via attribute access,
so a `@property`/relation loads **on demand**, exactly when the expression names it
(an untouched attribute never fires). A host object that comes back as the result is
the *same* object, not a snapshot. Because a (finite) expression only navigates a
finite path, cyclic graphs are fine — no cycle guard needed. Temporal values map to
`datetime`/`dateutil` types (years-months durations to `relativedelta`). The same
lazy mapping applies in feel-wasm (`Reflect.get`).

The `matches`/`replace`/`split` builtins run on the **host** regex engine, so in
Python the **`re`** dialect applies (DECISIONS.md ADR-16/RD-4) — the FEEL/XPath
flags `i s m x q` carry over (as inline `(?…)` flags / `re.escape`), as do inline
flags in the pattern. For results byte-identical to feel-core/TCK, build with the
Rust engine instead:

```sh
maturin develop --features xpath-regex
```

## lua — module (mlua)

Self-contained Rust integration tests embed a vendored Lua 5.4 and drive the module
from Lua scripts — no external interpreter needed:

```sh
cargo test -p feel-lua                    # 21 tests, Lua 5.4 compiled in (vendored)
```

To use it from a real Lua interpreter, build the loadable C module and run the
end-to-end smoke (the analogue of feel-wasm's `smoke.mjs`):

```sh
cargo build -p feel-lua --no-default-features --features lua54,module
LUA_CPATH='target/debug/lib?.so;;' lua5.4 crates/feel-lua/smoke.lua
```

(`lib?.so` expands `?` → `feel`, i.e. `libfeel.so`, so no rename is needed. Swap
`lua54` for `luajit`/`luau` to target those.) The context and the result are native
Lua values; parse/eval errors become Lua errors, and `evaluate_strict` also errors on
a null that arose from a type/domain error.

```lua
local feel = require("feel")

feel.evaluate("1 + 1")                                  -- => 2  (integer, not 2.0)
feel.evaluate("person.age", { person = { age = 42 } })  -- => 42
feel.evaluate("1 + true")                               -- => nil   (lenient)

-- Host functions: bound in the context, or via an ambient `functions` registry.
-- Lua has no kwargs, so FEEL named arguments arrive as a trailing options table.
feel.evaluate("f(2, 3)", { f = function(a, b) return a + b end })          -- => 5
feel.evaluate("f(2, b: 3)", { f = function(a, opts) return a + opts.b end })-- => 5
feel.evaluate("add(2, 3)", nil, { add = function(a, b) return a + b end })  -- => 5

-- Parse once, evaluate many times:
local prog = feel.compile("a + 1")
prog:evaluate({ a = 1 })                                -- => 2
prog:evaluate({ a = 41 })                               -- => 42
```

Like feel-py/feel-wasm, a context table is mapped **lazily** (DECISIONS.md ADR-21/
RD-9): `o.customer.address` resolves one hop at a time via `table[key]` (firing an
`__index` metamethod on demand), and a table/function that comes back as the result is
the *same* value, not a snapshot. A raised host-callable error is an **error-null** (→
`nil` lenient, an error under `evaluate_strict`), distinct from a callable that simply
`return`s `nil` (a value-null). The regex builtins use the bundled Rust dialect (no Lua
pattern engine; RD-7) and temporal values cross out as ISO-8601 strings (RD-8).

## benchmarks

Two harnesses quantify the parse-once / evaluate-many win and a cross-engine
comparison.

`feel-core` criterion bench — per workload, isolates `parse` (compile only),
`eval` (evaluate an already-compiled program) and `evaluate` (parse + eval).
`evaluate` minus `eval` is the per-call cost that `compile` removes:

```sh
cargo bench -p feel-core
```

`feel-wasm` Node bench — `feel-wasm` one-shot vs compiled vs **feelin** (a JS
FEEL engine), end-to-end including the JS↔WASM boundary:

```sh
wasm-pack build crates/feel-wasm --target nodejs
cd crates/feel-wasm && npm install && npm run bench
```

The headline result (with the logos lexer, ADR-3 addendum): parsing is cheap and
no longer rebuilds a lexer per call, so even the **one-shot** path is ~9–15×
faster than feelin, and the **compiled** path is ~18–33× faster (≈1.7–2.3× over
one-shot, by skipping the re-parse). Use `compile(...)` whenever the same
expression is evaluated more than once.

## Why this proves the architecture

`evaluate("1 + 1")` and `evaluate("5 in [1..10]")` give the same answer in
`feel-core` (Rust), in PostgreSQL (`feel_eval`), and in Node (`feel-wasm`),
all from one core. The ingestion path (TCK XML → Python → fixture →
feel-core assertion) is closed and cross-validates interval inclusivity against
the official DMN-TCK expectations. That is the success criterion.
