Skip to main content

mirascript_vm/interpreter/
call.rs

1use std::borrow::Cow;
2
3use crate::{MiraHandle, MiraManageable, bytecode::Program};
4
5use super::*;
6
7pub(crate) struct ScriptFunction {
8    pub(crate) execution: ExecutionId,
9    pub(crate) program: Rc<Program>,
10    pub(crate) function: usize,
11    pub(crate) frame: FrameId,
12    pub(crate) name: Cow<'static, str>,
13}
14
15impl MiraFunction for ScriptFunction {
16    fn call(&self, runtime: &mut Runtime, args: &[MiraValue]) -> Result<MiraManageable> {
17        if self.execution != runtime.execution {
18            return Err(MiraError::runtime(RuntimeErrorKind::ExecutionEnded));
19        }
20        let definition = &self.program.functions[self.function];
21        let frame = runtime.create_frame(definition.register_count, Some(self.frame));
22        if definition.variadic {
23            let fixed = definition.arg_count.saturating_sub(1);
24            for index in 0..fixed {
25                runtime.write_register(
26                    frame,
27                    RegisterId::new(index + 1),
28                    args.get(index).cloned().unwrap_or(MiraValue::NIL),
29                );
30            }
31            let rest = args
32                .iter()
33                .skip(fixed)
34                .cloned()
35                .map(operations::into_element)
36                .collect::<Vec<_>>();
37            if definition.arg_count > 0 {
38                let rest = runtime.insert(rest)?;
39                runtime.write_register(frame, RegisterId::new(definition.arg_count), rest);
40            }
41        } else {
42            for index in 0..definition.arg_count {
43                runtime.write_register(
44                    frame,
45                    RegisterId::new(index + 1),
46                    args.get(index).cloned().unwrap_or(MiraValue::NIL),
47                );
48            }
49        }
50        match runtime.execute_block(&definition.body, frame)? {
51            Flow::Return(value) => Ok(value.into()),
52            Flow::Continue => Ok(MiraValue::NIL.into()),
53            Flow::Break | Flow::LoopContinue => {
54                Err(MiraError::runtime(RuntimeErrorKind::InvalidControlFlow {
55                    context: "function",
56                }))
57            }
58        }
59    }
60
61    fn name(&self) -> &str {
62        self.name.as_ref()
63    }
64}
65
66impl Runtime {
67    pub(super) fn call_registers(
68        &mut self,
69        target: MiraValue,
70        registers: &[RegisterId],
71        spreads: &[usize],
72        frame: FrameId,
73    ) -> Result<MiraValue> {
74        if spreads.is_empty() {
75            let arguments = registers
76                .iter()
77                .cloned()
78                .map(|register| self.read_register(frame, register))
79                .collect::<Result<Vec<_>>>()?;
80            return self.call(target, &arguments);
81        }
82
83        let mut arguments = Vec::with_capacity(registers.len());
84        for (index, register) in registers.iter().enumerate() {
85            let value = self.read_register(frame, *register)?;
86            if spreads.contains(&index) {
87                arguments.extend(
88                    operations::array_spread(self, value)?
89                        .into_iter()
90                        .map(operations::into_element),
91                );
92            } else {
93                arguments.push(value);
94            }
95        }
96        self.call(target, &arguments)
97    }
98
99    pub(super) fn get_global_slot(&self, slot: usize) -> Result<MiraValue> {
100        let (name, std_slot) = &self.active_program().global_names[slot];
101
102        if let Some(value) = self.globals.get_hint(name, *std_slot) {
103            Ok(value)
104        } else {
105            self.undefined_global(name)
106        }
107    }
108
109    pub(super) fn get_global_name(&self, key: &str) -> Result<MiraValue> {
110        if let Some(value) = self.globals.get(key) {
111            Ok(value)
112        } else {
113            self.undefined_global(key)
114        }
115    }
116    #[cold]
117    #[inline(never)]
118    fn undefined_global(&self, name: &str) -> Result<MiraValue> {
119        Err(MiraError::runtime(RuntimeErrorKind::UndefinedGlobal {
120            name: name.to_owned(),
121        }))
122    }
123
124    pub(super) fn has_value(&mut self, value: MiraValue, key: MiraValue) -> Result<bool> {
125        operations::has(self, value, key, None)
126    }
127
128    pub(super) fn get_value(&mut self, value: MiraValue, key: MiraValue) -> Result<MiraValue> {
129        operations::get_value(self, value, key, None)
130    }
131
132    /// Call a function value owned by this Runtime.
133    pub fn call(&mut self, function: MiraValue, args: &[MiraValue]) -> Result<MiraValue> {
134        let MiraValueKind::Function(handle) = function.kind() else {
135            return self.err_not_callable(function);
136        };
137        self.call_function(handle, args)
138    }
139
140    pub(crate) fn call_function(
141        &mut self,
142        handle: MiraHandle<dyn MiraFunction>,
143        args: &[MiraValue],
144    ) -> Result<MiraValue> {
145        if self.call_stack.depth() >= self.options.max_call_depth as usize {
146            return self.err_call_depth();
147        }
148        self.checkpoint()?;
149        let callable = self.get_function_dyn(handle)?;
150        self.call_stack.push(handle);
151        let result = callable
152            .call(self, args)
153            .and_then(|value| self.insert(value));
154        self.call_stack.pop();
155        result
156    }
157
158    #[cold]
159    #[inline(never)]
160    fn err_call_depth(&self) -> Result<MiraValue> {
161        Err(MiraError::runtime(RuntimeErrorKind::MaxCallDepth {
162            max: self.options.max_call_depth,
163        }))
164    }
165    #[cold]
166    #[inline(never)]
167    fn err_not_callable(&self, value: MiraValue) -> Result<MiraValue> {
168        Err(MiraError::runtime(RuntimeErrorKind::NotCallable {
169            actual: value.value_type(),
170        }))
171    }
172
173    pub(crate) fn checkpoint(&mut self) -> Result<()> {
174        let remaining = self.checkpoint_remaining;
175        if remaining > 1 {
176            self.checkpoint_remaining = remaining - 1;
177            return Ok(());
178        }
179        self.checkpoint_remaining = self.options.checkpoint_interval.max(1);
180        if self.started.elapsed() >= self.options.timeout {
181            return Err(MiraError::runtime(RuntimeErrorKind::Timeout));
182        }
183        Ok(())
184    }
185}