Skip to content

Commit 24fb6d1

Browse files
authored
Make @intFromEnum an error for empty enums
1 parent 52066bf commit 24fb6d1

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/Sema.zig

+14-1
Original file line numberDiff line numberDiff line change
@@ -8629,6 +8629,7 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
86298629
.{src},
86308630
);
86318631
};
8632+
86328633
break :blk try sema.unionToTag(block, tag_ty, operand, operand_src);
86338634
},
86348635
else => {
@@ -8638,14 +8639,25 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
86388639
},
86398640
};
86408641
const enum_tag_ty = sema.typeOf(enum_tag);
8641-
86428642
const int_tag_ty = enum_tag_ty.intTagType(mod);
86438643

8644+
// TODO: use correct solution
8645+
// https://github.com/ziglang/zig/issues/15909
8646+
if (enum_tag_ty.enumFieldCount(mod) == 0 and !enum_tag_ty.isNonexhaustiveEnum(mod)) {
8647+
return sema.fail(block, operand_src, "cannot use @intFromEnum on empty enum '{}'", .{
8648+
enum_tag_ty.fmt(mod),
8649+
});
8650+
}
8651+
86448652
if (try sema.typeHasOnePossibleValue(enum_tag_ty)) |opv| {
86458653
return Air.internedToRef((try mod.getCoerced(opv, int_tag_ty)).toIntern());
86468654
}
86478655

86488656
if (try sema.resolveValue(enum_tag)) |enum_tag_val| {
8657+
if (enum_tag_val.isUndef(mod)) {
8658+
return mod.undefRef(int_tag_ty);
8659+
}
8660+
86498661
const val = try enum_tag_val.intFromEnum(enum_tag_ty, mod);
86508662
return Air.internedToRef(val.toIntern());
86518663
}
@@ -20944,6 +20956,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2094420956
if (enum_ty.enumFieldCount(mod) == 0) {
2094520957
// TODO I don't think this is the correct way to handle this but
2094620958
// it prevents a crash.
20959+
// https://github.com/ziglang/zig/issues/15909
2094720960
return sema.fail(block, operand_src, "cannot get @tagName of empty enum '{}'", .{
2094820961
enum_ty.fmt(mod),
2094920962
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export fn a() void {
2+
const E = enum {};
3+
var e: E = undefined;
4+
_ = &e;
5+
_ = @intFromEnum(e);
6+
}
7+
8+
// error
9+
// backend=stage2
10+
// target=native
11+
//
12+
// :5:22: error: cannot use @intFromEnum on empty enum 'tmp.a.E'

0 commit comments

Comments
 (0)