Public repository: timo / feel

Reader

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

feel / tools / ingest_tck.py · 89.3 KB · at 93b43c1c833b · raw

Outline: 45 definitions
1
#!/usr/bin/env python3
2
"""Ingest a single DMN-TCK literal-expression or boxed-context test into a feel-core fixture.
3
4
Source: https://github.com/dmn-tck/tck
5
6
Scope: this is NOT a general DMN/XML harness. It handles two decision forms:
7
8
1. **Literal-expression** decisions (`<literalExpression><text>EXPR</text>`):
9
   each decision emits one fixture case whose expression is the bare FEEL text.
10
11
2. **Boxed-context** decisions (`<decision><context><contextEntry>…</context>`):
12
   each decision emits one fixture case whose expression is the assembled FEEL
13
   context literal `{k1: e1, k2: e2, …}` and whose expected value is the
14
   structured `{key: scalar, …}` context. Every individual entry expression must
15
   pass `fits_slice_grammar`; if any entry is out-of-slice the whole decision is
16
   skipped.
17
18
Both forms only emit cases whose expression(s) fit feel-core's core-language
19
slice: arithmetic, comparison, `between`/`in`, `instance of`, three-valued
20
`and`/`or`/`not`, `if/then/else`, `for … return`, `some/every … satisfies`,
21
context literals, path access, and the full set of built-in functions. Each
22
case's `<inputNode>` values are captured as a `context` object and bound during
23
evaluation. See `fits_slice_grammar` for the exact predicate.
24
25
Anything outside the slice — or free names we could not bind — is skipped (and
26
reported), so we never produce false negatives for expressions the engine cannot
27
yet evaluate.
28
29
It also applies a *deviation registry*: a list of rules, each pairing a
30
predicate ("does this case match?") with a transform ("rewrite the expectation /
31
comparison mode"). Today only the DECIMAL/F64 rule is live; the others are
32
documented placeholders that future deviations hang off.
33
34
Usage:
35
    python tools/ingest_tck.py <path-to-tck-test> -o <fixture.json>
36
37
<path-to-tck-test> may be a TCK test directory (containing the .dmn and the
38
matching *-test-*.xml) or the .dmn file itself.
39
"""
40
41
from __future__ import annotations
42
43
import argparse
44
import json
45
import sys
46
import xml.etree.ElementTree as ET
47
from dataclasses import dataclass, field
48
from pathlib import Path
49
from typing import Callable, Optional
50
51
# --------------------------------------------------------------------------- #
52
# Slice grammar predicate: which expressions can feel-core actually evaluate?
53
# --------------------------------------------------------------------------- #
54
55
import re
56
57
# Keywords of the core-language slice. Any identifier that is NOT one of these
58
# (and not a for/some/every loop variable) is a *free* name — an input variable
59
# or a built-in function — which puts the expression outside the self-contained
60
# slice we ingest.
61
_KEYWORDS = {
62
    "for", "return", "in", "if", "then", "else", "some", "every", "satisfies",
63
    "and", "or", "not", "between", "true", "false", "null",
64
}
65
66
# Built-in / Any / Null type-name words allowed on the right of `instance of`
67
# (DMN §10.3.2.9). Multi-word names contribute several words (`date and time` ->
68
# date, time; `years and months duration` -> years, months, duration), joined by the
69
# `and` keyword. `list`/`context`/`range`/`function` are the generic heads. A type
70
# name outside this set is a model itemDefinition type (e.g. `t255`) the standalone
71
# engine cannot resolve, so the case is left outside the slice.
72
_TYPE_WORDS = {
73
    "Any", "Null", "number", "string", "boolean", "date", "time",
74
    "years", "months", "days", "duration", "list", "context", "range", "function",
75
}
76
77
# Built-in functions feel-core implements (DECISIONS.md ADR-15/ADR-17). A name
78
# immediately followed by `(` is a call head, not a free identifier; we blank
79
# those before the free-name scan so function calls fit the slice. Multi-word
80
# heads (`string length`) are included now (ADR-17); temporal (`date`/`now`),
81
# ranges, and user-defined functions are deliberately absent, so calls to them
82
# stay "free names" and the expression is (correctly) skipped.
83
_BUILTINS = frozenset({
84
    # conversion
85
    "string", "number",
86
    # string
87
    "substring", "contains", "replace", "split", "matches",
88
    "string length", "upper case", "lower case", "substring before",
89
    "substring after", "starts with", "ends with", "string join",
90
    # list
91
    "count", "min", "max", "sum", "mean", "product", "median", "stddev",
92
    "mode", "all", "any", "append", "concatenate", "union", "remove",
93
    "reverse", "flatten", "sublist",
94
    "list contains", "index of", "distinct values", "insert before",
95
    "list replace", "sort",
96
    # context
97
    "get value", "get entries", "context", "context put", "context merge",
98
    # numeric
99
    "decimal", "floor", "ceiling", "abs", "modulo",
100
    "sqrt", "exp", "log", "even", "odd",
101
    "round up", "round down", "round half up", "round half down",
102
    # boolean
103
    "is",
104
    # range (DMN §10.3.4.6) — first-class range values + Allen interval relations
105
    "range",
106
    "before", "after", "meets", "met by", "overlaps", "overlaps before",
107
    "overlaps after", "finishes", "finished by", "includes", "during",
108
    "starts", "started by", "coincides",
109
    # temporal constructors & clock (ADR-18)
110
    "date", "time", "date and time", "duration", "years and months duration",
111
    "now", "today",
112
    # temporal component functions (ADR-18)
113
    "day of week", "day of year", "week of year", "month of year",
114
})
115
116
# Built-ins that have **no** named-parameter form (feel-core, ADR-23): the purely
117
# variadic / dual-form aggregates and the varargs list builders. The spec gives
118
# them no single named-parameter signature, so feel-core's `builtin_param_names`
119
# table omits them and a named call to one (`sum(list: …)`, `all(list: …)`) is an
120
# error-null — even though the spec result would be a real value. A named call to
121
# one of these is therefore *not* in the slice and must stay skipped (keeping it
122
# would be a false positive: the TCK expects the real result, feel-core returns
123
# null). Every name here is single-word, which keeps the reject scan simple.
124
_NO_NAMED_FORM_BUILTINS = frozenset({
125
    "min", "max", "sum", "mean", "product", "median", "stddev", "mode",
126
    "all", "any", "append", "concatenate", "union",
127
})
128
129
130
def _balanced_bracket_group(rhs: str) -> bool:
131
    """`rhs` begins with `[` or `(`: true iff that opening bracket has a matching close
132
    (a balanced leading group). Covers both a *single* interval `[a..b]` and the
133
    comma-list / parenthesised test-list forms (`[2,3,1]`, `(false,true)`,
134
    `(1,<5,>=10)`, `[[a..b],[c..d]]`, `(=10)`) — all positive unary tests after `in`
135
    (Form 1). A close with nothing open (the reverse-bracket `]a..b]`) is rejected; the
136
    broader reverse-bracket / unbalanced detection lives in the `..` scan in
137
    `fits_slice_grammar`."""
138
    depth = 0
139
    for c in rhs:
140
        if c in "[(":
141
            depth += 1
142
        elif c in "])":
143
            depth -= 1
144
            if depth < 0:
145
                return False
146
            if depth == 0:
147
                return True
148
    return False  # unbalanced
149
150
151
def _value_range_brackets_ok(s: str) -> bool:
152
    """True if every `..` in value-position `s` sits inside a bracketed range literal /
153
    interval feel-core parses — INCLUDING the reverse-bracket spellings `]a..b]`
154
    (exclusive lower, ≡ `(a..b]`) and `[a..b[` (exclusive upper, ≡ `[a..b)`) and the
155
    UNBOUNDED spellings `[1..)` / `(..10]` / `(..)` (an omitted endpoint is `±∞`, valid
156
    only behind an OPEN bracket per grammar rule 66; a closed `[1..]` / `[..10]` does NOT
157
    parse — ADR-31), all shipped now. The structural balance check accepts the unbounded
158
    `..` (it still sits inside its bracket group); the open-bracket requirement on an
159
    omitted endpoint is enforced by the parser, not here (and the DMN-TCK has no
160
    value-position unbounded literal anyway — `range("[1..]")` is a blanked string). A
161
    scan that does NOT require bracket *types* to match: FEEL intervals legitimately mix
162
    `[`/`(`/`]` (`(1..2]`), so an opener and a closer pair by nesting alone. Reverse
163
    roles resolve positionally — a `]` with nothing open is a reverse-open opener; a `[`
164
    whose innermost group already holds a `..` is a reverse-close closer. Rejects a bare
165
    top-level `..` and stray / unbalanced brackets;
166
    a few exotic shapes not in the TCK (a reverse-open as a list's first element,
167
    `[a..[list]]`) are conservatively skipped rather than risk a false positive (which
168
    would crash the closed-loop fixture test)."""
169
    stack: list[bool] = []  # one flag per open group: has a `..` been seen inside it
170
    i = 0
171
    while i < len(s):
172
        if s[i : i + 2] == "..":
173
            if not stack:
174
                return False  # bare top-level `..`
175
            stack[-1] = True
176
            i += 2
177
            continue
178
        c = s[i]
179
        if c == "(":
180
            stack.append(False)
181
        elif c == "[":
182
            if stack and stack[-1]:  # inside a `..` group -> reverse-close `[a..b[`
183
                stack.pop()
184
            else:
185
                stack.append(False)
186
        elif c == "]":
187
            if stack:
188
                stack.pop()
189
            else:  # nothing open -> reverse-open `]a..b]`
190
                stack.append(False)
191
        elif c == ")":
192
            if not stack:
193
                return False  # close with nothing open
194
            stack.pop()
195
        i += 1
196
    return not stack  # leftover open group -> unbalanced
197
198
199
def _in_rhs_supported(after: str) -> bool:
200
    """True if the text after a membership `in` is a slice-supported positive unary
201
    test: a single comparison `<op> endpoint` (`< 10`, `= e`, `!= e`), a bracket/paren
202
    group — a single interval `[a..b]`/`(a..b)` OR a comma-list / parenthesised list of
203
    tests (`[2,3,1]`, `(false,true)`, `(1,<5,>=10)`, `[[a..b],[c..d]]`, `(=10)`), all
204
    now parsed as positive unary tests (Form 1) — a `not(…)` *test negation*
205
    (`not(1,2,3)`, `not(<5)`, `not([1..10])`; DMN rule 49, ≡ `not(x satisfies t)`) — or
206
    a *bare endpoint* expression: a scalar (`1 in 1` is `1 = 1`) or an expression
207
    yielding a range (`2 in range("[1..3]")` is membership). Endpoints may be function
208
    calls; names are pre-validated by the free-name scan in `fits_slice_grammar`."""
209
    t = after.lstrip()
210
    # `not(…)` after `in` is unary-test negation, parsed by the dedicated `InRhs`
211
    # production (never the boolean built-in). Validate the parenthesised test list as
212
    # a balanced group, exactly like a bare bracket group.
213
    m = re.match(r"not\b\s*", t)
214
    if m:
215
        rest = t[m.end() :]
216
        return rest[:1] == "(" and _balanced_bracket_group(rest)
217
    if re.match(r"<=|>=|!=|<|>|=", t):
218
        return True
219
    if t[:1] in "[(":
220
        return _balanced_bracket_group(t)
221
    # A bare non-bracket endpoint (a scalar, a variable, or a `range(…)` call): the
222
    # free-name scan in `fits_slice_grammar` has already validated every name here.
223
    return True
224
225
226
def strip_comments(expr: str) -> str:
227
    """Remove FEEL Java-style comments (`//…\\n` and `/*…*/`) from `expr`.
228
229
    String-aware: characters inside double-quoted literals are preserved as-is,
230
    so `"http://x"` and `"/* not a comment */"` are never mangled.
231
    Block comments do not nest (per the FEEL spec).
232
    """
233
    out: list[str] = []
234
    i = 0
235
    n = len(expr)
236
    while i < n:
237
        c = expr[i]
238
        if c == '"':
