Skip to content

Commit

Permalink
Improve handling of variants with same name (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tortar authored Aug 20, 2024
1 parent 1324c07 commit eacff43
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/DynamicSumTypes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,17 @@ macro sumtype(typedef)
typename = namify(type)
typeparams = type isa Symbol ? [] : type.args[2:end]
variants = type_with_variants.args[2:end]
!allunique(variants) && error("Duplicated variants in sumtype")
variants_with_P = [v for v in variants if v isa Expr && !isempty(intersect(typeparams, v.args[2:end]))]

variants_names = namify.([v isa Expr && v.head == :call && v.args[1] == :typeof ? v.args[2] : v for v in variants])
check_if_typeof(v) = v isa Expr && v.head == :call && v.args[1] == :typeof
variants_names = namify.([check_if_typeof(v) ? v.args[2] : v for v in variants])
for vname in unique(variants_names)
inds = findall(==(vname), variants_names)
length(inds) == 1 && continue
for (k, i) in enumerate(inds)
variants_names[i] = Symbol(variants_names[i], k)
variant_args = check_if_typeof(variants[i]) ? variants[i].args[2] : variants[i].args
variants_names[i] = Symbol([i == length(variant_args) ? a : Symbol(a, :_) for (i, a) in enumerate(variant_args)]...)
end
end

Expand Down
4 changes: 4 additions & 0 deletions test/sumtype_macro_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ struct None end

@test allvariants(E) == allvariants(typeof(f)) == (F = F, G = G, H = H)

ff1 = FF(F((1,1), (1.0, 1.0), :s))
ff2 = FF(F((Int32(1),Int32(1)), (1.0, 1.0), :s))
@test allvariants(FF) == (F_Int32 = F{Int32}, F_Int64 = F{Int64})

hawk_1 = Animal(Hawk(1.0, 2.0, 3))
hawk_2 = Animal(Hawk(; ground_speed = 2.3, flight_speed = 2))
wolf_1 = Animal(Wolf(2.0, 3.0, :black))
Expand Down

0 comments on commit eacff43

Please sign in to comment.