Skip to content

Comptime code generation #6165

@davrec72

Description

@davrec72

I have just come across Zig so I apologize if I don't have the syntax etc. quite right, but something like the following code-generation meta-programming functionality would be great, and would be simple and general enough to fit in with Zig's "zen" I think:

const Header = struct {
    magic: u32,
    name: []const u8,
};
fn addGetFuncs(comptime T: type) type {
    return struct {
        comptime {
            @qparse("data: Header,"); //PROPOSED
            inline for (@typeInfo(T).Struct.fields) |field| {
                @qparse("fn get_", field.name, "() ", field.field_type.name, " { return data.", field.name, "; }" ) //PROPOSED
            }
        } // "queued" string literals are parsed into enclosing context when non-dependent
    };
}

I added a similar experimental feature to Clang for C++ awhile back, but I think Zig would benefit even more because it seems to have nailed just about every design decision to enable really powerful metaprogramming -- using the same language for compile time and run time code (no constexpr headaches in C++), using the same language for the build system as well (no CMake headaches), and generally keeping everything as simple as possible so there aren't a million different AST nodes to reflect.

If you can eventually add reflection support for all the information in the AST, statements/expressions included, and combine that with a fully-general reification mechanism such as this, Zig could be at once the lowest-level language possible AND the highest-level language possible, I think.

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions