Add debug mode and VM tracing

Introduce a `debug_mode` flag to the `Environment` and a new `run_debug`
method. This method uses a `TracingObserver` to log the VM's execution
flow, including node evaluation and scope state changes. This allows for
detailed inspection of script execution.

The `BoundKind` enum now also includes a `display_name` method for
better log readability.
This commit is contained in:
Michael Schimmel
2026-02-18 00:56:29 +01:00
parent 25e3bc1d01
commit faada16723
5 changed files with 212 additions and 30 deletions
+90 -17
View File
@@ -27,6 +27,61 @@ struct CallFrame {
closure: Option<Rc<Closure>>,
}
/// Hook for observing VM execution (zero-cost when O::ACTIVE is false)
pub trait VMObserver {
const ACTIVE: bool = false;
fn before_eval(&mut self, _vm: &VM, _node: &Node<BoundKind, StaticType>, _indent: usize) {}
fn after_eval(&mut self, _vm: &VM, _node: &Node<BoundKind, StaticType>, _res: &Result<Value, String>, _indent: usize) {}
}
/// Default observer that does nothing and should be optimized away
pub struct NoOpObserver;
impl VMObserver for NoOpObserver {}
/// Observer that logs the execution tree and scope state
pub struct TracingObserver {
pub logs: Vec<String>,
}
impl TracingObserver {
pub fn new() -> Self {
Self { logs: Vec::new() }
}
fn pad(&self, indent: usize) -> String {
"| ".repeat(indent)
}
}
impl VMObserver for TracingObserver {
const ACTIVE: bool = true;
fn before_eval(&mut self, _vm: &VM, node: &Node<BoundKind, StaticType>, indent: usize) {
let pad = self.pad(indent);
self.logs.push(format!("{}{} [{}]: {{", pad, node.kind.display_name(), node.ty));
}
fn after_eval(&mut self, vm: &VM, node: &Node<BoundKind, StaticType>, res: &Result<Value, String>, indent: usize) {
let pad = self.pad(indent);
// Show scope state on certain nodes (like Delphi ShowScope)
match &node.kind {
BoundKind::DefLocal { .. } | BoundKind::Set { .. } | BoundKind::DefGlobal { .. } => {
let s_pad = self.pad(indent + 1);
self.logs.push(format!("{}--- Scope Status ---", s_pad));
self.logs.push(format!("{}Stack (top 5): {:?}", s_pad, vm.stack.iter().rev().take(5).collect::<Vec<_>>()));
},
_ => {}
}
let res_str = match res {
Ok(v) => format!("{}", v),
Err(e) => format!("ERROR: {}", e),
};
self.logs.push(format!("{}}} -> {}", pad, res_str));
}
}
pub struct VM {
stack: Vec<Value>,
globals: Rc<RefCell<Vec<Value>>>,
@@ -43,6 +98,10 @@ impl VM {
}
pub fn run(&mut self, root: &Node<BoundKind, StaticType>) -> Result<Value, String> {
self.run_with_observer(&mut NoOpObserver, root)
}
pub fn run_with_observer<O: VMObserver>(&mut self, observer: &mut O, root: &Node<BoundKind, StaticType>) -> Result<Value, String> {
self.stack.clear();
self.frames.clear();
@@ -52,19 +111,33 @@ impl VM {
closure: None,
});
let result = self.eval(root);
let result = self.eval(observer, 0, root);
self.frames.pop();
result
}
fn eval(&mut self, node: &Node<BoundKind, StaticType>) -> Result<Value, String> {
fn eval<O: VMObserver>(&mut self, observer: &mut O, indent: usize, node: &Node<BoundKind, StaticType>) -> Result<Value, String> {
if O::ACTIVE {
observer.before_eval(self, node, indent);
}
let result = self.eval_internal(observer, indent, node);
if O::ACTIVE {
observer.after_eval(self, node, &result, indent);
}
result
}
fn eval_internal<O: VMObserver>(&mut self, observer: &mut O, indent: usize, node: &Node<BoundKind, StaticType>) -> Result<Value, String> {
match &node.kind {
BoundKind::Nop => Ok(Value::Void),
BoundKind::Constant(v) => Ok(v.clone()),
BoundKind::DefGlobal { global_index, value } => {
let val = self.eval(value)?;
let val = self.eval(observer, indent + 1, value)?;
let idx = *global_index as usize;
let mut globals = self.globals.borrow_mut();
if idx >= globals.len() {
@@ -77,13 +150,13 @@ impl VM {
BoundKind::Get(addr) => self.get_value(*addr),
BoundKind::Set { addr, value } => {
let val = self.eval(value)?;
let val = self.eval(observer, indent + 1, value)?;
self.set_value(*addr, val.clone())?;
Ok(val)
},
BoundKind::DefLocal { slot, value, captured_by } => {
let val = self.eval(value)?;
let val = self.eval(observer, indent + 1, value)?;
let final_val = if !captured_by.is_empty() {
Value::Cell(Rc::new(RefCell::new(val)))
} else {
@@ -105,11 +178,11 @@ impl VM {
},
BoundKind::If { cond, then_br, else_br } => {
let c = self.eval(cond)?;
let c = self.eval(observer, indent + 1, cond)?;
if c.is_truthy() {
self.eval(then_br)
self.eval(observer, indent + 1, then_br)
} else if let Some(e) = else_br {
self.eval(e)
self.eval(observer, indent + 1, e)
} else {
Ok(Value::Void)
}
@@ -118,7 +191,7 @@ impl VM {
BoundKind::Block { exprs } => {
let mut last = Value::Void;
for e in exprs {
last = self.eval(e)?;
last = self.eval(observer, indent + 1, e)?;
}
Ok(last)
},
@@ -138,10 +211,10 @@ impl VM {
},
BoundKind::TailCall { callee, args } => {
let func_val = self.eval(callee)?;
let func_val = self.eval(observer, indent + 1, callee)?;
let mut arg_vals = Vec::with_capacity(args.len());
for arg in args {
arg_vals.push(self.eval(arg)?);
arg_vals.push(self.eval(observer, indent + 1, arg)?);
}
match func_val {
@@ -154,11 +227,11 @@ impl VM {
},
BoundKind::Call { callee, args } => {
let mut func_val = self.eval(callee)?;
let mut func_val = self.eval(observer, indent + 1, callee)?;
let mut arg_vals = Vec::with_capacity(args.len());
for arg in args {
arg_vals.push(self.eval(arg)?);
arg_vals.push(self.eval(observer, indent + 1, arg)?);
}
// Trampoline Loop
@@ -177,7 +250,7 @@ impl VM {
closure: Some(closure_rc.clone()),
});
let result = self.eval(&closure.function_node);
let result = self.eval(observer, indent + 1, &closure.function_node);
self.frames.pop();
self.stack.truncate(old_stack_top);
@@ -203,7 +276,7 @@ impl VM {
BoundKind::Tuple { elements } => {
let mut vals = Vec::with_capacity(elements.len());
for e in elements {
vals.push(self.eval(e)?);
vals.push(self.eval(observer, indent + 1, e)?);
}
Ok(Value::List(Rc::new(vals)))
},
@@ -211,8 +284,8 @@ impl VM {
BoundKind::Map { entries } => {
let mut map = HashMap::new();
for (k, v) in entries {
let key = self.eval(k)?;
let val = self.eval(v)?;
let key = self.eval(observer, indent + 1, k)?;
let val = self.eval(observer, indent + 1, v)?;
if let Value::Keyword(kw) = key {
map.insert(kw, val);