The model
- A
Moduleis one compilation unit: a string table, a type table (function signatures, structs with single inheritance and methods, arrays, ordered maps, cells, iterators), a constant pool, imports (host functions), globals, functions, exports, dynamic-operation hooks, and per-function debug line tables and local names. - A function is a frame of typed 64-bit registers plus a flat array of **
Inst**ructions: 200 of them, covering moves and constants, OPS integer and float arithmetic with their policies (PHP's int-to-floatpromoteand shiftsaturateincluded,powin every form), conversions, dynamic arithmetic with a numeric fast path, dynamic truthiness and logical not, calls (direct, indirect, host, tail, dynamic, and shaped dynamic calls with named and spread arguments), closures and cells, structs, arrays, insertion-ordered hash maps (PHP arrays) with copy-on-write separation and references into their slots, iteration, byte strings, type tests and casts, exceptions (raiseof any catchable kind with a payload), GC safepoints, and stackful coroutines for generators and async tasks (coro_new,yield,yield_kv,await,resume,resume_throw,coro_close,spawn). - A function or import may carry a
ParamList(names, rest parameters, defaults with a presence mask, by-reference parameters);ParamList::bindis the one binding rule every tier applies to dynamic calls. encodeanddecodeconvert between a module and its canonical bytes;disassembleprints it.ModuleBuilderbuilds modules: branches take labels, strings and constants are deduplicated, and simultaneous register moves are sequentialized correctly.
The normative semantics of every instruction, the encoding, and the verifier's rules are in the LexerSketch spec specs/LSB.md.
What it guarantees, and how each guarantee is checked:
| Guarantee | How it is held |
|---|---|
Encoding round-trips exactly: decode(encode(m)) == m. |
Property tests over arbitrary modules built from every opcode, every modifier value, and every table, debug information included. |
Each module has exactly one encoding: encode(decode(b)) == b for every accepted b. |
The same tests re-encode; fuzzed and mutated inputs that decode must re-encode byte for byte; the decoder rejects non-zero unused bytes and non-canonical tags. |
| The decoder never panics and never allocates more than the input justifies. | Thousands of arbitrary, framed, and mutated inputs per run; claims of four billion entries in tiny files are refused before any allocation; a 100,000-deep constant chain is refused in linear time. |
| Decoding honours its budgets. | Property tests decode random modules under random limits and check every count of every accepted result. |
| A built function has no unresolved or out-of-range branch. | Label resolution is compared with a reference resolver on random programs; raw targets are range-checked too. |
| Parallel moves keep every value. | Random move sets, cycles included and naming the builder's own temporaries, are executed and compared with parallel assignment, and the number of moves is exactly one per move plus one per cycle. |
overflow = promote never lands in a statically typed register the builder can see. |
Property test over every declared register type, for dynamic and typed instructions. |
| Encoding and disassembly are deterministic. | Equal modules give equal bytes and identical listings, before and after a round trip. |
| Dynamic calls bind by one rule. | ParamList::bind is checked against an independently written reference binder on random parameter lists and argument lists, errors included; named arguments bind the same in any order; the dparam_ref queries agree with the binding; 200,000 spread names bind in linear-logarithmic time. |
| Every modifier byte means exactly one thing. | All 256 values of Policy, IntOp, and FloatConv are checked exhaustively (48, 192, and 16 valid); raise decodes exactly the catchable error kinds; every format 2 instruction round-trips as a word, through a module, and through the listing. |
Installation
[]
= "0.3"
Without the standard library:
[]
= { = "0.3", = false }
Quick start
Build a function, encode it, decode it, read it:
use ;
let mut m = new;
let mut f = m.function;
let = ;
let sum = f.reg;
f.emit;
f.ret;
m.add_function.unwrap;
let module = m.finish.unwrap;
let bytes = encode;
let back = decode.unwrap;
assert_eq!;
assert!;
Loops, labels, and policies
The overflow policy is part of the instruction: iadd.i64 raises ArithOverflow, iadd.i64.wrap wraps, on every tier.
use ;
let wrap = new.with_policy;
let mut m = new;
let mut f = m.function;
let n = f.param;
let = ;
f.emit;
f.emit;
f.emit;
let = ;
f.bind;
f.emit;
f.jmp_if_not;
f.emit;
f.emit;
f.emit; // every loop passes a safepoint: GC and fuel
f.jmp;
f.bind;
f.ret;
m.add_function.unwrap;
let text = disassemble;
assert!;
assert!;
assert!;
Dynamic code
dyn registers, property access by name, and hooks that let a language define its own slow path:
use ;
let mut m = new;
// PHP-style loose `+` on strings and arrays lives in the language runtime.
let sig = m.func_type;
let loose_add = m.import;
m.hook;
let total = m.string;
let mut f = m.function;
let = ;
let = ;
let name = f.name_ref;
f.emit;
f.emit;
f.emit;
f.ret;
m.add_function.unwrap;
let module = m.finish.unwrap;
assert_eq!;
PHP's calls, arrays, and references
A dynamic call to a function with a real signature, a nested write that separates only a shared array, and a reference into a map slot:
use ;
let d = Dyn;
let mut m = new;
let = ;
// function f(&$a, $k = 0, ...$rest): the signature ends with the presence mask.
let list = new;
let mut f = m.function;
f.set_params;
let = ;
f.emit; // $a is a reference
f.emit; // $a[$k][] = ...
f.emit; // $r = &$a[$k]
f.ret_void;
m.add_function.unwrap;
let module = m.finish.unwrap;
// f($x, extra: 1): `$k` takes its default, `extra` lands in `$rest`.
let bound = list.bind.unwrap;
assert_eq!;
assert_eq!;
Hostile input
use ;
// A header followed by a string section claiming four billion strings.
let mut bytes = b"LSB\0\x02\0\0\0\0\0\0\0".to_vec;
bytes.extend;
let mut limits = default;
limits.max_strings = 1000;
let err = decode_with.unwrap_err;
assert_eq!;
assert_eq!;
Examples
Runnable programs in examples/:
| Example | What it shows |
|---|---|
quickstart |
An iterative Fibonacci built with labels and a parallel move, encoded, decoded, and disassembled. cargo run --example quickstart |
inspect |
Decoding a file under explicit limits and reporting where a corrupt one goes wrong. cargo run --example inspect -- module.lsb |
php |
PHP semantics in format 2: a by-reference, defaulted, variadic signature; a run-time by-reference decision; a shaped call with a spread and a named argument; separation; a reference into a map slot; raise of NoMatch; and how one call binds. cargo run --example php |
Performance
Encoding writes eight bytes per instruction from a value already laid out as the word; decoding validates each word with one mask test and one jump-table dispatch, and reserves every list once, after proving the input can fill it. Section lengths are computed by running the same writer against a byte counter, so the output buffer is allocated exactly once.
Measured with the benchmarks in benches/ on a module of 1,000 functions × 1,000 instructions (a realistic mix: constants, typed and dynamic arithmetic, a property read, a compare and branch, a call, a safepoint), x86_64, Rust stable, release profile:
| Benchmark | What it measures | Windows |
|---|---|---|
1m_insts/encode |
Encode the module (8.0 MB). | ~2.4 ms · ~419 M inst/s · ~3.2 GiB/s |
1m_insts/decode |
Decode it, with every check (two measurements in one run). | ~4.1–4.8 ms · ~210–245 M inst/s · ~1.6–1.9 GiB/s |
inst/from_bytes_1m |
Decode one million words alone, output preallocated. | ~2.2 ms · ~457 M inst/s |
1m_insts/build |
Build the module with the builder, labels resolved, branch targets and promote checked. |
~3.8–4.5 ms · ~220–260 M inst/s |
100k_insts/disassemble |
Disassemble 100,000 instructions to text. | ~12.3 ms · ~8.1 M inst/s |
bind/php_100k_calls |
Bind 100,000 dynamic calls to f($a, $b = 1, $c = 2, ...$rest) with ParamList::bind, four call shapes in turn (positional, named, extras into the rest map, all named). |
~6.7–7.3 ms · ~67–73 ns per call |
Decoding costs about twice from_bytes alone: the difference is allocating and first touching the 8 MB of decoded code. Ranges are across runs on a machine shared with other builds. The builder's overflow = promote check, fused into its branch-target pass, costs about 0.1–0.5 ms per million instructions (≈3–12%) in interleaved measurements. These are library-only numbers; nothing here measures a VM.
0.3.0 against 0.2.0, both built and run back to back on the same (loaded) machine: encoding and building are unchanged within the run-to-run spread; decoding measured faster in 0.3.0 (≈2.3–2.8 ms against ≈4.2–4.4 ms for the million-instruction module, a difference not isolated, so not claimed as a gain); disassembly measured ≈7% slower (≈10.6–10.9 ms against ≈9.9–10.2 ms per 100,000 instructions), not isolated either. The binder allocates its result (one slot per parameter, one list per rest parameter); a VM that binds on a hot path uses its own fast path for all-positional exact calls and checks the rest against ParamList::bind.
Criterion writes per-benchmark reports to target/criterion/. Numbers vary by CPU; use the trend across runs, not a single absolute.
Design notes
- A register machine whose decoded form is its executed form. The
Instenum is eight bytes, the same as its encoding, so there is no second representation to keep in sync and no parse step between loading and running. - Typed registers,
dynincluded. Declared register types make GC roots exact and let the verifier check every operand in one linear pass. Dynamic languages declaredynregisters and use thed*instructions; static languages use unboxed typed registers. Mixed code converts explicitly. - Constants are format values. The pool holds exact
i64,u64, IEEE bit patterns, chars, UTF-8 and byte strings, and arrays and maps of earlier constants; the runtime value layout is the VM's business at load time. That is why the crate does not depend onvalue-lang, whosei32integers and process-local symbols cannot represent or serialize these. - Fixed-width, canonical encoding. No variable-length integers: every value has one encoding, decoding is branch-light, and a decoded file re-encodes byte for byte.
- Structure here, meaning in the verifier. The decoder checks the format; whether an index is in range or a register is used at its type is the verifier's (0.5). Every accessor that follows an index returns
Option, and the disassembler prints bad references as<invalid>. - No recursion anywhere input reaches. Aggregate constants refer only to earlier constants, so their depth is computed in one forward pass; nothing else in the format nests.
Testing
The property tests in tests/properties.rs generate instructions from the crate's own opcode metadata (so every opcode and modifier is covered without a hand-kept list), build arbitrary modules (parameter lists and call shapes included), and check the round trip, canonicity, determinism, decoder robustness against arbitrary, framed, and mutated bytes, budgets, label resolution against a reference resolver, and parallel moves against parallel assignment. tests/codec.rs hand-assembles inputs for every decode error, independently of the encoder. tests/disasm.rs pins the listing format with a golden file. tests/binding.rs checks the dynamic-call binding rule against an independent reference, and tests/format2.rs every instruction, rename, and modifier change of format version 2. Every rust example in this README and in docs/API.md is compiled and run as a doctest.
Cross-platform support
- Linux (x86_64, aarch64)
- macOS (x86_64, Apple Silicon)
- Windows (x86_64)
The format is little-endian by definition and the crate uses no operating-system facilities, so the same module encodes to the same bytes on every platform.
Contributing
See REPS.md for the engineering standards every change is held to, dev/DIRECTIVES.md for the definition of done, and dev/ROADMAP.md for what comes next. Before a PR: cargo fmt --all, cargo clippy --all-targets --all-features -- -D warnings, and cargo test --all-features must be clean.