239
            # consume the whole quoted string verbatim
240
            j = i + 1
241
            while j < n and expr[j] != '"':
242
                if expr[j] == '\\':
243
                    j += 1  # skip escaped char
244
                j += 1
245
            out.append(expr[i : j + 1])
246
            i = j + 1
247
        elif expr[i : i + 2] == "//":
248
            # EOL comment — skip to (but not including) the newline
249
            i += 2
250
            while i < n and expr[i] != '\n':
251
                i += 1
252
        elif expr[i : i + 2] == "/*":
253
            # block comment — skip to closing */
254
            i += 2
255
            while i < n and expr[i : i + 2] != "*/":
256
                i += 1
257
            i += 2  # skip the closing */
258
        else:
259
            out.append(c)
260
            i += 1
261
    return "".join(out)
262
263
264
def _fn_literal_params_and_blank(scan: str) -> tuple[set[str], str]:
265
    """Find all ``function(…)`` heads in *scan*, extract formal parameter *names*
266
    (stripping any ``: type`` annotation — including nested ``context<…>`` generics
267
    — from typed params), and return the combined set of parameter names together
268
    with a copy of *scan* in which every ``function(…)`` head has been replaced by
269
    spaces.  The body that follows each head is left intact so the outer free-name
270
    scan can validate it; the parameter names are added to the ``allowed`` set so
271
    references to them inside the body are not flagged as free identifiers.
272
273
    Examples::
274
275
        function(a, b) body                         → params={a, b},  head blanked
276
        function(arg: number) body                  → params={arg},   head blanked
277
        function(ctx: context<name: string>) body   → params={ctx},   head blanked
278
        function() body                             → params={},      head blanked
279
    """
280
    params: set[str] = set()
281
    result = list(scan)
282
    for m in re.finditer(r"\bfunction\s*\(", scan):
283
        # Locate the matching closing ')' of the parameter list using depth tracking.
284
        paren_open = m.end() - 1  # index of the '(' in scan
285
        depth = 0
286
        j = paren_open
287
        while j < len(scan):
288
            c = scan[j]
289
            if c == "(":
290
                depth += 1
291
            elif c == ")":
292
                depth -= 1
293
                if depth == 0:
294
                    break
295
            j += 1
296
        # scan[paren_open + 1 : j] is the raw parameter list, e.g.
297
        # "" or "a, b" or "arg: number" or "ctx: context<name: string, age: number>".
298
        params_str = scan[paren_open + 1 : j]
299
        # Split by top-level commas (not those nested inside `< … >`).
300
        parts: list[str] = []
301
        cur: list[str] = []
302
        angle = 0
303
        for ch in params_str:
304
            if ch == "<":
305
                angle += 1
306
                cur.append(ch)
307
            elif ch == ">":
308
                angle -= 1
309
                cur.append(ch)
310
            elif ch == "," and angle == 0:
311
                parts.append("".join(cur))
312
                cur = []
313
            else:
314
                cur.append(ch)
315
        if cur:
316
            parts.append("".join(cur))
317
        for part in parts:
318
            part = part.strip()
319
            # The name is the token before the first `:` (typed param) or the
320
            # whole token (bare param).
321
            name_part = part.split(":")[0].strip() if ":" in part else part
322
            if re.match(r"^[A-Za-z_]\w*$", name_part):
323
                params.add(name_part)
324
        # Blank the entire `function(…)` head so type annotations and param names
325
        # inside the parens can never be mistaken for free identifiers.
326
        for k in range(m.start(), j + 1):
327
            result[k] = " "
328
    return params, "".join(result)
329
330
331
def fits_slice_grammar(expression: str, input_names: frozenset[str] = frozenset()) -> bool:
332
    """True if feel-core's core-language grammar can parse AND evaluate
333
    `expression` against a context built from `input_names` (the case's
334
    `<inputNode>` names). A name is acceptable if it is a keyword, a
335
    for/some/every loop variable, a context-literal key, a member access
336
    (`.field`), or one of `input_names`. Any other free name (a built-in
337
    function such as `date`/`abs`, or an input we did not capture) puts the
338
    expression outside the slice. Out-of-scope syntax (temporal `@` literals,
339
    filters, parenthesised range tests, multiple iteration contexts, …) is also
340
    rejected.
341
342
    This is a conservative heuristic: it prefers to skip a borderline case over
343
    keeping one feel-core cannot handle (a false positive would crash the
344
    fixture test). The closed loop validates the rest — `cargo test -p feel-core`
345
    asserts every kept case actually evaluates."""
346
    # Strip Java-style comments before any other scan so comment text is never
347
    # mistaken for free identifiers or operators.
348
    expression = strip_comments(expression)
349
    # Blank out string literals so their contents never look like identifiers,
350
    # operators or brackets. Temporal `@"…"` literals are in scope now (ADR-18);
351
    # blanking the quoted part leaves a lone `@`, which the scans below ignore.
352
    s = re.sub(r'"[^"]*"', " ", expression)
353
354
    # `instance of` type predicate (DMN §10.3.2.9). The right operand is a restricted
355
    # type expression, not a general expression, so validate it on its own and then
356
    # reduce `s` to the value expression for the remaining scans. Only the single
357
    # `value instance of type` form is in the slice (no trailing `and`/`or`, which
358
    # 0070 never uses). The type must use only built-in/`Any`/`Null` type words plus
359
    # the generic punctuation `< > , : ->`; context-type field keys (`k:`) are blanked
360
    # first, exactly like context-literal keys on the value side. An unrecognised type
361
    # name (a model itemDefinition type) puts the case outside the self-contained
362
    # slice, as does an unimplemented built-in.
363
    if re.search(r"\binstance\s+of\b", s):
364
        parts = re.split(r"\binstance\s+of\b", s)
365
        if len(parts) != 2:
366
            return False
367
        value_expr, type_expr = parts
368
        type_scan = re.sub(r"[A-Za-z_]\w*\s*:", " ", type_expr)  # drop `k:` field keys
369
        type_idents = re.findall(r"[A-Za-z_]\w*", type_scan)
370
        if any(tok not in (_TYPE_WORDS | {"and"}) for tok in type_idents):
371
            return False
372
        s = value_expr
373
374
    # A parenthesised comparison test in *value* position — `(< 10)`, `(=10)`,
375
    # `(!=10)` — is now an OPAQUE unary-test value (ADR-32): `Primary → "(" CmpOp Sum
376
    # ")"`, an opaque `Value::UnaryTestVal` with reflexive, range-incompatible equality.
377
    # So the paren form is SUPPORTED, in value position as well as directly after a
378
    # membership `in` (the one-element paren test-list `x in (=10)`; ADR-28). Only the
379
    # bracket-led leading comparison `[< 10]` has no grammar production, so it stays out
380
    # of the slice — and, as before, only when it does not directly follow an `in` (a
381
    # bracket test-list `x in [<5, >10]` is a supported positive unary test).
382
    for _m in re.finditer(r"\[\s*(?:<=|>=|!=|<|>|=)", s):
383
        if not re.search(r"(?:^|[^\w])in\s*$", s[: _m.start()]):
384
            return False
385
386
    # Multiple iteration contexts (`for i in a, j in b …`; ADR-25) are in the slice
387
    # now. The subsequent `, name in` variables are added to `bound` below and the
388
    # `, name in` clause is recognised as an iterator `in` in the membership scan.
389
390
    # Named-argument calls `f(name: value)` are in the slice now (ADR-23): feel-core
391
    # binds them via a per-built-in parameter-name table (FEEL spec §10.3.2.13.5).
392
    # The parameter names themselves are blanked alongside context-literal keys in
393
    # the free-name scan below, so an in-scope named call to a built-in fits. Two
394
    # named forms stay out of the slice, both handled here:
395
    #   * a named call to a variadic aggregate / varargs builder, which has no named
396
    #     form in feel-core (error-null vs. the spec's real result) — see
397
    #     `_NO_NAMED_FORM_BUILTINS`;
398
    #   * a named call whose head is not a built-in (a user-defined function), which
399
    #     the free-name scan rejects anyway because the head is a free name.
400
    # The pattern is anchored on `(` (context literals open with `{`), so it never
401
    # matches `{key: …}`.
402
    _variadic_heads = "|".join(sorted(_NO_NAMED_FORM_BUILTINS, key=len, reverse=True))
403
    if re.search(r"\b(?:" + _variadic_heads + r")\s*\(\s*[A-Za-z_][\w ]*?\s*:", s):
404
        return False
405
406
    # Postfix list filter / index `value[…]` (`[1,2,3][1]`, `xs[item > 2]`) is in
407
    # the slice now (DMN §10.3.2.5). The implicit element name `item` it binds is
408
    # handled as an allowed free name below; the `[…]` itself needs no special
409
    # casing here (a `[` in value position is a list literal, after a value a
410
    # subscript — both parse).
411
412
    # Free identifiers: not a keyword, not a loop variable bound by an enclosing
413
    # for/some/every, not a captured input name. Member segments (`.field`) and
414
    # context-literal keys (`field:`) are structural, not free names, so blank
415
    # them out before scanning. The single-dot match excludes `..` ranges. A member
416
    # name may be multi-word (`.start included`, `.end included`, `.time offset`; the
417
    # lexer joins adjacent name words, ADR-17), so consume a run of words after the
418
    # dot — stopping at a keyword, exactly as the lexer's join stops at a keyword
419
    # token (so `a.b and c` keeps `and c`).
420
    _kw_alt = "|".join(sorted(_KEYWORDS, key=len, reverse=True))
421
    scan = re.sub(
422
        r"(?<!\.)\.(?!\.)\s*[A-Za-z_]\w*(?:\s+(?!(?:" + _kw_alt + r")\b)[A-Za-z_]\w*)*",
423
        " ",
424
        s,
425
    )  # drop `.field` (incl. multi-word members)
426
    # Extract function-literal formal parameters and blank all `function(…)` heads.
427
    # IMPORTANT: this must happen BEFORE the context-key blanker below, because a
428
    # typed formal parameter `arg: number` looks exactly like a `key: value` pair to
429
    # that regex — if the key blanker ran first, it would destroy `arg` before we
430
    # could record it as a bound name.  By running here, we blank the entire
431
    # `function(…)` head (param list + type annotations) and collect the raw param
432
    # names, so neither the names nor the type annotations can trigger a false
433
    # "free identifier" alarm later.
434
    fn_params, scan = _fn_literal_params_and_blank(scan)
435
    # Drop context-literal keys and named-argument parameter names (`key:`). Both
436
    # may be multi-word FEEL names (`{full name: …}`, `substring(start position: …)`,
437
    # `number(decimal separator: …)`), so consume the whole space-separated run up to
438
    # the colon — a `:` only follows a context key or a named-argument name (string
439
    # and temporal literals are already blanked), and `{`/`(`/`,` break the run, so
440
    # this never swallows a keyword or operand.
441
    scan = re.sub(r"(?:[A-Za-z_]\w*\s+)*[A-Za-z_]\w*\s*:", " ", scan)
442
    # Drop implemented built-in call heads (`abs(`, `string length(`, …) so they
443
    # aren't treated as free names. Arguments keep being scanned, so a call whose
444
    # args reference an unknown name is still skipped. Multi-word heads (ADR-17)
445
    # may have any whitespace between parts, and are tried longest-first so a
446
    # multi-word head wins over a single-word prefix (`substring before` over
447
    # `substring`).
448
    heads = sorted(_BUILTINS, key=len, reverse=True)
449
    head_pat = "|".join(re.escape(b).replace(r"\ ", r"\s+") for b in heads)
450
    scan = re.sub(r"\b(?:" + head_pat + r")\s*\(", "(", scan)
451
    # Multi-word input names (`full name`, ADR-17) and special-character input
452
    # names (`a-b`, grammar rules 25–30; ADR-47 — the engine fuses such runs
453
    # against the scope at parse time) are single names; blank them before the
454
    # per-word scan so their parts aren't seen as free identifiers. Only the four
455
    # arithmetic symbols are covered: a `.` in an expression reads as member
456
    # access to this scanner (and to the engine's probe) long before an input
457
    # name could claim it, and no TCK suite binds a dotted input name. A symbol
458
    # run *not* covered by a bound input (genuine subtraction `a-b` of two bound
459
    # inputs) stays in-slice: both idents are blanked, the `-` remains.
460
    _run_syms = "+-*/"
461
    _blankable = (n for n in input_names if " " in n or any(c in n for c in _run_syms))
462
    for n in sorted(_blankable, key=len, reverse=True):
463
        scan = re.sub(r"\b" + re.escape(n).replace(r"\ ", r"\s+") + r"\b", " ", scan)
464
    bound = set(re.findall(r"\b(?:for|some|every)\s+([A-Za-z_]\w*)\s+in\b", scan))
465
    # Subsequent iteration contexts `…, j in b` bind further loop variables (ADR-25).
466
    bound |= set(re.findall(r",\s*([A-Za-z_]\w*)\s+in\b", scan))
467
    # `item` is the implicit element name a filter predicate `xs[item > 2]` binds
468
    # (DMN §10.3.2.5). It is only in scope inside a `[…]`, but allowing it globally
469
    # here is a safe over-approximation: an `item` used outside a filter would just
470
    # evaluate to null, and the TCK filter cases all reference it inside `[…]`.
471
    allowed = _KEYWORDS | {"item"} | bound | set(input_names) | fn_params
472
    idents = re.findall(r"[A-Za-z_]\w*", scan)
473
    if any(tok not in allowed for tok in idents):
474
        return False
475
476
    # `..` is only valid as a bare iteration range (`for i in a..b`) or inside a
477
    # membership interval (`x in [a..b]`).
478
    if ".." in s:
479
        if re.search(r"\b(?:for|some|every)\b", s):
480
            # In an iteration, ranges must be bare — reject any bracketed `..`.
481
            if re.search(r"[\[(][^\[\]()]*\.\.", s):
482
                return False
483
            # Note: iteration ranges are integer-only in feel-core. The two *date*
484
            # ranges the TCK expects to yield a day-by-day list are skipped by id
485
            # (`TEMPORAL_FOR_RANGE_SKIPS`); datetime/time/duration ranges yield null
486
            # in both the TCK and feel-core, so they stay in the slice.
487
        else:
488
            # Outside an iteration, a `..` is legal inside a *bracketed* range literal
489
            # / interval — a first-class range value (`[18..21] = [18..21]`,
490
            # `[1..10] instance of range<number>`, `]1..10].start`) or a
491
            # membership-interval RHS (`x in [a..b]`, validated further by the
492
            # membership scan below). The reverse-bracket spellings `]a..b]` / `[a..b[`
493
            # and the open-bracket unbounded spellings `[1..)` / `(..10]` (ADR-31) are in
494
            # scope now (shipped), so the structural scan accepts them and
495
            # rejects only a bare top-level `..` or genuinely unbalanced brackets.
496
            if not _value_range_brackets_ok(s):
497
                return False
498
499
    # Membership `in` (not a for/some/every iterator). The slice supports a single
500
    # comparison test (`x in < y`, `x in = y`) or a single interval (`x in [a..b]`,
501
    # endpoints may be function calls). The comma-list and bare-equality forms are
502
    # out of slice (deferred) — see `_in_rhs_supported`.
503
    for m in re.finditer(r"\bin\b", s):
504
        before = s[: m.start()]
505
        if re.search(r"\b(?:for|some|every)\s+[A-Za-z_]\w*\s*$", before):
506
            continue  # the first iterator `in`, handled above
507
        # A subsequent multi-context iterator `in` (`…, j in b`; ADR-25): `before`
508
        # ends with `, name`, and a for/some/every keyword opens the expression.
509
        if re.search(r",\s*[A-Za-z_]\w*\s*$", before) and re.search(
510
            r"\b(?:for|some|every)\b", before
511
        ):
512
            continue
513
        if not _in_rhs_supported(s[m.end() :]):
514
            return False
515
516
    return True
517
518
519
# --------------------------------------------------------------------------- #
520
# Extracted, pre-deviation test case
521
# --------------------------------------------------------------------------- #
522
523
524
@dataclass
525
class Case:
526
    id: str
527
    expression: str
528
    expected: object  # JSON-serialisable: number | bool | None
529
    expected_type: str  # "number" | "boolean" | "null"
530
    comparison: str = "exact"
531
    deviation: Optional[str] = None
532
    epsilon: Optional[float] = None
533
    # Optional §10.3.2.9.4 coercion target type (structural FEEL type string, e.g.
534
    # "string", "list<number>", "context<name: string, age: number>"). When set, the
535
    # fixture test applies `coerce(result, parse_type(coerce_to))` after evaluation,
536
    # modelling the decision-variable / literalExpression `typeRef` boundary
537
    # (0082-feel-coercion).
538
    coerce_to: Optional[str] = None
539
    # The case's `<inputNode>` values, mapped name -> JSON value. Bound as the
540
    # evaluation context by the fixture test. Omitted from the fixture if empty.
541
    context: dict = field(default_factory=dict)
542
543
    def to_fixture(self) -> dict:
544
        out = {
545
            "id": self.id,
546
            "expression": self.expression,
547
            "expected": self.expected,
548
            "expected_type": self.expected_type,
549
            "comparison": self.comparison,
550
            "deviation": self.deviation,
551
        }
552
        if self.coerce_to is not None:
553
            out["coerce_to"] = self.coerce_to
554
        if self.context:
555
            out["context"] = self.context
556
        if self.epsilon is not None:
557
            out["epsilon"] = self.epsilon
558
        return out
559
560
561
# --------------------------------------------------------------------------- #
562
# Deviation registry
563
# --------------------------------------------------------------------------- #
564
565
# feel-core uses f64 where the spec uses decimal128. For numeric results we
566
# therefore compare with a tolerance instead of exact equality. The tolerance
567
# also has to absorb the TCK's own rounding: non-terminating results (e.g.
568
# `exp`/`log`) are given to a fixed number of decimal places (8 -> up to 5e-9 of
569
# truncation error), which a 1e-9 tolerance would reject as a false negative.
570
F64_EPSILON = 1e-8
571
F64_DEVIATION_NOTE = (
572
    "feel-core uses f64 arithmetic while the DMN/FEEL spec mandates decimal128, "
573
    "and the TCK rounds non-terminating results to a fixed number of decimal "
574
    "places; numeric results are therefore compared with an epsilon tolerance "
575
    "instead of exact equality to avoid false negatives from either source."
576
)
577
578
579
@dataclass
580
class DeviationRule:
581
    name: str
582
    description: str
583
    applies: Callable[[Case], bool]
584
    transform: Callable[[Case], None]
585
    # Filled in at runtime for the summary.
586
    applied_count: int = field(default=0)
587
588
589
def _decimal_f64_applies(case: Case) -> bool:
590
    return case.expected_type == "number"
591
592
593
def _decimal_f64_transform(case: Case) -> None:
594
    case.comparison = "f64_epsilon"
595
    case.epsilon = F64_EPSILON
596
    case.deviation = F64_DEVIATION_NOTE
597
598
599
_TEMPORAL_TYPES = {"date", "time", "date and time", "duration"}
600
TEMPORAL_DEVIATION_NOTE = (
601
    "Temporal result compared in feel-core's canonical ISO-8601 form (ADR-18). "
602
    "feel-core backs temporal values with jiff; at the wrappers they cross the "
603
    "boundary as ISO-8601 strings, so PostgreSQL can cast to date/timestamptz/"
604
    "interval (ADR-5's interval mapping) and WASM can return JS Date objects."
605
)
606
607
608
def _temporal_applies(case: Case) -> bool:
609
    return case.expected_type in _TEMPORAL_TYPES
610
611
612
def _temporal_transform(case: Case) -> None:
613
    # The expectation is kept as the canonical ISO string; the fixture test parses
614
    # it into a temporal Value and compares structurally. Only the provenance note
615
    # is attached (no value rewrite — the TCK lexical form is already canonical).
616
    case.deviation = TEMPORAL_DEVIATION_NOTE
617
618
619
# Registry: add future deviations here as additional DeviationRule entries.
620
# Only the DECIMAL/F64 rule is implemented; the rest are intentional, documented
621
# placeholders (their predicate never matches yet).
622
DEVIATION_RULES: list[DeviationRule] = [
623
    DeviationRule(
624
        name="decimal-vs-f64",
625
        description="Numeric results: compare with epsilon (decimal128 vs f64).",
626
        applies=_decimal_f64_applies,
627
        transform=_decimal_f64_transform,
628
    ),
629
    # --- Placeholders (not yet implemented) ----------------------------------
630
    DeviationRule(
631
        name="temporal-interval-mapping",
632
        description=(
633
            "date/time/duration results compared in feel-core's canonical "
634
            "ISO-8601 form; documents the wrappers' boundary mapping (ADR-18, "
635
            "and ADR-5's PostgreSQL interval mapping)."
636
        ),
637
        applies=_temporal_applies,
638
        transform=_temporal_transform,
639
    ),
640
    DeviationRule(
641
        name="string-edge-cases",
642
        description=(
643
            "PLACEHOLDER: string normalisation / unicode edge cases once strings "
644
            "are a runtime Value."
645
        ),
646
        applies=lambda _case: False,
647
        transform=lambda _case: None,
648
    ),
649
    DeviationRule(
650
        name="regex-xpath-dialect",
651
        description=(
652
            "DOCUMENTED: replace/split/matches use Rust's `regex` crate, whose "
653
            "dialect differs from the spec's normative XQuery/XPath 2.0 F&O regex "
654
            "(backreferences in the pattern, the `q` flag, XML-schema character "
655
            "classes). The common TCK cases match identically; any case that fails "
656
            "purely from a dialect difference is excluded via REGEX_DIALECT_SKIPS "
657
            "below (not silently rewritten). Revisit with a dialect translator."
658
        ),
659
        applies=lambda _case: False,
660
        transform=lambda _case: None,
661
    ),
662
]
663
664
# Case ids (model_stem:testCase:resultNode) whose only failure is the regex
665
# dialect gap documented by the `regex-xpath-dialect` deviation above. These are
666
# skipped during extraction so the closed loop stays green without faking a
667
# result. Each needs an XQuery/XPath 2.0 F&O regex feature Rust's `regex` crate
668
# cannot reproduce (backreferences; XML-Schema class subtraction `[A-Z-[OI]]`;
669
# `\p{IsBasicLatin}` block names; `x`-flag whitespace handling inside classes),
670
# or an XPath string escape (`K`, `\n`) the slice's string lexer does not
671
# decode yet (note: basic FEEL string escapes — `\n`/`\t`/`\uXXXX`/… — ARE decoded
672
# by the lexer now, so the remaining entries are true regex-dialect gaps). Revisit
673
# alongside a dialect translator.
674
REGEX_DIALECT_SKIPS: frozenset[str] = frozenset({
675
    "1111-feel-matches-function:K2-MatchesFunc-1:K2-MatchesFunc-1",
676
    "1111-feel-matches-function:K2-MatchesFunc-2:K2-MatchesFunc-2",
677
    "1111-feel-matches-function:K2-MatchesFunc-3:K2-MatchesFunc-3",
678
    "1111-feel-matches-function:K2-MatchesFunc-4:K2-MatchesFunc-4",
679
    "1111-feel-matches-function:K2-MatchesFunc-5:K2-MatchesFunc-5",
680
    "1111-feel-matches-function:K2-MatchesFunc-6:K2-MatchesFunc-6",
681
    "1111-feel-matches-function:K2-MatchesFunc-17:K2-MatchesFunc-17",
682
    "1111-feel-matches-function:caselessmatch07:caselessmatch07",
683
    "1111-feel-matches-function:caselessmatch10:caselessmatch10",
684
    "1111-feel-matches-function:caselessmatch11:caselessmatch11",
685
    "1111-feel-matches-function:fn-matches-27:fn-matches-27",
686
    "1111-feel-matches-function:fn-matches-28:fn-matches-28",
687
    # `matches("Mary\\u000DJones", "Mary.Jones")`: now that the lexer decodes the
688
    # `\\u000D` carriage return, this exposes the `.` dialect difference — XPath's
689
    # `.` excludes CR (TCK expects false), Rust's `.` matches CR (would give true).
690
    # Before escape decoding the literal text failed to match, so the case passed by
691
    # accident; it is a genuine regex-dialect skip now.
692
    "1111-feel-matches-function:fn-matches-45:fn-matches-45",
693
})
694
695
# Case ids whose only failure is jiff's representable range, not a semantics gap
696
# (ADR-18). jiff's `civil::Date` caps the year at ±9999 and its `Span` caps the
697
# years/months magnitude, so the TCK's extreme-range dates/durations (and the
698
# odd `duration("PT0.S")` lexical form jiff rejects) cannot round-trip. Skipped
699
# here so the closed loop stays green without faking a result. Revisit if jiff
700
# widens its range or we special-case the parser.
701
TEMPORAL_RANGE_SKIPS: frozenset[str] = frozenset({
702
    # years beyond ±9999 (date / date and time)
703
    "1115-feel-date-function:015_1dd66594cf:feel-date-function_015_1dd66594cf",
704
    "1115-feel-date-function:016_31f3fef4a0:feel-date-function_016_31f3fef4a0",
705
    "1115-feel-date-function:029_88f5c7c90f:feel-date-function_029_88f5c7c90f",
706
    "1115-feel-date-function:030_9184a7bfc3:feel-date-function_030_9184a7bfc3",
707
    "1117-feel-date-and-time-function:011_eec2d5bdcd:feel-date-and-time-function_011_eec2d5bdcd",
708
    "1117-feel-date-and-time-function:012_225a105eef:feel-date-and-time-function_012_225a105eef",
709
    "1117-feel-date-and-time-function:027_ae365197dd:feel-date-and-time-function_027_ae365197dd",
710
    "1117-feel-date-and-time-function:028_1c3d56275f:feel-date-and-time-function_028_1c3d56275f",
711
    # durations beyond jiff's Span range, and the `PT0.S` lexical form jiff rejects
712
    "1120-feel-duration-function:011_2169615b94:feel-duration-function_011_2169615b94",
713
    "1120-feel-duration-function:034_aa9cbb21a6:feel-duration-function_034_aa9cbb21a6",
714
    "1120-feel-duration-function:035_93eef01ae7:feel-duration-function_035_93eef01ae7",
715
    "1120-feel-duration-function:036_5f2775875e:feel-duration-function_036_5f2775875e",
716
    "1120-feel-duration-function:037_8c9ea9c0e6:feel-duration-function_037_8c9ea9c0e6",
717
})
718
719
# Case ids that assert time/date-and-time equality at *second* resolution — the
720
# TCK treats values differing only in sub-second fraction as equal ("value
721
# resolution is seconds"). feel-core backs temporal values with jiff at
722
# nanosecond precision and compares them structurally (ADR-18), so `.0001` and
723
# `.0002` are genuinely distinct; matching the TCK here would mean discarding
724
# sub-second precision from equality, a lossy change we decline to make. Skipped
725
# so the closed loop stays green without weakening the comparison.
726
TEMPORAL_SUBSECOND_EQUALITY_SKIPS: frozenset[str] = frozenset({
727
    "0068-feel-equality:datetime_003_a:datetime_003_a",
728
    "0068-feel-equality:time_005:time_005",
729
})
730
731
# Case ids asserting that a *cross-type* equality test is `false` (DMN reads
732
# `true = 2`, `[1,2,3] = 1`, … as false). feel-core deliberately makes a non-null
733
# type mismatch under `=`/`!=` an error-null instead — a conscious "incomparable ⇒
734
# unknown" reading (ADR-14), unit-tested as `100 = "100"` → error and `{a: 1} = 1`
735
# → null. So `true in [false, 2, 3]` OR-folds to null where the TCK wants false.
736
# Exactly one 0072 membership case rides on this (the bracket/paren list parsing
737
# itself, Form 1, is unaffected). Skipped so the closed loop stays green without
738
# weakening `=`; aligning cross-type equality with the TCK's `false` is a separate
739
# semantics decision (its own ADR) — see ROADMAP.
740
CROSS_TYPE_EQUALITY_SKIPS: frozenset[str] = frozenset({
741
    "0072-feel-in:boolean_001_a:boolean_001_a",
742
})
743
744
# Named-argument calls that name a built-in *overload* whose parameter name
745
# feel-core's single-row parameter table cannot carry (ADR-23). The grammar parses
746
# these and the head is an in-slice built-in, but the bind fails, so the result is
747
# error-null instead of the spec value — skipped so the closed loop stays green
748
# without faking a result (positional forms of all of these are ingested and pass).
749
#   * Temporal constructors `date`/`time`/`date and time` invoked as `(from: …)`:
750
#     each has a `from` single-arg overload, but feel-core's table holds the
751
#     *component* names (`year`/`month`/`day`, `hour`/`minute`/`second`/`offset`,
752
#     `date`/`time`) so the two overloads can share one positional row — there is
753
#     no slot named `from`, so `from` is an unknown name → null.
754
#   * `context put` invoked with the deep-put overload by name: feel-core carries a
755
#     single `key` parameter and resolves the key-vs-keys (string-vs-list) overload
756
#     by the value's type, so the spec's distinct `keys` name is unknown (`nested007`
757
#     → null instead of a deep put) and a list passed to `key` deep-puts where the
758
#     spec wants a type-error null (`nested008`).
759
NAMED_ARG_OVERLOAD_SKIPS: frozenset[str] = frozenset({
760
    # temporal constructors: the `from` overload's name is absent from the table
761
    "1115-feel-date-function:050_8f1e299951:feel-date-function_050_8f1e299951",
762
    "1115-feel-date-function:051_ad98079864:feel-date-function_051_ad98079864",
763
    "1116-feel-time-function:080_2bbb8c86af:feel-time-function_080_2bbb8c86af",
764
    "1116-feel-time-function:081_69f4e0231e:feel-time-function_081_69f4e0231e",
765
    "1117-feel-date-and-time-function:086_12ca8ac1d3:feel-date-and-time-function_086_12ca8ac1d3",
766
    # `context put` deep-put overload reached by name (key/keys, string/list)
767
    "1146-feel-context-put-function:nested007:nested007",
768
    "1146-feel-context-put-function:nested008:nested008",
769
})
770
771
# `for`/`some`/`every` iteration ranges (`a..b`) are implemented only over
772
# integers (README "What the slice can evaluate"; spec §10.3.2.10). A *date* range
773
# iterates day-by-day in the spec, so the TCK expects `for i in
774
# @"1980-01-01"..@"1980-01-03"` (and its descending twin) to yield the three
775
# dates — but feel-core builds no temporal range iterator, so it evaluates to null.
776
# The grammar parses the range (the `@` literals are in scope, ADR-18), so the
777
# slice detector keeps it; these two ascending/descending date-range cases are
778
# skipped here instead. The datetime / time / duration range cases in the same dir
779
# (`decision_020`-`022`) are *not* skipped: the TCK yields null for them too, so
780
# feel-core's null already matches.
781
TEMPORAL_FOR_RANGE_SKIPS: frozenset[str] = frozenset({
782
    "0084-feel-for-loops:decision_017:decision_017",
783
    "0084-feel-for-loops:decision_018:decision_018",
784
})
785
786
# Individually out-of-scope cases whose *expression* fits the slice but whose
787
# *expected* result comes from a DMN feature feel-core does not model (so the bare
788
# expression evaluates to a different, correct-for-the-expression value). Not bugs
789
# in the engine and not broken TCK cases — just outside a FEEL-expression engine.
790
#   * 0021 `decision2`/`decision4`/`decision5`: implicit singleton-list ↔ scalar
791
#     coercion (§10.3.2.9.4). `sublist(…)`/`Employees[item="Bob"]` yield a singleton
792
#     *list*, which the TCK coerces to a scalar at the decision's declared scalar
793
#     output type (`decision2`/`decision4`) or as a string function argument
794
#     (`decision5`: `upper case(["Bob"]) = "BOB"`). feel-core does not auto-coerce a
795
#     singleton list to its element, so its `["…"]`/null is the right *expression*
796
#     value. The list-typed twins `decision1`/`decision3` are kept (and pass).
797
OUT_OF_SCOPE_EXPR_SKIPS: frozenset[str] = frozenset({
798
    "0021-singleton-list:001:decision2",
799
    "0021-singleton-list:001:decision4",
800
    "0021-singleton-list:001:decision5",
801
    # 1131 decision002 (`null()`) was here until ADR-38 added value-invocation.
802
})
803
804
# Named-zone literals feel-core's eager `TimeZone::get` validation rejects in the
805
# build's tzdb, so the `@"…@Zone"` literal is an error-null and any expression over
806
# it is null. A temporal-parsing/tzdb limitation (ADR-18), independent of the
807
# function under test. `Etc/GMT` fails here while ordinary `Area/City` zones (e.g.
808
# `Australia/Melbourne`) resolve, so only this one `is`-case is affected.
809
TZDB_ZONE_SKIPS: frozenset[str] = frozenset({
810
    "0103-feel-is-function:time_007:time_007",  # is(@"23:00:50@Etc/GMT", @"23:00:50Z")
811
})
812
813
# Context keys written as a bare *emoji* (`{🐎: "bar"}`). feel-core's name lexer
814
# accepts a Unicode identifier (XID-start then XID-continue), but an emoji is not an
815
# XID character, so a bare emoji key does not parse — the same "no special
816
# characters in names" scope boundary the README documents (ADR-17). The
817
# string-valued unicode cases in the same suite (`string length("🐎😀")`,
818
# `"\U01F40E" = "🐎"`, …) are kept and pass — emoji in *strings* work fine.
819
NON_XID_NAME_SKIPS: frozenset[str] = frozenset({
820
    "0083-feel-unicode:decision_006:decision_006",  # {🐎: "bar"}
821
    "0083-feel-unicode:decision_007:decision_007",  # {🐎: "😀"}
822
})
823
824
# ADR-24 (filter) and ADR-13/ADR-14 (quantifier short-circuit / sticky provenance):
825
# Three cases where feel-core's documented design produces a result that differs from
826
# the TCK expectation for a non-true predicate / short-circuiting quantifier.
827
#
828
# 1151-boxed-filter:004 — [1,2,3,4,5]["not a boolean"]
829
#   TCK expects null; feel-core returns [] (non-true predicate silently drops the
830
#   element per ADR-24 "Filter scope … Non-true predicate results drop the element").
831
#
832
# 1151-boxed-filter:005 — [1,2,3,4,5][if (item<=3) then true else "not a boolean"]
833
#   TCK expects null; feel-core returns [1,2,3] (same ADR-24 rule).
834
#
835
# 1153-boxed-some:006 — some element in [1,2] satisfies if (element=2) then true else …
836
#   TCK expects null; feel-core returns true because `some` short-circuits on the
837
#   first true (ADR-13/14 sticky-provenance: the dominating true wins regardless of
838
#   a subsequent non-boolean taint).
839
# The f64_epsilon comparison mode only works for scalar numbers; list results that
840
# contain floating-point numbers computed from decimal128 by the TCK reference
841
# implementation cannot be compared element-wise with epsilon tolerance.  These
842
# cases are skipped until the harness gains a list-numeric epsilon mode.
843
DECIMAL_LIST_SKIPS: frozenset[str] = frozenset({
844
    "0003-iteration:001:MonthlyPayment",  # [PMT2(loan1), PMT2(loan2)] — list of f64-imprecise numbers
845
})
846
847
BOXED_PREDICATE_DEVIATION_SKIPS: frozenset[str] = frozenset({
848
    "1151-boxed-filter:004:decision004",
849
    "1151-boxed-filter:005:decision005",
850
    "1153-boxed-some:006:decision006",
851
})
852
853
854
def apply_deviations(case: Case) -> None:
855
    """Run every registry rule whose predicate matches `case` (mutates in place)."""
