Public repository: timo / feel

Reader

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

feat(core): coerce() + typed formal parameters (ADR-35 follow-up, §10.3.2.9.4)

public

feat(core): coerce() + typed formal parameters (ADR-35 follow-up, §10.3.2.9.4)

Add `coerce(value, &FeelType) -> Value` to types.rs implementing the four
§10.3.2.9.4 implicit-conversion rules (null pass-through, from-singleton-list,
to-singleton-list, conforms-to).  Expose it as `pub fn coerce` + `pub fn
parse_type` from the crate root alongside `pub use ast::FeelType`.

Promote formal-parameter type annotations from discarded (ADR-35) to preserved:
FormalParam in the grammar now returns `(String, Option<FeelType>)`; Expr::FnDef,
Closure, and bind_params carry the change through.  bind_params applies coercion
to every typed actual argument after binding — a non-conforming arg returns Err(()),
which invoke_closure maps to error-null, matching the invocation-context coercion
the spec mandates (decision_bkm_002, fd_002).

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

modified crates/feel-core/src/ast.rs +4 −2

@@ -50,9 +50,11 @@
5050
     Invoke(Box<Expr>, CallArgs),
5151
     /// A FEEL function literal `function(a, b) body` — an anonymous closure that
5252
     /// captures the scope it is defined in (ADR-23). `params` are the formal
53
-    /// parameter names in order.
53
+    /// parameter names in order, each paired with an optional type annotation
54
+    /// (FEEL grammar rule 56, `name: Type`; `None` when untyped). The type
55
+    /// annotation is used at invocation for implicit coercion (§10.3.2.9.4).
5456
     FnDef {
55
-        params: Vec<String>,
57
+        params: Vec<(String, Option<FeelType>)>,
5658
         body: Box<Expr>,
5759
     },
5860
 

modified crates/feel-core/src/eval.rs +28 −6

@@ -348,20 +348,25 @@
348348
 /// Bind call arguments to a closure's formal parameters, returning the body scope
349349
 /// (the captured scope extended with the bindings). `Err(())` signals
350350
 /// non-conformance: an unknown named parameter, a parameter supplied both
