diff options
Diffstat (limited to 'tvix/eval/src')
-rw-r--r-- | tvix/eval/src/disassembler.rs | 37 | ||||
-rw-r--r-- | tvix/eval/src/lib.rs | 3 | ||||
-rw-r--r-- | tvix/eval/src/vm.rs | 14 |
3 files changed, 53 insertions, 1 deletions
diff --git a/tvix/eval/src/disassembler.rs b/tvix/eval/src/disassembler.rs new file mode 100644 index 000000000000..98a6dac9afc4 --- /dev/null +++ b/tvix/eval/src/disassembler.rs @@ -0,0 +1,37 @@ +//! Implements methods for disassembling and printing a representation +//! of compiled code, as well as tracing the runtime stack during +//! execution. +use std::io::{Stderr, Write}; +use tabwriter::TabWriter; + +use crate::opcode::OpCode; +use crate::value::Value; + +/// Helper struct to trace runtime values and automatically flush the +/// output after the value is dropped (i.e. in both success and +/// failure exits from the VM). +pub struct Tracer(TabWriter<Stderr>); + +impl Tracer { + pub fn new() -> Self { + let mut tw = TabWriter::new(std::io::stderr()); + write!(&mut tw, "=== runtime trace ===\n").ok(); + Tracer(tw) + } + + pub fn trace(&mut self, op: &OpCode, ip: usize, stack: &[Value]) { + write!(&mut self.0, "{:04} {:?}\t[ ", ip, op).ok(); + + for val in stack { + write!(&mut self.0, "{} ", val).ok(); + } + + write!(&mut self.0, "]\n").ok(); + } +} + +impl Drop for Tracer { + fn drop(&mut self) { + self.0.flush().ok(); + } +} diff --git a/tvix/eval/src/lib.rs b/tvix/eval/src/lib.rs index ba037d6c8a0a..f796034ded98 100644 --- a/tvix/eval/src/lib.rs +++ b/tvix/eval/src/lib.rs @@ -7,6 +7,9 @@ mod value; mod vm; mod warnings; +#[cfg(feature = "disassembler")] +mod disassembler; + #[cfg(test)] mod tests; diff --git a/tvix/eval/src/vm.rs b/tvix/eval/src/vm.rs index 8ee17258602e..0d0249e3f6c0 100644 --- a/tvix/eval/src/vm.rs +++ b/tvix/eval/src/vm.rs @@ -10,6 +10,9 @@ use crate::{ value::{NixAttrs, NixList, Value}, }; +#[cfg(feature = "disassembler")] +use crate::disassembler::Tracer; + pub struct VM { ip: usize, chunk: Chunk, @@ -88,8 +91,12 @@ impl VM { } fn run(&mut self) -> EvalResult<Value> { + #[cfg(feature = "disassembler")] + let mut tracer = Tracer::new(); + loop { - match self.inc_ip() { + let op = self.inc_ip(); + match op { OpCode::OpConstant(idx) => { let c = self.chunk.constant(idx).clone(); self.push(c); @@ -261,6 +268,11 @@ impl VM { } } + #[cfg(feature = "disassembler")] + { + tracer.trace(&op, self.ip, &self.stack); + } + if self.ip == self.chunk.code.len() { return Ok(self.pop()); } |