856
    for rule in DEVIATION_RULES:
857
        if rule.applies(case):
858
            rule.transform(case)
859
            rule.applied_count += 1
860
861
862
# --------------------------------------------------------------------------- #
863
# XML extraction (hard-wired to the literal-expression test form)
864
# --------------------------------------------------------------------------- #
865
866
867
def _local(tag: str) -> str:
868
    """Strip the XML namespace from a tag, leaving the local name."""
869
    return tag.rsplit("}", 1)[-1]
870
871
872
def resolve_inputs(path: Path) -> tuple[Path, Path]:
873
    """Return (dmn_path, test_xml_path) from a directory or .dmn file path."""
874
    if path.is_dir():
875
        dmns = sorted(path.glob("*.dmn"))
876
        if not dmns:
877
            sys.exit(f"no .dmn file found in {path}")
878
        dmn = dmns[0]
879
    elif path.suffix == ".dmn":
880
        dmn = path
881
    else:
882
        sys.exit(f"expected a TCK test directory or a .dmn file, got {path}")
883
884
    tests = sorted(dmn.parent.glob("*-test-*.xml"))
885
    if not tests:
886
        sys.exit(f"no *-test-*.xml file found next to {dmn}")
887
    return dmn, tests[0]
888
889
890
def parse_decisions(dmn_path: Path) -> dict[str, str]:
891
    """Map decision name -> literalExpression text.
892
893
    Only decisions whose *direct* logic child is a `<literalExpression>` are
894
    kept. Decisions backed by a `<relation>`, `<context>` or `<decisionTable>`
895
    are skipped — descending into them would wrongly mine an inner expression
896
    cell (e.g. a relation row value) as if it were the decision's expression.
897
    Boxed-context decisions are handled by `parse_context_decisions`."""
898
    root = ET.parse(dmn_path).getroot()
899
    decisions: dict[str, str] = {}
900
    for elem in root.iter():
901
        if _local(elem.tag) != "decision":
902
            continue
903
        name = elem.get("name")
904
        logic = _first_child(elem, "literalExpression")
905
        if name is None or logic is None:
906
            continue
907
        text_elem = _first_child(logic, "text")
908
        if text_elem is not None and text_elem.text is not None:
909
            decisions[name] = text_elem.text.strip()
910
    return decisions
911
912
913
def parse_context_decisions(dmn_path: Path) -> dict[str, list[tuple[str, str]]]:
914
    """Map decision name -> ordered (key, expression) list for boxed-context decisions.
915
916
    Only decisions whose direct logic child is a `<context>` are returned. Each
917
    `<contextEntry>` must have both a `<variable name="…">` and a
918
    `<literalExpression><text>…</text></literalExpression>`; decisions with any
919
    malformed or missing entry are silently skipped. The assembled FEEL context
920
    literal `{k1: e1, …}` is built by `extract_cases` after every entry
921
    expression passes `fits_slice_grammar`."""
922
    root = ET.parse(dmn_path).getroot()
923
    result: dict[str, list[tuple[str, str]]] = {}
924
    for elem in root.iter():
925
        if _local(elem.tag) != "decision":
926
            continue
927
        name = elem.get("name")
928
        ctx = _first_child(elem, "context")
929
        if name is None or ctx is None:
930
            continue
931
        entries: list[tuple[str, str]] = []
932
        ok = True
933
        for entry in ctx:
934
            if _local(entry.tag) != "contextEntry":
935
                continue
936
            var = _first_child(entry, "variable")
937
            lit = _first_child(entry, "literalExpression")
938
            if var is None or lit is None:
939
                ok = False
940
                break
941
            key = var.get("name", "")
942
            text_elem = _first_child(lit, "text")
943
            if text_elem is None or text_elem.text is None:
944
                ok = False
945
                break
946
            entries.append((key, text_elem.text.strip()))
947
        if ok and entries:
948
            result[name] = entries
949
    return result
950
951
952
# --------------------------------------------------------------------------- #
953
# 0082-specific: typeRef resolution, BKM parsing, invocation form, result cell
954
# --------------------------------------------------------------------------- #
955
956
# Primitive FEEL type names that appear as `typeRef` strings in DMN without a
957
# matching `<itemDefinition>`.
958
_FEEL_PRIMITIVE_TYPES: dict[str, str] = {
959
    "string": "string",
960
    "number": "number",
961
    "boolean": "boolean",
962
    "date": "date",
963
    "time": "time",
964
    "date and time": "date and time",
965
    "years and months duration": "years and months duration",
966
    "days and time duration": "days and time duration",
967
    "Any": "Any",
968
    "Null": "Null",
969
}
970
971
972
def parse_item_definitions(dmn_path: Path) -> dict[str, str]:
973
    """Parse ``<itemDefinition>`` elements and return a mapping from definition
974
    name to structural FEEL type string.
975
976
    Handles:
977
    * ``isCollection="true"`` → ``list<inner>``
978
    * ``<itemComponent>`` children → ``context<k: T, …>``
979
    * bare ``<typeRef>`` → primitive pass-through or recursive lookup
980
    * ``<functionItem>`` → skipped (DRG function-item type, no FEEL structural form)
981
    """
982
    root = ET.parse(dmn_path).getroot()
983
    raw: dict[str, ET.Element] = {}
984
    for elem in root.iter():
985
        if _local(elem.tag) == "itemDefinition":
986
            name = elem.get("name")
987
            if name:
988
                raw[name] = elem
989
990
    resolved: dict[str, str] = {}
991
992
    def resolve_typeref(ref: str) -> Optional[str]:
993
        if ref in _FEEL_PRIMITIVE_TYPES:
994
            return _FEEL_PRIMITIVE_TYPES[ref]
995
        if ref in resolved:
996
            return resolved[ref]
997
        if ref in raw:
998
            result = resolve_elem(raw[ref])
999
            if result:
1000
                resolved[ref] = result
1001
            return result
1002
        return None
1003
1004
    def resolve_elem(elem: ET.Element) -> Optional[str]:
1005
        is_collection = elem.get("isCollection", "false").lower() == "true"
1006
        # functionItem: a DRG function-item type, no structural FEEL equivalent.
1007
        if _first_child(elem, "functionItem") is not None:
1008
            return None
1009
        # itemComponent children → context<k: T, …>
1010
        components = [c for c in elem if _local(c.tag) == "itemComponent"]
1011
        if components:
1012
            fields: list[str] = []
1013
            for comp in components:
1014
                cname = comp.get("name", "")
1015
                ctype_elem = _first_child(comp, "typeRef")
1016
                if ctype_elem is None or not ctype_elem.text:
1017
                    return None
1018
                ctype = resolve_typeref(ctype_elem.text.strip())
1019
                if ctype is None:
1020
                    return None
1021
                fields.append(f"{cname}: {ctype}")
1022
            inner = "context<" + ", ".join(fields) + ">"
1023
            return f"list<{inner}>" if is_collection else inner
1024
        # bare typeRef
1025
        typeref_elem = _first_child(elem, "typeRef")
1026
        if typeref_elem is not None and typeref_elem.text:
1027
            inner = resolve_typeref(typeref_elem.text.strip())
1028
            if inner is None:
1029
                return None
1030
            return f"list<{inner}>" if is_collection else inner
1031
        return None
1032
1033
    for name, elem in raw.items():
1034
        if name not in resolved:
1035
            result = resolve_elem(elem)
1036
            if result:
1037
                resolved[name] = result
1038
    return resolved
1039
1040
1041
def _resolve_typeref_to_feel(typeref: Optional[str], item_defs: dict[str, str]) -> Optional[str]:
1042
    """Resolve a DMN ``typeRef`` string to a structural FEEL type string, or
1043
    ``None`` when the reference is absent or unresolvable."""
1044
    if typeref is None:
1045
        return None
1046
    if typeref in _FEEL_PRIMITIVE_TYPES:
1047
        return _FEEL_PRIMITIVE_TYPES[typeref]
1048
    return item_defs.get(typeref)
1049
1050
1051
def parse_decision_typerefs(dmn_path: Path, item_defs: dict[str, str]) -> dict[str, str]:
1052
    """Return a mapping from decision name to resolved FEEL type string for
1053
    decisions that carry a ``<variable typeRef="…">`` or
1054
    ``<literalExpression typeRef="…">``.  The ``literalExpression`` typeRef
1055
    takes precedence (it is more specific than the variable's declared type)."""
1056
    root = ET.parse(dmn_path).getroot()
1057
    result: dict[str, str] = {}
1058
    for elem in root.iter():
1059
        if _local(elem.tag) != "decision":
1060
            continue
1061
        name = elem.get("name")
1062
        if name is None:
1063
            continue
1064
        # Prefer literalExpression typeRef (most specific).
1065
        lit = _first_child(elem, "literalExpression")
1066
        var = _first_child(elem, "variable")
1067
        typeref: Optional[str] = None
1068
        if lit is not None:
1069
            typeref = lit.get("typeRef")
1070
        if typeref is None and var is not None:
1071
            typeref = var.get("typeRef")
1072
        if typeref:
1073
            resolved = _resolve_typeref_to_feel(typeref, item_defs)
1074
            if resolved:
1075
                result[name] = resolved
1076
    return result
1077
1078
1079
@dataclass
1080
class BKMDef:
1081
    """Parsed representation of a ``<businessKnowledgeModel>`` element."""
1082
    name: str
1083
    params: list[tuple[str, Optional[str]]]  # (param_name, feel_type_str | None)
1084
    body: str  # the encapsulated literalExpression text
1085
    return_type: Optional[str] = None  # structural FEEL type from the literalExpression typeRef
1086
1087
1088
def parse_bkms(dmn_path: Path, item_defs: dict[str, str]) -> dict[str, BKMDef]:
1089
    """Parse ``<businessKnowledgeModel>`` elements; return a mapping from BKM
1090
    name to :class:`BKMDef`."""
1091
    root = ET.parse(dmn_path).getroot()
1092
    bkms: dict[str, BKMDef] = {}
1093
    for elem in root.iter():
1094
        if _local(elem.tag) != "businessKnowledgeModel":
1095
            continue
1096
        name = elem.get("name")
1097
        if name is None:
1098
            continue
1099
        logic = _first_child(elem, "encapsulatedLogic")
1100
        if logic is None:
1101
            continue
1102
        lit = _first_child(logic, "literalExpression")
1103
        if lit is None:
1104
            continue
1105
        text_elem = _first_child(lit, "text")
1106
        if text_elem is None or not text_elem.text:
1107
            continue
1108
        body = text_elem.text.strip()
1109
        return_type = _resolve_typeref_to_feel(lit.get("typeRef"), item_defs)
1110
        params: list[tuple[str, Optional[str]]] = []
1111
        for child in logic:
1112
            if _local(child.tag) == "formalParameter":
1113
                p_name = child.get("name", "")
1114
                p_type = _resolve_typeref_to_feel(child.get("typeRef"), item_defs)
1115
                params.append((p_name, p_type))
1116
        bkms[name] = BKMDef(name=name, params=params, body=body, return_type=return_type)
1117
    return bkms
1118
1119
1120
def parse_knowledge_requirements(dmn_path: Path) -> dict[str, list[str]]:
1121
    """Return a mapping from decision name to a list of *BKM* names it requires
1122
    (via ``<knowledgeRequirement><requiredKnowledge href="#…"/>``)`.
1123
1124
    Only ``<businessKnowledgeModel>`` targets are included; references to
1125
    ``<decisionService>`` are silently ignored (DS is out of scope)."""
1126
    root = ET.parse(dmn_path).getroot()
1127
    # Build id -> name for BKMs only.
1128
    id_to_bkm: dict[str, str] = {}
1129
    for elem in root.iter():
1130
        if _local(elem.tag) == "businessKnowledgeModel":
1131
            bkm_id = elem.get("id")
1132
            bkm_name = elem.get("name")
1133
            if bkm_id and bkm_name:
1134
                id_to_bkm[bkm_id] = bkm_name
1135
    result: dict[str, list[str]] = {}
1136
    for elem in root.iter():
