Public repository: timo / feel

Reader

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

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>
Changeset23c48b66bd2325c5f85d12826fba87092aeddbcc
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents03b5e6481c37
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/builtins.rs +44 −0

@@ -40,6 +40,50 @@
4040
     "years and months duration",
4141
     "days and time duration",
4242
 ];
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
+}
4387
 
4488
 /// Dispatch a single- or multi-word built-in call. Arguments are already
4589
 /// evaluated (but unforced). The `env` carries the regex provider (consulted only

modified crates/feel-core/src/eval.rs +17 −2

@@ -96,7 +96,15 @@
9696
                     endpoint: self.eval(e, ctx)?.forced(),
9797
                 },
9898
             ))),
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
+            }),
100108
             Expr::ContextLit(entries) => self.eval_context_lit(entries, ctx),
101109
             Expr::Path(target, name) => Ok(match self.eval(target, ctx)? {
102110
                 // Selection on a list of contexts maps over the list and returns a
@@ -274,13 +282,20 @@
274282
         Ok(Args { positional, named })
275283
     }
276284
 
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.
278287
     fn invoke(&self, f: &Func, args: Args) -> EvalResult {
279288
         match f {
280289
             // A host callable owns its own arity/defaults (ADR-23): pass the args
281290
             // straight through, no checking here.
282291
             Func::Foreign(host_fn) => Ok(host_fn.call(args)),
283292
             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)),
284299
         }
285300
     }
286301
 

modified crates/feel-core/src/function.rs +10 −4

@@ -67,6 +67,12 @@
6767
     Closure(Closure),
6868
     /// A host callable (constructed only by the wrapper crates).
6969
     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),
7076
 }
7177
 
7278
 impl Func {
@@ -84,14 +90,14 @@
8490
 
8591
 impl PartialEq for Func {
8692
     /// 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).
9196
     fn eq(&self, other: &Self) -> bool {
9297
         match (self, other) {
9398
             (Func::Closure(a), Func::Closure(b)) => a == b,
9499
             (Func::Foreign(a), Func::Foreign(b)) => Arc::ptr_eq(a, b),
100
+            (Func::Builtin(a), Func::Builtin(b)) => a == b,
95101
             _ => false,
96102
         }
97103
     }

modified crates/feel-core/src/lib.rs +32 −4

@@ -1405,14 +1405,17 @@
14051405
     #[test]
14061406
     fn keyword_phrase_builtin_parses_in_call_position() {
14071407
         // 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).
14111413
         assert_eq!(
14121414
             ev(r#"string(date and time("2018-12-08"))"#),
14131415
             Value::String("2018-12-08T00:00:00".into())
14141416
         );
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(_)));
14161419
     }
14171420
 
14181421
     #[test]
@@ -2388,6 +2391,31 @@
23882391
         );
23892392
     }
23902393
 
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
+
23912419
     // --- host callables (ForeignFunction) ------------------------------------ //
23922420
 
23932421
     /// 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 @@
6767
         },
6868
         FeelType::Function(params, _ret) => match v {
6969
             // 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).
7273
             Value::Function(f) => match f.as_ref() {
7374
                 Func::Closure(c) => c.params.len() == params.len(),
74
-                Func::Foreign(_) => false,
75
+                Func::Foreign(_) | Func::Builtin(_) => false,
7576
             },
7677
             _ => false,
7778
         },