Skip to main content

mirascript_vm/value/
function.rs

1use std::fmt;
2use std::rc::Rc;
3
4use crate::{Result, RunOptions};
5
6use super::MiraAny;
7
8pub(crate) trait NativeRuntime {
9    fn call_value(&mut self, function: &MiraAny, args: &[MiraAny]) -> Result<MiraAny>;
10    fn get_value(&self, value: &MiraAny, key: &MiraAny) -> Result<MiraAny>;
11    fn options(&self) -> &RunOptions;
12    fn checkpoint(&mut self) -> Result<()>;
13}
14
15/// Capabilities available to a native callback during one VM execution.
16///
17/// The context cannot outlive the callback invocation.
18pub struct MiraCallContext<'a> {
19    pub(crate) runtime: &'a mut dyn NativeRuntime,
20}
21
22impl MiraCallContext<'_> {
23    /// Call a native, script, or callable extern value.
24    pub fn call(&mut self, function: &MiraAny, args: &[MiraAny]) -> Result<MiraAny> {
25        self.runtime.call_value(function, args)
26    }
27
28    /// Read a field or index using the same rules as a MiraScript expression.
29    pub fn get(&mut self, value: &MiraAny, key: impl Into<MiraAny>) -> Result<MiraAny> {
30        self.runtime.get_value(value, &key.into())
31    }
32
33    /// Return the options for the current execution.
34    pub fn options(&self) -> &RunOptions {
35        self.runtime.options()
36    }
37
38    /// Cooperatively check the current execution's timeout.
39    ///
40    /// Long-running native callbacks should call this method periodically.
41    pub fn checkpoint(&mut self) -> Result<()> {
42        self.runtime.checkpoint()
43    }
44}
45
46type NativeCallback = dyn for<'a> Fn(&mut MiraCallContext<'a>, &[MiraAny]) -> Result<MiraAny>;
47
48#[derive(Clone)]
49/// A named, single-threaded native function callable from MiraScript.
50pub struct MiraNativeFn {
51    callback: Rc<NativeCallback>,
52    name: Rc<str>,
53}
54
55impl MiraNativeFn {
56    /// Create a native function with the given diagnostic name.
57    ///
58    /// # Examples
59    ///
60    /// ```
61    /// use mirascript_vm::{MiraAny, MiraContext, MiraNativeFn, eval};
62    ///
63    /// let mut context = MiraContext::empty();
64    /// context.insert_fn("answer", MiraNativeFn::new("host.answer", |_, _| {
65    ///     Ok(MiraAny::Number(42.0))
66    /// }));
67    /// assert_eq!(eval("answer()", &context)?, MiraAny::Number(42.0));
68    /// # Ok::<(), mirascript_vm::MiraError>(())
69    /// ```
70    pub fn new(
71        name: impl Into<String>,
72        callback: impl for<'a> Fn(&mut MiraCallContext<'a>, &[MiraAny]) -> Result<MiraAny> + 'static,
73    ) -> Self {
74        Self {
75            callback: Rc::new(callback),
76            name: Rc::from(name.into()),
77        }
78    }
79
80    /// Create a native function named `<native>`.
81    pub fn anonymous(
82        callback: impl for<'a> Fn(&mut MiraCallContext<'a>, &[MiraAny]) -> Result<MiraAny> + 'static,
83    ) -> Self {
84        Self::new("<native>", callback)
85    }
86
87    /// Return the function name shown in diagnostics and stack traces.
88    pub fn name(&self) -> &str {
89        &self.name
90    }
91
92    pub(crate) fn shared_name(&self) -> Rc<str> {
93        Rc::clone(&self.name)
94    }
95
96    pub(crate) fn call(
97        &self,
98        context: &mut MiraCallContext<'_>,
99        args: &[MiraAny],
100    ) -> Result<MiraAny> {
101        (self.callback)(context, args)
102    }
103
104    pub(super) fn same(&self, other: &Self) -> bool {
105        Rc::ptr_eq(&self.callback, &other.callback)
106    }
107}
108
109impl<F> From<F> for MiraNativeFn
110where
111    F: for<'a> Fn(&mut MiraCallContext<'a>, &[MiraAny]) -> Result<MiraAny> + 'static,
112{
113    fn from(value: F) -> Self {
114        Self::anonymous(value)
115    }
116}
117
118impl fmt::Debug for MiraNativeFn {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.debug_tuple("MiraNativeFn").field(&self.name).finish()
121    }
122}
123
124#[derive(Debug, Clone)]
125/// A native or execution-scoped script function.
126pub enum MiraFunction {
127    /// A host callback that may safely outlive an execution.
128    Native(MiraNativeFn),
129    #[doc(hidden)]
130    Script {
131        execution: u64,
132        function: usize,
133        frame: usize,
134        name: Option<Rc<str>>,
135    },
136}
137
138impl MiraFunction {
139    /// Return the function's diagnostic name, when available.
140    pub fn name(&self) -> Option<&str> {
141        match self {
142            Self::Native(function) => Some(function.name()),
143            Self::Script { name, .. } => name.as_deref(),
144        }
145    }
146
147    pub(super) fn same(&self, other: &Self) -> bool {
148        match (self, other) {
149            (Self::Native(a), Self::Native(b)) => a.same(b),
150            (
151                Self::Script {
152                    execution: ae,
153                    function: af,
154                    frame: ac,
155                    ..
156                },
157                Self::Script {
158                    execution: be,
159                    function: bf,
160                    frame: bc,
161                    ..
162                },
163            ) => ae == be && af == bf && ac == bc,
164            _ => false,
165        }
166    }
167}