Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix logic in IncrementVisitor #10094

Merged
merged 1 commit into from
Dec 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions clippy_lints/src/loops/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ pub(super) struct IncrementVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>, // context reference
states: HirIdMap<IncrementVisitorVarState>, // incremented variables
depth: u32, // depth of conditional expressions
done: bool,
}

impl<'a, 'tcx> IncrementVisitor<'a, 'tcx> {
Expand All @@ -34,7 +33,6 @@ impl<'a, 'tcx> IncrementVisitor<'a, 'tcx> {
cx,
states: HirIdMap::default(),
depth: 0,
done: false,
}
}

Expand All @@ -51,10 +49,6 @@ impl<'a, 'tcx> IncrementVisitor<'a, 'tcx> {

impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
if self.done {
return;
}

// If node is a variable
if let Some(def_id) = path_to_local(expr) {
if let Some(parent) = get_parent_expr(self.cx, expr) {
Expand Down Expand Up @@ -95,7 +89,9 @@ impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
walk_expr(self, expr);
self.depth -= 1;
} else if let ExprKind::Continue(_) = expr.kind {
self.done = true;
// If we see a `continue` block, then we increment depth so that the IncrementVisitor
// state will be set to DontWarn if we see the variable being modified anywhere afterwards.
self.depth += 1;
} else {
walk_expr(self, expr);
}
Expand Down
30 changes: 30 additions & 0 deletions tests/ui/explicit_counter_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,33 @@ mod issue_7920 {
}
}
}

mod issue_10058 {
pub fn test() {
// should not lint since we are increasing counter potentially more than once in the loop
let values = [0, 1, 0, 1, 1, 1, 0, 1, 0, 1];
let mut counter = 0;
for value in values {
counter += 1;

if value == 0 {
continue;
}

counter += 1;
}
}

pub fn test2() {
// should not lint since we are increasing counter potentially more than once in the loop
let values = [0, 1, 0, 1, 1, 1, 0, 1, 0, 1];
let mut counter = 0;
for value in values {
counter += 1;

if value != 0 {
counter += 1;
}
}
}
}