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;
22pub 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#[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#[derive(Clone, Debug)]
50pub struct MiraScript {
51 id: ScriptId,
52 program: Rc<Program>,
53}
54
55impl MiraScript {
56 pub fn id(&self) -> ScriptId {
58 self.id
59 }
60}
61
62#[derive(Clone)]
64pub struct RunOptions {
65 pub timeout: Duration,
67 pub checkpoint_interval: u32,
69 pub max_call_depth: u32,
71 pub max_array_len: usize,
73 pub providers: Rc<dyn RuntimeProviders>,
75}
76
77pub trait RuntimeProviders {
79 fn random(&self) -> f64 {
81 rand::random()
82 }
83
84 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 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
117pub fn compile(source: &str) -> Result<MiraScript> {
128 compile_with(source, &CompileConfig::new())
129}
130
131pub 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#[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}