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/// String interning for attribute names and identifiers.
63pub mod intern;
64/// NaN-boxed value representation for the VM stack.
65pub mod nanbox;
66/// Bytecode instruction set.
67pub mod opcode;
68/// VM-specific value representation.
69pub mod value;
70/// Bytecode interpreter / execution engine.
71pub mod vm;
72
73// Re-exports for ergonomic use.
74pub use bridge::{BuiltinBridgeFn, BuiltinBridgeGuard, call_builtin_bridge, set_builtin_bridge};
75pub use builtins::BuiltinRegistry;
76pub use chunk::Chunk;
77pub use compiler::Compiler;
78pub use error::{CompileError, VMError};
79pub use intern::{Interner, Symbol};
80pub use opcode::OpCode;
81pub use value::{StringKeyedValue, VMBuiltin, VMThunk, VMValue};
82pub use vm::{FlakeResolverGuard, set_flake_resolver, vm_fallback_count, VM};
83
84use std::cell::RefCell;
85use std::collections::HashMap;
86use std::collections::hash_map::DefaultHasher;
87use std::hash::{Hash, Hasher};
88use std::rc::Rc;
89
90/// A cached compilation result: the chunk (shared via Rc) and a cloned interner.
91struct CachedCompile {
92 chunk: Rc<Chunk>,
93 interner: Interner,
94}
95
96thread_local! {
97 /// Per-thread compilation cache keyed by expression string hash.
98 ///
99 /// Benchmarks show that compilation takes 85-92% of total eval time,
100 /// so caching compiled chunks provides a dramatic speedup on repeated
101 /// evaluations of the same expression (the common case in benchmarks
102 /// and in real evaluation loops like `builtins.map` over many items).
103 static COMPILE_CACHE: RefCell<HashMap<u64, CachedCompile>> =
104 RefCell::new(HashMap::new());
105}
106
107/// Hash an expression string for the compile cache.
108fn hash_expr(input: &str) -> u64 {
109 let mut hasher = DefaultHasher::new();
110 input.hash(&mut hasher);
111 hasher.finish()
112}
113
114/// Result of bytecode evaluation: the value plus the interner needed
115/// to resolve symbol-keyed attrsets.
116pub struct EvalResult {
117 /// The evaluated value (may contain `Symbol`-keyed attrsets).
118 pub value: VMValue,
119 /// The interner used during compilation and execution.
120 pub interner: Interner,
121}
122
123impl EvalResult {
124 /// Convert the result to a fully string-keyed value.
125 #[must_use]
126 pub fn to_string_keyed(&self) -> StringKeyedValue {
127 self.value.to_string_keyed(&self.interner)
128 }
129}
130
131/// Compile and execute a Nix expression string via the bytecode VM.
132///
133/// Returns the raw [`VMValue`] (which may contain `Symbol`-keyed attrsets).
134/// For a fully resolved result, use [`eval_full`] instead.
135pub fn eval(input: &str) -> Result<VMValue, EvalError> {
136 let result = eval_full(input)?;
137 Ok(result.value)
138}
139
140/// Compile and execute a Nix expression, returning the value and interner.
141///
142/// Use this when you need to inspect attrset keys or display results.
143///
144/// Uses a thread-local compilation cache: if the same expression string
145/// has been compiled before, the cached bytecode is reused (avoiding the
146/// rnix parse + compile overhead which benchmarks show is 85-92% of total
147/// eval time).
148pub fn eval_full(input: &str) -> Result<EvalResult, EvalError> {
149 let key = hash_expr(input);
150
151 // Try the cache first.
152 let cached = COMPILE_CACHE.with(|cache| {
153 cache.borrow().get(&key).map(|entry| {
154 (entry.chunk.clone(), entry.interner.clone())
155 })
156 });
157
158 let (chunk, mut interner) = if let Some((rc_chunk, interner)) = cached {
159 // Cache hit: use the Rc<Chunk> directly. The VM needs an owned Chunk,
160 // so we clone from the Rc (the Rc makes this cheap for re-use).
161 ((*rc_chunk).clone(), interner)
162 } else {
163 // Cache miss: compile, cache, and return.
164 let (chunk, interner) = Compiler::compile(input).map_err(EvalError::Compile)?;
165 let rc_chunk = Rc::new(chunk.clone());
166 COMPILE_CACHE.with(|cache| {
167 cache.borrow_mut().insert(key, CachedCompile {
168 chunk: rc_chunk,
169 interner: interner.clone(),
170 });
171 });
172 (chunk, interner)
173 };
174
175 let value = VM::execute(chunk, &mut interner).map_err(EvalError::Runtime)?;
176 Ok(EvalResult { value, interner })
177}
178
179/// Clear the thread-local compilation cache.
180///
181/// Useful in tests or when memory pressure is a concern.
182pub fn clear_compile_cache() {
183 COMPILE_CACHE.with(|cache| cache.borrow_mut().clear());
184}
185
186/// Unified error type wrapping both compile and runtime errors.
187#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
188pub enum EvalError {
189 /// A compilation error.
190 #[error("compile error: {0}")]
191 Compile(CompileError),
192 /// A runtime error.
193 #[error("runtime error: {0}")]
194 Runtime(VMError),
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn eval_simple_addition() {
203 assert_eq!(eval("1 + 2").unwrap(), VMValue::Int(3));
204 }
205
206 #[test]
207 fn eval_null_literal() {
208 assert_eq!(eval("null").unwrap(), VMValue::Null);
209 }
210
211 #[test]
212 fn eval_bool_logic() {
213 assert_eq!(eval("true && false").unwrap(), VMValue::Bool(false));
214 assert_eq!(eval("true || false").unwrap(), VMValue::Bool(true));
215 }
216
217 #[test]
218 fn eval_let_binding() {
219 assert_eq!(eval("let x = 10; in x").unwrap(), VMValue::Int(10));
220 }
221
222 #[test]
223 fn eval_lambda_call() {
224 assert_eq!(eval("(x: x + 1) 5").unwrap(), VMValue::Int(6));
225 }
226
227 #[test]
228 fn eval_compile_error() {
229 let result = eval("let in");
230 assert!(result.is_err());
231 assert!(matches!(result, Err(EvalError::Compile(_))));
232 }
233
234 #[test]
235 fn eval_runtime_error_div_zero() {
236 let result = eval("1 / 0");
237 assert!(result.is_err());
238 assert!(matches!(
239 result,
240 Err(EvalError::Runtime(VMError::DivisionByZero))
241 ));
242 }
243
244 #[test]
245 fn eval_lazy_let_thunk() {
246 // Non-trivial let binding should be lazily evaluated.
247 assert_eq!(eval("let x = 2 * 3; in x").unwrap(), VMValue::Int(6));
248 }
249
250 #[test]
251 fn eval_lazy_let_cross_ref() {
252 // Let-binding thunks can reference other bindings from the same block.
253 clear_compile_cache();
254 assert_eq!(
255 eval("let f = x: x + 1; g = f 10; in g").unwrap(),
256 VMValue::Int(11)
257 );
258 }
259
260 #[test]
261 fn eval_fixpoint_via_intermediate() {
262 // The fixpoint pattern works when accessed through an intermediate variable.
263 clear_compile_cache();
264 let result = eval(
265 "let fix = f: let x = f x; in x; r = fix (self: { a = 1; }); s = r.a; in s",
266 );
267 assert_eq!(result.unwrap(), VMValue::Int(1));
268 }
269}