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