← Back to context

Comment by robertlagrant

11 hours ago

What we need is a numeric type that cannot be zero.

What we need are refinement types, where there’s a base type and a predicate. F* has this:

     val (/) : int -> (divisor:int { divisor <> 0 }) -> int

And also cannot be INT_MIN, otherwise -1 / INT_MIN is undefined behaviour(!) in C and C++.

The only way to achieve this is to either put a runtime software check on a variable whenever it's assigned/used, or to literally add hardware support in processors themselves which literally throws an interrupt when a "neverShallBeZero" variable is assigned to zero.

There's no viable way to statically prove at compile-time that these variables will never become zero at runtime, ultimately forcing a system of endless runtime checks (be it software or hardware)... which is why processors already throw exception interrupts when division by zero is attempted.

  • You're kind of saying the only way to do it is in software or hardware :)

    An alternative https://en.wikipedia.org/wiki/Projectively_extended_real_lin...

    The projectively extended real line defines division by zero, no reason you couldn't have a floating point type that implemented it.

    >There's no viable way to statically prove at compile-time that these variables will never become zero at runtime

    strongly typed programming languages like Ada allow for types which have ranges such as disallowing zero -- but also any arbitrary thing like you can create a floating point "degrees" type which is [0.0, 360.0] or any other ranged type

It would be more flexible for a compiler to reuse the range analysis logic used in optimizations for statically verifiable divide by zeros. That way you could extend it to other things like statically verifiable overflows.

For stuff like niche value optimization sure. For practical arithmetic code, nah. Like with this bug, all that changed is that garbage data in gives the user an error that they tried to process garbage data. Adding a new type doesn't make the code better, it just moves the error around. And you really don't want an infix division operator to fail to type check if the right hand side isn't a nonzero type, do you?