Skip to content

Commit 62cd8d9

Browse files
committed
fix logic in IncrementVisitor
There used to be a logical bug where IncrementVisitor would completely stop checking an expression/block after seeing a continue statement. This led to issues such as #10058 where a variable incremented (or otherwise modified) after any continue statement could still be considered incremented only once. The solution is to continue scanning the expression after seeing a `continue` statement, but increment self.depth so that the Visitor thinks that the rest of the loop is within a conditional.
1 parent 3c14075 commit 62cd8d9

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

clippy_lints/src/loops/utils.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
9595
walk_expr(self, expr);
9696
self.depth -= 1;
9797
} else if let ExprKind::Continue(_) = expr.kind {
98-
self.done = true;
98+
self.depth += 1;
9999
} else {
100100
walk_expr(self, expr);
101101
}

tests/ui/explicit_counter_loop.rs

+30
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,33 @@ mod issue_7920 {
189189
}
190190
}
191191
}
192+
193+
mod issue_10058 {
194+
pub fn test() {
195+
// should not lint since we are increasing counter potentially more than once in the loop
196+
let values = [0, 1, 0, 1, 1, 1, 0, 1, 0, 1];
197+
let mut counter = 0;
198+
for value in values {
199+
counter += 1;
200+
201+
if value == 0 {
202+
continue;
203+
}
204+
205+
counter += 1;
206+
}
207+
}
208+
209+
pub fn test2() {
210+
// should not lint since we are increasing counter potentially more than once in the loop
211+
let values = [0, 1, 0, 1, 1, 1, 0, 1, 0, 1];
212+
let mut counter = 0;
213+
for value in values {
214+
counter += 1;
215+
216+
if value != 0 {
217+
counter += 1;
218+
}
219+
}
220+
}
221+
}

0 commit comments

Comments
 (0)