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 · 88.6 KB · at 90f493059be5 · raw

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