Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

Architecture Decisions

Short ADR-style entries (context → decision → consequence) for the choices that shape this vertical slice. Decisions that are conventions for later work (not yet exercised) are included so the rationale is recorded.

ADR-1: feel-core has no target-specific dependencies (Cardinal Rule)

  • Context: The engine must run inside PostgreSQL (pgrx), the browser/Node (wasm-bindgen) and Python (pyo3) — and, planned, Lua (mlua) — from one core. Two distinct invariants make "one core" mean something, and conflating them has caused confusion (ADR-16 describes itself as a "relaxation of the cardinal rule"), so name them apart:
    • I1 — Dependency purity (inviolable). feel-core depends only on portable crates (today: lalrpop/lalrpop-util, logos, unicode-ident, jiff, and the optional regex); no target crate (pgrx/wasm-bindgen/pyo3/mlua) ever enters its tree. Never relaxed.
    • I2 — Result determinism (relaxable, but only loudly). The same expression yields the same FEEL value on every target. A strong default, not an absolute: ADR-16 (host regex dialect) and per-host temporal representation (RD-2/RD-5) consciously relax it — always feature-flagged and documented, never silently. The boundary representation of a value (jsonb vs native vs ISO) is a wrapper concern (ADR-4), not part of I2.
  • Decision: Keep I1 absolute and I2 the default. Anything target-specific — including the JSON/native boundary mapping — lives exclusively in the wrapper crates (feel-pg, feel-wasm, feel-py, and the planned feel-lua).
  • Consequence: The core is reusable and testable on the host toolchain. I1 is enforced mechanically with cargo tree -p feel-core (must show no pgrx/wasm-bindgen/pyo3/mlua). Each I2 relaxation is recorded as an ADR or RD, so a reader sees exactly where — and why — two targets may differ.

ADR-2: Numbers are f64 for now (deviation from spec decimal128)

  • Context: FEEL mandates decimal128 (IEEE 754-2008, 34 significant digits). Using a decimal crate now would add weight before the architecture is proven.
  • Decision: Model Value::Number as f64. Do not pull in rust_decimal or bigdecimal yet. The deviation is accepted deliberately and fixed later.
  • Consequence: Some spec-exact numeric results are unreachable due to binary floating-point rounding. The TCK ingestion compensates by switching numeric comparisons to an epsilon tolerance (see ADR-6) so we get no false negatives.

ADR-3: Parser is generated from a declarative lalrpop grammar

  • Context: FEEL's grammar is left-recursive (e.g. additive expressions). A hand-written recursive-descent parser would have to encode that awkwardly.
  • Decision: Use lalrpop (LR(1), supports left recursion natively). The grammar lives as a declarative artifact crates/feel-core/src/feel.lalrpop and is generated at build time by crates/feel-core/build.rs. No hand-written parser.
  • Consequence: Grammar changes are localized to one .lalrpop file. There is a build-time dependency on lalrpop (a build-dependency only — it does not violate ADR-1). Generated code is included via lalrpop_mod!.
  • Addendum (logos lexer): lalrpop's built-in lexer is regex-driven — it pulls the regex-automata stack into the binary and rebuilds a matcher DFA on every ExprParser::new() (a fixed ~680 µs we briefly cached around). We replaced it with a logos compile-time-DFA lexer (src/lexer.rs) fed to the parser via an extern { enum Tok { … } } token block; lalrpop-util drops to default-features = false. Identifiers use unicode-ident's compact XID tables via a lead-char range (no \p{L} regex tables baked in), and keywords are remapped from a lexed name so maximal munch is preserved. ExprParser::new() is now free (~435 ns total parse for 1 + 1) and the regex crate is no longer needed just to tokenize — the prerequisite for ADR-16's bundle reduction. The grammar productions are unchanged; only the lexing mechanism moved.

ADR-4: Context and arrays cross target boundaries as JSON / jsonb

  • Context: Both targets need a language-neutral way to pass structured input (context) in and structured results out.
  • Decision: Represent context and (future) arrays as JSON at the boundary: PostgreSQL jsonb for feel-pg, a JSON string for feel-wasm. The mapping between JSON and feel-core types lives in the wrapper crates, not in core.
  • Consequence: feel_eval(expr text, context jsonb) RETURNS jsonb and evaluate(expr, context_json) -> String (JSON). Integral numbers are emitted as JSON integers so 1 + 1 yields 2, not 2.0. feel-core stays free of any serialization dependency in its non-dev tree.
  • Status: The literal "JSON at the boundary" framing is superseded. It held when feel-wasm exchanged JSON strings; the boundary has since become language-neutral structured values whose concrete representation is per-wrapper — jsonb (feel-pg) versus native host values mapped lazily through the ForeignObject seam (feel-wasm/feel-py, and the planned feel-lua), temporal values as native types or ISO-8601. See ADR-12 (Context), ADR-18 (temporal), ADR-20 (feel-py native mapping) and ADR-21 (lazy host values). The durable part holds: the mapping lives in the wrappers, never in core (ADR-1/I1), and integral numbers stay integers (1 + 1 → 2). The per-target representation differences are the I2-representation kind (ADR-1), not value divergence.

ADR-5: Temporal mapping convention (not exercised in this slice)

  • Context: FEEL has rich temporal types; PostgreSQL has its own. We want a consistent mapping before temporal work starts.
  • Decision: Prefer PostgreSQL interval ↔ FEEL days-and-time-duration. This slice implements no temporal types; the decision is recorded for later.
  • Consequence: When temporal support lands, the boundary mapping and a TCK deviation rule (placeholder already present) follow this convention.

ADR-6: TCK ingestion with an extensible deviation registry

  • Context: Because of ADR-2 (and future deviations), naively comparing our results to TCK expectations would produce false negatives.
  • Decision: tools/ingest_tck.py carries a deviation registry: a list of rules, each a (predicate, transform) pair. The live decimal-vs-f64 rule switches numeric expectations to comparison: "f64_epsilon" with a recorded deviation note. Future deviations (temporal, string edge cases) are present as documented, inert placeholders.
  • Consequence: Fixtures carry their own comparison mode (exact or f64_epsilon + epsilon). The feel-core fixture test honours that mode. New deviations are added as registry entries, not by editing expectations by hand.

ADR-7: Deliberately minimal grammar slice (superseded by ADR-8)

  • Context: The goal is to prove the dual-target architecture, not FEEL completeness.
  • Decision: The grammar covers only number literals, binary +, interval literals, and the in membership test — exactly what the acceptance tests and the ingested TCK cases need. The Python ingestion filters out any decision whose expression falls outside this slice.
  • Consequence: Most TCK decisions in a file are (correctly) skipped and reported. Widening the engine means widening the grammar and the ingestion predicate together.
  • Status: Superseded by ADR-8 — the architecture is proven, so the slice was widened to the FEEL core language. The principle (widen grammar and ingestion predicate together) still holds.

ADR-8: Widen the slice to the FEEL core language

  • Context: With the dual-target architecture proven, the next useful step is language coverage. The reference scope is the "core language" taught in learn-dmn-in-15-minutes: operators, literals, and control flow.
  • Decision: The grammar now covers: literals (number, string, boolean, null, list); arithmetic (+ - * /, ** left-associative, unary -); comparison (< <= > >= = !=, between, interval in); three-valued and/or/not; and control flow (if/then/else, for … return, some/every … satisfies) with variable references. Built-in functions and temporal types are still out of scope (see Roadmap). Numbers remain f64 (ADR-2). ** is left-associative and unary - binds tighter than ** (-3 ** 2 == 9), matching DMN-TCK 0075.
  • Consequence: The grammar is a full lalrpop precedence ladder (still conflict-free). The ingestion predicate widened in lockstep (ADR-11). Function and temporal TCK dirs are still skipped and reported.

ADR-9: Type errors evaluate to null (three-valued logic)

  • Context: FEEL is built on three-valued (Kleene) logic and is null-friendly: most operations on the wrong type yield null, not an error. The TCK encodes this directly (e.g. true and 123 → null, false = 0 → null, 100 / 0 → null).
  • Decision: The evaluator returns Value::Null for type mismatches, division by zero, non-finite arithmetic, non-boolean logic operands, and wrong-TYPE if conditions. FeelError is now effectively parse-only; evaluation always produces a Value. (A null if condition is a special case — see ADR-13.)
  • Consequence: This is a visible behaviour change at the wrappers — feel_eval('1 + true') now returns JSON null instead of raising an ERROR. It is required for the three-valued TCK cases to pass and matches the spec.
  • Status: Refined by ADR-14 — the error sources named here (type mismatch, division by zero, non-finite arithmetic, non-boolean logic operands) now produce an error-null (Value::Error) rather than a plain Value::Null, so provenance is tracked and the strict boundary can surface them. The three-valued result is unchanged (error-null behaves identically to null inside core).

ADR-10: Value extended with String and List (map type superseded by ADR-12)

  • Context: The core language needs strings (comparison, literals) and lists (for results, list literals, some/every sources).
  • Decision: Add Value::String and Value::List. Deliberately no context/map value type yet — the slice uses list literals, not contexts, so path access (i.price) is unnecessary. The boundary mapping (ADR-4) extends accordingly: both wrappers serialise strings to JSON strings and lists to JSON arrays, and accept the same on input (nested objects map to null).
  • Consequence: ADR-1 (Cardinal Rule) and ADR-4 (JSON boundary) are intact; only the wrapper mapping grew. List equality/expected comparison is structural and exact (no per-element f64_epsilon).
  • Status: The "no map type" part is superseded by ADR-12 — nested-object input and path access pulled Value::Context in.

ADR-12: Value::Context map type, path access, and context literals

  • Context: Real input is structured (nested objects), and the TCK dirs we most wanted to unlock (e.g. 0016-some-every with i.price) need a context/map value and member access. Identifiers were also ASCII-only, rejecting names like über.
  • Decision:
    • Identifiers widen to Unicode letters/digits ([\p{L}_][\p{L}\p{N}_]*); keyword precedence and longest-match are unaffected.
    • Add Value::Context(BTreeMap<String, Value>) — a FEEL context. BTreeMap gives structural (order-insensitive) equality for free and deterministic, key-ordered JSON output. Contexts are unordered, so they are not orderable (</> → null); equality is three-valued and recursive like lists.
    • Grammar gains a Postfix layer for path access a.b.c (binds tighter than unary minus; .. stays a distinct token) and a context literal {a: 1, b: a + 1} (keys are a Name or string literal). Context-literal entries bind progressively — a later entry may reference an earlier one.
    • Path on a non-context, or a missing member, is null (ADR-9 spirit).
    • Boundary mapping (ADR-4) extends in both wrappers: JSON objects ↔ Value::Context (previously objects mapped to null).
  • Consequence: ADR-1 and ADR-4 hold; only wrapper mapping and core grew. feel_eval('p.age', '{"p":{"age":42}}'::jsonb) now returns 42, and feel_eval('{a:1}') returns a jsonb object. if semantics are unchanged (a non-boolean/null condition still → null; see Roadmap).

ADR-11: Ingestion fitness is slice-grammar detection with bound inputs

  • Context: The old predicate was two per-form regexes (integer-add, integer-range). The widened grammar can't be captured that way.
  • Decision: fits_slice_grammar(expression, input_names) keeps a literal-expression decision iff every name in it is acceptable — a keyword, a for/some/every loop variable, a context-literal key, a member access (.field), or one of the case's captured <inputNode> names — and it uses no out-of-scope syntax (temporal @, filters, parenthesised range tests, multiple iteration contexts, in forms other than a bracketed interval). Context literals {} are now in scope (ADR-12). Each case's <inputNode> values are captured into a context object and bound during evaluation, so input-reading expressions are now ingestible. parse_decisions only accepts a decision whose direct logic is a <literalExpression> (relations/contexts/ decision tables are skipped, not mined for inner cells). It is intentionally conservative: a borderline case is skipped rather than risk a false positive.
  • Consequence: The engine itself remains the source of truth — the fixture-driven test (cargo test -p feel-core) parses and evaluates every kept case against its bound context, so any predicate leak fails loudly and the predicate is tightened. Cases the predicate over-skips are reported, never silently wrong. (This loop already caught a relation decision wrongly mined as "widget", and the contested 0032 if-null case — see Roadmap.)

ADR-13: if distinguishes a null condition from a wrong-type one

  • Context: Enabling input-bound TCK ingestion (ADR-11/12) surfaced 0032-conditionals, where if bool then … else … with bool = null expects the else branch (→ 90). Our if (ADR-9) returned null for any non-boolean condition, matching Camunda/feel-scala — which deliberately deviates from the TCK, arguing a mistyped condition should not be silently swallowed. The OMG DMN reference (jDMN, validating the TCK) instead treats if as condition == true ? then : else, so false/null/non-boolean all go to else.
  • Decision: Adopt a synthesis that is TCK-compliant and honours Camunda's argument, keyed on the kind of condition:
    • true → then; false → else.
    • null → else — null is a legitimate FEEL value meaning "not true", and the TCK requires it. (This is the one point where we must diverge from Camunda to stay TCK-compliant.)
    • any other type (number, string, list, context) → null — a genuine type error, kept visible per ADR-9. This honours Camunda's concern. The TCK never tests a wrong-type if condition, so nothing forces us off the safe path here; we knowingly diverge from jDMN only on this untested input.
  • Consequence: 0032-conditionals (cases 001–003) ingests and passes; if 5 then 1 else 2 and if "x" then 1 else 2 stay null (observably). The divergence from jDMN is confined to untested wrong-type conditions and is documented rather than silent.
  • Status: Refined by ADR-14 — the "wrong-type → null" outcome is now an error-null, and the if rule keys on null provenance rather than the static type of the condition.

ADR-14: Error provenance — Value::Error ("error-null") with sticky three-valued logic

  • Context: FEEL overloads null with two meanings: a legitimate absence (missing field, explicit null) and the result of a type/domain error (1 + true, 1/0, comparing incomparable types). ADR-9 made both plain null, which conflicts with "errors should never pass silently": an error that becomes null then vanishes. ADR-13's if keyed on the static type of the condition, which still swallowed a computed error-null (if (5 + "x") …).
  • Decision: Track provenance with a distinct Value::Error ("error-null"). It behaves identically to Value::Null for every FEEL operation (equality: error = null → true; ordering; three-valued logic) so spec/TCK results are unchanged. The error sources of ADR-9 now produce Value::Error; the null literal, unbound variables and missing members stay Value::Null.
    • AND/OR (Design 1 — sticky, strong Kleene): the truth value is exactly strong three-valued logic — a dominating false (and) / true (or) wins regardless of the other operand, so false and (1/0) is false and the TCK stays green. Provenance is consulted only for the "unknown" null result: it is an error-null iff a contributing unknown operand was tainted (an error-null, or a wrong-typed value — a value-null is a legitimate untainted unknown). Quantifiers fold the same rule. (The contagious/weak-Kleene alternative — any error operand poisons the result — was rejected: it breaks false and <error> = false.)
    • if: true → then; false/value-null → else; error-null or wrong-type condition → error-null (the error escalates, refining ADR-13).
    • Boundary policy (in the wrappers, per ADR-1/ADR-4): lenient (default) collapses error-null to JSON/jsonb null; strict surfaces it. feel-pg's feel_eval(…, strict => true) raises an ERROR; feel-wasm's evaluate_strict returns {"error": …}. The pure core never throws.
  • Consequence: "errors never pass silently" is honoured without leaving the spec: the core stays TCK-compliant (errors are null there) but provenance is tracked, and the edge may escalate it. Value gains contains_error() and into_lenient(); the fixture test and lenient wrappers compare/serialise the lenient view. An in-expression assert non null(x) tripwire is a natural complement once built-in functions land (see Roadmap).

