Skip to main content

mirascript_vm/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4extern crate self as mirascript_vm;
5
6mod bytecode;
7mod context;
8mod error;
9mod interpreter;
10mod operations;
11mod standard_library;
12mod value;
13
14use std::rc::Rc;
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16
17pub use context::MiraContext;
18pub use error::{MiraError, Result};
19pub use mirascript_core as core;
20pub use mirascript_vm_derive::{MiraArray, MiraExtern, MiraRecord};
21pub use value::{
22    MiraAny, MiraArray, MiraCallContext, MiraExtern, MiraFunction, MiraModule, MiraNativeFn,
23    MiraRecord, MiraShared,
24};
25
26#[doc(hidden)]
27pub mod __private {
28    pub use crate::value::MiraBridge;
29}
30
31use bytecode::Program;
32
33/// A validated, reusable MiraScript program.
34#[derive(Clone)]
35pub struct MiraScript {
36    program: Program,
37}
38
39/// Limits and injectable providers for one execution.
40#[derive(Clone)]
41pub struct RunOptions {
42    /// Maximum wall-clock time allowed for one execution.
43    pub timeout: Duration,
44    /// Number of interpreter checkpoints between timeout-provider checks.
45    ///
46    /// Values below one are treated as one.
47    pub checkpoint_interval: u32,
48    /// Maximum nested script, native, and extern call depth.
49    pub max_call_depth: u32,
50    /// Maximum number of elements created by bounded array operations.
51    pub max_array_len: usize,
52    /// Host implementation for random numbers, time, and debug output.
53    pub providers: Rc<dyn RuntimeProviders>,
54}
55
56/// Host capabilities used by non-deterministic standard-library functions.
57pub trait RuntimeProviders {
58    /// Return a uniformly distributed random number in `[0, 1)`.
59    fn random(&self) -> f64 {
60        rand::random()
61    }
62
63    /// Return the current Unix timestamp in milliseconds.
64    fn now_millis(&self) -> i64 {
65        SystemTime::now()
66            .duration_since(UNIX_EPOCH)
67            .unwrap_or_default()
68            .as_millis() as i64
69    }
70
71    /// Emit one debug message from a script.
72    fn debug(&self, message: &str) {
73        eprintln!("{message}");
74    }
75}
76
77struct SystemRuntimeProviders;
78
79impl RuntimeProviders for SystemRuntimeProviders {}
80
81std::thread_local! {
82    static DEFAULT_RUNTIME_PROVIDERS: Rc<dyn RuntimeProviders> = Rc::new(SystemRuntimeProviders);
83}
84
85impl Default for RunOptions {
86    fn default() -> Self {
87        Self {
88            timeout: Duration::from_millis(100),
89            checkpoint_interval: 100,
90            max_call_depth: 128,
91            max_array_len: 0x100_0000,
92            providers: DEFAULT_RUNTIME_PROVIDERS.with(Clone::clone),
93        }
94    }
95}
96
97/// Compile source with the default compiler configuration.
98///
99/// The returned program is validated once and can be reused with multiple
100/// [`MiraContext`] values.
101///
102/// # Examples
103///
104/// ```
105/// use mirascript_vm::{MiraAny, MiraContext, compile};
106///
107/// let script = compile("answer + 1")?;
108/// let mut context = MiraContext::new();
109/// context.insert("answer", 41);
110/// assert_eq!(script.run(&context)?, MiraAny::Number(42.0));
111/// # Ok::<(), mirascript_vm::MiraError>(())
112/// ```
113pub fn compile(source: &str) -> Result<MiraScript> {
114    compile_with(source, &core::Config::new())
115}
116
117/// Compile source with an explicit [`core::Config`].
118pub fn compile_with(source: &str, config: &core::Config) -> Result<MiraScript> {
119    let (chunk, diagnostics) = core::Compiler::compile(source, config);
120    let chunk = chunk.ok_or(MiraError::Compile { diagnostics })?;
121    Ok(MiraScript {
122        program: Program::decode(&chunk)?,
123    })
124}
125
126/// Compile and execute source once with default [`RunOptions`].
127///
128/// # Examples
129///
130/// ```
131/// use mirascript_vm::{MiraAny, MiraContext, eval};
132///
133/// assert_eq!(eval("6 * 7", &MiraContext::new())?, MiraAny::Number(42.0));
134/// # Ok::<(), mirascript_vm::MiraError>(())
135/// ```
136pub fn eval(source: &str, context: &MiraContext) -> Result<MiraAny> {
137    compile(source)?.run(context)
138}
139
140impl MiraScript {
141    /// Execute this program with default [`RunOptions`].
142    pub fn run(&self, context: &MiraContext) -> Result<MiraAny> {
143        self.run_with(context, &RunOptions::default())
144    }
145
146    /// Execute this program with explicit limits and runtime providers.
147    pub fn run_with(&self, context: &MiraContext, options: &RunOptions) -> Result<MiraAny> {
148        interpreter::run(&self.program, context, options)
149    }
150}