Add error hint when looping over ErrorUnion

This commit is contained in:
David Rubin 2024-02-03 11:16:27 -08:00 committed by GitHub
parent f2e249e920
commit eb4024036d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 0 deletions

View File

@ -4221,6 +4221,11 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
const msg = try sema.errMsg(block, arg_src, "type '{}' is not indexable and not a range", .{object_ty.fmt(sema.mod)});
errdefer msg.destroy(sema.gpa);
try sema.errNote(block, arg_src, msg, "for loop operand must be a range, array, slice, tuple, or vector", .{});
if (object_ty.zigTypeTag(mod) == .ErrorUnion) {
try sema.errNote(block, arg_src, msg, "consider using 'try', 'catch', or 'if'", .{});
}
break :msg msg;
};
return sema.failWithOwnedErrorMsg(block, msg);

View File

@ -0,0 +1,15 @@
fn b() !u32 {
return 2;
}
export fn a() void {
for (b()) |_| {}
}
// error
// backend=stage2
// target=native
//
// :6:11: error: type '@typeInfo(@typeInfo(@TypeOf(tmp.b)).Fn.return_type.?).ErrorUnion.error_set!u32' is not indexable and not a range
// :6:11: note: for loop operand must be a range, array, slice, tuple, or vector
// :6:11: note: consider using 'try', 'catch', or 'if'