ADR-15: Single-word built-in functions (call grammar + dispatch table)

  • Context: The slice had no built-in functions (ADR-7/ADR-8). Full FEEL also allows space-containing names (string length), which the lexer cannot tokenise as one Name. The first useful, low-risk increment is the single- word, non-temporal functions — they reuse the existing Value kinds and unlock a large batch of self-contained feel-*-function TCK dirs.
  • Decision: Add function calls as a new production in the Postfix grammar rule: Name "(" args ")" → Expr::FnCall(name, args). An LR(1) lookahead of ( after a Name shifts into the call, otherwise it reduces to a Var, so plain variable references are unaffected; not(...) keeps its own keyword rule. A builtins module dispatches by name + arity. Implemented (per spec §10.3.4): conversion string/number; string substring/contains/replace/split/ matches; list count/min/max/sum/mean/product/median/stddev/ mode/all/any/append/concatenate/union/remove/reverse/flatten/ sublist; numeric decimal/floor/ceiling/abs/modulo/sqrt/exp/log/ even/odd. (even/odd reject non-integers, sqrt negatives, and log non-positive arguments as domain errors.)
    • Error policy (ADR-14): wrong arity / wrong type / domain error / unknown name → error-null; spec-legitimate empty/absent results (sum([]) = null, min([]) = null, mode([]) = [], count([]) = 0) → value-null. The N=0 vararg form (all(), mode()) is null, distinct from the empty-list arg.
    • Varargs: aggregates accept either one list argument or a list of scalars (sum([1,2,3]) == sum(1,2,3)); a single list arg is unwrapped (coerce_list).
    • Non-terminating results (decimal-vs-f64 deviation): exp/log return irrationals the TCK rounds to a fixed number of decimal places (8 → up to 5e-9 of truncation error), so the numeric comparison tolerance was widened from 1e-9 to 1e-8 to absorb that alongside the decimal128→f64 rounding.
    • Regex (regex-xpath-dialect deviation): replace/split/matches use Rust's regex crate, whose dialect differs from the spec's normative XQuery/XPath 2.0 F&O regex. A minimal translation ($N → ${N} in the replacement; rejecting non-smixq flags) covers the common cases; features Rust's finite-automaton engine cannot do (backreferences, class subtraction [A-Z-[OI]], \p{IsBasicLatin} block names) — plus XPath string escapes (\u, \n) the lexer does not decode — are skipped via the documented REGEX_DIALECT_SKIPS list in tools/ingest_tck.py (not silently rewritten).
  • Consequence: feel-core gains a regex dependency (portable, so ADR-1 holds). The ingest predicate whitelists implemented built-in call heads so their calls fit the slice while unimplemented/temporal/multi-word/user-defined ones stay skipped. Two latent ingest bugs surfaced and were fixed: a declared xsd:string value was mis-typed as a number (string(2) = "2"), and string results were whitespace-stripped (substring("foob r", -2, 1) = " "). Unlocked 20 feel-*-function / list / string TCK dirs (303 → 541 fixture cases).
  • Deferred (still out of scope): space-containing names (string length) are now done — see ADR-17. Temporal functions and abs on durations (await ADR temporal types), sort and the matching-function form of list replace (need function values), range relations and is (need first-class ranges / temporal identity), and a full XPath-regex dialect bridge.

ADR-16: Host-environment regex dialect (per-target FeelRegex provider)

  • Context: The matches/replace/split builtins (ADR-15) used Rust's regex crate everywhere. That crate's regex-automata stack (engine + Unicode tables, ~0.6 MB of code plus .rodata) dominated the WASM bundle. It was pulled by two consumers: lalrpop's built-in lexer and these three builtins. Removing the lexer's copy (the logos addendum to ADR-3) is not enough — the builtins still pull the whole stack. Meanwhile most hosts already ship a capable regex engine (the browser/Node RegExp; Python's re; PostgreSQL's POSIX ARE), and FEEL/XPath regex is its own dialect that no single embedded engine reproduces exactly anyway. (Where a host has no regex engine — Lua offers only the weaker Lua patterns, not regex — the seam degrades gracefully: keep the bundled RustRegex, as feel-pg does (RD-1), rather than force a lossy host dialect. The provider is a per-target choice, not an obligation.)
  • Decision: Abstract the three regex builtins behind a FeelRegex trait (is_match/replace/split, each returning None → FEEL null for a dialect/pattern error) and thread it through evaluation via an Evaluator carrying &dyn FeelRegex (kept out of Context, which is cloned per loop). The public API adds evaluate_with / CompiledExpr::evaluate_with; the no-argument evaluate uses a default provider. The Rust engine becomes an optional feel-core dependency behind the default rust-regex feature. Each target then uses its host's engine — and therefore its host's dialect:
    • feel-wasm: a JS RegExp provider (ECMAScript dialect); built with default-features = false, so the Rust regex stack leaves the bundle (1,289,360 → 272,636 bytes, ~79% smaller).
    • feel-pg: keeps RustRegex for now (size is irrelevant server-side); a PgRegex (POSIX ARE) provider is a recorded future option (a note in feel-pg), not built here.
    • default feel-core / cargo test: RustRegex, so the ADR-15 results and the TCK fixtures are unchanged.
    • purists: feel-wasm's opt-in xpath-regex feature re-bundles RustRegex for byte-identical cross-target results, paying the size cost knowingly.
  • Consequence: This is a deliberate, scoped relaxation of the cardinal rule "same core, same result across targets" (ADR-1): only these three builtins are now dialect-dependent — every other value is still bit-identical everywhere. The relaxation is loud, not silent: it is feature-flagged, the reversible xpath-regex escape hatch exists, and TCK regex fixtures validate the rust-regex path (the JS/PG dialects are host-defined). The flag-mapping corners differ by dialect (the JS provider maps i/s/m, escapes for q, and ignores x, which ECMAScript lacks; invalid flag letters → null in both). A bare feel-core --no-default-features build with no injected provider has no engine to consult, so the three builtins are an error-null ("unsupported in this build", via FeelRegex::available) — distinct from the value-null an invalid pattern produces, so the strict boundary surfaces it (ADR-14). ADR-15's regex-xpath-dialect deviation is now per-target rather than global.

ADR-17: Full FEEL names (whitespace) + multi-word built-ins via a two-tier lexer join

  • Context: FEEL names may contain spaces — both user names (full name, year of birth) and built-ins (string length, list contains, date and time). ADR-15 deferred these because the single-Name-token lexer cannot form them. The spec resolves the ambiguity they create (a + b = a name or an addition?) with a name oracle: the parser must know the names in scope and take the longest match. That couples parsing to the evaluation context — a large lift we did not want for this increment (temporal values stay out, too).

  • Decision: Join multi-word names in a second pass over the token stream (lexer::join_names), so the grammar is unchanged — the Name terminal just carries a space-normalised payload now. No name oracle is needed: soundness comes from FEEL having no juxtaposition of two expressions, so two adjacent Name tokens can only be one name. Two tiers:

    • Tier 1 (generic): greedily merge a run of adjacent Name tokens. Keywords are separate tokens (the keyword() remap already ran) and stop the run, so x and y stays boolean — the join is backward-compatible (it only turns the previously-invalid a b into a name). Covers user names and every keyword-free multi-word built-in.
    • Tier 2 (the built-in exception): a fixed, closed dictionary of keyword- containing built-in phrases (builtins::KEYWORD_PHRASE_BUILTINS: date and time, years and months duration) matched only in call position (immediately followed by (). It needs no oracle because the set is finite and holds only built-in names, never user variables — this is the bounded "exception for built-ins" that lets date and time(…) parse without scope-aware parsing.

    The non-temporal multi-word built-ins are implemented (per spec §10.3.4): string string length/upper case/lower case/substring before/substring after/ starts with/ends with/string join; list list contains/index of/ distinct values/insert before/list replace (positional form); context get value/get entries. Dispatch is the same match name as ADR-15 (a normalised single-space key), so single- and multi-word calls share one path.

    • Error policy (ADR-14) is unchanged: wrong arity/type/domain → error-null; spec-legitimate empties (string join([]) = "", index of(l, x) = [], get entries({}) = []) → value-null/empty. string join skips null items and treats a scalar as a one-element list; get value returns null for an absent or present-null entry; list replace truncates a fractional position. The keyword-phrase temporals parse but dispatch to error-null until temporal types land (the name machinery is what lands here).
    • Ingestion widened in lockstep: multi-word call heads and multi-word free names fit the slice predicate, and parse_expected_node learns context (<component>) results so get entries' {key, value} list is no longer degraded to [null]. Unlocked 1104-1108/1140 (string), 0011/1155/0012 (list), 0080/0081 (context); 541 → 672 fixture cases.
  • Consequence: No grammar change and no new lalrpop conflict — the token set is identical, only Name payloads grew. ADR-1 holds: names are strings and the JSON boundary already carries arbitrary keys, so the wrappers are untouched.

  • Deviations (deliberate, documented):

    • Special characters in names (+ - * / . ' and the ? name-part char) are out — a name is whitespace-joined words only. These are what reintroduce the arithmetic ambiguity, so supporting them would need the oracle.
    • Keyword-containing variables (date and time as a free name) are out; only the fixed built-in phrases are recognised, and only in call position.
    • The date and time(x) vs date and (time(x)) collision is resolved toward the built-in phrase (the oracle case). Both are temporal-adjacent and yield null today, so the choice is observable only once temporal types exist.

ADR-18: Temporal types (date, time, date and time, the two durations)

  • Context: Temporal support was deferred from the start (ADR-8) with the PostgreSQL mapping pre-decided (ADR-5) and the multi-word name machinery shipped (ADR-17, so date and time(…) already lexed). This is the largest remaining slice: FEEL's five temporal types, their @"…" literals, arithmetic, comparison, component access, and the temporal built-in functions.
  • Decision:
    • Library jiff (RD-/portable, ADR-1 holds). Its calendar-aware Span / SignedDuration map cleanly onto FEEL's two distinct duration types, it has nanosecond precision, and ISO-8601 parse/format. feel-core never enables jiff's wasm-bindgen-pulling js feature; the wrappers do. The embedded IANA tzdb (needed only to resolve named zones like @Europe/Paris where there is no system tzdb, i.e. on wasm) is opt-in behind a feature flag, mirroring ADR-16's regex split: feel-core's default tzdb-bundle feature embeds it (native builds and feel-pg get full zones; native also has the system tzdb); feel-wasm builds default-features = false and so is offset-only by default (+02:00/Z work, a named zone evaluates to null), re-enabling the bundle via its iana-tz feature.
    • Five flat Value variants (matching the existing flat style): Date, Time, DateTime (each civil value + an optional zone preserved verbatim for output: Z vs +00:00 vs @Area/City), YearsMonthsDuration(i64 months), DaysTimeDuration(SignedDuration). All temporal logic — parsing, canonical ISO-8601 formatting, comparison/equality, arithmetic, component access — lives in one temporal module; eval/builtins delegate.
    • @"…" literal is a new lexer value token (its type is inferred from the lexical form); a malformed literal is an error-null. Date strings are strict 4-digit-year; 24:00:00 rolls to next-day midnight; a zero offset is Z; offsets are bounded to ±14:00; a named zone combined with an explicit offset, and a leap second, are errors.
    • Arithmetic follows the FEEL table: date/time/date-and-time ± duration, date ± days-time-duration → date, point − point → days-time-duration, duration ± duration, duration × / number, duration / duration → number. Two date-times subtract only when both are instants (a date is midnight UTC; a zoned date-time) or both floating (a zoneless date-time); a mix is a type error. String + concatenates. Component access (.year, .time offset, .seconds, …) extends Expr::Path.
    • Built-ins: constructors date/time/date and time/duration/ years and months duration (with their arity overloads), components day of week/month of year (names) and day of year/week of year (numbers), and abs on durations (ADR-15 had deferred it).
    • Injected clock (generalises ADR-16's regex seam): an EvalEnv carries the regex provider and the instant now()/today() read. CompiledExpr gains evaluate_with_env. feel-pg supplies GetCurrentTransactionStartTimestamp() (transaction-stable, matching PostgreSQL's now()); feel-wasm supplies Date.now(); tests inject a fixed instant (so the clock builtins are deterministic).
    • Boundary = canonical ISO-8601 (durations P1Y2M, dates 2017-08-03). feel-pg emits ISO jsonb strings, so a plain SQL cast yields native date/timestamptz/interval (activating ADR-5's mapping) with the cast's error path staying in SQL. feel-wasm returns date/date-and-time as native JS Date objects (ISO string fallback when Date can't represent them; time and durations stay ISO strings) and accepts JS Date objects anywhere in the context input.
  • Consequence: Reverses ADR-5's deferral; the temporal-interval-mapping deviation is now live. Ingested 0007, 0095–0098, 1115–1117, 1120–1121 and the temporal halves of 0100/0075/0099: 672 → 1709 fixture cases. The default WASM bundle grows ~272 KB → ~479 KB (the jiff date/time code, no tzdb); --features iana-tz adds the tzdb for ~723 KB. ADR-1 is intact (cargo tree -p feel-core shows no pgrx/wasm-bindgen).
  • Deviations (deliberate, documented): jiff caps the year at ±9999 and its Span caps the years/months magnitude, so the TCK's extreme-range dates/durations (and the odd duration("PT0.S") lexical form) cannot round-trip; these are listed in tools/ingest_tck.py's TEMPORAL_RANGE_SKIPS. Unary tests (the non-interval in forms) and special-character/hyphen names stay out of scope (see Roadmap).

ADR-19: Round and context-manipulation built-ins

  • Context: After ADR-18, four TCK dirs the core already evaluates had never been ingested (0057-feel-context, 0068-feel-equality, 0074-feel-properties, 1148-feel-now-function), and the four round … functions plus context / context put / context merge were absent from both the ingest whitelist and the dispatch table — leaving 1141–1147 skipped wholesale.
  • Decision (2026-06-16):
    • round up / round down / round half up / round half down(n, scale) — added to the numeric dispatch (builtins::round_fn). scale is required (the one-arg form is left out pending TCK clarification). Numbers are f64 (ADR-2), so the modes map onto native f64 rounding: away-from-zero (ceil/floor by sign), toward-zero (trunc), nearest-ties-away (f64::round), nearest-ties-toward. A scale outside decimal128's [-6111, 6176] range is null; a scale valid for decimal128 but beyond f64's exponent range is a no-op (returns n).
    • context(entries), context put(context, key|keys, value), context merge(contexts) — added to the context dispatch. context put takes a string key (shallow) or a list path (deep_put, recursing the spec's context put(m[k], rest, v); descending into a missing/non-context intermediate is null). Duplicate keys in context are null; context merge overwrites at the top level (no deep merge); a single context/entry is coerced to a one-element list.
    • Context literals with duplicate keys now evaluate to error-null too (eval_context_lit), matching context() and DMN-TCK 0057.
  • Consequence: 1709 → 1940 fixture cases across 11 new dirs. No grammar or lexer change — the multi-word heads ride ADR-17's generic name-join. The ingest's slice detector gained a postfix-[ filter/index reject (feel-core implements no filters) and a TEMPORAL_SUBSECOND_EQUALITY_SKIPS list for the two 0068 cases that assert second-resolution temporal equality (feel-core compares jiff values at nanosecond precision; matching would discard sub-second precision). Named-argument call variants stay out of the slice (the AST is positional-only, ADR-15).

ADR-20: Python bindings (feel-py, PyO3 + maturin)

  • Context: feel-core already has a Postgres wrapper (feel-pg) and a WASM wrapper (feel-wasm); Python is a common host for decision logic and data pipelines. A fourth wrapper should expose FEEL to Python without touching the pure core (ADR-1): all target glue, including the JSON/native boundary mapping, lives in the wrapper.
  • Decision (2026-06-16): new crates/feel-py, built with PyO3 0.28 + maturin (abi3-py39 → a single wheel for every CPython ≥ 3.9). Surface mirrors feel-wasm: free evaluate(expr, context=None) / evaluate_strict(...) plus a compile(expr) returning a reusable CompiledExpr (parse-once / evaluate-many). The lenient/strict null policy is ADR-14; a parse/eval error or a strict error-null raises feel.FeelError (a subclass of ValueError). now()/today() read the system clock as a fixed-offset UTC instant. The three boundary sub-decisions are recorded as RD-4 (regex dialect), RD-5 (temporal mapping) and RD-6 (context mapping). feel-py keeps feel-core's default features (so RustRegex is available as the xpath-regex provider, and the system tzdb resolves named zones) and is in the workspace members but not default-members — it needs a PyO3 link context (built via maturin), like feel-pg needs pgrx.
  • Consequence: a fourth target on the same core, verified by 21 pytest cases (crates/feel-py/tests) plus a Rust unit test for the replacement-string translation. Alongside it, feel-wasm's js_to_value was hardened with the same cycle/depth guard feel-py uses: its recursion was previously unbounded, so a cyclic JS object (a.b = a, legal in JS) could overflow the stack; a back-edge now maps to null (no other behaviour change — own-enumerable getters still fire as before). (The eager boundary conversion this describes — and both cycle guards — were superseded by ADR-21, which makes context mapping lazy.)

ADR-21: Lazy host values (Value::Foreign, the ForeignObject seam)

  • Context: The wrappers (feel-py, feel-wasm) converted the whole host object graph into a materialised Value tree eagerly at the boundary (RD-6). That walks branches the expression never touches, snapshots data instead of reflecting the live object, and needs an up-front cycle/depth guard. The recurring use case is an ORM row or a deep object where order.customer.address should resolve one hop at a time, loading relations on demand. RD-6 had rejected the lazy alternative, fearing it would duck-type the evaluator and contaminate all targets; on revisiting, the seam turned out far cleaner, so RD-6 is flipped.
  • Decision (2026-06-17): add a target-agnostic, std-only trait ForeignObject { get(key) -> Value; force() -> Value; as_any() } and a Value::Foreign(Foreign) variant, where Foreign(Arc<dyn ForeignObject>) is a newtype that hand-implements Debug/Clone/PartialEq (the last as Arc::ptr_eq) so Value keeps its derives. feel-core never constructs a Foreign; only the wrappers do. The rule: the FEEL dot (Expr::Path) resolves a Foreign lazily, by name, via get — the one place it is not forced; every other consumption (arithmetic, comparison, three-valued logic, if, in/between, iteration, builtin arguments) first calls Value::forced, an #[inline] tag test that materialises one level via force. get uses host attribute access (getattr / Reflect.get), so it fires @property/accessor getters — ORM relations load exactly when the expression names them; force enumerates own instance data only (no blanket property sweep). A Foreign that reaches the result passes through: the wrapper recovers the original host object via as_any and returns it untouched (identity, no re-traversal). Operators keep FEEL semantics by construction — force only converts a host value into a Value, then FEEL's own arithmetic/comparison runs; the host's __add__/+ is never invoked. The boundary sub-decision is RD-6 (now flipped).
  • Consequence: lazy is the default mapping in both wrappers, replacing the eager RD-6 conversion. Pure-Rust embedders are unaffected and pay nothing: Value does not grow (the variant is a 16-byte fat pointer, under the 32-byte temporal variant — pinned by a size test), and the forced checks fall through with a single predicted branch when no Foreign exists. ADR-1 holds — the trait is std-only, like the FeelRegex seam (ADR-16) — and feel-pg, which never builds a Foreign, gains one defensive, unreachable match arm that treats a stray Foreign as an error-null (the evaluator's "unexpected value -> error-null" rule), not a silent value-null. Cyclic graphs need no engine guard: a finite expression navigates a finite path, and output passes through rather than re-walking, so the js_to_value/py_to_value guards added under ADR-20 are removed. The single residual is structurally comparing two distinct cyclic foreign graphs, bounded by an Arc::ptr_eq short-circuit plus a recursion cap in feel_equal. Verified by feel-core foreign-seam unit tests (path is lazy → get, consume forces, an unbounded graph terminates along a finite path, Value size pinned), 24 feel-py pytest cases (a getter fires on access, an untouched sibling property does not, identity pass-through, cyclic finite path), and feel-wasm smoke cases (Reflect.get getter, nested navigation, pass-through identity, cyclic termination).
  • Thread-safety & lifetime (deliberate, and Lua-relevant): ForeignObject: Debug carries no Send/Sync bound, so Value and Context became !Send + !Sync the moment a Foreign can appear. This is intentional — host handles are themselves !Send (a JsValue; an mlua Table) — and costs the current hosts nothing, since each evaluates on a single thread (the pgrx backend, the WASM thread, under the Python GIL). The price: a Value/Context carrying a Foreign cannot cross threads; a cross-thread embedder must first materialise a Foreign-free Value (force the subtree) or take the eager-snapshot route (RD-6, "if flipped back"). The trait object is Arc<dyn ForeignObject + 'static>, so a wrapper's stored handle must be owned/'static — Py<PyAny>, JsValue, and mlua ≥ 0.10's lifetime-free Table all qualify (an older, lifetime-parameterised mlua would not). This is what makes the planned feel-lua (ADR-22) a clean fit rather than a fight with the borrow checker.

ADR-22: Lua bindings (feel-lua, mlua)

  • Context: feel-core already powers three wrappers (feel-pg, feel-wasm, feel-py). Lua is a common embedded-scripting and rules host (game logic, Redis, nginx/ OpenResty, Neovim, application plugins), so a fifth target is a natural next step. This entry was recorded before the crate was built (in the spirit of ADR-5) and is now realised; the three boundary sub-decisions stand as RD-7 (regex), RD-8 (temporal) and RD-9 (context mapping), and the seven reusable seams are the "Adding a wrapper" contract below. Built 2026-06-17.
  • Library (reconsidered, not just inherited): the candidates were re-checked rather than taking the original note at face value. rlua is deprecated (v0.20 is a thin re-export of mlua) — a dead end; hlua is effectively unmaintained; piccolo (a pure-Rust stackless VM) is attractive (no C, sandboxing-focused) but pre-1.0 with an incomplete stdlib, and its values are gc-arena-bound with a 'gc lifetime — the opposite of what the Arc<dyn ForeignObject + 'static> seam needs, reintroducing exactly the lifetime fight an old lifetime-parameterised mlua would. mlua (0.11.6) is actively maintained, covers Lua 5.1–5.5 + LuaJIT + Luau, has first-class loadable- module support, and — since 0.10 — owned 'static Table/Function/Value. So mlua wins on the merits, not by default.
  • Decision: a new crates/feel-lua, a wrapper over the same core (ADR-1/I1 holds — mlua lives only here), built with mlua 0.11. It ships as a Lua-loadable C module (#[mlua::lua_module] fn feel → luaopen_feel, exposing feel.evaluate/evaluate_strict/compile) — the analogue of feel-py's Python module and feel-wasm's JS module. The module-building logic is factored into a plain build_module(&Lua) so the Rust integration tests drive it against an embedded VM. Like feel-py and feel-pg, feel-lua needs a Lua link context, so it sits in the workspace members but not default-members (a bare cargo build keeps building only the portable members). Cargo features select the Lua flavour/mode: default = ["lua54", "vendored"] (the test/embed build, where Lua::new() works), with luajit/luau and a module feature (link the host's Lua, build the loadable .so: cargo build -p feel-lua --no-default-features --features lua54,module). vendored and module are practically exclusive — one embeds Lua, the other expects the host's.
  • Hazard handled: Lua signals errors by longjmp (like PostgreSQL — the RD-1 hazard), but mlua wraps every C-API call and surfaces them as Result<_, mlua::Error>, so the longjmp never unwinds through Rust frames. Two distinct mappings: a failed member access (LuaForeign::get/force: a raised __index, a bad access) is a value-null (the defensive feel-py getattr pattern, ADR-21); a failed host call (LuaForeignFn::call: a raised Lua error) is an error-null (Value::Error, ADR-14/ADR-23), distinct from a callable that simply returns nil (value-null).
  • Named arguments: Lua has no kwargs, so — exactly like feel-wasm's options object — FEEL named arguments become a single trailing table {name = value}. A returned host callable/table passes back by identity (as_any downcast). Argument marshalling uses mlua's IntoLua so the conversion runs with the &Lua that Function::call already holds (ForeignFunction::call is handed no state).
  • Consequence: a fifth target on the same core, verified two ways (per the user-chosen "both"): 21 Rust integration tests embedding a vendored VM, and a smoke.lua run end-to-end through the loadable module under the system lua5.4. Value stays !Send (ADR-21), which matches mlua's non-Send values rather than fighting them. I2 (ADR-1) relaxes here exactly as elsewhere — no Lua regex (RD-7), no native Lua temporal (RD-8) — both loud and documented, neither a surprise.

ADR-23: User-defined functions — FEEL closures and host callables

  • Context: the engine could only call built-ins; FEEL's own function(a, b) body literal (DMN-TCK level 3, 0030/0031) and — the bigger driver for this project — host-provided functions (a JS function, a Python callable passed into evaluation) had no representation. The seam was already anticipated: ADR-21's ForeignObject is the object analogue, and the builtins note already required a UDF call to bind its arguments unforced.
  • Decision: one first-class Value::Function(Arc<Func>) where Func is either a native Closure { params, body, captured } (a function(…) literal, captured with its definition scope — FEEL functions are lexical closures, spec §10.3.2.9) or a Foreign(Arc<dyn ForeignFunction>) host callable. ForeignFunction is the function analogue of ForeignObject: std-only, target-agnostic, constructed only by wrappers (ADR-1 holds). A single Arc keeps the variant one word, so Value stays 40 bytes (the size-regression test pins it).
    • Grammar: function becomes a keyword; the literal is a loosest-binding form (body extends right, like if). A unified Arg rule parses positional (expr) and named (name: expr) arguments — clean LR(1), the : lookahead decides — into CallArgs { positional, named }.
    • Dispatch (in eval): a function-valued context binding wins first (so a binding can shadow a built-in — host override), then the built-in, then the ambient FunctionRegistry on EvalEnv, else error-null. Arguments are evaluated unforced so ADR-21 path laziness flows through a call (built-ins force internally; closures and host callables receive them lazy).
    • Binding is lenient vs. spec §10.3.2.13.5: an unsupplied parameter is value-null (the spec's named-arg rule, extended to positional under-supply — no strict arity), while genuine non-conformance (unknown name, double-bind, too many positional) is an error-null. A recursion depth cap turns runaway self-application into an error-null instead of a stack overflow.
    • Named arguments are a deliberate, tolerant superset of spec rule 39: the spec makes positional and named exclusive, but we allow them mixed (f(2, b: 3)), because that maps one-to-one onto Python's f(*positional, **named) and so reaches a host callable's positional-only and keyword-only parameters. Pure-positional and pure-named stay spec-conformant. Named arguments work for built-ins too (spec §10.3.2.13.5) via a per-built-in parameter-name table + reorder shim; the purely variadic aggregates (min/max/sum/…) have no named-parameter form and reject named calls.
    • Host injection has two paths (both, per the design choice): bind a callable directly as a context value, or pass an ambient functions registry. Per wrapper: feel-py maps named args to real Python kwargs (f(*pos, **named)); feel-wasm has no kwargs, so named args become a single trailing options object {name: value}; a returned host callable passes back out by identity (as_any downcast). feel-pg has no host-function seam (its input is JSONB, not host handles) — native function(…) literals still evaluate there, and a function reaching the JSONB output is null.
  • Testing: DMN-TCK 0030/0031 cannot be auto-ingested — their decisions are boxed <context>/<functionDefinition> (not literal expressions) invoking user-defined and imported functions, both outside the slice, so tools/ingest_tck.py skips them. The tests are therefore hand-written: feel-core unit tests + a hand-written 0030 fixture (each case carrying a source provenance note reconstructing the TCK semantics as a self-contained expression), plus pytest and Node smoke cases for the host paths. Named-argument calls to built-ins are auto-ingested, though (abs(n: -1), substring(string: …, start position: …)): the slice detector keeps them and the closed loop validates the binding. Two named forms feel-core's parameter tables cannot bind stay skipped — a named call to a variadic aggregate / varargs builder (no named form) and the temporal-constructor / context put overloads whose name is absent from the single-row table (date(from: …), context put(…, keys: …)) — both documented in the ingester (_NO_NAMED_FORM_BUILTINS, NAMED_ARG_OVERLOAD_SKIPS). During the chore/fixture-refresh sweep (2026-06-18) the ingester produced 0 cases for 0030 (still a boxed-context dir); the 7 hand-written cases were deliberately retained — they test real feel-core functionality and have no auto-ingestible equivalent.
  • Consequence: FEEL gains first-class functions across every target that has a host function concept, reusing ADR-21's laziness and identity pass-through wholesale. Still out of scope (documented): typed parameters function(a: string), general invocation on an arbitrary expression (expr(args), lib.fn(args)), and external/imported functions.

ADR-24: List filter, index & projection — list[…] (DMN §10.3.2.5)

  • Context: the postfix […] operator was the last missing piece of the "Lists and filters" section (§10.3.2.5) — both positional indexing (list[1], list[-1]) and the Boolean filter (list[item > 5]). It was deferred for one round (see the roadmap entry, now resolved) with the grammar conflict flagged for deliberate checking.
  • Decision: one AST node Expr::Filter(Box<Expr>, Box<Expr>) for source[bracket], parsed as a postfix production on the Postfix layer — the same precedence as path access (a.b[1] is (a.b)[1], xs.x[2] is (xs.x)[2]).
    • Grammar (conflict resolved): a [ in primary position is a list literal (Primary → List); a [ directly after a completed Postfix is unambiguously a subscript; interval [a..b] only follows in. This is the identical shift-after-value pattern the . path rule already uses, so it stays LR(1) — lalrpop builds conflict-free (the build.rs gate would fail otherwise).
    • Index vs. filter is decided at evaluation by the bracket's value type (the spec leaves the form to the value): the bracket is evaluated once in the outer scope — a Number is a 1-based positional index (negative-from-end via the shared resolve_index; non-integer or out of range → value-null); anything else is a Boolean filter, re-evaluated per element. item is unbound in the outer scope, so a real predicate like item > 2 is null there and correctly falls through to the filter path.
    • Filter scope (filter_scope) binds the current element as item; if the element is a context, its entries are also spread into scope so they read without an item. prefix ([{x:1}][x = 1]) — but a context that already carries an item key keeps that key as item. The element is forced for the entry-spread while the item binding stays the original value, preserving Foreign identity (ADR-21). Non-true predicate results (false / null / error) drop the element.
    • Source coercion (implicit conversion §10.3.2.9.4): a non-list, non-null source is a singleton (5[1] = 5, 5[item > 3] = [5]); null source → null; error → error.
    • Projection: the Expr::Path arm gains a list case so .field over a list of contexts maps the access ([{x:1},{x:2}].x = [1,2], missing key → null in that slot), sharing one member_access helper with the scalar case. The list is not forced first, so a single Foreign keeps the lazy-dot path (ADR-21).
  • Tests: feel-core unit tests for index/filter/projection (incl. singleton coercion, the item-key shadow, and composition), plus the ingested DMN-TCK 0001-filter (Employees[dept = 20].name). The slice detector dropped its postfix-[ reject, added item as an allowed implicit name, and now collects context-element keys from input data (collect_context_keys) so a filter referencing an element's entries fits the slice.
  • Consequence: §10.3.2.5 is complete. Still out of scope (documented): unary tests (the non-interval in forms), and sort/matching-list replace (need a function-valued comparator — feasible now that function values exist, ADR-23).

ADR-25: Multiple iteration contexts — for/some/every (FEEL rules 44/46)

  • Context: for, some and every were single-context only (for i in a return …). FEEL allows one or more comma-separated iteration contexts (for i in a, j in b return …; rules 44 & 46), iterating the Cartesian product of the sources. DMN-TCK 0033-for-loops (for h in heights, w in widths return h * w → [20,30,40,60,60,90]) exercises it and was being skipped by the ingester.
  • Decision: Expr::For and Expr::Quantified now hold bindings: Vec<(String, IterSource)> (the tuple idiom already used by ContextLit) instead of a single var/source.
    • Grammar: one new IterCtx rule (name in source) fed through the existing Comma<T> helper over the shared IterSrc. A top-level , is consumed only by Comma<IterCtx> — IterSrc (Sum ".." Sum | Disjunction) never eats one — so after each context the lookahead is , (more) or return/satisfies, keeping it LR(1). The build.rs lalrpop gate fails on any conflict; it builds clean, and single-context input still parses unchanged.
    • Semantics (eval): eval_for/eval_quantified recurse over the bindings. The body/predicate runs over the Cartesian product in declaration order with the rightmost context varying fastest; each source is resolved in the scope of the contexts to its left, so a later source may reference an earlier variable (for i in [1,2], j in i..3 return j = [1,2,3,2,3]). iter_values is reused unchanged (one source, one scope) — the recursion supplies the per-level scope.
    • Edge cases (parity with single context): a non-iterable source at any level makes the whole expression an error-null; the quantifier short-circuit (some→true / every→false on the first dominating tuple) and the sticky error-provenance (saw_unknown/tainted) are preserved across the full product via a small QuantOutcome enum.
    • Slice detector: fits_slice_grammar dropped its multi-context reject, now captures the subsequent , name in variables as bound names, and recognises a , name in clause as an iterator in (not an unsupported membership form).
  • Tests: feel-core unit tests for for/some/every multi-context (product order, left-to-right source scoping, empty-source product, short-circuit), plus the ingested DMN-TCK multi-context for-loop cases now kept by the slice detector.
  • Consequence: rules 44/46 are complete except the for-body special variable partial (the partial result list), which stays out of scope — it is unsupported for a single context too, and TCK cases using it remain skipped by the free-identifier scan.

ADR-26: instance of type predicate — type lattice & structural conformance (DMN §10.3.2.9)

  • Context: instance of (value instance of type, grammar rule 51) was the last comparison-level operator missing from feel-core, and the only one needing a notion the engine lacked entirely: a type. DMN-TCK 0070-feel-instance-of exercises it across every value kind, against built-in/Any/Null types and inline generics.
  • Decision: add a minimal type lattice L as ast::FeelType (the primitive nodes, Any/Null, the parameterised list/range/context/function nodes, and an Unknown node for unmappable type names), and one AST node Expr::InstanceOf(Box<Expr>, FeelType). The FeelType is resolved at parse time — it carries no runtime data.
    • Type grammar (spec rule 52), restricted & LR(1)-clean: the right operand parses via a dedicated InstanceType sub-grammar reachable only after instance of — a named type, list<T>/range<T>, context<k: T, …>, or function<…> -> T. The field-vs-type choice inside <…> reuses the same one-token (:) lookahead the call Arg rule already uses, so lalrpop builds conflict-free (the build.rs gate enforces it). An unmappable name — a model itemDefinition type this standalone engine can't resolve, a typo, or a bare list/context that "requires parameters" — becomes FeelType::Unknown, so e.g. 123 instance of list evaluates to null (the spec result) rather than failing to parse.
    • instance of lexing (no new reserved words): instance and of are not reserved — FEEL names may contain them (year of birth, the day of week built-in), so reserving of would break those. Instead a pre-pass ([lexer::mark_instance_of]) fuses only the adjacent instance of pair into one Tok::InstanceOf operator before name-joining; a lone instance/of stays an ordinary name-word. The function-type arrow -> is a new logos token (it only ever appears literally in a function type, so maximal-munch keeps -/> intact elsewhere). The three keyword-containing temporal type names (date and time, years and months duration, days and time duration) are now joined into a single Name wherever they occur (previously only in call position) so they read as type names too; they are reserved FEEL type/constructor names, so the only behaviour lost is logical-and of variables literally named date/time/… — not meaningful FEEL.
    • Semantics — structural conformance (types::value_conforms_to): rather than a canonical type(value) + lattice conforms_to with joins, the value is checked against the target type structurally (equivalent for every FEEL shape, less code). Top level: an unmappable type → null; a null/error value is an instance only of Null; otherwise the value must conform. A null nested in a list element or context field has type Null and Null <: T, so it conforms — which is why {a: null} instance of context<a: string> is true while top-level null instance of string is false. context conformance allows extra value keys (n ≥ m); functions check arity only (untyped closures map to (Any, …) -> Any).
  • Tests: ingested DMN-TCK 0070-feel-instance-of (119 self-contained cases; the slice detector now splits on instance of and validates the type's words against a built-in whitelist). The 23 skipped cases reference model itemDefinition types (no type registry exists — out of scope) or are function-literal values (function literals aren't ingested generally); both are covered by feel-core unit tests, alongside the spec Table 62 examples and the nested-null/Null edges.
  • Consequence: §10.3.2.9 type-checking is supported for the self-contained type language. Still out of scope (documented): model-defined itemDefinition types (need a type registry threaded from the embedder). (range values: see ADR-27 — they are now first-class, so instance of range<T> is no longer always false.)

ADR-27: First-class range values (DMN §10.3.4.6)

  • Context: ranges were deferred from the start (ADR-7/ADR-8) as tests only — [a..b] was reachable in the grammar solely after in, with no value of its own. The documented blocker was the interval-vs-list bracket ambiguity: factoring IntervalStart → "[" as its own nonterminal clashes with the list literal on the bare [. Making ranges first-class unlocks 1156-range-function, the relation suite 1130-feel-interval, and the range cases in 0068-feel-equality / 0072-feel-in.
  • Decision: add Value::Range(Box<RangeVal>) (two same-typed endpoints + per-bracket openness), boxed so Value stays 40 bytes, and make a range a first-class value end-to-end.
    • Grammar — no LR rewrite needed (LALR would not have helped; it is weaker than lalrpop's default LR(1)). A range literal is an ordinary Primary (Expr::RangeLit) whose production shares the "[" Sum (resp. "(" Sum) prefix with the list literal (resp. grouping) and branches on the next token — .. ⇒ range, ]/,/) ⇒ list / grouping. The branch is on disjoint lookahead (.. is unique), so it is LR(1)-clean with no IntervalStart nonterminal — exactly the factoring that used to conflict. build.rs's no-conflict gate proves it.
    • in RHS — bare endpoint. InRhs takes a bare Sum; ast::unary_test_from_expr routes a written interval literal to the dedicated UnaryTest::Interval (byte-for- byte the old membership test, no regression) and anything else to UnaryTest::Endpoint, evaluated as equality x = e — or, when e is a range value, as range membership (2 in range("[1..3]")). This also gives bare equality (1 in 1) for free. The comma-list-of-tests forms (x in [1,2,3], x in [[a..b],[c..d]]) stay deferred — there the brackets are a list of tests, not one value (the genuine ambiguity).
    • range(string) built-in. It compiles the string, then gates on the AST shape: the expression must be a range literal whose endpoints are literals — a number / string / @"…" / null, or a temporal constructor on a string literal. So range("[date(string(\"…\"))..…]") is null even though it would evaluate fine (the spec wants literals only). The evaluated endpoints must then be non-null, same-typed and ascending (via feel_order), else null.
    • Equality & instance of. =/!= compare ranges structurally (openness flags + both endpoints, FEEL-equal); instance of range<T> requires both endpoints to conform to T (reusing conforms_nested, so a null endpoint conforms).
    • Relations (Allen interval algebra). The 13 §10.3.4.6 relations (before/after/ meets/met by/overlaps/overlaps before/overlaps after/finishes/finished by/includes/during/starts/started by/coincides) are built-ins. Each operand is viewed uniformly as an interval — a point p is the degenerate closed [p..p] — so one inclusion-aware formula per relation covers every point/range overload; six are the swap of another (after = before(b,a)). Endpoint comparison uses feel_order; an incomparable pair is an error-null.
    • Wrappers. A range has no native host type, so feel-lua/feel-py map it to a table/dict carrying DMN's four range properties (start, end, start included, end included).
  • Tests: ingested 1156-range-function (41 cases) and re-ingested 0068/0072 (+3 range equality, +8 range membership); suite 2598 → 2650. 1130-feel-interval's decisions are boxed contexts the literalExpression-only ingester does not read, so its full 132-case relation truth table (every openness edge) is exercised as a feel-core unit test instead.
  • Consequence: ranges are first-class — constructible, comparable, type-checkable, usable in value position and as in membership. Still deferred (the bracket-ambiguity forms): comma-list-of-tests in (now done, ADR-28), the reverse-bracket interval notation ]a..b] / [a..b[ and the range properties (now done, ADR-29), unbounded ranges ([1..], (null..10)), and the comparison-test-as-range value ((< 10)). See ROADMAP.md for entry points.

ADR-28: comma-list-of-tests in-RHS (positive unary test lists)

  • Context: the one bracket-ambiguity form left after ADR-27 was the comma-list of tests on the right of in — x in [1,2,3], x in (false,true), x in (1,<5,>=10), x in [[2..4],[1..3]]. A reviewer sharpened the diagnosis: the in-RHS is a different grammatical category (DMN rule 49, positive unary tests), not an expression — which is what separate lalrpop nonterminals are for. The earlier "would force a hand-written parser" worry was specific to the scope-dependent special-character-name oracle, and a TCK measurement showed that has ~0 payoff in the expression slice. So: stay on lalrpop.
  • Decision: give InRhs its own test-mode productions instead of delegating the whole RHS to Sum.
    • Bracket-free NbSum chain is the lever. The bare-endpoint branch of InRhs routes through NbSum/NbProduct/…/NbPrimary — a copy of the Sum precedence chain whose leftmost primary drops List, RangeLit and the "(" Expr ")" grouping. By never starting with [/(, it leaves the in [ / in ( states with exactly one bracket production (the test-list / interval) instead of two competing ones (test-list vs. the value List/RangeLit reachable through a full Sum). With only one, the interval-vs-list split is a clean first-element factoring — parse the first Sum, then branch on .. (interval) vs. ,/]/) (list) — a FIRST-overlap on a shared prefix, not a token-role conflict, so it is LR(1)-clean. build.rs's gate passed on the first build. (This is the discriminator that also explains why reverse-OPEN ]a..b] is fatal: it overloads ] as an opener against its closer role — same token, two actions, not factorable. See ROADMAP.)
    • Elements reuse existing machinery. UnaryTestElem is CmpOp Sum (a comparison) or a bare Sum; a nested interval [2..4] arrives as a RangeLit value that unary_test_from_expr reclassifies to UnaryTest::Interval. Expr::In already carries Vec<UnaryTest> and eval_in already OR-folds it (ADR-27), so eval is untouched — x in [1,2,3] → [Endpoint(1),Endpoint(2),Endpoint(3)], x in [[2..4],[1..3]] → [Interval,Interval], all evaluate as the OR of element tests.
    • (=10)/(!=10) come free. A one-element paren test whose element is a comparison is structurally just a Compare element, so the in-position cases (10 in (=10) → true) fall out of the same test-mode grammar with no extra work — the parser half of "comparison-as-range" without its eval half.
  • Two plan hypotheses the TCK then falsified (measured, not argued):
    • Null endpoint is not ±∞. 5 in [null..10] and friends expect null, not true — a null bound is "unknown ⇒ unknown result", which feel-core's three-valued range_contains already returns. So those five 0072 cases were already green via the widened ingester; the planned ±∞ membership change was dropped (it would have flipped them red).
    • (< 10) is not a promoted range. 0068 says (< 10) = (null..10) → false and (= 10) = [10..10] → false, while (< 10) = (< 10), (= 10) = (= 10), (!= 10) = (!= 10) → true. A parenthesised comparison-test value equals an identical test but is never equal to a Range — i.e. it is an opaque unary-test value, not the range the desugar hypothesis assumed. Modelling it needs a new Value variant touching equality; deferred as genuinely spec-murky (this resolves the range_006 question the ADR-27 consequence list left open).
  • Cross-type equality skip (TCK bug). One 0072 case, true in [false, 2, 3], expects false, but feel-core returns null — which is what the spec also requires. §10.3.2.2 states cross-type = is null ("values must be of the same kind to obtain a non-null result"; example: "I" = 1 → null). Table 53 confirms: inputs outside the same-kind domain yield null. Table 56 expands e in [a, b, c] to e=a or e=b or e=c; with (true=false) or (true=2) or (true=3) = false or null or null = null (Table 51). The 0068-feel-equality fixtures agree (false = 0 → null, 100 = "100" → null). The TCK expectation of false is inconsistent with the spec and has been filed upstream. Skipped by id (CROSS_TYPE_EQUALITY_SKIPS).
  • Tests: widened the ingester in-RHS gate (_balanced_bracket_group, and the value-position (<…) reject now fires only when not after in); re-ingested 0072-feel-in (255 → 325). Suite 2650 → 2720. A data-driven lib.rs test (in_unary_test_lists_tck_0072) covers the forms directly.
  • Consequence: the comma-list / paren-list / (=e) test forms are in. Of the originally planned follow-ups only this one was real; the ±∞ and range-promotion forms were retired by the TCK. Reverse-bracket intervals ]a..b] / [a..b[ (the fatal token-role case + the filter-free-endpoint refactor) are now done (ADR-29). Still deferred: unbounded [1..] / [..10] omitted endpoints, the opaque comparison-test value (< 10) in value position, and not(tests) negation.

ADR-29: Reverse-bracket interval literals & range properties (DMN §10.3.2.6)

  • Context: ADR-27/ADR-28 left three range forms deferred; this clears two — the reverse-bracket interval spellings ]a..b] (exclusive lower, ≡ (a..b]) and [a..b[ (exclusive upper, ≡ [a..b)) — plus the range property accessors .start / .end / .start included / .end included (DMN §10.3.2.6) that make them observable. The two bracket surgeries are independent and were diagnosed differently by ADR-28: reverse-OPEN is a token-role problem (lexer), reverse-CLOSE a filter shift/reduce (grammar).
  • Decision: ship all three, each at its natural layer.
    • Reverse-OPEN ]a..b] — lexer retag, not grammar. Letting ] open a primary collides with its universal closer role: the empty list [] and a [ followed by a reverse-open ] are not LR(1)-separable (one terminal, two shift targets — the fatal case ADR-28 foreshadowed). So a final lexer post-pass (mark_reverse_open, alongside mark_instance_of/join_names) retags an opening ] to a distinct RBracketOpen terminal. A ] opens iff it is in value-expected position (the previous token does not complete a value) and a .. follows at the same bracket depth before the group closes — so every list / filter / interval close and the empty list [] stay an ordinary RBracket. The grammar then admits RBracketOpen Sum ".." Endpoint IntervalEnd; no ]-closer state is shared, the build.rs no-conflict gate stays green, and the parser stays fully lalrpop-generated (tokenisation is not parsing).
    • Reverse-CLOSE [a..b[ — filter-free endpoint, pure grammar. Adding [ as a third IntervalEnd bracket clashes with the Postfix "[" Expr "]" filter, which wants to shift a trailing [ as a subscript. Resolve it with a filter-free high-endpoint nonterminal Endpoint (the Sum chain with the filter dropped from EpPostfix, base case reusing the shared Primary), used for every interval's high endpoint. With no Postfix "[" … item live there, a trailing [ can only be the close — LR(1)-clean. Mirrors the NbSum precedent (ADR-28). Cost: an interval's high endpoint cannot itself end in a [...] subscript ([a..xs[2]]) — a shape no TCK case uses; the low endpoint and ordinary filters are unaffected. Composes with reverse-OPEN: ]a..b[ ≡ (a..b).
    • Range properties — a member_access arm. A Value::Range reads .start/.end (the stored endpoint values, so an eventual unbounded endpoint surfaces as its null without special-casing) and .start included/.end included (= !start_open / !end_open). The two-word property names arrive pre-joined by the lexer (ADR-17). An unknown property is a value-null, mirroring temporal::get_property (a range has properties). No Value/AST change — Value::Range and the RangeLit AST already existed (ADR-27); this only wires the dot.
  • Tests: a structural reverse-bracket scan replaced the ingester's depth counter (_value_range_brackets_ok: pairs brackets by nesting without requiring types to match — FEEL intervals mix [/(/] — and resolves reverse roles positionally), and .field blanking now consumes joined multi-word member names (stopping at a keyword, like the lexer's join, so a.b and c keeps and c). Re-ingesting the three affected suites added 8 closed-loop cases: 0068 (1..10] = ]1..10] / [1..10) = [1..10[ (notation equivalence), 1156 range("]18..21]") = ]18..21] / range("[18..21[") = [18..21[ (the range(string) builtin also parses reverse brackets), and 0074's four .time offset properties. Suite 2720 → 2728. Unit tests reverse_open_bracket_intervals, reverse_close_bracket_intervals, range_properties cover the forms directly.
  • Consequence: reverse-bracket intervals are first-class in value and in position, and range properties are readable. 0074's range_* decisions are boxed contexts (4 contextEntry literals each) the literalExpression-only ingester does not read — same as 1130 — so the reverse-bracket property expressions (]1..10].start included) are covered by range_properties rather than ingested; lifting that is ingester-only work (a <context> extractor branch + structured expected-value parsing), no library change. Still deferred (the last two ADR-27 forms, both LR(1)-clean at the grammar — the block is semantic): unbounded omitted-endpoint ranges [1..] / [..10] (needs Option AST endpoints + eval treating omitted as ±∞, distinct from a null bound's "unknown") and the opaque comparison-test value (< 10) in value position (needs a new Value variant with reflexive, range-incompatible equality; ADR-28). not(tests) negation too. See ROADMAP.md.

ADR-30: not(tests) test negation on the RHS of in (DMN §10.3.2.6, rule 49)

  • Context: the last grammar-side in-RHS form deferred by ADR-27/ADR-28 — negating a positive unary-test list, x in not([1,2,3]) / x in not(<5) / x in not([1..10]). ADR-28 flagged it as "LR(1)-solvable but the block is semantic." The block was a token-role collision, not a real ambiguity: in the unary-test category not(…) is always test negation (x in not(t) ≡ not(x satisfies t), three-valued), NEVER the boolean not(…) built-in — but the bare-endpoint branch NbSum → … → NbPrimary reached the boolean "not" "(" Expr ")" production, so a not after in had two parses.
  • Decision: ship it as a dedicated test-mode production, resolving the fork by removing the rival from the bare branch.
    • NbPrimary drops the boolean not. The Nb* chain exists only as InRhs's bare-endpoint branch; removing "not" "(" Expr ")" from NbPrimary means the bare branch can never start with not. (A boolean not(…) is unaffected everywhere else — it lives in the full Primary, reachable through Sum.) Semantically this is exactly right: per spec a not(…) after in is test negation, not a boolean endpoint.
    • A dedicated InRhs → "not" "(" Comma<UnaryTestElem> ")" production. With the bare branch's not gone, this is the only production starting with not in the in-RHS state — one shift target, LR(1)-clean (the build.rs no-conflict gate proves it). Reusing UnaryTestElem means each inner element becomes a test via unary_test_from_expr exactly like a bare list, so not(5) is the negated = 5 test, not(<5) a negated comparison, not([1..10]) a negated interval — no special-casing.
    • AST: a new UnaryTest::Not(Vec<UnaryTest>). It carries the inner test list; no Expr change. eval_unary_test OR-folds the inner tests (the same disjunction as a bare list) and negates the result with a Kleene not3: not(true)=false, not(false)=true, not(null)=null, and a tainted unknown (error-null / wrong-typed) stays an error-null — mirroring and3/or3 provenance, so negating an unknown never manufactures a definite truth. (x in not((null..10]) ⇒ null, not true.)
  • Tests: unit test membership_not_test_negation covers list / bare / comparison / interval / mixed inner tests and the Kleene-null case directly. The ingester's _in_rhs_supported now admits not(…) after in (validated as a balanced paren group, like a bare bracket list). The DMN-TCK has no in not(…) case in any suite, so no fixture changed and no suite was re-ingested; the closed loop (fixtures_test) stays green and the form is exercised by the unit test.
  • Consequence: every in-RHS grammar form is now in. The two remaining deferrals are purely semantic-value work, not grammar: unbounded omitted-endpoint ranges [1..] / [..10] and the opaque comparison-test value (< 10) in value position (both ADR-29).

ADR-31: Unbounded omitted-endpoint ranges — [1..) / (..10] (DMN §10.3.4.6)

  • Context: the most invasive of the three range deferrals (ADR-27 → ADR-30). A range endpoint may be omitted, denoting an unbounded bound, ±∞: [1..) is everything ≥ 1, (..10] everything ≤ 10. This is semantically distinct from a present null endpoint: [null..10] keeps the three-valued "unknown" membership (5 in [null..10] ⇒ null, per DMN-TCK 0072), while (..10] is a definite bound (5 in (..10] ⇒ true). The two must never collapse to the same representation. Unlike the earlier range work this ripples through every layer — AST, value, eval, builtins, grammar, the host wrappers — because both endpoints become optional everywhere.
  • Decision: model an omitted endpoint as None, kept rigorously apart from Some(null), and require — everywhere, literal and range() — an open bracket on the omitted side (FEEL grammar rule 66, §10.3.2.7: an unbounded bound has its inclusivity flag false).
    • AST Interval.start/.end → Option<Box<Expr>>; value RangeVal.start/.end → Option<Value> (None = unbounded). RangeVal is still boxed behind Value::Range(Box<RangeVal>), so Value stays 40 bytes (the value_size_did_not_grow guard is untouched). A present null bound evaluates to Some(Value::Null); only a syntactically omitted endpoint is None.
    • An omitted endpoint requires an OPEN bracket on that side, and at most one may be omitted (rule 66). [1..), (..10], ]1..) are valid; [1..] / [..10] (a closed bracket with no value) and (..) (both omitted — no rule-66 alternative) are parse errors, exactly as range("[1..]") / range("(..)") are null (next-but-one bullet). Since only an open bracket is writable there, an unbounded side's openness flag is always "open" — and is in any case ignored by every semantic operation (±∞ is no member): equality compares the flag only where a side is bounded ([1..) ≠ [1..10], (..10] ≠ [null..10]); .start included/.end included of an unbounded side is false; .start/.end of it is null. The flag is stored as written only so string([1..)) echoes the bracket.
    • Eval. range_contains takes Option<&Value> per side — a None side is satisfied unconditionally (so 5 in [1..)/5 in (..10] are true), a Some(null) side still goes three-valued. instance of range<T> treats an unbounded side as vacuously conforming (the bounded side types the range, like a null/empty slot). The §10.3.4.6 Allen relations view each operand through a Bound { NegInf, Val, PosInf } (an omitted lower = NegInf, upper = PosInf); ±∞ compares below/above every value and two same-sign ±∞ are equal, so before((..5],[10..)), includes((..7],[3..7]), coincides((..5],]..5]) need no further special-casing.
    • Grammar (LR(1)-clean, build.rs gate). A HiEnd nonterminal carries the part after .. for a present-low range: Endpoint IntervalEnd (bounded, any close bracket) or the bare open ")" (unbounded high, rule 66 (c)). The closed opener "[" keeps its low endpoint mandatory (Sum). Each open opener "(" / ](RBracketOpen) splits in two: a present low (Sum) takes any HiEnd; an omitted low ("(" "..") takes an inline bounded high (Endpoint IntervalEnd, rule 66 (b)). That split is what forbids the both-omitted (..) — there is simply no production for it — while a closed bracket on an omitted side ([1..] / [..10]) never had one. The unbounded-high ")" carries no "]" (closed) and no reverse-close "[" ([ ∈ FIRST(Endpoint), so after .. a [ always shifts into a nested-endpoint parse — the rare [1..[ is spelt [1..)). Reused verbatim by RangeLit (value position) and the InRhs interval tests. (.. ∉ FIRST(Sum) keeps the present-vs-omitted-low choice one-token-clean.)
    • range() string builtin follows the SAME rule 66. Rule 66 alternatives: (a) both endpoints present, (b) open start ".." endpoint end, (c) start ".." endpoint open end. So range("[2..)") ≡ >=2 and range("(..2)") ≡ <2 are valid (spec §10.3.4.6 examples), while a closed bracket with no value, or both endpoints omitted, is null: range("[..2]") / range("[1..]") (DMN-TCK 1156 004_e/004_f, "closed … endpoint with no value is not valid"), range("[..]"), range("(..)"). Because range() parses its string through the same value-position grammar, these strings already fail at compile; the in-range_fn checks are defensive belt-and-suspenders.
  • One uniform rule, no exceptions. Literal and range() obey rule 66 identically — an omitted endpoint needs an open bracket, and at most one endpoint may be omitted. So every malformed range literal is a parse error and every malformed range() string is null, with no [1..]-parses-but-range("[1..]")-is-null surprise and no special-cased (..). (An earlier draft accepted the literal (..) as a universal-range convenience; it was dropped for this uniformity — the spec has no both-unbounded surface syntax anyway.) The spec's canonical unbounded value is in fact the comparison >= 1 / < 10 (mapped to a one-endpoint range, §10.3.2.7); the bracket spelling is rule-66 sugar that feel-core makes available in value/test position too.
  • Tests: unbounded_ranges covers membership (incl. the (..10] ≠ [null..10] distinction both ways), value-position equality, range properties, instance of, string(...) rendering, and the Allen relations over unbounded operands; unbounded_closed_bracket_is_a_parse_error pins the rule-66 rejection of [1..] / [..10]. range_builtin covers the open-bracket range("[2..)") ≡ >=2 plus the closed-bracket / both-omitted null cases (1156). The ingester's structural ..-scan still admits unbounded forms (the open-bracket requirement is the parser's job, and the DMN-TCK has no value-position unbounded literal — range("…") strings are blanked); 0072 / 1156 re-ingest produced no fixture change, and the closed loop (fixtures_test) stays green.
  • Consequence: every §10.3.4.6 range grammar form is now in. The only remaining range deferral is the opaque comparison-test value (< 10) in value position (ADR-28's measured semantics; needs a new Value variant), which is unrelated to endpoints — and which, once built, is the spec-canonical value form of an unbounded range.

ADR-32: opaque comparison-test value (< 10) in value position (DMN §10.3.4.6)

  • Context: the last range deferral after ADR-27 → ADR-31 — a parenthesised comparison test in value position, (< 10) / (= 10) / (!= 10). ADR-28 measured its semantics off 0068 and explicitly left it open (the range_006 question): a desugar to a one-endpoint Range was falsified — (< 10) = (null..10) and (= 10) = [10..10] are false, while (< 10) = (< 10), (= 10) = (= 10), (!= 10) = (!= 10) are true. So it equals an identical test reflexively but is never equal to a Range: an opaque unary-test value, not the unbounded range it superficially resembles. The in-position forms (x in (=10) / (!=10)) already worked as tests (ADR-28); only this value-position equality was open.
  • Decision: model it as a dedicated, opaque Value variant — not a Range.
    • Grammar — one new Primary alternative, LR(1)-clean. Primary → "(" CmpOp Sum ")". No CmpOp token is in FIRST(Expr), so seeing a CmpOp straight after ( is an unambiguous new path that never competes with the "(" Expr ")" grouping or the "(" Sum ".." … range form — build.rs's no-conflict gate passed on the first build. A new AST node Expr::UnaryTestVal(CmpOp, Box<Expr>) carries it (distinct from Expr::Compare, which has a left operand and yields a boolean).
    • Value — a boxed opaque variant. Value::UnaryTestVal(Box<UnaryTestVal>), payload { op: CmpOp, endpoint: Value }. Boxed so the variant stays one word and Value does not grow past 40 bytes (the value_size_did_not_grow test). Construction (eval.rs) evaluates and forceds the endpoint, exactly like a range endpoint.
    • Equality — structural, reflexive, range-incompatible. A new arm pair in feel_equal_depth: (UnaryTestVal, UnaryTestVal) is a definite false on a differing operator, else the three-valued equality of the endpoints (so (<10) = (<10) is true); (UnaryTestVal, _) / (_, UnaryTestVal) is a definite false — against a Range or anything else (null/error are settled earlier). This is the crux: a false, not the type-mismatch error-null the final _ arm would give, which is what 0068 demands.
    • No order, no host type, conforms to nothing but Any. It is not orderable (as_interval → None, so the Allen relations error-null on it), has no instance of type but Any (the structural types.rs arms only match concrete shapes), and the wrappers (feel-py / feel-lua) cross it out as host None/nil like a native closure. string((< 10)) renders the written form (< 10) (endpoint quoted as a list member is).
  • Tests: value_position_comparison_test (the true/false reflexive + range-incompatible pairs, the operator/endpoint structural cases, string(...), and a regression block proving the in-position test forms are unchanged). Re-ingested only 0068-feel-equality — the ingester's value-position paren-comparison reject now fires only for a bracket-led comparison ([< 10], which has no production) not directly after in; the paren form is admitted. 0068 101 → 109 (the eight range_006/range_007…012 cases, incl. the ADR-28-deferred range_006). Suite 2728 → 2736; closed loop (fixtures_test) green.
  • Consequence: every §10.3.4.6 range and comparison-test-value grammar form is now in — the ADR-27 → ADR-32 range arc is closed. The remaining in-RHS deferral (not(tests) negation) was itself resolved by ADR-30; nothing range-shaped remains open.
  • Correction (ADR-33): the consequence list above understated the value. ADR-32 said the comparison-test value has "no host type, conforms to nothing but Any" and left its member_access returning error-null. §10.3.2.7 contradicts that — it is "a typed instance of the range type" with range properties. ADR-33 supplies them without disturbing the opaque equality this ADR fixed.

ADR-33: range properties + instance of range<T> for the comparison-test value (DMN §10.3.2.7)

  • Context: ADR-32 modelled (< 10) / (= 10) / … as the opaque Value::UnaryTestVal, correctly making its equality reflexive-only ((=10) = [10..10] is false, off 0068). But it also declared the value typeless ("conforms to nothing but Any") and gave it no member access — member_access fell through to Value::Error → null. §10.3.2.7 ("Ranges", Table 42) says otherwise: the single-endpoint-with-operator form (grammar rule 7.a) is "a typed instance of the range type". It has the four range properties — the other endpoint is undefined (property null, inclusivity flag false) and the present endpoint's inclusivity follows the operator — and it is a range<T>. TCK 0074-feel-properties range_006–011 pin those property values exactly. So two TCK suites fix two independent facets of the same value: 0068 fixes equality (opaque — identical properties to [10..10] yet not equal to it), 0074 fixes properties (range-shaped).
  • Decision: keep ADR-32's opaque equality untouched and add the two range-typed projections, both derived from the boxed { op, endpoint }:
    • member_access — a Value::UnaryTestVal arm (eval.rs), mirroring the Value::Range arm. Per Table 42, by operator (start, start incl, end, end incl) is: < → (null, false, e, false); <= → (null, false, e, true); > → (e, false, null, false); >= → (e, true, null, false); = → (e, true, e, true); != → (e, false, e, false). An undefined endpoint's property is null (matching the unbounded-Range None rule, ADR-31); an unknown property is value-null (it has properties). The crux: (=10).start and (=10).end are 10/10 even though (=10) ≠ [10..10] — properties and equality are decoupled.
    • instance of range<T> — a Value::UnaryTestVal arm in value_conforms_to (types.rs). The single present endpoint must conform to T; the undefined side conforms vacuously, exactly like an unbounded Range endpoint. So (<10) instance of range<number> is true while (<10) = (..10) stays false (ADR-32) — conformance and equality are likewise independent. This corrects ADR-32's "conforms to nothing but Any", which was a §10.3.2.7 deviation.
  • Why no equality change: a value with start/end/inclusivity identical to [10..10] that is nonetheless ≠ [10..10] is exactly what 0068 + 0074 jointly demand; member_access is a read, not a promotion. feel_equal_depth's UnaryTestVal arms (ADR-32) are unchanged, as is the 40-byte Value size.
  • Why a distinct variant, not Range + an is_test flag. Once (< 10) projects to the same start/end/inclusivity as (..10) (and (= 10) to the same as [10..10]), the only observable difference is equality — so one could fold both into a single Range { start, end, start_open, end_open, is_test } whose = also compares is_test (the CmpOp is recoverable from the canonical range fields, so no operator need be stored). That was weighed and rejected:
    • Illegal states. A comparison test is grammar rule 7.a — one operator, one endpoint — so the compact { op, endpoint } makes a two-bounded "test" (Range { start: 5, end: 10, is_test: true }, which matches no FEEL expression) unrepresentable. The unified form admits it, plus redundant denormalised endpoint fields that can drift.
    • A cross-cutting flag. is_test would have to be honoured by equality, string() ((< 10) vs [10..10] rendering) and the Allen-relation exclusion (ADR-32: as_interval → None), but ignored by in-membership, member_access, instance of and range(). Honoured in ~3 ops, ignored in ~15 — and the silent default (forgetting the bit) is wrong for equality, right elsewhere. A distinct variant makes "no range identity / not orderable" a type fact, not a flag every present and future range op must remember.
    • It is idiomatically a newtype over range. §10.3.2.7 makes it range-typed for type and properties while 0068 proves it is not substitutable for a range under identity — "same projected shape, own identity" is the textbook newtype, i.e. a distinct value, not a runtime discriminator. The small projection-logic overlap (the Table-42 mapping) is shared by reuse, not by merging the types — a UnaryTestVal helper if it ever grows, never a unified Value variant. (Hard TCK data is only (<10) ≠ (null..10) and (=10) ≠ [10..10]; (<10) ≠ (..10) is our principled extension of 0068's "never equal to a Range", and a unified flag would have to carry exactly that case too.)
  • Tests: range_properties extended with the six-operator property table, the unknown-property null, and the instance of range<T> conformance (incl. a wrong-endpoint-type false). Re-ingested only 0074-feel-properties (the five range_006/007/009/010/011 boxed-context decisions left in OUT_OF_SCOPE_EXPR_SKIPS by ADR-29's proviso, now removed). 0074 48 → 53; suite 2872 → 2877; closed loop (fixtures_test) green.
  • Consequence: §10.3.2.7's "typed instance of the range type" is now honoured in full for the comparison-test value — both its range properties (0074) and its instance of range<T> conformance — while its equality stays opaque per 0068. range_008/range_012 (!= cases) remain commented out upstream (dmn-tck PR #671); the member_access/conformance arms already cover != for when they return.

Adding a wrapper — the host-binding contract

The four wrappers (feel-pg, feel-wasm, feel-py, planned feel-lua) implement the same seven seams against feel-core. Writing them down once turns "add a target" into "fill a template" rather than re-deriving the boundary (as feel-py did, landing RD-4/5/6). Each seam links the ADR that defines it and the concrete core entry point.

  1. Parse — feel_core::compile(expr) -> CompiledExpr. Parse once, evaluate many (feel-pg caches per call-site via pgrx fn_extra; the others expose compile).
  2. Evaluate — CompiledExpr::evaluate_with_env(&ctx, &EvalEnv): the single general entry the wrappers call (ADR-16/ADR-18; the regex-only evaluate_with was retired). Build the Context with Context::insert.
  3. Input mapping (lazy) — scalars and temporals convert eagerly; an object/dict/ table becomes Value::Foreign wrapping a host-specific ForeignObject (get = the FEEL dot, by name; force = materialise one level; as_any = recover the handle). Catch host errors inside get/force → value-null (ADR-21).
  4. Output mapping — Value → host value; a Value::Foreign that reaches the result is handed back by identity via as_any downcast (no re-traversal); temporal values map to native host types or ISO-8601 (ADR-18); error-null/value-null per the strict/lenient policy.
  5. Regex provider — implement FeelRegex over the host engine, or reuse the bundled RustRegex when the host has none (ADR-16; only matches/replace/split consult it).
  6. Clock — put a fixed jiff::Zoned instant in the EvalEnv so now()/today() are stable for the whole evaluation (ADR-18; e.g. feel-pg's transaction start).
  7. Strict vs lenient — after eval, value.contains_error() decides: raise/throw (strict) or into_lenient() → null (lenient default) (ADR-14).

Per-wrapper choices at a glance (the detail, with revisit triggers, is in RD-1…9):

Seam feel-pg feel-wasm feel-py feel-lua
Input mapping lazy JsonbForeign (RD-11) lazy JsForeign lazy PyForeign lazy LuaForeign (RD-9)
Regex dialect RustRegex (RD-1) JsRegex (ADR-16) PyRegex/re (RD-4) RustRegex (RD-7)
Temporal repr ISO→native cast (RD-2) JS Date / ISO (ADR-18) datetime/dateutil (RD-5) ISO-8601 string (RD-8)
Clock transaction start Date.now() system (jiff::now()) system (jiff::now())
Strict surface raise ERROR throw raise FeelError Lua error
Parse cache fn_extra (auto) compile() compile() compile()

(The matrix is a summary; RD-1…6 keep the full "weighed / decision / revisit trigger / if flipped" rationale a grid can't carry.)

Revisable design decisions

Softer than the ADRs above: deliberate, reversible choices that are not architectural commitments. Each records the trade-off, the decision taken now, the trigger that would flip it, and the work a flip implies — so revisiting is cheap and informed rather than a re-discovery. Expect these to change.

RD-1: feel-pg keeps the Rust regex dialect (no PgRegex provider yet)

  • Weighed: ADR-16 made the three regex builtins host-pluggable. The Postgres candidate would be a PgRegex provider routing matches/replace/split through Postgres' own POSIX ARE engine, so FEEL regex matches the native ~/regexp_* behaviour. Against that: (1) the bundle-size win that justified the WASM switch does not exist server-side — the regex stack inside a .so costs nothing that matters; (2) RustRegex keeps feel-pg on the same dialect as feel-core and the TCK fixtures (the validated reference), whereas POSIX ARE would be a third, untested dialect; (3) a PgRegex is real unsafe-FFI work — DirectFunctionCall into textregexreplace/regexp_split_to_array/ textregexeq, Datum/text marshalling, and crucially catching Postgres' regex ereport/longjmp so a bad pattern yields a FEEL null instead of aborting the whole query.
  • Decision (2026-06-16): feel-pg stays on the default RustRegex provider. The evaluate_with seam and a note in feel-pg/src/lib.rs keep the door open; nothing is built. Net effect: regex results in Postgres equal those in feel-core's test suite today.
  • Revisit trigger: a concrete requirement that FEEL regex inside Postgres behave exactly like the native ~/regexp_* functions — e.g. users authoring patterns they test against PG and expecting identical semantics. Until then, dialect-parity with the reference core is the more valuable property.
  • If flipped: implement struct PgRegex in feel-pg as a feel_core::FeelRegex, mapping the three methods onto Postgres regex via DirectFunctionCall (wrap each call so a regex error becomes None → FEEL null, never a longjmp unwinding through Rust); pass it via CompiledExpr::evaluate_with instead of the default evaluate; document POSIX ARE (and its flag/escape differences from XPath) as a per-target divergence under ADR-16; and decide validation — the TCK fixtures are XPath-leaning, so PG-dialect cases would need their own expectations.

RD-2: feel-pg returns temporal values as ISO strings, not native PG types

  • Weighed: ADR-18 maps temporal results to canonical ISO-8601 jsonb strings, so a caller casts (… ::date/::timestamptz/::interval) to get a native type. The alternative is typed-returning SQL functions (feel_eval_date, feel_eval_ts, feel_eval_interval) returning a native pgrx::Date/Timestamp/ Interval. Against that: (1) ISO + cast already yields every native type with no extra runtime code; (2) crucially, the cast's error path runs in Postgres SQL — it never ereport/longjmps through Rust frames (the RD-1 hazard); a typed-returning variant would be safe only with explicit Rust-side range/ precision guards (Postgres' date range, ns→µs truncation) before IntoDatum; (3) the result type of feel_eval is unknown until evaluation, so a single typed function cannot serve all expressions — it would be a family of functions the caller must pick between, which a cast does for free.
  • Decision (2026-06-16): feel-pg keeps feel_eval … RETURNS jsonb with temporal values as ISO-8601 strings; conversion to native types is the documented cast recipe. Nothing typed is built.
  • Revisit trigger: a concrete need to call feel_eval directly where a native date/timestamptz/interval is required without a cast (e.g. a generated column, or indexing the result) and the cast is too awkward.
  • If flipped: add feel_eval_date/_ts/_interval wrappers that evaluate as today, then range/precision-check the temporal Value in Rust and build the Datum via IntoDatum (never calling an ereport-ing C function), mapping an out-of-range value to SQL NULL rather than risking a longjmp.

RD-3: feel-wasm is offset-only by default (the IANA tzdb is opt-in)

  • Weighed: ADR-18 makes the embedded IANA tzdb a feature flag. The bundle is ~258 KB of data — over half the WASM module. Most FEEL expressions that use zones use a numeric offset (+02:00) or Z, which need no tzdb; only named-zone literals/lookups (@Europe/Paris) do. Against bundling by default: the size dominates a module that is otherwise ~479 KB. Against not bundling: named zones silently become null in the default build.
  • Decision (2026-06-16): feel-wasm defaults to offset-only (no tzdb; ~479 KB); named zones evaluate to null. Full named-zone support is one flag away — wasm-pack build … -- --features iana-tz (~723 KB). feel-pg and native builds keep the bundle (size is irrelevant there), so they are unaffected.
  • Revisit trigger: named zones become common enough in WASM use that null is a surprise — then flip feel-wasm's default to include iana-tz.
  • If flipped: add iana-tz to a default feature on feel-wasm (or document building with it), accepting the larger default bundle.

RD-4: feel-py uses the Python re regex dialect (xpath-regex to opt out)

  • Weighed: ADR-16 makes the three regex builtins host-pluggable. Unlike feel-pg (RD-1, which kept RustRegex for TCK-dialect parity) and like feel-wasm (JS dialect), Python ships its own re engine, and the FEEL/XPath flags i s m x q all carry over — i/s/m/x as inline (?…) flags, q via re.escape, and inline flags in the pattern pass straight through. So the host dialect is both available and idiomatic for Python authors. Against: re is a third dialect that diverges from feel-core/TCK in the corners (Python supports backreferences the Rust engine rejects; class subtraction/XSD block names differ).
  • Decision (2026-06-16): feel-py defaults to the Python re dialect via a PyRegex provider (it holds the GIL, since the builtins call back into Python). The xpath-regex build feature instead compiles feel-core's RustRegex, for results byte-identical to feel-core/TCK. XPath $N replacement references are translated to re's \g<N> form (xpath_replacement_to_python, the Python pendant of feel-core's xpath_replacement_to_rust). Edge: a capturing group in a split delimiter makes re.split emit the captures (XPath does not) → such a result is a FEEL null (documented divergence).
  • Revisit trigger: users expect FEEL regex in Python to match feel-core/TCK by default (e.g. patterns authored against the reference) rather than the re dialect.
  • If flipped: make xpath-regex the default feature (or document building with it); the seam (evaluate_with_env + the cfg provider switch) is already in place.

RD-5: feel-py temporal mapping (native types; years-months via relativedelta)

  • Weighed: ADR-18's boundary is canonical ISO-8601. Python has native datetime.date/datetime/time/timedelta, but no native years-months duration. Options for that one type: an ISO string (as feel-wasm leaves durations), dateutil.relativedelta (a real, arithmetic-capable type), or a bespoke class.
  • Decision (2026-06-16): map date→date, date and time→datetime, time→time, days-time-duration→timedelta, and years-months-duration→ dateutil.relativedelta — adding python-dateutil as a runtime dependency. Input is symmetric (a native temporal in the context maps back to the FEEL type; a relativedelta's years/months become a years-months duration, its other fields ignored — FEEL has no mixed duration). The conversion goes through the ISO bridge (to_iso/temporal_from_iso) except the two durations, which are built from components.
  • Revisit trigger: a desire for zero runtime dependencies (drop python-dateutil).
  • If flipped: return years-months durations as an ISO-8601 string or a small module-level class; drop the python-dateutil dependency.

RD-6: feel-py/feel-wasm context mapping is lazy (flipped 2026-06-17 → ADR-21)

  • Weighed: The original choice (2026-06-16) converted the whole host graph eagerly and rejected a lazy Value::Foreign, fearing it would duck-type the evaluator and land a foreign-value concept in all targets against ADR-1's spirit, and that lazy getattr would fire @property/descriptors (side effects / DB hits on ORM rows). On revisiting for ORM rows and large/live graphs, those concerns proved manageable: the foreign value is self-describing (no EvalEnv resolver needed, just a trait object that knows how to get/force itself), the force checks are a single inlined tag test (pure-Rust embedders pay nothing, Value does not grow), and the side-effect firing is now desired and bounded — only the attributes the expression names fire, which is exactly the on-demand load users want.
  • Decision (2026-06-17, flipped): convert lazily — wrap a host object/dict behind feel-core's ForeignObject seam, resolving each dot on demand via getattr/Reflect.get; scalars and temporals stay eager; a foreign result passes the original object back by identity. Full rationale and mechanics in ADR-21. The previous eager rule (instance __dict__, no property firing, an id()/depth cycle guard) is gone; bulk force still reads instance data only, so a blanket materialisation never sweeps properties.
  • Revisit trigger: a need to forbid side effects entirely at the boundary (a hard guarantee that no @property/getter ever runs during evaluation).
  • If flipped (back): reintroduce an eager shallow→deep snapshot as an opt-in (e.g. an eager=/force= parameter) while keeping the lazy default — the seam (ForeignObject + Value::forced) already supports forcing a whole subtree.

RD-7: feel-lua keeps the Rust regex dialect (no Lua-pattern provider)

  • Weighed: ADR-16 makes the three regex builtins host-pluggable. Unlike the browser (RegExp), Python (re) and Postgres (POSIX ARE), Lua has no regex engine — only Lua patterns, which lack alternation, full quantifiers and general grouping, so they cannot express FEEL/XPath regex. A faithful LuaRegex is therefore off the table; the realistic options are (a) keep the bundled RustRegex (parity with feel-core/TCK, like feel-pg RD-1) or (b) bind a C regex library (lrexlib/PCRE) — real FFI weight for a marginal gain.
  • Decision (2026-06-17, implemented): feel-lua keeps the default RustRegex provider — same dialect as feel-core and the TCK fixtures (the validated reference), and no native dependency. Because the feel-core dependency keeps its default features, no regex feature flag is needed here (simpler than feel-wasm/feel-py). The evaluate_with_env seam leaves the door open.
  • Revisit trigger: a concrete need for FEEL regex in Lua to match a host PCRE binding users already author against.
  • If flipped: implement struct LuaRegex over lrexlib/PCRE as a feel_core::FeelRegex, mapping its errors to None → FEEL null, and pass it via evaluate_with_env; document PCRE as a per-target divergence under ADR-16.

RD-8: feel-lua temporal mapping is ISO-8601 strings

  • Weighed: ADR-18's boundary is canonical ISO-8601. Lua has no native date/time type — only numbers, strings and tables (os.time/os.date work in epoch seconds or {year=, month=, …} tables). Options for the five FEEL temporal types: ISO-8601 strings (as feel-wasm leaves durations), os.date-style tables, or userdata from a Lua datetime library.
  • Decision (2026-06-17, implemented): map every temporal result to a canonical ISO-8601 string (via temporal::to_iso) — the portable boundary ADR-18 already produces, with zero extra dependency and no lossy conversion. On input there is no native Lua temporal type, so a date/time is just a string the FEEL date()/time()/duration() builtins parse. A convenience os.date-style table form ({year=, month=, day=, …}) on input is a possible later addition, not the default.
  • Revisit trigger: users want first-class Lua date objects (integration with a specific Lua datetime lib) rather than ISO strings.
  • If flipped: add a table/userdata mapping in the wrapper boundary (to_iso/ temporal_from_iso already bridge the value side); keep ISO as the fallback.

RD-9: feel-lua context mapping is lazy (LuaForeign)

  • Weighed: ADR-21 made host context mapping lazy via ForeignObject, so an ORM row or deep table resolves one dot at a time. A Lua table can carry an __index metamethod (a computed/lazy field) exactly like a Python @property, so the lazy seam fits; an eager alternative would snapshot and miss metamethod semantics.
  • Decision (2026-06-17, implemented): wrap an mlua::Table in a LuaForeign implementing ForeignObject: get via Table::get (which fires __index, the on-demand load), an Err → value-null; force materialises one level — a sequence (#t >= 1) becomes a Value::List of t[1..=#t], any other table a Value::Context of its string-keyed pairs; as_any recovers the handle for identity pass-through. Scalars and temporals (RD-8) stay eager. Mirrors feel-py's PyForeign and feel-wasm's JsForeign. Documented simplification: a Lua table is ambiguous (it is both array and map), so the sequence/map split is a heuristic — a mixed table's hash part is dropped when a sequence border exists, non-string map keys are dropped, and an empty table forces to an empty context (not an empty list).
  • Revisit trigger: a need to forbid metamethod side effects entirely during evaluation (a hard "no __index runs" guarantee).
  • If flipped: offer an opt-in eager snapshot (force the whole subtree at the boundary) while keeping lazy the default — the same escape hatch RD-6 describes.

RD-10: feel-pg volatility — STABLE feel_eval, plus an IMMUTABLE feel_eval_immutable

  • Weighed: feel_eval shipped as the pgrx default (VOLATILE, PARALLEL UNSAFE), which over-constrains the planner and bars the function from index expressions. But the evaluator is referentially transparent: no global mutable state, I/O or randomness (ADR-1), context output is BTreeMap-ordered, and the only ambient input is the instant behind now()/today() (ADR-18), which feel-pg pins to the transaction start. That makes feel_eval precisely STABLE (the same reason PostgreSQL's own transaction_timestamp() is STABLE) and PARALLEL SAFE (a parallel worker is a separate process with its own fn_extra cache). It cannot be IMMUTABLE — now() differs across transactions. The pull toward an immutable surface is concrete: expression indexes (and generated columns, constant folding) over a jsonb column require an IMMUTABLE callee. Three hazards to a "pure" subset: (1) now()/today(); (2) named IANA zones, whose offset is read from the updatable tzdb; (3) exp/log/sqrt and the regex builtins, stable only up to a libc / regex-crate version.
  • Decision (2026-06-17, implemented): keep one STABLE feel_eval and add a second, IMMUTABLE feel_eval_immutable, rather than overloading volatility on one function — a function has a single volatility class, and mislabelling one silently corrupts any index built on it. Both are PARALLEL SAFE and COST 500 — measured, not guessed: a parse-cached eval of a low-to-medium expression runs ~13.5 µs/call on pg18, ≈ 560× a baseline procost-1 C function (one cpu_operator_cost ≈ 24 ns on this box), so 500 is the by-the-book figure rounded down (the plpgsql=100 scale would put it ~1400; 500 is the conservative middle). The bulk is not FEEL evaluation but the pgrx JsonB boundary, which round-trips jsonb↔text↔serde_json twice per call (jsonb_out+parse in, serialize+jsonb_in out); a comparable jsonb plpgsql UDF using native binary jsonb is ~1.2 µs. feel_eval is also STRICT (pgrx default for non-Option args): an explicit SQL NULL context yields NULL, but the DEFAULT '{}' keeps the context-free feel_eval('1+1') working — an accepted edge. feel_eval_immutable enforces determinism in two layers, both in feel-core: a static clock check (CompiledExpr::is_clock_free, cached in fn_extra) that hard-ERRORs on now()/today(); and a runtime named-zone ban (EvalEnv::forbidding_named_zones) that turns a named zone into null (ERROR under strict => true). Fixed offsets and Z are kept — they are tzdb-independent and all an index needs. Math/regex are accepted as immutable: a libc/regex upgrade is rare and at worst wants a one-off REINDEX, the same pragmatic stance PostgreSQL takes for its own such functions. The named-zone ban is applied at the only sites that can mint one — the @"…" literal and the time()/date and time() string constructors — so a named zone can never exist to leak through a later comparison.
  • Revisit trigger: a need for named zones inside an index (then a tzdb-version-pinned variant, or a generated UTC-normalised column); evidence that COST 500 mis-orders plans (re-tune it, or make it expression-aware); or — most likely — optimising the jsonb boundary away (a binary-jsonb traversal / lazy JsonbForeign per ADR-21, replacing the pgrx JsonB text round-trip), which would cut the real per-call cost toward feel-wasm's ~2 µs and warrant a much lower COST.
  • If flipped (drop the immutable subset): delete feel_eval_immutable and the two feel-core seams (is_clock_free, forbidding_named_zones/vet_named_zone); callers needing an index would precompute the value into a stored column via a trigger.
  • Update (2026-06-17): the "optimising the jsonb boundary away" revisit trigger fired the same day — see RD-11. The pgrx JsonB text round-trip is gone, the per-call cost dropped from ~13.5 µs to ~2.3 µs, and COST was re-tuned 500 → 100 on both functions.

RD-11: feel-pg binary jsonb boundary — direct C API, lazy input (no serde)

  • Weighed: RD-10 measured feel_eval at ~13.5 µs/call and pinned the cost on the pgrx JsonB boundary, which round-trips jsonb↔text↔serde_json twice per call (jsonb_out + serde_json::from_str in; serde_json::to_string + jsonb_in out) — not FEEL evaluation (a native-binary jsonb PL/pgSQL UDF is ~1.2 µs) and not jsonb access. PostgreSQL exposes its binary jsonb container API (pushJsonbValue/JsonbValueToJsonb to build; JsonbIterator* / getKeyJsonValueFromContainer to read), all #[pg_guard] extern "C-unwind"-wrapped in pgrx. Three independent levers: C (binary output), B (eager binary input), A (lazy binary input via a JsonbForeign behind feel-core's ForeignObject seam, ADR-21 — the same lazy boundary feel-py/wasm/lua use). Gate: only proceed past C if it reliably reproduces the serde output across arrays/complex shapes.
  • Decision (2026-06-17, implemented): all three built; C is the gate and passed (a pg_test asserts binary output = expected jsonb across deep/mixed nesting, empty containers, the 2⁵³ integer/float boundary, unicode, every temporal type, and null/error). A benchmark (pg18, release, JIT + parallelism off, warm, N = 1M; baseline ~0.2 µs/row subtracted) decided the input strategy over two workloads:
    • decision expr if person.age >= 18 then "adult" else "minor", small nested ctx: serde-in + binary-out 3.6 µs, eager 2.6 µs, lazy 2.3 µs.
    • selective deep path k17.sub.value over a ~30-key nested ctx: serde 116 µs, eager 120 µs, lazy 7.9 µs. Lazy (A+C) wins both — marginally on the small case, ~15× on selective access into a large context (it walks only the navigated path) — and eager never wins (it materialises the whole context, even trailing serde on the big one). So lazy is the default and the only input path; eager (B) is not offered. Binary output alone took full feel_eval from 13.5 → 3.6 µs; lazy binary input brings it to ~2.3 µs, on par with feel-wasm (~2.0 µs). The serde_json dependency is dropped from feel-pg. COST re-tuned 500 → 100 (≈ PL/pgSQL's default; feel_eval is now roughly an ordinary function cost-wise).
    • Boundary newtype: PgJsonb(*mut pg_sys::Jsonb) replaces pgrx JsonB as the arg and return type; its FromDatum only detoasts (no jsonb_out), IntoDatum is JsonbPGetDatum, and the ArgAbi/BoxRet/SqlTranslatable impls mirror pgrx's own JsonB so it drops straight into #[pg_extern] as a SQL jsonb.
    • Safety — the "no ereport/longjmp through Rust frames" cost — is moderate and bounded. Every jsonb C function is #[pg_guard] extern "C-unwind", so a Postgres ereport/longjmp (e.g. a jsonb size-limit error from JsonbValueToJsonb) is caught at the FFI boundary and re-raised as a Rust panic that unwinds normally (destructors run, no stack corruption), surfacing as the original PG ERROR. No manual PgTryBuilder is needed for stack safety; a genuine encode error is left to propagate as a real ERROR rather than masked as null. The read path does not ereport for valid in-memory jsonb; AnyNumeric guards its own f64↔numeric conversions. One nuance the lazy output surfaced and fixed: a Foreign forced mid-encode yields a temporary sub-Value dropped before the final JsonbValueToJsonb, so value_to_jsonb copies every emitted string/key into an output arena (numerics are palloc'd, scalars inline) rather than borrowing.
    • Lazy lifetime invariant: a JsonbForeign holds a *mut JsonbContainer valid only for the call — created from the live argument, used during evaluate_with_env, forced to owned jsonb on output, dropped before return; it never escapes eval_to_jsonb. A Value carrying one is !Send (ADR-21), fine for the single-threaded per-call evaluation.
  • Revisit trigger: a workload that consistently consumes the entire context (where eager's single walk could beat lazy's per-key Foreign allocations) — reintroduce eager (B) as an opt-in then; evidence that COST 100 mis-orders plans; or a pgrx change to how the jsonb FFI is guarded.
  • If flipped (back to serde): restore the pgrx JsonB arg/return type and the serde context_from_json/value_to_json helpers, re-add the serde_json dependency, and bump COST back toward 500.

Roadmap: deferred scope (recorded, not yet built)

These were considered and deliberately deferred to keep the slice thin. Listed so the rationale and entry points survive. The next concrete increments (with entry points and the TCK coverage each unlocks) live in ROADMAP.md — notably first-class range values and the remaining in unary-test list forms.

  • Built-in functions — single-word slice done (ADR-15); non-temporal multi-word slice done (ADR-17): a Name "(" … ")" production in Postfix, a builtins dispatch table, the conversion/string/list/numeric functions (incl. regex-backed replace/split/matches), and the multi-word string/list/ context functions (string length, upper/lower case, distinct values, get value/get entries, …) reached via the lexer name-join. Still deferred: sort and the matching-function form of list replace (need function values); range relations and is; the temporal functions (await temporal types). Built-ins would also enable an explicit assert non null(x) tripwire — an in-expression complement to the strict boundary policy (ADR-14) for surfacing error-nulls where the author wants them loud.

  • Temporal types — done (ADR-18). The five temporal types, @"…" literals, arithmetic/comparison/component access, the temporal built-ins, and an injected clock landed; the boundary is canonical ISO-8601 (native PG casts; WASM Date objects). Reversed ADR-5's deferral and made the temporal-interval-mapping deviation live. Unary tests are now done for the bracket forms: the comparison forms (x in <10 / x in =@"…"), single intervals over any endpoints, bare equality (1 in 1, ADR-27), and the comma-list / paren-list / (=e) test forms (x in [1,2,3] / x in (1,<5,>=10), ADR-28) all landed (Expr::In carries Vec<UnaryTest>). Still deferred: not(tests) negation, the opaque comparison-test value (< 10) in value position (see ROADMAP.md), special-character/hyphen names (Date-Time, ADR-17 deviation); and temporal values outside jiff's representable range (ADR-18, TEMPORAL_RANGE_SKIPS).

  • inputNode context binding in ingestion — done (ADR-11/ADR-12). Each <testCase>'s <inputNode> values are captured into a per-fixture context, built into a Context in the fixture test and bound during evaluation. Unlocked 0016-some-every (path access over a list of contexts) and 0032-conditionals (cases 001–003, after the if-semantics decision in ADR-13). 0012-list-functions is now unlocked too (list built-ins landed in ADR-15).

  • List filter, index & projection — done (ADR-24). The postfix […] operator (1-based index with negative-from-end and out-of-range → null; Boolean filter list[item > 5] with item binding + context-entry spread) and .field projection over a list of contexts. Landed on the Postfix layer alongside path access; the flagged grammar conflict with list literals / interval in [a..b] was checked and is conflict-free (LR(1)). Unlocked DMN-TCK 0001-filter.

  • Boxed-context ingestion — done (ingester-only; no feel-core change). The ingester (tools/ingest_tck.py) now reads DMN boxed-context decisions (<decision><context><contextEntry>…</context>) in addition to literal-expression decisions. Each such decision is assembled into a FEEL context literal {k1: e1, k2: e2, …} (order preserved; multi-word keys are bare FEEL names the lexer joins); the expected value comes from the test-XML <component> tree (already parsed by parse_expected_node). Every entry expression is individually checked by fits_slice_grammar; if any entry is out-of-slice the whole decision is skipped. The fixture test's expected_value handles "context" type via json_to_value, mapping the JSON object to Value::Context(BTreeMap{…}) for structural equality. Unlocked: 0074-feel-properties range_001–005 (+5 fixture cases, 20 range-property assertions); 1130-feel-interval all 14 Allen-relation decisions (+14 fixture cases, 132 boolean assertions). Suite 2853 → 2872. Former caveat now closed (ADR-33): 0074 range_006–011 (the comparison-test values (<10) / (>=10) etc.) were excluded under the ADR-29 proviso because member_access for Value::UnaryTestVal was unimplemented; ADR-33 added the range-property and instance of range<T> arms and re-ingested them (+5, suite 2872 → 2877), so they are no longer in OUT_OF_SCOPE_EXPR_SKIPS. 0030/0031 (boxed context + user-defined functions) remain outside the slice via the free-name scan (ADR-23) and need no separate exclusion.

ADR-34: Java-style comments in the lexer (DMN §10.3.1.2)

  • Context: The FEEL spec (§10.3.1.2, "Additional syntax rules") states that "Java-style comments can be used, i.e., // to end of line and /* ... */". TCK 0073-feel-comments exercises all three shapes: inline block, EOL, and multi-line block with trailing EOL. Without comment support every / is lexed as division (Slash), so 1 + /* 1 + */ 1 fails to parse entirely.
  • Decision: skip both comment forms at the logos pass-1 level — before the multi-pass lexer post-processing (mark_instance_of, join_names, mark_reverse_open). Comments are dropped before those passes see the stream, so they require no changes.
    • EOL comment (// … \n): matched by #[regex(r"//[^\n]*", logos::skip, priority = 5, allow_greedy = true)]. allow_greedy is required because logos 0.16 rejects [^\n]* (equivalent to .*) without an explicit opt-in.
    • Block comment (/* … */): matched by #[regex(r"/\*([^*]|\*[^/])*\*/", logos::skip, priority = 5)]. Non-nested; the alternation ([^*]|\*[^/]) matches any char that is not *, or a * not followed by /, so **/ closes correctly and /***/ does not over-consume.
    • Both patterns live on a single Comment enum variant that logos::skip causes to be silently dropped — it never enters the token stream and the lalrpop grammar never references it. The Display impl's exhaustive match gets an unreachable!() arm.
    • Priority = 5 ensures // / /* win over the 1-char / (Slash) under maximal munch regardless of declaration order. Bare / (division) and -> are unaffected.
  • Ingester: fits_slice_grammar would have mistaken comment words for free identifiers and skipped the cases. A strip_comments(expr) helper (added to tools/ingest_tck.py) strips both comment forms — string-aware so "http://x" is preserved — and is called at the top of fits_slice_grammar. The raw expression is still written verbatim to the fixture; feel-core handles it.
  • Coverage: +3 fixture cases (0073 decisions 001–003, all → 2). Suite 2887 → 2890.

ADR-35: Typed formal parameters in function literals (DMN §10.3.2.13, rule 56)

  • Context: FEEL grammar rule 56 allows formal parameters to carry a type annotation: function(n: number, s: string) body. ADR-23 introduced function(…) literals with bare-name params only (rule 55 as if rule 56 didn't exist). TCK 0092-feel-lambda uses typed params throughout (e.g. function (a: number) 1 + a), so bare-name-only params are a parse failure for every 0092 case.
  • Decision: Extend the grammar with a FormalParam rule replacing the Comma<Name> in the two FnDef TextualExpr productions:
    • Grammar (feel.lalrpop): FormalParam: String = { <n:Name> => n, <n:Name> ":" InstanceType => n }. The type annotation is parsed via the existing InstanceType nonterminal and then discarded — only the parameter name flows into Expr::FnDef { params: Vec<String> }. Expr::FnDef and the evaluator are unchanged.
    • LR(1): After a Name, the one-token lookahead : shifts into the typed branch while ,/) reduce to the bare branch — mirrors the Arg rule's decision. build.rs LALRPOP no-conflict gate verifies.
    • Nb/Ep clones: function(...) literals do not appear in the bracket-free NbPostfix/EpPostfix chains; only TextualExpr needs the change.
    • Type enforcement: This slice binds arguments by name only; arity is already params.len(). A typed annotation like a: number is parsed and dropped; no runtime type check is performed. This matches the spec semantics for this slice (the type system is advisory at the expression level).
  • Tests: typed_formal_params_parse_and_eval and typed_params_closure_and_currying in lib.rs (positional, generic function type annotation, closure with typed param, three-level currying). Unlocks 0092 cases 001–014 and 016.
  • Consequence: ADR-23's "typed parameters out of scope" deferral is now resolved. function(a: number) 1 + a parses and evaluates correctly.

ADR-36: First-class built-in function values (DMN §10.3.2.13.1)

  • Context: The FEEL spec (§10.3.2.13.1) defines invocation on any expression (grammar rule 38: expression parameters). A built-in name used as a value expression — e.g. bkm(abs, sqrt) where the BKM stores the function and calls fn1(-5) * fn2(25) — must yield a callable function value rather than null. TCK 0092-feel-lambda cases 014 and 016 exercise this directly; case 017/018 also rely on it (deferred, needs sort/2).
  • Decision:
    • function.rs: Add Func::Builtin(String) variant alongside Closure and Foreign. The string is the spec name (identical to what builtins::call dispatches on, including multi-word joined names like "string length"). Clone and PartialEq (builtins equal by name) added naturally.
    • builtins.rs: Add pub(crate) fn is_builtin(name: &str) -> bool — a matches!-based membership predicate over the full built-in name set. Used by the evaluator to decide whether an unbound name is a built-in reference.
    • eval.rs Expr::Var: If ctx.get(name) is None and is_builtin(name), return Func::Builtin(name) as the value. A context binding still shadows a built-in (checked first), preserving ADR-23's precedence rule.
    • eval.rs invoke: New Func::Builtin(n) arm dispatches to builtins::call(n, args, env). Wrong-arity or type-error calls return Some(Error) from call, propagated as error-null; a missing name (impossible in practice) falls back to Value::Error.
    • types.rs: Func::Builtin conforms to Any only (same as Foreign — arity is not statically known in the type lattice for this slice).
  • Consequence: keyword_phrase_builtin_parses_in_call_position test updated: the multi-word name "date and time" out of call position now correctly returns a Function value rather than null (it was null only because the name was unbound; now it resolves to the built-in). Unlocks 0092 cases 014 and 016.
  • Tests: builtin_as_first_class_value and builtin_passed_as_argument_and_invoked in lib.rs.
  • Coverage: +16 fixture cases (0092 testCases 001–014 incl. 010_a, and 016). Suite 2880 → 2896.

ADR-37: Higher-order built-ins — sort + matching list replace (DMN §10.3.4.9 / §10.3.4.4)

  • Context: sort(list, precedes) and the matching-function form of list replace(list, match, newItem) have been deferred since ADR-15 (list functions) and ADR-24 (list filter), noted again in ADR-36 (sort/2). Both take a function-valued argument that must be invoked inside the evaluator — a capability builtins::call(name, args, env) has never had: it receives only &EvalEnv, not the Evaluator that owns invoke/invoke_closure and the call_depth recursion guard. Function values now exist (ADR-23) and are first-class (ADR-36), so this is a contained addition. Unlocks 0013-sort (3 cases), 0092-feel-lambda testCases 017/018, and 6 previously-skipped function-form cases in 1155-list-replace-function.
  • Decision:
    • function.rs: Add pub(crate) trait Applier { fn apply(&self, f: &Func, args: Args) -> Value; } — a narrow seam mirroring ForeignFunction/FunctionRegistry. Collapses a FeelError (unreachable inside the evaluator) to Value::Error.
    • eval.rs: impl Applier for Evaluator<'_> delegates to self.invoke(f, args).unwrap_or(Value::Error), reusing the existing closure path (lexical scope binding via bind_params, recursion guard via call_depth). Both call sites that pass self to builtins::call are updated to supply self as the applier.
    • builtins.rs: call signature gains applier: &dyn Applier. Two new functions:
      • sort_fn(args, applier) — [list, precedes]. Null list → null; non-list → error; non-function second arg → error. Closure arity guard rejects a non-2-param predicate before invoking. Stable insertion sort: move items[i] left while precedes(items[i], items[i-1]) returns Boolean(true), stop on Boolean(false), any other result → error for the whole call.
      • list_replace_fn(args, applier) — dispatches on whether args[1] is Value::Function: matching form (iterate, apply match(item, newItem), replace on true, error on non-boolean; closure arity-2 guard) or positional form (existing implementation, unchanged). Named match: overload routed in reorder_named by checking whether the named args contain the key "match" before the generic table lookup.
    • Registration: "sort" added to is_builtin, call dispatch (list section), and builtin_param_names("sort") ⇒ &["list", "precedes"]. builtin_param_names("list replace") entry documents that reorder_named handles the dual overload.
    • Wrapper crates: Fixed missing Func::Builtin(_) arms in feel-wasm, feel-py, feel-lua function-value marshal paths (gap left by ADR-36). All three treat a built-in ref like a native closure — cross out as null/nil/None (no host representation).
    • Ingester: "sort" added to _BUILTINS. fits_slice_grammar gains a function-literal extraction step before the free-name scan: \bfunction\s*\(bare_params\) patterns are found, param names collected into fn_params (added to allowed), and the head blanked from scan. Only untyped bare-identifier param lists match; a : annotation keeps the expression outside auto-ingest.
  • Tests: sort_ascending_descending, sort_by_context_field, sort_stable, sort_named_args, sort_as_first_class_builtin, sort_error_cases, sort_higher_order_closure_over_input, list_replace_matching_form, list_replace_matching_named_args, list_replace_matching_error_cases in lib.rs function_tests.
  • Consequence: Resolves the sort/list replace matching-form deferrals at ADR-15 (L331), ADR-24 (L779), the roadmap "Smaller deferrals" note, and ADR-36 (L1761). Suite 2896 → 2907.

ADR-38: Value-invocation of a literal callee (DMN §10.3.2.13.2)

  • Context: 1131-feel-function-invocation exercises the spec rule that invoking a non-function yields null (§10.3.2.13.2). All 8 decisions call a literal that is not a function — null(), "some_func"(), "abs"(-1), @"2023-11-11"(), 123(), true(), false(), and an unknown name non_existing_function(). The unknown-name case (001) already worked: FnCall dispatch returns Value::Error (→ null). Cases 002–008 did not parse: the grammar's only invocation form was Name "(" … ")" — a literal callee (null(, 123(, "abs"() was a syntax error. The suite was never ingested; null() sat in OUT_OF_SCOPE_EXPR_SKIPS with an ADR-23 note. The fix requires a separate AST node to keep named dispatch (FnCall) on its unchanged path — routing a Name through value-evaluation would break every builtin call because builtins are not scope-bound Value::Function values.
  • Decision:
    • ast.rs: New Expr::Invoke(Box<Expr>, CallArgs) variant. Semantics: evaluate the callee expression; invoke if it is a Value::Function, otherwise error-null (→ null at the lenient boundary). is_clock_free gets a matching arm that treats Invoke like FnCall without the now/today guard (a literal callee is never a clock read).
    • feel.lalrpop: New Invocable nonterminal for the six literal forms (Num, Str, TemporalLit, "true", "false", "null"). Name is deliberately absent. Two productions in Postfix: <e:Invocable> "(" ")" => Invoke(…) and <e:Invocable> "(" <a:Comma<Arg>> ")" => Invoke(…). NbPostfix and EpPostfix (interval-endpoint / in-RHS clones) are not extended — 1131 expressions are top-level. LALRPOP's no-conflict build gate validates LR(1)-cleanliness.
    • eval.rs: Expr::Invoke arm evaluates the callee with .forced(), dispatches to invoke for Value::Function, returns Value::Error for everything else. Reuses the existing eval_args / invoke helpers unchanged.
    • Ingester: OUT_OF_SCOPE_EXPR_SKIPS entry for 1131:002:decision002 removed. Case 001 (non_existing_function()) remains outside auto-ingest: fits_slice_grammar cannot distinguish a deliberately unknown name from a missing input name. It is hand-written into the fixture (same practice as 0092-feel-lambda cases 017/018, ADR-37).
  • Tests: invoke_non_function_yields_null in lib.rs::function_tests asserts all eight 1131 shapes → null, plus a regression check that abs(-1) / abs(n: -2) still route through FnCall. All 8 cases covered by tck_fixtures_pass via the ingested fixture.
  • Consequence: Resolves the "General invocation → non-function" item in the ROADMAP "Smaller, independent deferrals" section. Invoking an arbitrary expression that holds a function (var(args), lib.fn(args)) remains deferred (would require widening Invocable to Postfix, reintroducing the Name-vs-Var ambiguity). Suite 2907 → 2915.

ADR-39: Target-type coercion — §10.3.2.9.4 implicit conversions (0082)

  • Context: 0082-feel-coercion tests the DMN rule that a decision's result is coerced against its declared output type (typeRef on <variable> or <literalExpression>). Four conversions apply, in order: (1) null/error → null; (2) from-singleton-list — unwrap [e] to e by ONE level if e conforms to the target (NOT recursive: [[10]] → number → null); (3) to-singleton-list — wrap v into [v] iff v conforms to the list element type; (4) conforms-to — pass v through if it structurally conforms, else null. The suite was previously listed as out-of-scope ("DRG semantics"), but the coercion rules are FEEL-level concerns that feel-core can implement directly — only the five decisionService_* cases require the DRG layer.

  • Decision:

    • types.rs: New pub(crate) fn coerce(v: Value, t: &FeelType) -> Value implementing the four rules beside the existing value_conforms_to. The from-singleton-list rule (Rule 2) performs exactly ONE level of unwrapping: if items.len() == 1 { value_conforms_to(&items[0], t) ? items[0] : Null } — NOT coerce(items[0], t), which would incorrectly recurse.

    • Typed formal parameters (completing the ADR-35 follow-up):

      • ast.rs: Expr::FnDef.params: Vec<(String, Option<FeelType>)> (was Vec<String> — the type annotation was previously parsed then discarded).
      • function.rs: Closure.params updated to match.
      • feel.lalrpop: FormalParam rule now returns (String, Option<FeelType>); pub Type: FeelType = InstanceType; added as a new public entry point so parse_type() can deserialise "coerce_to" strings from the fixture.
      • eval.rs / bind_params: for each non-null actual arg with a declared param type, coerce(arg, &ty) is called; if it yields Null (non-conforming argument), bind_params returns Err(()) and the whole call is error-null. A null actual arg has type Null <: T per the nested-null rule and is bound as-is.
    • lib.rs: Exports pub use ast::FeelType, pub fn parse_type(s) -> Option<FeelType> (via feel::TypeParser), and pub fn coerce(v, t) -> Value.

    • Fixture harness (fixtures_test.rs): optional "coerce_to" field — a structural FEEL type string — triggers coerce(result, parse_type(coerce_to)) after evaluation and before comparison.

    • Ingester (ingest_tck.py) — four new capabilities:

      1. parse_item_definitions resolves <itemDefinition> trees into structural FEEL type strings (isCollection → list<…>, itemComponent → context<…>, bare typeRef → primitive); _resolve_typeref_to_feel / parse_decision_typerefs map decision variables to their resolved type for coerce_to emission.
      2. parse_bkms + parse_knowledge_requirements + _inline_bkms: BKMs are inlined as FEEL function literals in a synthetic context wrapper {bkm: function(p: T, …) body, __result: call_expr}.__result. The BKM's return typeRef (when present) becomes coerce_to for the case.
      3. parse_invocation_decisions converts <invocation> form decisions into named-argument FEEL calls; the <invocation typeRef> becomes coerce_to with the BKM return type as fallback.
      4. parse_context_result_decisions handles boxed-context decisions with a trailing unnamed result cell → {named_entries…, __result: result_expr}.__result.
      5. _fn_literal_params_and_blank replaces the old _fn_literal_pat regex: it now handles typed formal parameters (function(arg: number), function(ctx: context<name: string, age: number>)) by finding the balanced closing ) and splitting the param list on top-level commas (not those nested inside < >). Critically, this helper runs BEFORE the context-key blanker — arg: in function(arg: number) looks like a context key to the regex and would be destroyed before the param name could be recorded as bound.
  • Scope cut: the five decisionService_* cases require DRG service encapsulation and remain skipped (type="decisionService" structural skip + two ds_invoke_* decisions naturally rejected by fits_slice_grammar because the DS name is a free identifier). No OUT_OF_SCOPE_EXPR_SKIPS entries needed — the existing machinery handles it.

  • Tests: 31 cases in 0082-feel-coercion.json; exercised by tck_fixtures_pass as part of the 92-fixture suite. Unit tests typed_formal_params_parse_and_eval and typed_params_closure_and_currying in lib.rs::function_tests. Suite 2915 → 2946.

ADR-40: Leading-dot & exponent number literals (§10.3.2.3.1 / grammar rule 35) + 0100/0101/0102-feel-constants

  • Context: FEEL grammar rule 35 allows a numeric literal to begin with a dot (".872") and to carry an optional exponent ("1.2e3"). The compliance-level-2 suite 0101-feel-constants tests exactly these forms (.872, -.872). The ingester's fits_slice_grammar predicate already admitted all three feel-constants suites (no free names), but the engine couldn't evaluate .872 because the logos lexer regex only covered digit-led mantissas without exponents.

  • Decision: Widen the Num token regex in lexer.rs to match FEEL rule 35 in full:

    ([0-9]+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?
    

    The leading-dot branch (\.[0-9]+) requires at least one digit after the dot, so it never overlaps with .. (DotDot, two chars) or a lone . (Dot, one char); logos's maximal-munch resolves every case without a priority annotation. Negatives stay as unary minus over the literal (consistent with 0099-arithmetic-negation). No grammar/AST/eval changes were needed — f64::from_str already handles these forms. No ingester change was needed — the grammar-slice predicate already accepted them (ADR-7 in reverse: the engine widened to catch up to what the predicate admitted).

  • Fixtures ingested:

    • 0100-feel-constants (compliance-level-2) — 2 cases: true, false [boolean, exact]. Suite 2946 → 2948.
    • 0101-feel-constants (compliance-level-2) — 6 cases: .872, -.872, 50, -50, 125.4321987654, -125.4321987654 [number, f64_epsilon, epsilon=1e-8]. Suite 2948 → 2954.
    • 0102-feel-constants (compliance-level-2) — 4 cases: "foo bar", "šomeÚnicodeŠtriňg", "横綱", a long ASCII string [string, exact]. Suite 2954 → 2958.
  • Unit tests (number_literals_rule35 in lib.rs): direct coverage of .872, -.872, 1.2e3, 1E-3, .5e2 so the regex widening has non-fixture verification. Suite 2946 → 2958.

ADR-41: 0008-LX-arithmetic — structured-input + path access (compliance-level-2)

  • Context: The compliance-level-2 suite 0008-LX-arithmetic exercises a single literal-expression decision payment (standard amortized-loan monthly-payment formula) over a structured tLoan input (principal, rate, termMonths : number). The expression (loan.principal*loan.rate/12)/(1-(1+loan.rate/12)**-loan.termMonths) combines all five arithmetic operators, unary minus tighter than ** (ADR-8), and path access into a context value. Three test cases vary the loan parameters and expect floating-point decimal results.

  • Decision: Ingest the suite as-is — no engine or ingester changes were required. The ingester already converts <inputNode><component> children to a nested dict (see parse_input_value in tools/ingest_tck.py); the test harness binds a nested JSON object as Value::Context (via json_to_value in fixtures_test.rs); path access on a context value already resolves correctly; and fits_slice_grammar accepts the expression because loan is a captured input name and .field members are blanked. Numeric results use f64_epsilon comparison (epsilon=1e-8) via the decimal-vs-f64 deviation (ADR-2 / ADR-6).

  • Consequence: The suite confirms structured-input binding and path-access conformance in the fixture-driven test for the first time. The f64 error for the loan values (~1e-11 absolute) is well within the 1e-8 epsilon, so no epsilon widening was needed.

  • Fixtures ingested: 0008-LX-arithmetic (compliance-level-2) — 3 cases, f64_epsilon. Suite 2958 → 2961.

ADR-42: 0009-invocation-arithmetic — BKM invocation + arithmetic (compliance-level-2)

  • Context: The compliance-level-2 suite 0009-invocation-arithmetic exercises a BKM-backed literal-expression decision MonthlyPayment whose FEEL expression is PMT(Loan.amount, Loan.rate, Loan.term)+fee. The BKM PMT is a user-defined function(p: number, r: number, n: number) with body (p*r/12)/(1-(1+r/12)**-n). Inputs are a structured Loan : tLoan {amount, rate, term : number} and scalar fee : number. Three test cases vary the loan parameters; fee is fixed at 100. Expected decimal results (2878.69…, 662.70…, 2961.03…) are exactly the ADR-41 PMT values plus fee.

  • Decision: Ingest the suite as-is — no engine or ingester changes were required. The ingester's _inline_bkms path rewrites the BKM-backed decision into a self-contained {PMT: function(...) ..., __result: PMT(Loan.amount, ...)+fee}.__result expression (the same __result wrapper introduced for 0082-feel-coercion). Invocation with positional args, typed-parameter binding (§10.3.2.13.2), implicit coercion (§10.3.2.9.4), arithmetic including left-associative ** and unary minus tighter than ** (ADR-8), and structured-input path access (ADR-41) are all fully operational. Numeric results use f64_epsilon (epsilon=1e-8) via the decimal-vs-f64 deviation (ADR-2 / ADR-6).

  • Consequence: First compliance-level-2 suite that combines BKM inlining with positional invocation and arithmetic — the canonical §10.6.5 "Calculation" pattern from the spec. The f64 error for the loan values (~1e-11 absolute) is well within the 1e-8 epsilon, so no epsilon widening was needed.

  • Fixtures ingested: 0009-invocation-arithmetic (compliance-level-2) — 3 cases, f64_epsilon. Suite 2961 → 2964.

ADR-43: 0106-feel-ternary-logic & 0107-feel-ternary-logic-not — three-valued and/or/not (compliance-level-2)

  • Context: The compliance-level-2 suites 0106-feel-ternary-logic and 0107-feel-ternary-logic-not test FEEL's Kleene (three-valued) logic as defined in spec §10.3.2.4 and Tables 51 and 74. Suite 0106 has two decisions (DecisionAnd = A and B, DecisionOr = A or B) and covers the full true/false/null × true/false/null input matrix (9 test cases × 2 decisions = 18 fixture cases). Suite 0107 has one decision (DecisionNot = not(A)) with three test cases (true→false, false→true, null→null). All inputs are boolean or null; no non-boolean operands appear. The predecessor suites 0064/0065/0066 (ingested earlier) cover conjunction/disjunction/negation with literal operands (including non-boolean error cases); 0106/0107 add context-bound inputs that mirror the full ternary truth tables from the spec.

  • Decision: Ingest both suites as-is — no engine or ingester changes were required. The three-valued logic combinators and3/or3 (eval.rs, lines 749–807) and Expr::Not evaluation (lines 186–200) already implement Table 51 (conjunction/disjunction with null) and Table 74 (not(null)=null) exactly. The ingester's context-binding path maps xsi:nil="true" input nodes to null and produces exact-comparison cases. All expressions (A and B, A or B, not(A)) are core-slice keywords and pass fits_slice_grammar without skips. Unit tests logic_three_valued() (lib.rs, line 1005) had already verified the same matrix; 0106/0107 provide the official TCK provenance.

  • Consequence: The full ternary truth table (Table 51) and negation (Table 74) are now covered by TCK-sourced fixtures in addition to the earlier unit tests and 0064–0066 literal suites. Both suites use comparison: "exact" (no floating-point deviation needed). The 0106/0107 context-bound inputs complement 0064/0065/0066's literal-operand style.

  • Fixtures ingested: 0106-feel-ternary-logic (compliance-level-2) — 18 cases, exact; 0107-feel-ternary-logic-not (compliance-level-2) — 3 cases, exact. Suite 2964 → 2985.

ADR-44: 1150–1154 & 1161 — boxed-expression element forms (compliance-level-3)

  • Context: The compliance-level-3 suites 1150-boxed-conditional, 1151-boxed-filter, 1152-boxed-for, 1153-boxed-some, 1154-boxed-every, and 1161-boxed-list-expression exercise the DMN 1.5 boxed-expression element forms (spec §10.2.1.5 / §10.2.1.8–10): structured XML elements (<conditional>, <filter>, <for>, <some>, <every>, <list>) rather than the <literalExpression> FEEL text that all earlier suites use. Each element form maps directly to an existing FEEL construct: <conditional> → if/then/else, <filter> → L[predicate], <for iteratorVariable> → for v in L return …, <some/every iteratorVariable> → some/every v in L satisfies …, <list> → [e1, e2, …]. The six suites contribute 21 active test cases (commented-out decisions, pending PR #602 RTF, are invisible to ElementTree and excluded naturally). The 1150–1154 suites are contributed by "StrayAlien"; 1161 is a KIE/jbpm-authored model with three <inputData> nodes (A: number, B: boolean, C: string) and a typeRef=stringList list literal.

  • Decision: Ingester-only change — the engine needed no modification. Four new parser functions were added to tools/ingest_tck.py (each follows the direct-children _first_child pattern of the existing parse_invocation_decisions / parse_context_result_decisions):

    • parse_conditional_decisions → translates <conditional><if><then><else> to if (IF) then (THEN) else (ELSE).
    • parse_filter_decisions → translates <filter><in><match> to (IN)[MATCH] (the predicate references item, already an allowed implicit name).
    • parse_iterator_decisions → handles all three iterator tags in one function; translates <for iteratorVariable="v"><in><return> to for v in (IN) return (BODY) and <some/every iteratorVariable="v"><in><satisfies> to some/every v in (IN) satisfies (BODY).
    • parse_list_decisions → translates <list> of direct <literalExpression> children to [row1, row2, …].

    Each assembled expression is validated once through fits_slice_grammar. The four new dispatch branches (forms 5–8) follow the invocation_decisions branch in extract_cases, before the final else: continue.

    Three documented deviations (new skip set BOXED_PREDICATE_DEVIATION_SKIPS):

    • 1151-boxed-filter:004:decision004 — ([1,2,3,4,5])["not a boolean"]. TCK expects null; feel-core returns []. ADR-24 deliberately drops non-true filter predicate results (eval_filter, eval.rs, lines 900–906) rather than escalating a non-boolean predicate to error-null.
    • 1151-boxed-filter:005:decision005 — ([1,2,3,4,5])[if (item<=3) then true else "not a boolean"]. TCK expects null; feel-core returns [1,2,3]. Same ADR-24 rule.
    • 1153-boxed-some:006:decision006 — some element in ([1,2]) satisfies (if (element=2) then true else "not a boolean"). TCK expects null; feel-core returns true because some short-circuits on the first true (quant_product, eval.rs, line 953), per the sticky-provenance / strong-Kleene design of ADR-13/ADR-14 (true dominates before the later non-boolean taint is seen). Notably 1154-boxed-every:006 (passes) because for every the false-dominating value is never hit, the taint survives exhaustion, and the result is error-null → null.

    Reversing these deviations would require changing ADR-24 and ADR-13/14, risking regressions in 0001-filter and the 0106/0107 ternary-logic fixtures. The house style is to document divergences in a skip set rather than chase them.

    Also fixed: a latent bug in parse_value_elem where the text-heuristic boolean check (text in ("true", "false")) fired before the explicit-string-type check, causing <value xsi:type="xsd:string">true</value> to be mis-parsed as the boolean true rather than the string "true". Fixed by promoting the xsi_type.endswith("string") guard to run first (before the boolean check), consistent with the existing code comment "a declared string type is authoritative". The fix was surfaced by 1161's string(B) cell whose expected TCK value is "true" (string). All 2985 pre-existing fixture cases still pass, confirming no prior fixture was affected.

  • Consequence: The four boxed-expression element forms are now ingested and covered by TCK-sourced fixtures. The engine needed zero changes — if/then/else, list[predicate], for/some/every, and list literals were all already implemented. All 18 kept cases use comparison: "exact".

  • Fixtures ingested: 1150-boxed-conditional (compliance-level-3) — 3 cases, exact; 1151-boxed-filter (compliance-level-3) — 2 cases, exact (2 deviation-skips); 1152-boxed-for (compliance-level-3) — 2 cases, exact; 1153-boxed-some (compliance-level-3) — 4 cases, exact (1 deviation-skip); 1154-boxed-every (compliance-level-3) — 5 cases, exact; 1161-boxed-list-expression (compliance-level-3) — 2 cases, exact. Suite 2985 → 3003.

ADR-45: 0005, 0016, 0032, 0034, 0070 — deferred quick-win suites ingested (compliance-level-3)

  • Context: Five suites that were always within the engine's FEEL slice but had never been committed as fixtures. All five had been confirmed ingestible (the ingester produced cases when run manually) but were not yet part of the fixture set because they were investigated after earlier coverage pushes and left for a follow-up round. In the same pass, 0003-iteration was found to produce a single list-of-numbers case that fails exact comparison due to the decimal128 vs f64 gap — the decimal-vs-f64 deviation rule only covers scalar numbers, not list elements.

  • Decision:

    • 0005-literal-invocation (3 cases, f64_epsilon): boxed-context+result-cell decision inlining a BKM PMT as a function literal. The decimal-vs-f64 deviation fires (scalar numeric result).
    • 0016-some-every (2 cases, exact): some/every over a list of contexts (priceTable2) with path access i.price. 5 decisions skipped: priceTable1 references are outside the slice (DRG-scope name); gtTen and even are user-defined functions not in the built-in table; values in a list is a multi-word name requiring the name-join lexer (ADR-17) but appears inside the quantifier source, where fits_slice_grammar does not recognize it as a bound name.
    • 0032-conditionals (6 cases, 3 exact + 3 f64_epsilon): if/then/else with context-bound date and number inputs. decimal-vs-f64 fires for the numeric branch cases.
    • 0034-drg-scopes (2 cases, exact): leaf decisions (decision A 1, decision B 1) that use only <context> with literal-expression entries; the 10 decisions that reference other decision names as FEEL identifiers are silently skipped (DRG-scope propagation is out of scope for a FEEL-expression engine).
    • 0070-feel-instance-of (129 cases, exact): the full instance of truth table across all primitive FEEL types (Any, number, boolean, string, date, time, date and time, years and months duration, days and time duration, function, list, context) plus structural context types (context<k: T, …>) and nested contexts. 13 decisions skipped: they reference user-defined typeRef aliases (t255, tFooBar, tNumberList, tAnyList, t_context_013) that the ingester cannot resolve to inline structural types.
    • 0003-iteration (0 cases — no fixture file): the sole case for i in Loans return PMT2(i) produces a list of decimal128-computed numbers. The f64_epsilon comparison mode applies only to scalar expected_type: "number" results; list elements cannot be compared element-wise with epsilon tolerance under the current harness design. Documented in the new DECIMAL_LIST_SKIPS frozenset; no fixture file is produced until the harness gains a list-numeric epsilon mode.
  • Consequence: The five new fixture files add 142 cases, all exact or f64_epsilon. The DECIMAL_LIST_SKIPS mechanism is now in place for future list-of-numbers cases.

  • Fixtures ingested: 0005-literal-invocation (compliance-level-3) — 3 cases, f64_epsilon; 0016-some-every (compliance-level-3) — 2 cases, exact; 0032-conditionals (compliance-level-3) — 6 cases, mixed; 0034-drg-scopes (compliance-level-3) — 2 cases, exact; 0070-feel-instance-of (compliance-level-3) — 129 cases, exact. Suite 3003 → 3145.

ADR-46: Descendant expression e ... name + ForeignObject::identity (DMN §10.3.2.7, rule 68)

  • Context: Grammar rule 68 (descendant expression = expression, "...", name) was the one spec feature surfaced by reading the grammar rather than the TCK — no DMN-TCK case (level 2 or 3) exercises it, so it was documented as coverage gap #14. Semantics (§10.3.2.7, Table 68): where e is a context, e ... name returns a list of every value bound to name in e and all nested contexts, collected pre-order ({a:{b:{b:1}}} ... b → [{b:1}, 1]). The . operator already maps over a list of contexts; descendant recurses depth-first through the whole structure.

    The design crux: descendant is the engine's first unbounded collection traversal. ADR-21's laziness-terminates guarantee (a written .-path is finite, so cyclic host graphs are harmless — lib.rs test unbounded_graph_terminates_along_a_finite_path) does not apply: descendant recurses through the whole reachable graph, so a cyclic host graph behind Value::Foreign would loop forever.

  • Decision: Five-part change.

    1. Lexer — a new ... token (DotDotDot). logos longest-match keeps it disjoint from ./..; no LR interaction.

    2. Grammar — one Postfix production <e:Postfix> "..." <n:Name> → Expr::Descendant, same precedence as the . path operator. ... is a unique lookahead after a completed Postfix, so it is LR(1)-clean (the build.rs no-conflict gate is green).

    3. AST/eval — Expr::Descendant(Box<Expr>, String); the evaluator's descendant_collect walks pre-order over Context/List (collect the match, then recurse into every child) and Foreign (force one level, recurse). A null/error target propagates; a non-navigable scalar is null (mirrors .); otherwise the result is a list (possibly empty). A DESCENDANT_MAX_DEPTH = 1024 cap is a secondary backstop.

    4. Cycle guard / DAG de-dup — a HashSet<usize> visited-set keyed on a new ForeignObject::identity() -> usize trait method (default = the Rust allocation address). Only an Arc-backed Value::Foreign can form a cycle (pure-Rust values are owned trees), and only Foreign nodes are keyed in the set, so the guard is a no-op (empty set) for a pure-Rust embedder. The set stores plain integers — it owns nothing, cannot extend any object's lifetime, and is dropped at scope exit (RAII; the workspace uses panic = unwind, so also on panic): no leak.

      The set is global (threaded through the whole traversal, never cleared), so it does double duty: it breaks cycles and de-duplicates shared acyclic host sub-objects (a diamond/DAG reachable via two paths is collected once, not once per path). Pure-FEEL contexts are owned value trees and never Foreign, so they are never keyed — the spec domain keeps exact multiset semantics; only host-object sharing (out of DMN spec) is de-duped. The alternative, a path-scoped set (insert on entry, remove on exit), would match per-path multiset semantics and still terminate on cycles, but it risks exponential blowup on diamond-heavy DAGs (a subgraph reachable via 2ᵏ paths is traversed 2ᵏ times) — a real hazard for feel-py's ORM/object-graph target. The global set is therefore the deliberate choice: trade per-path multiset semantics for shared host data in exchange for cycle-safety and DAG-blow-up protection.

    5. Per-host identity overrides — the default allocation address is sound only when one Arc maps to one host object. Every host wrapper mints a fresh Arc per wrap (shallow_convert* → Arc::new re-run on every force/get), so two wrappers around the same host object have distinct allocations. The correct identity is host-specific:

      • feel-py — self.obj.as_ptr() (= Python id(), stable across Py::clone, no GIL).
      • feel-lua — self.table.to_pointer() (mlua's Lua table pointer; stable across Table::clone).
      • feel-wasm — a process-wide WeakMap<object, number> (js_identity): JS exposes no cheap object address and a JsValue handle index is not object identity across different reads, so a WeakMap assigns each distinct object a stable integer. Its keys are weakly held → reclaimed by GC, so it neither pins objects nor grows unboundedly.
      • feel-pg — exempt: jsonb is a serialized value tree, so a JsonbForeign sub-graph is definitionally acyclic; no override, no cycle test.

      This keeps feel-core's guard a plain HashSet<usize> (target-agnostic) while pushing "what is the same object" into each host — symmetric with the existing ForeignObject::as_any output-identity seam (ADR-21).

  • Consequence: The last spec grammar rule (68) is implemented; the engine's FEEL slice is now rule-1–68 complete (modulo the DRG-only out-of-scope forms). No TCK case exists, so the fixture suite is unchanged (still 3145 cases / 110 files). Tests added: feel-core (foreign_tests, incl. two cyclic-Foreign shapes — a fresh-Arc-per-access Cycle keyed on id and a single-shared-Arc SharedCycle keyed on the allocation address), feel-py (cyclic dict + cyclic class instance), feel-lua (cyclic table), feel-wasm (cyclic object), feel-pg (jsonb tree — terminates by construction). All non-pg suites pass; feel-pg is exercised via cargo pgx test (the pgrx harness, not runnable without a managed Postgres).