Commit 943176bbfc

Will Lillis <wlillis@umass.edu>
2024-09-23 22:04:24
fix: Add error note when attempt is made to destructure error union (#21491)
closes #21417
1 parent 5096397
Changed files (2)
src
test
cases
src/Sema.zig
@@ -5428,6 +5428,9 @@ fn zirValidateDestructure(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
             const msg = try sema.errMsg(src, "type '{}' cannot be destructured", .{operand_ty.fmt(pt)});
             errdefer msg.destroy(sema.gpa);
             try sema.errNote(destructure_src, msg, "result destructured here", .{});
+            if (operand_ty.zigTypeTag(pt.zcu) == .error_union) {
+                try sema.errNote(src, msg, "consider using 'try', 'catch', or 'if'", .{});
+            }
             break :msg msg;
         });
     }
test/cases/compile_errors/destructure_error_union.zig
@@ -0,0 +1,15 @@
+pub export fn entry() void {
+    const Foo = struct { u8, u8 };
+    const foo: anyerror!Foo = error.Failure;
+    const bar, const baz = foo;
+    _ = bar;
+    _ = baz;
+}
+
+// error
+// backend=stage2
+// target=native
+//
+// :4:28: error: type 'anyerror!tmp.entry.Foo' cannot be destructured
+// :4:26: note: result destructured here
+// :4:28: note: consider using 'try', 'catch', or 'if'