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#[derive(Clone)]
35pub struct MiraScript {
36 program: Program,
37}
38
39#[derive(Clone)]
41pub struct RunOptions {
42 pub timeout: Duration,
44 pub checkpoint_interval: u32,
48 pub max_call_depth: u32,
50 pub max_array_len: usize,
52 pub providers: Rc<dyn RuntimeProviders>,
54}
55
56pub trait RuntimeProviders {
58 fn random(&self) -> f64 {
60 rand::random()
61 }
62
63 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 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
97pub fn compile(source: &str) -> Result<MiraScript> {
114 compile_with(source, &core::Config::new())
115}
116
117pub 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
126pub fn eval(source: &str, context: &MiraContext) -> Result<MiraAny> {
137 compile(source)?.run(context)
138}
139
140impl MiraScript {
141 pub fn run(&self, context: &MiraContext) -> Result<MiraAny> {
143 self.run_with(context, &RunOptions::default())
144 }
145
146 pub fn run_with(&self, context: &MiraContext, options: &RunOptions) -> Result<MiraAny> {
148 interpreter::run(&self.program, context, options)
149 }
150}