bvm_lang/lib.rs
1//! # bvm_lang
2//!
3//! A small, fast bytecode virtual machine — the execution engine an interpreted
4//! language runs on once its source has been compiled down to instructions.
5//!
6//! `bvm-lang` is a **register machine**. Instructions name the registers they read
7//! and write (`Add { dst, lhs, rhs }`) instead of shuffling an operand stack, so a
8//! program runs in far fewer dispatch steps than the stack-machine equivalent.
9//! Each [`Op`] is a fixed-size, already-decoded value; a program is a slice of
10//! them plus a pool of constants, walked by a program counter in a single
11//! `match`-based dispatch loop. The whole crate is safe Rust — `unsafe` is
12//! forbidden — and treats the bytecode it runs as untrusted: a malformed program
13//! produces a [`VmError`], never a panic.
14//!
15//! The runtime value type is [`Value`] from
16//! [`value-lang`](https://docs.rs/value-lang): an eight-byte NaN-boxed handle that
17//! represents `nil`, a boolean, a 32-bit integer, a float, or an interned symbol.
18//! Every register holds one, and the VM speaks the same value as the rest of the
19//! language-construction family.
20//!
21//! ## The pieces
22//!
23//! - [`Op`] — the instruction set: data movement, arithmetic, comparison, logic,
24//! branches, and termination.
25//! - [`Chunk`] — a built program: instructions, a constant pool, and an
26//! automatically sized register file. Construct one with [`Chunk::emit`] and
27//! [`Chunk::constant`]; fix up forward branches with [`Chunk::patch`].
28//! - [`Vm`] — the interpreter. [`Vm::run`] executes a chunk and returns its
29//! result [`Value`].
30//! - [`VmError`] — every way a run can fail, from a type mismatch to a corrupt
31//! branch target.
32//!
33//! ## Example
34//!
35//! Compile and run `(2 + 3) * 4`:
36//!
37//! ```
38//! use bvm_lang::{Chunk, Op, Vm};
39//!
40//! let mut chunk = Chunk::new();
41//! chunk.emit(Op::LoadInt { dst: 0, val: 2 });
42//! chunk.emit(Op::LoadInt { dst: 1, val: 3 });
43//! chunk.emit(Op::Add { dst: 0, lhs: 0, rhs: 1 }); // r0 = 2 + 3
44//! chunk.emit(Op::LoadInt { dst: 1, val: 4 });
45//! chunk.emit(Op::Mul { dst: 0, lhs: 0, rhs: 1 }); // r0 = 5 * 4
46//! chunk.emit(Op::Return { src: 0 });
47//!
48//! let mut vm = Vm::new();
49//! let result = vm.run(&chunk).expect("well-formed program");
50//! assert_eq!(result.as_int(), Some(20));
51//! ```
52//!
53//! ## Semantics
54//!
55//! Arithmetic and ordering work over a single numeric tower: integer-with-integer
56//! stays an integer and is **overflow-checked** (a fault is reported, never a
57//! silent wrap), while any float operand promotes the result to float. Integer
58//! division or remainder by zero is a [`VmError::DivideByZero`]; float division by
59//! zero follows IEEE-754. Comparisons and [`Op::Not`] produce booleans, and every
60//! branch condition must be a boolean. See [`Op`] for per-instruction detail.
61//!
62//! ## `no_std`
63//!
64//! The crate is `no_std`-compatible and needs only `alloc` (the code, constant
65//! pool, and register file are heap-allocated vectors). The default `std` feature
66//! is additive and forwards to `value-lang`. The optional `serde` feature derives
67//! `Serialize` / `Deserialize` for [`Op`] and [`Chunk`], so compiled bytecode can
68//! be persisted and reloaded.
69
70#![cfg_attr(not(feature = "std"), no_std)]
71#![cfg_attr(docsrs, feature(doc_cfg))]
72#![deny(missing_docs)]
73#![deny(unused_must_use)]
74#![deny(unused_results)]
75#![deny(clippy::unwrap_used)]
76#![deny(clippy::expect_used)]
77#![deny(clippy::todo)]
78#![deny(clippy::unimplemented)]
79#![deny(clippy::print_stdout)]
80#![deny(clippy::print_stderr)]
81#![deny(clippy::dbg_macro)]
82#![deny(clippy::unreachable)]
83#![forbid(unsafe_code)]
84
85extern crate alloc;
86
87mod chunk;
88mod error;
89mod eval;
90mod op;
91mod vm;
92
93pub use chunk::Chunk;
94pub use error::VmError;
95pub use op::{Addr, Const, Op, Reg};
96pub use vm::Vm;
97
98/// The runtime value every register holds, re-exported from
99/// [`value-lang`](https://docs.rs/value-lang).
100///
101/// See [`Value`] for the eight-byte NaN-boxed representation and its
102/// constructors and accessors. [`Unpacked`] is the tagged-union view for matching
103/// on a value's kind, and [`Symbol`] is the interned-string handle a value can
104/// carry.
105pub use value_lang::{Symbol, Unpacked, Value};
106
107#[cfg(test)]
108mod tests {
109 #![allow(clippy::unwrap_used, clippy::expect_used)]
110 use super::*;
111
112 #[test]
113 fn test_public_surface_runs_end_to_end() {
114 let mut chunk = Chunk::new();
115 let k = chunk.constant(Value::float(1.5)).expect("pool has room");
116 let _ = chunk.emit(Op::LoadConst { dst: 0, index: k });
117 let _ = chunk.emit(Op::LoadInt { dst: 1, val: 2 });
118 let _ = chunk.emit(Op::Add {
119 dst: 0,
120 lhs: 0,
121 rhs: 1,
122 });
123 let _ = chunk.emit(Op::Return { src: 0 });
124
125 let mut vm = Vm::new();
126 assert_eq!(vm.run(&chunk).map(|v| v.as_float()), Ok(Some(3.5)));
127 }
128}