Skip to main content

mirascript_vm/interpreter/
call.rs

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