From 943176bbfcf3125451fa64e082ee357c28e70413 Mon Sep 17 00:00:00 2001 From: Will Lillis Date: Mon, 23 Sep 2024 16:04:24 -0400 Subject: [PATCH] fix: Add error note when attempt is made to destructure error union (#21491) closes #21417 --- src/Sema.zig | 3 +++ .../compile_errors/destructure_error_union.zig | 15 +++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 test/cases/compile_errors/destructure_error_union.zig diff --git a/src/Sema.zig b/src/Sema.zig index 14a4061b00..40556d2136 100644 --- a/src/Sema.zig +++ b/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; }); } diff --git a/test/cases/compile_errors/destructure_error_union.zig b/test/cases/compile_errors/destructure_error_union.zig new file mode 100644 index 0000000000..fb5872707d --- /dev/null +++ b/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'