Skip to content

Commit

Permalink
Fix type-instability of ∘ and Some when wrapping types (JuliaLang#35980)
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed May 24, 2020
1 parent dd3f173 commit 0413ef0
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 1 deletion.
18 changes: 17 additions & 1 deletion base/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -873,10 +873,26 @@ julia> ∘(fs...)(3)
```
"""
function end

struct ComposedFunction{F,G} <: Function
f::F
g::G
ComposedFunction{F, G}(f, g) where {F, G} = new{F, G}(f, g)
ComposedFunction(f, g) = new{Core.Typeof(f),Core.Typeof(g)}(f, g)
end

(c::ComposedFunction)(x...) = c.f(c.g(x...))

(f) = f
(f, g) = (x...)->f(g(x...))
(f, g) = ComposedFunction(f, g)
(f, g, h...) = (f g, h...)

function show(io::IO, c::ComposedFunction)
show(io, c.f)
print(io, "")
show(io, c.g)
end

"""
!f::Function
Expand Down
2 changes: 2 additions & 0 deletions base/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ function show(io::IO, ::MIME"text/plain", f::Function)
end
end

show(io::IO, ::MIME"text/plain", c::ComposedFunction) = show(io, c)

function show(io::IO, ::MIME"text/plain", iter::Union{KeySet,ValueIterator})
isempty(iter) && get(io, :compact, false) && return show(io, iter)
summary(io, iter)
Expand Down
2 changes: 2 additions & 0 deletions base/some.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ struct Some{T}
value::T
end

Some(::Type{T}) where {T} = Some{Type{T}}(T)

promote_rule(::Type{Some{T}}, ::Type{Some{S}}) where {T, S<:T} = Some{T}

nonnothingtype(::Type{T}) where {T} = Core.Compiler.typesubtract(T, Nothing)
Expand Down
2 changes: 2 additions & 0 deletions test/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714
@test (FreeMagma(1), FreeMagma(2)) === FreeMagma((1,2))
@test (FreeMagma(1), FreeMagma(2), FreeMagma(3)) === FreeMagma(((1,2), 3))
@test (FreeMagma(1), FreeMagma(2), FreeMagma(3), FreeMagma(4)) === FreeMagma((((1,2), 3), 4))

@test fieldtypes(typeof(Float64 Int)) == (Type{Float64}, Type{Int})
end

@testset "function negation" begin
Expand Down
3 changes: 3 additions & 0 deletions test/some.jl
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,6 @@ using Base: notnothing
# isnothing()
@test !isnothing(1)
@test isnothing(nothing)

# type stability
@test fieldtype(typeof(Some(Int)), 1) === Type{Int}

0 comments on commit 0413ef0

Please sign in to comment.