1137
        if _local(elem.tag) != "decision":
1138
            continue
1139
        name = elem.get("name")
1140
        if name is None:
1141
            continue
1142
        bkm_names: list[str] = []
1143
        for req in elem:
1144
            if _local(req.tag) == "knowledgeRequirement":
1145
                rk = _first_child(req, "requiredKnowledge")
1146
                if rk is not None:
1147
                    href = rk.get("href", "").lstrip("#")
1148
                    bkm_name = id_to_bkm.get(href)
1149
                    if bkm_name:
1150
                        bkm_names.append(bkm_name)
1151
        if bkm_names:
1152
            result[name] = bkm_names
1153
    return result
1154
1155
1156
def parse_invocation_decisions(
1157
    dmn_path: Path, item_defs: dict[str, str]
1158
) -> dict[str, tuple[str, Optional[str]]]:
1159
    """Parse ``<invocation>`` form decisions; return a mapping from decision name
1160
    to ``(call_expression, coerce_to)`` where:
1161
1162
    * ``call_expression`` is the equivalent FEEL named-argument call, e.g.
1163
      ``bkm_001(nameAndAge: {name: "foo", age: 10})``.
1164
    * ``coerce_to`` is the resolved FEEL type from the ``<invocation typeRef="…">``,
1165
      or ``None`` when absent.
1166
    """
1167
    root = ET.parse(dmn_path).getroot()
1168
    result: dict[str, tuple[str, Optional[str]]] = {}
1169
    for elem in root.iter():
1170
        if _local(elem.tag) != "decision":
1171
            continue
1172
        name = elem.get("name")
1173
        if name is None:
1174
            continue
1175
        invoc = _first_child(elem, "invocation")
1176
        if invoc is None:
1177
            continue
1178
        callee_lit = _first_child(invoc, "literalExpression")
1179
        if callee_lit is None:
1180
            continue
1181
        callee_text = _first_child(callee_lit, "text")
1182
        if callee_text is None or not callee_text.text:
1183
            continue
1184
        callee = callee_text.text.strip()
1185
        args: list[str] = []
1186
        for child in invoc:
1187
            if _local(child.tag) == "binding":
1188
                param = _first_child(child, "parameter")
1189
                lit = _first_child(child, "literalExpression")
1190
                if param is None or lit is None:
1191
                    continue
1192
                param_name = param.get("name", "")
1193
                text_elem = _first_child(lit, "text")
1194
                if text_elem is None or not text_elem.text:
1195
                    continue
1196
                args.append(f"{param_name}: {text_elem.text.strip()}")
1197
        call_expr = f"{callee}({', '.join(args)})"
1198
        coerce_to = _resolve_typeref_to_feel(invoc.get("typeRef"), item_defs)
1199
        result[name] = (call_expr, coerce_to)
1200
    return result
1201
1202
1203
def parse_context_result_decisions(
1204
    dmn_path: Path,
1205
) -> dict[str, tuple[list[tuple[str, str]], str]]:
1206
    """Parse boxed-context decisions that carry a trailing *result cell* — a
1207
    ``<contextEntry>`` with no ``<variable>`` as the final entry.
1208
1209
    Returns a mapping from decision name to ``(named_entries, result_expr)`` where:
1210
1211
    * ``named_entries`` is an ordered list of ``(key, expression)`` pairs for all
1212
      named entries (every entry *except* the last).
1213
    * ``result_expr`` is the FEEL expression text of the unnamed result cell.
1214
1215
    Decisions where every entry has a ``<variable>`` (no result cell), or where
1216
    any entry is malformed, are silently omitted."""
1217
    root = ET.parse(dmn_path).getroot()
1218
    result: dict[str, tuple[list[tuple[str, str]], str]] = {}
1219
    for elem in root.iter():
1220
        if _local(elem.tag) != "decision":
1221
            continue
1222
        name = elem.get("name")
1223
        ctx = _first_child(elem, "context")
1224
        if name is None or ctx is None:
1225
            continue
1226
        all_entries = [c for c in ctx if _local(c.tag) == "contextEntry"]
1227
        if not all_entries:
1228
            continue
1229
        # Last entry must have no <variable> (the result cell).
1230
        last = all_entries[-1]
1231
        if _first_child(last, "variable") is not None:
1232
            continue
1233
        last_lit = _first_child(last, "literalExpression")
1234
        if last_lit is None:
1235
            continue
1236
        last_text = _first_child(last_lit, "text")
1237
        if last_text is None or not last_text.text:
1238
            continue
1239
        result_expr = last_text.text.strip()
1240
        # Extract named entries (all but the last).
1241
        named_entries: list[tuple[str, str]] = []
1242
        ok = True
1243
        for entry in all_entries[:-1]:
1244
            var = _first_child(entry, "variable")
1245
            lit = _first_child(entry, "literalExpression")
1246
            if var is None or lit is None:
1247
                ok = False
1248
                break
1249
            key = var.get("name", "")
1250
            text_elem = _first_child(lit, "text")
1251
            if text_elem is None or not text_elem.text:
1252
                ok = False
1253
                break
1254
            named_entries.append((key, text_elem.text.strip()))
1255
        if ok and result_expr:
1256
            result[name] = (named_entries, result_expr)
1257
    return result
1258
1259
1260
def parse_conditional_decisions(dmn_path: Path) -> dict[str, tuple[str, str, str]]:
1261
    """Parse ``<conditional>`` form decisions; return a mapping from decision name
1262
    to ``(if_expr, then_expr, else_expr)`` where each expression is the FEEL text
1263
    of the corresponding ``<literalExpression><text>`` child.
1264
1265
    Only decisions whose direct logic child is ``<conditional>`` are returned.
1266
    Decisions with a missing or malformed child are silently omitted."""
1267
    root = ET.parse(dmn_path).getroot()
1268
    result: dict[str, tuple[str, str, str]] = {}
1269
    for elem in root.iter():
1270
        if _local(elem.tag) != "decision":
1271
            continue
1272
        name = elem.get("name")
1273
        cond = _first_child(elem, "conditional")
1274
        if name is None or cond is None:
1275
            continue
1276
        if_branch = _first_child(cond, "if")
1277
        then_branch = _first_child(cond, "then")
1278
        else_branch = _first_child(cond, "else")
1279
        if if_branch is None or then_branch is None or else_branch is None:
1280
            continue
1281
        def _text_of(branch: ET.Element) -> Optional[str]:
1282
            lit = _first_child(branch, "literalExpression")
1283
            if lit is None:
1284
                return None
1285
            t = _first_child(lit, "text")
1286
            return t.text.strip() if t is not None and t.text is not None else None
1287
        if_expr = _text_of(if_branch)
1288
        then_expr = _text_of(then_branch)
1289
        else_expr = _text_of(else_branch)
1290
        if if_expr is None or then_expr is None or else_expr is None:
1291
            continue
1292
        result[name] = (if_expr, then_expr, else_expr)
1293
    return result
1294
1295
1296
def parse_filter_decisions(dmn_path: Path) -> dict[str, tuple[str, str]]:
1297
    """Parse ``<filter>`` form decisions; return a mapping from decision name to
1298
    ``(in_expr, match_expr)`` where each expression is the FEEL text of the
1299
    corresponding ``<literalExpression><text>`` child.
1300
1301
    Only decisions whose direct logic child is ``<filter>`` are returned."""
1302
    root = ET.parse(dmn_path).getroot()
1303
    result: dict[str, tuple[str, str]] = {}
1304
    for elem in root.iter():
1305
        if _local(elem.tag) != "decision":
1306
            continue
1307
        name = elem.get("name")
1308
        filt = _first_child(elem, "filter")
1309
        if name is None or filt is None:
1310
            continue
1311
        in_branch = _first_child(filt, "in")
1312
        match_branch = _first_child(filt, "match")
1313
        if in_branch is None or match_branch is None:
1314
            continue
1315
        def _text_of_lit(branch: ET.Element) -> Optional[str]:
1316
            lit = _first_child(branch, "literalExpression")
1317
            if lit is None:
1318
                return None
1319
            t = _first_child(lit, "text")
1320
            return t.text.strip() if t is not None and t.text is not None else None
1321
        in_expr = _text_of_lit(in_branch)
1322
        match_expr = _text_of_lit(match_branch)
1323
        if in_expr is None or match_expr is None:
1324
            continue
1325
        result[name] = (in_expr, match_expr)
1326
    return result
1327
1328
1329
def parse_iterator_decisions(
1330
    dmn_path: Path,
1331
) -> dict[str, tuple[str, str, str, str]]:
1332
    """Parse ``<for>``, ``<some>``, and ``<every>`` form decisions; return a
1333
    mapping from decision name to ``(kind, var, in_expr, body_expr)`` where:
1334
1335
    * ``kind`` is ``"for"``, ``"some"``, or ``"every"``.
1336
    * ``var`` is the ``iteratorVariable`` attribute value.
1337
    * ``in_expr`` is the FEEL text of the ``<in><literalExpression><text>`` cell.
1338
    * ``body_expr`` is the FEEL text of the ``<return>`` (for ``for``) or
1339
      ``<satisfies>`` (for ``some``/``every``) cell.
1340
1341
    Only decisions whose direct logic child is one of the three iterator elements
1342
    are returned. Decisions with missing attributes or cells are silently omitted."""
1343
    _ITERATOR_TAGS = {"for": "return", "some": "satisfies", "every": "satisfies"}
1344
    root = ET.parse(dmn_path).getroot()
1345
    result: dict[str, tuple[str, str, str, str]] = {}
1346
    for elem in root.iter():
1347
        if _local(elem.tag) != "decision":
1348
            continue
1349
        name = elem.get("name")
1350
        if name is None:
1351
            continue
1352
        iter_elem: Optional[ET.Element] = None
1353
        kind: Optional[str] = None
1354
        for tag in _ITERATOR_TAGS:
1355
            child = _first_child(elem, tag)
1356
            if child is not None:
1357
                iter_elem = child
1358
                kind = tag
1359
                break
1360
        if iter_elem is None or kind is None:
1361
            continue
1362
        var = iter_elem.get("iteratorVariable")
1363
        if not var:
1364
            continue
1365
        in_branch = _first_child(iter_elem, "in")
1366
        body_tag = _ITERATOR_TAGS[kind]
1367
        body_branch = _first_child(iter_elem, body_tag)
1368
        if in_branch is None or body_branch is None:
1369
            continue
1370
        def _text_of_iter(branch: ET.Element) -> Optional[str]:
1371
            lit = _first_child(branch, "literalExpression")
1372
            if lit is None:
1373
                return None
1374
            t = _first_child(lit, "text")
1375
            return t.text.strip() if t is not None and t.text is not None else None
1376
        in_expr = _text_of_iter(in_branch)
1377
        body_expr = _text_of_iter(body_branch)
1378
        if in_expr is None or body_expr is None:
1379
            continue
1380
        result[name] = (kind, var, in_expr, body_expr)
1381
    return result
1382
1383
1384
def parse_list_decisions(dmn_path: Path) -> dict[str, list[str]]:
1385
    """Parse ``<list>`` form decisions (boxed list literal); return a mapping from
1386
    decision name to an ordered list of FEEL text strings, one per direct
1387
    ``<literalExpression>`` child of the ``<list>`` element.
1388
1389
    Only decisions whose direct logic child is a ``<list>`` are returned.
1390
    Rows with a missing or empty ``<text>`` are silently omitted from the row
1391
    list; decisions with zero valid rows are excluded."""
1392
    root = ET.parse(dmn_path).getroot()
1393
    result: dict[str, list[str]] = {}
1394
    for elem in root.iter():
1395
        if _local(elem.tag) != "decision":
1396
            continue
1397
        name = elem.get("name")
1398
        lst = _first_child(elem, "list")
1399
        if name is None or lst is None:
1400
            continue
1401
        rows: list[str] = []
1402
        for child in lst:
1403
            if _local(child.tag) != "literalExpression":
1404
                continue
1405
            t = _first_child(child, "text")
1406
            if t is None or not t.text:
1407
                continue
1408
            rows.append(t.text.strip())
