Skip to main content

fel_core/extensions/
registry.rs

1//! Extension function registry (`ExtensionRegistry`) and registration errors.
2#![allow(clippy::missing_docs_in_private_items)]
3
4use std::collections::HashMap;
5
6use crate::types::Value as TypeValue;
7
8use super::catalog::{BUILTIN_FUNCTIONS, RESERVED_WORDS};
9use super::types::ExtensionFunc;
10
11/// Host-supplied FEL extension functions (Core §3.12), consulted for non-builtin names.
12///
13/// The port lets a host back extensions with what its runtime has: Rust closures
14/// ([`ExtensionRegistry`]), JavaScript functions across WASM, or Python callables.
15/// Implementations need not be `Send` or `Sync`. The evaluator owns the call contract
16/// through [`call_extension`] (arity bounds, null propagation, a failed call becoming
17/// a diagnostic), so an implementation only looks up and invokes.
18pub trait ExtensionFunctions {
19    /// Arity bounds `(min_args, max_args)` when `name` is registered; `None` otherwise.
20    fn arity(&self, name: &str) -> Option<(usize, Option<usize>)>;
21
22    /// Invokes extension `name` with arity-checked, non-null `args`.
23    ///
24    /// # Errors
25    ///
26    /// A message when the host implementation failed (threw, raised, or returned an
27    /// unrepresentable value). Core §3.12 forbids propagating it: the evaluator yields
28    /// `null` and records an error diagnostic.
29    fn invoke(&self, name: &str, args: &[TypeValue]) -> Result<TypeValue, String>;
30}
31
32/// Checks that `name` may be registered: neither a reserved word nor a built-in (Core §3.12).
33///
34/// # Errors
35///
36/// [`ExtensionError::NameConflict`] when `name` collides.
37pub fn check_extension_name(name: &str) -> Result<(), ExtensionError> {
38    if RESERVED_WORDS.contains(&name) || BUILTIN_FUNCTIONS.iter().any(|entry| entry.name == name) {
39        return Err(ExtensionError::NameConflict(name.to_string()));
40    }
41    Ok(())
42}
43
44/// Calls extension `name` under Core §3.12: arity bounds, null propagation, totality.
45///
46/// A `null` argument short-circuits to `null` without invoking the host; a host
47/// failure becomes [`ExtensionCallOutcome::Failed`], never a panic.
48pub fn call_extension(
49    functions: &dyn ExtensionFunctions,
50    name: &str,
51    args: &[TypeValue],
52) -> ExtensionCallOutcome {
53    let Some((min_args, max_args)) = functions.arity(name) else {
54        return ExtensionCallOutcome::NotFound;
55    };
56
57    let got = args.len();
58    if got < min_args || max_args.is_some_and(|max| got > max) {
59        return ExtensionCallOutcome::ArityMismatch {
60            name: name.to_string(),
61            min_args,
62            max_args,
63            got,
64        };
65    }
66
67    if args.iter().any(TypeValue::is_null) {
68        return ExtensionCallOutcome::Ok(TypeValue::Null);
69    }
70
71    match functions.invoke(name, args) {
72        Ok(value) => ExtensionCallOutcome::Ok(value),
73        Err(message) => ExtensionCallOutcome::Failed {
74            name: name.to_string(),
75            message,
76        },
77    }
78}
79
80/// Registry of extension functions backed by Rust closures.
81pub struct ExtensionRegistry {
82    extensions: HashMap<String, ExtensionFunc>,
83}
84
85/// Error type for extension registration failures.
86#[derive(Debug, Clone)]
87pub enum ExtensionError {
88    /// Registration rejected: name matches a reserved word or built-in function.
89    NameConflict(String),
90}
91
92/// Result of [`ExtensionRegistry::call`].
93#[derive(Debug, Clone, PartialEq)]
94pub enum ExtensionCallOutcome {
95    /// No extension registered under this name.
96    NotFound,
97    /// Extension invoked (or null-propagated without invoking).
98    Ok(TypeValue),
99    /// Argument count outside registered bounds; host should record a diagnostic and yield null.
100    ArityMismatch {
101        /// Extension name.
102        name: String,
103        /// Registered minimum arity.
104        min_args: usize,
105        /// Registered maximum arity, if bounded.
106        max_args: Option<usize>,
107        /// Supplied argument count.
108        got: usize,
109    },
110    /// The host implementation failed; host should record a diagnostic and yield null.
111    Failed {
112        /// Extension name.
113        name: String,
114        /// Host failure message.
115        message: String,
116    },
117}
118
119impl std::fmt::Display for ExtensionError {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        match self {
122            ExtensionError::NameConflict(name) => {
123                write!(
124                    f,
125                    "cannot register extension '{name}': conflicts with reserved word or built-in function"
126                )
127            }
128        }
129    }
130}
131
132impl std::error::Error for ExtensionError {}
133
134impl ExtensionRegistry {
135    /// Empty registry (no custom extensions).
136    pub fn new() -> Self {
137        Self {
138            extensions: HashMap::new(),
139        }
140    }
141
142    /// Register an extension function.
143    ///
144    /// Returns an error if the name conflicts with a reserved word or built-in.
145    pub fn register(
146        &mut self,
147        name: impl Into<String>,
148        min_args: usize,
149        max_args: Option<usize>,
150        func: impl Fn(&[TypeValue]) -> TypeValue + Send + Sync + 'static,
151    ) -> Result<(), ExtensionError> {
152        let name = name.into();
153        check_extension_name(&name)?;
154
155        self.extensions.insert(
156            name.clone(),
157            ExtensionFunc {
158                name: name.clone(),
159                min_args,
160                max_args,
161                func: Box::new(func),
162            },
163        );
164        Ok(())
165    }
166
167    /// Look up an extension function by name.
168    pub fn get(&self, name: &str) -> Option<&ExtensionFunc> {
169        self.extensions.get(name)
170    }
171
172    /// True if `name` is registered.
173    pub fn contains(&self, name: &str) -> bool {
174        self.extensions.contains_key(name)
175    }
176
177    /// Call an extension function with null propagation.
178    ///
179    /// Returns [`ExtensionCallOutcome::NotFound`] if the extension is not registered.
180    /// Returns [`ExtensionCallOutcome::ArityMismatch`] when `args.len()` is outside
181    /// the bounds recorded at registration (caller should emit the message and yield null).
182    pub fn call(&self, name: &str, args: &[TypeValue]) -> ExtensionCallOutcome {
183        call_extension(self, name, args)
184    }
185}
186
187impl ExtensionFunctions for ExtensionRegistry {
188    fn arity(&self, name: &str) -> Option<(usize, Option<usize>)> {
189        self.extensions
190            .get(name)
191            .map(|ext| (ext.min_args, ext.max_args))
192    }
193
194    fn invoke(&self, name: &str, args: &[TypeValue]) -> Result<TypeValue, String> {
195        self.extensions
196            .get(name)
197            .map(|ext| (ext.func)(args))
198            .ok_or_else(|| format!("extension '{name}' is not registered"))
199    }
200}
201
202impl Default for ExtensionRegistry {
203    fn default() -> Self {
204        Self::new()
205    }
206}