Skip to main content

sui_bytecode/
lib.rs

1//! Bytecode compiler and VM for the Nix evaluator.
2//!
3//! This crate provides an alternative evaluation backend for sui-eval.
4//! Instead of tree-walking the rnix AST, expressions are compiled to
5//! a stack-based bytecode and executed by a virtual machine.
6//!
7//! # Architecture
8//!
9//! ```text
10//! Nix source --> rnix parser (CST) --> Compiler --> Chunk (bytecode)
11//!                                                        |
12//!                                                        v
13//!                                                  VM --> VMValue
14//! ```
15//!
16//! # Phase 1 + 2 Coverage
17//!
18//! Currently supports:
19//! - Literals: int, float, bool, null, string, path
20//! - Arithmetic: `+`, `-`, `*`, `/`, unary `-`
21//! - Comparison: `==`, `!=`, `<`, `>`, `<=`, `>=`
22//! - Logical: `!`, `&&`, `||`, `->` (with short-circuit)
23//! - Strings: literals, interpolation
24//! - Variables: `let`/`in` with local binding
25//! - Functions: lambda, apply, pattern destructuring with defaults
26//! - Lists: construction, `++` concatenation
27//! - Attribute sets: construction, `.` selection, `?` has-attr,
28//!   `//` update, `or` default
29//! - Control flow: `if`/`then`/`else`, `assert`
30//! - Upvalue capture: Lua 5.x-style closures over non-local variables
31//! - `with` scopes: dynamic variable lookup via with-scope stack
32//! - `rec` attribute sets: self-referencing bindings
33//! - `inherit` and `inherit (source)`: in both `let` and attrset
34//! - Dotted attribute paths: `{ a.b = 1; a.c = 2; }` merging
35//! - Dynamic attribute keys: `{ ${expr} = value; }`
36//! - Builtins: 50+ functions (type checks, list ops, attrset ops,
37//!   string ops, arithmetic, control flow, conversion)
38//! - `import` with file caching
39//! - Thunks / lazy evaluation (MakeThunk/Force opcodes, blackhole detection)
40//! - Lazy attrset values (non-trivial values wrapped in thunks)
41//! - `derivation` / `derivationStrict` (native implementation via sui-compat)
42//! - `builtins.getFlake` (path-based flake references)
43//! - `builtins.scopedImport` (with-wrapping approach)
44//! - VM-level dispatch for interner-dependent builtins (attrNames,
45//!   listToAttrs, removeAttrs, hasAttr, getAttr, catAttrs)
46//! - Deep-force at VM boundary (recursively forces thunks in attrsets/lists)
47//!
48//! # Not Yet Implemented
49//!
50//! - String interpolation contexts
51
52/// Builtin bridge: tree-walker builtins callable from the VM.
53pub mod bridge;
54/// Built-in function registry for the VM.
55pub mod builtins;
56/// Bytecode container (instructions + constant pool).
57pub mod chunk;
58/// AST-to-bytecode compiler.
59pub mod compiler;
60/// Error types for compiler and VM.
61pub mod error;
62
63/// Fallback accounting + the `SUI_VM_STRICT` latch — see the module docs for
64/// why the per-builtin layer is counted but never fatal.
65pub mod fallback;
66/// String interning for attribute names and identifiers.
67pub mod intern;
68/// NaN-boxed value representation for the VM stack.
69pub mod nanbox;
70/// Bytecode instruction set.
71pub mod opcode;
72/// VM-specific value representation.
73pub mod value;
74/// Bytecode interpreter / execution engine.
75pub mod vm;
76
77// Re-exports for ergonomic use.
78pub use bridge::{
79    BuiltinBridgeFn, BuiltinBridgeGuard, PathMaterializerFn, PathMaterializerGuard,
80    call_builtin_bridge, materialize, materialize_path, set_builtin_bridge,
81    set_path_materializer,
82};
83pub use builtins::BuiltinRegistry;
84pub use chunk::Chunk;
85pub use compiler::Compiler;
86pub use error::{CompileError, VMError};
87pub use intern::{Interner, Symbol};
88pub use opcode::OpCode;
89pub use value::{StringKeyedValue, VMBuiltin, VMThunk, VMValue};
90pub use vm::{FlakeResolverGuard, set_flake_resolver, vm_fallback_count, VM};
91
92use std::cell::RefCell;
93use std::collections::HashMap;
94use std::collections::hash_map::DefaultHasher;
95use std::hash::{Hash, Hasher};
96use std::rc::Rc;
97
98/// A cached compilation result: the chunk (shared via Rc) and a cloned interner.
99struct CachedCompile {
100    chunk: Rc<Chunk>,
101    interner: Interner,
102}
103
104thread_local! {
105    /// Per-thread compilation cache keyed by expression string hash.
106    ///
107    /// Benchmarks show that compilation takes 85-92% of total eval time,
108    /// so caching compiled chunks provides a dramatic speedup on repeated
109    /// evaluations of the same expression (the common case in benchmarks
110    /// and in real evaluation loops like `builtins.map` over many items).
111    static COMPILE_CACHE: RefCell<HashMap<u64, CachedCompile>> =
112        RefCell::new(HashMap::new());
113}
114
115/// Hash an expression string for the compile cache.
116fn hash_expr(input: &str) -> u64 {
117    let mut hasher = DefaultHasher::new();
118    input.hash(&mut hasher);
119    hasher.finish()
120}
121
122/// Result of bytecode evaluation: the value plus the interner needed
123/// to resolve symbol-keyed attrsets.
124pub struct EvalResult {
125    /// The evaluated value (may contain `Symbol`-keyed attrsets).
126    pub value: VMValue,
127    /// The interner used during compilation and execution.
128    pub interner: Interner,
129}
130
131impl EvalResult {
132    /// Convert the result to a fully string-keyed value.
133    #[must_use]
134    pub fn to_string_keyed(&self) -> StringKeyedValue {
135        self.value.to_string_keyed(&self.interner)
136    }
137}
138
139/// Compile and execute a Nix expression string via the bytecode VM.
140///
141/// Returns the raw [`VMValue`] (which may contain `Symbol`-keyed attrsets).
142/// For a fully resolved result, use [`eval_full`] instead.
143pub fn eval(input: &str) -> Result<VMValue, EvalError> {
144    let result = eval_full(input)?;
145    Ok(result.value)
146}
147
148/// Compile and execute a Nix expression, returning the value and interner.
149///
150/// Use this when you need to inspect attrset keys or display results.
151///
152/// Uses a thread-local compilation cache: if the same expression string
153/// has been compiled before, the cached bytecode is reused (avoiding the
154/// rnix parse + compile overhead which benchmarks show is 85-92% of total
155/// eval time).
156pub fn eval_full(input: &str) -> Result<EvalResult, EvalError> {
157    let key = hash_expr(input);
158
159    // Try the cache first.
160    let cached = COMPILE_CACHE.with(|cache| {
161        cache.borrow().get(&key).map(|entry| {
162            (entry.chunk.clone(), entry.interner.clone())
163        })
164    });
165
166    let (chunk, mut interner) = if let Some((rc_chunk, interner)) = cached {
167        // Cache hit: use the Rc<Chunk> directly. The VM needs an owned Chunk,
168        // so we clone from the Rc (the Rc makes this cheap for re-use).
169        ((*rc_chunk).clone(), interner)
170    } else {
171        // Cache miss: compile, cache, and return.
172        let (chunk, interner) = Compiler::compile(input).map_err(EvalError::Compile)?;
173        let rc_chunk = Rc::new(chunk.clone());
174        COMPILE_CACHE.with(|cache| {
175            cache.borrow_mut().insert(key, CachedCompile {
176                chunk: rc_chunk,
177                interner: interner.clone(),
178            });
179        });
180        (chunk, interner)
181    };
182
183    let value = VM::execute(chunk, &mut interner).map_err(EvalError::Runtime)?;
184    Ok(EvalResult { value, interner })
185}
186
187/// Clear the thread-local compilation cache.
188///
189/// Useful in tests or when memory pressure is a concern.
190pub fn clear_compile_cache() {
191    COMPILE_CACHE.with(|cache| cache.borrow_mut().clear());
192}
193
194/// Unified error type wrapping both compile and runtime errors.
195#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
196pub enum EvalError {
197    /// A compilation error.
198    #[error("compile error: {0}")]
199    Compile(CompileError),
200    /// A runtime error.
201    #[error("runtime error: {0}")]
202    Runtime(VMError),
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn eval_simple_addition() {
211        assert_eq!(eval("1 + 2").unwrap(), VMValue::Int(3));
212    }
213
214    #[test]
215    fn eval_null_literal() {
216        assert_eq!(eval("null").unwrap(), VMValue::Null);
217    }
218
219    #[test]
220    fn eval_bool_logic() {
221        assert_eq!(eval("true && false").unwrap(), VMValue::Bool(false));
222        assert_eq!(eval("true || false").unwrap(), VMValue::Bool(true));
223    }
224
225    #[test]
226    fn eval_let_binding() {
227        assert_eq!(eval("let x = 10; in x").unwrap(), VMValue::Int(10));
228    }
229
230    #[test]
231    fn eval_lambda_call() {
232        assert_eq!(eval("(x: x + 1) 5").unwrap(), VMValue::Int(6));
233    }
234
235    #[test]
236    fn eval_compile_error() {
237        let result = eval("let in");
238        assert!(result.is_err());
239        assert!(matches!(result, Err(EvalError::Compile(_))));
240    }
241
242    #[test]
243    fn eval_runtime_error_div_zero() {
244        let result = eval("1 / 0");
245        assert!(result.is_err());
246        assert!(matches!(
247            result,
248            Err(EvalError::Runtime(VMError::DivisionByZero))
249        ));
250    }
251
252    #[test]
253    fn eval_lazy_let_thunk() {
254        // Non-trivial let binding should be lazily evaluated.
255        assert_eq!(eval("let x = 2 * 3; in x").unwrap(), VMValue::Int(6));
256    }
257
258    #[test]
259    fn eval_lazy_let_cross_ref() {
260        // Let-binding thunks can reference other bindings from the same block.
261        clear_compile_cache();
262        assert_eq!(
263            eval("let f = x: x + 1; g = f 10; in g").unwrap(),
264            VMValue::Int(11)
265        );
266    }
267
268    #[test]
269    fn eval_fixpoint_via_intermediate() {
270        // The fixpoint pattern works when accessed through an intermediate variable.
271        clear_compile_cache();
272        let result = eval(
273            "let fix = f: let x = f x; in x; r = fix (self: { a = 1; }); s = r.a; in s",
274        );
275        assert_eq!(result.unwrap(), VMValue::Int(1));
276    }
277}