nybl_vm/lib.rs
1//! Bytecode compiler and stack VM for the Nybl programming language.
2//!
3//! `nybl-vm` implements the same language, host interface, values, limits, and
4//! diagnostics as the tree-walker in [`nybl-lang`](https://docs.rs/nybl-lang),
5//! while compiling source to reusable bytecode. It is the usual choice for
6//! scripts that run hot loops or are executed repeatedly at runtime.
7//!
8//! # One-shot execution
9//!
10//! [`run`] parses, compiles, validates, and executes one isolated program:
11//!
12//! ```
13//! use nybl::{NyblError, NyblHost, NyblLimits, Value};
14//!
15//! struct Host;
16//! impl NyblHost for Host {
17//! fn call(
18//! &mut self,
19//! _: &str,
20//! _: &[Value],
21//! _: u32,
22//! ) -> Option<Result<Value, NyblError>> {
23//! None
24//! }
25//!
26//! fn on_print(&mut self, message: &str) {
27//! assert_eq!(message, "42");
28//! }
29//! }
30//!
31//! let mut host = Host;
32//! nybl_vm::run(
33//! "print(6 * 7)",
34//! &mut host,
35//! &NyblLimits::standard(),
36//! ).unwrap();
37//! ```
38//!
39//! # Compile once, execute with fresh state
40//!
41//! Use [`compile`] and [`execute`] when the bytecode should be reused but each
42//! run should start with fresh globals:
43//!
44//! ```
45//! # use nybl::{NyblError, NyblHost, NyblLimits, Value};
46//! # struct Host;
47//! # impl NyblHost for Host {
48//! # fn call(&mut self, _: &str, _: &[Value], _: u32)
49//! # -> Option<Result<Value, NyblError>> { None }
50//! # }
51//! let statements = nybl::parse("let answer = 6 * 7").unwrap();
52//! let chunk = nybl_vm::compile(&statements).unwrap();
53//! nybl_vm::validate_chunk(&chunk).unwrap();
54//!
55//! let mut host = Host;
56//! nybl_vm::execute(
57//! chunk,
58//! &mut host,
59//! &NyblLimits::standard(),
60//! ).unwrap();
61//! ```
62//!
63//! [`validate_chunk`] rejects malformed control flow, operands, pool indices,
64//! and nested chunks before execution. [`disassemble`] provides a readable
65//! representation for tooling and diagnostics.
66//!
67//! # Persistent programs
68//!
69//! [`NyblInstance`] loads and compiles once, then retains globals, modules,
70//! functions, types, methods, callbacks, and random-number state across host
71//! calls. Root-level `pub fn` declarations define the callable ABI.
72//!
73//! ```
74//! # use nybl::{NyblError, NyblHost, NyblLimits, Value};
75//! # struct Host;
76//! # impl NyblHost for Host {
77//! # fn call(&mut self, _: &str, _: &[Value], _: u32)
78//! # -> Option<Result<Value, NyblError>> { None }
79//! # }
80//! let mut host = Host;
81//! let mut instance = nybl_vm::NyblInstance::load(
82//! "let count = 0\npub fn next() { count += 1; return count }",
83//! &mut host,
84//! &NyblLimits::standard(),
85//! ).unwrap();
86//! assert_eq!(
87//! instance.call("next", &[], &mut host).unwrap().inspect(),
88//! "1",
89//! );
90//! ```
91//!
92//! # Reference parameters
93//!
94//! The VM implements Nybl's explicit `ref` parameters with the same
95//! transactional copy-in/copy-out semantics as the tree-walker and AOT
96//! engine. Mutable plain-variable targets commit together after a normal
97//! return and roll back together on runtime or resource errors. Parameter
98//! modes remain attached to first-class callable values.
99//!
100//! Rust [`NyblInstance::call`] and [`NyblInstance::call_value`] arguments are
101//! value-only and reject ref-bearing callables before execution. See the
102//! [reference-parameters
103//! guide](https://nybl-lang.com/docs/functions/reference-parameters/) for the
104//! complete target, forwarding, evaluation-order, and method rules.
105//! User-defined `ref self` receivers use the same transactional commit and
106//! rollback path as explicit reference arguments; ordinary `self` is
107//! read-only.
108//!
109//! # Features
110//!
111//! - `std` (default) retains Rust standard-library host behavior and forwards
112//! to `nybl-lang/std`.
113//! - `nybl-std` (default) forwards to `nybl-lang/nybl-std` so hosts can
114//! resolve the bundled `std.*` modules.
115//! - `no_std` forwards to `nybl-lang/no_std`; combine it with
116//! `default-features = false` for bare-metal or
117//! `wasm32-unknown-unknown` builds.
118//! If Cargo unifies `std` and `no_std`, `std` wins.
119//!
120//! See the [embedding guide](https://nybl-lang.com/docs/embedding/) and
121//! [stateful instance guide](https://nybl-lang.com/docs/embedding/instances/)
122//! for lifecycle, limits, callback affinity, and engine-selection details.
123
124#![cfg_attr(all(feature = "no_std", not(feature = "std")), no_std)]
125
126#[cfg(all(feature = "no_std", not(feature = "std")))]
127extern crate alloc;
128
129// A genuine no_std unit-test build still uses Rust's standard test harness;
130// make that test-only dependency explicit.
131#[cfg(all(test, feature = "no_std", not(feature = "std")))]
132extern crate std;
133
134pub mod chunk;
135pub mod compiler;
136pub mod disasm;
137pub mod validate;
138pub mod vm;
139
140pub use chunk::{
141 Chunk, CodeOffset, ConstIdx, Constant, EnumConstructShape, EnumDef, EnumIdx, EnumVariantDef,
142 EnumVariantShape, FnDef, FnIdx, Instr, InterpIdx, InterpPart, InterpRecipe, LoopStateKind,
143 NameIdx, StructDef, StructIdx,
144};
145pub use compiler::compile;
146pub use disasm::disassemble;
147pub use validate::validate_chunk;
148pub use vm::{CompiledScript, NyblInstance, PreparedEntry, Vm, execute, run};