Public repository: timo / feel

Reader

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

feel / crates / feel-core / src / ast.rs · 19.5 KB · at da382279c66c · raw

Outline: 20 definitions
1
//! Abstract syntax tree produced by the generated parser.
2
3
/// A parsed FEEL expression (core-language slice).
4
#[derive(Debug, Clone, PartialEq)]
5
pub enum Expr {
6
    // --- literals ---
7
    /// Numeric literal.
8
    Number(f64),
9
    /// String literal.
10
    Str(String),
11
    /// A temporal literal `@"…"` (date/time/date-and-time/duration; ADR-18). The
12
    /// string is the inner text; its type is resolved at evaluation from the form.
13
    TemporalLit(String),
14
    /// Boolean literal (`true` / `false`).
15
    Bool(bool),
16
    /// The `null` literal.
17
    Null,
18
    /// List literal, e.g. `[1, 2, 3]` or `[]`.
19
    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),
25
    /// Context literal, e.g. `{a: 1, b: a + 1}`. Entries are ordered as written;
26
    /// later entries may reference earlier ones (progressive binding).
27
    ContextLit(Vec<(String, Box<Expr>)>),
28
    /// Variable / name reference (e.g. a `for`/`some`/`every` loop variable).
29
    Var(String),
30
    /// Member / path access on a context, e.g. `person.age`. When the left-hand
31
    /// side is a list of contexts, the access is mapped over the list and returns
32
    /// a list of selections (DMN §10.3.2.5), e.g. `[{x:1},{x:2}].x = [1, 2]`.
33
    Path(Box<Expr>, String),
34
    /// Descendant navigation `e ... name` (DMN §10.3.2.7, grammar rule 68): collect
35
    /// every value bound to `name` in `e` and all of its nested contexts (and lists
36
    /// of contexts), depth-first, into a list. Unlike [`Path`](Expr::Path) (a shallow
37
    /// single-level selection), this is a recursive traversal — the engine's first
38
    /// *unbounded* collection, so a cyclic host graph behind [`Value::Foreign`]
39
    /// requires a visited-set guard in the evaluator (see `descendant_collect`).
40
    Descendant(Box<Expr>, String),
41
    /// Filter / index `collection[bracket]` (DMN §10.3.2.5). A numeric bracket is
42
    /// a 1-based index (negative-from-end, out-of-range → null); any other bracket
43
    /// is a boolean filter evaluated per element with the element bound as `item`.
44
    Filter(Box<Expr>, Box<Expr>),
45
    /// A function call by name, e.g. `count([1,2,3])`, `abs(-1)`, or — for a
46
    /// user-defined / host function bound in scope — `myFn(a, b: 2)`. The string is
47
    /// the function name; [`CallArgs`] carries the (possibly mixed) positional and
48
    /// named arguments. Dispatch (context function / built-in / host registry) is
49
    /// resolved at evaluation (ADR-23).
50
    FnCall(String, CallArgs),
51
    /// Invocation of a *value* callee, e.g. `123()`, `"abs"(-1)`, `null()` (ADR-38).
52
    /// Distinct from [`FnCall`]: here the callee expression is evaluated first; if it
53
    /// is not a [`Value::Function`] the call yields null (DMN §10.3.2.13.2). The
54
    /// grammar only produces this for literal callees (never for a `Name`), so today
55
    /// every `Invoke` evaluates to null; the function branch is the correct general
56
    /// semantics should the callee grammar widen in future.
57
    Invoke(Box<Expr>, CallArgs),
58
    /// A FEEL function literal `function(a, b) body` — an anonymous closure that
59
    /// captures the scope it is defined in (ADR-23). `params` are the formal
60
    /// parameter names in order, each paired with an optional type annotation
61
    /// (FEEL grammar rule 56, `name: Type`; `None` when untyped). The type
62
    /// annotation is used at invocation for implicit coercion (§10.3.2.9.4).
63
    FnDef {
64
        params: Vec<(String, Option<FeelType>)>,
65
        body: Box<Expr>,
66
    },
67
68
    // --- arithmetic ---
69
    /// Unary arithmetic negation `-x`.
70
    Neg(Box<Expr>),
71
    /// Binary arithmetic `lhs <op> rhs`.
72
    Arith(ArithOp, Box<Expr>, Box<Expr>),
73
74
    // --- comparison ---
75
    /// Binary comparison `lhs <op> rhs`.
76
    Compare(CmpOp, Box<Expr>, Box<Expr>),
77
    /// `value between low and high` — sugar for `low <= value and value <= high`.
78
    Between(Box<Expr>, Box<Expr>, Box<Expr>),
79
    /// Membership test `value in <tests>` (DMN §10.3.2.6, grammar rule 49). The
80
    /// right-hand side is one or more *positive unary tests* (an interval, an
81
    /// `<op> endpoint` comparison, or a bare expression meaning equality), combined
82
    /// with OR. See [`UnaryTest`]. A `not(…)` on the RHS is *test* negation
83
    /// ([`UnaryTest::Not`]), `x in not(t)` ≡ `not(x satisfies t)` (Kleene), never the
84
    /// boolean `not(…)` built-in.
85
    In(Box<Expr>, Vec<UnaryTest>),
86
    /// A parenthesised comparison-test *value* in value position — `(< 10)`,
87
    /// `(= 10)`, `(!= 10)` (DMN §10.3.4.6). Distinct from a [`Compare`](Expr::Compare):
88
    /// here the comparison has no left operand, so it is not a boolean but an **opaque
89
    /// unary-test value** ([`Value::UnaryTestVal`](crate::Value::UnaryTestVal)) with
90
    /// reflexive, range-*incompatible* equality (ADR-32) — `(<10) = (<10)` is true but
91
    /// `(<10) = (null..10)` is false. The `in`-position forms (`x in (=10)`) keep the
92
    /// dedicated [`UnaryTest::Compare`] test; this is the value-position sibling.
93
    UnaryTestVal(CmpOp, Box<Expr>),
94
    /// Type predicate `value instance of type` (DMN §10.3.2.9, grammar rule 51).
95
    /// The right operand is a [`FeelType`] resolved at parse time (it carries no
96
    /// runtime data); an unmappable type name parses as [`FeelType::Unknown`] so
97
    /// `123 instance of list` evaluates to `null` rather than failing to parse.
98
    InstanceOf(Box<Expr>, FeelType),
99
100
    // --- logic (three-valued / Kleene) ---
101
    And(Box<Expr>, Box<Expr>),
102
    Or(Box<Expr>, Box<Expr>),
103
    Not(Box<Expr>),
104
105
    // --- control flow ---
106
    /// `if cond then then_branch else else_branch`.
107
    If(Box<Expr>, Box<Expr>, Box<Expr>),
108
    /// `for var in source { , var in source } return body`. One or more
109
    /// iteration contexts (FEEL grammar rule 44): the body is evaluated over the
110
    /// Cartesian product of the sources, in declaration order with the rightmost
111
    /// context varying fastest. Each source may reference the variables of the
112
    /// contexts to its left (it is evaluated in their scope).
113
    For {
114
        bindings: Vec<(String, IterSource)>,
115
        body: Box<Expr>,
116
    },
117
    /// `some|every var in source { , var in source } satisfies predicate` (FEEL
118
    /// grammar rule 46). Like [`Expr::For`], the predicate ranges over the
119
    /// Cartesian product of the (left-to-right scoped) sources.
120
    Quantified {
121
        kind: Quantifier,
122
        bindings: Vec<(String, IterSource)>,
123
        predicate: Box<Expr>,
124
    },
