Type conversion issues - BenoitKnecht/julia GitHub Wiki

We need both implicit and explicit conversions

implicit conversions can be inserted at compile time, avoiding the overhead of processing them at dispatch time: without conversion, dispatch is O(log(Nmethods)*Nargs) with it, dispatch is O(log(Nmethods)*Nargs*log(Nconversions)), plus there may be a hell of a linear slowdown.

in fortress, every value has an explicit static type as well as a dynamic type. conversions are inserted based solely on static types, which (as they fully admit) may lead to doing a conversion even if the real, run-time type of a value would match a method without conversion. this is wrong. in julia there are only dynamic types, and static types are estimates of those. if the estimates aren't good enough, we must defer to run time.

so the compiler could insert a conversion iff it can prove that one is appropriate, otherwise it defers to run time. searching for a valid conversion is only done if a method wouldn't be found otherwise, so the compiler can at least speed up dispatch by avoiding run-time conversion.

but we still need to mark whether a conversion is "safe", e.g.

int8 -> int32 is safe, automatic
int32 -> int8 can be done, but never implicitly

Types of numeric literals

if we have

function f(x)
  return x+1
end

We want this to be of type A-->A for ALL scalar types A. If "1" is considered an int32, narrower types will be clobbered and you won't get the specialized code you want. MATLAB solves this by narrowing everything, but this is just as bad.

A good solution (from fortress) is to have a different type for literals, implicitly convertible to any numeric type. You would have both IntLiteral and FloatLiteral.

A detail is picking a default type to convert to when there is no other information, for example "x = 1+2". There are many applicable + methods, all with the same specificity (int8+int8 is just as specific as int32+int32). This seems solvable by carefully ordering methods of the same specificity to give priority to preferred types, say int32 and double.

This mechanism can be quite powerful. For example, we could have an object pi of type Pi, and a type Bignum[N] (meaning arbitrary-precision numbers with N digits). You could write a conversion::Pi-->Bignum[N] that computes pi to N digits!

⚠️ **GitHub.com Fallback** ⚠️