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 error;
8mod interpreter;
9mod operations;
10mod standard_library;
11mod value;
12
13use std::{
14    num::NonZeroU64,
15    rc::Rc,
16    sync::atomic::{AtomicU64, Ordering},
17    time::{Duration, SystemTime, UNIX_EPOCH},
18};
19
20pub use core::{CompileConfig, DiagnosticPositionEncoding, InputMode};
21pub use mirascript_core as core;
22pub use mirascript_vm_derive::{MiraArray, MiraRecord};
23
24pub use error::*;
25pub use interpreter::Runtime;
26pub(crate) use value::MiraValueKind;
27pub use value::{
28    MiraArray, MiraExtern, MiraFunction, MiraHandle, MiraManageable, MiraModule, MiraNativeFn,
29    MiraRecord, MiraShapedArray, MiraShapedRecord, MiraType, MiraValue,
30};
31
32use bytecode::Program;
33
34static NEXT_SCRIPT_ID: AtomicU64 = AtomicU64::new(1);
35
36/// Stable identity shared by clones of one compiled script.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct ScriptId(NonZeroU64);
39
40impl ScriptId {
41    fn new() -> Self {
42        let id = NEXT_SCRIPT_ID.fetch_add(1, Ordering::Relaxed);
43        Self(NonZeroU64::new(id).expect("MiraScript identifier space exhausted"))
44    }
45}
46
47/// A validated, reusable MiraScript program.
48#[derive(Clone, Debug)]
49pub struct MiraScript {
50    id: ScriptId,
51    program: Rc<Program>,
52}
53
54impl MiraScript {
55    /// Return the stable identity shared by clones of this script.
56    pub fn id(&self) -> ScriptId {
57        self.id
58    }
59}
60
61/// Limits and injectable providers used for each Runtime execution.
62#[derive(Clone)]
63pub struct RunOptions {
64    /// Maximum wall-clock time allowed for one execution.
65    pub timeout: Duration,
66    /// Number of interpreter checkpoints between timeout-provider checks.
67    pub checkpoint_interval: u32,
68    /// Maximum nested script and native call depth.
69    pub max_call_depth: u32,
70    /// Maximum number of elements created by bounded array operations.
71    pub max_array_len: usize,
72    /// Host implementation for random numbers, time, and debug output.
73    pub providers: Rc<dyn RuntimeProviders>,
74}
75
76/// Host capabilities used by non-deterministic standard-library functions.
77pub trait RuntimeProviders {
78    /// Return a uniformly distributed random number in `[0, 1)`.
79    fn random(&self) -> f64 {
80        rand::random()
81    }
82
83    /// Return the current Unix timestamp in milliseconds.
84    fn now_millis(&self) -> i64 {
85        SystemTime::now()
86            .duration_since(UNIX_EPOCH)
87            .unwrap_or_default()
88            .as_millis() as i64
89    }
90
91    /// Emit one debug message from a script.
92    fn debug(&self, message: &str) {
93        eprintln!("{message}");
94    }
95}
96
97struct SystemRuntimeProviders;
98impl RuntimeProviders for SystemRuntimeProviders {}
99
100std::thread_local! {
101    static DEFAULT_RUNTIME_PROVIDERS: Rc<dyn RuntimeProviders> = Rc::new(SystemRuntimeProviders);
102}
103
104impl Default for RunOptions {
105    fn default() -> Self {
106        Self {
107            timeout: Duration::from_millis(100),
108            checkpoint_interval: 100,
109            max_call_depth: 128,
110            max_array_len: 0x100_0000,
111            providers: DEFAULT_RUNTIME_PROVIDERS.with(Clone::clone),
112        }
113    }
114}
115
116/// Compile source with the default compiler configuration.
117///
118/// ```
119/// use mirascript_vm::{MiraValue, Runtime, compile};
120///
121/// let script = compile("6 * 7")?;
122/// let mut runtime = Runtime::new();
123/// assert_eq!(runtime.run(&script)?, MiraValue::number(42.0));
124/// # Ok::<(), Box<mirascript_vm::MiraError>>(())
125/// ```
126pub fn compile(source: &str) -> Result<MiraScript> {
127    compile_with(source, &CompileConfig::new())
128}
129
130/// Compile source with an explicit [`CompileConfig`].
131///
132/// ```
133/// use mirascript_vm::{MiraValue, Runtime, CompileConfig, InputMode, compile_with};
134///
135/// let mut config = CompileConfig::new();
136/// config.input_mode = InputMode::Template;
137/// let script = compile_with("Hello, $name!", &config)?;
138/// let mut runtime = Runtime::new();
139/// runtime.insert_global("name", &"Alice")?;
140/// assert_eq!(runtime.run(&script)?.as_str(&runtime)?.unwrap(), "Hello, Alice!");
141/// # Ok::<(), Box<mirascript_vm::MiraError>>(())
142/// ```
143pub fn compile_with(source: &str, config: &CompileConfig) -> Result<MiraScript> {
144    let (chunk, diagnostics) = core::Compiler::compile(source, config);
145    let chunk = chunk.ok_or_else(|| MiraError::compile(&diagnostics))?;
146    Ok(MiraScript {
147        id: ScriptId::new(),
148        program: Rc::new(Program::decode(&chunk)?),
149    })
150}
151
152/// Items used by the derive macros. They are not a stable user-facing API.
153#[doc(hidden)]
154pub mod __private {
155    pub use crate::value::types::{
156        MiraField, shaped_array_from_array, shaped_array_from_record, shaped_record_from_array,
157        shaped_record_from_record,
158    };
159}