zig icon indicating copy to clipboard operation
zig copied to clipboard

stage2: Support `std.log` at comptime, using `@compileError`

Open topolarity opened this issue 3 years ago • 0 comments

This is a rudimentary (and arguably cursed) implementation of comptime logging that works in stage 2.

I'm not sure we'll want to merge this, but it might be useful so I decided to open the PR just to get feedback.

test {
    const Foo = struct { a: u8, b: i32 };
    const data = Foo{ .a = 15, .b = -16 };
    comptime std.log.err(
        \\Error encountered!
        \\Data was: {}
        \\
        \\Have you tried turning it off and on again?
        , .{ data });
}

when compiled, this prints:

$ ./stage2/bin/zig test test.zig
lib/std/log.zig:183:9: error: Error encountered!
                              Data was: test.test_0.Foo{ .a = 15, .b = -16 }

                              Have you tried turning it off and on again?

lib/test_runner.zig:130:34: note: called from here
lib/std/log.zig:139:21: note: called from here
lib/std/log.zig:217:16: note: called from here
test.zig:6:25: note: called from here

You can only log one message, since this uses @compileError. AFAIK @compileLog currently has no way of printing a string if it's not a string literal.

kudos to @r00ster91 for the idea

topolarity avatar Jul 30 '22 21:07 topolarity