Ideas wanted for creating types in comptime

I’m currently working on a code generation for a type of schema, and I want the types produced to work with the std.json module and similar modules that provide serialization and deserialization.

My current approach is to generate the source for the files, but after reading this comment I got inspired to try and generate the binaries directly without generating source code. I would like to take the approach presented here using the @Type builtin, but it won’t work because I would need to add functions, which are declarations and @Type can’t reify structs with declarations.

So I’m a bit stuck atm, because while I have gotten pretty far with the source generator I think it would be much neater to use comptime, but I don’t see how due to the limitation on declarations in structs. Am I stuck with the source generation approach or is there some way to do what I want to do directly in comptime?

1 Like

One option would be to just wrap your generated type and provide jsonParse() and jsonStringify() on the wrapper. maybe something like this

fn MyAutoSer(comptime T: type) type{
    return struct{
        value: GenType(T),

        pub fn jsonParse(self: @This(), ...) {
            // serialize into self.value
        }
        pub fn jsonStringify(self: @This(), ...) {
            // deserialize from self.value
        }
    };
}
2 Likes

This is an approach I didn’t think of, thanks! I don’t think I’ll use it, as it would require me to write an extra .value every time I want to access a field, and because some generated types will have fields of other generated types it would get unergonomic quickly.

I think I’ll continue with the source generation approach and consider metaprogramming if Andrew changes his mind on reification.