Skip to main content

Crate mirascript_vm

Crate mirascript_vm 

Source
Expand description

§mirascript-vm

mirascript-vm is the native, single-threaded Rust runtime for MiraScript. Source is compiled and validated independently from execution: a MiraScript contains only the decoded program and owned constant table, while a Runtime owns globals, the standard library, execution state, and every dynamically allocated value.

§Quick start

use mirascript_vm::{MiraRecord, MiraValue, Runtime, compile};

#[derive(MiraRecord)]
struct Foo {
    bar: u8,
}

let script = compile("foo.bar")?;
let mut runtime = Runtime::new();
let foo = runtime.insert_record(Foo { bar: 42 })?;
runtime.insert_global("foo", MiraValue::record(foo))?;

assert_eq!(runtime.run(&script)?, MiraValue::number(42.0));

One script can run in multiple runtimes, and one runtime can run any number of scripts. Each run resets frames, registers, the call stack, timeout accounting, and its execution generation. Globals, standard-library values, the arena, and materialized string constants remain until the runtime is dropped. Re-entering Runtime::run from a native callback returns RuntimeErrorKind::ReentrantRun.

§Values and arena ownership

MiraValue is an 8-byte, copyable NaN-box. Nil, booleans, numbers, and truly static strings are inline; dynamic strings, arrays, records, functions, and modules use 48-bit typed handles into the owning runtime’s append-only arena. Checked lookups reject foreign, out-of-range, and wrongly typed handles.

The compiled constant table never contains runtime handles. A string constant is allocated only when its bytecode instruction executes and is cached by (ScriptId, constant_index) in that runtime. Unexecuted branches allocate nothing, clones of one script share the cache identity, and different runtimes materialize their own copies.

Use Runtime::insert for an owned MiraManageable, or the category-specific insert_string, insert_array, insert_record, insert_function, and insert_module methods when a typed MiraHandle<T> is needed. The matching checked get_* and get_*_mut methods let the host inspect or mutate live values.

§Host records, arrays, functions, and modules

All compound behavior is dispatched through dyn MiraArray, dyn MiraRecord, dyn MiraFunction, and dyn MiraModule. Script and host implementations use the same traits; MiraManageable carries an owned value until Runtime::insert places it in the correct arena.

#[derive(MiraRecord)] supports all structs and #[derive(MiraArray)] supports tuple and unit structs. Both preserve #[mira(rename = "...")], #[mira(skip)], generics, dependency aliases, and #[mira(crate = ...)]. Nested derived records and arrays are projection views: they retain a typed parent handle and read the field from the runtime on every access instead of cloning it.

use mirascript_vm::{MiraRecord, MiraValue, Runtime, compile};

#[derive(MiraRecord)]
struct Position { x: f64, y: f64 }

#[derive(MiraRecord)]
struct User { name: String, position: Position }

let mut runtime = Runtime::new();
let user = runtime.insert_record(User {
    name: "Ada".into(),
    position: Position { x: 3.0, y: 4.0 },
})?;
runtime.insert_global("user", MiraValue::record(user))?;

let script = compile("user.position.x")?;
assert_eq!(runtime.run(&script)?, MiraValue::number(3.0));
runtime.get_record_mut(user)?.position.x = 10.0;
assert_eq!(runtime.run(&script)?, MiraValue::number(10.0));

Use #[mira] to expose native functions and inline modules. The original Rust function is unchanged; the macro adds an upper-case companion constant that can be inserted into a runtime. Inside a Mira module, function diagnostic names are qualified while export keys remain local.

use mirascript_vm::{Runtime, mira};

#[mira]
mod arithmetic {
    use mirascript_vm::MiraValue;

    #[mira]
    pub const ANSWER: usize = 42;

    #[mira]
    pub fn add(a: f64, b: f64) -> f64 { a + b }

    #[mira]
    pub fn sum(start: f64, rest: &[MiraValue]) -> mirascript_vm::Result<f64> {
        rest.iter().try_fold(start, |sum, value| {
            Ok(sum + f64::try_from(*value)?)
        })
    }
}

assert_eq!(arithmetic::add(1.0, 2.0), 3.0);
let mut runtime = Runtime::new();
runtime.insert_global("arithmetic", ARITHMETIC)?;
assert_eq!(runtime.eval("arithmetic.add(1, 2)")?, 3.into());
assert_eq!(runtime.eval("arithmetic.sum(1, 2, 3)")?, 6.into());

const = NAME overrides the Rust companion constant, rename = "full.name" overrides the MiraFunction or MiraModule diagnostic name, and use = "key" overrides the direct parent module’s export key. Consecutive #[mira] modules build dotted default names; an unmarked module starts a new naming root.

