Skip to content

Commit

Permalink
Merge pull request #29600 from tpapp/tp/add-fieldtypes
Browse files Browse the repository at this point in the history
Add Base.fieldtypes.
  • Loading branch information
JeffBezanson authored Nov 1, 2018
2 parents 51683c4 + e33a266 commit 6d416e4
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,7 @@ export
fieldname,
fieldnames,
fieldcount,
fieldtypes,
propertynames,
isabstracttype,
isbitstype,
Expand Down
18 changes: 18 additions & 0 deletions base/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,24 @@ function fieldcount(@nospecialize t)
return length(t.types)
end

"""
fieldtypes(T::Type)
The declared types of all fields in a composite DataType `T` as a tuple.
# Examples
```jldoctest
julia> struct Foo
x::Int64
y::String
end
julia> fieldtypes(Foo)
(Int64, String)
```
"""
fieldtypes(T::Type) = ntuple(i -> fieldtype(T, i), fieldcount(T))

# return all instances, for types that can be enumerated

"""
Expand Down
1 change: 1 addition & 0 deletions doc/src/base/base.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ Base.isconcretetype
Base.isbits
Base.isbitstype
Core.fieldtype
Base.fieldtypes
Base.fieldcount
Base.fieldoffset
Base.datatype_alignment
Expand Down
4 changes: 4 additions & 0 deletions test/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,10 @@ tlayout = TLayout(5,7,11)
@test fieldtype((NamedTuple{(:a,:b),T} where T<:Tuple{Vararg{Integer}}), 2) === Integer
@test_throws BoundsError fieldtype(NamedTuple{(:a,:b)}, 3)

@test fieldtypes(NamedTuple{(:a,:b)}) == (Any, Any)
@test fieldtypes((NamedTuple{T,Tuple{Int,String}} where T)) === (Int, String)
@test fieldtypes(TLayout) === (Int8, Int16, Int32)

import Base: datatype_alignment, return_types
@test datatype_alignment(UInt16) == 2
@test datatype_alignment(TLayout) == 4
Expand Down

0 comments on commit 6d416e4

Please sign in to comment.