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-coredepends only on portable crates (today:lalrpop/lalrpop-util,logos,unicode-ident,jiff, and the optionalregex); 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.
- I1 — Dependency purity (inviolable).
- 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 plannedfeel-lua). - Consequence: The core is reusable and testable on the host toolchain. I1 is
enforced mechanically with
cargo tree -p feel-core(must show nopgrx/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::Numberasf64. Do not pull inrust_decimalorbigdecimalyet. 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 artifactcrates/feel-core/src/feel.lalrpopand is generated at build time bycrates/feel-core/build.rs. No hand-written parser. - Consequence: Grammar changes are localized to one
.lalrpopfile. There is a build-time dependency onlalrpop(a build-dependency only — it does not violate ADR-1). Generated code is included vialalrpop_mod!. - Addendum (logos lexer): lalrpop's built-in lexer is regex-driven — it
pulls the
regex-automatastack into the binary and rebuilds a matcher DFA on everyExprParser::new()(a fixed ~680 µs we briefly cached around). We replaced it with alogoscompile-time-DFA lexer (src/lexer.rs) fed to the parser via anextern { enum Tok { … } }token block;lalrpop-utildrops todefault-features = false. Identifiers useunicode-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 for1 + 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
jsonbforfeel-pg, a JSON string forfeel-wasm. The mapping between JSON andfeel-coretypes lives in the wrapper crates, not in core. - Consequence:
feel_eval(expr text, context jsonb) RETURNS jsonbandevaluate(expr, context_json) -> String(JSON). Integral numbers are emitted as JSON integers so1 + 1yields2, not2.0.feel-corestays 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 theForeignObjectseam (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↔ FEELdays-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.pycarries a deviation registry: a list of rules, each a (predicate, transform) pair. The livedecimal-vs-f64rule switches numeric expectations tocomparison: "f64_epsilon"with a recordeddeviationnote. Future deviations (temporal, string edge cases) are present as documented, inert placeholders. - Consequence: Fixtures carry their own comparison mode (
exactorf64_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 theinmembership 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, intervalin); three-valuedand/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 remainf64(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::Nullfor type mismatches, division by zero, non-finite arithmetic, non-boolean logic operands, and wrong-TYPEifconditions.FeelErroris now effectively parse-only; evaluation always produces aValue. (A nullifcondition is a special case — see ADR-13.) - Consequence: This is a visible behaviour change at the wrappers —
feel_eval('1 + true')now returns JSONnullinstead 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 plainValue::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
(
forresults, list literals,some/everysources). - Decision: Add
Value::StringandValue::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/
expectedcomparison is structural and exact (no per-elementf64_epsilon). - Status: The "no map type" part is superseded by ADR-12 — nested-object
input and path access pulled
Value::Contextin.
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.BTreeMapgives 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
Postfixlayer for path accessa.b.c(binds tighter than unary minus;..stays a distinct token) and a context literal{a: 1, b: a + 1}(keys are aNameor 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).
- Identifiers widen to Unicode letters/digits (
- Consequence: ADR-1 and ADR-4 hold; only wrapper mapping and core grew.
feel_eval('p.age', '{"p":{"age":42}}'::jsonb)now returns42, andfeel_eval('{a:1}')returns a jsonb object.ifsemantics 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,informs other than a bracketed interval). Context literals{}are now in scope (ADR-12). Each case's<inputNode>values are captured into acontextobject and bound during evaluation, so input-reading expressions are now ingestible.parse_decisionsonly 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 0032if-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 …withbool = nullexpects the else branch (→ 90). Ourif(ADR-9) returnednullfor 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 treatsifascondition == 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 —nullis 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
ifcondition, 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 2andif "x" then 1 else 2staynull(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
ifrule 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
nullwith two meanings: a legitimate absence (missing field, explicitnull) and the result of a type/domain error (1 + true,1/0, comparing incomparable types). ADR-9 made both plainnull, which conflicts with "errors should never pass silently": an error that becomesnullthen vanishes. ADR-13'sifkeyed 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 toValue::Nullfor every FEEL operation (equality:error = null→ true; ordering; three-valued logic) so spec/TCK results are unchanged. The error sources of ADR-9 now produceValue::Error; thenullliteral, unbound variables and missing members stayValue::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, sofalse and (1/0)isfalseand 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 breaksfalse 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'sfeel_eval(…, strict => true)raises an ERROR;feel-wasm'sevaluate_strictreturns{"error": …}. The pure core never throws.
- AND/OR (Design 1 — sticky, strong Kleene): the truth value is exactly
strong three-valued logic — a dominating
- 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.
Valuegainscontains_error()andinto_lenient(); the fixture test and lenient wrappers compare/serialise the lenient view. An in-expressionassert 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 oneName. The first useful, low-risk increment is the single- word, non-temporal functions — they reuse the existingValuekinds and unlock a large batch of self-containedfeel-*-functionTCK dirs. - Decision: Add function calls as a new production in the
Postfixgrammar rule:Name "(" args ")"→Expr::FnCall(name, args). An LR(1) lookahead of(after aNameshifts into the call, otherwise it reduces to aVar, so plain variable references are unaffected;not(...)keeps its own keyword rule. Abuiltinsmodule dispatches by name + arity. Implemented (per spec §10.3.4): conversionstring/number; stringsubstring/contains/replace/split/matches; listcount/min/max/sum/mean/product/median/stddev/mode/all/any/append/concatenate/union/remove/reverse/flatten/sublist; numericdecimal/floor/ceiling/abs/modulo/sqrt/exp/log/even/odd. (even/oddreject non-integers,sqrtnegatives, andlognon-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()) isnull, 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-f64deviation):exp/logreturn 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-dialectdeviation):replace/split/matchesuse Rust'sregexcrate, 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-smixqflags) 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 documentedREGEX_DIALECT_SKIPSlist intools/ingest_tck.py(not silently rewritten).
- Error policy (ADR-14): wrong arity / wrong type / domain error / unknown
name → error-null; spec-legitimate empty/absent results (
- Consequence:
feel-coregains aregexdependency (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 declaredxsd:stringvalue was mis-typed as a number (string(2) = "2"), and string results were whitespace-stripped (substring("foob r", -2, 1) = " "). Unlocked 20feel-*-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 andabson durations (await ADR temporal types),sortand the matching-function form oflist replace(need function values), range relations andis(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/splitbuiltins (ADR-15) used Rust'sregexcrate everywhere. That crate'sregex-automatastack (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/NodeRegExp; Python'sre; 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 bundledRustRegex, 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
FeelRegextrait (is_match/replace/split, each returningNone→ FEEL null for a dialect/pattern error) and thread it through evaluation via anEvaluatorcarrying&dyn FeelRegex(kept out ofContext, which is cloned per loop). The public API addsevaluate_with/CompiledExpr::evaluate_with; the no-argumentevaluateuses a default provider. The Rust engine becomes an optionalfeel-coredependency behind the defaultrust-regexfeature. Each target then uses its host's engine — and therefore its host's dialect:feel-wasm: a JSRegExpprovider (ECMAScript dialect); built withdefault-features = false, so the Rust regex stack leaves the bundle (1,289,360 → 272,636 bytes, ~79% smaller).feel-pg: keepsRustRegexfor now (size is irrelevant server-side); aPgRegex(POSIX ARE) provider is a recorded future option (a note infeel-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-inxpath-regexfeature re-bundlesRustRegexfor 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-regexescape hatch exists, and TCK regex fixtures validate therust-regexpath (the JS/PG dialects are host-defined). The flag-mapping corners differ by dialect (the JS provider mapsi/s/m, escapes forq, and ignoresx, which ECMAScript lacks; invalid flag letters → null in both). A barefeel-core --no-default-featuresbuild with no injected provider has no engine to consult, so the three builtins are an error-null ("unsupported in this build", viaFeelRegex::available) — distinct from the value-null an invalid pattern produces, so the strict boundary surfaces it (ADR-14). ADR-15'sregex-xpath-dialectdeviation 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 — theNameterminal just carries a space-normalised payload now. No name oracle is needed: soundness comes from FEEL having no juxtaposition of two expressions, so two adjacentNametokens can only be one name. Two tiers:- Tier 1 (generic): greedily merge a run of adjacent
Nametokens. Keywords are separate tokens (thekeyword()remap already ran) and stop the run, sox and ystays boolean — the join is backward-compatible (it only turns the previously-invalida binto 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 letsdate 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; listlist contains/index of/distinct values/insert before/list replace(positional form); contextget value/get entries. Dispatch is the samematch nameas 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 joinskips null items and treats a scalar as a one-element list;get valuereturns null for an absent or present-null entry;list replacetruncates 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_nodelearns context (<component>) results soget 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.
- Tier 1 (generic): greedily merge a run of adjacent
-
Consequence: No grammar change and no new lalrpop conflict — the token set is identical, only
Namepayloads 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 timeas a free name) are out; only the fixed built-in phrases are recognised, and only in call position. - The
date and time(x)vsdate 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.
- Special characters in names (
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-awareSpan/SignedDurationmap 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-pullingjsfeature; the wrappers do. The embedded IANA tzdb (needed only to resolve named zones like@Europe/Pariswhere 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 defaulttzdb-bundlefeature embeds it (native builds and feel-pg get full zones; native also has the system tzdb); feel-wasm buildsdefault-features = falseand so is offset-only by default (+02:00/Zwork, a named zone evaluates to null), re-enabling the bundle via itsiana-tzfeature. - Five flat
Valuevariants (matching the existing flat style):Date,Time,DateTime(each civil value + an optional zone preserved verbatim for output:Zvs+00:00vs@Area/City),YearsMonthsDuration(i64 months),DaysTimeDuration(SignedDuration). All temporal logic — parsing, canonical ISO-8601 formatting, comparison/equality, arithmetic, component access — lives in onetemporalmodule;eval/builtinsdelegate. @"…"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:00rolls to next-day midnight; a zero offset isZ; 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, …) extendsExpr::Path. - Built-ins: constructors
date/time/date and time/duration/years and months duration(with their arity overloads), componentsday of week/month of year(names) andday of year/week of year(numbers), andabson durations (ADR-15 had deferred it). - Injected clock (generalises ADR-16's regex seam): an
EvalEnvcarries the regex provider and the instantnow()/today()read.CompiledExprgainsevaluate_with_env. feel-pg suppliesGetCurrentTransactionStartTimestamp()(transaction-stable, matching PostgreSQL'snow()); feel-wasm suppliesDate.now(); tests inject a fixed instant (so the clock builtins are deterministic). - Boundary = canonical ISO-8601 (durations
P1Y2M, dates2017-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 JSDateobjects (ISO string fallback whenDatecan't represent them; time and durations stay ISO strings) and accepts JSDateobjects anywhere in the context input.
- Library
- Consequence: Reverses ADR-5's deferral; the
temporal-interval-mappingdeviation 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-tzadds the tzdb for ~723 KB. ADR-1 is intact (cargo tree -p feel-coreshows no pgrx/wasm-bindgen). - Deviations (deliberate, documented): jiff caps the year at ±9999 and its
Spancaps the years/months magnitude, so the TCK's extreme-range dates/durations (and the oddduration("PT0.S")lexical form) cannot round-trip; these are listed intools/ingest_tck.py'sTEMPORAL_RANGE_SKIPS. Unary tests (the non-intervalinforms) 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 fourround …functions pluscontext/context put/context mergewere absent from both the ingest whitelist and the dispatch table — leaving1141–1147skipped 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).scaleis 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/floorby sign), toward-zero (trunc), nearest-ties-away (f64::round), nearest-ties-toward. Ascaleoutside decimal128's[-6111, 6176]range is null; ascalevalid for decimal128 but beyond f64's exponent range is a no-op (returnsn).context(entries),context put(context, key|keys, value),context merge(contexts)— added to the context dispatch.context puttakes a string key (shallow) or a list path (deep_put, recursing the spec'scontext put(m[k], rest, v); descending into a missing/non-context intermediate is null). Duplicate keys incontextare null;context mergeoverwrites 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), matchingcontext()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 aTEMPORAL_SUBSECOND_EQUALITY_SKIPSlist for the two0068cases 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: freeevaluate(expr, context=None)/evaluate_strict(...)plus acompile(expr)returning a reusableCompiledExpr(parse-once / evaluate-many). The lenient/strict null policy is ADR-14; a parse/eval error or a strict error-null raisesfeel.FeelError(a subclass ofValueError).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-pykeeps feel-core's default features (soRustRegexis available as thexpath-regexprovider, and the system tzdb resolves named zones) and is in the workspacemembersbut notdefault-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'sjs_to_valuewas 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 tonull(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
Valuetree 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 whereorder.customer.addressshould 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 aValue::Foreign(Foreign)variant, whereForeign(Arc<dyn ForeignObject>)is a newtype that hand-implementsDebug/Clone/PartialEq(the last asArc::ptr_eq) soValuekeeps its derives. feel-core never constructs aForeign; only the wrappers do. The rule: the FEEL dot (Expr::Path) resolves aForeignlazily, by name, viaget— the one place it is not forced; every other consumption (arithmetic, comparison, three-valued logic,if,in/between, iteration, builtin arguments) first callsValue::forced, an#[inline]tag test that materialises one level viaforce.getuses host attribute access (getattr/Reflect.get), so it fires@property/accessor getters — ORM relations load exactly when the expression names them;forceenumerates own instance data only (no blanket property sweep). AForeignthat reaches the result passes through: the wrapper recovers the original host object viaas_anyand returns it untouched (identity, no re-traversal). Operators keep FEEL semantics by construction —forceonly converts a host value into aValue, 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:
Valuedoes not grow (the variant is a 16-byte fat pointer, under the 32-byte temporal variant — pinned by a size test), and theforcedchecks fall through with a single predicted branch when noForeignexists. ADR-1 holds — the trait is std-only, like theFeelRegexseam (ADR-16) — and feel-pg, which never builds aForeign, gains one defensive, unreachable match arm that treats a strayForeignas 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 thejs_to_value/py_to_valueguards added under ADR-20 are removed. The single residual is structurally comparing two distinct cyclic foreign graphs, bounded by anArc::ptr_eqshort-circuit plus a recursion cap infeel_equal. Verified by feel-core foreign-seam unit tests (path is lazy →get, consume forces, an unbounded graph terminates along a finite path,Valuesize 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.getgetter, nested navigation, pass-through identity, cyclic termination). - Thread-safety & lifetime (deliberate, and Lua-relevant):
ForeignObject: Debugcarries noSend/Syncbound, soValueandContextbecame!Send + !Syncthe moment aForeigncan appear. This is intentional — host handles are themselves!Send(aJsValue; an mluaTable) — 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: aValue/Contextcarrying aForeigncannot cross threads; a cross-thread embedder must first materialise aForeign-freeValue(force the subtree) or take the eager-snapshot route (RD-6, "if flipped back"). The trait object isArc<dyn ForeignObject + 'static>, so a wrapper's stored handle must be owned/'static—Py<PyAny>,JsValue, and mlua ≥ 0.10's lifetime-freeTableall 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'gclifetime — the opposite of what theArc<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'staticTable/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 —mlualives only here), built with mlua 0.11. It ships as a Lua-loadable C module (#[mlua::lua_module] fn feel → luaopen_feel, exposingfeel.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 plainbuild_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 workspacemembersbut notdefault-members(a barecargo buildkeeps building only the portable members). Cargo features select the Lua flavour/mode:default = ["lua54", "vendored"](the test/embed build, whereLua::new()works), withluajit/luauand amodulefeature (link the host's Lua, build the loadable.so:cargo build -p feel-lua --no-default-features --features lua54,module).vendoredandmoduleare 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 asResult<_, 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-pygetattrpattern, 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 simplyreturnsnil(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_anydowncast). Argument marshalling uses mlua'sIntoLuaso the conversion runs with the&LuathatFunction::callalready holds (ForeignFunction::callis 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.luarun end-to-end through the loadable module under the systemlua5.4.Valuestays!Send(ADR-21), which matches mlua's non-Sendvalues 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) bodyliteral (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'sForeignObjectis 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>)whereFuncis either a nativeClosure { params, body, captured }(afunction(…)literal, captured with its definition scope — FEEL functions are lexical closures, spec §10.3.2.9) or aForeign(Arc<dyn ForeignFunction>)host callable.ForeignFunctionis the function analogue ofForeignObject: std-only, target-agnostic, constructed only by wrappers (ADR-1 holds). A singleArckeeps the variant one word, soValuestays 40 bytes (the size-regression test pins it).- Grammar:
functionbecomes a keyword; the literal is a loosest-binding form (body extends right, likeif). A unifiedArgrule parses positional (expr) and named (name: expr) arguments — clean LR(1), the:lookahead decides — intoCallArgs { 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
FunctionRegistryonEvalEnv, 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'sf(*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
functionsregistry. 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_anydowncast). feel-pg has no host-function seam (its input is JSONB, not host handles) — nativefunction(…)literals still evaluate there, and a function reaching the JSONB output is null.
- Grammar:
- 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, sotools/ingest_tck.pyskips them. The tests are therefore hand-written: feel-core unit tests + a hand-written0030fixture (each case carrying asourceprovenance 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 putoverloads 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 thechore/fixture-refreshsweep (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>)forsource[bracket], parsed as a postfix production on thePostfixlayer — 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 completedPostfixis unambiguously a subscript; interval[a..b]only followsin. This is the identical shift-after-value pattern the.path rule already uses, so it stays LR(1) — lalrpop builds conflict-free (thebuild.rsgate 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
Numberis a 1-based positional index (negative-from-end via the sharedresolve_index; non-integer or out of range → value-null); anything else is a Boolean filter, re-evaluated per element.itemis unbound in the outer scope, so a real predicate likeitem > 2is null there and correctly falls through to the filter path. - Filter scope (
filter_scope) binds the current element asitem; if the element is a context, its entries are also spread into scope so they read without anitem.prefix ([{x:1}][x = 1]) — but a context that already carries anitemkey keeps that key asitem. The element is forced for the entry-spread while theitembinding stays the original value, preservingForeignidentity (ADR-21). Non-truepredicate 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]);nullsource →null; error → error. - Projection: the
Expr::Patharm gains a list case so.fieldover a list of contexts maps the access ([{x:1},{x:2}].x = [1,2], missing key → null in that slot), sharing onemember_accesshelper with the scalar case. The list is not forced first, so a singleForeignkeeps the lazy-dot path (ADR-21).
- Grammar (conflict resolved): a
- Tests: feel-core unit tests for index/filter/projection (incl. singleton coercion,
the
item-key shadow, and composition), plus the ingested DMN-TCK0001-filter(Employees[dept = 20].name). The slice detector dropped its postfix-[reject, addeditemas 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
informs), andsort/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,someandeverywere 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-TCK0033-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::ForandExpr::Quantifiednow holdbindings: Vec<(String, IterSource)>(the tuple idiom already used byContextLit) instead of a singlevar/source.- Grammar: one new
IterCtxrule (name in source) fed through the existingComma<T>helper over the sharedIterSrc. A top-level,is consumed only byComma<IterCtx>—IterSrc(Sum ".." Sum|Disjunction) never eats one — so after each context the lookahead is,(more) orreturn/satisfies, keeping it LR(1). Thebuild.rslalrpop gate fails on any conflict; it builds clean, and single-context input still parses unchanged. - Semantics (eval):
eval_for/eval_quantifiedrecurse 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_valuesis 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 smallQuantOutcomeenum. - Slice detector:
fits_slice_grammardropped its multi-context reject, now captures the subsequent, name invariables as bound names, and recognises a, name inclause as an iteratorin(not an unsupported membership form).
- Grammar: one new
- Tests: feel-core unit tests for
for/some/everymulti-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 variablepartial(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-TCK0070-feel-instance-ofexercises it across every value kind, against built-in/Any/Nulltypes and inline generics. - Decision: add a minimal type lattice L as
ast::FeelType(the primitive nodes,Any/Null, the parameterisedlist/range/context/functionnodes, and anUnknownnode for unmappable type names), and one AST nodeExpr::InstanceOf(Box<Expr>, FeelType). TheFeelTypeis 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
InstanceTypesub-grammar reachable only afterinstance of— a named type,list<T>/range<T>,context<k: T, …>, orfunction<…> -> T. The field-vs-type choice inside<…>reuses the same one-token (:) lookahead the callArgrule already uses, so lalrpop builds conflict-free (thebuild.rsgate enforces it). An unmappable name — a modelitemDefinitiontype this standalone engine can't resolve, a typo, or a barelist/contextthat "requires parameters" — becomesFeelType::Unknown, so e.g.123 instance of listevaluates tonull(the spec result) rather than failing to parse. instance oflexing (no new reserved words):instanceandofare not reserved — FEEL names may contain them (year of birth, theday of weekbuilt-in), so reservingofwould break those. Instead a pre-pass ([lexer::mark_instance_of]) fuses only the adjacentinstanceofpair into oneTok::InstanceOfoperator before name-joining; a loneinstance/ofstays an ordinary name-word. The function-type arrow->is a newlogostoken (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 singleNamewherever 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-andof variables literally nameddate/time/… — not meaningful FEEL.- Semantics — structural conformance (
types::value_conforms_to): rather than a canonicaltype(value)+ latticeconforms_towith joins, the value is checked against the target type structurally (equivalent for every FEEL shape, less code). Top level: an unmappable type →null; anull/error value is an instance only ofNull; otherwise the value must conform. Anullnested in a list element or context field has typeNullandNull <: T, so it conforms — which is why{a: null} instance of context<a: string>istruewhile top-levelnull instance of stringisfalse.contextconformance allows extra value keys (n ≥ m); functions check arity only (untyped closures map to(Any, …) -> Any).
- Type grammar (spec rule 52), restricted & LR(1)-clean: the right operand parses
via a dedicated
- Tests: ingested DMN-TCK
0070-feel-instance-of(119 self-contained cases; the slice detector now splits oninstance ofand validates the type's words against a built-in whitelist). The 23 skipped cases reference modelitemDefinitiontypes (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/Nulledges. - Consequence: §10.3.2.9 type-checking is supported for the self-contained type
language. Still out of scope (documented): model-defined
itemDefinitiontypes (need a type registry threaded from the embedder). (rangevalues: see ADR-27 — they are now first-class, soinstance of range<T>is no longer alwaysfalse.)
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 afterin, with no value of its own. The documented blocker was the interval-vs-list bracket ambiguity: factoringIntervalStart → "["as its own nonterminal clashes with the list literal on the bare[. Making ranges first-class unlocks1156-range-function, the relation suite1130-feel-interval, and the range cases in0068-feel-equality/0072-feel-in. - Decision: add
Value::Range(Box<RangeVal>)(two same-typed endpoints + per-bracket openness), boxed soValuestays 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 noIntervalStartnonterminal — exactly the factoring that used to conflict.build.rs's no-conflict gate proves it. inRHS — bare endpoint.InRhstakes a bareSum;ast::unary_test_from_exprroutes a written interval literal to the dedicatedUnaryTest::Interval(byte-for- byte the old membership test, no regression) and anything else toUnaryTest::Endpoint, evaluated as equalityx = e— or, wheneis 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. Sorange("[date(string(\"…\"))..…]")isnulleven though it would evaluate fine (the spec wants literals only). The evaluated endpoints must then be non-null, same-typed and ascending (viafeel_order), elsenull.- Equality &
instance of.=/!=compare ranges structurally (openness flags + both endpoints, FEEL-equal);instance of range<T>requires both endpoints to conform toT(reusingconforms_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 pointpis 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 usesfeel_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).
- 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
- Tests: ingested
1156-range-function(41 cases) and re-ingested0068/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
inmembership. Still deferred (the bracket-ambiguity forms): comma-list-of-testsin(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: thein-RHS is a different grammatical category (DMN rule 49, positive unary tests), not anexpression— 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
InRhsits own test-mode productions instead of delegating the whole RHS toSum.- Bracket-free
NbSumchain is the lever. The bare-endpoint branch ofInRhsroutes throughNbSum/NbProduct/…/NbPrimary— a copy of theSumprecedence chain whose leftmost primary dropsList,RangeLitand the"(" Expr ")"grouping. By never starting with[/(, it leaves thein [/in (states with exactly one bracket production (the test-list / interval) instead of two competing ones (test-list vs. the valueList/RangeLitreachable through a fullSum). With only one, the interval-vs-list split is a clean first-element factoring — parse the firstSum, 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.
UnaryTestElemisCmpOp Sum(a comparison) or a bareSum; a nested interval[2..4]arrives as aRangeLitvalue thatunary_test_from_exprreclassifies toUnaryTest::Interval.Expr::Inalready carriesVec<UnaryTest>andeval_inalready 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 aCompareelement, so thein-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.
- Bracket-free
- Two plan hypotheses the TCK then falsified (measured, not argued):
- Null endpoint is not ±∞.
5 in [null..10]and friends expect null, nottrue— a null bound is "unknown ⇒ unknown result", which feel-core's three-valuedrange_containsalready 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 aRange— i.e. it is an opaque unary-test value, not the range the desugar hypothesis assumed. Modelling it needs a newValuevariant touching equality; deferred as genuinely spec-murky (this resolves therange_006question the ADR-27 consequence list left open).
- Null endpoint is not ±∞.
- Cross-type equality skip (TCK bug). One 0072 case,
true in [false, 2, 3], expectsfalse, 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 expandse in [a, b, c]toe=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 offalseis 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 afterin); re-ingested0072-feel-in(255 → 325). Suite 2650 → 2720. A data-drivenlib.rstest (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, andnot(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, alongsidemark_instance_of/join_names) retags an opening]to a distinctRBracketOpenterminal. 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 ordinaryRBracket. The grammar then admitsRBracketOpen Sum ".." Endpoint IntervalEnd; no]-closer state is shared, thebuild.rsno-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 thirdIntervalEndbracket clashes with thePostfix "[" Expr "]"filter, which wants to shift a trailing[as a subscript. Resolve it with a filter-free high-endpoint nonterminalEndpoint(theSumchain with the filter dropped fromEpPostfix, base case reusing the sharedPrimary), used for every interval's high endpoint. With noPostfix "[" …item live there, a trailing[can only be the close — LR(1)-clean. Mirrors theNbSumprecedent (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_accessarm. AValue::Rangereads.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, mirroringtemporal::get_property(a range has properties). NoValue/AST change —Value::Rangeand theRangeLitAST already existed (ADR-27); this only wires the dot.
- Reverse-OPEN
- 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.fieldblanking now consumes joined multi-word member names (stopping at a keyword, like the lexer's join, soa.b and ckeepsand c). Re-ingesting the three affected suites added 8 closed-loop cases:0068(1..10] = ]1..10]/[1..10) = [1..10[(notation equivalence),1156range("]18..21]") = ]18..21]/range("[18..21[") = [18..21[(therange(string)builtin also parses reverse brackets), and0074's four.time offsetproperties. Suite 2720 → 2728. Unit testsreverse_open_bracket_intervals,reverse_close_bracket_intervals,range_propertiescover the forms directly. - Consequence: reverse-bracket intervals are first-class in value and
inposition, and range properties are readable. 0074'srange_*decisions are boxed contexts (4contextEntryliterals each) the literalExpression-only ingester does not read — same as 1130 — so the reverse-bracket property expressions (]1..10].start included) are covered byrange_propertiesrather 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](needsOptionAST endpoints + eval treating omitted as ±∞, distinct from a null bound's "unknown") and the opaque comparison-test value(< 10)in value position (needs a newValuevariant 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 categorynot(…)is always test negation (x in not(t)≡not(x satisfies t), three-valued), NEVER the booleannot(…)built-in — but the bare-endpoint branchNbSum → … → NbPrimaryreached the boolean"not" "(" Expr ")"production, so anotafterinhad two parses. - Decision: ship it as a dedicated test-mode production, resolving the fork by removing
the rival from the bare branch.
NbPrimarydrops the booleannot. TheNb*chain exists only asInRhs's bare-endpoint branch; removing"not" "(" Expr ")"fromNbPrimarymeans the bare branch can never start withnot. (A booleannot(…)is unaffected everywhere else — it lives in the fullPrimary, reachable throughSum.) Semantically this is exactly right: per spec anot(…)afterinis test negation, not a boolean endpoint.- A dedicated
InRhs → "not" "(" Comma<UnaryTestElem> ")"production. With the bare branch'snotgone, this is the only production starting withnotin thein-RHS state — one shift target, LR(1)-clean (thebuild.rsno-conflict gate proves it). ReusingUnaryTestElemmeans each inner element becomes a test viaunary_test_from_exprexactly like a bare list, sonot(5)is the negated= 5test,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; noExprchange.eval_unary_testOR-folds the inner tests (the same disjunction as a bare list) and negates the result with a Kleenenot3:not(true)=false,not(false)=true,not(null)=null, and a tainted unknown (error-null / wrong-typed) stays an error-null — mirroringand3/or3provenance, so negating an unknown never manufactures a definite truth. (x in not((null..10])⇒ null, not true.)
- Tests: unit test
membership_not_test_negationcovers list / bare / comparison / interval / mixed inner tests and the Kleene-null case directly. The ingester's_in_rhs_supportednow admitsnot(…)afterin(validated as a balanced paren group, like a bare bracket list). The DMN-TCK has noin 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 presentnullendpoint:[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 fromSome(null), and require — everywhere, literal andrange()— 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>>; valueRangeVal.start/.end→Option<Value>(None= unbounded).RangeValis still boxed behindValue::Range(Box<RangeVal>), soValuestays 40 bytes (thevalue_size_did_not_growguard is untouched). A presentnullbound evaluates toSome(Value::Null); only a syntactically omitted endpoint isNone. - 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 asrange("[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 includedof an unbounded side isfalse;.start/.endof it isnull. The flag is stored as written only sostring([1..))echoes the bracket. - Eval.
range_containstakesOption<&Value>per side — aNoneside is satisfied unconditionally (so5 in [1..)/5 in (..10]are true), aSome(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 aBound { NegInf, Val, PosInf }(an omitted lower =NegInf, upper =PosInf);±∞compares below/above every value and two same-sign±∞are equal, sobefore((..5],[10..)),includes((..7],[3..7]),coincides((..5],]..5])need no further special-casing. - Grammar (LR(1)-clean, build.rs gate). A
HiEndnonterminal 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 anyHiEnd; 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 byRangeLit(value position) and theInRhsinterval 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. Sorange("[2..)")≡>=2andrange("(..2)")≡<2are 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 1156004_e/004_f, "closed … endpoint with no value is not valid"),range("[..]"),range("(..)"). Becauserange()parses its string through the same value-position grammar, these strings already fail atcompile; the in-range_fnchecks are defensive belt-and-suspenders.
- AST
- 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 malformedrange()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_rangescovers 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_errorpins the rule-66 rejection of[1..]/[..10].range_builtincovers the open-bracketrange("[2..)")≡>=2plus 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 newValuevariant), 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 (therange_006question): a desugar to a one-endpointRangewas 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 aRange: an opaque unary-test value, not the unbounded range it superficially resembles. Thein-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
Valuevariant — not aRange.- Grammar — one new
Primaryalternative, LR(1)-clean.Primary → "(" CmpOp Sum ")". NoCmpOptoken is inFIRST(Expr), so seeing aCmpOpstraight 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 nodeExpr::UnaryTestVal(CmpOp, Box<Expr>)carries it (distinct fromExpr::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 andValuedoes not grow past 40 bytes (thevalue_size_did_not_growtest). Construction (eval.rs) evaluates andforceds the endpoint, exactly like a range endpoint. - Equality — structural, reflexive, range-incompatible. A new arm pair in
feel_equal_depth:(UnaryTestVal, UnaryTestVal)is a definitefalseon a differing operator, else the three-valued equality of the endpoints (so(<10) = (<10)is true);(UnaryTestVal, _)/(_, UnaryTestVal)is a definitefalse— against aRangeor anything else (null/error are settled earlier). This is the crux: afalse, 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 noinstance oftype butAny(the structuraltypes.rsarms only match concrete shapes), and the wrappers (feel-py / feel-lua) cross it out as hostNone/nillike a native closure.string((< 10))renders the written form(< 10)(endpoint quoted as a list member is).
- Grammar — one new
- Tests:
value_position_comparison_test(the true/false reflexive + range-incompatible pairs, the operator/endpoint structural cases,string(...), and a regression block proving thein-position test forms are unchanged). Re-ingested only0068-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 afterin; the paren form is admitted. 0068 101 → 109 (the eightrange_006/range_007…012cases, incl. the ADR-28-deferredrange_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 itsmember_accessreturning 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 opaqueValue::UnaryTestVal, correctly making its equality reflexive-only ((=10) = [10..10]is false, off 0068). But it also declared the value typeless ("conforms to nothing butAny") and gave it no member access —member_accessfell through toValue::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 (propertynull, inclusivity flagfalse) and the present endpoint's inclusivity follows the operator — and it is arange<T>. TCK0074-feel-propertiesrange_006–011pin 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— aValue::UnaryTestValarm (eval.rs), mirroring theValue::Rangearm. 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 isnull(matching the unbounded-RangeNonerule, ADR-31); an unknown property is value-null (it has properties). The crux:(=10).startand(=10).endare10/10even though(=10) ≠ [10..10]— properties and equality are decoupled.instance of range<T>— aValue::UnaryTestValarm invalue_conforms_to(types.rs). The single present endpoint must conform toT; the undefined side conforms vacuously, exactly like an unboundedRangeendpoint. 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 butAny", 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_accessis a read, not a promotion.feel_equal_depth'sUnaryTestValarms (ADR-32) are unchanged, as is the 40-byteValuesize. - Why a distinct variant, not
Range+ anis_testflag. Once(< 10)projects to the samestart/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 singleRange { start, end, start_open, end_open, is_test }whose=also comparesis_test(theCmpOpis 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_testwould have to be honoured by equality,string()((< 10)vs[10..10]rendering) and the Allen-relation exclusion (ADR-32:as_interval→None), but ignored byin-membership,member_access,instance ofandrange(). 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
UnaryTestValhelper if it ever grows, never a unifiedValuevariant. (Hard TCK data is only(<10) ≠ (null..10)and(=10) ≠ [10..10];(<10) ≠ (..10)is our principled extension of 0068's "never equal to aRange", and a unified flag would have to carry exactly that case too.)
- Illegal states. A comparison test is grammar rule 7.a — one operator, one endpoint —
so the compact
- Tests:
range_propertiesextended with the six-operator property table, the unknown-property null, and theinstance of range<T>conformance (incl. a wrong-endpoint-typefalse). Re-ingested only0074-feel-properties(the fiverange_006/007/009/010/011boxed-context decisions left inOUT_OF_SCOPE_EXPR_SKIPSby ADR-29's proviso, now removed).007448 → 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); themember_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.
- Parse —
feel_core::compile(expr) -> CompiledExpr. Parse once, evaluate many (feel-pg caches per call-site via pgrxfn_extra; the others exposecompile). - Evaluate —
CompiledExpr::evaluate_with_env(&ctx, &EvalEnv): the single general entry the wrappers call (ADR-16/ADR-18; the regex-onlyevaluate_withwas retired). Build theContextwithContext::insert. - Input mapping (lazy) — scalars and temporals convert eagerly; an object/dict/
table becomes
Value::Foreignwrapping a host-specificForeignObject(get= the FEEL dot, by name;force= materialise one level;as_any= recover the handle). Catch host errors insideget/force→ value-null (ADR-21). - Output mapping —
Value→ host value; aValue::Foreignthat reaches the result is handed back by identity viaas_anydowncast (no re-traversal); temporal values map to native host types or ISO-8601 (ADR-18); error-null/value-null per the strict/lenient policy. - Regex provider — implement
FeelRegexover the host engine, or reuse the bundledRustRegexwhen the host has none (ADR-16; onlymatches/replace/splitconsult it). - Clock — put a fixed
jiff::Zonedinstant in theEvalEnvsonow()/today()are stable for the whole evaluation (ADR-18; e.g. feel-pg's transaction start). - Strict vs lenient — after eval,
value.contains_error()decides: raise/throw (strict) orinto_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
PgRegexprovider routingmatches/replace/splitthrough 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.socosts nothing that matters; (2)RustRegexkeeps 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) aPgRegexis real unsafe-FFI work —DirectFunctionCallintotextregexreplace/regexp_split_to_array/textregexeq, Datum/text marshalling, and crucially catching Postgres' regexereport/longjmp so a bad pattern yields a FEELnullinstead of aborting the whole query. - Decision (2026-06-16): feel-pg stays on the default
RustRegexprovider. Theevaluate_withseam and a note infeel-pg/src/lib.rskeep 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 PgRegexin feel-pg as afeel_core::FeelRegex, mapping the three methods onto Postgres regex viaDirectFunctionCall(wrap each call so a regex error becomesNone→ FEEL null, never a longjmp unwinding through Rust); pass it viaCompiledExpr::evaluate_withinstead of the defaultevaluate; 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 nativepgrx::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 neverereport/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) beforeIntoDatum; (3) the result type offeel_evalis 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 jsonbwith 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_evaldirectly where a nativedate/timestamptz/intervalis 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/_intervalwrappers that evaluate as today, then range/precision-check the temporalValuein Rust and build the Datum viaIntoDatum(never calling anereport-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) orZ, 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-tzto adefaultfeature 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
RustRegexfor TCK-dialect parity) and like feel-wasm (JS dialect), Python ships its ownreengine, and the FEEL/XPath flagsi s m x qall carry over —i/s/m/xas inline(?…)flags,qviare.escape, and inline flags in the pattern pass straight through. So the host dialect is both available and idiomatic for Python authors. Against:reis 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
redialect via aPyRegexprovider (it holds the GIL, since the builtins call back into Python). Thexpath-regexbuild feature instead compiles feel-core'sRustRegex, for results byte-identical to feel-core/TCK. XPath$Nreplacement references are translated tore's\g<N>form (xpath_replacement_to_python, the Python pendant of feel-core'sxpath_replacement_to_rust). Edge: a capturing group in asplitdelimiter makesre.splitemit 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
redialect. - If flipped: make
xpath-regexthe default feature (or document building with it); the seam (evaluate_with_env+ thecfgprovider 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— addingpython-dateutilas a runtime dependency. Input is symmetric (a native temporal in the context maps back to the FEEL type; arelativedelta'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-dateutildependency.
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 lazygetattrwould 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 (noEvalEnvresolver needed, just a trait object that knows how toget/forceitself), the force checks are a single inlined tag test (pure-Rust embedders pay nothing,Valuedoes 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
ForeignObjectseam, resolving each dot on demand viagetattr/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, anid()/depth cycle guard) is gone; bulkforcestill 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→deepsnapshot as an opt-in (e.g. aneager=/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 faithfulLuaRegexis therefore off the table; the realistic options are (a) keep the bundledRustRegex(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
RustRegexprovider — 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). Theevaluate_with_envseam 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 LuaRegexoverlrexlib/PCRE as afeel_core::FeelRegex, mapping its errors toNone→ FEEL null, and pass it viaevaluate_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.datework 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 FEELdate()/time()/duration()builtins parse. A convenienceos.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_isoalready 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__indexmetamethod (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::Tablein aLuaForeignimplementingForeignObject:getviaTable::get(which fires__index, the on-demand load), anErr→ value-null;forcematerialises one level — a sequence (#t >= 1) becomes aValue::Listoft[1..=#t], any other table aValue::Contextof its string-keyed pairs;as_anyrecovers the handle for identity pass-through. Scalars and temporals (RD-8) stay eager. Mirrors feel-py'sPyForeignand feel-wasm'sJsForeign. 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
__indexruns" 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_evalshipped 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 isBTreeMap-ordered, and the only ambient input is the instant behindnow()/today()(ADR-18), which feel-pg pins to the transaction start. That makesfeel_evalprecisely STABLE (the same reason PostgreSQL's owntransaction_timestamp()is STABLE) and PARALLEL SAFE (a parallel worker is a separate process with its ownfn_extracache). It cannot be IMMUTABLE —now()differs across transactions. The pull toward an immutable surface is concrete: expression indexes (and generated columns, constant folding) over ajsonbcolumn 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/sqrtand the regex builtins, stable only up to a libc /regex-crate version. - Decision (2026-06-17, implemented): keep one STABLE
feel_evaland add a second, IMMUTABLEfeel_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 andCOST 500— measured, not guessed: a parse-cached eval of a low-to-medium expression runs ~13.5 µs/call on pg18, ≈ 560× a baselineprocost-1 C function (onecpu_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 pgrxJsonBboundary, which round-trips jsonb↔text↔serde_jsontwice per call (jsonb_out+parse in, serialize+jsonb_inout); a comparable jsonb plpgsql UDF using native binary jsonb is ~1.2 µs.feel_evalis also STRICT (pgrx default for non-Optionargs): an explicit SQLNULLcontext yieldsNULL, but theDEFAULT '{}'keeps the context-freefeel_eval('1+1')working — an accepted edge.feel_eval_immutableenforces determinism in two layers, both in feel-core: a static clock check (CompiledExpr::is_clock_free, cached infn_extra) that hard-ERRORs onnow()/today(); and a runtime named-zone ban (EvalEnv::forbidding_named_zones) that turns a named zone into null (ERROR understrict => true). Fixed offsets andZare kept — they are tzdb-independent and all an index needs. Math/regex are accepted as immutable: a libc/regexupgrade is rare and at worst wants a one-offREINDEX, 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 thetime()/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 500mis-orders plans (re-tune it, or make it expression-aware); or — most likely — optimising the jsonb boundary away (a binary-jsonb traversal / lazyJsonbForeignper ADR-21, replacing the pgrxJsonBtext 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_immutableand 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
JsonBtext round-trip is gone, the per-call cost dropped from ~13.5 µs to ~2.3 µs, andCOSTwas 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_evalat ~13.5 µs/call and pinned the cost on the pgrxJsonBboundary, which round-trips jsonb↔text↔serde_jsontwice per call (jsonb_out+serde_json::from_strin;serde_json::to_string+jsonb_inout) — 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/JsonbValueToJsonbto build;JsonbIterator*/getKeyJsonValueFromContainerto 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 aJsonbForeignbehind feel-core'sForeignObjectseam, 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.valueover 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 fullfeel_evalfrom 13.5 → 3.6 µs; lazy binary input brings it to ~2.3 µs, on par with feel-wasm (~2.0 µs). Theserde_jsondependency is dropped from feel-pg.COSTre-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 pgrxJsonBas the arg and return type; itsFromDatumonly detoasts (nojsonb_out),IntoDatumisJsonbPGetDatum, and theArgAbi/BoxRet/SqlTranslatableimpls mirror pgrx's ownJsonBso it drops straight into#[pg_extern]as a SQLjsonb. - 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 Postgresereport/longjmp(e.g. a jsonb size-limit error fromJsonbValueToJsonb) 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 manualPgTryBuilderis 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 notereportfor valid in-memory jsonb;AnyNumericguards its own f64↔numeric conversions. One nuance the lazy output surfaced and fixed: aForeignforced mid-encode yields a temporary sub-Valuedropped before the finalJsonbValueToJsonb, sovalue_to_jsonbcopies every emitted string/key into an output arena (numerics are palloc'd, scalars inline) rather than borrowing. - Lazy lifetime invariant: a
JsonbForeignholds a*mut JsonbContainervalid only for the call — created from the live argument, used duringevaluate_with_env, forced to owned jsonb on output, dropped before return; it never escapeseval_to_jsonb. AValuecarrying one is!Send(ADR-21), fine for the single-threaded per-call evaluation.
- decision expr
- Revisit trigger: a workload that consistently consumes the entire context (where
eager's single walk could beat lazy's per-key
Foreignallocations) — reintroduce eager (B) as an opt-in then; evidence thatCOST 100mis-orders plans; or a pgrx change to how the jsonb FFI is guarded. - If flipped (back to serde): restore the pgrx
JsonBarg/return type and the serdecontext_from_json/value_to_jsonhelpers, re-add theserde_jsondependency, and bumpCOSTback 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 inPostfix, abuiltinsdispatch table, the conversion/string/list/numeric functions (incl.regex-backedreplace/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:sortand the matching-function form oflist replace(need function values); range relations andis; the temporal functions (await temporal types). Built-ins would also enable an explicitassert 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; WASMDateobjects). Reversed ADR-5's deferral and made thetemporal-interval-mappingdeviation 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::IncarriesVec<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-fixturecontext, built into aContextin 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 theif-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 filterlist[item > 5]withitembinding + context-entry spread) and.fieldprojection over a list of contexts. Landed on thePostfixlayer alongside path access; the flagged grammar conflict with list literals / intervalin [a..b]was checked and is conflict-free (LR(1)). Unlocked DMN-TCK0001-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 byparse_expected_node). Every entry expression is individually checked byfits_slice_grammar; if any entry is out-of-slice the whole decision is skipped. The fixture test'sexpected_valuehandles"context"type viajson_to_value, mapping the JSON object toValue::Context(BTreeMap{…})for structural equality. Unlocked:0074-feel-propertiesrange_001–005 (+5 fixture cases, 20 range-property assertions);1130-feel-intervalall 14 Allen-relation decisions (+14 fixture cases, 132 boolean assertions). Suite 2853 → 2872. Former caveat now closed (ADR-33):0074range_006–011 (the comparison-test values(<10)/(>=10)etc.) were excluded under the ADR-29 proviso becausemember_accessforValue::UnaryTestValwas unimplemented; ADR-33 added the range-property andinstance of range<T>arms and re-ingested them (+5, suite 2872 → 2877), so they are no longer inOUT_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/* ... */". TCK0073-feel-commentsexercises all three shapes: inline block, EOL, and multi-line block with trailing EOL. Without comment support every/is lexed as division (Slash), so1 + /* 1 + */ 1fails 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_greedyis required becauselogos0.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
Commentenum variant thatlogos::skipcauses to be silently dropped — it never enters the token stream and the lalrpop grammar never references it. TheDisplayimpl's exhaustive match gets anunreachable!()arm. - Priority = 5 ensures
////*win over the 1-char/(Slash) under maximal munch regardless of declaration order. Bare/(division) and->are unaffected.
- EOL comment (
- Ingester:
fits_slice_grammarwould have mistaken comment words for free identifiers and skipped the cases. Astrip_comments(expr)helper (added totools/ingest_tck.py) strips both comment forms — string-aware so"http://x"is preserved — and is called at the top offits_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 introducedfunction(…)literals with bare-name params only (rule 55 as if rule 56 didn't exist). TCK0092-feel-lambdauses 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
FormalParamrule replacing theComma<Name>in the twoFnDefTextualExprproductions:- Grammar (
feel.lalrpop):FormalParam: String = { <n:Name> => n, <n:Name> ":" InstanceType => n }. The type annotation is parsed via the existingInstanceTypenonterminal and then discarded — only the parameter name flows intoExpr::FnDef { params: Vec<String> }.Expr::FnDefand 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 theArgrule's decision.build.rsLALRPOP no-conflict gate verifies. Nb/Epclones:function(...)literals do not appear in the bracket-freeNbPostfix/EpPostfixchains; onlyTextualExprneeds the change.- Type enforcement: This slice binds arguments by name only; arity is already
params.len(). A typed annotation likea: numberis 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).
- Grammar (
- Tests:
typed_formal_params_parse_and_evalandtyped_params_closure_and_curryinginlib.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 + aparses 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 callsfn1(-5) * fn2(25)— must yield a callable function value rather than null. TCK0092-feel-lambdacases 014 and 016 exercise this directly; case 017/018 also rely on it (deferred, needssort/2). - Decision:
function.rs: AddFunc::Builtin(String)variant alongsideClosureandForeign. The string is the spec name (identical to whatbuiltins::calldispatches on, including multi-word joined names like"string length").CloneandPartialEq(builtins equal by name) added naturally.builtins.rs: Addpub(crate) fn is_builtin(name: &str) -> bool— amatches!-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.rsExpr::Var: Ifctx.get(name)isNoneandis_builtin(name), returnFunc::Builtin(name)as the value. A context binding still shadows a built-in (checked first), preserving ADR-23's precedence rule.eval.rsinvoke: NewFunc::Builtin(n)arm dispatches tobuiltins::call(n, args, env). Wrong-arity or type-error calls returnSome(Error)fromcall, propagated as error-null; a missing name (impossible in practice) falls back toValue::Error.types.rs:Func::Builtinconforms toAnyonly (same asForeign— arity is not statically known in the type lattice for this slice).
- Consequence:
keyword_phrase_builtin_parses_in_call_positiontest updated: the multi-word name"date and time"out of call position now correctly returns aFunctionvalue 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_valueandbuiltin_passed_as_argument_and_invokedinlib.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 oflist 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 capabilitybuiltins::call(name, args, env)has never had: it receives only&EvalEnv, not theEvaluatorthat ownsinvoke/invoke_closureand thecall_depthrecursion guard. Function values now exist (ADR-23) and are first-class (ADR-36), so this is a contained addition. Unlocks0013-sort(3 cases),0092-feel-lambdatestCases 017/018, and 6 previously-skipped function-form cases in1155-list-replace-function. - Decision:
function.rs: Addpub(crate) trait Applier { fn apply(&self, f: &Func, args: Args) -> Value; }— a narrow seam mirroringForeignFunction/FunctionRegistry. Collapses aFeelError(unreachable inside the evaluator) toValue::Error.eval.rs:impl Applier for Evaluator<'_>delegates toself.invoke(f, args).unwrap_or(Value::Error), reusing the existing closure path (lexical scope binding viabind_params, recursion guard viacall_depth). Both call sites that passselftobuiltins::callare updated to supplyselfas the applier.builtins.rs:callsignature gainsapplier: &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: moveitems[i]left whileprecedes(items[i], items[i-1])returnsBoolean(true), stop onBoolean(false), any other result → error for the whole call.list_replace_fn(args, applier)— dispatches on whetherargs[1]isValue::Function: matching form (iterate, applymatch(item, newItem), replace ontrue, error on non-boolean; closure arity-2 guard) or positional form (existing implementation, unchanged). Namedmatch:overload routed inreorder_namedby checking whether the named args contain the key"match"before the generic table lookup.
- Registration:
"sort"added tois_builtin,calldispatch (list section), andbuiltin_param_names("sort") ⇒ &["list", "precedes"].builtin_param_names("list replace")entry documents thatreorder_namedhandles the dual overload. - Wrapper crates: Fixed missing
Func::Builtin(_)arms infeel-wasm,feel-py,feel-luafunction-value marshal paths (gap left by ADR-36). All three treat a built-in ref like a native closure — cross out asnull/nil/None(no host representation). - Ingester:
"sort"added to_BUILTINS.fits_slice_grammargains a function-literal extraction step before the free-name scan:\bfunction\s*\(bare_params\)patterns are found, param names collected intofn_params(added toallowed), and the head blanked fromscan. 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_casesinlib.rsfunction_tests. - Consequence: Resolves the
sort/list replacematching-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-invocationexercises 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 namenon_existing_function(). The unknown-name case (001) already worked:FnCalldispatch returnsValue::Error(→ null). Cases 002–008 did not parse: the grammar's only invocation form wasName "(" … ")"— a literal callee (null(,123(,"abs"() was a syntax error. The suite was never ingested;null()sat inOUT_OF_SCOPE_EXPR_SKIPSwith an ADR-23 note. The fix requires a separate AST node to keep named dispatch (FnCall) on its unchanged path — routing aNamethrough value-evaluation would break every builtin call because builtins are not scope-boundValue::Functionvalues. - Decision:
ast.rs: NewExpr::Invoke(Box<Expr>, CallArgs)variant. Semantics: evaluate the callee expression; invoke if it is aValue::Function, otherwise error-null (→ null at the lenient boundary).is_clock_freegets a matching arm that treatsInvokelikeFnCallwithout thenow/todayguard (a literal callee is never a clock read).feel.lalrpop: NewInvocablenonterminal for the six literal forms (Num,Str,TemporalLit,"true","false","null").Nameis deliberately absent. Two productions inPostfix:<e:Invocable> "(" ")" => Invoke(…)and<e:Invocable> "(" <a:Comma<Arg>> ")" => Invoke(…).NbPostfixandEpPostfix(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::Invokearm evaluates the callee with.forced(), dispatches toinvokeforValue::Function, returnsValue::Errorfor everything else. Reuses the existingeval_args/invokehelpers unchanged.- Ingester:
OUT_OF_SCOPE_EXPR_SKIPSentry for1131:002:decision002removed. Case 001 (non_existing_function()) remains outside auto-ingest:fits_slice_grammarcannot distinguish a deliberately unknown name from a missing input name. It is hand-written into the fixture (same practice as0092-feel-lambdacases 017/018, ADR-37).
- Tests:
invoke_non_function_yields_nullinlib.rs::function_testsasserts all eight 1131 shapes → null, plus a regression check thatabs(-1)/abs(n: -2)still route throughFnCall. All 8 cases covered bytck_fixtures_passvia 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 wideningInvocabletoPostfix, reintroducing theName-vs-Varambiguity). Suite 2907 → 2915.
ADR-39: Target-type coercion — §10.3.2.9.4 implicit conversions (0082)
-
Context:
0082-feel-coerciontests the DMN rule that a decision's result is coerced against its declared output type (typeRefon<variable>or<literalExpression>). Four conversions apply, in order: (1)null/error →null; (2) from-singleton-list — unwrap[e]toeby ONE level ifeconforms to the target (NOT recursive:[[10]]→number→ null); (3) to-singleton-list — wrapvinto[v]iffvconforms to the list element type; (4) conforms-to — passvthrough if it structurally conforms, elsenull. The suite was previously listed as out-of-scope ("DRG semantics"), but the coercion rules are FEEL-level concerns thatfeel-corecan implement directly — only the fivedecisionService_*cases require the DRG layer. -
Decision:
-
types.rs: Newpub(crate) fn coerce(v: Value, t: &FeelType) -> Valueimplementing the four rules beside the existingvalue_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 }— NOTcoerce(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>)>(wasVec<String>— the type annotation was previously parsed then discarded).function.rs:Closure.paramsupdated to match.feel.lalrpop:FormalParamrule now returns(String, Option<FeelType>);pub Type: FeelType = InstanceType;added as a new public entry point soparse_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 yieldsNull(non-conforming argument),bind_paramsreturnsErr(())and the whole call is error-null. A null actual arg has typeNull <: Tper the nested-null rule and is bound as-is.
-
lib.rs: Exportspub use ast::FeelType,pub fn parse_type(s) -> Option<FeelType>(viafeel::TypeParser), andpub fn coerce(v, t) -> Value. -
Fixture harness (
fixtures_test.rs): optional"coerce_to"field — a structural FEEL type string — triggerscoerce(result, parse_type(coerce_to))after evaluation and before comparison. -
Ingester (
ingest_tck.py) — four new capabilities:parse_item_definitionsresolves<itemDefinition>trees into structural FEEL type strings (isCollection→list<…>,itemComponent→context<…>, baretypeRef→ primitive);_resolve_typeref_to_feel/parse_decision_typerefsmap decision variables to their resolved type forcoerce_toemission.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 returntypeRef(when present) becomescoerce_tofor the case.parse_invocation_decisionsconverts<invocation>form decisions into named-argument FEEL calls; the<invocation typeRef>becomescoerce_towith the BKM return type as fallback.parse_context_result_decisionshandles boxed-context decisions with a trailing unnamed result cell →{named_entries…, __result: result_expr}.__result._fn_literal_params_and_blankreplaces the old_fn_literal_patregex: 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:infunction(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 + twods_invoke_*decisions naturally rejected byfits_slice_grammarbecause the DS name is a free identifier). NoOUT_OF_SCOPE_EXPR_SKIPSentries needed — the existing machinery handles it. -
Tests: 31 cases in
0082-feel-coercion.json; exercised bytck_fixtures_passas part of the 92-fixture suite. Unit teststyped_formal_params_parse_and_evalandtyped_params_closure_and_curryinginlib.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 suite0101-feel-constantstests exactly these forms (.872,-.872). The ingester'sfits_slice_grammarpredicate already admitted all three feel-constants suites (no free names), but the engine couldn't evaluate.872because the logos lexer regex only covered digit-led mantissas without exponents. -
Decision: Widen the
Numtoken regex inlexer.rsto 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 with0099-arithmetic-negation). No grammar/AST/eval changes were needed —f64::from_stralready 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_rule35inlib.rs): direct coverage of.872,-.872,1.2e3,1E-3,.5e2so 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-arithmeticexercises a single literal-expression decisionpayment(standard amortized-loan monthly-payment formula) over a structuredtLoaninput (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 (seeparse_input_valueintools/ingest_tck.py); the test harness binds a nested JSON object asValue::Context(viajson_to_valueinfixtures_test.rs); path access on a context value already resolves correctly; andfits_slice_grammaraccepts the expression becauseloanis a captured input name and.fieldmembers are blanked. Numeric results usef64_epsiloncomparison (epsilon=1e-8) via thedecimal-vs-f64deviation (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-arithmeticexercises a BKM-backed literal-expression decisionMonthlyPaymentwhose FEEL expression isPMT(Loan.amount, Loan.rate, Loan.term)+fee. The BKMPMTis a user-definedfunction(p: number, r: number, n: number)with body(p*r/12)/(1-(1+r/12)**-n). Inputs are a structuredLoan : tLoan {amount, rate, term : number}and scalarfee : number. Three test cases vary the loan parameters;feeis fixed at 100. Expected decimal results (2878.69…, 662.70…, 2961.03…) are exactly the ADR-41 PMT values plusfee. -
Decision: Ingest the suite as-is — no engine or ingester changes were required. The ingester's
_inline_bkmspath rewrites the BKM-backed decision into a self-contained{PMT: function(...) ..., __result: PMT(Loan.amount, ...)+fee}.__resultexpression (the same__resultwrapper introduced for0082-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 usef64_epsilon(epsilon=1e-8) via thedecimal-vs-f64deviation (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-logicand0107-feel-ternary-logic-nottest 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) andExpr::Notevaluation (lines 186–200) already implement Table 51 (conjunction/disjunction with null) and Table 74 (not(null)=null) exactly. The ingester's context-binding path mapsxsi: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 passfits_slice_grammarwithout skips. Unit testslogic_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, and1161-boxed-list-expressionexercise 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 atypeRef=stringListlist 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_childpattern of the existingparse_invocation_decisions/parse_context_result_decisions):parse_conditional_decisions→ translates<conditional><if><then><else>toif (IF) then (THEN) else (ELSE).parse_filter_decisions→ translates<filter><in><match>to(IN)[MATCH](the predicate referencesitem, already an allowed implicit name).parse_iterator_decisions→ handles all three iterator tags in one function; translates<for iteratorVariable="v"><in><return>tofor v in (IN) return (BODY)and<some/every iteratorVariable="v"><in><satisfies>tosome/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 theinvocation_decisionsbranch inextract_cases, before the finalelse: 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 expectsnull; feel-core returns[]. ADR-24 deliberately drops non-truefilter 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 expectsnull; 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 expectsnull; feel-core returnstruebecausesomeshort-circuits on the firsttrue(quant_product,eval.rs, line 953), per the sticky-provenance / strong-Kleene design of ADR-13/ADR-14 (truedominates before the later non-boolean taint is seen). Notably1154-boxed-every:006(passes) because foreverythefalse-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-filterand the0106/0107ternary-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_elemwhere 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 booleantruerather than the string"true". Fixed by promoting thexsi_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'sstring(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 usecomparison: "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-iterationwas found to produce a single list-of-numbers case that failsexactcomparison due to the decimal128 vs f64 gap — thedecimal-vs-f64deviation rule only covers scalar numbers, not list elements. -
Decision:
0005-literal-invocation(3 cases,f64_epsilon): boxed-context+result-cell decision inlining a BKMPMTas a function literal. Thedecimal-vs-f64deviation fires (scalar numeric result).0016-some-every(2 cases,exact):some/everyover a list of contexts (priceTable2) with path accessi.price. 5 decisions skipped:priceTable1references are outside the slice (DRG-scope name);gtTenandevenare user-defined functions not in the built-in table;values in a listis a multi-word name requiring the name-join lexer (ADR-17) but appears inside the quantifier source, wherefits_slice_grammardoes not recognize it as a bound name.0032-conditionals(6 cases, 3exact+ 3f64_epsilon):if/then/elsewith context-bound date and number inputs.decimal-vs-f64fires 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 fullinstance oftruth 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-definedtypeRefaliases (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 casefor i in Loans return PMT2(i)produces a list of decimal128-computed numbers. Thef64_epsiloncomparison mode applies only to scalarexpected_type: "number"results; list elements cannot be compared element-wise with epsilon tolerance under the current harness design. Documented in the newDECIMAL_LIST_SKIPSfrozenset; no fixture file is produced until the harness gains a list-numeric epsilon mode.
-
Consequence: The five new fixture files add 142 cases, all
exactorf64_epsilon. TheDECIMAL_LIST_SKIPSmechanism 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): whereeis a context,e ... namereturns a list of every value bound tonameineand 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.rstestunbounded_graph_terminates_along_a_finite_path) does not apply: descendant recurses through the whole reachable graph, so a cyclic host graph behindValue::Foreignwould loop forever. -
Decision: Five-part change.
-
Lexer — a new
...token (DotDotDot). logos longest-match keeps it disjoint from./..; no LR interaction. -
Grammar — one
Postfixproduction<e:Postfix> "..." <n:Name>→Expr::Descendant, same precedence as the.path operator....is a unique lookahead after a completedPostfix, so it is LR(1)-clean (thebuild.rsno-conflict gate is green). -
AST/eval —
Expr::Descendant(Box<Expr>, String); the evaluator'sdescendant_collectwalks pre-order overContext/List(collect the match, then recurse into every child) andForeign(force one level, recurse). A null/error target propagates; a non-navigable scalar isnull(mirrors.); otherwise the result is a list (possibly empty). ADESCENDANT_MAX_DEPTH = 1024cap is a secondary backstop. -
Cycle guard / DAG de-dup — a
HashSet<usize>visited-set keyed on a newForeignObject::identity() -> usizetrait method (default = the Rust allocation address). Only anArc-backedValue::Foreigncan form a cycle (pure-Rust values are owned trees), and onlyForeignnodes 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 usespanic = 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. -
Per-host identity overrides — the default allocation address is sound only when one
Arcmaps to one host object. Every host wrapper mints a freshArcper wrap (shallow_convert*→Arc::newre-run on everyforce/get), so two wrappers around the same host object have distinct allocations. The correct identity is host-specific:- feel-py —
self.obj.as_ptr()(= Pythonid(), stable acrossPy::clone, no GIL). - feel-lua —
self.table.to_pointer()(mlua's Lua table pointer; stable acrossTable::clone). - feel-wasm — a process-wide
WeakMap<object, number>(js_identity): JS exposes no cheap object address and aJsValuehandle 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:
jsonbis a serialized value tree, so aJsonbForeignsub-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 existingForeignObject::as_anyoutput-identity seam (ADR-21). - feel-py —
-
-
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-accessCyclekeyed onidand a single-shared-ArcSharedCyclekeyed 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 viacargo pgx test(the pgrx harness, not runnable without a managed Postgres).