How to write compat shim for builtin function changes (e.g. `@abs` vs `@fabs`)?

Interesting problem, it seems that the builtin calls are name checked during the AstGen step and so it complains before evaluating the comptime if.

I was able to get the following to work using a conditional module in the build.zig:

// build.zig

pub fn build(b: *std.Built) void {
    //...
    const abs = if (@import("builtin").zig_version.minor > 11)
        b.addModule("abs", .{ .source_file = .{ .path = "src/abs.zig" } })
    else
        b.addModule("abs", .{ .source_file = .{ .path = "src/fabs.zig" } });
    exe.addModule("abs", abs);
    //...
}
// src/abs.zig
pub inline fn abs(a: anytype) @TypeOf(@abs(a)) {
    return @abs(a);
}
// src/fabs.zig
pub inline fn abs(a: anytype) @TypeOf(@fabs(a)) {
    return @fabs(a);
}
5 Likes