Public repository: timo / feel

Reader

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

feat(core): first-class range values

public

feat(core): first-class range values

Make a DMN range (`[1..10]`, `(a..b]`) a first-class value, not just a
unary test on the right of `in`:

- `Value::Range(Box<RangeVal>)` — two same-typed endpoints + per-bracket
  openness; boxed so `Value` stays 40 bytes. Recurses in
  `contains_error`/`into_lenient` and renders in interval notation via
  `string(...)`.
- `Expr::RangeLit(Interval)` + grammar: a range literal in value position.
  Inlined the bracket body so `List` and `RangeLit` share the `"[" Sum`
  (resp. `"(" Sum`) prefix and branch on `..` vs `]`/`,`/`)` — LR(1)-clean
  with no separate `IntervalStart` nonterminal (the old clash), proven by
  build.rs's no-conflict gate. The `in`-RHS interval *test* is unchanged.
- equality (`=`/`!=`): ranges equal iff openness flags and both endpoints
  match (DMN §10.3.4.6); a type-mismatched endpoint -> error-null.
- `instance of range<T>`: both endpoints must conform to `T`.
- wrappers (feel-lua/feel-py) map a range to a native table/dict carrying
  DMN's `start`/`end`/`start included`/`end included` properties.

All 64 lib tests and the 2598-case fixture suite stay green.

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

modified crates/feel-core/src/ast.rs +6 −0

@@ -17,6 +17,11 @@
1717
     Null,
1818
     /// List literal, e.g. `[1, 2, 3]` or `[]`.
1919
     List(Vec<Expr>),
20
+    /// A range / interval literal in *value* position, e.g. `[1..10)` or
21
+    /// `(a..b]` (DMN §10.3.4.6). Evaluates to a [`Value::Range`](crate::Value::Range).
22
+    /// The same [`Interval`] node also serves as a unary *test* on the right of `in`
23
+    /// ([`UnaryTest::Interval`]); here it is a first-class value.
24
+    RangeLit(Interval),
2025
     /// Context literal, e.g. `{a: 1, b: a + 1}`. Entries are ordered as written;
2126
     /// later entries may reference earlier ones (progressive binding).
2227
     ContextLit(Vec<(String, Box<Expr>)>),
@@ -311,6 +316,7 @@
311316
             | Expr::Null
312317
             | Expr::Var(_) => true,
313318
             Expr::List(items) => items.iter().all(Expr::is_clock_free),
319
+            Expr::RangeLit(iv) => iv.start.is_clock_free() && iv.end.is_clock_free(),
314320
             Expr::ContextLit(entries) => entries.iter().all(|(_, e)| e.is_clock_free()),
315321
             Expr::Path(target, _) => target.is_clock_free(),
316322
             Expr::Filter(source, bracket) => {

modified crates/feel-core/src/builtins.rs +9 −0

@@ -619,6 +619,15 @@
619619
         Value::Foreign(f) => value_to_string(&f.0.force()),
620620
         // A function value has no FEEL string form; render an opaque marker (ADR-23).
621621
         Value::Function(_) => "function".to_string(),
622
+        // A range renders in interval notation, e.g. `[1..10)` / `["a".."c"]`; the
623
+        // endpoints are quoted as list members are (so strings keep their quotes).
624
+        Value::Range(r) => format!(
625
+            "{}{}..{}{}",
626
+            if r.start_open { '(' } else { '[' },
627
+            render_member(&r.start),
628
+            render_member(&r.end),
629
+            if r.end_open { ')' } else { ']' },
630
+        ),
622631
         Value::Null | Value::Error => "null".to_string(),
623632
     }
624633
 }

modified crates/feel-core/src/eval.rs +31 −0

@@ -70,6 +70,20 @@
7070
                     out.push(self.eval(item, ctx)?);
7171
                 }
7272
                 Ok(Value::List(out))
