From 8579904ddd489b73cb61721c31b9e9c14ed9e264 Mon Sep 17 00:00:00 2001 From: r00ster91 Date: Fri, 21 Jul 2023 02:58:41 +0200 Subject: [PATCH] Sema: add error note for !?Type types when optional type is expected --- src/Sema.zig | 17 ++++++++++++++--- .../while_expected_optional_got_error_union.zig | 1 + 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Sema.zig b/src/Sema.zig index 123ba93cbee5c44b9e53c2473dcd6f61dd3cafea..f286b6385f13b5925447d5c3dc518c5fac43bda6 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -2228,8 +2228,19 @@ fn failWithModRemNegative(sema: *Sema, block: *Block, src: LazySrcLoc, lhs_ty: T }); } -fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, optional_ty: Type) CompileError { - return sema.fail(block, src, "expected optional type, found '{}'", .{optional_ty.fmt(sema.mod)}); +fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, non_optional_ty: Type) CompileError { + const mod = sema.mod; + const msg = msg: { + const msg = try sema.errMsg(block, src, "expected optional type, found '{}'", .{ + non_optional_ty.fmt(mod), + }); + errdefer msg.destroy(sema.gpa); + if (non_optional_ty.zigTypeTag(mod) == .ErrorUnion) { + try sema.errNote(block, src, msg, "consider using 'try', 'catch', or 'if'", .{}); + } + break :msg msg; + }; + return sema.failWithOwnedErrorMsg(block, msg); } fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError { @@ -9038,7 +9049,7 @@ fn analyzeOptionalPayloadPtr( const opt_type = optional_ptr_ty.childType(zcu); if (opt_type.zigTypeTag(zcu) != .Optional) { - return sema.fail(block, src, "expected optional type, found '{}'", .{opt_type.fmt(zcu)}); + return sema.failWithExpectedOptionalType(block, src, opt_type); } const child_type = opt_type.optionalChild(zcu); diff --git a/test/cases/compile_errors/while_expected_optional_got_error_union.zig b/test/cases/compile_errors/while_expected_optional_got_error_union.zig index 7bde2c866d296a04cbf449bd43769dcf3f8e9d52..1b4a64770b454e3c9e2c0e34ee563df040002765 100644 --- a/test/cases/compile_errors/while_expected_optional_got_error_union.zig +++ b/test/cases/compile_errors/while_expected_optional_got_error_union.zig @@ -12,3 +12,4 @@ fn bar() anyerror!i32 { // target=native // // :2:15: error: expected optional type, found 'anyerror!i32' +// :2:15: note: consider using 'try', 'catch', or 'if' -- 2.54.0