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 / function.rs · 5.9 KB · at da382279c66c · raw

Outline: 8 definitions
1
//! First-class function values: native FEEL closures and host callables (ADR-23).
2
//!
3
//! A [`Value::Function`](crate::Value::Function) carries an [`Arc<Func>`](Func),
4
//! which is either:
5
//!
6
//! * a [`Closure`] — a FEEL `function(a, b) body` literal, captured with the scope
7
//!   it was defined in (FEEL functions are lexical closures, spec §10.3.2.9), or
8
//! * a [`ForeignFunction`] — a host callable (a JS function, a Python callable)
9
//!   wrapped per target, exactly like [`ForeignObject`](crate::ForeignObject) wraps
10
//!   a host *object* (ADR-21). `feel-core` never constructs one; only the wrapper
11
//!   crates do, so the cardinal rule (ADR-1) stays intact — the trait is std-only.
12
//!
13
//! Both are invoked through the same dispatch in the evaluator, and both bind their
14
//! arguments *unforced* so path laziness flows through the call (ADR-21).
15
16
use std::any::Any;
17
use std::fmt;
18
use std::sync::Arc;
19
20
use crate::value::Value;
21
22
/// Evaluated call arguments. Positional and named are kept apart and may appear
23
/// **mixed** in one call (`f(2, b: 3)`) — deliberately more tolerant than FEEL
24
/// spec rule 39 (which makes them exclusive). The split maps one-to-one onto
25
/// Python's `f(*positional, **named)`, so a host callable's positional-only and
26
/// keyword-only parameters are both reachable from FEEL. Shared by closure
27
/// invocation and the [`ForeignFunction`] trait.
28
#[derive(Debug)]
29
pub struct Args {
30
    pub positional: Vec<Value>,
31
    pub named: Vec<(String, Value)>,
32
}
33
34
/// Apply capability threaded into higher-order built-ins (ADR-37). Implemented by
35
/// `Evaluator` so `sort`, `list replace` (matching form), and any future higher-order
36
/// built-in can invoke a function-valued argument through the same path as a direct
37
/// call — including the recursion-depth guard and lexical-scope binding.
38
///
39
/// `pub(crate)` mirrors [`ForeignFunction`]: only the core crate wires up the
40
/// implementation; host crates never need to touch it.
41
pub(crate) trait Applier {
42
    /// Invoke `f` with `args` exactly as a direct FEEL call would. A `FeelError`
43
    /// (parse failure — not reachable here) or any other error-path collapses to
44
    /// `Value::Error` (error-null, ADR-14), because built-ins return `Value`, not
45
    /// `Result<Value, FeelError>`.
46
    fn apply(&self, f: &Func, args: Args) -> Value;
47
}
48
49
/// A host callable resolved lazily, implemented per target (feel-py's `PyForeignFn`,
50
/// feel-wasm's `JsForeignFn`). Mirrors [`ForeignObject`](crate::ForeignObject).
51
pub trait ForeignFunction: fmt::Debug {
52
    /// Invoke the host callable with the (still-unforced) FEEL arguments.
53
    ///
54
    /// The wrapper marshals `args` back to its host's calling convention: Python
55
    /// `f(*positional, **named)` (so host defaults, keyword-only and positional-only
56
    /// parameters all apply), JS `f(positional…, {named})`. `feel-core` performs **no**
57
    /// arity check — the host owns that. A host error (a thrown exception, a missing
58
    /// required argument) is mapped by the wrapper to [`Value::Error`] (error-null,
59
    /// ADR-14).
60
    fn call(&self, args: Args) -> Value;
61
62
    /// Recover the concrete host handle for identity pass-through on output (return
63
    /// the original callable untouched instead of re-wrapping it).
64
    fn as_any(&self) -> &dyn Any;
65
}
66
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).
72
#[derive(Debug, Clone, PartialEq)]
73
pub struct Closure {
74
    pub params: Vec<(String, Option<crate::ast::FeelType>)>,
75
    pub body: Arc<crate::ast::Expr>,
76
    pub captured: crate::Context,
77
}
78
79
/// The payload behind [`Value::Function`](crate::Value::Function). Boxed in a single
80
/// thin `Arc` at the `Value` level, so the variant is one word and `Value` does not
81
/// grow (the size regression test pins it).
82
#[derive(Debug, Clone)]
83
pub enum Func {
84
    /// A native FEEL closure.
85
    Closure(Closure),
86
    /// A host callable (constructed only by the wrapper crates).
87
    Foreign(Arc<dyn ForeignFunction>),
88
    /// A reference to a named built-in function (e.g. `abs`, `sqrt`). Created when a
89
    /// bare built-in name is used as a value — `bkm(abs, sqrt)` — so it can be stored
90
    /// in a context, passed as a parameter, and later invoked through `builtins::call`
91
    /// (ADR-36). The string is the spec name (identical to what [`builtins::call`]
92
    /// dispatches on, including multi-word joined names like `"string length"`).
93
    Builtin(String),
94
}
95
96
impl Func {
97
    /// Wrap this function in a [`Value::Function`](crate::Value::Function).
98
    ///
99
    /// A function value is intentionally **not** `Send`/`Sync` (a `Foreign`
100
    /// callable holds a host handle that is itself `!Send`, like a
101
    /// [`Foreign`](crate::Foreign) object — ADR-21/ADR-23), so the `Arc` here is a
102
    /// non-`Send`/`Sync` `Arc` by design; the lint is allowed at this single seam.
103
    #[allow(clippy::arc_with_non_send_sync)]
104
    pub fn into_value(self) -> Value {
105
        Value::Function(Arc::new(self))
106
    }
107
}
108
109
impl PartialEq for Func {
110
    /// Closures compare structurally; foreign callables compare by identity (same
111
    /// `Arc`); built-in references compare by name. This is the derive's notion of
112
    /// equality (for `Context` comparison/tests), **not** FEEL `=` — that goes through
113
    /// the evaluator, which treats two distinct functions as incomparable (error-null).
114
    fn eq(&self, other: &Self) -> bool {
115
        match (self, other) {
116
            (Func::Closure(a), Func::Closure(b)) => a == b,
117
            (Func::Foreign(a), Func::Foreign(b)) => Arc::ptr_eq(a, b),
118
            (Func::Builtin(a), Func::Builtin(b)) => a == b,
119
            _ => false,
120
        }
121
    }
122
}