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