73
+            }
74
+            // A range literal in value position (DMN §10.3.4.6): evaluate both
75
+            // endpoints and box them into a `Value::Range`. Unlike the `range(string)`
76
+            // built-in, a *literal* is taken at face value — no ordering/type check —
77
+            // mirroring the interval *test* form, which also evaluates endpoints lazily.
78
+            Expr::RangeLit(iv) => {
79
+                let start = self.eval(&iv.start, ctx)?.forced();
80
+                let end = self.eval(&iv.end, ctx)?.forced();
81
+                Ok(Value::Range(Box::new(crate::value::RangeVal {
82
+                    start,
83
+                    end,
84
+                    start_open: iv.start_open,
85
+                    end_open: iv.end_open,
86
+                })))
7387
             }
7488
             Expr::Var(name) => Ok(ctx.get(name).cloned().unwrap_or(Value::Null)),
7589
             Expr::ContextLit(entries) => self.eval_context_lit(entries, ctx),
@@ -447,6 +461,23 @@
447461
                 }
448462
             }
449463
             result
464
+        }
465
+        // Ranges are equal iff both bracket-openness flags match and both endpoints
466
+        // are FEEL-equal (DMN §10.3.4.6). A type-mismatched endpoint makes the whole
467
+        // comparison error-null (`None`), unless an openness/endpoint difference has
468
+        // already made it a definite `false`.
469
+        (Value::Range(x), Value::Range(y)) => {
470
+            if x.start_open != y.start_open || x.end_open != y.end_open {
471
+                return Some(false);
472
+            }
473
+            match (
474
+                feel_equal_depth(&x.start, &y.start, depth + 1),
475
+                feel_equal_depth(&x.end, &y.end, depth + 1),
476
+            ) {
477
+                (Some(false), _) | (_, Some(false)) => Some(false),
478
+                (None, _) | (_, None) => None,
479
+                (Some(true), Some(true)) => Some(true),
480
+            }
450481
         }
451482
         // Temporal: same-type -> Some(bool); cross temporal type -> None (-> error-null).
452483
         (x, y) if temporal::is_temporal(x) && temporal::is_temporal(y) => temporal::equal(x, y),

modified crates/feel-core/src/feel.lalrpop +18 −0

@@ -230,6 +230,7 @@
230230
     "false" => Expr::Bool(false),
231231
     "null" => Expr::Null,
232232
     List,
233
+    RangeLit,
233234
     Context,
234235
     "not" "(" <e:Expr> ")" => Expr::Not(Box::new(e)),
235236
     "(" <e:Expr> ")" => e,
@@ -239,6 +240,23 @@
239240
 List: Expr = {
240241
     "[" "]" => Expr::List(vec![]),
241242
     "[" <es:Comma<Expr>> "]" => Expr::List(es),
243
+};
244
+
245
+// A range / interval literal in *value* position (DMN §10.3.4.6), e.g. `[1..10)` or
246
+// `(a..b]`. It shares its opening `"[" Sum` (resp. `"(" Sum`) prefix with the list
247
+// literal (resp. the parenthesised-expression form): the parser commits to a range
248
+// only on seeing `..` after the first endpoint — a `]`/`,`/`)` instead reduces that
249
+// `Sum` up to a full `Expr` for `List` / grouping. The branch is on disjoint
250
+// lookahead (`..` is unique here), so it stays LR(1)-clean *without* a separate
251
+// `IntervalStart` nonterminal — factoring `IntervalStart → "["` is exactly what
252
+// clashed with `List` on the bare `[` (build.rs's no-conflict gate proves this).
253
+// The `in`-RHS *test* form keeps its own `Interval` rule below (a unary test, not a
254
+// value), reachable only after `in`, so the two never share an LR state.
255
+RangeLit: Expr = {
256
+    "[" <lo:Sum> ".." <hi:Sum> <eo:IntervalEnd> =>
257
+        Expr::RangeLit(Interval { start_open: false, start: Box::new(lo), end: Box::new(hi), end_open: eo }),
258
+    "(" <lo:Sum> ".." <hi:Sum> <eo:IntervalEnd> =>
259
+        Expr::RangeLit(Interval { start_open: true, start: Box::new(lo), end: Box::new(hi), end_open: eo }),
242260
 };
243261
 
244262
 // Context literal `{a: 1, b: a + 1}`. Keys are a bare Name or a string literal