351
-/// positionally and by name, or more positional arguments than parameters. An
352
-/// unsupplied parameter is bound to value-null (spec §10.3.2.13.5).
353
-fn bind_params(captured: &Context, params: &[String], args: Args) -> Result<Context, ()> {
351
+/// positionally and by name, more positional arguments than parameters, or a
352
+/// typed parameter whose actual argument fails §10.3.2.9.4 implicit conversion.
353
+/// An unsupplied parameter is bound to value-null (spec §10.3.2.13.5).
354
+fn bind_params(
355
+    captured: &Context,
356
+    params: &[(String, Option<FeelType>)],
357
+    args: Args,
358
+) -> Result<Context, ()> {
354359
     if args.positional.len() > params.len() {
355360
         return Err(()); // too many positional arguments
356361
     }
357362
     let mut scope = captured.clone();
358363
     let mut bound = vec![false; params.len()];
359364
     for (i, value) in args.positional.into_iter().enumerate() {
360
-        scope.insert(params[i].clone(), value);
365
+        scope.insert(params[i].0.clone(), value);
361366
         bound[i] = true;
362367
     }
363368
     for (name, value) in args.named {
364
-        match params.iter().position(|p| *p == name) {
369
+        match params.iter().position(|(p, _)| p == &name) {
365370
             Some(i) if !bound[i] => {
366371
                 scope.insert(name, value);
367372
                 bound[i] = true;
@@ -370,9 +375,26 @@
370375
             None => return Err(()),    // unknown parameter name
371376
         }
372377
     }
373
-    for (i, param) in params.iter().enumerate() {
378
+    for (i, (param, _)) in params.iter().enumerate() {
374379
         if !bound[i] {
375380
             scope.insert(param.clone(), Value::Null); // unsupplied -> value-null
381
+        }
382
+    }
383
+    // Apply invocation-context implicit conversions (§10.3.2.9.4): for each
384
+    // typed formal parameter, coerce the actual argument. A null argument has
385
+    // type `Null <: T` and is left as-is; a coercion failure (non-conforming
386
+    // actual) aborts the entire call → error-null (`decision_bkm_002`, `fd_002`).
387
+    for (name, ty) in params {
388
+        if let Some(t) = ty {
389
+            if let Some(v) = scope.get(name) {
390
+                if !matches!(v, Value::Null) {
391
+                    let coerced = crate::types::coerce(v.clone(), t);
392
+                    if matches!(coerced, Value::Null) {
393
+                        return Err(());
394
+                    }
395
+                    scope.insert(name.clone(), coerced);
396
+                }
397
+            }
376398
         }
377399
     }
378400
     Ok(scope)

modified crates/feel-core/src/feel.lalrpop +15 −12

@@ -80,6 +80,10 @@
8080
 
8181
 pub Expr: Expr = TextualExpr;
8282
 
83
+/// A structural FEEL type expression (`number`, `list<string>`,
84
+/// `context<a: number>`, …), used by `parse_type` at the crate root.
85
+pub Type: FeelType = InstanceType;
86
+
8387
 // Loosest-binding forms. `for`/`if`/`some`/`every` extend to the end of their
8488
 // sub-expressions (which are themselves full TextualExprs), enabling nesting
8589
 // like `for i in [1,2,3] return if i > 0 then i else -i`.
@@ -97,12 +101,11 @@
97101
         Expr::Quantified { kind: Quantifier::Some, bindings: bs, predicate: Box::new(p) },
98102
     "every" <bs:Comma<IterCtx>> "satisfies" <p:TextualExpr> =>
99103
         Expr::Quantified { kind: Quantifier::Every, bindings: bs, predicate: Box::new(p) },
100
-    // A FEEL function literal `function(a, b) body` (ADR-23/ADR-35). Like `if`/`for`,
101
-    // the body is a full TextualExpr, so it extends to the end of the sub-expression.
102
-    // `function` is a keyword token, so `function(` is unambiguously a literal (not
103
-    // a call). Each formal parameter is a bare name or an optionally typed name
104
-    // `name: Type` (FEEL grammar rule 56, ADR-35); the type annotation is parsed and
105
-    // discarded — this slice binds by name only, and arity is `params.len()`.
104
+    // A FEEL function literal `function(a, b) body` (ADR-23/ADR-35 follow-up). Like
105
+    // `if`/`for`, the body is a full TextualExpr. `function` is a keyword token so
106
+    // `function(` is unambiguously a literal. Each formal parameter is a bare name or
107
+    // a typed name `name: Type` (FEEL grammar rule 56); the optional type annotation
108
+    // is now preserved alongside the name for invocation-context coercion (§10.3.2.9.4).
106109
     "function" "(" ")" <b:TextualExpr> =>
107110
         Expr::FnDef { params: vec![], body: Box::new(b) },
108111
     "function" "(" <ps:Comma<FormalParam>> ")" <b:TextualExpr> =>
@@ -247,15 +250,15 @@
247250
     <e:Expr> => ArgEntry::Pos(e),
248251
 };
249252
 
250
-// One formal parameter in a function literal (FEEL grammar rule 56, ADR-35).
253
+// One formal parameter in a function literal (FEEL grammar rule 56, ADR-35 follow-up).
251254
 // Either a bare name (`a`) or a typed name (`a: number`, `fn1: function<number>->number`).
252
-// The type annotation is parsed via the existing `InstanceType` grammar and discarded
253
-// — this slice binds arguments by name only; arity is already `params.len()`.
255
+// The type annotation is preserved alongside the name for invocation-context coercion
256
+// (§10.3.2.9.4): `None` for an untyped parameter, `Some(t)` when a type is present.
254257
 // LR(1)-clean: after `Name`, a lookahead `:` shifts into the typed branch while
255258
 // `,`/`)` reduce to the bare branch (mirrors the `Arg` rule's one-token decision).
256
-FormalParam: String = {
257
-    <n:Name> => n,
258
-    <n:Name> ":" InstanceType => n,
259
+FormalParam: (String, Option<FeelType>) = {
260
+    <n:Name> => (n, None),
261
+    <n:Name> ":" <t:InstanceType> => (n, Some(t)),
259262
 };
260263
 
261264
 Primary: Expr = {

modified crates/feel-core/src/function.rs +6 −3

@@ -64,11 +64,14 @@
6464
     fn as_any(&self) -> &dyn Any;
6565
 }
6666
 
67
-/// A FEEL closure: formal parameter names, the body AST, and the scope captured at
68
-/// definition (lexical closure, spec §10.3.2.9).
67
+/// A FEEL closure: formal parameters (name + optional type annotation), the body
68
+/// AST, and the scope captured at definition (lexical closure, spec §10.3.2.9).
69
+/// Each element is `(name, type)` where `type` is `None` for an untyped parameter
70
+/// and `Some(t)` when the parameter carries a FEEL type annotation (`arg: number`).
71
+/// The type is used at invocation for implicit coercion (§10.3.2.9.4, ADR-35 follow-up).
6972
 #[derive(Debug, Clone, PartialEq)]
7073
 pub struct Closure {
71
-    pub params: Vec<String>,
74
+    pub params: Vec<(String, Option<crate::ast::FeelType>)>,
7275
     pub body: Arc<crate::ast::Expr>,
7376
     pub captured: crate::Context,
7477
 }

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

@@ -15,6 +15,7 @@
1515
 mod types;
1616
 mod value;
1717
 
18
+pub use ast::FeelType;
1819
 pub use error::FeelError;
1920
 pub use foreign::{Foreign, ForeignObject};
2021
 pub use function::{Args, ForeignFunction, Func};
@@ -266,6 +267,27 @@
266267
 /// ```
267268
 pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> {
268269
     compile(expr)?.evaluate(context)
270
+}
271
+
272
+/// Parse a structural FEEL type expression (`number`, `list<string>`,
273
+/// `context<a: number, b: string>`, `function<number> -> boolean`, …) into a
274
+/// [`FeelType`].  Returns `None` if the input is syntactically invalid or
275
+/// contains an unmappable name (one that maps to [`FeelType::Unknown`]).
276
+pub fn parse_type(s: &str) -> Option<FeelType> {
277
+    feel::TypeParser::new()
278
+        .parse(lexer::lex(s))
279
+        .ok()
280
+        .filter(|t| t.is_mappable())
281
+}
282
+
283
+/// Apply the §10.3.2.9.4 implicit conversion from `v` toward target type `t`.
284
+///
285
+/// Returns `Value::Null` when the conversion is mandatory but cannot be
286
+/// performed (type mismatch, null input, or unknown target type).  The five
287
+/// rules — null/error pass-through, from-singleton-list, to-singleton-list,
288
+/// and conforms-to — are documented on [`types::coerce`].
289
+pub fn coerce(v: Value, t: &FeelType) -> Value {
290
+    types::coerce(v, t)
269291
 }
270292
 
271293
 #[cfg(test)]

modified crates/feel-core/src/types.rs +50 −0

@@ -90,3 +90,53 @@
9090
         _ => value_conforms_to(v, t),
9191
     }
9292
 }
93
+
94
+/// Apply the §10.3.2.9.4 implicit conversion from `v` toward target type `t`,
95
+/// returning the converted value or [`Value::Null`] when a mandatory conversion
96
+/// cannot be performed.
97
+///
98
+/// Rule order (first applicable wins):
99
+///
100
+/// 1. **null/error** cannot be coerced — stays `null`
101
+///    (`decision_008`, `decision_bkm_004_b`).
102
+/// 2. **from singleton list** — when `v` is `[e]` and `t` is *not* a list
103
+///    type, unwrap and recurse with `e` (`decision_007`, `literal_005`).
104
+/// 3. **to singleton list** — when `t` is `list<s>` and `v` is *not* a list,
105
+///    wrap into `[v]` iff `v` conforms to `s`, else `null`
106
+///    (`decision_006_a`, `literal_004`).
107
+/// 4. **conforms-to** — pass `v` through unchanged if it satisfies `t`,
108
+///    else `null` (`decision_001`, `decision_004`, `fd_002`).
109
+///
110
+/// An [`Unknown`](FeelType::Unknown) target is outside the lattice; coercion is
111
+/// mandatory but impossible, so `null` is returned.
112
+pub(crate) fn coerce(v: Value, t: &FeelType) -> Value {
113
+    // Rule 1: null / error cannot be coerced.
114
+    match &v {
115
+        Value::Null | Value::Error => return Value::Null,
116
+        _ => {}
117
+    }
118
+    // An unmappable target type (Unknown anywhere in the tree) → null.
119
+    if !t.is_mappable() {
120
+        return Value::Null;
121
+    }
122
+    // Rule 2: from-singleton-list — target is NOT a list, value IS a singleton.
123
+    if !matches!(t, FeelType::List(_)) {
124
+        if let Value::List(ref items) = v {
125
+            if items.len() == 1 {
126
+                return coerce(items[0].clone(), t);
127
+            }
128
+        }
129
+    }
130
+    // Rule 3: to-singleton-list — target IS a list, value is NOT a list.
131
+    if let FeelType::List(elem) = t {
132
+        if !matches!(v, Value::List(_)) {
133
+            return if value_conforms_to(&v, elem) {
134
+                Value::List(vec![v])
135
+            } else {
136
+                Value::Null
137
+            };
138
+        }
139
+    }
140
+    // Rule 4: conforms-to — pass through or null.
141
+    if value_conforms_to(&v, t) { v } else { Value::Null }
142
+}