[swift-evolution] Simplified Conversion of Integer Types
clattner at apple.com
Tue Jan 19 23:12:10 CST 2016
On Jan 19, 2016, at 6:57 PM, John McCall <rjmccall at apple.com> wrote:
>> The first two are a strong goal for swift 3, the later is "nice to have” if it fits since it is “just” sugar and there is a lot of other stuff going on. We are also interested in introducing a proper BigInt type, but that is even “nicer to have” for Swift 3.
> Random thoughts here:
> Integer promotions are nice for arithmetic, but they can mask bugs for “reinterpret” style conversions. You don’t want an Int32 to Double/UnsafePointer reinterpretation to implicitly promote to Int64; you want it to be a compiler error. But that’s a special-case limitation that can reasonably be directly addressed on those APIs.
> It's probably reasonably to have general rules that allow integer arithmetic to just promote to the wider type, but I don’t think we can do common-type promotion without special knowledge of type rank.
> My understanding is that numerics people don’t love implicit promotions between floating-point types. Float promotions and conversions are comparatively expensive, and they can introduce subtle rounding bugs; the standard advice is that programmers should be writing their code to avoid them.
> Integer-to-float promotions have similar performance issues as float promotions, and IntN -> FloatN is technically lossy.
We should discuss this in more detail when and if it comes up and fits into Swift 3.
I’m imagining a real ranking scheme for integer types, involving value preserving promotions from smaller to larger types. For floating point, it would be Float->Double->CGFloat, even though Double->CGFloat is lossy on 32-bit targets. The key to making this work great in swift is to only introduce a promotion if the destination type is already in the system, and to “punish” the promotion by adding a cost to the solution (thus preferencing cheaper solutions).
I’m aware of at least some of the reasons that numerics people dislike promotions (some of which don’t translate to Swift, like when people write “somefloat+4.0” when they should have written “somefloat+4.0f”), and I believe that this approach would solve them.
We will need specific design and iteration on this approach though (again, when there is time to do the implementation and evaluation) because at this point it is just a hand wavy idea.
More information about the swift-evolution