modified crates/feel-core/src/lib.rs +25 −0

@@ -386,6 +386,31 @@
386386
     }
387387
 
388388
     #[test]
389
+    fn first_class_range_literals() {
390
+        // A range literal in value position is a first-class value, equal to itself.
391
+        assert_eq!(ev("[1..10] = [1..10]"), b(true));
392
+        assert_eq!(ev("(1..10] = (1..10]"), b(true));
393
+        assert_eq!(ev("[1..10) = [1..10)"), b(true));
394
+        // Openness and endpoints are part of identity.
395
+        assert_eq!(ev("[1..10] = [1..10)"), b(false));
396
+        assert_eq!(ev("[1..10] = (1..10]"), b(false));
397
+        assert_eq!(ev("[1..10] = [1..11]"), b(false));
398
+        // Endpoints of any orderable type.
399
+        assert_eq!(ev(r#"["a".."c"] = ["a".."c"]"#), b(true));
400
+        // `instance of range<T>` checks both endpoints' type.
401
+        assert_eq!(ev("[1..10] instance of range<number>"), b(true));
402
+        assert_eq!(ev(r#"["a".."c"] instance of range<string>"#), b(true));
403
+        assert_eq!(ev("[1..10] instance of range<string>"), b(false));
404
+        // A range literal nests as a list element (list of ranges).
405
+        assert_eq!(ev("[[1..2], [3..4]] = [[1..2], [3..4]]"), b(true));
406
+        // The `in` membership *test* form is unchanged (regression).
407
+        assert_eq!(ev("5 in [1..10]"), b(true));
408
+        assert_eq!(ev("15 in [1..10]"), b(false));
409
+        // A plain list literal is still a list, not a range.
410
+        assert_eq!(ev("[1, 2, 3]"), list(vec![num(1.0), num(2.0), num(3.0)]));
411
+    }
412
+
413
+    #[test]
389414
     fn arithmetic_and_precedence() {
390415
         assert_eq!(ev("1 + 1"), num(2.0));
391416
         assert_eq!(ev("1 + 2 * 3"), num(7.0)); // * binds tighter than +

modified crates/feel-core/src/types.rs +13 −4

@@ -22,10 +22,19 @@
2222
 pub(crate) fn value_conforms_to(v: &Value, t: &FeelType) -> bool {
2323
     match t {
2424
         FeelType::Any => true,
25
-        // Only `null` has type Null (handled by the caller / `conforms_nested`); no
26
-        // first-class range value exists in feel-core; `Unknown` is pre-screened by
27
-        // `FeelType::is_mappable`. All three never match a concrete value here.
28
-        FeelType::Null | FeelType::Range(_) | FeelType::Unknown => false,
25
+        // Only `null` has type Null (handled by the caller / `conforms_nested`);
26
+        // `Unknown` is pre-screened by `FeelType::is_mappable`. Neither matches a
27
+        // concrete value here.
28
+        FeelType::Null | FeelType::Unknown => false,
29
+        // `range<T>`: a range value whose *both* endpoints conform to `T` (DMN
30
+        // §10.3.4.6). Endpoints go through `conforms_nested`, so a null endpoint
31
+        // conforms to any `T` (Null <: T), matching the list/context rules.
32
+        FeelType::Range(elem) => match v {
33
+            Value::Range(r) => {
34
+                conforms_nested(&r.start, elem) && conforms_nested(&r.end, elem)
35
+            }
36
+            _ => false,
37
+        },
2938
         FeelType::Number => matches!(v, Value::Number(_)),
3039
         FeelType::String => matches!(v, Value::String(_)),
3140
         FeelType::Boolean => matches!(v, Value::Boolean(_)),

modified crates/feel-core/src/value.rs +26 −0

@@ -28,6 +28,12 @@
2828
     YearsMonthsDuration(i64),
2929
     /// A FEEL `days and time duration`, as an absolute signed duration.
3030
     DaysTimeDuration(jiff::SignedDuration),
31
+    /// A first-class range / interval value (DMN §10.3.4.6), e.g. `[1..10)` or
32
+    /// `range("[1..10]")`. Boxed so the variant stays one word and `Value` does not
33
+    /// grow past 40 bytes (see the size test in `lib.rs`). The endpoints are any two
34
+    /// orderable, same-typed [`Value`]s; the booleans carry each bracket's openness
35
+    /// (`[`/`]` closed, `(`/`)` open).
36
+    Range(Box<RangeVal>),
3137
     /// A lazily-resolved host value (a Python/JS object behind a target-specific
3238
     /// [`ForeignObject`](crate::foreign::ForeignObject)). Only the wrapper crates
3339
     /// ever construct one (ADR-21); the FEEL dot resolves it by name on demand,
@@ -52,6 +58,20 @@
5258
     Error,
5359
 }
5460
 
61
+/// The payload of a [`Value::Range`]: two same-typed endpoints plus each bracket's
62
+/// openness. A *well-formed* range has `start <= end` and both endpoints non-null of
63
+/// the same orderable type; the constructors ([`crate::builtins`] `range`, the
64
+/// `[a..b]` literal) enforce that, so consumers may assume it.
65
+#[derive(Debug, Clone, PartialEq)]
66
+pub struct RangeVal {
67
+    pub start: Value,
68
+    pub end: Value,
69
+    /// `true` if the lower bound is *exclusive* (`(`/`]` start).
70
+    pub start_open: bool,
71
+    /// `true` if the upper bound is *exclusive* (`)`/`[` end).
72
+    pub end_open: bool,
73
+}
74
+
5575
 impl Value {
5676
     /// True if this value is, or transitively contains, an [`Value::Error`].
5777
     /// Used by the strict boundary policy in the wrappers.
@@ -60,6 +80,7 @@
6080
             Value::Error => true,
6181
             Value::List(items) => items.iter().any(Value::contains_error),
6282
             Value::Context(map) => map.values().any(Value::contains_error),
83
+            Value::Range(r) => r.start.contains_error() || r.end.contains_error(),
6384
             _ => false,
6485
         }
6586
     }
@@ -92,6 +113,11 @@
92113
                     .map(|(k, v)| (k, v.into_lenient()))
93114
                     .collect(),
94115
             ),
116
+            Value::Range(r) => Value::Range(Box::new(RangeVal {
117
+                start: r.start.into_lenient(),
118
+                end: r.end.into_lenient(),
119
+                ..*r
120
+            })),
95121
             other => other,
96122
         }
97123
     }

modified crates/feel-lua/src/lib.rs +10 −0

@@ -377,6 +377,16 @@
377377
             }
378378
             LuaValue::Table(t)
379379
         }
