Public repository: timo / feel

Reader

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

feat(core): widen grammar and evaluator to the FEEL core language

public

feat(core): widen grammar and evaluator to the FEEL core language

Grow the deliberate slice from "numbers + binary + + intervals + in" to the
core FEEL language taught in learn-dmn-in-15-minutes:

- Literals: string, boolean, null, list (`[a, b, c]` / `[]`); numbers stay f64.
- Arithmetic: `+ - * /`, `**` (left-associative, per DMN-TCK 0075), unary `-`
  (binds tighter than `**`, so `-3 ** 2 == 9`); division-by-zero and overflow
  collapse to null.
- Comparison: `< <= > >= = !=`, `between … and …`. Equality and ordering are
  three-valued and cross-type (different non-null types compare to null; only
  numbers/strings are ordered); list equality is structural.
- Logic: `and`/`or`/`not(…)` with Kleene three-valued semantics (verified
  against TCK 0064/0065/0066).
- Control flow: `if/then/else`, `for … return`, `some/every … satisfies`, with
  bare integer ranges (`2..4`) as iteration sources and a child-scoped loop
  variable (`Context::with`).
- Variable references resolve from the context (unbound -> null).

Type errors evaluate to null rather than raising; FeelError is now effectively
parse-only. The grammar is a full lalrpop precedence ladder and still compiles
with no LR(1) conflicts. 13 acceptance tests cover the new constructs.

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

modified crates/feel-core/src/ast.rs +85 −3

@@ -1,14 +1,96 @@
11
 //! Abstract syntax tree produced by the generated parser.
22
 
3
-/// A parsed FEEL expression (slice subset).
3
+/// A parsed FEEL expression (core-language slice).
44
 #[derive(Debug, Clone, PartialEq)]
55
 pub enum Expr {
6
+    // --- literals ---
67
     /// Numeric literal.
78
     Number(f64),
8
-    /// Binary addition `lhs + rhs`.
9
-    Add(Box<Expr>, Box<Expr>),
9
+    /// String literal.
10
+    Str(String),
11
+    /// Boolean literal (`true` / `false`).
12
+    Bool(bool),
13
+    /// The `null` literal.
14
+    Null,
15
+    /// List literal, e.g. `[1, 2, 3]` or `[]`.
16
+    List(Vec<Expr>),
17
+    /// Variable / name reference (e.g. a `for`/`some`/`every` loop variable).
18
+    Var(String),
19
+
20
+    // --- arithmetic ---
21
+    /// Unary arithmetic negation `-x`.
22
+    Neg(Box<Expr>),
23
+    /// Binary arithmetic `lhs <op> rhs`.
24
+    Arith(ArithOp, Box<Expr>, Box<Expr>),
25
+
26
+    // --- comparison ---
27
+    /// Binary comparison `lhs <op> rhs`.
28
+    Compare(CmpOp, Box<Expr>, Box<Expr>),
29
+    /// `value between low and high` — sugar for `low <= value and value <= high`.
30
+    Between(Box<Expr>, Box<Expr>, Box<Expr>),
1031
     /// Membership test `value in interval`.
1132
     In(Box<Expr>, Interval),
33
+
34
+    // --- logic (three-valued / Kleene) ---
35
+    And(Box<Expr>, Box<Expr>),
36
+    Or(Box<Expr>, Box<Expr>),
37
+    Not(Box<Expr>),
38
+
39
+    // --- control flow ---
40
+    /// `if cond then then_branch else else_branch`.
41
+    If(Box<Expr>, Box<Expr>, Box<Expr>),
42
+    /// `for var in source return body`.
43
+    For {
44
+        var: String,
45
+        source: IterSource,
46
+        body: Box<Expr>,
47
+    },
48
+    /// `some|every var in source satisfies predicate`.
49
+    Quantified {
50
+        kind: Quantifier,
51
+        var: String,
52
+        source: IterSource,
53
+        predicate: Box<Expr>,
54
+    },
55
+}
56
+
57
+/// Binary arithmetic operators.
58
+#[derive(Debug, Clone, Copy, PartialEq)]
59
+pub enum ArithOp {
60
+    Add,
61
+    Sub,
62
+    Mul,
63
+    Div,
64
+    /// Exponentiation `**` (right-associative).
65
+    Pow,
66
+}
67
+
68
+/// Comparison operators.
69
+#[derive(Debug, Clone, Copy, PartialEq)]
70
+pub enum CmpOp {
71
+    Lt,
72
+    Le,
73
+    Gt,
74
+    Ge,
75
+    Eq,
76
+    Ne,
77
+}
78
+
79
+/// Which quantifier a [`Expr::Quantified`] is.
80
+#[derive(Debug, Clone, Copy, PartialEq)]
81
+pub enum Quantifier {
82
+    Some,
83
+    Every,
84
+}
85
+
86
+/// The `in` source of a `for`/`some`/`every` loop.
87
+#[derive(Debug, Clone, PartialEq)]
88
+pub enum IterSource {
89
+    /// Any expression that should evaluate to a list (e.g. `[1,2,3]` or a var).
90
+    Expr(Box<Expr>),
91
+    /// A bare integer range `start..end` (e.g. `for i in 2..4`), generating an
92
+    /// ascending or descending integer list. Distinct from an interval literal.
93
+    Range(Box<Expr>, Box<Expr>),
1294
 }
1395
 
1496
 /// An interval (range) literal, e.g. `[1..10)`.

