From c73edd78e955b41c416d9b6e3134982fbbb4a895 Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Tue, 13 Apr 2021 08:34:54 -0600 Subject: [PATCH] Prefer small unions when generating types from json objects/arrays (#144) * 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 --- src/gentypes.jl | 7 ++++++- test/gentypes.jl | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/gentypes.jl b/src/gentypes.jl index 02bd0df..1c32a06 100644 --- a/src/gentypes.jl +++ b/src/gentypes.jl @@ -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 diff --git a/test/gentypes.jl b/test/gentypes.jl index e0e4a13..9cf6897 100644 --- a/test/gentypes.jl +++ b/test/gentypes.jl @@ -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