authorgravatar for john.schmidt.h@gmail.comJohn Schmidt <john.schmidt.h@gmail.com> 2022-04-03 14:01:06+02:00
committergravatar for john.schmidt.h@gmail.comJohn Schmidt <john.schmidt.h@gmail.com> 2022-04-03 14:28:03+02:00
log174a889364d285e32534016f7425e8adaf9cab3c
tree855977e2558d4a68bde85d8ce17da75924cdaada
parentfd1ce329b3f978a4ac2ae272afee7f07b5841990

sema: add compile error for duplicate union field


2 files changed, 31 insertions(+), 1 deletions(-)

src/Sema.zig+16-1
...@@ -22215,7 +22215,22 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil...@@ -22215,7 +22215,22 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
22215 }22215 }
2221622216
22217 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);22217 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
22218 assert(!gop.found_existing);22218 if (gop.found_existing) {
22219 const msg = msg: {
22220 const tree = try sema.getAstTree(&block_scope);
22221 const field_src = enumFieldSrcLoc(decl, tree.*, union_obj.node_offset, field_i);
22222 const msg = try sema.errMsg(&block_scope, field_src, "duplicate union field: '{s}'", .{field_name});
22223 errdefer msg.destroy(gpa);
22224
22225 const prev_field_index = union_obj.fields.getIndex(field_name).?;
22226 const prev_field_src = enumFieldSrcLoc(decl, tree.*, union_obj.node_offset, prev_field_index);
22227 try sema.mod.errNoteNonLazy(prev_field_src.toSrcLoc(decl), msg, "other field here", .{});
22228 try sema.errNote(&block_scope, src, msg, "union declared here", .{});
22229 break :msg msg;
22230 };
22231 return sema.failWithOwnedErrorMsg(&block_scope, msg);
22232 }
22233
22219 gop.value_ptr.* = .{22234 gop.value_ptr.* = .{
22220 .ty = try field_ty.copy(decl_arena_allocator),22235 .ty = try field_ty.copy(decl_arena_allocator),
22221 .abi_align = 0,22236 .abi_align = 0,
test/compile_errors/stage2/union_duplicate_field_definition.zig created+15
...@@ -0,0 +1,15 @@
1const U = union {
2 foo: u32,
3 foo: u32,
4};
5
6export fn entry() void {
7 const u: U = .{ .foo = 100 };
8 _ = u;
9}
10
11// duplicate union field name
12//
13// :3:5: error: duplicate union field: 'foo'
14// :2:5: note: other field here
15// :1:11: note: union declared here