MiraExtern is currently only a public, sealed marker. It has no constructor or derive macro, and downstream crates cannot implement it.

§Execution options and providers

Runtime::with_options configures the timeout, checkpoint interval, maximum call depth, maximum bounded array length, and a RuntimeProviders implementation for random numbers, time, and debug output.

use std::rc::Rc;
use mirascript_vm::{RunOptions, Runtime, RuntimeProviders, compile};

struct Deterministic;
impl RuntimeProviders for Deterministic {
    fn random(&self) -> f64 { 0.25 }
}

let mut runtime = Runtime::with_options(RunOptions {
    providers: Rc::new(Deterministic),
    ..RunOptions::default()
});
assert_eq!(runtime.run(&compile("random()")?)?.as_number(), Some(0.25));

Timeout checks are cooperative. Loop backedges and function calls reach checkpoints; a blocking native callback cannot be preempted.

§Lifetimes and errors

Strings, arrays, and records returned from a run remain valid in that runtime. Script closures and modules retain their shared decoded program and execution generation but cannot escape as results; cached callables from an older run return RuntimeErrorKind::ExecutionEnded. The runtime has no garbage collector: all arena values are released together when it is dropped.

MiraError separates compiler diagnostics, invalid bytecode, structured runtime failures, conversion failures with field/index paths, and arbitrary host errors. Runtime errors retain bytecode offsets and call-stack context.

§Development

cargo fmt --all -- --check
cargo check --workspace --all-targets
cargo test --workspace
cargo doc --workspace --no-deps
git diff --check

Re-exports§

pub use mirascript_core as core;

Macros§

global_builtin
A macro to define a global builtin function and insert it into the runtime.

Structs§

CompileConfig
Diagnostics
Represents a diagnostic message produced by the compiler.
MiraArrayEntry
One element produced by MiraArray::iter.
MiraHandle
A compact, runtime-checked handle to an arena-managed value.
MiraNativeFn
A named, single-threaded native function callable from MiraScript.
MiraRecordEntry
One field produced by MiraRecord::iter.
MiraScript
A validated, reusable MiraScript program.
MiraValue
A compact value understood by the Rust VM.
RunOptions
Limits and injectable providers used for each Runtime execution.
Runtime
Persistent state used to execute compiled MiraScript programs.
RuntimeTrace
Runtime source location and call stack attached to an execution error.
ScriptId
Stable identity shared by clones of one compiled script.

Enums§

ConversionPathSegment
One segment in a failed Rust value conversion path.
ConversionReason
The reason a MiraScript value could not be converted to a Rust type.
DiagnosticCode
Diagnostic codes for MiraScript compiler and tools.
DiagnosticPositionEncoding
Encoding for counting positions in diagnostics.
InputMode
Mode for reading input.
InvalidBytecodeReason
Represents the reason for an invalid bytecode error.
MiraError
An error produced while compiling, decoding, executing, or bridging values.
MiraManageable
An owned value waiting to be inserted into a Runtime arena.
MiraType
A MiraScript runtime value category.
RuntimeErrorKind
A VM or standard-library execution failure.

Traits§

MiraArray
A read-only MiraScript array view.
MiraExtern
Reserved marker for a future MiraScript external value implementation.
MiraFunction
A callable MiraScript function implementation.
MiraModule
A named collection of MiraScript-visible values.
MiraRecord
A read-only MiraScript record view.
MiraShapedArray
A fixed-shape array whose length is known from its Rust type.
MiraShapedRecord
A fixed-shape record whose field names are known from its Rust type.
RuntimeProviders
Host capabilities used by non-deterministic standard-library functions.
TryFromMira
A trait for converting values from the runtime into Rust types.

Functions§

compile
Compile source with the default compiler configuration.
compile_with
Compile source with an explicit CompileConfig.
default_runtime_providers
Return a reference-counted handle to the default runtime providers.

Type Aliases§

MiraArrayHandle
A handle to a MiraScript array value.
MiraArrayIter
A sequential iterator over array elements.
MiraExternHandle
A handle to a MiraScript extern value.
MiraFunctionHandle
A handle to a MiraScript function value.
MiraModuleHandle
A handle to a MiraScript module value.
MiraRecordHandle
A handle to a MiraScript record value.
MiraRecordIter
A sequential iterator over record fields.
MiraStringHandle
A handle to a MiraScript string value.
Result
Result type returned by the MiraScript VM.

Attribute Macros§

mira
Expose a Rust function or inline module as a MiraScript value.

Derive Macros§

MiraArray
Derive a read-only MiraScript array view for a tuple struct.
MiraRecord
Derive a read-only MiraScript record view for a named-field struct.