zig
zig copied to clipboard
Expose docComment in @typeInfo data
This issue did just give me an idea though: what if
@typeInfodata included the doc comment? So I could e.g. do:fn getDef(comptime T: type, field: []const u8) ?builtin.StructField { const info = @typeInfo(T); const defs = switch (info) { builtin.TypeId.Struct => |s| s.defs, builtin.TypeId.Union => |u| u.defs, builtin.TypeId.Enum => |e| e.defs, else => return null, }; inline for (defs) |def| { if (mem.eql(u8, def.name, field)) return def; } return null; } fn methodDocs(comptime T: type, field: []const u8) !?[]const u8 { const def = getDefInfo(T, field) orelse return error.NoSuchMethod; return def.docComment; }
Originally posted by @daurnimator in https://github.com/ziglang/zig/issues/2539#issuecomment-495029211
One thing that was mentioned in IRC is that this would allow storing comptime metadata in comments and changing program behavior based on it. I think we can all agree that comments changing program behavior is exceptionally un-zen.
Something like #1099 would allow a more obvious path for whatever that kind of thing is trying to accomplish, but the possibility would still be there if this feature existed.
comments changing program behavior is exceptionally un-zen
Doccomments are not normal comments.
Converting text from doccomments to CLI --help message chunks looks like a good idea, and is a program behaviour change.
If @Type(.Struct/.Enum/.Union) ever get decls definition then this is possible through comptime without loss of decls through @src() and @embedFile() abuse by wrapping everything in @Type(.Struct) with a documentation field and later reconstructing the intended type with @Type().
It would be nicer to have it in TypeInfo rather than the hack for generation of things like OpenAPI object specifications if documentation hooks are never implemented.
Edit: added "rather than the hack"
How much memory will the compiler eat with this feature?
One interesting use-case for this would be auto-generation of OpenAPI documentation without need for a separate build-step.
We can currently generate schema from type introspection, but we cannot access comments so you can't see what the fields are supposed to mean.