C
Chris Smith
George Neuner said:We're talking at cross purposes. I'm questioning whether a strong
type system can be completely static as some people here seem to
think. I maintain that it is simply not possible to make compile time
guarantees about *all* runtime behavior and that, in particular,
narrowing conversions will _always_ require runtime checking.
Nah, we're not at cross-purposes. I'm discussing the same thing you
are. My answer is that while narrowing conversion are not (by
definition) type-safe, a sufficiently strong type system can remove
these type-unsafe narrowing conversions from a program.
Again, the discussion is about narrowing the result. It doesn't
matter how much the compiler knows about the ranges. When the
computation mixes types, the range of the result can only widen as the
compiler determines the types involved.
Well, there are certain operations that can reduce the range. For
example, dividing a number that's known to be in the range 6-10 by the
exact constant 2 yields a result that's guaranteed to be in the range 3-
5. That's a smaller range.
That said, though, there is a more fundamental point here. When you
perform a a narrowing type conversion, one of two things must be true:
(a) you know more about the types than the compiler, and thus know that
the conversion is safe, or (b) your code is broken. Exluding the
possibility that you've written buggy code, you must possess some
knowledge that convinces you the conversion is safe. In that case, we
need only allow the type system to have that same knowledge, and the
problem is solved.
(One thing worth pointing out here is that it's quite possible that you
want to do something different depending on the kind of data. In that
case, the sufficiently powerful type system would need to have rules so
that an if statemement creates a modified type environment to take that
into account. This is different from a runtime type check, in that you
are writing explicit code that provides correct program behavior in
either case.)