Skip to main content

mq_lang/runtime/
host.rs

1//! Host-registered native functions: the embedding API that lets a Rust host expose its own
2//! functions to mq code.
3//!
4//! A [`HostFunctions`] registry is owned per [`Engine`](crate::Engine)/[`Evaluator`](crate::eval::Evaluator)
5//! and consulted by the evaluator whenever a called identifier isn't a local binding, right
6//! before falling back to the built-in function table. This lets host functions be called from
7//! mq code without any special syntax, exactly like builtins, while still being shadowable by a
8//! `def` of the same name.
9
10use crate::{Ident, RuntimeValue, Shared};
11use rustc_hash::FxHashMap;
12
13pub mod adapter;
14pub use adapter::{IntoHostFunction, ValueAdapter};
15
16/// Marker trait bounding host function closures to what's safe to store behind [`Shared`].
17/// `Send + Sync` is only required when the `sync` feature (which backs [`Shared`] with `Arc`)
18/// is enabled; under the default `Rc`-backed build, closures may freely capture non-`Send` state.
19#[cfg(feature = "sync")]
20pub trait HostFunctionSyncBound: Send + Sync {}
21#[cfg(feature = "sync")]
22impl<T: Send + Sync> HostFunctionSyncBound for T {}
23
24#[cfg(not(feature = "sync"))]
25pub trait HostFunctionSyncBound {}
26#[cfg(not(feature = "sync"))]
27impl<T> HostFunctionSyncBound for T {}
28
29/// Error returned by a host-registered function, or produced while marshalling arguments and
30/// return values (see the `ValueAdapter` trait). Carries only a message, so it stays
31/// `PartialEq`-comparable and cheap to embed in `RuntimeError`.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct HostFunctionError(String);
34
35impl HostFunctionError {
36    /// Creates a new host function error with the given message.
37    pub fn new(message: impl Into<String>) -> Self {
38        Self(message.into())
39    }
40
41    /// Returns the error message.
42    pub fn message(&self) -> &str {
43        &self.0
44    }
45}
46
47impl std::fmt::Display for HostFunctionError {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(f, "{}", self.0)
50    }
51}
52
53impl std::error::Error for HostFunctionError {}
54
55impl From<&str> for HostFunctionError {
56    fn from(s: &str) -> Self {
57        Self::new(s)
58    }
59}
60
61impl From<String> for HostFunctionError {
62    fn from(s: String) -> Self {
63        Self::new(s)
64    }
65}
66
67/// Result type returned by a host function call.
68pub type HostFnResult = Result<RuntimeValue, HostFunctionError>;
69
70/// Extracts a human-readable message from a caught panic payload.
71pub(crate) fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
72    if let Some(s) = payload.downcast_ref::<&str>() {
73        (*s).to_string()
74    } else if let Some(s) = payload.downcast_ref::<String>() {
75        s.clone()
76    } else {
77        "unknown panic".to_string()
78    }
79}
80
81/// A native Rust function callable from mq code, registered via [`HostFunctions::insert`].
82///
83/// Receives the already-evaluated call arguments and returns a single [`RuntimeValue`]. Blanket-
84/// implemented for any matching closure, so hosts never need to name this trait directly.
85///
86/// Dispatch goes through [`Self::call`] rather than calling `dyn HostFunction` values directly:
87/// the standard library only provides `Fn`-trait impls for `Box<dyn Fn..>`, not for `Rc`/`Arc`
88/// (which back [`Shared`] depending on the `sync` feature), so an explicit method keeps
89/// invocation through `Shared<dyn HostFunction>` unambiguous.
90pub trait HostFunction: HostFunctionSyncBound + 'static {
91    /// Invokes the function with evaluated arguments.
92    fn call(&self, args: &[RuntimeValue]) -> HostFnResult;
93}
94
95impl<F> HostFunction for F
96where
97    F: Fn(&[RuntimeValue]) -> HostFnResult + HostFunctionSyncBound + 'static,
98{
99    fn call(&self, args: &[RuntimeValue]) -> HostFnResult {
100        (self)(args)
101    }
102}
103
104/// A registry of native Rust functions exposed to mq code under a given name.
105///
106/// Cloning is O(1): registered functions are stored behind [`Shared`], so a clone shares the
107/// same underlying entries (matching how [`Engine`](crate::Engine) itself is `Clone`).
108#[derive(Clone, Default)]
109pub struct HostFunctions(FxHashMap<Ident, Shared<dyn HostFunction>>);
110
111impl std::fmt::Debug for HostFunctions {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        f.debug_struct("HostFunctions")
114            .field("names", &self.0.keys().map(Ident::to_string).collect::<Vec<_>>())
115            .finish()
116    }
117}
118
119impl HostFunctions {
120    /// Registers a raw host function under `name`, callable from mq code as `name(...)`.
121    ///
122    /// If a function is already registered under `name`, it is replaced.
123    pub fn insert(&mut self, name: impl Into<Ident>, f: impl HostFunction) {
124        self.0.insert(name.into(), Shared::new(f));
125    }
126
127    /// Like [`Self::insert`], but takes an already-boxed function; used by
128    /// [`crate::Engine::register_fn`]'s typed-argument overload.
129    pub(crate) fn insert_shared(&mut self, name: impl Into<Ident>, f: Shared<dyn HostFunction>) {
130        self.0.insert(name.into(), f);
131    }
132
133    /// Removes the function registered under `name`, if any. Returns whether one was removed.
134    pub fn remove(&mut self, name: impl Into<Ident>) -> bool {
135        self.0.remove(&name.into()).is_some()
136    }
137
138    /// Whether a function is registered under `name`.
139    pub fn contains(&self, name: &Ident) -> bool {
140        self.0.contains_key(name)
141    }
142
143    /// Looks up the function registered under `name`, cloning the [`Shared`] handle.
144    pub(crate) fn get(&self, name: &Ident) -> Option<Shared<dyn HostFunction>> {
145        self.0.get(name).cloned()
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn test_insert_and_get() {
155        let mut fns = HostFunctions::default();
156        assert!(!fns.contains(&Ident::new("double")));
157
158        fns.insert("double", |args: &[RuntimeValue]| match args {
159            [RuntimeValue::Number(n)] => Ok(RuntimeValue::from(crate::number::Number::from(n.value() * 2.0))),
160            _ => Err(HostFunctionError::new("expected one number")),
161        });
162
163        assert!(fns.contains(&Ident::new("double")));
164        let f = fns.get(&Ident::new("double")).unwrap();
165        let result = f
166            .call(&[RuntimeValue::from(crate::number::Number::from(21.0))])
167            .unwrap();
168        assert_eq!(result, RuntimeValue::from(crate::number::Number::from(42.0)));
169    }
170
171    #[test]
172    fn test_insert_replaces_existing() {
173        let mut fns = HostFunctions::default();
174        fns.insert("f", |_: &[RuntimeValue]| {
175            Ok(RuntimeValue::from(crate::number::Number::from(1_i64)))
176        });
177        fns.insert("f", |_: &[RuntimeValue]| Ok(RuntimeValue::Boolean(true)));
178
179        let f = fns.get(&Ident::new("f")).unwrap();
180        assert_eq!(f.call(&[]).unwrap(), RuntimeValue::Boolean(true));
181    }
182
183    #[test]
184    fn test_remove() {
185        let mut fns = HostFunctions::default();
186        fns.insert("f", |_: &[RuntimeValue]| Ok(RuntimeValue::NONE));
187
188        assert!(fns.remove("f"));
189        assert!(!fns.contains(&Ident::new("f")));
190        assert!(!fns.remove("f"));
191    }
192
193    #[test]
194    fn test_get_missing_returns_none() {
195        let fns = HostFunctions::default();
196        assert!(fns.get(&Ident::new("missing")).is_none());
197    }
198
199    #[test]
200    fn test_host_function_error_display_and_message() {
201        let err = HostFunctionError::new("boom");
202        assert_eq!(err.message(), "boom");
203        assert_eq!(err.to_string(), "boom");
204
205        let err: HostFunctionError = "from str".into();
206        assert_eq!(err.message(), "from str");
207
208        let err: HostFunctionError = String::from("from string").into();
209        assert_eq!(err.message(), "from string");
210    }
211
212    #[test]
213    fn test_debug_lists_names() {
214        let mut fns = HostFunctions::default();
215        fns.insert("alpha", |_: &[RuntimeValue]| Ok(RuntimeValue::NONE));
216        let debug = format!("{:?}", fns);
217        assert!(debug.contains("alpha"));
218    }
219}