Skip to content

Commit

Permalink
Improve precision of nfields_tfunc on Union (JuliaLang#37497)
Browse files Browse the repository at this point in the history
`nfields_tfunc(Tuple{Int, Union{Int, Float64}})` gave `Const(2)`,
but `nfields_tfunc(Union{Tuple{Int, Float64}, Tuple{Int, Int}})` gave
`Int`. In general, it's not great for the tfuncs to give different
answers when given `==` types, because other parts of the system
will happily substitute such types without changes to the user code,
which can change the inference result and lead to instability.
  • Loading branch information
Keno authored Sep 13, 2020
1 parent 85a0f14 commit 938fdaa
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
5 changes: 5 additions & 0 deletions base/compiler/tfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,11 @@ function nfields_tfunc(@nospecialize(x))
return Const(isdefined(x, :types) ? length(x.types) : length(x.name.names))
end
end
if isa(x, Union)
na = nfields_tfunc(x.a)
na === Int && return Int
return tmerge(na, nfields_tfunc(x.b))
end
return Int
end
add_tfunc(nfields, 1, 1, nfields_tfunc, 1)
Expand Down
1 change: 1 addition & 0 deletions test/compiler/inference.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1435,6 +1435,7 @@ end
@test nfields_tfunc(Type{Union{}}) === Const(0)
@test nfields_tfunc(Tuple{Int, Vararg{Int}}) === Int
@test nfields_tfunc(Tuple{Int, Integer}) === Const(2)
@test nfields_tfunc(Union{Tuple{Int, Float64}, Tuple{Int, Int}}) === Const(2)

using Core.Compiler: typeof_tfunc
@test typeof_tfunc(Tuple{Vararg{Int}}) == Type{Tuple{Vararg{Int,N}}} where N
Expand Down

0 comments on commit 938fdaa

Please sign in to comment.