h2: add better VM value stack tracing

This commit is contained in:
りき萌 2025-09-02 20:30:47 +02:00
parent 45099916fe
commit 2eea1f201f

View file

@ -147,6 +147,24 @@ pub fn stackFrame(vm: *const Vm, index: usize) StackFrame {
} }
} }
const StackFmt = struct {
stack: []const Value,
pub fn format(f: *const StackFmt, writer: *std.Io.Writer) !void {
try writer.writeAll("[");
for (f.stack, 0..) |val, i| {
if (i != 0)
try writer.writeAll(", ");
try val.format(writer);
}
try writer.writeAll("]");
}
};
fn stackFmt(stack: []const Value) StackFmt {
return .{ .stack = stack };
}
/// Debug assertion for bytecode validity. /// Debug assertion for bytecode validity.
/// In future versions, this may become disabled in release builds. /// In future versions, this may become disabled in release builds.
fn validateBytecode(vm: *Vm, ok: bool, comptime fmt: []const u8, args: anytype) Error!void { fn validateBytecode(vm: *Vm, ok: bool, comptime fmt: []const u8, args: anytype) Error!void {
@ -167,7 +185,7 @@ pub fn push(vm: *Vm, val: Value) Error!void {
if (vm.stack_top >= vm.stack.len) { if (vm.stack_top >= vm.stack.len) {
return vm.throw("too many live temporary values (local variables and expression operands)", .{}); return vm.throw("too many live temporary values (local variables and expression operands)", .{});
} }
log.debug("PUSH {any} <- {f}", .{ vm.stack[0..vm.stack_top], val }); log.debug("PUSH {f} <- {f}", .{ stackFmt(vm.stack[0..vm.stack_top]), val });
vm.stack[vm.stack_top] = val; vm.stack[vm.stack_top] = val;
vm.stack_top += 1; vm.stack_top += 1;
} }
@ -176,7 +194,7 @@ pub fn pop(vm: *Vm) Error!Value {
try vm.validateBytecode(vm.stack_top > 0, "value stack underflow", .{}); try vm.validateBytecode(vm.stack_top > 0, "value stack underflow", .{});
vm.stack_top -= 1; vm.stack_top -= 1;
const result = vm.stack[vm.stack_top]; const result = vm.stack[vm.stack_top];
log.debug("POP {any} -> {f}", .{ vm.stack[0..vm.stack_top], result }); log.debug("POP {f} -> {f}", .{ stackFmt(vm.stack[0..vm.stack_top]), result });
return vm.stack[vm.stack_top]; return vm.stack[vm.stack_top];
} }