Public repository: timo / feel

Reader

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

feat(ingester): BKM inlining, coerce_to, and boxed-context result cell (0082)

public

feat(ingester): BKM inlining, coerce_to, and boxed-context result cell (0082)

Three new capabilities, all needed to ingest 0082-feel-coercion:

1. **`coerce_to` emission** — resolves DMN `<itemDefinition>` elements into
   structural FEEL type strings (`tNameAndAge` → `context<name: string, age:
   number>`, `tNumberList` → `list<number>`, etc.) and emits `"coerce_to"` on
   fixture cases where a decision variable or literalExpression carries a
   `typeRef`. The fixture harness then calls `coerce(result, parse_type(coerce_to))`
   after evaluation, modelling the §10.3.2.9.4 target-type boundary.

2. **BKM inlining** — parses `<businessKnowledgeModel>` elements and inlines
   them as FEEL function literals in a synthetic context wrapper:
   `{bkm: function(p: T) body, __result: call_expr}.__result`. Supports both
   plain BKM-backed literal-expression decisions (`decision_bkm_*`) and
   `<invocation>`-form decisions (`invoke_*`). The BKM's return `typeRef`
   (when present) becomes `coerce_to` for the assembled case.

3. **Boxed-context result cell** — `parse_context_result_decisions` detects a
   trailing `<contextEntry>` with no `<variable>` (the DMN result value cell)
   and emits `{named_entries…, __result: result_expr}.__result`, enabling
   `fd_001` and `fd_002`.

4. **`fits_slice_grammar` fix** — `_fn_literal_params_and_blank` now handles
   typed formal parameters like `function(arg: number)` and
   `function(ctx: context<name: string, age: number>)`. Crucially, this helper
   is now called BEFORE the context-key blanker, since `arg: number` would
   otherwise look like a `key: value` pair to the key regex, destroying the
   param name before it could be recorded as bound.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changeset2da91afd632552dadc8258c3b3261c580bf7655e
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents7a63712efc96
Children
Pushlog
by timo via ssh

modified tools/ingest_tck.py +534 −38

@@ -261,6 +261,73 @@
261261
     return "".join(out)
262262
 
263263
 
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
+
264331
 def fits_slice_grammar(expression: str, input_names: frozenset[str] = frozenset()) -> bool:
265332
     """True if feel-core's core-language grammar can parse AND evaluate
266333
     `expression` against a context built from `input_names` (the case's
@@ -356,6 +423,15 @@
356423
         " ",
357424
         s,
358425
     )  # 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)
359435
     # Drop context-literal keys and named-argument parameter names (`key:`). Both
360436
     # may be multi-word FEEL names (`{full name: …}`, `substring(start position: …)`,
361437
     # `number(decimal separator: …)`), so consume the whole space-separated run up to
@@ -383,28 +459,6 @@
383459
     # (DMN §10.3.2.5). It is only in scope inside a `[…]`, but allowing it globally
384460
     # here is a safe over-approximation: an `item` used outside a filter would just
385461
     # evaluate to null, and the TCK filter cases all reference it inside `[…]`.
386
-    # Untyped function literals `function(p1, p2) body` (FEEL rule 55, ADR-23):
387
-    # formal parameter names are not free identifiers — they are bound by the literal.
388
-    # Collect them, add to `allowed`, and blank the `function(…)` head so the body
389
-    # can be scanned with the params treated as bound names.
390
-    #
391
-    # Only bare (untyped) comma-separated identifiers are accepted: a `:` in the
392
-    # parameter list (`function(a: number)`) does NOT match and keeps the expression
393
-    # outside the auto-ingested slice (TCK suites 0013-sort and 1155 use only bare
394
-    # params, so this suffices). Zero-param `function()` blanks the head without
395
-    # adding any names. `function` as a *call head* (not a literal) is not a built-in
396
-    # and never appears in auto-ingestible expressions, so the pattern exclusively
397
-    # targets literal `function(...)` bodies.
398
-    _fn_literal_pat = (
399
-        r"\bfunction\s*\(\s*([A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*\s*)?\)"
400
-    )
401
-    fn_params: set = set()
402
-    for _m in re.finditer(_fn_literal_pat, scan):
403
-        _ps = (_m.group(1) or "").strip()
404
-        if _ps:
405
-            for _p in _ps.split(","):
406
-                fn_params.add(_p.strip())
407
-    scan = re.sub(_fn_literal_pat, " ", scan)
408462
     allowed = _KEYWORDS | {"item"} | bound | set(input_names) | fn_params
409463
     idents = re.findall(r"[A-Za-z_]\w*", scan)
410464
     if any(tok not in allowed for tok in idents):
@@ -467,6 +521,12 @@
467521
     comparison: str = "exact"
468522
     deviation: Optional[str] = None
469523
     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
470530
     # The case's `<inputNode>` values, mapped name -> JSON value. Bound as the
471531
     # evaluation context by the fixture test. Omitted from the fixture if empty.
472532
     context: dict = field(default_factory=dict)
@@ -480,6 +540,8 @@
480540
             "comparison": self.comparison,
481541
             "deviation": self.deviation,
482542
         }
543
+        if self.coerce_to is not None:
544
+            out["coerce_to"] = self.coerce_to
483545
         if self.context:
484546
             out["context"] = self.context
485547
         if self.epsilon is not None:
@@ -849,6 +911,346 @@
849911
     return result
850912
 
851913
 
914
+# --------------------------------------------------------------------------- #
915
+# 0082-specific: typeRef resolution, BKM parsing, invocation form, result cell
916
+# --------------------------------------------------------------------------- #
917
+
918
+# Primitive FEEL type names that appear as `typeRef` strings in DMN without a
919
+# matching `<itemDefinition>`.
920
+_FEEL_PRIMITIVE_TYPES: dict[str, str] = {
921
+    "string": "string",
922
+    "number": "number",
923
+    "boolean": "boolean",
924
+    "date": "date",
925
+    "time": "time",
926
+    "date and time": "date and time",
927
+    "years and months duration": "years and months duration",
928
+    "days and time duration": "days and time duration",
929
+    "Any": "Any",
930
+    "Null": "Null",
931
+}
932
+
933
+
934
+def parse_item_definitions(dmn_path: Path) -> dict[str, str]:
935
+    """Parse ``<itemDefinition>`` elements and return a mapping from definition
936
+    name to structural FEEL type string.
937
+
938
+    Handles:
939
+    * ``isCollection="true"`` → ``list<inner>``
940
+    * ``<itemComponent>`` children → ``context<k: T, …>``
941
+    * bare ``<typeRef>`` → primitive pass-through or recursive lookup
942
+    * ``<functionItem>`` → skipped (DRG function-item type, no FEEL structural form)
943
+    """
944
+    root = ET.parse(dmn_path).getroot()
945
+    raw: dict[str, ET.Element] = {}
946
+    for elem in root.iter():
947
+        if _local(elem.tag) == "itemDefinition":
948
+            name = elem.get("name")
949
+            if name:
950
+                raw[name] = elem
951
+
952
+    resolved: dict[str, str] = {}
953
+
954
+    def resolve_typeref(ref: str) -> Optional[str]:
955
+        if ref in _FEEL_PRIMITIVE_TYPES:
956
+            return _FEEL_PRIMITIVE_TYPES[ref]
957
+        if ref in resolved:
958
+            return resolved[ref]
959
+        if ref in raw:
960
+            result = resolve_elem(raw[ref])
961
+            if result:
962
+                resolved[ref] = result
963
+            return result
964
+        return None
965
+
966
+    def resolve_elem(elem: ET.Element) -> Optional[str]:
967
+        is_collection = elem.get("isCollection", "false").lower() == "true"
968
+        # functionItem: a DRG function-item type, no structural FEEL equivalent.
969
+        if _first_child(elem, "functionItem") is not None:
970
+            return None
971
+        # itemComponent children → context<k: T, …>
972
+        components = [c for c in elem if _local(c.tag) == "itemComponent"]
973
+        if components:
974
+            fields: list[str] = []
975
+            for comp in components:
976
+                cname = comp.get("name", "")
977
+                ctype_elem = _first_child(comp, "typeRef")
978
+                if ctype_elem is None or not ctype_elem.text:
979
+                    return None
980
+                ctype = resolve_typeref(ctype_elem.text.strip())
981
+                if ctype is None:
982
+                    return None
983
+                fields.append(f"{cname}: {ctype}")
984
+            inner = "context<" + ", ".join(fields) + ">"
985
+            return f"list<{inner}>" if is_collection else inner
986
+        # bare typeRef
987
+        typeref_elem = _first_child(elem, "typeRef")
988
+        if typeref_elem is not None and typeref_elem.text:
989
+            inner = resolve_typeref(typeref_elem.text.strip())
990
+            if inner is None:
991
+                return None
992
+            return f"list<{inner}>" if is_collection else inner
993
+        return None
994
+
995
+    for name, elem in raw.items():
996
+        if name not in resolved:
997
+            result = resolve_elem(elem)
998
+            if result:
999
+                resolved[name] = result
1000
+    return resolved
1001
+
1002
+
1003
+def _resolve_typeref_to_feel(typeref: Optional[str], item_defs: dict[str, str]) -> Optional[str]:
1004
+    """Resolve a DMN ``typeRef`` string to a structural FEEL type string, or
1005
+    ``None`` when the reference is absent or unresolvable."""
1006
+    if typeref is None:
1007
+        return None
1008
+    if typeref in _FEEL_PRIMITIVE_TYPES:
1009
+        return _FEEL_PRIMITIVE_TYPES[typeref]
1010
+    return item_defs.get(typeref)
1011
+
1012
+
1013
+def parse_decision_typerefs(dmn_path: Path, item_defs: dict[str, str]) -> dict[str, str]:
1014
+    """Return a mapping from decision name to resolved FEEL type string for
1015
+    decisions that carry a ``<variable typeRef="…">`` or
1016
+    ``<literalExpression typeRef="…">``.  The ``literalExpression`` typeRef
1017
+    takes precedence (it is more specific than the variable's declared type)."""
1018
+    root = ET.parse(dmn_path).getroot()
1019
+    result: dict[str, str] = {}
1020
+    for elem in root.iter():
1021
+        if _local(elem.tag) != "decision":
1022
+            continue
1023
+        name = elem.get("name")
1024
+        if name is None:
1025
+            continue
1026
+        # Prefer literalExpression typeRef (most specific).
1027
+        lit = _first_child(elem, "literalExpression")
1028
+        var = _first_child(elem, "variable")
1029
+        typeref: Optional[str] = None
1030
+        if lit is not None:
1031
+            typeref = lit.get("typeRef")
1032
+        if typeref is None and var is not None:
1033
+            typeref = var.get("typeRef")
1034
+        if typeref:
1035
+            resolved = _resolve_typeref_to_feel(typeref, item_defs)
1036
+            if resolved:
1037
+                result[name] = resolved
1038
+    return result
1039
+
1040
+
1041
+@dataclass
1042
+class BKMDef:
1043
+    """Parsed representation of a ``<businessKnowledgeModel>`` element."""
1044
+    name: str
1045
+    params: list[tuple[str, Optional[str]]]  # (param_name, feel_type_str | None)
1046
+    body: str  # the encapsulated literalExpression text
1047
+    return_type: Optional[str] = None  # structural FEEL type from the literalExpression typeRef
1048
+
1049
+
1050
+def parse_bkms(dmn_path: Path, item_defs: dict[str, str]) -> dict[str, BKMDef]:
1051
+    """Parse ``<businessKnowledgeModel>`` elements; return a mapping from BKM
1052
+    name to :class:`BKMDef`."""
1053
+    root = ET.parse(dmn_path).getroot()
1054
+    bkms: dict[str, BKMDef] = {}
1055
+    for elem in root.iter():
1056
+        if _local(elem.tag) != "businessKnowledgeModel":
1057
+            continue
1058
+        name = elem.get("name")
1059
+        if name is None:
1060
+            continue
1061
+        logic = _first_child(elem, "encapsulatedLogic")
1062
+        if logic is None:
1063
+            continue
1064
+        lit = _first_child(logic, "literalExpression")
1065
+        if lit is None:
1066
+            continue
1067
+        text_elem = _first_child(lit, "text")
1068
+        if text_elem is None or not text_elem.text:
1069
+            continue
1070
+        body = text_elem.text.strip()
1071
+        return_type = _resolve_typeref_to_feel(lit.get("typeRef"), item_defs)
1072
+        params: list[tuple[str, Optional[str]]] = []
1073
+        for child in logic:
1074
+            if _local(child.tag) == "formalParameter":
1075
+                p_name = child.get("name", "")
1076
+                p_type = _resolve_typeref_to_feel(child.get("typeRef"), item_defs)
1077
+                params.append((p_name, p_type))
1078
+        bkms[name] = BKMDef(name=name, params=params, body=body, return_type=return_type)
1079
+    return bkms
1080
+
1081
+
1082
+def parse_knowledge_requirements(dmn_path: Path) -> dict[str, list[str]]:
1083
+    """Return a mapping from decision name to a list of *BKM* names it requires
1084
+    (via ``<knowledgeRequirement><requiredKnowledge href="#…"/>``)`.
1085
+
1086
+    Only ``<businessKnowledgeModel>`` targets are included; references to
1087
+    ``<decisionService>`` are silently ignored (DS is out of scope)."""
1088
+    root = ET.parse(dmn_path).getroot()
1089
+    # Build id -> name for BKMs only.
1090
+    id_to_bkm: dict[str, str] = {}
1091
+    for elem in root.iter():
1092
+        if _local(elem.tag) == "businessKnowledgeModel":
1093
+            bkm_id = elem.get("id")
1094
+            bkm_name = elem.get("name")
1095
+            if bkm_id and bkm_name:
1096
+                id_to_bkm[bkm_id] = bkm_name
1097
+    result: dict[str, list[str]] = {}
1098
+    for elem in root.iter():
1099
+        if _local(elem.tag) != "decision":
1100
+            continue
1101
+        name = elem.get("name")
1102
+        if name is None:
1103
+            continue
1104
+        bkm_names: list[str] = []
1105
+        for req in elem:
1106
+            if _local(req.tag) == "knowledgeRequirement":
1107
+                rk = _first_child(req, "requiredKnowledge")
1108
+                if rk is not None:
1109
+                    href = rk.get("href", "").lstrip("#")
1110
+                    bkm_name = id_to_bkm.get(href)
1111
+                    if bkm_name:
1112
+                        bkm_names.append(bkm_name)
1113
+        if bkm_names:
1114
+            result[name] = bkm_names
1115
+    return result
1116
+
1117
+
1118
+def parse_invocation_decisions(
1119
+    dmn_path: Path, item_defs: dict[str, str]
1120
+) -> dict[str, tuple[str, Optional[str]]]:
1121
+    """Parse ``<invocation>`` form decisions; return a mapping from decision name
1122
+    to ``(call_expression, coerce_to)`` where:
1123
+
1124
+    * ``call_expression`` is the equivalent FEEL named-argument call, e.g.
1125
+      ``bkm_001(nameAndAge: {name: "foo", age: 10})``.
1126
+    * ``coerce_to`` is the resolved FEEL type from the ``<invocation typeRef="…">``,
1127
+      or ``None`` when absent.
1128
+    """
1129
+    root = ET.parse(dmn_path).getroot()
1130
+    result: dict[str, tuple[str, Optional[str]]] = {}
1131
+    for elem in root.iter():
1132
+        if _local(elem.tag) != "decision":
1133
+            continue
1134
+        name = elem.get("name")
1135
+        if name is None:
1136
+            continue
1137
+        invoc = _first_child(elem, "invocation")
1138
+        if invoc is None:
1139
+            continue
1140
+        callee_lit = _first_child(invoc, "literalExpression")
1141
+        if callee_lit is None:
1142
+            continue
1143
+        callee_text = _first_child(callee_lit, "text")
1144
+        if callee_text is None or not callee_text.text:
1145
+            continue
1146
+        callee = callee_text.text.strip()
1147
+        args: list[str] = []
1148
+        for child in invoc:
1149
+            if _local(child.tag) == "binding":
1150
+                param = _first_child(child, "parameter")
1151
+                lit = _first_child(child, "literalExpression")
1152
+                if param is None or lit is None:
1153
+                    continue
1154
+                param_name = param.get("name", "")
1155
+                text_elem = _first_child(lit, "text")
1156
+                if text_elem is None or not text_elem.text:
1157
+                    continue
1158
+                args.append(f"{param_name}: {text_elem.text.strip()}")
1159
+        call_expr = f"{callee}({', '.join(args)})"
1160
+        coerce_to = _resolve_typeref_to_feel(invoc.get("typeRef"), item_defs)
1161
+        result[name] = (call_expr, coerce_to)
1162
+    return result
1163
+
1164
+
1165
+def parse_context_result_decisions(
1166
+    dmn_path: Path,
1167
+) -> dict[str, tuple[list[tuple[str, str]], str]]:
1168
+    """Parse boxed-context decisions that carry a trailing *result cell* — a
1169
+    ``<contextEntry>`` with no ``<variable>`` as the final entry.
1170
+
1171
+    Returns a mapping from decision name to ``(named_entries, result_expr)`` where:
1172
+
1173
+    * ``named_entries`` is an ordered list of ``(key, expression)`` pairs for all
1174
+      named entries (every entry *except* the last).
1175
+    * ``result_expr`` is the FEEL expression text of the unnamed result cell.
1176
+
1177
+    Decisions where every entry has a ``<variable>`` (no result cell), or where
1178
+    any entry is malformed, are silently omitted."""
1179
+    root = ET.parse(dmn_path).getroot()
1180
+    result: dict[str, tuple[list[tuple[str, str]], str]] = {}
1181
+    for elem in root.iter():
1182
+        if _local(elem.tag) != "decision":
1183
+            continue
1184
+        name = elem.get("name")
1185
+        ctx = _first_child(elem, "context")
1186
+        if name is None or ctx is None:
1187
+            continue
1188
+        all_entries = [c for c in ctx if _local(c.tag) == "contextEntry"]
1189
+        if not all_entries:
1190
+            continue
1191
+        # Last entry must have no <variable> (the result cell).
1192
+        last = all_entries[-1]
1193
+        if _first_child(last, "variable") is not None:
1194
+            continue
1195
+        last_lit = _first_child(last, "literalExpression")
1196
+        if last_lit is None:
1197
+            continue
1198
+        last_text = _first_child(last_lit, "text")
1199
+        if last_text is None or not last_text.text:
1200
+            continue
1201
+        result_expr = last_text.text.strip()
1202
+        # Extract named entries (all but the last).
1203
+        named_entries: list[tuple[str, str]] = []
1204
+        ok = True
1205
+        for entry in all_entries[:-1]:
1206
+            var = _first_child(entry, "variable")
1207
+            lit = _first_child(entry, "literalExpression")
1208
+            if var is None or lit is None:
1209
+                ok = False
1210
+                break
1211
+            key = var.get("name", "")
1212
+            text_elem = _first_child(lit, "text")
1213
+            if text_elem is None or not text_elem.text:
1214
+                ok = False
1215
+                break
1216
+            named_entries.append((key, text_elem.text.strip()))
1217
+        if ok and result_expr:
1218
+            result[name] = (named_entries, result_expr)
1219
+    return result
1220
+
1221
+
1222
+def _inline_bkms(
1223
+    call_expr: str,
1224
+    bkm_names: frozenset[str],
1225
+    bkms: dict[str, BKMDef],
1226
+) -> tuple[str, Optional[str]]:
1227
+    """Inline the named BKMs as FEEL function literals in a context literal
1228
+    wrapping ``call_expr``, then project the result via the synthetic
1229
+    ``__result`` key.
1230
+
1231
+    Output form::
1232
+
1233
+        {bkm1: function(p: T, …) body1, …, __result: call_expr}.__result
1234
+
1235
+    Returns ``(assembled_expression, bkm_return_type)`` where ``bkm_return_type``
1236
+    is the return type of the *first* BKM that declares one (``None`` otherwise)
1237
+    — used as a ``coerce_to`` fallback when neither the invocation nor the
1238
+    decision variable carries an explicit ``typeRef``."""
1239
+    entries: list[str] = []
1240
+    bkm_return_type: Optional[str] = None
1241
+    for bkm_name in sorted(bkm_names):  # deterministic output order
1242
+        bkm = bkms[bkm_name]
1243
+        param_parts: list[str] = []
1244
+        for p_name, p_type in bkm.params:
1245
+            param_parts.append(f"{p_name}: {p_type}" if p_type else p_name)
1246
+        fn_literal = f"function({', '.join(param_parts)}) {bkm.body}"
1247
+        entries.append(f"{bkm_name}: {fn_literal}")
1248
+        if bkm.return_type is not None and bkm_return_type is None:
1249
+            bkm_return_type = bkm.return_type
1250
+    entries.append(f"__result: {call_expr}")
1251
+    return "{" + ", ".join(entries) + "}.__result", bkm_return_type
1252
+
1253
+
8521254
 _XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
8531255
 
8541256
 
@@ -973,8 +1375,16 @@
9731375
 
9741376
 def extract_cases(dmn_path: Path, test_path: Path) -> tuple[list[Case], list[tuple[str, str]]]:
9751377
     """Return (kept cases, skipped (id, reason) pairs)."""
1378
+    # Parse type infrastructure for coerce_to resolution.
1379
+    item_defs = parse_item_definitions(dmn_path)
1380
+    decision_typerefs = parse_decision_typerefs(dmn_path, item_defs)
1381
+    # Parse decision expressions (four forms).
9761382
     decisions = parse_decisions(dmn_path)
9771383
     context_decisions = parse_context_decisions(dmn_path)
1384
+    context_result_decisions = parse_context_result_decisions(dmn_path)
1385
+    bkms = parse_bkms(dmn_path, item_defs)
1386
+    knowledge_reqs = parse_knowledge_requirements(dmn_path)
1387
+    invocation_decisions = parse_invocation_decisions(dmn_path, item_defs)
9781388
     model_stem = dmn_path.stem
9791389
 
9801390
     root = ET.parse(test_path).getroot()
@@ -1009,25 +1419,61 @@
10091419
             if name is None:
10101420
                 continue
10111421
 
1012
-            # Resolve the decision to an expression. Literal-expression decisions
1013
-            # emit one case per entry; boxed-context decisions assemble a FEEL
1014
-            # context literal `{k1: e1, …}` after checking each entry individually.
1422
+            expression: Optional[str] = None
1423
+            case_coerce_to: Optional[str] = None
1424
+            case_id = f"{model_stem}:{tc_id}:{name}"
1425
+
1426
+            # ----------------------------------------------------------------- #
1427
+            # Resolve the decision to an expression (four forms):                #
1428
+            #                                                                     #
1429
+            # 1. Literal-expression decision (possibly BKM-backed)               #
1430
+            # 2. Boxed-context decision with no result cell                      #
1431
+            # 3. Boxed-context decision with a trailing result cell (fd_*)       #
1432
+            # 4. Invocation-form decision                                         #
1433
+            # ----------------------------------------------------------------- #
1434
+
10151435
             if name in decisions:
1016
-                expression = decisions[name]
1017
-                case_id = f"{model_stem}:{tc_id}:{name}"
1018
-                # NB: `errorResult="true"` is *not* skipped wholesale. Many such cases
1019
-                # are genuine expression errors feel-core reproduces (a malformed regex,
1020
-                # a bad argument → error-null, collapsed to null at the lenient boundary,
1021
-                # which matches the expected nil) — valuable coverage. The few where the
1022
-                # error comes from DMN *decision output-type* validation rather than the
1023
-                # expression (e.g. `1+1` asserted to error against a non-number output
1024
-                # type, as in 0082) are handled per-case / by not ingesting that suite.
1025
-                if not fits_slice_grammar(expression, input_names):
1026
-                    skipped.append((case_id, f"outside slice grammar: {expression!r}"))
1027
-                    continue
1436
+                raw_expr = decisions[name]
1437
+                bkm_names = frozenset(knowledge_reqs.get(name, []))
1438
+                if bkm_names:
1439
+                    # BKM-backed literal-expression: check the raw call expression
1440
+                    # with the BKM names treated as bound names, then inline.
1441
+                    if not fits_slice_grammar(raw_expr, input_names | bkm_names):
1442
+                        skipped.append((case_id, f"outside slice grammar: {raw_expr!r}"))
1443
+                        continue
1444
+                    # Also validate each BKM body against its own param names.
1445
+                    bkm_body_ok = True
1446
+                    for bkm_name in bkm_names:
1447
+                        bkm = bkms.get(bkm_name)
1448
+                        if bkm is None:
1449
+                            bkm_body_ok = False
1450
+                            break
1451
+                        bkm_param_names = frozenset(p for p, _ in bkm.params)
1452
+                        if not fits_slice_grammar(bkm.body, bkm_param_names):
1453
+                            bkm_body_ok = False
1454
+                            break
1455
+                    if not bkm_body_ok:
1456
+                        skipped.append((case_id, f"BKM body outside slice for {name!r}"))
1457
+                        continue
1458
+                    expression, bkm_return_type = _inline_bkms(raw_expr, bkm_names, bkms)
1459
+                    # coerce_to priority: decision variable typeRef > BKM return typeRef
1460
+                    case_coerce_to = decision_typerefs.get(name) or bkm_return_type
1461
+                else:
1462
+                    # NB: `errorResult="true"` is *not* skipped wholesale. Many such
1463
+                    # cases are genuine expression errors feel-core reproduces (a
1464
+                    # malformed regex, a bad argument → error-null, collapsed to null at
1465
+                    # the lenient boundary, which matches the expected nil) — valuable
1466
+                    # coverage. The few where the error comes from DMN *decision
1467
+                    # output-type* validation rather than the expression are handled via
1468
+                    # the `coerce_to` mechanism (0082-feel-coercion).
1469
+                    if not fits_slice_grammar(raw_expr, input_names):
1470
+                        skipped.append((case_id, f"outside slice grammar: {raw_expr!r}"))
1471
+                        continue
1472
+                    expression = raw_expr
1473
+                    case_coerce_to = decision_typerefs.get(name)
1474
+
10281475
             elif name in context_decisions:
10291476
                 entries = context_decisions[name]
1030
-                case_id = f"{model_stem}:{tc_id}:{name}"
10311477
                 skip_reason: Optional[str] = None
10321478
                 for key, entry_expr in entries:
10331479
                     if not fits_slice_grammar(entry_expr, input_names):
@@ -1037,6 +1483,55 @@
10371483
                     skipped.append((case_id, skip_reason))
10381484
                     continue
10391485
                 expression = "{" + ", ".join(f"{k}: {e}" for k, e in entries) + "}"
1486
+                # Regular boxed-context decisions carry no result-cell coercion.
1487
+
1488
+            elif name in context_result_decisions:
1489
+                # Boxed-context with a trailing unnamed result cell:
1490
+                #   {k1: e1, …, __result: result_expr}.__result
1491
+                named_entries, result_expr = context_result_decisions[name]
1492
+                prior_keys = frozenset(k for k, _ in named_entries)
1493
+                skip_reason2: Optional[str] = None
1494
+                for key, entry_expr in named_entries:
1495
+                    if not fits_slice_grammar(entry_expr, input_names):
1496
+                        skip_reason2 = f"context entry {key!r} outside slice: {entry_expr!r}"
1497
+                        break
1498
+                if not skip_reason2 and not fits_slice_grammar(
1499
+                    result_expr, input_names | prior_keys
1500
+                ):
1501
+                    skip_reason2 = f"result cell outside slice: {result_expr!r}"
1502
+                if skip_reason2:
1503
+                    skipped.append((case_id, skip_reason2))
1504
+                    continue
1505
+                all_entries = list(named_entries) + [("__result", result_expr)]
1506
+                expression = "{" + ", ".join(f"{k}: {e}" for k, e in all_entries) + "}.__result"
1507
+                case_coerce_to = decision_typerefs.get(name)
1508
+
1509
+            elif name in invocation_decisions:
1510
+                call_expr, inv_coerce_to = invocation_decisions[name]
1511
+                bkm_names = frozenset(knowledge_reqs.get(name, []))
1512
+                # The call names a BKM directly; treat BKM names as bound during
1513
+                # the slice check of the call expression.
1514
+                if not fits_slice_grammar(call_expr, input_names | bkm_names):
1515
+                    skipped.append((case_id, f"outside slice grammar: {call_expr!r}"))
1516
+                    continue
1517
+                # Validate each BKM body.
1518
+                bkm_body_ok2 = True
1519
+                for bkm_name in bkm_names:
1520
+                    bkm = bkms.get(bkm_name)
1521
+                    if bkm is None:
1522
+                        bkm_body_ok2 = False
1523
+                        break
1524
+                    bkm_param_names = frozenset(p for p, _ in bkm.params)
1525
+                    if not fits_slice_grammar(bkm.body, bkm_param_names):
1526
+                        bkm_body_ok2 = False
1527
+                        break
1528
+                if not bkm_body_ok2:
1529
+                    skipped.append((case_id, f"BKM body outside slice for {name!r}"))
1530
+                    continue
1531
+                expression, bkm_return_type2 = _inline_bkms(call_expr, bkm_names, bkms)
1532
+                # coerce_to priority: invocation typeRef > BKM return typeRef > variable typeRef
1533
+                case_coerce_to = inv_coerce_to or bkm_return_type2 or decision_typerefs.get(name)
1534
+
10401535
             else:
10411536
                 continue
10421537
 
@@ -1083,6 +1578,7 @@
10831578
                 expression=expression,
10841579
                 expected=expected,
10851580
                 expected_type=expected_type,
1581
+                coerce_to=case_coerce_to,
10861582
                 context=inputs,
10871583
             )
10881584
             apply_deviations(case)