modified crates/feel-core/src/eval.rs +313 −32

@@ -1,41 +1,322 @@
11
 //! Tree-walking evaluator for the parsed AST.
2
-
3
-use crate::ast::{Expr, Interval};
2
+//!
3
+//! FEEL is null-friendly: most type errors (arithmetic on non-numbers,
4
+//! comparing incomparable types, division by zero, a non-boolean condition,
5
+//! …) evaluate to `null` rather than raising — this is the three-valued
6
+//! (Kleene) logic the language is built on (see DECISIONS.md). `FeelError` is
7
+//! therefore reserved for parse failures; evaluation here essentially always
8
+//! produces a `Value`.
9
+
10
+use std::cmp::Ordering;
11
+
12
+use crate::ast::{ArithOp, CmpOp, Expr, Interval, IterSource, Quantifier};
413
 use crate::{Context, FeelError, Value};
514
 
15
+type EvalResult = Result<Value, FeelError>;
16
+
617
 /// Evaluate an AST node against a context.
7
-pub(crate) fn eval(expr: &Expr, ctx: &Context) -> Result<Value, FeelError> {
18
+pub(crate) fn eval(expr: &Expr, ctx: &Context) -> EvalResult {
819
     match expr {
20
+        // --- literals ---
921
         Expr::Number(n) => Ok(Value::Number(*n)),
10
-        Expr::Add(lhs, rhs) => {
11
-            let a = as_number(eval(lhs, ctx)?)?;
12
-            let b = as_number(eval(rhs, ctx)?)?;
13
-            Ok(Value::Number(a + b))
22
+        Expr::Str(s) => Ok(Value::String(s.clone())),
23
+        Expr::Bool(b) => Ok(Value::Boolean(*b)),
24
+        Expr::Null => Ok(Value::Null),
25
+        Expr::List(items) => {
26
+            let mut out = Vec::with_capacity(items.len());
27
+            for item in items {
28
+                out.push(eval(item, ctx)?);
29
+            }
30
+            Ok(Value::List(out))
31
+        }
32
+        Expr::Var(name) => Ok(ctx.get(name).cloned().unwrap_or(Value::Null)),
33
+
34
+        // --- arithmetic ---
35
+        Expr::Neg(e) => Ok(match eval(e, ctx)? {
36
+            Value::Number(n) => Value::Number(-n),
37
+            _ => Value::Null,
38
+        }),
39
+        Expr::Arith(op, l, r) => eval_arith(*op, eval(l, ctx)?, eval(r, ctx)?),
40
+
41
+        // --- comparison ---
42
+        Expr::Compare(op, l, r) => Ok(eval_compare(*op, &eval(l, ctx)?, &eval(r, ctx)?)),
43
+        Expr::Between(v, lo, hi) => {
44
+            let v = eval(v, ctx)?;
45
+            let lo = eval(lo, ctx)?;
46
+            let hi = eval(hi, ctx)?;
47
+            // low <= v  and  v <= high   (three-valued)
48
+            Ok(and3(
49
+                eval_compare(CmpOp::Le, &lo, &v),
50
+                eval_compare(CmpOp::Le, &v, &hi),
51
+            ))
1452
         }
1553
         Expr::In(value, interval) => eval_in(value, interval, ctx),
16
-    }
17
-}
18
-
19
-/// Membership test, with interval inclusivity exactly per the S-FEEL spec
20
-/// (clause 10.3.2 / S-FEEL semantics):
21
-///   [a..b]  -> a <= o <= b
22
-///   (a..b]  -> a <  o <= b
23
-///   [a..b)  -> a <= o <  b
24
-///   (a..b)  -> a <  o <  b
25
-fn eval_in(value: &Expr, interval: &Interval, ctx: &Context) -> Result<Value, FeelError> {
26
-    let o = as_number(eval(value, ctx)?)?;
27
-    let lo = as_number(eval(&interval.start, ctx)?)?;
28
-    let hi = as_number(eval(&interval.end, ctx)?)?;
29
-
30
-    let lower_ok = if interval.start_open { o > lo } else { o >= lo };
31
-    let upper_ok = if interval.end_open { o < hi } else { o <= hi };
32
-
33
-    Ok(Value::Boolean(lower_ok && upper_ok))
34
-}
35
-
36
-fn as_number(v: Value) -> Result<f64, FeelError> {
54
+
55
+        // --- three-valued logic ---
56
+        Expr::And(l, r) => Ok(and3(eval(l, ctx)?, eval(r, ctx)?)),
57
+        Expr::Or(l, r) => Ok(or3(eval(l, ctx)?, eval(r, ctx)?)),
58
+        Expr::Not(e) => Ok(match eval(e, ctx)? {
59
+            Value::Boolean(b) => Value::Boolean(!b),
60
+            _ => Value::Null,
61
+        }),
62
+
63
+        // --- control flow ---
64
+        Expr::If(c, t, e) => match eval(c, ctx)? {
65
+            Value::Boolean(true) => eval(t, ctx),
66
+            Value::Boolean(false) => eval(e, ctx),
67
+            _ => Ok(Value::Null), // non-boolean condition -> null
68
+        },
69
+        Expr::For { var, source, body } => eval_for(var, source, body, ctx),
70
+        Expr::Quantified {
71
+            kind,
72
+            var,
73
+            source,
74
+            predicate,
75
+        } => eval_quantified(*kind, var, source, predicate, ctx),
76
+    }
77
+}
78
+
79
+// --------------------------------------------------------------------------- //
80
+// Arithmetic
81
+// --------------------------------------------------------------------------- //
82
+
83
+fn eval_arith(op: ArithOp, lhs: Value, rhs: Value) -> EvalResult {
84
+    let (a, b) = match (as_number(&lhs), as_number(&rhs)) {
85
+        (Some(a), Some(b)) => (a, b),
86
+        _ => return Ok(Value::Null), // non-numeric operand -> null
87
+    };
88
+    let out = match op {
89
+        ArithOp::Add => a + b,
90
+        ArithOp::Sub => a - b,
91
+        ArithOp::Mul => a * b,
92
+        ArithOp::Div => {
93
+            if b == 0.0 {
94
+                return Ok(Value::Null); // division by zero -> null
95
+            }
96
+            a / b
97
+        }
98
+        ArithOp::Pow => a.powf(b),
99
+    };
100
+    // Non-finite results (overflow / NaN, e.g. (-8) ** 0.5) collapse to null;
101
+    // this also keeps every Number JSON-representable at the wrappers.
102
+    Ok(if out.is_finite() {
103
+        Value::Number(out)
104
+    } else {
105
+        Value::Null
106
+    })
107
+}
108
+
109
+// --------------------------------------------------------------------------- //
110
+// Comparison & equality (three-valued, cross-type)
111
+// --------------------------------------------------------------------------- //
112
+
113
+fn eval_compare(op: CmpOp, a: &Value, b: &Value) -> Value {
114
+    match op {
115
+        CmpOp::Eq => from_opt_bool(feel_equal(a, b)),
116
+        CmpOp::Ne => from_opt_bool(feel_equal(a, b).map(|eq| !eq)),
117
+        CmpOp::Lt => order_to_bool(feel_order(a, b), |o| o == Ordering::Less),
118
+        CmpOp::Le => order_to_bool(feel_order(a, b), |o| o != Ordering::Greater),
119
+        CmpOp::Gt => order_to_bool(feel_order(a, b), |o| o == Ordering::Greater),
120
+        CmpOp::Ge => order_to_bool(feel_order(a, b), |o| o != Ordering::Less),
121
+    }
122
+}
123
+
124
+/// FEEL equality, three-valued:
125
+///   * both null            -> Some(true)
126
+///   * exactly one null     -> Some(false)
127
+///   * same type            -> Some(value comparison) (lists compared elementwise)
128
+///   * different non-null   -> None  (-> null)
129
+fn feel_equal(a: &Value, b: &Value) -> Option<bool> {
130
+    match (a, b) {
131
+        (Value::Null, Value::Null) => Some(true),
132
+        (Value::Null, _) | (_, Value::Null) => Some(false),
133
+        (Value::Number(x), Value::Number(y)) => Some(x == y),
134
+        (Value::Boolean(x), Value::Boolean(y)) => Some(x == y),
135
+        (Value::String(x), Value::String(y)) => Some(x == y),
136
+        (Value::List(xs), Value::List(ys)) => {
137
+            if xs.len() != ys.len() {
138
+                return Some(false);
139
+            }
140
+            let mut result = Some(true);
141
+            for (x, y) in xs.iter().zip(ys) {
142
+                match feel_equal(x, y) {
143
+                    Some(false) => return Some(false),
144
+                    None => result = None, // type-mismatched element -> null (unless a later false)
145
+                    Some(true) => {}
146
+                }
147
+            }
148
+            result
149
+        }
150
+        _ => None, // different, non-null types
151
+    }
152
+}
153
+
154
+/// FEEL ordering. Only numbers and strings are ordered; anything else (null,
155
+/// boolean, list, or a type mismatch) yields `None` (-> null).
156
+fn feel_order(a: &Value, b: &Value) -> Option<Ordering> {
157
+    match (a, b) {
158
+        (Value::Number(x), Value::Number(y)) => x.partial_cmp(y),
159
+        (Value::String(x), Value::String(y)) => Some(x.cmp(y)),
160
+        _ => None,
161
+    }
162
+}
163
+
164
+fn from_opt_bool(b: Option<bool>) -> Value {
165
+    match b {
166
+        Some(b) => Value::Boolean(b),
167
+        None => Value::Null,
168
+    }
169
+}
170
+
171
+fn order_to_bool(ord: Option<Ordering>, pred: impl Fn(Ordering) -> bool) -> Value {
172
+    match ord {
173
+        Some(o) => Value::Boolean(pred(o)),
174
+        None => Value::Null,
175
+    }
176
+}
177
+
178
+/// Membership test, interval inclusivity exactly per S-FEEL:
179
+///   [a..b] -> a <= o <= b ;  (a..b] -> a < o <= b ;  [a..b) -> a <= o < b ;
180
+///   (a..b) -> a < o < b
181
+fn eval_in(value: &Expr, interval: &Interval, ctx: &Context) -> EvalResult {
182
+    let o = eval(value, ctx)?;
183
+    let lo = eval(&interval.start, ctx)?;
184
+    let hi = eval(&interval.end, ctx)?;
185
+
186
+    let lower = if interval.start_open {
187
+        eval_compare(CmpOp::Lt, &lo, &o)
188
+    } else {
189
+        eval_compare(CmpOp::Le, &lo, &o)
190
+    };
191
+    let upper = if interval.end_open {
192
+        eval_compare(CmpOp::Lt, &o, &hi)
193
+    } else {
194
+        eval_compare(CmpOp::Le, &o, &hi)
195
+    };
196
+    Ok(and3(lower, upper))
197
+}
198
+
199
+// --------------------------------------------------------------------------- //
200
+// Kleene logic
201
+// --------------------------------------------------------------------------- //
202
+
203
+/// `and`: false if either operand is `false`, true if both are `true`, else null.
204
+fn and3(a: Value, b: Value) -> Value {
205
+    if is_false(&a) || is_false(&b) {
206
+        Value::Boolean(false)
207
+    } else if is_true(&a) && is_true(&b) {
208
+        Value::Boolean(true)
209
+    } else {
210
+        Value::Null
211
+    }
212
+}
213
+
214
+/// `or`: true if either operand is `true`, false if both are `false`, else null.
215
+fn or3(a: Value, b: Value) -> Value {
216
+    if is_true(&a) || is_true(&b) {
217
+        Value::Boolean(true)
218
+    } else if is_false(&a) && is_false(&b) {
219
+        Value::Boolean(false)
220
+    } else {
221
+        Value::Null
222
+    }
223
+}
224
+
225
+fn is_true(v: &Value) -> bool {
226
+    matches!(v, Value::Boolean(true))
227
+}
228
+
229
+fn is_false(v: &Value) -> bool {
230
+    matches!(v, Value::Boolean(false))
231
+}
232
+
233
+// --------------------------------------------------------------------------- //
234
+// Iteration: for / some / every
235
+// --------------------------------------------------------------------------- //
236
+
237
+/// Resolve a `for`/`some`/`every` source to the list it iterates over.
238
+/// Returns `None` when the source is not iterable (e.g. a range with
239
+/// non-numeric bounds) — the caller maps that to `null`.
240
+fn iter_values(source: &IterSource, ctx: &Context) -> Result<Option<Vec<Value>>, FeelError> {
241
+    match source {
242
+        IterSource::Expr(e) => Ok(match eval(e, ctx)? {
243
+            Value::List(items) => Some(items),
244
+            _ => None,
245
+        }),
246
+        IterSource::Range(lo, hi) => {
247
+            let lo = eval(lo, ctx)?;
248
+            let hi = eval(hi, ctx)?;
249
+            match (as_number(&lo), as_number(&hi)) {
250
+                (Some(lo), Some(hi)) => Ok(Some(int_range(lo, hi))),
251
+                _ => Ok(None),
252
+            }
253
+        }
254
+    }
255
+}
256
+
257
+/// Inclusive integer range with a ±1 step: `2..4` -> [2,3,4], `4..2` -> [4,3,2].
258
+fn int_range(lo: f64, hi: f64) -> Vec<Value> {
259
+    // Guard against pathological/non-integer bounds producing huge or endless
260
+    // loops; this slice only ever sees small ranges.
261
+    const CAP: usize = 1_000_000;
262
+    let mut out = Vec::new();
263
+    let step = if lo <= hi { 1.0 } else { -1.0 };
264
+    let mut x = lo;
265
+    while (step > 0.0 && x <= hi) || (step < 0.0 && x >= hi) {
266
+        out.push(Value::Number(x));
267
+        if out.len() >= CAP {
268
+            break;
269
+        }
270
+        x += step;
271
+    }
272
+    out
273
+}
274
+
275
+fn eval_for(var: &str, source: &IterSource, body: &Expr, ctx: &Context) -> EvalResult {
276
+    let Some(items) = iter_values(source, ctx)? else {
277
+        return Ok(Value::Null);
278
+    };
279
+    let mut out = Vec::with_capacity(items.len());
280
+    for item in items {
281
+        out.push(eval(body, &ctx.with(var, item))?);
282
+    }
283
+    Ok(Value::List(out))
284
+}
285
+
286
+fn eval_quantified(
287
+    kind: Quantifier,
288
+    var: &str,
289
+    source: &IterSource,
290
+    predicate: &Expr,
291
+    ctx: &Context,
292
+) -> EvalResult {
293
+    let Some(items) = iter_values(source, ctx)? else {
294
+        return Ok(Value::Null);
295
+    };
296
+    let mut any_null = false;
297
+    for item in items {
298
+        match eval(predicate, &ctx.with(var, item))? {
299
+            Value::Boolean(true) if kind == Quantifier::Some => return Ok(Value::Boolean(true)),
300
+            Value::Boolean(false) if kind == Quantifier::Every => return Ok(Value::Boolean(false)),
301
+            Value::Boolean(_) => {}
302
+            _ => any_null = true, // non-boolean / null predicate result
303
+        }
304
+    }
305
+    Ok(if any_null {
306
+        Value::Null
307
+    } else {
308
+        match kind {
309
+            Quantifier::Some => Value::Boolean(false),
310
+            Quantifier::Every => Value::Boolean(true),
311
+        }
312
+    })
313
+}
314
+
315
+// --------------------------------------------------------------------------- //
316
+
317
+fn as_number(v: &Value) -> Option<f64> {
37318
     match v {
38
-        Value::Number(n) => Ok(n),
39
-        other => Err(FeelError::Eval(format!("expected a number, got {other:?}"))),
40
-    }
41
-}
319
+        Value::Number(n) => Some(*n),
320
+        _ => None,
321
+    }
322
+}

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

