dbg in Rust is very useful for debugging, but it seems we can’t implement it in Zig, function below is the best solution I can think of, although works, less practical than rust’s.
fn dbg(v: anytype, loc: std.builtin.SourceLocation) @TypeOf(v) {
std.debug.print("{s}:{d} {any}\n", .{ loc.file, loc.line, v });
return v;
}
pub fn main() !void {
const a: usize = 1;
const b = dbg(a + 1, @src());
std.debug.print("{d}\n", .{b});
}
dimdin
October 31, 2024, 3:44pm
2
2 Likes
Thanks a lot! This is the updated version of dbg:
pub fn dbg(v: anytype) @TypeOf(v) {
const debug_info = std.debug.getSelfDebugInfo() catch return v;
const address = @returnAddress();
const module = debug_info.getModuleForAddress(address) catch return v;
const symbol_info = module.getSymbolAtAddress(debug_info.allocator, address) catch return v;
defer symbol_info.deinit(debug_info.allocator);
const line, const column = if (symbol_info.line_info) |line_info|
.{ line_info.line, line_info.column }
else
.{ 0, 0 };
std.debug.print("[{s}:{d}:{d}] -> {any}\n", .{ symbol_info.symbol_name, line, column, v });
return v;
}
6 Likes