Commit b67378fb08

Andrew Kelley <andrew@ziglang.org>
2021-04-08 06:04:55
Sema: `@intToEnum` error msg includes a "declared here" hint
1 parent a62e19e
Changed files (2)
src
test
stage2
src/Sema.zig
@@ -1983,9 +1983,23 @@ fn zirIntToEnum(sema: *Sema, block: *Scope.Block, inst: zir.Inst.Index) InnerErr
 
     if (try sema.resolveDefinedValue(block, operand_src, operand)) |int_val| {
         if (!dest_ty.enumHasInt(int_val, target)) {
-            return mod.fail(&block.base, src, "enum '{}' has no tag with value {}", .{
-                dest_ty, int_val,
-            });
+            const msg = msg: {
+                const msg = try mod.errMsg(
+                    &block.base,
+                    src,
+                    "enum '{}' has no tag with value {}",
+                    .{ dest_ty, int_val },
+                );
+                errdefer msg.destroy(sema.gpa);
+                try mod.errNoteNonLazy(
+                    dest_ty.declSrcLoc(),
+                    msg,
+                    "enum declared here",
+                    .{},
+                );
+                break :msg msg;
+            };
+            return mod.failWithOwnedErrorMsg(&block.base, msg);
         }
         return mod.constInst(arena, src, .{
             .ty = dest_ty,
test/stage2/cbe.zig
@@ -674,6 +674,34 @@ pub fn addCases(ctx: *TestContext) !void {
             ":1:28: error: duplicate enum tag",
             ":1:22: note: other tag here",
         });
+
+        case.addError(
+            \\export fn foo() void {
+            \\    const a = true;
+            \\    const b = @enumToInt(a);
+            \\}
+        , &.{
+            ":3:26: error: expected enum or tagged union, found bool",
+        });
+
+        case.addError(
+            \\export fn foo() void {
+            \\    const a = 1;
+            \\    const b = @intToEnum(bool, a);
+            \\}
+        , &.{
+            ":3:26: error: expected enum, found bool",
+        });
+
+        case.addError(
+            \\const E = enum { a, b, c };
+            \\export fn foo() void {
+            \\    const b = @intToEnum(E, 3);
+            \\}
+        , &.{
+            ":3:15: error: enum 'E' has no tag with value 3",
+            ":1:11: note: enum declared here",
+        });
     }
 
     ctx.c("empty start function", linux_x64,