@@ -1,35 +1,120 @@
1
-// Minimal (S-)FEEL grammar slice.
1
+// (S-)FEEL grammar — the "core language" slice.
22
 //
3
-// Scope: exactly what the acceptance tests need — integer/decimal number
4
-// literals, binary `+`, interval literals `[a..b]` / `(a..b]` / `[a..b)` /
5
-// `(a..b)`, and the `in` membership test. This is a deliberate subset of the
6
-// full FEEL grammar (see specs/FEEL.pdf). It is left-recursive on purpose;
7
-// lalrpop (LR(1)) handles that natively, which is the reason we chose it.
3
+// Scope: literals (number, string, boolean, null, list), arithmetic
4
+// (`+ - * /`, `**`, unary `-`), comparison (`< <= > >= = !=`, `between`, `in`),
5
+// three-valued logic (`and`/`or`/`not`), and control flow (`if/then/else`,
6
+// `for … return`, `some/every … satisfies`) plus variable references. This is a
7
+// deliberate subset of full FEEL (no built-in functions, no temporal types —
8
+// see DECISIONS.md, ADR-7). It is left-recursive on purpose; lalrpop (LR(1))
9
+// handles that natively, which is the reason we chose it.
810
 
9
-use crate::ast::{Expr, Interval};
11
+use crate::ast::{ArithOp, CmpOp, Expr, Interval, IterSource, Quantifier};
1012
 
