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