About @src()

@src() or rather std.builtin.SourceLocation is a pretty good struct but whenever I want to print something about @src() I wish there was a custom formatter in there somewhere like this.

pub fn format(self: SourceLocation, writer: *std.Io.Writer) !void {
    try writer.print("{s}:{d}:{d} in {s} [{s}]", .{
        self.file,
        self.line,
        self.column,
        self.fn_name,
        self.module,
    });
}

Is this acceptable cause I know SourceLocation is directly used in codegen and I don’t know if this will clutter everything there.
P.S. I think this is a too verbose example just using file, line and column would be enough maybe.

There is std.fmt.Alt(), which essentially wraps a type with a custom formater. You use it like so:

pub fn main()!void {
    const src = @src();
    std.debug.print("{any}\n", .{src});
    // Generate Wrapper type for my custom formatter
    const fmtWrapper = std.fmt.Alt(std.builtin.SourceLocation, formatSrc);
    std.debug.print("{f}\n", .{fmtWrapper{.data=src}});
}

/// Custom Format Function
pub fn formatSrc(self: std.builtin.SourceLocation, writer: *std.Io.Writer) !void {
    try writer.print("{s}:{d}:{d} in {s} [{s}]", .{
        self.file,
        self.line,
        self.column,
        self.fn_name,
        self.module,
    });
}

const std = @import("std");

7 Likes

Oh thanks, I didn’t know that.

1 Like