Zig: Implement an analog of C99's __func__

Created on 6 Jun 2020  路  1Comment  路  Source: ziglang/zig

Right now, the lack of an analog for C99's __func__ (aka __FUNCTION__ in GCC) leads to painful error-handling code at API boundaries (see below) as well as to inadvertent copy-paste errors since function names are hardcoded as string literals all over the place and it's easy to miss cases when the string isn't correct.

A concrete, simplified example from a C API that I'm developing, where we must write out the function name as a string literal once per each invocation of error handler:

pub export fn fooCreateContext(version: u64, flags: u64, context: ?*foo.context) foo.status {
    if (version > 0) return status.invalidArgument("fooCreateContext", "version");
    if (flags != 0) return status.invalidArgument("fooCreateContext", "flags");
    if (context == null) return status.invalidArgument("fooCreateContext", "context");

(Wherein status.invalidArgument in turn invokes a user-supplied error callback hook that needs to be able to report the function name whence the error originated.)

Related issue: https://github.com/ziglang/zig/issues/2029

proposal

Most helpful comment

2029 has been accepted, and so this proposal is no longer needed. Once it is implemented:

pub export fn fooCreateContext(version: u64, flags: u64, context: ?*foo.context) foo.status {
    if (version > 0) return status.invalidArgument(@src().fn_name, "version");
    if (flags != 0) return status.invalidArgument(@src().fn_name, "flags");
    if (context == null) return status.invalidArgument(@src().fn_name, "context");

>All comments

2029 has been accepted, and so this proposal is no longer needed. Once it is implemented:

pub export fn fooCreateContext(version: u64, flags: u64, context: ?*foo.context) foo.status {
    if (version > 0) return status.invalidArgument(@src().fn_name, "version");
    if (flags != 0) return status.invalidArgument(@src().fn_name, "flags");
    if (context == null) return status.invalidArgument(@src().fn_name, "context");
Was this page helpful?
0 / 5 - 0 ratings