Skip to content

Commit 799bded

Browse files
authored
Rollup merge of #93574 - compiler-errors:bad-let-suggestion, r=lcnr
don't suggest adding `let` due to bad assignment expressions inside of `while` loop adds a check that our `lhs` expression is actually within the conditional part of the `while` loop, instead of anywhere in the `while` body. fixes #93486
2 parents ef50086 + bc23bbb commit 799bded

File tree

3 files changed

+33
-8
lines changed

3 files changed

+33
-8
lines changed

compiler/rustc_typeck/src/check/expr.rs

+16-8
Original file line numberDiff line numberDiff line change
@@ -865,14 +865,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
865865
),
866866
..
867867
}) => {
868-
// We have a situation like `while Some(0) = value.get(0) {`, where `while let`
869-
// was more likely intended.
870-
err.span_suggestion_verbose(
871-
expr.span.shrink_to_lo(),
872-
"you might have meant to use pattern destructuring",
873-
"let ".to_string(),
874-
Applicability::MachineApplicable,
875-
);
868+
// Check if our lhs is a child of the condition of a while loop
869+
let expr_is_ancestor = std::iter::successors(Some(lhs.hir_id), |id| {
870+
self.tcx.hir().find_parent_node(*id)
871+
})
872+
.take_while(|id| *id != parent)
873+
.any(|id| id == expr.hir_id);
874+
// if it is, then we have a situation like `while Some(0) = value.get(0) {`,
875+
// where `while let` was more likely intended.
876+
if expr_is_ancestor {
877+
err.span_suggestion_verbose(
878+
expr.span.shrink_to_lo(),
879+
"you might have meant to use pattern destructuring",
880+
"let ".to_string(),
881+
Applicability::MachineApplicable,
882+
);
883+
}
876884
break;
877885
}
878886
hir::Node::Item(_)

src/test/ui/typeck/issue-93486.rs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
fn main() {
2+
while let 1 = 1 {
3+
vec![].last_mut().unwrap() = 3_u8;
4+
//~^ ERROR invalid left-hand side of assignment
5+
}
6+
}

src/test/ui/typeck/issue-93486.stderr

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0070]: invalid left-hand side of assignment
2+
--> $DIR/issue-93486.rs:3:36
3+
|
4+
LL | vec![].last_mut().unwrap() = 3_u8;
5+
| -------------------------- ^
6+
| |
7+
| cannot assign to this expression
8+
9+
error: aborting due to previous error
10+
11+
For more information about this error, try `rustc --explain E0070`.

0 commit comments

Comments
 (0)