Skip to content

Commit 71a478b

Browse files
vtjnashJeffBezanson
authored andcommitted
implement fieldnames reflection for Tuples (#16540)
fix #14858
1 parent efc9a1e commit 71a478b

2 files changed

Lines changed: 6 additions & 0 deletions

File tree

base/reflection.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ end
5757
Get the name of field `i` of a `DataType`.
5858
"""
5959
fieldname(t::DataType, i::Integer) = t.name.names[i]::Symbol
60+
fieldname{T<:Tuple}(t::Type{T}, i::Integer) = i < 1 || i > nfields(t) ? throw(BoundsError(t, i)) : Int(i)
6061

6162
"""
6263
fieldnames(x::DataType)
@@ -71,6 +72,7 @@ function fieldnames(v)
7172
return fieldnames(t)
7273
end
7374
fieldnames(t::DataType) = Symbol[fieldname(t, n) for n in 1:nfields(t)]
75+
fieldnames{T<:Tuple}(t::Type{T}) = Int[n for n in 1:nfields(t)]
7476

7577
isconst(s::Symbol) = ccall(:jl_is_const, Int32, (Ptr{Void}, Any), C_NULL, s) != 0
7678

test/reflection.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,10 @@ tlayout = TLayout(5,7,11)
251251
@test_throws BoundsError fieldname(TLayout, 4)
252252
@test_throws BoundsError fieldoffset(TLayout, 4)
253253

254+
@test fieldnames((1,2,3)) == fieldnames(NTuple{3, Int}) == [fieldname(NTuple{3, Int}, i) for i = 1:3] == [1, 2, 3]
255+
@test_throws BoundsError fieldname(NTuple{3, Int}, 0)
256+
@test_throws BoundsError fieldname(NTuple{3, Int}, 4)
257+
254258
import Base: isstructtype, type_alignment, return_types
255259
@test !isstructtype(Union{})
256260
@test !isstructtype(Union{Int,Float64})

0 commit comments

Comments
 (0)