Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type-stable constructorof(::Type{<:NamedTuple})(args...) #17

Merged
merged 3 commits into from
Oct 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions src/ConstructionBase.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ T{Int64,Int64}(10, 2)
getfield(parentmodule(T), nameof(T))
end

constructorof(::Type{<:Tuple}) = tuple
constructorof(::Type{<:NamedTuple{names}}) where names =
NamedTupleConstructor{names}()

struct NamedTupleConstructor{names} end

@generated function (::NamedTupleConstructor{names})(args...) where names
quote
Base.@_inline_meta
$(NamedTuple{names, Tuple{args...}})(args)
end
end

function assert_hasfields(T, fnames)
for fname in fnames
if !(fname in fieldnames(T))
Expand Down Expand Up @@ -150,15 +163,5 @@ end
)
end

@generated function setproperties(obj::NamedTuple, patch::NamedTuple)
# this function is only generated to force the following check
# at compile time
assert_hasfields(obj, fieldnames(patch))
Expr(:block,
Expr(:meta, :inline),
:(merge(obj, patch))
)
end


end # module
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ end
@inferred constructorof(AB{Int, Int})
@test constructorof(AB{Int, Int})(1, 2) === AB(1,2)
@test constructorof(AB{Int, Int})(1.0, 2) === AB(1.0,2)
@test constructorof(typeof((a=1, b=2)))(1.0, 2) === (a=1.0, b=2)
@test constructorof(NamedTuple{(:a, :b)})(1.0, 2) === (a=1.0, b=2)
@test constructorof(Tuple)(1.0, 2) === (1.0, 2)
@test constructorof(Tuple{Nothing, Missing})(1.0, 2) === (1.0, 2)
end

@testset "setproperties" begin
Expand Down