zig
                                
                                 zig copied to clipboard
                                
                                    zig copied to clipboard
                            
                            
                            
                        implement `@expect` builtin
closes #489
Why @expect takes a bool:
- @expectaffects branching codegen and you can only branch on a bool.
- Expecting a specific value can be done with unreachablewith respect to the optimizer.
Why @expect doesn't have a probability:
- Probabilities don't make a practical difference in codegen vs. binary.
- The switch usecase can't reliably predict codegen (could be a jump table, some could be comparisons, or it could be a mixture of both)
Probabilities don't make a practical difference in codegen vs. binary.
Are you saying that LLVM's expect.with.probability doesn't do anything?
Expect with probability seems to affect switch cases but it's unclear how it does so practically compared to if.
When there is no expected value nor probability, wouldn't a name like @likely instead of @expect be more fitting so that this builtin doesn't get mixed up to be an assertion or function like std.testing.expect?
For purposes of consistency with C (compiler __builtin_expect vs the common #define LIKELY(x) __builtin_expect(x, 1)), it seems better to name it likely.
I don't want likely as it implies an unlikely. Note that the only real purpose of this builtin is the unlikely version, and unlikely is a bit ugly imo.
I will change it up to accept a second field for true or false instead and keep expect as per @kprotty suggestion when we talked about it.
Since the user can implement a likely or unlikely pretty easily themselves when a second field is added:
inline fn likely(x: bool) bool {
    return @expect(x, true);
}
inline fn unlikely(x: bool) bool {
    return @expect(x, false);
}
I think this would be the best solution. Thanks! :)
Should likely and unlikely functions be part of the standard library? On one hand, they're one-liners any user can easily write, on the other hand, everyone writing their likely and unlikely functions is worse, a likely/unlikely micropackage would also suck. Discuss.
Thought about that yesterday, but I think making @expect take a second "expected" bool supports both likely and unlikely without a wrapper.
What about a nice sugary @expect(operand: anytype, expected: anytype) and add a check for @typeOf(operand) == @typeOf(expected)?
No, this will defeat the purpose of this builtin.
nobody 
@expects the Spanish inquisition!!
Reverted in 9be8a9000faead40b1aec4877506ff10b066659c. I would like a chance to review this please.