125
}
126
127
/// Arguments of an [`Expr::FnCall`]: positional and named are kept apart, and may
128
/// appear **mixed** in one call (`f(2, b: 3)`) — see ADR-23 (a deliberate, tolerant
129
/// superset of FEEL spec rule 39). An empty `positional` and `named` is a no-arg
130
/// call.
131
#[derive(Debug, Clone, PartialEq, Default)]
132
pub struct CallArgs {
133
    pub positional: Vec<Expr>,
134
    pub named: Vec<(String, Expr)>,
135
}
136
137
/// One parsed argument, before it is sorted into [`CallArgs`]. Used only by the
138
/// grammar action [`callargs_from`]; not stored in the AST.
139
pub enum ArgEntry {
140
    Pos(Expr),
141
    Named(String, Expr),
142
}
143
144
/// Sort a parsed argument list into [`CallArgs`], preserving the order within each
145
/// group. Mixing positional and named is allowed (ADR-23).
146
pub fn callargs_from(entries: Vec<ArgEntry>) -> CallArgs {
147
    let mut out = CallArgs::default();
148
    for entry in entries {
149
        match entry {
150
            ArgEntry::Pos(e) => out.positional.push(e),
151
            ArgEntry::Named(name, e) => out.named.push((name, e)),
152
        }
153
    }
154
    out
155
}
156
157
/// Binary arithmetic operators.
158
#[derive(Debug, Clone, Copy, PartialEq)]
159
pub enum ArithOp {
160
    Add,
161
    Sub,
162
    Mul,
163
    Div,
164
    /// Exponentiation `**` (right-associative).
165
    Pow,
166
}
167
168
/// Comparison operators.
169
#[derive(Debug, Clone, Copy, PartialEq)]
170
pub enum CmpOp {
171
    Lt,
172
    Le,
173
    Gt,
174
    Ge,
175
    Eq,
176
    Ne,
177
}
178
179
/// Which quantifier a [`Expr::Quantified`] is.
180
#[derive(Debug, Clone, Copy, PartialEq)]
181
pub enum Quantifier {
182
    Some,
183
    Every,
184
}
185
186
/// The `in` source of a `for`/`some`/`every` loop.
187
#[derive(Debug, Clone, PartialEq)]
188
pub enum IterSource {
189
    /// Any expression that should evaluate to a list (e.g. `[1,2,3]` or a var).
190
    Expr(Box<Expr>),
191
    /// A bare integer range `start..end` (e.g. `for i in 2..4`), generating an
192
    /// ascending or descending integer list. Distinct from an interval literal.
193
    Range(Box<Expr>, Box<Expr>),
194
}
195
196
/// An interval (range) literal, e.g. `[1..10)`.
197
///
198
/// `start_open`/`end_open` encode the bracket: `[`/`]` are closed (inclusive),
199
/// `(`/`)` are open (exclusive).
200
///
201
/// An endpoint is `None` when it was **syntactically omitted** — an *unbounded*
202
/// bound, `±∞` (`[1..)` is everything `≥ 1`, `(..10]` everything `≤ 10`; ADR-31).
203
/// This is semantically distinct from a *present* `null` endpoint (`Some(Expr::Null)`),
204
/// which keeps the three-valued "unknown" membership of `[null..10]`. The openness
205
/// flag of an omitted endpoint is meaningless (`±∞` is never a member); every
206
/// semantic operation ignores it on the unbounded side.
207
#[derive(Debug, Clone, PartialEq)]
208
pub struct Interval {
209
    pub start_open: bool,
210
    pub start: Option<Box<Expr>>,
211
    pub end: Option<Box<Expr>>,
212
    pub end_open: bool,
213
}
214
215
/// One positive unary test (DMN grammar rule 54): an interval, an `<op> endpoint`
216
/// comparison, or — for a bare expression — an equality (`= endpoint`).
217
#[derive(Debug, Clone, PartialEq)]
218
pub enum UnaryTest {
219
    /// `< e`, `<= e`, `> e`, `>= e`, `= e`, `!= e`. A bare endpoint parses as
220
    /// `Compare(Eq, e)` (so `x in 3` means `x = 3`, and `x in [a,b]` is `= a` OR
221
    /// `= b`).
222
    Compare(CmpOp, Box<Expr>),
223
    /// An interval test `[a..b]` / `(a..b)` / … (the bracket openness in [`Interval`]).
224
    Interval(Interval),
225
    /// A bare endpoint expression on the right of `in`, e.g. `x in e`. Evaluated as
226
    /// equality `x = e` when `e` is a scalar, or as range *membership* when `e`
227
    /// evaluates to a [`range`](crate::Value::Range) value — so `2 in range("[1..3]")`
228
    /// is a containment test, not `2 = <range>` (DMN §10.3.2.6). A *written* interval
229
    /// literal `[a..b]` keeps the dedicated [`UnaryTest::Interval`] form instead (see
230
    /// [`unary_test_from_expr`]), so existing interval tests are unchanged.
231
    Endpoint(Box<Expr>),
232
    /// Negation of a positive unary-test list, `x in not(t1, t2, …)` (DMN §10.3.2.6,
233
    /// grammar rule 49). In the unary-test context `not(…)` is **always** test
234
    /// negation — `x in not(t)` ≡ `not(x satisfies t)`, three-valued/Kleene — and is
235
    /// *not* the boolean `not(…)` built-in. The inner tests are OR-folded (the same
236
    /// disjunction as a bare list) and the result negated, so `x in not(1,2,3)` ≡
237
    /// `not(x = 1 or x = 2 or x = 3)`. Each inner endpoint becomes a test via
238
    /// [`unary_test_from_expr`], so `not(5)` is the negation of the `= 5` test and
239
    /// `not(< 5)` / `not([1..10])` negate a comparison / interval test.
240
    Not(Vec<UnaryTest>),
241
}
242
243
/// Build the unary test for a bare RHS expression `x in e`. A written interval
244
/// literal keeps the dedicated [`UnaryTest::Interval`] test (so `x in [a..b]` is
245
/// byte-for-byte unchanged); every other expression becomes an
246
/// [`UnaryTest::Endpoint`] (equality, or range membership if it evaluates to a range).
247
pub fn unary_test_from_expr(e: Expr) -> UnaryTest {
248
    match e {
249
        Expr::RangeLit(iv) => UnaryTest::Interval(iv),
250
        other => UnaryTest::Endpoint(Box::new(other)),
251
    }
252
}
253
254
/// A node in the FEEL type lattice **L** (DMN §10.3.2.9), the right operand of
255
/// `instance of`. Built from the restricted `type` grammar (spec rule 52) at parse
256
/// time. Primitive nodes plus the top/bottom (`Any`/`Null`) and the parameterised
257
/// `list`/`range`/`context`/`function` nodes are modelled; an unmappable type name
258
/// (a model `itemDefinition` type this standalone engine can't resolve, a typo, or a
259
/// bare `list`/`context` that "requires parameters") becomes [`FeelType::Unknown`],
260
/// which makes the predicate evaluate to `null` (spec: "type cannot be mapped to L").
261
#[derive(Debug, Clone, PartialEq)]
262
pub enum FeelType {
263
    Any,
264
    Null,
265
    Number,
266
    String,
267
    Boolean,
268
    Date,
269
    Time,
270
    DateTime,
271
    YearsMonthsDuration,
272
    DaysTimeDuration,
273
    List(Box<FeelType>),
274
    Range(Box<FeelType>),
275
    /// Context type `context<k1: T1, …>`; fields kept in written order.
276
    Context(Vec<(String, FeelType)>),
277
    /// Function type `function<T1, …> -> U` (params, return).
278
    Function(Vec<FeelType>, Box<FeelType>),
279
    /// A type expression that cannot be mapped to a node in **L**.
280
    Unknown,
281
}
282
283
impl FeelType {
284
    /// `true` unless an [`Unknown`](FeelType::Unknown) appears anywhere in the tree.
285
    /// The evaluator short-circuits an unmappable type to `null` (spec rule 51).
286
    pub(crate) fn is_mappable(&self) -> bool {
287
        match self {
288
            FeelType::Unknown => false,
289
            FeelType::List(t) | FeelType::Range(t) => t.is_mappable(),
290
            FeelType::Context(fields) => fields.iter().all(|(_, t)| t.is_mappable()),
291
            FeelType::Function(params, ret) => {
292
                params.iter().all(FeelType::is_mappable) && ret.is_mappable()
293
            }
294
            _ => true,
295
        }
296
    }
297
}
298
299
/// One argument inside a generic type's `<…>` (used only by the grammar). A bare
300
/// type (`list<number>`, `range<date>`, `function` params) or a named field
301
/// (`context<a: string>`). Sorted out by [`generic_type`]; not stored in the AST.
302
pub enum TypeArg {
303
    Ty(FeelType),
304
    Field(String, FeelType),
305
}
306
307
/// Map a (possibly multi-word) type-name to its lattice node. Unrecognised names —
308
/// model `itemDefinition` types, typos, and the bare collection names that require
309
/// parameters (`list`, `context`, `range`, `function`) — become
310
/// [`FeelType::Unknown`] (⇒ predicate `null`, matching the spec `123 instance of
311
/// list → null`).
312
pub fn simple_type(name: &str) -> FeelType {
313
    match name {
314
        "Any" => FeelType::Any,
315
        "Null" => FeelType::Null,
316
        "number" => FeelType::Number,
317
        "string" => FeelType::String,
318
        "boolean" => FeelType::Boolean,
319
        "date" => FeelType::Date,
320
        "time" => FeelType::Time,
321
        "date and time" => FeelType::DateTime,
322
        "years and months duration" => FeelType::YearsMonthsDuration,
323
        "days and time duration" => FeelType::DaysTimeDuration,
324
        _ => FeelType::Unknown,
325
    }
326
}
327
328
/// Build a parameterised type from a generic head (`list`/`range`/`context`) and its
329
/// `<…>` arguments. A wrong head, wrong arity, or a type/field mismatch (a field in
330
/// `list<…>`, or a bare type in `context<…>`) yields [`FeelType::Unknown`].
331
pub fn generic_type(head: String, args: Vec<TypeArg>) -> FeelType {
332
    match head.as_str() {
333
        "list" | "range" => match <[TypeArg; 1]>::try_from(args) {
334
            Ok([TypeArg::Ty(t)]) => {
335
                let t = Box::new(t);
336
                if head == "list" {
337
                    FeelType::List(t)
338
                } else {
339
                    FeelType::Range(t)
340
                }
341
            }
342
            _ => FeelType::Unknown,
343
        },
344
        "context" => {
345
            let mut fields = Vec::with_capacity(args.len());
346
            for arg in args {
347
                match arg {
348
                    TypeArg::Field(k, t) => fields.push((k, t)),
349
                    TypeArg::Ty(_) => return FeelType::Unknown,
350
                }
351
            }
352
            FeelType::Context(fields)
353
        }
354
        _ => FeelType::Unknown,
355
    }
356
}
357
358
impl Expr {
359
    /// `true` if evaluating this expression can never read the wall clock — i.e.
360
    /// it calls neither `now()` nor `today()` anywhere in the tree, including
361
    /// nested function literals, list/context entries, and loop sources/bodies.
362
    ///
363
    /// This is the *static* half of IMMUTABLE eligibility (exposed as
364
    /// [`crate::CompiledExpr::is_clock_free`]). It deliberately does **not**
365
    /// consider named time zones (a runtime/data property, vetted via
366
    /// [`crate::EvalEnv::forbidding_named_zones`]) nor host functions (the
367
    /// embedder's concern — feel-pg has no host-function seam). The match is
368
    /// exhaustive so a new `Expr` variant forces this to be reconsidered.
369
    pub(crate) fn is_clock_free(&self) -> bool {
370
        match self {
371
            Expr::Number(_)
372
            | Expr::Str(_)
373
            | Expr::TemporalLit(_)
374
            | Expr::Bool(_)
375
            | Expr::Null
376
            | Expr::Var(_) => true,
377
            Expr::List(items) => items.iter().all(Expr::is_clock_free),
378
            Expr::RangeLit(iv) => interval_is_clock_free(iv),
379
            Expr::ContextLit(entries) => entries.iter().all(|(_, e)| e.is_clock_free()),
380
            Expr::Path(target, _) => target.is_clock_free(),
381
            Expr::Descendant(target, _) => target.is_clock_free(),
382
            Expr::Filter(source, bracket) => {
383
                source.is_clock_free() && bracket.is_clock_free()
384
            }
385
            // `now`/`today` are the only clock-reading built-ins (ADR-18). Any
386
            // call by those names is treated as a clock read regardless of args.
387
            Expr::FnCall(name, args) => {
388
                name != "now"
389
                    && name != "today"
390
                    && args.positional.iter().all(Expr::is_clock_free)
391
                    && args.named.iter().all(|(_, e)| e.is_clock_free())
392
            }
393
            Expr::Invoke(callee, args) => {
394
                callee.is_clock_free()
395
                    && args.positional.iter().all(Expr::is_clock_free)
396
                    && args.named.iter().all(|(_, e)| e.is_clock_free())
397
            }
398
            Expr::FnDef { body, .. } => body.is_clock_free(),
399
            Expr::Neg(e) | Expr::Not(e) | Expr::UnaryTestVal(_, e) => e.is_clock_free(),
400
            Expr::Arith(_, a, b) | Expr::Compare(_, a, b) | Expr::And(a, b) | Expr::Or(a, b) => {
401
                a.is_clock_free() && b.is_clock_free()
402
            }
403
            Expr::Between(a, b, c) | Expr::If(a, b, c) => {
404
                a.is_clock_free() && b.is_clock_free() && c.is_clock_free()
405
            }
406
            Expr::In(value, tests) => {
407
                value.is_clock_free() && tests.iter().all(UnaryTest::is_clock_free)
408
            }
409
            // The type operand is static (resolved to a `FeelType` at parse time, no
410
            // nested `Expr`), so only the value expression can read the clock.
411
            Expr::InstanceOf(value, _ty) => value.is_clock_free(),
412
            Expr::For { bindings, body } => {
413
                bindings.iter().all(|(_, s)| s.is_clock_free()) && body.is_clock_free()
414
            }
415
            Expr::Quantified {
416
                bindings,
417
                predicate,
418
                ..
419
            } => bindings.iter().all(|(_, s)| s.is_clock_free()) && predicate.is_clock_free(),
420
        }
421
    }
422
}
423
424
impl IterSource {
425
    fn is_clock_free(&self) -> bool {
426
        match self {
427
            IterSource::Expr(e) => e.is_clock_free(),
428
            IterSource::Range(a, b) => a.is_clock_free() && b.is_clock_free(),
429
        }
430
    }
431
}
432
433
/// Both endpoints of an interval are clock-free — an omitted (unbounded, `None`)
434
/// endpoint is trivially clock-free (ADR-31).
435
fn interval_is_clock_free(iv: &Interval) -> bool {
436
    iv.start.as_ref().is_none_or(|e| e.is_clock_free())
437
        && iv.end.as_ref().is_none_or(|e| e.is_clock_free())
438
}
439
440
impl UnaryTest {
441
    fn is_clock_free(&self) -> bool {
442
        match self {
443
            UnaryTest::Compare(_, e) | UnaryTest::Endpoint(e) => e.is_clock_free(),
444
            UnaryTest::Interval(iv) => interval_is_clock_free(iv),
445
            UnaryTest::Not(tests) => tests.iter().all(UnaryTest::is_clock_free),
446
        }
447
    }
448
}