380
+        // A range has no native Lua type; hand it back as a table carrying DMN's
381
+        // four range properties (§10.3.4.6), so `r["start included"]` reads naturally.
382
+        Value::Range(r) => {
383
+            let t = lua.create_table()?;
384
+            t.set("start", value_to_lua(lua, &r.start)?)?;
385
+            t.set("end", value_to_lua(lua, &r.end)?)?;
386
+            t.set("start included", !r.start_open)?;
387
+            t.set("end included", !r.end_open)?;
388
+            LuaValue::Table(t)
389
+        }
380390
         Value::Date(_)
381391
         | Value::Time(_)
382392
         | Value::DateTime(_)

modified crates/feel-py/src/lib.rs +10 −0

@@ -465,6 +465,16 @@
465465
             for (k, v) in map {
466466
                 dict.set_item(k, value_to_py(py, v)?)?;
467467
             }
468
+            dict.into_any()
469
+        }
470
+        // A range has no native Python type; hand it back as a dict carrying DMN's
471
+        // four range properties (§10.3.4.6), so `r["start included"]` reads naturally.
472
+        Value::Range(r) => {
473
+            let dict = PyDict::new(py);
474
+            dict.set_item("start", value_to_py(py, &r.start)?)?;
475
+            dict.set_item("end", value_to_py(py, &r.end)?)?;
476
+            dict.set_item("start included", !r.start_open)?;
477
+            dict.set_item("end included", !r.end_open)?;
468478
             dict.into_any()
469479
         }
470480
         Value::Date(d) => {