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

Covariance support for @NamedTuple #43513

Closed
wants to merge 3 commits into from
Closed
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
19 changes: 11 additions & 8 deletions base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -396,13 +396,16 @@ NamedTuple{(:a, :b), Tuple{Float64, String}}
!!! compat "Julia 1.5"
This macro is available as of Julia 1.5.
"""
macro NamedTuple(ex)
Meta.isexpr(ex, :braces) || Meta.isexpr(ex, :block) ||
throw(ArgumentError("@NamedTuple expects {...} or begin...end"))
decls = filter(e -> !(e isa LineNumberNode), ex.args)
all(e -> e isa Symbol || Meta.isexpr(e, :(::)), decls) ||
macro NamedTuple(x)
Meta.isexpr(x, (:braces, :block)) || throw(ArgumentError("@NamedTuple expects {...} or begin...end"))
covar = Meta.isexpr(x,:braces,1) && Meta.isexpr(x.args[1], :<:)
covar && (x = x.args[1])
xdecls = filter(xa -> !(xa isa LineNumberNode), x.args)
all(xa -> xa isa Symbol || Meta.isexpr(xa, :(::)), xdecls) ||
throw(ArgumentError("@NamedTuple must contain a sequence of name or name::type expressions"))
vars = [QuoteNode(e isa Symbol ? e : e.args[1]) for e in decls]
types = [esc(e isa Symbol ? :Any : e.args[2]) for e in decls]
return :(NamedTuple{($(vars...),), Tuple{$(types...)}})
vars = [QuoteNode(xa isa Symbol ? xa : xa.args[1]) for xa in xdecls]
types = [esc(xa isa Symbol ? :Any : xa.args[2]) for xa in xdecls]
covar ?
:(NamedTuple{($(vars...),), <:Tuple{$(types...)}}) :
:(NamedTuple{($(vars...),), Tuple{$(types...)}})
end
4 changes: 4 additions & 0 deletions test/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,10 @@ end
@test @NamedTuple{a::Int, b} === NamedTuple{(:a, :b),Tuple{Int,Any}}
@test_throws LoadError include_string(Main, "@NamedTuple{a::Int, b, 3}")
@test_throws LoadError include_string(Main, "@NamedTuple(a::Int, b)")
@test (a=1,b=true) isa @NamedTuple{a::Int, b::Bool}
@test (a=1,b=true) isa @NamedTuple{<:(a::Int, b::Bool)}
@test (a=1,b=true) isa @NamedTuple{<:(a::Int, b::Union{Bool,Nothing})}
@test (a=1,b=nothing) isa @NamedTuple{<:(a::Int, b::Union{Bool,Nothing})}
end

# issue #29333, implicit names
Expand Down