Skip to content

Commit 45787ea

Browse files
committed
Allow creating constants with the same type.
1 parent 05a318f commit 45787ea

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/core/value/constant.jl

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,10 +238,15 @@ function ConstantStruct(value::T, ctx::Context=GlobalContext(); name=String(name
238238

239239
if anonymous
240240
ConstantStruct(constants, ctx; packed=packed)
241+
elseif haskey(types(ctx), name)
242+
typ = types(ctx)[name]
243+
if collect(elements(typ)) != llvmtype.(constants)
244+
throw(ArgumentError("Cannot create struct $name {$(join(llvmtype.(constants), ", "))} as it is already defined in this context as {$(join(elements(typ), ", "))}."))
245+
end
246+
ConstantStruct(typ, constants)
241247
else
242-
# check if this name already exists in the context
243-
haskey(types(ctx), name) && throw(ArgumentError("Type name '$name' is already used in this context. Use a different context, name, or request an anonymous struct."))
244248
typ = StructType(name, ctx)
249+
elements!(typ, llvmtype.(constants))
245250
ConstantStruct(typ, constants)
246251
end
247252
end

test/core.jl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ struct TestStruct
44
z::Float16
55
end
66

7+
struct AnotherTestStruct
8+
x::Int
9+
end
10+
711
struct TestSingleton
812
end
913

@@ -478,7 +482,11 @@ Context() do ctx
478482
]
479483
@test collect(operands(constant_struct)) == expected_operands
480484

481-
@test_throws ArgumentError ConstantStruct(test_struct, ctx)
485+
# re-creating the same type shouldn't fail
486+
ConstantStruct(TestStruct(true, 42, 0), ctx)
487+
# unless it's a conflicting type
488+
@test_throws ArgumentError ConstantStruct(AnotherTestStruct(1), ctx; name="TestStruct")
489+
482490
end
483491
let
484492
test_struct = TestSingleton()

0 commit comments

Comments
 (0)