better compile-time evaluation of type expressions #7060
Description
Right now, Julia does not seem to do a good job of partially evaluating type expressions that are known at compile time. For example:
f{T}(x::T) = T <: Real ? 1 : 2
should be compiled to f(x) = 1
for f(3)
or f(x) = 2
for f(4+5im)
, but code_native(f, (Int,))
reveals that this is not the case: in fact, the code for this function is quite involved. Fixed by #7088.
It would be nice to have this work for cases where using dispatch is impractical, especially in macros. For example, as discussed in #7033, I would like to generalize the @horner
macro to use a better algorithm for cases where the argument is complex but the coefficients are real, but it should inline to the correct code depending upon the argument type.
Another example that should be possible to evaluate at compile time is:
g{T}(x::T) = method_exists(one, (T,)) ? 1 : 2
Explicit method_exists
checks are used, for example, in reducedim.jl
and multimedia.jl
. (It might be good to evaluate this statically only if method_exists
returns true
, to preserve the current dynamic behavior.)
A third example mentioned on the mailing list in the context of better type promotion for Array*Number
for SIUnits
quantities is that it would be nice to have isleaftype(T)
evaluated at compile time. (Partially fixed by #7088.)
Activity