Skip to content

Commit

Permalink
Prevent invalidations from eltype(::Type{<:NamedTuple}) (#36921)
Browse files Browse the repository at this point in the history
This provides a fallback `eltype` method specialized for imprecise
NamedType types. Formerly we were calling the generic eltype fallback
`eltype(::Type) = Any`, but relying on the generic fallback makes
code vulnerable to invalidation when new `eltype` methods are added.
Since this affects any poorly-inferred keyword-arg function,
it's best to isolate this by defining a specialization.
  • Loading branch information
timholy authored Aug 5, 2020
1 parent 371bfa8 commit 59a87ee
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
4 changes: 3 additions & 1 deletion base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ function show(io::IO, t::NamedTuple)
end
end

eltype(::Type{NamedTuple{names,T}} where names) where {T} = eltype(T)
eltype(::Type{T}) where T<:NamedTuple = nteltype(T)
nteltype(::Type) = Any
nteltype(::Type{NamedTuple{names,T}} where names) where {T} = eltype(T)

==(a::NamedTuple{n}, b::NamedTuple{n}) where {n} = Tuple(a) == Tuple(b)
==(a::NamedTuple, b::NamedTuple) = false
Expand Down
15 changes: 13 additions & 2 deletions test/worlds.jl
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ function instance(f, types)
for i = 1:length(specs)
if isassigned(specs, i)
mi = specs[i]::Core.MethodInstance
if mi.specTypes === tt
if mi.specTypes <: tt && tt <: mi.specTypes
inst = mi
break
end
Expand Down Expand Up @@ -324,6 +324,18 @@ abstract type Colorant35855 end
Base.convert(::Type{C}, c) where {C<:Colorant35855} = false
@test worlds(mi) == w

# NamedTuple and extensions of eltype
outer(anyc) = inner(anyc[])
inner(s::Union{Vector,Dict}; kw=false) = inneri(s, kwi=maximum(s), kwb=kw)
inneri(s, args...; kwargs...) = inneri(IOBuffer(), s, args...; kwargs...)
inneri(io::IO, s::Union{Vector,Dict}; kwi=0, kwb=false) = (print(io, first(s), " "^kwi, kwb); String(take!(io)))
@test outer(Ref{Any}([1,2,3])) == "1 false"
mi = instance(Core.kwfunc(inneri), (NamedTuple{(:kwi,:kwb),TT} where TT<:Tuple{Any,Bool}, typeof(inneri), Vector{T} where T))
w = worlds(mi)
abstract type Container{T} end
Base.eltype(::Type{C}) where {T,C<:Container{T}} = T
@test worlds(mi) == w

# invoke_in_world
f_inworld(x) = "world one; x=$x"
g_inworld(x; y) = "world one; x=$x, y=$y"
Expand All @@ -336,4 +348,3 @@ wc_aiw2 = get_world_counter()
@test Base.invoke_in_world(wc_aiw2, f_inworld, 2) == "world two; x=2"
@test Base.invoke_in_world(wc_aiw1, g_inworld, 2, y=3) == "world one; x=2, y=3"
@test Base.invoke_in_world(wc_aiw2, g_inworld, 2, y=3) == "world two; x=2, y=3"

0 comments on commit 59a87ee

Please sign in to comment.