proposal: learn comptime-known-ranges from branches on runtime values #12872
Labels
proposal
This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone
Uh oh!
There was an error while loading. Please reload this page.
Related to #12863
Instead of narrowing (creating a new type) one could attach the reduced range to the type within the block and treat any branches outside of that range as dead code without changing the underlying type. Consider the example given:
Here
@TypeOf(narrow) == E
while the range ofnarrow
only includes the laterc
andd
tags. If we changee
to beconst
then the range ofe
within the same scope thatnarrow
is introduced is equivalent but the underlying type remains the same.This can be expanded upon to include other forms of branching such as:
Thus zig can learn the range of a value at compile-time by keeping track of the set/range of possible values that remain within a branch.
By keeping the same underlying type it's possible to operate on integers :
And implicitly cast based on the range:
If the range of a value on the right hand side of a truncating operation is comptime-known then the range of the result is guaranteed to be below the top of the range thus any use of
%
and&
narrows the range of the type. The same applies tocomptime_int
on the right hand side:The same applies for addition and multiplication:
Since the type of the value doesn't change, the value can still be passed safely to functions without casts:
However integers can be narrowed when the range of the value is within the range of a smaller destination type:
Note that if the range is larger than that of the underlying type then overflow is possible.
Operators
Thus the standard operators should now result in:
note: the
range(n...m)
syntax is not part of the proposalExtension
For safety, allow function parameters and return types to express the range desired and throw a compile-error when the range cannot be satisfied:
or maybe as an expression:
However ranges for parameters/return types requires more thought.
There likely needs to be a way to preserve intent as this proposal tries to infer it without providing specification other than through assert. Some way to express the intent (likely in the type signature) and to maintain it should be considered upon evaluation of this proposal.
The text was updated successfully, but these errors were encountered: