Skip to content

Commit 369933a

Browse files
author
yossydev
committed
fix: improve error messaging for unreachable loop return cases
1 parent 558ac1c commit 369933a

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

compiler/rustc_hir_typeck/src/coercion.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1666,9 +1666,26 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
16661666
ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>,
16671667
ty: Ty<'tcx>,
16681668
) {
1669-
let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else {
1670-
return;
1671-
};
1669+
let hir = tcx.hir();
1670+
let item = hir.get_parent_item(expr.hir_id);
1671+
1672+
if let some(node) = tcx.opt_hir_node(item.into())
1673+
&& let some(body_id) = node.body_id()
1674+
&& let some(sig) = node.fn_sig()
1675+
&& let hir::exprkind::block(block, _) = hir.body(body_id).value.kind
1676+
&& !ty.is_never()
1677+
{
1678+
for stmt in block.stmts {
1679+
if let hir::stmtkind::local(local) = stmt.kind {
1680+
if let hir::patkind::binding(_, _, _, none) = local.pat.kind {
1681+
err.span_note(
1682+
stmt.span,
1683+
"This pattern has a single binding, which might cause issues if the loop doesn't execute. Consider handling the case where the loop might not run.",
1684+
);
1685+
}
1686+
}
1687+
}
1688+
}
16721689
let mut span: MultiSpan = vec![loop_span].into();
16731690
span.push_span_label(loop_span, "this might have zero elements to iterate on");
16741691
const MAXITER: usize = 3;

0 commit comments

Comments
 (0)