I met compile error in enum that has a negative value.
The code:
enum Nums
Zero = -2
One
Two
end
The error:
Error in line 4: value of enum member Two would overflow the base type Int32
This error arises in 0.29.0, not 0.28.0. I know this is suppressed by specifying each value like:
enum Nums
Zero = -2
One = -1
Two = 0
end
This is a feature for safety or a bug of the compiler?
Definitely a bug. Two should not be assigned a value that would overflow Int32.
The culprit is this line: https://github.com/crystal-lang/crystal/blob/e3fa96752588df94d386ce1551ad03526a8545c9/src/compiler/crystal/semantic/top_level_visitor.cr#L692
I wrote the overflow check incorrectly for negative values... I wish we had a way to try to do stuff and know whether it overflows without having to raise and catch an exception. Something like ?+ or Int32.add_with_overflow... that way I wouldn't have to do custom math to check things like this.
it would be nice to have has an api where you could get the result of the overflow. Something like unsafe_div except you would have to pass a pointer to the overflow var and check to see if it was set to 1 like it is here.
I was thinking something like.
overflow = 0
100.unsafe_mul(123, pointerof(overflow))
if overflow == 1
p "* has overflowed"
end
Most helpful comment
The culprit is this line: https://github.com/crystal-lang/crystal/blob/e3fa96752588df94d386ce1551ad03526a8545c9/src/compiler/crystal/semantic/top_level_visitor.cr#L692
I wrote the overflow check incorrectly for negative values... I wish we had a way to try to do stuff and know whether it overflows without having to raise and catch an exception. Something like
?+orInt32.add_with_overflow... that way I wouldn't have to do custom math to check things like this.