Log
23c48b66bd23
feat(core): first-class built-in function values (ADR-36)
public
feat(core): first-class built-in function values (ADR-36)
A bare built-in name used as a value expression (e.g. `bkm(abs, sqrt)`)
now evaluates to `Value::Function(Func::Builtin(name))` instead of null.
- `function.rs`: add `Func::Builtin(String)` variant; extend `PartialEq`
(builtins equal by name).
- `builtins.rs`: add `is_builtin(name)` predicate — a pure membership
check over the full built-in name set (including multi-word joined names
like `"string length"`).
- `eval.rs` `Expr::Var`: if the name is not in the context but is a
known builtin, return `Func::Builtin(name)` as the value. Context
bindings still shadow built-ins (checked first).
- `eval.rs` `invoke`: add `Func::Builtin(n)` arm dispatching to
`builtins::call` — wrong-arity/type calls return error-null.
- `types.rs`: `Func::Builtin` conforms to `Any` only (same as `Foreign`,
unknown arity in the type lattice).
Update `keyword_phrase_builtin_parses_in_call_position` test: the
multi-word name `"date and time"` out of call position now correctly
returns a function value (not null).
Add unit tests: bare builtin → Function value, context shadows builtin,
builtin passed as argument and invoked, wrong-arity → null.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
modified
crates/feel-core/src/builtins.rs
+44 −0
@@ -40,6 +40,50 @@
40 40 " years and months duration " , 41 41 " days and time duration " , 42 42 ]; 43 + 44 +/// Return `true` if `name` is a recognised built-in (i.e. `call` returns `Some` for it). 45 +/// 46 +/// Used by the evaluator to promote a bare built-in name used as a value expression 47 +/// to a [`Func::Builtin`](crate::function::Func::Builtin) — e.g. `bkm(abs, sqrt)` 48 +/// where `abs`/`sqrt` are first-class function values (ADR-36). The names match 49 +/// the spec's joined multi-word form (e.g. `"string length"`, `"date and time"`) as 50 +/// produced by the lexer. 51 +pub (crate ) fn is_builtin (name: & str ) -> bool { 52 + matches! ( 53 + name, 54 + // conversion 55 + " string " | " number " | 56 + // string functions 57 + " substring " | " contains " | " replace " | " split " | " matches " | 58 + " string length " | " upper case " | " lower case " | 59 + " substring before " | " substring after " | 60 + " starts with " | " ends with " | " string join " | 61 + // list functions 62 + " count " | " min " | " max " | " sum " | " mean " | " product " | 63 + " median " | " stddev " | " mode " | " all " | " any " | 64 + " append " | " concatenate " | " union " | " remove " | " reverse " | 65 + " flatten " | " sublist " | " list contains " | " index of " | 66 + " distinct values " | " insert before " | " list replace " | 67 + // context functions 68 + " get value " | " get entries " | " context " | " context put " | " context merge " | 69 + // numeric functions 70 + " decimal " | " floor " | " ceiling " | 71 + " round up " | " round down " | " round half up " | " round half down " | 72 + " abs " | " modulo " | " sqrt " | " exp " | " log " | " even " | " odd " | 73 + // temporal clock 74 + " now " | " today " | 75 + // temporal constructors / component functions 76 + " date " | " time " | " date and time " | " duration " | " years and months duration " | 77 + " day of week " | " month of year " | " day of year " | " week of year " | 78 + // boolean / range 79 + " is " | " range " | 80 + // Allen's interval relations 81 + " before " | " after " | " meets " | " met by " | 82 + " overlaps " | " overlaps before " | " overlaps after " | 83 + " finishes " | " finished by " | " includes " | " during " | 84 + " starts " | " started by " | " coincides " 85 + ) 86 +} 43 87 44 88 /// Dispatch a single- or multi-word built-in call. Arguments are already 45 89 /// evaluated (but unforced). The `env` carries the regex provider (consulted only
modified
crates/feel-core/src/eval.rs
+17 −2
@@ -96,7 +96,15 @@
96 96 endpoint: self .eval(e, ctx)? .forced(), 97 97 }, 98 98 ))), 99 - Expr::Var(name) = > Ok (ctx.get(name).cloned().unwrap_or(Value::Null)), 99 + // Variable reference: (1) a context binding, (2) a known built-in name 100 + // → a first-class function value (ADR-36), (3) an unbound name → null. 101 + Expr::Var(name) = > Ok (if let Some (v) = ctx.get(name) { 102 + v.clone() 103 + } else if crate ::builtins::is_builtin(name) { 104 + Func::Builtin(name.clone()).into_value() 105 + } else { 106 + Value::Null 107 + }), 100 108 Expr::ContextLit(entries) = > self .eval_context_lit(entries, ctx), 101 109 Expr::Path(target, name) = > Ok (match self .eval(target, ctx)? { 102 110 // Selection on a list of contexts maps over the list and returns a
@@ -274,13 +282,20 @@
274 282 Ok (Args { positional, named }) 275 283 } 276 284 277 - /// Invoke a function value (native closure or host callable) with evaluated args. 285 + /// Invoke a function value (native closure, host callable, or built-in ref) with 286 + /// evaluated args. 278 287 fn invoke (& self , f: & Func , args: Args ) -> EvalResult { 279 288 match f { 280 289 // A host callable owns its own arity/defaults (ADR-23): pass the args 281 290 // straight through, no checking here. 282 291 Func::Foreign(host_fn) = > Ok (host_fn.call(args)), 283 292 Func::Closure(closure) = > self .invoke_closure(closure, args), 293 + // A first-class built-in reference: dispatch through the normal built-in 294 + // table. `call` returns `None` only for names not in the table — which 295 + // cannot happen here (the name was validated by `is_builtin` when the 296 + // value was created) — so `unwrap_or(Error)` is a safety net (ADR-36). 297 + Func::Builtin(name) = > Ok (crate ::builtins::call(name, args, self .env) 298 + .unwrap_or(Value::Error)), 284 299 } 285 300 } 286 301
modified
crates/feel-core/src/function.rs
+10 −4
@@ -67,6 +67,12 @@
67 67 Closure(Closure), 68 68 /// A host callable (constructed only by the wrapper crates). 69 69 Foreign(Arc< dyn ForeignFunction> ), 70 + /// A reference to a named built-in function (e.g. `abs`, `sqrt`). Created when a 71 + /// bare built-in name is used as a value — `bkm(abs, sqrt)` — so it can be stored 72 + /// in a context, passed as a parameter, and later invoked through `builtins::call` 73 + /// (ADR-36). The string is the spec name (identical to what [`builtins::call`] 74 + /// dispatches on, including multi-word joined names like `"string length"`). 75 + Builtin(String ), 70 76 } 71 77 72 78 impl Func {
@@ -84,14 +90,14 @@
84 90 85 91 impl PartialEq for Func { 86 92 /// Closures compare structurally; foreign callables compare by identity (same 87 - /// `Arc`), like the [`Foreign`](crate::Foreign) newtype. This is the derive's 88 - /// notion of equality (for `Context` comparison/tests), **not** FEEL `=` — that 89 - /// goes through the evaluator, which treats two distinct functions as 90 - /// incomparable (error-null). 93 + /// `Arc`); built-in references compare by name. This is the derive's notion of 94 + /// equality (for `Context` comparison/tests), **not** FEEL `=` — that goes through 95 + /// the evaluator, which treats two distinct functions as incomparable (error-null). 91 96 fn eq (& self , other: & Self ) -> bool { 92 97 match (self , other) { 93 98 (Func::Closure(a), Func::Closure(b)) = > a = = b, 94 99 (Func::Foreign(a), Func::Foreign(b)) = > Arc::ptr_eq(a, b), 100 + (Func::Builtin(a), Func::Builtin(b)) = > a = = b, 95 101 _ = > false , 96 102 } 97 103 }
modified
crates/feel-core/src/lib.rs
+32 −4
@@ -1405,14 +1405,17 @@
1405 1405 #[ test ] 1406 1406 fn keyword_phrase_builtin_parses_in_call_position () { 1407 1407 // A keyword-containing builtin name (`date and time`) is recognised as one 1408 - // call head in call position and now evaluates (ADR-18), NOT as 1409 - // `date and (time(...))` (ADR-17). Out of call position it stays the 1410 - // boolean `and` (back-compat), so `date`/`time` unbound -> a value-null. 1408 + // call head in call position and evaluates (ADR-18), NOT as 1409 + // `date and (time(...))` (ADR-17). The lexer joins it as a single Name token 1410 + // in every position, so `date and time` out of call position is the Name 1411 + // `"date and time"` — which now evaluates to a first-class function value 1412 + // (ADR-36) rather than null (which was the unbound-variable result before). 1411 1413 assert_eq! ( 1412 1414 ev(r#"string(date and time("2018-12-08"))"# ), 1413 1415 Value::String (" 2018-12-08T00:00:00 " .into()) 1414 1416 ); 1415 - assert_eq! (ev(" date and time " ), Value::Null); 1417 + // Out of call position: resolves to the built-in function value (ADR-36). 1418 + assert! (matches! (ev(" date and time " ), Value::Function(_))); 1416 1419 } 1417 1420 1418 1421 #[ test ]
@@ -2388,6 +2391,31 @@
2388 2391 ); 2389 2392 } 2390 2393 2394 + // --- first-class built-in function values (ADR-36) ----------------------- // 2395 + 2396 + #[ test ] 2397 + fn builtin_as_first_class_value () { 2398 + // A bare built-in name evaluates to a Function value when used as a value. 2399 + assert! (matches! (ev(" abs " ), Value::Function(_))); 2400 + assert! (matches! (ev(" sqrt " ), Value::Function(_))); 2401 + // A context binding shadows the built-in (binding takes precedence). 2402 + assert_eq! (ev(" {abs: 42, r: abs}.r " ), Value::Number(42.0 )); 2403 + } 2404 + 2405 + #[ test ] 2406 + fn builtin_passed_as_argument_and_invoked () { 2407 + // A built-in can be passed as a lambda argument and invoked via the param. 2408 + assert_eq! ( 2409 + ev(" {bkm: function (fn1, fn2) fn1(-5) * fn2(25), r: bkm(abs, sqrt)}.r " ), 2410 + Value::Number(25.0 ) 2411 + ); 2412 + // A built-in with wrong arity -> error-null -> null (lenient). 2413 + assert_eq! ( 2414 + ev(" {bkm: function (fn1) fn1(10, 2), r: bkm(sqrt)}.r " ), 2415 + Value::Null 2416 + ); 2417 + } 2418 + 2391 2419 // --- host callables (ForeignFunction) ------------------------------------ // 2392 2420 2393 2421 /// A host function that sums all of its numeric arguments (positional + named),
modified
crates/feel-core/src/types.rs
+4 −3
@@ -67,11 +67,12 @@
67 67 }, 68 68 FeelType::Function(params, _ret) = > match v { 69 69 // Untyped FEEL closures map to `(Any, …, Any) -> Any`, so only the arity 70 - // is checked (covers `function<> -> Any`). A host callable has unknown 71 - // arity, so it conforms to nothing more specific than `Any`. 70 + // is checked (covers `function<> -> Any`). A host callable or built-in 71 + // reference has unknown/variable arity, so it conforms to nothing more 72 + // specific than `Any` (same treatment as `Foreign`, ADR-36). 72 73 Value::Function(f) = > match f.as_ref() { 73 74 Func::Closure(c) = > c.params.len() = = params.len(), 74 - Func::Foreign(_) = > false , 75 + Func::Foreign(_) | Func::Builtin(_) = > false , 75 76 }, 76 77 _ = > false , 77 78 },