1use crate::{Ident, RuntimeValue, Shared};
11use rustc_hash::FxHashMap;
12
13pub mod adapter;
14pub use adapter::{IntoHostFunction, ValueAdapter};
15
16#[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#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct HostFunctionError(String);
34
35impl HostFunctionError {
36 pub fn new(message: impl Into<String>) -> Self {
38 Self(message.into())
39 }
40
41 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
67pub type HostFnResult = Result<RuntimeValue, HostFunctionError>;
69
70pub(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
81pub trait HostFunction: HostFunctionSyncBound + 'static {
91 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#[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 pub fn insert(&mut self, name: impl Into<Ident>, f: impl HostFunction) {
124 self.0.insert(name.into(), Shared::new(f));
125 }
126
127 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 pub fn remove(&mut self, name: impl Into<Ident>) -> bool {
135 self.0.remove(&name.into()).is_some()
136 }
137
138 pub fn contains(&self, name: &Ident) -> bool {
140 self.0.contains_key(name)
141 }
142
143 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}