mirascript_vm/interpreter/
runtime.rs1use std::{collections::HashMap, num::NonZeroU64, rc::Rc, time::Instant};
2
3use crate::{
4 MiraError, MiraManageable, MiraNativeFn, MiraScript, MiraValue, Result, RunOptions,
5 RuntimeErrorKind, ScriptId,
6 bytecode::{Constant, Program},
7 compile,
8 value::MiraArena,
9};
10
11use super::{CallStack, Flow, FrameArena, FrameId, Globals};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub(crate) struct ExecutionId(NonZeroU64);
15
16impl ExecutionId {
17 const INITIAL: Self = Self(NonZeroU64::MIN);
18
19 fn next(self) -> Self {
23 let id = self
24 .0
25 .get()
26 .checked_add(1)
27 .and_then(NonZeroU64::new)
28 .expect("MiraScript execution identifier space exhausted");
29 Self(id)
30 }
31}
32
33pub struct Runtime {
38 pub(crate) execution: ExecutionId,
39 pub(crate) options: RunOptions,
40 pub(crate) globals: Globals,
41 pub(crate) arena: MiraArena,
42 constant_cache: HashMap<(ScriptId, usize), MiraValue>,
43 running: bool,
44 active_script: Option<ScriptId>,
45 pub(crate) program: Option<Rc<Program>>,
46 pub(crate) started: Instant,
47 pub(crate) checkpoint_remaining: u32,
48 pub(super) frames: FrameArena,
49 pub(super) call_stack: CallStack,
50}
51
52impl Runtime {
53 pub fn new() -> Self {
55 Self::with_options(RunOptions::default())
56 }
57
58 pub fn with_options(options: RunOptions) -> Self {
60 let checkpoint_remaining = options.checkpoint_interval.max(1);
61 let mut runtime = Self {
62 execution: ExecutionId::INITIAL,
63 options,
64 globals: Globals::new(),
65 arena: MiraArena::new(),
66 constant_cache: HashMap::new(),
67 running: false,
68 active_script: None,
69 program: None,
70 started: Instant::now(),
71 checkpoint_remaining,
72 frames: FrameArena::new(0),
73 call_stack: CallStack::new(),
74 };
75 crate::standard_library::install(&mut runtime);
76 runtime
77 }
78
79 pub fn eval(&mut self, script: &str) -> Result<MiraValue> {
81 let script = compile(script)?;
82 self.run(&script)
83 }
84
85 pub fn run(&mut self, script: &MiraScript) -> Result<MiraValue> {
87 if self.running {
88 return Err(MiraError::runtime(RuntimeErrorKind::ReentrantRun));
89 }
90
91 self.running = true;
92 self.execution = self.execution.next();
93 self.active_script = Some(script.id);
94 self.program = Some(Rc::clone(&script.program));
95 self.started = Instant::now();
96 self.checkpoint_remaining = self.options.checkpoint_interval.max(1);
97 self.frames.begin_run(script.program.root.register_count);
98 debug_assert_eq!(self.call_stack.depth(), 0);
99
100 let result = (|| {
101 let body = &script.program.root.body;
102 let value = match self.execute_block(body, FrameId::ROOT)? {
103 Flow::Return(value) => value,
104 Flow::Continue => MiraValue::nil(),
105 Flow::Break | Flow::LoopContinue => {
106 return Err(MiraError::runtime(RuntimeErrorKind::InvalidControlFlow {
107 context: "root",
108 }));
109 }
110 };
111 if self.contains_script_reference(value)? {
112 return Err(MiraError::runtime(RuntimeErrorKind::EscapingClosure));
113 }
114 Ok(value)
115 })();
116
117 self.running = false;
118 self.active_script = None;
119 self.program = None;
120 debug_assert_eq!(self.call_stack.depth(), 0);
121 result
122 }
123
124 pub fn options(&self) -> &RunOptions {
126 &self.options
127 }
128
129 pub fn insert_global(
131 &mut self,
132 name: impl Into<String>,
133 value: impl Into<MiraManageable>,
134 ) -> Result<Option<MiraValue>> {
135 let value = self.insert(value)?;
136 Ok(self.globals.insert(name.into(), value))
137 }
138
139 pub fn insert_fn(&mut self, name: impl Into<String>, function: impl Into<MiraNativeFn>) {
141 let name = name.into();
142 let function = function.into().with_name(name.clone());
143 let handle = self
144 .insert_function(function)
145 .expect("a fresh native function arena slot must be available");
146 self.globals.insert(
147 name,
148 MiraValue::from_function_handle(handle.erase_function()),
149 );
150 }
151
152 pub fn get_global(&self, name: &str) -> Option<MiraValue> {
154 self.globals.get(name)
155 }
156
157 pub fn contains_global(&self, name: &str) -> bool {
159 self.globals.contains_key(name)
160 }
161
162 pub fn global_names(&self) -> impl Iterator<Item = &str> {
164 self.globals.keys()
165 }
166
167 pub fn values_equal(&mut self, left: MiraValue, right: MiraValue) -> Result<bool> {
169 crate::operations::host_equal(self, left, right)
170 }
171
172 pub(crate) fn active_program(&self) -> &Rc<Program> {
173 self.program
174 .as_ref()
175 .expect("interpreter operations require an active program")
176 }
177
178 pub(crate) fn materialize_constant(&mut self, index: usize) -> Result<MiraValue> {
179 let constant = &self.active_program().constants[index];
180 match constant {
181 Constant::Nil => Ok(MiraValue::nil()),
182 Constant::True => Ok(MiraValue::boolean(true)),
183 Constant::False => Ok(MiraValue::boolean(false)),
184 Constant::Int(value) => Ok(MiraValue::number(f64::from(*value))),
185 Constant::Float(value) => Ok(MiraValue::number(*value)),
186 Constant::String(value) => {
187 let script = self
188 .active_script
189 .expect("constant materialization requires an active script");
190 if let Some(value) = self.constant_cache.get(&(script, index)) {
191 return Ok(*value);
192 }
193 let value = self.insert(value.clone().into_string())?;
194 self.constant_cache.insert((script, index), value);
195 Ok(value)
196 }
197 }
198 }
199
200 pub(crate) fn constant_string(&self, index: usize) -> Result<Option<&str>> {
201 match &self.active_program().constants[index] {
202 Constant::Nil => Ok(None),
203 Constant::String(value) => Ok(Some(value)),
204 _ => Err(MiraError::runtime(RuntimeErrorKind::InvalidConstantKind {
205 index,
206 expected: "string",
207 })),
208 }
209 }
210
211 #[cfg(test)]
212 pub(crate) fn materialized_constant_count(&self) -> usize {
213 self.constant_cache.len()
214 }
215}
216
217impl Default for Runtime {
218 fn default() -> Self {
219 Self::new()
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use crate::{Runtime, compile};
226
227 #[test]
228 fn string_constants_are_materialized_lazily_and_cached_per_script() {
229 let skipped = compile("if false { 'unreachable' } else { 1 }").unwrap();
230 let repeated = compile("'cached'").unwrap();
231 let repeated_clone = repeated.clone();
232 let distinct = compile("'cached'").unwrap();
233
234 let mut first = Runtime::new();
235 first.run(&skipped).unwrap();
236 assert_eq!(first.materialized_constant_count(), 0);
237
238 let first_value = first.run(&repeated).unwrap();
239 assert_eq!(first_value.as_str(&first).unwrap(), Some("cached"));
240 assert_eq!(first.materialized_constant_count(), 1);
241 first.run(&repeated_clone).unwrap();
242 assert_eq!(first.materialized_constant_count(), 1);
243 first.run(&distinct).unwrap();
244 assert_eq!(first.materialized_constant_count(), 2);
245
246 let mut second = Runtime::new();
247 let second_value = second.run(&repeated).unwrap();
248 assert_eq!(second.materialized_constant_count(), 1);
249 assert!(first_value.is_string());
250 assert!(second_value.is_string());
251 assert!(second.insert(first_value).is_err());
252 }
253}