zig/test/cases/compile_errors/compile_log.zig
mlugg 4976b58ab1
Prevent analysis of functions only referenced at comptime
The idea here is that there are two ways we can reference a function at runtime:

* Through a direct call, i.e. where the function is comptime-known
* Through a function pointer

This means we can easily perform a form of rudimentary escape analysis
on functions. If we ever see a `decl_ref` or `ref` of a function, we
have a function pointer, which could "leak" into runtime code, so we
emit the function; but for a plain `decl_val`, there's no need to.

This change means that `comptime { _ = f; }` no longer forces a function
to be emitted, which was used for some things (mainly tests). These use
sites have been replaced with `_ = &f;`, which still triggers analysis
of the function body, since you're taking a pointer to the function.

Resolves: #6256
Resolves: #15353
2023-05-29 23:06:08 +01:00

30 lines
772 B
Zig

export fn foo() void {
comptime bar(12, "hi");
_ = &bar;
}
fn bar(a: i32, b: []const u8) void {
@compileLog("begin");
@compileLog("a", a, "b", b);
@compileLog("end");
}
export fn baz() void {
const S = struct { a: u32 };
@compileLog(@sizeOf(S));
}
// error
// backend=llvm
// target=native
//
// :6:5: error: found compile log statement
// :12:5: note: also here
//
// Compile Log Output:
// @as(*const [5:0]u8, "begin")
// @as(*const [1:0]u8, "a"), @as(i32, 12), @as(*const [1:0]u8, "b"), @as([]const u8, "hi")
// @as(*const [3:0]u8, "end")
// @as(comptime_int, 4)
// @as(*const [5:0]u8, "begin")
// @as(*const [1:0]u8, "a"), @as(i32, [runtime value]), @as(*const [1:0]u8, "b"), @as([]const u8, [runtime value])
// @as(*const [3:0]u8, "end")