ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.68k stars 2.47k forks source link

compiler: remove unused struct fields #21010

Open andrewrk opened 1 month ago

andrewrk commented 1 month ago

Unfortunately we cannot have a compile error for unused struct fields (#12854) since whether a field is used depends on semantic analysis (#3028). However, for structs that have automatic layout, it is legal for the compiler to remove fields that are not used. The compiler should do that automatically.

silversquirl commented 1 month ago

Wouldn't this mean no function that uses a struct with possibly-unused fields can be sent to code generation until all functions have been analyzed? Since a function analyzed later could use the field and thus affect the codegen of previous functions. Seems like the compile time performance implications would be pretty significant

andrewrk commented 1 month ago

That's a great point, and since it might have compiler design implications, it means it needs to be tackled earlier.

mlugg commented 1 month ago

Yeah, this isn't feasible as-is for precisely the reason silversquirl gave above. Moreover, any semantic analysis which requires resolving the type layout -- for instance, @sizeOf -- would require first resolving all possible usages of the type. So, we have an absurd situation where @sizeOf logically depends on the entire program -- including the code following itself -- being analyzed.

mlugg commented 1 month ago

If we go ahead with SpexGuy's idea to make @field and friends take an @Type(.EnumLiteral) rather than a string, then we could define a sufficient condition for omitting a field: if that identifier never occurs in any other type field, enum literal, or field access, in the entire ZCU. However, this condition is so narrow as to be entirely useless.

andrewrk commented 1 month ago

It would be possible to combine these two things:

in order to trade programmer effort for optimality. It would probably be a huge pain in the ass though.

mlugg commented 1 month ago

Hmm -- so for every field, you can mark it (fictional syntax) unused(is_field_unused) (default is unused(false)), and you get a compile error if it was used and marked unused or vice versa? Yeah, that could work, but I anticipate it being a huge PITA. And it makes the benefits of this proposal dubious -- at that point, just make the field type conditional, marking it void if it'll be unused.

andrewrk commented 1 month ago

My point is that the unused declaration would exist potentially even outside the module that declares the struct. The struct would be declared like normal (consider the motivating use case of #20977).