Public repository: timo / feel

Reader

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

feat(ingest): detect self-contained expressions and parse list/string results

public

feat(ingest): detect self-contained expressions and parse list/string results

Replace the two narrow regexes (integer-add and integer-range) with a single
`fits_slice_grammar` heuristic that keeps any literal-expression decision the
core-language engine can parse AND self-evaluate: it rejects free identifiers
(input variables and built-in function names), temporal `@` literals, context
`{}`, filters, parenthesised range tests, multiple iteration contexts, and the
`in` forms beyond a bracketed interval. The closed loop validates the rest —
`cargo test -p feel-core` asserts every kept case actually evaluates.

Make `parse_expected` structure-aware so it handles `<list>` results
recursively (nested lists supported) and stop skipping string results. Teach
the fixture test about `list` and `string` expected types via a recursive
`json_to_value` (list comparison is structural/exact).

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

modified crates/feel-core/tests/fixtures_test.rs +21 −9

@@ -99,16 +99,28 @@
9999
                 .as_f64()
100100
                 .unwrap_or_else(|| panic!("[{id}] expected number")),
101101
         ),
102
+        Some("string") => Value::String(
103
+            expected
104
+                .as_str()
105
+                .unwrap_or_else(|| panic!("[{id}] expected string"))
106
+                .to_string(),
107
+        ),
108
+        Some("list") => json_to_value(expected),
102109
         Some("null") => Value::Null,
103110
         // Fall back to the JSON shape if the type tag is absent.
104
-        _ => {
105
-            if expected.is_boolean() {
106
-                Value::Boolean(expected.as_bool().unwrap())
107
-            } else if expected.is_number() {
108
-                Value::Number(expected.as_f64().unwrap())
109
-            } else {
110
-                Value::Null
111
-            }
112
-        }
111
+        _ => json_to_value(expected),
113112
     }
114113
 }
114
+
115
+/// Recursively map a fixture's JSON value to a [`Value`] (used for list results,
116
+/// which may be nested). Note: list comparison is structural/exact — numeric
117
+/// items inside a list are not given the scalar `f64_epsilon` tolerance.
118
+fn json_to_value(json: &serde_json::Value) -> Value {
119
+    match json {
120
+        serde_json::Value::Bool(b) => Value::Boolean(*b),
121
+        serde_json::Value::Number(n) => Value::Number(n.as_f64().expect("finite number")),
122
+        serde_json::Value::String(s) => Value::String(s.clone()),
123
+        serde_json::Value::Array(a) => Value::List(a.iter().map(json_to_value).collect()),
124
+        serde_json::Value::Null | serde_json::Value::Object(_) => Value::Null,
125
+    }
126
+}

modified tools/ingest_tck.py +113 −41

@@ -3,15 +3,17 @@
33
 
44
 Source: https://github.com/dmn-tck/tck
55
 
6
-Scope (deliberately narrow): this is NOT a general DMN/XML harness. It handles
7
-exactly the "literal expression" test form, and only emits fixture cases whose
8
-expression fits feel-core's current grammar slice:
9
-
10
-  * integer addition            e.g.  "10 + 5"
11
-  * integer range membership    e.g.  "5 in [1..10]"
12
-
13
-Every other decision in the file is skipped (and reported), so we never produce
14
-false negatives for expressions the engine cannot yet evaluate.
6
+Scope: this is NOT a general DMN/XML harness. It handles exactly the "literal
7
+expression" test form, and only emits fixture cases whose expression fits
8
+feel-core's core-language slice AND is *self-contained* (references no input
9
+variables): arithmetic, comparison, `between`/`in`, three-valued `and`/`or`/`not`,
10
+`if/then/else`, `for … return`, and `some/every … satisfies` over literal lists
11
+and ranges. See `fits_slice_grammar` for the exact predicate.
12
+
13
+Anything outside the slice — built-in functions, temporal types, context
14
+literals, filters, or any decision that reads input data — is skipped (and
15
+reported), so we never produce false negatives for expressions the engine cannot
16
+yet evaluate.
1517
 
1618
 It also applies a *deviation registry*: a list of rules, each pairing a
1719
 predicate ("does this case match?") with a transform ("rewrite the expectation /
@@ -41,19 +43,75 @@
4143
 
4244
 import re
4345
 
44
-# One or more non-negative integers joined by '+'  (e.g. "10+5", "1 + 2 + 3").
45
-_INT_ADD = re.compile(r"^\s*\d+(\s*\+\s*\d+)*\s*$")
46
-
47
-# "<int> in <interval>" with numeric endpoints and any bracket combination
48
-# (e.g. "5 in [1..10]", "2 in (2..4]").
49
-_IN_RANGE = re.compile(
50
-    r"^\s*\d+(?:\.\d+)?\s+in\s+[\[(]\s*\d+(?:\.\d+)?\s*\.\.\s*\d+(?:\.\d+)?\s*[\])]\s*$"
51
-)
46
+# Keywords of the core-language slice. Any identifier that is NOT one of these
47
+# (and not a for/some/every loop variable) is a *free* name — an input variable
48
+# or a built-in function — which puts the expression outside the self-contained
49
+# slice we ingest.
50
+_KEYWORDS = {
51
+    "for", "return", "in", "if", "then", "else", "some", "every", "satisfies",
52
+    "and", "or", "not", "between", "true", "false", "null",
53
+}
5254
 
5355
 
5456
 def fits_slice_grammar(expression: str) -> bool:
55
-    """True if feel-core's current grammar can parse and evaluate `expression`."""
56
-    return bool(_INT_ADD.match(expression) or _IN_RANGE.match(expression))
57
+    """True if feel-core's core-language grammar can parse AND self-evaluate
58
+    `expression` — i.e. it references no input variables and uses no out-of-scope
59
+    syntax (built-in functions, temporal `@` literals, context `{}`, filters,
60
+    parenthesised range tests, multiple iteration contexts, …).
61
+
62
+    This is a conservative heuristic: it prefers to skip a borderline case over
63
+    keeping one feel-core cannot handle (a false positive would crash the
64
+    fixture test). The closed loop validates the rest — `cargo test -p feel-core`
65
+    asserts every kept case actually evaluates."""
66
+    # Blank out string literals so their contents never look like identifiers,
67
+    # operators or brackets.
68
+    s = re.sub(r'"[^"]*"', " ", expression)
69
+
70
+    # Out-of-scope literal syntax: context `{...}` and temporal `@"..."`.
71
+    if any(ch in s for ch in "{}@"):
72
+        return False
73
+
74
+    # Parenthesised unary range/comparison tests like `(< 10)`, `(=10)`.
75
+    if re.search(r"[\[(]\s*(<=|>=|!=|<|>|=)", s):
76
+        return False
77
+
78
+    # Multiple iteration contexts: `for i in a, j in b ...` (not yet supported).
79
+    if re.search(r",\s*[A-Za-z_]\w*\s+in\b", s):
80
+        return False
81
+
82
+    # Free identifiers: not a keyword and not a loop variable bound by an
83
+    # enclosing for/some/every. Rejects input variables, built-in function names
84
+    # (e.g. `date`, `abs`) and scientific notation (the `e4` in `1.23e4`).
85
+    bound = set(re.findall(r"\b(?:for|some|every)\s+([A-Za-z_]\w*)\s+in\b", s))
86
+    idents = re.findall(r"[A-Za-z_]\w*", s)
87
+    if any(tok not in _KEYWORDS and tok not in bound for tok in idents):
88
+        return False
89
+
90
+    # `..` is only valid as a bare iteration range (`for i in a..b`) or inside a
91
+    # membership interval (`x in [a..b]`).
92
+    if ".." in s:
93
+        if re.search(r"\b(?:for|some|every)\b", s):
94
+            # In an iteration, ranges must be bare — reject any bracketed `..`.
95
+            if re.search(r"[\[(][^\[\]()]*\.\.", s):
96
+                return False
97
+        else:
98
+            # Otherwise every `..` must sit inside a membership interval.
99
+            membership = re.findall(r"\bin\s*[\[(][^\[\]()]*\.\.[^\[\]()]*[\])]", s)
100
+            if len(membership) != s.count(".."):
101
+                return False
102
+
103
+    # Membership `in` (i.e. not a for/some/every iterator) is only supported for
104
+    # a bracketed interval `[a..b]`. Reject the other FEEL `in` forms the grammar
105
+    # does not implement: `x in y`, `x in (t1, t2)`, `x in =y`, `x in [list]`.
106
+    for m in re.finditer(r"\bin\b", s):
107
+        before = s[: m.start()]
108
+        if re.search(r"\b(?:for|some|every)\s+[A-Za-z_]\w*\s*$", before):
109
+            continue  # this is an iterator `in`, handled above
110
+        after = s[m.end() :]
111
+        if not re.match(r"\s*[\[(][^\[\]()]*\.\.[^\[\]()]*[\])]", after):
112
+            return False
113
+
114
+    return True
57115
 
58116
 
59117
 # --------------------------------------------------------------------------- #
@@ -208,33 +266,50 @@
208266
     return decisions
209267
 
210268
 
211
-def parse_expected(result_node: ET.Element) -> tuple[object, str]:
212
-    """Extract (value, type) from a <resultNode>'s <expected><value>."""
213
-    value_elem = None
214
-    for child in result_node.iter():
215
-        if _local(child.tag) == "value":
216
-            value_elem = child
217
-            break
218
-    if value_elem is None:
269
+_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"
270
+
271
+
272
+def _first_child(elem: ET.Element, *names: str) -> Optional[ET.Element]:
273
+    """First direct child whose local tag is one of `names`."""
274
+    for child in elem:
275
+        if _local(child.tag) in names:
276
+            return child
277
+    return None
278
+
279
+
280
+def parse_value_elem(value_elem: ET.Element) -> tuple[object, str]:
281
+    """Parse a scalar <value> element -> (python value, type)."""
282
+    if value_elem.get(f"{_XSI}nil") == "true":
219283
         return None, "null"
220
-
221
-    # xsi:nil -> FEEL null
222
-    nil = value_elem.get("{http://www.w3.org/2001/XMLSchema-instance}nil")
223
-    if nil == "true":
224
-        return None, "null"
225
-
226
-    xsi_type = value_elem.get("{http://www.w3.org/2001/XMLSchema-instance}type", "")
284
+    xsi_type = value_elem.get(f"{_XSI}type", "")
227285
     text = (value_elem.text or "").strip()
228
-
229286
     if text in ("true", "false") or xsi_type.endswith("boolean"):
230287
         return text == "true", "boolean"
231
-
232288
     # decimal / double / integer, or anything that parses as a number
233289
     try:
234
-        num = float(text)
235
-        return num, "number"
290
+        return float(text), "number"
236291
     except ValueError:
237292
         return text, "string"
293
+
294
+
295
+def parse_expected_node(node: ET.Element) -> tuple[object, str]:
296
+    """Parse an <expected> or <item> node's <value>/<list> child (recursive)."""
297
+    child = _first_child(node, "value", "list")
298
+    if child is None:
299
+        return None, "null"
300
+    if _local(child.tag) == "value":
301
+        return parse_value_elem(child)
302
+    # <list><item>...</item>...</list> -> a (possibly nested) JSON array.
303
+    items = [parse_expected_node(it)[0] for it in child if _local(it.tag) == "item"]
304
+    return items, "list"
305
+
306
+
307
+def parse_expected(result_node: ET.Element) -> tuple[object, str]:
308
+    """Extract (value, type) from a <resultNode>'s <expected> (scalar or list)."""
309
+    expected = _first_child(result_node, "expected")
310
+    if expected is None:
311
+        return None, "null"
312
+    return parse_expected_node(expected)
238313
 
239314
 
240315
 def extract_cases(dmn_path: Path, test_path: Path) -> tuple[list[Case], list[tuple[str, str]]]:
@@ -264,9 +339,6 @@
264339
                 continue
265340
 
266341
             expected, expected_type = parse_expected(result_node)
267
-            if expected_type == "string":
268
-                skipped.append((case_id, f"string result not in slice: {expression!r}"))
269
-                continue
270342
 
271343
             case = Case(
272344
                 id=case_id,