Skip to content

Commit 22833b4

Browse files
committed
Fix explicit_counter_loop FP when the counter is only modified inside
the `else` block of `let...else` binding.
1 parent b734854 commit 22833b4

3 files changed

Lines changed: 39 additions & 1 deletion

File tree

clippy_lints/src/loops/utils.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,17 @@ impl<'a, 'tcx> IncrementVisitor<'a, 'tcx> {
4646
}
4747

4848
impl<'tcx> Visitor<'tcx> for IncrementVisitor<'_, 'tcx> {
49+
fn visit_local(&mut self, l: &'tcx LetStmt<'tcx>) {
50+
if let Some(init) = l.init {
51+
self.visit_expr(init);
52+
if let Some(els) = l.els {
53+
self.depth += 1;
54+
self.visit_block(els);
55+
self.depth -= 1;
56+
}
57+
}
58+
}
59+
4960
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
5061
// If node is a variable
5162
if let Some(def_id) = expr.res_local_id() {

tests/ui/explicit_counter_loop.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,3 +363,24 @@ pub fn issue_16642() {
363363
base += 1;
364364
}
365365
}
366+
367+
fn issue_17014(v: Vec<u8>) {
368+
let mut count = 0;
369+
for item in &v {
370+
let Some(_) = Some(0) else {
371+
count += 1;
372+
continue;
373+
};
374+
}
375+
376+
let mut count = 0;
377+
for item in &v {
378+
//~^ explicit_counter_loop
379+
let Some(_) = ({
380+
count += 1;
381+
Some(0)
382+
}) else {
383+
continue;
384+
};
385+
}
386+
}

tests/ui/explicit_counter_loop.stderr

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,5 +105,11 @@ error: the variable `base` is used as a loop counter
105105
LL | for _ in 5..MAX {
106106
| ^^^^^^^^^^^^^^^ help: consider using: `for (base, _) in (100..).zip((5..MAX))`
107107

108-
error: aborting due to 17 previous errors
108+
error: the variable `count` is used as a loop counter
109+
--> tests/ui/explicit_counter_loop.rs:377:5
110+
|
111+
LL | for item in &v {
112+
| ^^^^^^^^^^^^^^ help: consider using: `for (count, item) in v.iter().enumerate()`
113+
114+
error: aborting due to 18 previous errors
109115

0 commit comments

Comments
 (0)