1409
        if rows:
1410
            result[name] = rows
1411
    return result
1412
1413
1414
def _inline_bkms(
1415
    call_expr: str,
1416
    bkm_names: frozenset[str],
1417
    bkms: dict[str, BKMDef],
1418
) -> tuple[str, Optional[str]]:
1419
    """Inline the named BKMs as FEEL function literals in a context literal
1420
    wrapping ``call_expr``, then project the result via the synthetic
1421
    ``__result`` key.
1422
1423
    Output form::
1424
1425
        {bkm1: function(p: T, …) body1, …, __result: call_expr}.__result
1426
1427
    Returns ``(assembled_expression, bkm_return_type)`` where ``bkm_return_type``
1428
    is the return type of the *first* BKM that declares one (``None`` otherwise)
1429
    — used as a ``coerce_to`` fallback when neither the invocation nor the
1430
    decision variable carries an explicit ``typeRef``."""
1431
    entries: list[str] = []
1432
    bkm_return_type: Optional[str] = None
1433
    for bkm_name in sorted(bkm_names):  # deterministic output order
1434
        bkm = bkms[bkm_name]
1435
        param_parts: list[str] = []
1436
        for p_name, p_type in bkm.params:
1437
            param_parts.append(f"{p_name}: {p_type}" if p_type else p_name)
1438
        fn_literal = f"function({', '.join(param_parts)}) {bkm.body}"
1439
        entries.append(f"{bkm_name}: {fn_literal}")
1440
        if bkm.return_type is not None and bkm_return_type is None:
1441
            bkm_return_type = bkm.return_type
1442
    entries.append(f"__result: {call_expr}")
1443
    return "{" + ", ".join(entries) + "}.__result", bkm_return_type
1444
1445
1446
_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
1447
1448
1449
def _first_child(elem: ET.Element, *names: str) -> Optional[ET.Element]:
1450
    """First direct child whose local tag is one of `names`."""
1451
    for child in elem:
1452
        if _local(child.tag) in names:
1453
            return child
1454
    return None
1455
1456
1457
def parse_value_elem(value_elem: ET.Element) -> tuple[object, str]:
1458
    """Parse a scalar <value> element -> (python value, type)."""
1459
    if value_elem.get(f"{_XSI}nil") == "true":
1460
        return None, "null"
1461
    xsi_type = value_elem.get(f"{_XSI}type", "")
1462
    raw = value_elem.text or ""
1463
    text = raw.strip()
1464
    # A declared string type is authoritative: a string result like "2" must not
1465
    # be mis-read as the number 2 (e.g. `string(2)` returns the string "2").  It must
1466
    # also win over the boolean text heuristic so `<value xsi:type="xsd:string">true</value>`
1467
    # is the string "true", not the boolean true.  Keep the raw text un-stripped — a
1468
    # string result may legitimately be whitespace (e.g. `substring("foob r", -2, 1) = " "`).
1469
    if xsi_type.endswith("string"):
1470
        return raw, "string"
1471
    if xsi_type.endswith("boolean") or text in ("true", "false"):
1472
        return text == "true", "boolean"
1473
    # Temporal types (ADR-18). The lexical text is the canonical ISO-8601 form
1474
    # feel-core round-trips. Check dateTime before date/time (it ends with "time"
1475
    # and contains "date"). XSD uses one `duration` for both FEEL duration kinds;
1476
    # feel-core re-derives the kind from the lexical form, so one tag suffices.
1477
    low = xsi_type.lower()
1478
    if low.endswith("datetime"):
1479
        return text, "date and time"
1480
    if low.endswith("date"):
1481
        return text, "date"
1482
    if low.endswith("time"):
1483
        return text, "time"
1484
    if low.endswith("duration"):
1485
        return text, "duration"
1486
    # decimal / double / integer, or anything that parses as a number
1487
    try:
1488
        return float(text), "number"
1489
    except ValueError:
1490
        return text, "string"
1491
1492
1493
def parse_expected_node(node: ET.Element) -> tuple[object, str]:
1494
    """Parse an <expected>/<item>/<component> node (recursive): a scalar <value>,
1495
    a <list> of items, or a context expressed as one-or-more <component name="…">
1496
    children (-> dict, e.g. the `{key, value}` entries `get entries` returns)."""
1497
    child = _first_child(node, "value", "list")
1498
    if child is None:
1499
        components = [c for c in node if _local(c.tag) == "component"]
1500
        if components:
1501
            return {c.get("name"): parse_expected_node(c)[0] for c in components}, "context"
1502
        return None, "null"
1503
    if _local(child.tag) == "value":
1504
        return parse_value_elem(child)
1505
    # <list><item>...</item>...</list> -> a (possibly nested) JSON array.
1506
    items = [parse_expected_node(it)[0] for it in child if _local(it.tag) == "item"]
1507
    return items, "list"
1508
1509
1510
def parse_expected(result_node: ET.Element) -> tuple[object, str]:
1511
    """Extract (value, type) from a <resultNode>'s <expected> (scalar or list)."""
1512
    expected = _first_child(result_node, "expected")
1513
    if expected is None:
1514
        return None, "null"
1515
    return parse_expected_node(expected)
1516
1517
1518
def parse_input_value(node: ET.Element) -> object:
1519
    """Parse an <inputNode>/<item>/<component> into a JSON-serialisable value.
1520
1521
    Scalars come from a <value> child, lists from <list><item>…</item></list>,
1522
    and contexts from one-or-more <component name="…"> children (-> dict)."""
1523
    value_child = _first_child(node, "value")
1524
    if value_child is not None:
1525
        val, typ = parse_value_elem(value_child)
1526
        # A temporal input is tagged so the fixture context can bind it as a
1527
        # typed temporal value rather than a plain string (ADR-18).
1528
        if typ in ("date", "time", "date and time", "duration"):
1529
            return {"@type": typ, "@value": val}
1530
        return val
1531
    list_child = _first_child(node, "list")
1532
    if list_child is not None:
1533
        return [parse_input_value(it) for it in list_child if _local(it.tag) == "item"]
1534
    components = [c for c in node if _local(c.tag) == "component"]
1535
    if components:
1536
        return {c.get("name"): parse_input_value(c) for c in components}
1537
    return None  # nil / empty input
1538
1539
1540
def parse_inputs(test_case: ET.Element) -> dict:
1541
    """Map each direct <inputNode name="…"> of a testCase to its JSON value."""
1542
    inputs: dict = {}
1543
    for child in test_case:
1544
        if _local(child.tag) == "inputNode":
1545
            name = child.get("name")
1546
            if name:
1547
                inputs[name] = parse_input_value(child)
1548
    return inputs
1549
1550
1551
def collect_context_keys(value: object) -> set[str]:
1552
    """Every context (component) key appearing anywhere in an input value. Inside a
1553
    filter over a list of contexts these keys are referenceable without an `item.`
1554
    prefix (`Employees[dept = 20]`), and via path access generally (§10.3.2.5), so
1555
    they are bound names for the slice detector — not free identifiers. The `@type`/
1556
    `@value` keys of a tagged temporal input never appear in expressions and contain
1557
    `@`, so they are harmless even if collected."""
1558
    keys: set[str] = set()
1559
    if isinstance(value, dict):
1560
        for k, v in value.items():
1561
            keys.add(k)
1562
            keys |= collect_context_keys(v)
1563
    elif isinstance(value, list):
1564
        for v in value:
1565
            keys |= collect_context_keys(v)
1566
    return keys
1567
1568
1569
def extract_cases(dmn_path: Path, test_path: Path) -> tuple[list[Case], list[tuple[str, str]]]:
1570
    """Return (kept cases, skipped (id, reason) pairs)."""
1571
    # Parse type infrastructure for coerce_to resolution.
1572
    item_defs = parse_item_definitions(dmn_path)
1573
    decision_typerefs = parse_decision_typerefs(dmn_path, item_defs)
1574
    # Parse decision expressions (eight forms).
1575
    decisions = parse_decisions(dmn_path)
1576
    context_decisions = parse_context_decisions(dmn_path)
1577
    context_result_decisions = parse_context_result_decisions(dmn_path)
1578
    bkms = parse_bkms(dmn_path, item_defs)
1579
    knowledge_reqs = parse_knowledge_requirements(dmn_path)
1580
    invocation_decisions = parse_invocation_decisions(dmn_path, item_defs)
1581
    # Boxed element-form decisions (DMN 1.5 §10.2.1.5 / §10.2.1.8–10).
1582
    conditional_decisions = parse_conditional_decisions(dmn_path)
1583
    filter_decisions = parse_filter_decisions(dmn_path)
1584
    iterator_decisions = parse_iterator_decisions(dmn_path)
1585
    list_decisions = parse_list_decisions(dmn_path)
1586
    model_stem = dmn_path.stem
1587
1588
    root = ET.parse(test_path).getroot()
1589
    kept: list[Case] = []
1590
    skipped: list[tuple[str, str]] = []
1591
1592
    for test_case in root.iter():
1593
        if _local(test_case.tag) != "testCase":
1594
            continue
1595
        tc_id = test_case.get("id", "?")
1596
        # A decision-service test case (`type="decisionService"`) invokes a whole
1597
        # DRG decision service, not a standalone literal expression: its result is
1598
        # governed by service encapsulation (an output not exposed by the service is
1599
        # null, regardless of the underlying decision's literal). feel-core is a FEEL
1600
        # *expression* engine with no DRG, so extracting the bare expression would
1601
        # compare against the service's value, not the expression's. Skip the whole
1602
        # case structurally (the expression-only siblings in the same dir are kept).
1603
        if test_case.get("type") == "decisionService":
1604
            skipped.append((tc_id, "decision-service invocation (DRG, out of scope)"))
1605
            continue
1606
        inputs = parse_inputs(test_case)
1607
        # Input node names plus the context keys of their (possibly nested, possibly
1608
        # list-element) values: all are bound names a filter/path may reference.
1609
        member_keys: set[str] = set()
1610
        for value in inputs.values():
1611
            member_keys |= collect_context_keys(value)
1612
        input_names = frozenset(inputs) | member_keys
1613
        for result_node in test_case.iter():
1614
            if _local(result_node.tag) != "resultNode":
1615
                continue
1616
            name = result_node.get("name")
1617
            if name is None:
1618
                continue
1619
1620
            expression: Optional[str] = None
1621
            case_coerce_to: Optional[str] = None
1622
            case_id = f"{model_stem}:{tc_id}:{name}"
1623
1624
            # ----------------------------------------------------------------- #
1625
            # Resolve the decision to an expression (eight forms):               #
1626
            #                                                                     #
1627
            # 1. Literal-expression decision (possibly BKM-backed)               #
1628
            # 2. Boxed-context decision with no result cell                      #
1629
            # 3. Boxed-context decision with a trailing result cell (fd_*)       #
1630
            # 4. Invocation-form decision                                         #
1631
            # 5. Boxed-conditional decision (<conditional> element form)         #
1632
            # 6. Boxed-filter decision (<filter> element form)                   #
1633
            # 7. Boxed-iterator decision (<for>/<some>/<every> element forms)    #
1634
            # 8. Boxed-list decision (<list> element form)                       #
1635
            # ----------------------------------------------------------------- #
1636
1637
            if name in decisions:
1638
                raw_expr = decisions[name]
1639
                bkm_names = frozenset(knowledge_reqs.get(name, []))
1640
                if bkm_names:
1641
                    # BKM-backed literal-expression: check the raw call expression
1642
                    # with the BKM names treated as bound names, then inline.
1643
                    if not fits_slice_grammar(raw_expr, input_names | bkm_names):
1644
                        skipped.append((case_id, f"outside slice grammar: {raw_expr!r}"))
1645
                        continue
1646
                    # Also validate each BKM body against its own param names.
1647
                    bkm_body_ok = True
1648
                    for bkm_name in bkm_names:
1649
                        bkm = bkms.get(bkm_name)
1650
                        if bkm is None:
1651
                            bkm_body_ok = False
1652
                            break
1653
                        bkm_param_names = frozenset(p for p, _ in bkm.params)
