Skip to content

Commit 52c03de

Browse files
committed
add missing compile error for OpaqueType inside structs/unions
closes #1862
1 parent e03c770 commit 52c03de

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/analyze.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2679,6 +2679,13 @@ static Error resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type) {
26792679
buf_sprintf("enums, not structs, support field assignment"));
26802680
}
26812681

2682+
if (field_type->id == ZigTypeIdOpaque) {
2683+
add_node_error(g, field_node->data.struct_field.type,
2684+
buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in structs"));
2685+
struct_type->data.structure.resolve_status = ResolveStatusInvalid;
2686+
continue;
2687+
}
2688+
26822689
switch (type_requires_comptime(g, field_type)) {
26832690
case ReqCompTimeYes:
26842691
struct_type->data.structure.requires_comptime = true;
@@ -2963,6 +2970,13 @@ static Error resolve_union_zero_bits(CodeGen *g, ZigType *union_type) {
29632970
}
29642971
union_field->type_entry = field_type;
29652972

2973+
if (field_type->id == ZigTypeIdOpaque) {
2974+
add_node_error(g, field_node->data.struct_field.type,
2975+
buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in unions"));
2976+
union_type->data.unionation.is_invalid = true;
2977+
continue;
2978+
}
2979+
29662980
switch (type_requires_comptime(g, field_type)) {
29672981
case ReqCompTimeInvalid:
29682982
union_type->data.unionation.is_invalid = true;

test/compile_errors.zig

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
const tests = @import("tests.zig");
22

33
pub fn addCases(cases: *tests.CompileErrorContext) void {
4+
cases.addTest(
5+
"directly embedding opaque type in struct and union",
6+
\\const O = @OpaqueType();
7+
\\const Foo = struct {
8+
\\ o: O,
9+
\\};
10+
\\const Bar = union {
11+
\\ One: i32,
12+
\\ Two: O,
13+
\\};
14+
\\export fn a() void {
15+
\\ var foo: Foo = undefined;
16+
\\}
17+
\\export fn b() void {
18+
\\ var bar: Bar = undefined;
19+
\\}
20+
,
21+
".tmp_source.zig:3:8: error: opaque types have unknown size and therefore cannot be directly embedded in structs",
22+
".tmp_source.zig:7:10: error: opaque types have unknown size and therefore cannot be directly embedded in unions",
23+
);
24+
425
cases.addTest(
526
"implicit cast between C pointer and Zig pointer - bad const/align/child",
627
\\export fn a() void {

0 commit comments

Comments
 (0)