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>
| Changeset | c3e08c2ac5b323da3f25381b498f6b1c63caa01c |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 828141660cd7 |
| Children | |
| Pushlog | by timo via ssh |
modified crates/feel-core/src/ast.rs +4 −2
| @@ -50,9 +50,11 @@ | ||
| 50 | 50 | Invoke(Box<Expr>, CallArgs), |
| 51 | 51 | /// A FEEL function literal `function(a, b) body` — an anonymous closure that |
| 52 | 52 | /// 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). | |
| 54 | 56 | FnDef { |
| 55 | - params: Vec<String>, | |
| 57 | + params: Vec<(String, Option<FeelType>)>, | |
| 56 | 58 | body: Box<Expr>, |
| 57 | 59 | }, |
| 58 | 60 | |
modified crates/feel-core/src/eval.rs +28 −6
| @@ -348,20 +348,25 @@ | ||
| 348 | 348 | /// Bind call arguments to a closure's formal parameters, returning the body scope |
| 349 | 349 | /// (the captured scope extended with the bindings). `Err(())` signals |
| 350 | 350 | /// 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, ()> { | |
| 354 | 359 | if args.positional.len() > params.len() { |
| 355 | 360 | return Err(()); // too many positional arguments |
| 356 | 361 | } |
| 357 | 362 | let mut scope = captured.clone(); |
| 358 | 363 | let mut bound = vec![false; params.len()]; |
| 359 | 364 | for (i, value) in args.positional.into_iter().enumerate() { |
| 360 | - scope.insert(params[i].clone(), value); | |
| 365 | + scope.insert(params[i].0.clone(), value); | |
| 361 | 366 | bound[i] = true; |
| 362 | 367 | } |
| 363 | 368 | for (name, value) in args.named { |
| 364 | - match params.iter().position(|p| *p == name) { | |
| 369 | + match params.iter().position(|(p, _)| p == &name) { | |
| 365 | 370 | Some(i) if !bound[i] => { |
| 366 | 371 | scope.insert(name, value); |
| 367 | 372 | bound[i] = true; |
| @@ -370,9 +375,26 @@ | ||
| 370 | 375 | None => return Err(()), // unknown parameter name |
| 371 | 376 | } |
| 372 | 377 | } |
| 373 | - for (i, param) in params.iter().enumerate() { | |
| 378 | + for (i, (param, _)) in params.iter().enumerate() { | |
| 374 | 379 | if !bound[i] { |
| 375 | 380 | 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 | + } | |
| 376 | 398 | } |
| 377 | 399 | } |
| 378 | 400 | Ok(scope) |
modified crates/feel-core/src/feel.lalrpop +15 −12
| @@ -80,6 +80,10 @@ | ||
| 80 | 80 | |
| 81 | 81 | pub Expr: Expr = TextualExpr; |
| 82 | 82 | |
| 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 | + | |
| 83 | 87 | // Loosest-binding forms. `for`/`if`/`some`/`every` extend to the end of their |
| 84 | 88 | // sub-expressions (which are themselves full TextualExprs), enabling nesting |
| 85 | 89 | // like `for i in [1,2,3] return if i > 0 then i else -i`. |
| @@ -97,12 +101,11 @@ | ||
| 97 | 101 | Expr::Quantified { kind: Quantifier::Some, bindings: bs, predicate: Box::new(p) }, |
| 98 | 102 | "every" <bs:Comma<IterCtx>> "satisfies" <p:TextualExpr> => |
| 99 | 103 | 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). | |
| 106 | 109 | "function" "(" ")" <b:TextualExpr> => |
| 107 | 110 | Expr::FnDef { params: vec![], body: Box::new(b) }, |
| 108 | 111 | "function" "(" <ps:Comma<FormalParam>> ")" <b:TextualExpr> => |
| @@ -247,15 +250,15 @@ | ||
| 247 | 250 | <e:Expr> => ArgEntry::Pos(e), |
| 248 | 251 | }; |
| 249 | 252 | |
| 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). | |
| 251 | 254 | // 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. | |
| 254 | 257 | // LR(1)-clean: after `Name`, a lookahead `:` shifts into the typed branch while |
| 255 | 258 | // `,`/`)` 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)), | |
| 259 | 262 | }; |
| 260 | 263 | |
| 261 | 264 | Primary: Expr = { |
modified crates/feel-core/src/function.rs +6 −3
| @@ -64,11 +64,14 @@ | ||
| 64 | 64 | fn as_any(&self) -> &dyn Any; |
| 65 | 65 | } |
| 66 | 66 | |
| 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). | |
| 69 | 72 | #[derive(Debug, Clone, PartialEq)] |
| 70 | 73 | pub struct Closure { |
| 71 | - pub params: Vec<String>, | |
| 74 | + pub params: Vec<(String, Option<crate::ast::FeelType>)>, | |
| 72 | 75 | pub body: Arc<crate::ast::Expr>, |
| 73 | 76 | pub captured: crate::Context, |
| 74 | 77 | } |
modified crates/feel-core/src/lib.rs +22 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | mod types; |
| 16 | 16 | mod value; |
| 17 | 17 | |
| 18 | +pub use ast::FeelType; | |
| 18 | 19 | pub use error::FeelError; |
| 19 | 20 | pub use foreign::{Foreign, ForeignObject}; |
| 20 | 21 | pub use function::{Args, ForeignFunction, Func}; |
| @@ -266,6 +267,27 @@ | ||
| 266 | 267 | /// ``` |
| 267 | 268 | pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> { |
| 268 | 269 | 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) | |
| 269 | 291 | } |
| 270 | 292 | |
| 271 | 293 | #[cfg(test)] |
modified crates/feel-core/src/types.rs +50 −0
| @@ -90,3 +90,53 @@ | ||
| 90 | 90 | _ => value_conforms_to(v, t), |
| 91 | 91 | } |
| 92 | 92 | } |
| 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 | +} | |