1654
                        if not fits_slice_grammar(bkm.body, bkm_param_names):
1655
                            bkm_body_ok = False
1656
                            break
1657
                    if not bkm_body_ok:
1658
                        skipped.append((case_id, f"BKM body outside slice for {name!r}"))
1659
                        continue
1660
                    expression, bkm_return_type = _inline_bkms(raw_expr, bkm_names, bkms)
1661
                    # coerce_to priority: decision variable typeRef > BKM return typeRef
1662
                    case_coerce_to = decision_typerefs.get(name) or bkm_return_type
1663
                else:
1664
                    # NB: `errorResult="true"` is *not* skipped wholesale. Many such
1665
                    # cases are genuine expression errors feel-core reproduces (a
1666
                    # malformed regex, a bad argument → error-null, collapsed to null at
1667
                    # the lenient boundary, which matches the expected nil) — valuable
1668
                    # coverage. The few where the error comes from DMN *decision
1669
                    # output-type* validation rather than the expression are handled via
1670
                    # the `coerce_to` mechanism (0082-feel-coercion).
1671
                    if not fits_slice_grammar(raw_expr, input_names):
1672
                        skipped.append((case_id, f"outside slice grammar: {raw_expr!r}"))
1673
                        continue
1674
                    expression = raw_expr
1675
                    case_coerce_to = decision_typerefs.get(name)
1676
1677
            elif name in context_decisions:
1678
                entries = context_decisions[name]
1679
                skip_reason: Optional[str] = None
1680
                for key, entry_expr in entries:
1681
                    if not fits_slice_grammar(entry_expr, input_names):
1682
                        skip_reason = f"context entry {key!r} outside slice: {entry_expr!r}"
1683
                        break
1684
                if skip_reason:
1685
                    skipped.append((case_id, skip_reason))
1686
                    continue
1687
                expression = "{" + ", ".join(f"{k}: {e}" for k, e in entries) + "}"
1688
                # Regular boxed-context decisions carry no result-cell coercion.
1689
1690
            elif name in context_result_decisions:
1691
                # Boxed-context with a trailing unnamed result cell:
1692
                #   {k1: e1, …, __result: result_expr}.__result
1693
                named_entries, result_expr = context_result_decisions[name]
1694
                prior_keys = frozenset(k for k, _ in named_entries)
1695
                skip_reason2: Optional[str] = None
1696
                for key, entry_expr in named_entries:
1697
                    if not fits_slice_grammar(entry_expr, input_names):
1698
                        skip_reason2 = f"context entry {key!r} outside slice: {entry_expr!r}"
1699
                        break
1700
                if not skip_reason2 and not fits_slice_grammar(
1701
                    result_expr, input_names | prior_keys
1702
                ):
1703
                    skip_reason2 = f"result cell outside slice: {result_expr!r}"
1704
                if skip_reason2:
1705
                    skipped.append((case_id, skip_reason2))
1706
                    continue
1707
                all_entries = list(named_entries) + [("__result", result_expr)]
1708
                expression = "{" + ", ".join(f"{k}: {e}" for k, e in all_entries) + "}.__result"
1709
                case_coerce_to = decision_typerefs.get(name)
1710
1711
            elif name in invocation_decisions:
1712
                call_expr, inv_coerce_to = invocation_decisions[name]
1713
                bkm_names = frozenset(knowledge_reqs.get(name, []))
1714
                # The call names a BKM directly; treat BKM names as bound during
1715
                # the slice check of the call expression.
1716
                if not fits_slice_grammar(call_expr, input_names | bkm_names):
1717
                    skipped.append((case_id, f"outside slice grammar: {call_expr!r}"))
1718
                    continue
1719
                # Validate each BKM body.
1720
                bkm_body_ok2 = True
1721
                for bkm_name in bkm_names:
1722
                    bkm = bkms.get(bkm_name)
1723
                    if bkm is None:
1724
                        bkm_body_ok2 = False
1725
                        break
1726
                    bkm_param_names = frozenset(p for p, _ in bkm.params)
1727
                    if not fits_slice_grammar(bkm.body, bkm_param_names):
1728
                        bkm_body_ok2 = False
1729
                        break
1730
                if not bkm_body_ok2:
1731
                    skipped.append((case_id, f"BKM body outside slice for {name!r}"))
1732
                    continue
1733
                expression, bkm_return_type2 = _inline_bkms(call_expr, bkm_names, bkms)
1734
                # coerce_to priority: invocation typeRef > BKM return typeRef > variable typeRef
1735
                case_coerce_to = inv_coerce_to or bkm_return_type2 or decision_typerefs.get(name)
1736
1737
            elif name in conditional_decisions:
1738
                # Boxed conditional: if (IF) then (THEN) else (ELSE)
1739
                if_expr, then_expr, else_expr = conditional_decisions[name]
1740
                assembled = f"if ({if_expr}) then ({then_expr}) else ({else_expr})"
1741
                if not fits_slice_grammar(assembled, input_names):
1742
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
1743
                    continue
1744
                expression = assembled
1745
                case_coerce_to = decision_typerefs.get(name)
1746
1747
            elif name in filter_decisions:
1748
                # Boxed filter: (IN)[MATCH]  (predicate uses `item`)
1749
                in_expr, match_expr = filter_decisions[name]
1750
                assembled = f"({in_expr})[{match_expr}]"
1751
                # `item` is always bound in filter scope; include it so the slice
1752
                # detector does not reject its implicit use inside `match_expr`.
1753
                if not fits_slice_grammar(assembled, input_names | frozenset({"item"})):
1754
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
1755
                    continue
1756
                expression = assembled
1757
                case_coerce_to = decision_typerefs.get(name)
1758
1759
            elif name in iterator_decisions:
1760
                # Boxed iterator: for VAR in (IN) return (BODY)
1761
                #                 some/every VAR in (IN) satisfies (BODY)
1762
                kind, var, in_expr, body_expr = iterator_decisions[name]
1763
                if kind == "for":
1764
                    assembled = f"for {var} in ({in_expr}) return ({body_expr})"
1765
                else:
1766
                    assembled = f"{kind} {var} in ({in_expr}) satisfies ({body_expr})"
1767
                # The iterator variable is bound inside the body; include it in the
1768
                # slice check so the grammar detector treats it as known.
1769
                iter_bound = input_names | frozenset({var})
1770
                if not fits_slice_grammar(assembled, iter_bound):
1771
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
1772
                    continue
1773
                expression = assembled
1774
                case_coerce_to = decision_typerefs.get(name)
1775
1776
            elif name in list_decisions:
1777
                # Boxed list literal: [row1, row2, …]
1778
                rows = list_decisions[name]
1779
                assembled = "[" + ", ".join(rows) + "]"
1780
                if not fits_slice_grammar(assembled, input_names):
1781
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
1782
                    continue
1783
                expression = assembled
1784
                case_coerce_to = decision_typerefs.get(name)
1785
1786
            else:
1787
                continue
1788
1789
            if case_id in REGEX_DIALECT_SKIPS:
1790
                skipped.append((case_id, "regex-xpath-dialect deviation"))
1791
                continue
1792
1793
            if case_id in TEMPORAL_RANGE_SKIPS:
1794
                skipped.append((case_id, "temporal value outside jiff's range (ADR-18)"))
1795
                continue
1796
1797
            if case_id in TEMPORAL_SUBSECOND_EQUALITY_SKIPS:
1798
                skipped.append((case_id, "second-resolution temporal equality (ADR-18)"))
1799
                continue
1800
1801
            if case_id in CROSS_TYPE_EQUALITY_SKIPS:
1802
                skipped.append((case_id, "cross-type `=` is error-null in feel-core, not false (ADR-14)"))
1803
                continue
1804
1805
            if case_id in NAMED_ARG_OVERLOAD_SKIPS:
1806
                skipped.append((case_id, "named-arg overload not in feel-core's param table (ADR-23)"))
1807
                continue
1808
1809
            if case_id in TEMPORAL_FOR_RANGE_SKIPS:
1810
                skipped.append((case_id, "date `for` range iteration not implemented (integer ranges only)"))
1811
                continue
1812
1813
            if case_id in OUT_OF_SCOPE_EXPR_SKIPS:
1814
                skipped.append((case_id, "expected result needs a DMN feature outside a FEEL-expression engine"))
1815
                continue
1816
1817
            if case_id in TZDB_ZONE_SKIPS:
1818
                skipped.append((case_id, "named zone not resolvable in this build's tzdb (ADR-18)"))
1819
                continue
1820
1821
            if case_id in NON_XID_NAME_SKIPS:
1822
                skipped.append((case_id, "emoji / non-XID bare name not in the slice (ADR-17)"))
1823
                continue
1824
1825
            if case_id in DECIMAL_LIST_SKIPS:
1826
                skipped.append((
1827
                    case_id,
1828
                    "list of decimal128 numbers — f64_epsilon mode only covers scalar results; "
1829
                    "element-wise epsilon for list results not yet supported by the harness",
1830
                ))
1831
                continue
1832
1833
            if case_id in BOXED_PREDICATE_DEVIATION_SKIPS:
1834
                skipped.append((
1835
                    case_id,
1836
                    "boxed predicate deviation: non-true filter predicate drops element "
1837
                    "(ADR-24) / some short-circuits on true before non-boolean taint (ADR-13/14)",
1838
                ))
1839
                continue
1840
1841
            expected, expected_type = parse_expected(result_node)
1842
1843
            case = Case(
1844
                id=case_id,
1845
                expression=expression,
1846
                expected=expected,
1847
                expected_type=expected_type,
1848
                coerce_to=case_coerce_to,
1849
                context=inputs,
1850
            )
1851
            apply_deviations(case)
1852
            kept.append(case)
1853
1854
    kept.sort(key=lambda c: c.id)
1855
    return kept, skipped
1856
1857
1858
# --------------------------------------------------------------------------- #
1859
# CLI
1860
# --------------------------------------------------------------------------- #
1861
1862
1863
def main(argv: Optional[list[str]] = None) -> int:
1864
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1865
    parser.add_argument("path", type=Path, help="TCK test directory or .dmn file")
1866
    parser.add_argument("-o", "--output", type=Path, required=True, help="fixture JSON output path")
1867
    args = parser.parse_args(argv)
1868
1869
    dmn_path, test_path = resolve_inputs(args.path)
1870
    cases, skipped = extract_cases(dmn_path, test_path)
1871
1872
    if not cases:
1873
        print("No cases matched the slice grammar — nothing written.", file=sys.stderr)
1874
        for case_id, reason in skipped:
1875
            print(f"  skipped {case_id}: {reason}", file=sys.stderr)
1876
        return 1
1877
1878
    args.output.parent.mkdir(parents=True, exist_ok=True)
1879
    fixture = [c.to_fixture() for c in cases]
1880
    args.output.write_text(json.dumps(fixture, indent=2) + "\n", encoding="utf-8")
1881
1882
    # ----------------------------- summary --------------------------------- #
1883
    print(f"DMN model:   {dmn_path}")
1884
    print(f"Test cases:  {test_path}")
1885
    print(f"Fixture:     {args.output}  ({len(cases)} case(s))")
1886
    print()
1887
    print("Processed cases:")
1888
    for case in cases:
1889
        extra = f"  (epsilon={case.epsilon})" if case.epsilon is not None else ""
1890
        print(f"  + {case.id}: {case.expression!r} -> {case.expected} "
1891
              f"[{case.expected_type}, {case.comparison}]{extra}")
1892
    print()
1893
    print("Deviation rules:")
1894
    for rule in DEVIATION_RULES:
1895
        status = f"applied to {rule.applied_count} case(s)" if rule.applied_count else "not applied"
1896
        print(f"  - {rule.name}: {status}")
1897
    if skipped:
1898
        print()
1899
        print(f"Skipped {len(skipped)} decision(s) outside the slice:")
1900
        for case_id, reason in skipped:
1901
            print(f"  - {case_id}: {reason}")
1902
    return 0
1903
1904
1905
if __name__ == "__main__":
1906
    raise SystemExit(main())