Skip to main content

logicaffeine_compile/vm/
mod.rs

1//! Register bytecode VM.
2//!
3//! A fast, portable interpreter that runs the same `RuntimeValue` semantics as
4//! the tree-walker. It is the browser/WASM execution engine and the substrate
5//! the native copy-and-patch JIT tiers up from. Built incrementally, RED-first,
6//! differential-tested against the tree-walker.
7
8pub mod compiler;
9// Off-thread native compilation (HOTSWAP §6). Native-only: it needs std::thread and
10// the forge backend, neither of which exists on wasm (which never installs a tier).
11#[cfg(not(target_arch = "wasm32"))]
12mod bg_compile;
13// AOT-native tier loader (HOTSWAP §Axis-3): dlopen a rustc-built cdylib. Native-only.
14#[cfg(not(target_arch = "wasm32"))]
15pub mod aot_tier;
16// Background AOT-native compilation (HOTSWAP §Axis-3 / P18): build+load off-thread.
17#[cfg(not(target_arch = "wasm32"))]
18pub mod bg_aot;
19// Relocatable per-function bytecode units (HOTSWAP §7) — the producer behind the
20// Axis-1 warm side-table and the OPFS tier cache. Pure data; available on all targets.
21pub mod fn_bytecode;
22// LOGOS_TIER_TRACE observability (HOTSWAP §P13): one stderr line per tier hot-swap.
23pub mod tier_trace;
24// LOGOS_PERF_MAP: name the JIT's machine code in /tmp/perf-<pid>.map. Native-only (no JIT on wasm).
25#[cfg(not(target_arch = "wasm32"))]
26pub mod perf_map;
27// Tier cache (HOTSWAP §P12): persist a compiled FnBytecode keyed by source+config+tier.
28pub mod binisa;
29/// Bytecode disassembler — readable text for the Studio debug drawer and any
30/// future `largo --disasm`. Pure, headless, no VM state.
31pub mod disasm;
32/// Which integers of a region of bytecode are held exact: one decision for every backend that lowers the bytecode.
33pub(crate) mod exactness;
34/// Which registers hold a value of the exact extension, for every backend that lowers the bytecode onto the
35/// linked value runtime.
36pub(crate) mod tower;
37/// The variables of a region of bytecode: its definitions, joined where one read is reached by several.
38pub(crate) mod variables;
39/// The machine form a number variable is held in when its definitions make numbers of different forms.
40pub(crate) mod numbers;
41#[cfg(test)]
42#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/fuzz.rs"]
43mod fuzz;
44mod instruction;
45pub mod isa;
46pub mod journal;
47mod machine;
48/// The narrow (8-byte) NaN-boxed register-file
49/// value (see the module docs). Under `feature = "narrow-value"` it backs
50/// [`value::Value`] and the VM register file; the default build keeps the fat
51/// `RuntimeValue` path, so the scalar accessors/arith here are exercised only by
52/// the in-module tests then. `allow(dead_code)` keeps the default build quiet
53/// about the methods only the narrow path calls.
54#[cfg_attr(not(feature = "narrow-value"), allow(dead_code))]
55mod nanbox;
56mod native_tier;
57pub mod pebble;
58pub mod peephole;
59pub mod reach;
60/// Reversibility classification of the ISA — the static substrate for running the whole language
61/// backward (`forward ; reverse ≡ identity`), the software prerequisite for the adiabatic /
62/// sub-Landauer chip. Locked by `tests/reverse_op_lock.rs`.
63pub mod reverse;
64pub mod session;
65pub mod tier_cache;
66mod value;
67
68/// WebAssembly code generation from VM bytecode: the shared byte emitter (`wasm::encode` +
69/// `wasm::func`, always built) plus the WS6 browser WASM-JIT tier (`wasm::region_jit`, behind
70/// the `wasm-jit` feature). The direct AOT backend (`largo build --emit wasm`) consumes the
71/// same emitter.
72/// The "field name" a `Some` arm's binding carries, in place of a real field.
73///
74/// LOGOS encodes Options transparently — `some x` IS x — so a `Some` arm binds the WHOLE matched
75/// value rather than one of its fields. A struct arm and a `Some` arm reach `BindArm` looking
76/// identical otherwise, and guessing between them (by binding index, say) silently changes what a
77/// real struct arm does. A marker no identifier can spell tells them apart exactly.
78pub const SOME_BINDING_MARKER: &str = "\u{0}some";
79
80pub mod wasm;
81
82/// Back-compat facade: the WS6 browser WASM-JIT tier moved into the shared `wasm` codegen
83/// submodule — `wasm::func` for the byte emitter, `wasm::region_jit` for the tier + host.
84/// `machine.rs` (`super::wasm_jit::WasmTier`) and the `wasm_jit_*` differential/browser test
85/// suites still reach it here, unchanged.
86#[cfg(feature = "wasm-jit")]
87pub mod wasm_jit {
88    pub use super::wasm::func::{compile_function_to_wasm, compile_region_to_wasm};
89    #[cfg(target_arch = "wasm32")]
90    pub use super::wasm::region_jit::run_on_host;
91    pub use super::wasm::region_jit::WasmTier;
92}
93
94pub use compiler::Compiler;
95pub use disasm::{disassemble, format_constant, op_io, DisasmLine, OpIo};
96pub use instruction::{
97    BoundaryType, ChanElem, CompiledProgram, Constant, EnumTypeDef, EnumVariantDef, ObsSiteDesc,
98    ObsSiteKind, Op, Reg, StructTypeDef, NO_SITE,
99};
100pub use journal::{HistoryTape, JournalEntry};
101pub use machine::Vm;
102pub(crate) use machine::{DebugView, DebugVmState, HeapObjView};
103pub(crate) use machine::{VmBlock, VmStep};
104pub use reverse::{reversibility, EffectKind, InverseSpec, JournalKind, RevClass};
105// The reversible cooperative scheduler + the compiled-function shape — the in-crate soft-core differential
106// (`codegen_sva/rtl.rs`) hand-builds bytecode for the scheduler-only ops (`ChanClose`/`TaskAwait`) that no
107// source emits, and drives them through this scheduler for its VM oracle. `CompiledFunction` is also public
108// so the fabric coverage lock can hand-build a SPAWN witness (a producer child) the same way.
109pub use instruction::CompiledFunction;
110pub(crate) use machine::RevCoop;
111pub use native_tier::{
112    install_native_tier, installed_native_tier, ArrayPin, CalleeSig, FnTable, HoistGuard,
113    NativeCtx, NativeFn, NativeFrame, NativeOutcome, NativeRet, NativeTier, NativeWriteback,
114    ObservedKind, ParamKind, PinElem, RegBox, RegionFn, RegionOutcome, RegionReturn,
115    RegionReturnKind, SlotKind, NATIVE_TIER_THRESHOLD, REGION_TIER_THRESHOLD,
116};
117pub use value::Value;
118
119use crate::ast::stmt::Stmt;
120use crate::intern::Interner;
121
122/// Hard cap on registers a single frame may claim. Generous for real programs;
123/// prevents a pathological frame from claiming the whole register file.
124pub const MAX_REGISTERS_PER_FRAME: usize = 16_384;
125/// Hard cap on the total register file across all live frames. Deep recursion
126/// hits this and errors instead of consuming unbounded memory.
127pub const MAX_REGISTER_FILE: usize = 1 << 20;
128/// Maximum expression nesting depth the compiler will descend before erroring
129/// (guards the compiler's own recursion against adversarial inputs). Debug
130/// builds allocate every match arm's locals in `compile_expr_into_inner`'s
131/// frame — measured in the tens of KiB per nesting level as the compiler
132/// grows — so 64 keeps the worst case well inside a default 2 MiB
133/// test-thread stack while still exceeding any realistic expression depth.
134/// (An explicit-work-stack compiler would remove the native-stack coupling
135/// entirely; tracked as future work.)
136pub const MAX_EXPR_DEPTH: usize = 64;
137
138/// Shannon entropy of a two-outcome branch profile, in bits (EXODIA 3.3).
139/// 0.0 = perfectly predictable (the hardware branch predictor wins; Tier-1
140/// code is fine), 1.0 = a coin flip (Tier-2 should restructure the branch
141/// away). Zero samples are zero entropy.
142pub fn branch_entropy(taken: u64, not_taken: u64) -> f64 {
143    let total = taken + not_taken;
144    if total == 0 || taken == 0 || not_taken == 0 {
145        return 0.0;
146    }
147    let p = taken as f64 / total as f64;
148    -(p * p.log2() + (1.0 - p) * (1.0 - p).log2())
149}
150
151/// Compile a statement block to bytecode and run it, returning captured output.
152pub fn compile_and_run(stmts: &[Stmt], interner: &Interner) -> Result<String, String> {
153    let program = Compiler::compile(stmts, interner)?;
154    let mut vm = Vm::new(&program);
155    if let Some(tier) = installed_native_tier() {
156        vm = vm.with_native_tier(tier);
157    }
158    vm.run()?;
159    Ok(vm.output().to_string())
160}
161
162/// Compile and run, preserving partial output alongside any error — the shape
163/// the differential harness compares against the tree-walker (which also keeps
164/// the lines emitted before a runtime error). `types` carries the discovery
165/// pass's struct definitions (for default-fill on construction).
166pub fn run_to_outcome(
167    stmts: &[Stmt],
168    interner: &Interner,
169    types: Option<&crate::analysis::TypeRegistry>,
170    policies: Option<&crate::analysis::PolicyRegistry>,
171) -> (String, Option<String>) {
172    let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
173    let program = match Compiler::compile_with_oracle(stmts, interner, types, Some(oracle)) {
174        Ok(p) => p,
175        Err(e) => return (String::new(), Some(e)),
176    };
177    let mut vm = Vm::new(&program);
178    if let Some(tier) = installed_native_tier() {
179        vm = vm.with_native_tier(tier);
180    }
181    if let Some(registry) = policies {
182        vm = vm.with_policy_ctx(registry, interner);
183    }
184    match vm.run() {
185        Ok(()) => (vm.output().to_string(), None),
186        Err(e) => (vm.output().to_string(), Some(e)),
187    }
188}
189
190/// [`run_to_outcome`], plus the failure-site id in force at the point an `Err` propagated from
191/// (Wave 3: "runtime failures carry a location") — `None` on success, or when the failure happened
192/// outside any `Stmt::Site` marker (`## Main`/`## Test`'s own top-level statements carry none).
193/// `compile.rs::locate_runtime_failure` is the one place this id becomes a rendered `file:line:col`.
194pub fn run_to_outcome_located(
195    stmts: &[Stmt],
196    interner: &Interner,
197    types: Option<&crate::analysis::TypeRegistry>,
198    policies: Option<&crate::analysis::PolicyRegistry>,
199) -> (String, Option<String>, Option<u32>) {
200    let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
201    let program = match Compiler::compile_with_oracle(stmts, interner, types, Some(oracle)) {
202        Ok(p) => p,
203        Err(e) => return (String::new(), Some(e), None),
204    };
205    let mut vm = Vm::new(&program);
206    if let Some(tier) = installed_native_tier() {
207        vm = vm.with_native_tier(tier);
208    }
209    if let Some(registry) = policies {
210        vm = vm.with_policy_ctx(registry, interner);
211    }
212    match vm.run() {
213        Ok(()) => (vm.output().to_string(), None, None),
214        Err(e) => {
215            let site = vm.failing_site();
216            (vm.output().to_string(), Some(e), site)
217        }
218    }
219}
220
221/// RUN-ONLY wall-time — the MIN nanoseconds over `iters` executions of the CHIP bytecode on the register
222/// VM, compiled ONCE (so parse / compile / stdlib-prelude load are excluded). This is the fair host
223/// counterpart to the FPGA soft-core's on-chip cycle counter, which also measures execution only — and it
224/// runs the SAME `compile_for_chip` bytecode the silicon executes, so VM-vs-FPGA is one instruction stream,
225/// host CPU vs custom silicon. `None` if the program does not compile to the chip subset.
226pub fn run_nanos(
227    stmts: &[Stmt],
228    interner: &Interner,
229    types: Option<&crate::analysis::TypeRegistry>,
230    iters: usize,
231) -> Option<u128> {
232    let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
233    let program = Compiler::compile_for_chip(stmts, interner, types, Some(oracle)).ok()?;
234    {
235        let mut vm = Vm::new(&program);
236        let _ = vm.run(); // warm up
237    }
238    let mut best = u128::MAX;
239    for _ in 0..iters {
240        let mut vm = Vm::new(&program);
241        let t = std::time::Instant::now();
242        let _ = vm.run();
243        best = best.min(t.elapsed().as_nanos());
244    }
245    Some(best)
246}
247
248/// [`run_to_outcome`] in the OBSERVED profile (Wave 13): `Note`/`Warn`/`Record`/
249/// `During` lower to `Op::Obs`, so the VM emits the SAME observation event stream
250/// the tree-walker does (into the `observe` channel — separate from program
251/// output). The dev/test differential entry; the compiled/release tiers keep the
252/// elided profile. Program output is byte-identical to [`run_to_outcome`].
253pub fn run_to_outcome_observed(
254    stmts: &[Stmt],
255    interner: &Interner,
256    types: Option<&crate::analysis::TypeRegistry>,
257    policies: Option<&crate::analysis::PolicyRegistry>,
258) -> (String, Option<String>) {
259    let program = match Compiler::compile_observed(stmts, interner, types) {
260        Ok(p) => p,
261        Err(e) => return (String::new(), Some(e)),
262    };
263    let mut vm = Vm::new(&program);
264    if let Some(registry) = policies {
265        vm = vm.with_policy_ctx(registry, interner);
266    }
267    match vm.run() {
268        Ok(()) => (vm.output().to_string(), None),
269        Err(e) => (vm.output().to_string(), Some(e)),
270    }
271}
272
273/// Run a `## Test` body's COMPUTATION on the bytecode VM for the `--tiers all`
274/// differential (Wave 13): the test-only statements (`Expect`/`ForAll`/…) compile
275/// as no-ops, so the VM executes exactly the surrounding computation.
276///
277/// STRICT shape: `Err(reason)` means the VM never ran the program (the compiler
278/// refused it — a typed refusal, distinguishable from a runtime failure);
279/// `Ok((output, error))` means the VM genuinely executed, with its output as
280/// newline-joined lines (the interpreter's convention, so the tier comparison
281/// is byte-for-byte) and any runtime error alongside the partial output.
282pub fn run_tiers_strict(
283    stmts: &[Stmt],
284    interner: &Interner,
285    types: Option<&crate::analysis::TypeRegistry>,
286    policies: Option<&crate::analysis::PolicyRegistry>,
287) -> Result<(String, Option<String>), String> {
288    let program = Compiler::compile_tiers(stmts, interner, types)?;
289    let mut vm = Vm::new(&program);
290    if let Some(registry) = policies {
291        vm = vm.with_policy_ctx(registry, interner);
292    }
293    let error = vm.run().err();
294    Ok((vm.into_lines().join("\n"), error))
295}
296
297/// Drive a prepared VM to completion, honoring the thread's armed fuel (`largo
298/// run --max-steps`, the MCP `step_budget`). A budgeted run stays on the
299/// resumable STEPPED loop and stops at the deterministic op where the shared
300/// cell runs dry; an unbudgeted run is the untouched hot loop. The ONE place
301/// this dance lives — the live sync path and the strict engine runs share it.
302pub(crate) fn drive_vm(vm: &mut Vm) -> Option<String> {
303    match crate::interpreter::active_fuel() {
304        Some(fuel) => {
305            logicaffeine_base::money::clear_ambient_rates();
306            let before = vm.steps_run();
307            let step = vm.run_steps(fuel.remaining.get());
308            let spent = vm.steps_run() - before;
309            fuel.remaining.set(fuel.remaining.get().saturating_sub(spent));
310            match step {
311                Ok(VmStep::Paused) => {
312                    fuel.remaining.set(0);
313                    fuel.exhausted.set(true);
314                    Some(fuel.exhaust_message())
315                }
316                Ok(VmStep::Blocked) => {
317                    Some("vm: concurrency op requires the scheduler driver".to_string())
318                }
319                Ok(VmStep::Done(_)) => None,
320                Err(e) => Some(e),
321            }
322        }
323        None => vm.run().err(),
324    }
325}
326
327/// [`run_to_outcome`] with the program argument vector for the `args()`
328/// system native (full argv; index 0 is the program name) and an optional
329/// caller-supplied native tier. A `Some(tier)` overrides the process-wide
330/// installed tier — differential suites use a private tier per program so
331/// its compile counters are isolated from every other test in the binary.
332pub fn run_to_outcome_with_args(
333    stmts: &[Stmt],
334    interner: &Interner,
335    types: Option<&crate::analysis::TypeRegistry>,
336    policies: Option<&crate::analysis::PolicyRegistry>,
337    program_args: &[String],
338    tier: Option<&dyn NativeTier>,
339) -> (String, Option<String>) {
340    let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
341    let program = match Compiler::compile_with_oracle(stmts, interner, types, Some(oracle)) {
342        Ok(p) => p,
343        Err(e) => return (String::new(), Some(e)),
344    };
345    let mut vm = Vm::new(&program).with_program_args(program_args.to_vec());
346    let chosen: Option<&dyn NativeTier> = match tier {
347        Some(t) => Some(t),
348        None => installed_native_tier().map(|t| t as &dyn NativeTier),
349    };
350    if let Some(t) = chosen {
351        vm = vm.with_native_tier(t);
352    }
353    if let Some(registry) = policies {
354        vm = vm.with_policy_ctx(registry, interner);
355    }
356    match vm.run() {
357        Ok(()) => (vm.output().to_string(), None),
358        Err(e) => (vm.output().to_string(), Some(e)),
359    }
360}
361
362/// [`run_to_outcome_with_args`] with BACKGROUND native compilation (HOTSWAP §6): hot
363/// functions compile on a worker thread while the interpreter keeps running bytecode,
364/// then their chains are drained + published. Requires a process-installed tier (the
365/// worker needs a `&'static` backend); with none installed it runs pure bytecode.
366/// Drains outstanding compiles before returning so the native tier engages
367/// deterministically for the differential gates.
368#[cfg(not(target_arch = "wasm32"))]
369pub fn run_to_outcome_bg(
370    stmts: &[Stmt],
371    interner: &Interner,
372    types: Option<&crate::analysis::TypeRegistry>,
373    policies: Option<&crate::analysis::PolicyRegistry>,
374    program_args: &[String],
375) -> (String, Option<String>) {
376    let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
377    let program = match Compiler::compile_with_oracle(stmts, interner, types, Some(oracle)) {
378        Ok(p) => p,
379        Err(e) => return (String::new(), Some(e)),
380    };
381    let mut vm = Vm::new(&program).with_program_args(program_args.to_vec());
382    if let Some(t) = installed_native_tier() {
383        vm = vm.with_bg_native_tier(t);
384    }
385    if let Some(registry) = policies {
386        vm = vm.with_policy_ctx(registry, interner);
387    }
388    let result = match vm.run() {
389        Ok(()) => (vm.output().to_string(), None),
390        Err(e) => (vm.output().to_string(), Some(e)),
391    };
392    vm.drain_pending_compiles();
393    result
394}
395
396#[cfg(test)]
397#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/tests.rs"]
398mod tests;