#comptime typeId | RTTI

1 messages · Page 1 of 1 (latest)

meager socket
#

I've seen here in the discord a couple times this typeId trick but didn't have reason to use it till now. MasterQ32 also made a post about this: https://zig.news/xq/cool-zig-patterns-type-identifier-3mfd

pub fn typeId(comptime T: type) usize {
    _ = T;
    const H = struct {
        var byte: u8 = 0;
    };
    return @ptrToInt(&H.byte);
}```
Thing is, when used in a `comptime` context the last line becomes a compile error:

error: unable to evaluate comptime expression
return @intToEnum(TypeId, @ptrToInt(&H.byte));
^~~~~~~~~~~~~~~~~~~~~~~
note: operation is runtime due to this operand
return @intToEnum(TypeId, @ptrToInt(&H.byte));
^~~~~~~~~~~~```
I found the same message here: https://github.com/ziglang/zig/issues/2352#issuecomment-1279902162
Is this currently bugged or am I doing something wrong?
The language reference states this:

Zig is able to preserve memory addresses in comptime code, as long as the pointer is never dereferenced.

glossy minnow
#

This will eventually work at comptime but it hasn't been implemented yet.

meager socket
#

oh i see

past tundra
glossy minnow
#

You could pass pointers around directly instead of integer IDs, and convert to integers only when needed at runtime.

past tundra
#

pointers to the H.byte field?

glossy minnow
#

yeah, so pass around type_id: *u8 .

past tundra
#

ig that's better than a manual list ahah

solid charm
#

could also obfuscate it some and cast it to *opaque{}

#

or even *const opaque{}

#

btw, another way to have RTTI now in stage2 is to just use @typeName, which, iiuc, will always return a unique string per type

#

wherein you could either use the address of the string itself, similar to the original idea, or use the string contents as the id in e.g. a string hash map

glossy minnow
#

I don't think @typeName is necessarily unique. Two packages could have files with the same name containing types with the same name, and those would be distinct types but both be assigned the same name IIUC.

solid charm
#

You'll see things like expected main.Foo

glossy minnow
#

Two different packages can have the same name when imported from different packages

solid charm
#

Oh, fair point, hadn't considered that