How to retrieve function names via `@typeInfo` in zig 0.17.0?

I think this old hack that is not using @typeInfo, but @typeName with a generic, probably still works:

But it is still questionable whether you should rely upon it, I guess it would be good to at least add a unity test that makes sure that it still works, so you get notified if it eventually breaks (If it wouldn’t be immediately obvious to how your code uses it).

fn functionName(comptime func: anytype) []const u8 {
    const T = @TypeOf(func);
    std.debug.assert(@typeInfo(T) == .@"fn");
    const wrapper_name = @typeName(Wrapper(func));

    var it = std.mem.splitSequence(u8, wrapper_name, ".Wrapper((function '");
    _ = it.first();
    const rest = it.next().?;
    return rest[0 .. rest.len - 3];
}

test functionName {
    try std.testing.expectEqualStrings("Wrapper", functionName(Wrapper));
    try std.testing.expectEqualStrings("add", functionName(add));
    try std.testing.expectEqualStrings("splitSequence", functionName(std.mem.splitSequence));
}

fn Wrapper(comptime arg: anytype) type {
    return struct {
        const stuff = arg;
    };
}

fn add(a: i32, b: i32) i32 {
    return a + b;
}

const std = @import("std");

related: Getting function name at comptime and stringify

2 Likes