Skip to main content

mirascript_vm/interpreter/
runtime.rs

1use std::{collections::HashMap, num::NonZeroU64, rc::Rc, time::Instant};
2
3use crate::{
4    MiraError, MiraScript, MiraValue, Result, RunOptions, RuntimeErrorKind, ScriptId,
5    bytecode::{Constant, Program},
6    compile,
7    value::MiraArena,
8};
9
10use super::{CallStack, Flow, FrameArena, FrameId, Globals};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub(crate) struct ExecutionId(NonZeroU64);
14
15impl ExecutionId {
16    const INITIAL: Self = Self(NonZeroU64::MIN);
17
18    // Script references are resolved through this Runtime's arena before this
19    // generation is compared, so foreign Runtime values remain guarded by the
20    // arena identifier and the generation only needs to be Runtime-local.
21    fn next(self) -> Self {
22        let id = self
23            .0
24            .get()
25            .checked_add(1)
26            .and_then(NonZeroU64::new)
27            .expect("MiraScript execution identifier space exhausted");
28        Self(id)
29    }
30}
31
32/// Persistent state used to execute compiled MiraScript programs.
33///
34/// A Runtime owns all dynamically allocated values. Values containing handles
35/// therefore remain usable until this Runtime is dropped.
36pub struct Runtime {
37    pub(crate) execution: ExecutionId,
38    pub(crate) options: RunOptions,
39    pub(crate) globals: Globals,
40    pub(crate) arena: MiraArena,
41    constant_cache: HashMap<(ScriptId, usize), MiraValue>,
42    running: bool,
43    active_script: Option<ScriptId>,
44    pub(crate) program: Option<Rc<Program>>,
45    pub(crate) started: Instant,
46    pub(crate) checkpoint_remaining: u32,
47    pub(super) frames: FrameArena,
48    pub(super) call_stack: CallStack,
49}
50
51impl Runtime {
52    /// Create a Runtime using default limits and install the standard library.
53    pub fn new() -> Self {
54        Self::with_options(RunOptions::default())
55    }
56
57    /// Create a Runtime using explicit execution limits and providers.
58    pub fn with_options(options: RunOptions) -> Self {
59        let checkpoint_remaining = options.checkpoint_interval.max(1);
60        let mut runtime = Self {
61            execution: ExecutionId::INITIAL,
62            options,
63            globals: Globals::new(),
64            arena: MiraArena::new(),
65            constant_cache: HashMap::new(),
66            running: false,
67            active_script: None,
68            program: None,
69            started: Instant::now(),
70            checkpoint_remaining,
71            frames: FrameArena::new(0),
72            call_stack: CallStack::new(),
73        };
74        crate::standard_library::install(&mut runtime);
75        runtime
76    }
77
78    /// Compile and execute a MiraScript program in this Runtime.
79    pub fn eval(&mut self, script: &str) -> Result<MiraValue> {
80        let script = compile(script)?;
81        self.run(&script)
82    }
83
84    /// Compile and execute a MiraScript program in this Runtime, returning the result or panicking on error.
85    pub fn eval_unchecked(&mut self, script: &str) -> MiraValue {
86        self.eval(script).expect("evaluation failed")
87    }
88
89    /// Execute a compiled script in this Runtime.
90    pub fn run(&mut self, script: &MiraScript) -> Result<MiraValue> {
91        if self.running {
92            return Err(MiraError::runtime(RuntimeErrorKind::ReentrantRun));
93        }
94
95        self.running = true;
96        self.execution = self.execution.next();
97        self.active_script = Some(script.id());
98        self.program = Some(script.program());
99        self.started = Instant::now();
100        self.checkpoint_remaining = self.options.checkpoint_interval.max(1);
101        self.frames
102            .begin_run(script.program_ref().root.register_count);
103        debug_assert_eq!(self.call_stack.depth(), 0);
104
105        let result = (|| {
106            let body = &script.program_ref().root.body;
107            let value = match self.execute_block(body, FrameId::ROOT)? {
108                Flow::Return(value) => value,
109                Flow::Continue => MiraValue::NIL,
110                Flow::Break | Flow::LoopContinue => {
111                    return Err(MiraError::runtime(RuntimeErrorKind::InvalidControlFlow {
112                        context: "root",
113                    }));
114                }
115            };
116            if self.contains_script_reference(value)? {
117                return Err(MiraError::runtime(RuntimeErrorKind::EscapingClosure));
118            }
119            Ok(value)
120        })();
121
122        self.running = false;
123        self.active_script = None;
124        self.program = None;
125        debug_assert_eq!(self.call_stack.depth(), 0);
126        result
127    }
128
129    /// Return the Runtime's execution configuration.
130    pub fn options(&self) -> &RunOptions {
131        &self.options
132    }
133
134    /// Compare values using MiraScript's structural equality semantics.
135    pub fn values_equal(&mut self, left: MiraValue, right: MiraValue) -> Result<bool> {
136        crate::operations::host_equal(self, left, right)
137    }
138
139    pub(crate) fn active_program(&self) -> &Rc<Program> {
140        self.program
141            .as_ref()
142            .expect("interpreter operations require an active program")
143    }
144
145    pub(crate) fn materialize_constant(&mut self, index: usize) -> Result<MiraValue> {
146        let constant = &self.active_program().constants[index];
147        match constant {
148            Constant::Nil => Ok(MiraValue::NIL),
149            Constant::True => Ok(MiraValue::boolean(true)),
150            Constant::False => Ok(MiraValue::boolean(false)),
151            Constant::Int(value) => Ok(MiraValue::number(f64::from(*value))),
152            Constant::Float(value) => Ok(MiraValue::number(*value)),
153            Constant::String(value) => {
154                let script = self
155                    .active_script
156                    .expect("constant materialization requires an active script");
157                if let Some(value) = self.constant_cache.get(&(script, index)) {
158                    return Ok(*value);
159                }
160                let value = self.insert(value.clone().into_string())?;
161                self.constant_cache.insert((script, index), value);
162                Ok(value)
163            }
164        }
165    }
166
167    pub(crate) fn constant_string(&self, index: usize) -> Result<Option<&str>> {
168        match &self.active_program().constants[index] {
169            Constant::Nil => Ok(None),
170            Constant::String(value) => Ok(Some(value)),
171            _ => Err(MiraError::runtime(RuntimeErrorKind::InvalidConstantKind {
172                index,
173                expected: "string",
174            })),
175        }
176    }
177
178    #[cfg(test)]
179    pub(crate) fn materialized_constant_count(&self) -> usize {
180        self.constant_cache.len()
181    }
182}
183
184impl Default for Runtime {
185    fn default() -> Self {
186        Self::new()
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use crate::{Runtime, compile};
193
194    #[test]
195    fn string_constants_are_materialized_lazily_and_cached_per_script() {
196        let skipped = compile("if false { 'unreachable' } else { 1 }").unwrap();
197        let repeated = compile("'cached'").unwrap();
198        let repeated_clone = repeated.clone();
199        let distinct = compile("'cached'").unwrap();
200
201        let mut first = Runtime::new();
202        first.run(&skipped).unwrap();
203        assert_eq!(first.materialized_constant_count(), 0);
204
205        let first_value = first.run(&repeated).unwrap();
206        assert_eq!(first_value.as_str(&first).unwrap(), Some("cached"));
207        assert_eq!(first.materialized_constant_count(), 1);
208        first.run(&repeated_clone).unwrap();
209        assert_eq!(first.materialized_constant_count(), 1);
210        first.run(&distinct).unwrap();
211        assert_eq!(first.materialized_constant_count(), 2);
212
213        let mut second = Runtime::new();
214        let second_value = second.run(&repeated).unwrap();
215        assert_eq!(second.materialized_constant_count(), 1);
216        assert!(first_value.is_string());
217        assert!(second_value.is_string());
218        assert!(second.insert(first_value).is_err());
219    }
220}