4 ms·
A lot of Zig relies on compilation being lazy in the same sort of way.
by anonymoushn 1y ago
A lot of Zig relies on compilation being lazy in the same sort of way.
- dwattttt 1y agoFor the validity of the program? As in, a program will fail to compile (or compile but be incorrect) if an optimisation misbehaves? That sounds as bad as relying on undefined behaviour in C.
- Laremere 1y agoIt's not an optimization. What gets evaluated via the lazy evaluation is well defined. Control flow which has a value defined at comptime will only evaluate the path taken. In the op example, the block is evaluated twice, once for each enum value, and the inner switch is followed at comptime so only one prong is evaluated.
- anonymoushn 1y agoWell, for example you may have some functions which accept types and return types, which are not compatible with some input types, and indicate their incompatibility by raising an error so that compilation fails. If the program actually does not pass some type to such a function that leads to this sort of error, it would seem like a bug for the compiler to choose to evaluate that function with that argument anyway, in the same way that it would be a bug if I had said "template" throughout this comment. And it is not generally regarded as a deficiency in C++ that if the compiler suddenly chose to instantiate every template with every value or type, some of the resulting instantiations would not compile.
- dwattttt 1y agoTo take an extreme example, what if I asserted the Riemann hypothesis in comptime? It's relying on comptime execution to act as a proof checker. Which is fine for small inputs and uses, but it's not something that would scale well.
- deleted 1y ago[deleted]
- 9029 1y agoNope, this is not relying on optimization, it's just how compile time evaluation works. The language guarantees "folding" here regardless of optimization level in use. The inline keyword used in the original post is not an optimization hint, it does a specific thing. It forces the switch prong to be evaluated for all possible values. This makes the value comptime, which makes it possible to have a comptime unreachable prong when switching on it. There are similarities here to C++ if constexpr and static_assert, if those are familiar to you.