Skip to content

Commit

Permalink
Prefer small unions when generating types from json objects/arrays (#144
Browse files Browse the repository at this point in the history
)

* Prefer small unions when generating types from json objects/arrays

Fixes #141. In general, the Julia compiler handles Union types really
well these days, so let's prefer them when generating types. Users are
of course always free to modify the generated file if the generated
Union field is too strict.

* fix test
  • Loading branch information
quinnj authored Apr 13, 2021
1 parent fed2ed7 commit c73edd7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/gentypes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@ struct Top end
get_type(NT, k) = hasfield(NT, k) ? fieldtype(NT, k) : Nothing

# unify two types to a single type
function promoteunion(T, S)
new = promote_type(T, S)
return isabstracttype(new) ? Union{T, S} : new
end

unify(a, b) = unify(b, a)
unify(a::Type{T}, b::Type{S}) where {T,S} = Base.promote_typejoin(T, S)
unify(a::Type{T}, b::Type{S}) where {T,S} = promoteunion(T, S)
unify(a::Type{T}, b::Type{S}) where {T,S<:T} = T
unify(a::Type{Top}, b::Type{T}) where {T} = T

Expand Down
1 change: 1 addition & 0 deletions test/gentypes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@

@test !(JSONTypes.Root.mutable)
@test parsed[1].c.d == 4
@test fieldtype(JSONTypes.Root, 1) == Union{Int64, String}
end

@testset "Raw Types" begin
Expand Down

0 comments on commit c73edd7

Please sign in to comment.