1113
 grammar;
1214
 
13
-// An expression is either a plain additive expression, or an additive
14
-// expression tested for membership in an interval (`o in [a..b]`).
15
-pub Expr: Expr = {
16
-    <lhs:Additive> "in" <iv:Interval> => Expr::In(Box::new(lhs), iv),
17
-    Additive,
15
+pub Expr: Expr = TextualExpr;
16
+
17
+// Loosest-binding forms. `for`/`if`/`some`/`every` extend to the end of their
18
+// sub-expressions (which are themselves full TextualExprs), enabling nesting
19
+// like `for i in [1,2,3] return if i > 0 then i else -i`.
20
+TextualExpr: Expr = {
21
+    "for" <v:Name> "in" <s:IterSrc> "return" <b:TextualExpr> =>
22
+        Expr::For { var: v, source: s, body: Box::new(b) },
23
+    "if" <c:TextualExpr> "then" <t:TextualExpr> "else" <e:TextualExpr> =>
24
+        Expr::If(Box::new(c), Box::new(t), Box::new(e)),
25
+    "some" <v:Name> "in" <s:IterSrc> "satisfies" <p:TextualExpr> =>
26
+        Expr::Quantified { kind: Quantifier::Some, var: v, source: s, predicate: Box::new(p) },
27
+    "every" <v:Name> "in" <s:IterSrc> "satisfies" <p:TextualExpr> =>
28
+        Expr::Quantified { kind: Quantifier::Every, var: v, source: s, predicate: Box::new(p) },
29
+    Disjunction,
1830
 };
1931
 
20
-// Left-associative addition. Left recursion is free in LR parsing.
21
-Additive: Expr = {
22
-    <l:Additive> "+" <r:Primary> => Expr::Add(Box::new(l), Box::new(r)),
32
+Disjunction: Expr = {
33
+    <l:Disjunction> "or" <r:Conjunction> => Expr::Or(Box::new(l), Box::new(r)),
34
+    Conjunction,
35
+};
36
+
37
+Conjunction: Expr = {
38
+    <l:Conjunction> "and" <r:Comparison> => Expr::And(Box::new(l), Box::new(r)),
39
+    Comparison,
40
+};
41
+
42
+// Comparison bounds are `Sum` (not full expressions) so that the `and` in
43
+// `x between a and b` is unambiguously the between-`and`, not logical `and`.
44
+Comparison: Expr = {
45
+    <l:Sum> <op:CmpOp> <r:Sum> => Expr::Compare(op, Box::new(l), Box::new(r)),
46
+    <v:Sum> "between" <lo:Sum> "and" <hi:Sum> => Expr::Between(Box::new(v), Box::new(lo), Box::new(hi)),
47
+    <v:Sum> "in" <iv:Interval> => Expr::In(Box::new(v), iv),
48
+    Sum,
49
+};
50
+
51
+CmpOp: CmpOp = {
52
+    "<"  => CmpOp::Lt,
53
+    "<=" => CmpOp::Le,
54
+    ">"  => CmpOp::Gt,
55
+    ">=" => CmpOp::Ge,
56
+    "="  => CmpOp::Eq,
57
+    "!=" => CmpOp::Ne,
58
+};
59
+
60
+Sum: Expr = {
61
+    <l:Sum> "+" <r:Product> => Expr::Arith(ArithOp::Add, Box::new(l), Box::new(r)),
62
+    <l:Sum> "-" <r:Product> => Expr::Arith(ArithOp::Sub, Box::new(l), Box::new(r)),
63
+    Product,
64
+};
65
+
66
+Product: Expr = {
67
+    <l:Product> "*" <r:Power> => Expr::Arith(ArithOp::Mul, Box::new(l), Box::new(r)),
68
+    <l:Product> "/" <r:Power> => Expr::Arith(ArithOp::Div, Box::new(l), Box::new(r)),
69
+    Power,
70
+};
71
+
72
+// Exponentiation is LEFT-associative in DMN FEEL: `3 ** 4 ** 5` == (3**4)**5
73
+// (verified against DMN-TCK 0075-feel-exponent).
74
+Power: Expr = {
75
+    <l:Power> "**" <r:Unary> => Expr::Arith(ArithOp::Pow, Box::new(l), Box::new(r)),
76
+    Unary,
77
+};
78
+
79
+// Unary minus binds tighter than `**`: `-3 ** 2` == (-3)**2 == 9 (per TCK 0075).
80
+Unary: Expr = {
81
+    "-" <e:Unary> => Expr::Neg(Box::new(e)),
2382
     Primary,
2483
 };
2584
 
2685
 Primary: Expr = {
2786
     Num => Expr::Number(<>),
87
+    Str => Expr::Str(<>),
88
+    "true" => Expr::Bool(true),
89
+    "false" => Expr::Bool(false),
90
+    "null" => Expr::Null,
91
+    List,
92
+    "not" "(" <e:Expr> ")" => Expr::Not(Box::new(e)),
93
+    "(" <e:Expr> ")" => e,
94
+    Name => Expr::Var(<>),
2895
 };
2996
 
30
-// Interval / range literal. The boolean carries openness of each endpoint.
97
+List: Expr = {
98
+    "[" "]" => Expr::List(vec![]),
99
+    "[" <es:Comma<Expr>> "]" => Expr::List(es),
100
+};
101
+
102
+// One-or-more comma-separated, no trailing comma.
103
+Comma<T>: Vec<T> = {
104
+    <mut v:(<T> ",")*> <last:T> => { v.push(last); v },
105
+};
106
+
107
+// Iteration source for `for`/`some`/`every`: a bare integer range `a..b`
108
+// (generates an ascending/descending integer list) or a list expression.
109
+IterSrc: IterSource = {
110
+    <lo:Sum> ".." <hi:Sum> => IterSource::Range(Box::new(lo), Box::new(hi)),
111
+    <e:Disjunction> => IterSource::Expr(Box::new(e)),
112
+};
113
+
114
+// Interval / range literal (only reachable after membership `in`). The boolean
115
+// carries the openness of each endpoint.
31116
 Interval: Interval = {
32
-    <so:IntervalStart> <lo:Primary> ".." <hi:Primary> <eo:IntervalEnd> =>
117
+    <so:IntervalStart> <lo:Sum> ".." <hi:Sum> <eo:IntervalEnd> =>
33118
         Interval { start_open: so, start: Box::new(lo), end: Box::new(hi), end_open: eo },
34119
 };
35120
 
@@ -43,5 +128,15 @@
43128
     ")" => true,  // open
44129
 };
45130
 
46
-// FEEL number literal (we model numbers as f64 for this slice; see DECISIONS.md).
131
+// FEEL number literal (modelled as f64 for this slice; see DECISIONS.md, ADR-2).
47132
 Num: f64 = <s:r"[0-9]+(\.[0-9]+)?"> => s.parse().expect("number literal lexed but did not parse");
133
+
134
+// FEEL string literal. Escapes are not handled in this slice (the ingested
135
+// cases use plain strings); strings are delimited by double quotes.
136
+Str: String = <s:r#""[^"]*""#> => s[1..s.len() - 1].to_string();
137
+
138
+// Simple identifier — enough for `for`/`some`/`every` loop variables and other
139
+// variable references. (Full FEEL names with spaces are only needed for
140
+// built-in function names, which are out of scope.) Keyword string-literals
141
+// take lexer precedence, so `and`/`in`/`for`/`true`/… are never parsed as names.
142
+Name: String = <s:r"[A-Za-z_][A-Za-z_0-9]*"> => s.to_string();

modified crates/feel-core/src/lib.rs +186 −44

@@ -50,6 +50,14 @@
5050
     /// Look up a bound value.
5151
     pub fn get(&self, name: &str) -> Option<&Value> {
5252
         self.vars.get(name)
53
+    }
54
+
55
+    /// Return a child context with `name` additionally bound to `value`, leaving
56
+    /// `self` unchanged. Used to scope `for`/`some`/`every` loop variables.
57
+    pub fn with(&self, name: impl Into<String>, value: Value) -> Context {
58
+        let mut child = self.clone();
59
+        child.insert(name, value);
60
+        child
5361
     }
5462
 }
5563
 
@@ -70,51 +78,185 @@
7078
 mod tests {
7179
     use super::*;
7280
 
73
-    fn empty() -> Context {
74
-        Context::empty()
75
-    }
76
-
77
-    #[test]
78
-    fn addition() {
79
-        assert_eq!(evaluate("1 + 1", &empty()).unwrap(), Value::Number(2.0));
80
-    }
81
-
82
-    #[test]
83
-    fn membership_true() {
84
-        assert_eq!(
85
-            evaluate("5 in [1..10]", &empty()).unwrap(),
86
-            Value::Boolean(true)
87
-        );
88
-    }
89
-
90
-    #[test]
91
-    fn interval_inclusivity() {
92
-        // Closed lower bound includes the endpoint; open excludes it.
93
-        assert_eq!(
94
-            evaluate("1 in [1..10]", &empty()).unwrap(),
95
-            Value::Boolean(true)
96
-        );
97
-        assert_eq!(
98
-            evaluate("1 in (1..10]", &empty()).unwrap(),
99
-            Value::Boolean(false)
100
-        );
101
-        // Closed upper bound includes; open excludes.
102
-        assert_eq!(
103
-            evaluate("10 in [1..10)", &empty()).unwrap(),
104
-            Value::Boolean(false)
105
-        );
106
-        // Out of range entirely.
107
-        assert_eq!(
108
-            evaluate("11 in [1..10]", &empty()).unwrap(),
109
-            Value::Boolean(false)
110
-        );
81
+    /// Evaluate against an empty context, panicking on error.
82
+    fn ev(src: &str) -> Value {
83
+        evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
84
+    }
85
+
86
+    fn num(n: f64) -> Value {
87
+        Value::Number(n)
88
+    }
89
+    fn b(v: bool) -> Value {
90
+        Value::Boolean(v)
91
+    }
92
+    fn list(items: Vec<Value>) -> Value {
93
+        Value::List(items)
94
+    }
95
+
96
+    #[test]
97
+    fn literals() {
98
+        assert_eq!(ev("42"), num(42.0));
99
+        assert_eq!(ev("3.5"), num(3.5));
100
+        assert_eq!(ev(r#""foo""#), Value::String("foo".into()));
101
+        assert_eq!(ev("true"), b(true));
102
+        assert_eq!(ev("false"), b(false));
103
+        assert_eq!(ev("null"), Value::Null);
104
+        assert_eq!(ev("[1, 2, 3]"), list(vec![num(1.0), num(2.0), num(3.0)]));
105
+        assert_eq!(ev("[]"), list(vec![]));
106
+    }
107
+
108
+    #[test]
109
+    fn arithmetic_and_precedence() {
110
+        assert_eq!(ev("1 + 1"), num(2.0));
111
+        assert_eq!(ev("1 + 2 * 3"), num(7.0)); // * binds tighter than +
112
+        assert_eq!(ev("(1 + 2) * 3"), num(9.0));
113
+        assert_eq!(ev("10 - 4 - 3"), num(3.0)); // - is left-associative
114
+        assert_eq!(ev("12 / 4"), num(3.0));
115
+        assert_eq!(ev("--10"), num(10.0)); // unary minus stacks
116
+    }
117
+
118
+    #[test]
119
+    fn exponent_is_left_associative_and_below_unary_minus() {
120
+        // Verified against DMN-TCK 0075-feel-exponent.
121
+        assert_eq!(ev("3 ** 4 ** 5"), num(3486784401.0)); // (3**4)**5
122
+        assert_eq!(ev("-3 ** 2"), num(9.0)); // (-3)**2
123
+        assert_eq!(ev("2 * 3 ** 2"), num(18.0)); // ** tighter than *
124
+    }
125
+
126
+    #[test]
127
+    fn type_errors_and_div_zero_are_null() {
128
+        assert_eq!(ev("1 + true"), Value::Null);
129
+        assert_eq!(ev(r#"1 + "x""#), Value::Null);
130
+        assert_eq!(ev("1 / 0"), Value::Null);
131
+        assert_eq!(ev("-true"), Value::Null);
132
+    }
133
+
134
+    #[test]
135
+    fn comparison() {
136
+        assert_eq!(ev("1 < 2"), b(true));
137
+        assert_eq!(ev("2 <= 2"), b(true));
138
+        assert_eq!(ev("3 > 5"), b(false));
139
+        assert_eq!(ev(r#""apple" < "banana""#), b(true)); // lexicographic
140
+        assert_eq!(ev("1 < null"), Value::Null); // ordering with null -> null
141
+        assert_eq!(ev("1 < true"), Value::Null); // incomparable types -> null
142
+    }
143
+
144
+    #[test]
145
+    fn equality_three_valued() {
146
+        // Values taken from DMN-TCK 0068-feel-equality.
147
+        assert_eq!(ev("null = null"), b(true));
148
+        assert_eq!(ev("null != null"), b(false));
149
+        assert_eq!(ev("true = null"), b(false));
150
+        assert_eq!(ev("true = false"), b(false));
151
+        assert_eq!(ev("123 = 123"), b(true));
152
+        assert_eq!(ev("-1 = 1"), b(false));
153
+        assert_eq!(ev(r#""foo" = "foo""#), b(true));
154
+        assert_eq!(ev(r#""foo" != "Foo""#), b(true));
155
+        // Different non-null types compare to null, not false.
156
+        assert_eq!(ev("false = 0"), Value::Null);
157
+        assert_eq!(ev(r#"100 = "100""#), Value::Null);
158
+        // Lists compare structurally.
159
+        assert_eq!(ev("[1,2,3] = [1,2,3]"), b(true));
160
+        assert_eq!(ev("[1,1,1] = [1,1,1,1]"), b(false));
161
+        assert_eq!(ev("[1,2,3] = [3,2,1]"), b(false));
162
+        assert_eq!(ev("[] = []"), b(true));
163
+        assert_eq!(ev("[] = null"), b(false));
164
+    }
165
+
166
+    #[test]
167
+    fn between() {
168
+        assert_eq!(ev("5 between 1 and 10"), b(true));
169
+        assert_eq!(ev("1 between 1 and 10"), b(true)); // inclusive
170
+        assert_eq!(ev("0 between 1 and 10"), b(false));
171
+        assert_eq!(ev(r#""c" between "b" and "d""#), b(true));
172
+    }
173
+
174
+    #[test]
175
+    fn logic_three_valued() {
176
+        // Values taken from DMN-TCK 0064/0065/0066.
177
+        assert_eq!(ev("true and true"), b(true));
178
+        assert_eq!(ev("true and false"), b(false));
179
+        assert_eq!(ev("true and null"), Value::Null);
180
+        assert_eq!(ev("false and null"), b(false)); // false dominates
181
+        assert_eq!(ev("false and 123"), b(false));
182
+        assert_eq!(ev("true and 123"), Value::Null); // non-boolean -> null
183
+        assert_eq!(ev("true or false"), b(true));
184
+        assert_eq!(ev("true or null"), b(true)); // true dominates
185
+        assert_eq!(ev("false or null"), Value::Null);
186
+        assert_eq!(ev("123 or true"), b(true));
187
+        assert_eq!(ev("not(true)"), b(false));
188
+        assert_eq!(ev("not(false)"), b(true));
189
+        assert_eq!(ev("not(null)"), Value::Null);
190
+        assert_eq!(ev("not(0)"), Value::Null);
191
+    }
192
+
193
+    #[test]
194
+    fn membership_and_interval_inclusivity() {
195
+        assert_eq!(ev("5 in [1..10]"), b(true));
196
+        assert_eq!(ev("1 in [1..10]"), b(true)); // closed lower includes
197
+        assert_eq!(ev("1 in (1..10]"), b(false)); // open lower excludes
198
+        assert_eq!(ev("10 in [1..10)"), b(false)); // open upper excludes
199
+        assert_eq!(ev("11 in [1..10]"), b(false)); // out of range
200
+    }
201
+
202
+    #[test]
203
+    fn if_then_else() {
204
+        assert_eq!(ev("if true then 1 else 2"), num(1.0));
205
+        assert_eq!(ev("if false then 1 else 2"), num(2.0));
206
+        assert_eq!(ev("if 1 < 2 then 10 else 20"), num(10.0));
207
+        assert_eq!(ev("if 5 then 1 else 2"), Value::Null); // non-boolean condition
208
+    }
209
+
210
+    #[test]
211
+    fn for_loops() {
212
+        assert_eq!(
213
+            ev("for i in [1,2,3] return i + 1"),
214
+            list(vec![num(2.0), num(3.0), num(4.0)])
215
+        );
216
+        assert_eq!(ev("for i in [] return i"), list(vec![]));
217
+        assert_eq!(
218
+            ev("for i in 2..4 return i"),
219
+            list(vec![num(2.0), num(3.0), num(4.0)])
220
+        );
221
+        assert_eq!(
222
+            ev("for i in 4..2 return i"), // descending
223
+            list(vec![num(4.0), num(3.0), num(2.0)])
224
+        );
225
+        assert_eq!(
226
+            ev("for i in -1..1 return i"),
227
+            list(vec![num(-1.0), num(0.0), num(1.0)])
228
+        );
229
+        // body may itself be a control-flow expression
230
+        assert_eq!(
231
+            ev("for i in [1,2,3] return if i = 2 then 0 else i"),
232
+            list(vec![num(1.0), num(0.0), num(3.0)])
233
+        );
234
+        // nested for
235
+        assert_eq!(
236
+            ev("for x in [[1,2],[3,4]] return for y in x return y"),
237
+            list(vec![
238
+                list(vec![num(1.0), num(2.0)]),
239
+                list(vec![num(3.0), num(4.0)]),
240
+            ])
241
+        );
242
+    }
243
+
244
+    #[test]
245
+    fn quantifiers() {
246
+        assert_eq!(ev("some i in [1,2,3] satisfies i > 2"), b(true));
247
+        assert_eq!(ev("some i in [1,2,3] satisfies i > 5"), b(false));
248
+        assert_eq!(ev("every i in [2,4,6] satisfies i > 1"), b(true));
249
+        assert_eq!(ev("every i in [1,2,3] satisfies i > 2"), b(false));
250
+        // empty list: some -> false, every -> true
251
+        assert_eq!(ev("some i in [] satisfies i > 0"), b(false));
252
+        assert_eq!(ev("every i in [] satisfies i > 0"), b(true));
253
+        // range source
254
+        assert_eq!(ev("every i in 1..5 satisfies i > 0"), b(true));
111255
     }
112256
 
113257
     #[test]
114258
     fn parse_error_is_reported() {
115
-        assert!(matches!(
116
-            evaluate("1 +", &empty()),
117
-            Err(FeelError::Parse(_))
118
-        ));
119
-    }
120
-}
259
+        assert!(matches!(evaluate("1 +", &Context::empty()), Err(FeelError::Parse(_))));
260
+        assert!(matches!(evaluate("if x then", &Context::empty()), Err(FeelError::Parse(_))));
261
+    }
262
+}

modified crates/feel-core/src/value.rs +7 −2

@@ -1,12 +1,17 @@
11
 //! Runtime values.
22
 
3
-/// The minimal value domain for this slice.
3
+/// The value domain for the core-language slice.
44
 ///
55
 /// Numbers are `f64` for now — a deliberate, documented deviation from the
6
-/// FEEL spec's `decimal128` (see DECISIONS.md).
6
+/// FEEL spec's `decimal128` (see DECISIONS.md, ADR-2). Strings and lists were
7
+/// added when the slice grew from "numbers + intervals" to the core language
8
+/// (operators, control flow, `for`/`some`/`every`); there is deliberately no
9
+/// context/map value type yet (see ADR-7).
710
 #[derive(Debug, Clone, PartialEq)]
811
 pub enum Value {
912
     Number(f64),
1013
     Boolean(bool),
14
+    String(String),
15
+    List(Vec<Value>),
1116
     Null,
1217
 }