JuliaData / StructTypes.jl

Abstract definitions and convenience methods for describing, processing, and constructing Julia objects
https://juliadata.github.io/StructTypes.jl/stable/
MIT License
80 stars 22 forks source link

Named tuples not converting #72

Closed zot closed 2 years ago

zot commented 2 years ago

Hi, I'm getting this error trying to convert a NamedTuple to store in a NamedTuple field:

ERROR: ArgumentError: type does not have a definite number of fields
Stacktrace:
  [1] fieldcount(t::Any)
    @ Base ./reflection.jl:729
  [2] construct
    @ ~/.julia/packages/StructTypes/Cmlkm/src/StructTypes.jl:573 [inlined]
  [3] constructfrom(#unused#::StructTypes.UnorderedStruct, #unused#::Type{NamedTuple}, #unused#::StructTypes.UnorderedStruct, obj::NamedTuple{(), Tuple{}})
    @ StructTypes ~/.julia/packages/StructTypes/Cmlkm/src/StructTypes.jl:1046
  [4] constructfrom
    @ ~/.julia/packages/StructTypes/Cmlkm/src/StructTypes.jl:1018 [inlined]
  [5] constructfrom(#unused#::Type{NamedTuple}, obj::NamedTuple{(), Tuple{}})
    @ StructTypes ~/.julia/packages/StructTypes/Cmlkm/src/StructTypes.jl:905
  [6] StructClosure
    @ ~/.julia/packages/StructTypes/Cmlkm/src/StructTypes.jl:1041 [inlined]

I made some definitions that seem to fix it, what do you think (seems like both Struct and UnorderedStruct are needed)?

constructfrom(::Struct, ::Type{ST}, ::Struct, obj::OT) where {ST <: NamedTuple, OT <: ST} = obj
constructfrom(::UnorderedStruct, ::Type{ST}, ::UnorderedStruct, obj::OT) where {ST <: NamedTuple, OT <: ST} = obj
zot commented 2 years ago

This definition seems to capture both and also work:

StructTypes.constructfrom(::Struct, ::Type{ST}, ::Struct, obj::NamedTuple) where {ST <: NamedTuple} =
    obj
zot commented 2 years ago

This is just to make NamedTuple{} work, like when you use a NamedTuple as a kind of JS object. Going through the whole UnorderedStruct process is better because it checks field by field...

zot commented 2 years ago

I didn't see this issue before: https://github.com/JuliaData/StructTypes.jl/issues/68 -- I searched for named and didn't find any matching issues -- didn't realize GitHub doesn't seem to match on partial words

quinnj commented 2 years ago

After discussing examples with @zot, I think this is resolved in the latest release.