diff --git a/clippy_lints/src/loops.rs b/clippy_lints/src/loops.rs index 6dfe0a7ec01..8a12530cb0d 100644 --- a/clippy_lints/src/loops.rs +++ b/clippy_lints/src/loops.rs @@ -1996,9 +1996,6 @@ impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> { if self.state == VarState::DontWarn { return; } - if self.past_loop { - return; - } if SpanlessEq::new(self.cx).eq_expr(&expr, self.end_expr) { self.past_loop = true; return; @@ -2027,7 +2024,12 @@ impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> { _ => (), } } - } else if is_loop(expr) { + + if self.past_loop { + self.state = VarState::DontWarn; + return; + } + } else if !self.past_loop && is_loop(expr) { self.state = VarState::DontWarn; return; } else if is_conditional(expr) { diff --git a/tests/ui/for_loop.rs b/tests/ui/for_loop.rs index 286ef190cbf..029b6f7aa20 100644 --- a/tests/ui/for_loop.rs +++ b/tests/ui/for_loop.rs @@ -575,7 +575,13 @@ mod issue_2496 { mod issue_1219 { #[warn(clippy::explicit_counter_loop)] pub fn test() { - // should not trigger the lint, because of the continue statement + // should not trigger the lint because variable is used after the loop #473 + let vec = vec![1,2,3]; + let mut index = 0; + for _v in &vec { index += 1 } + println!("index: {}", index); + + // should not trigger the lint because the count is conditional #1219 let text = "banana"; let mut count = 0; for ch in text.chars() { @@ -583,36 +589,17 @@ mod issue_1219 { continue; } count += 1; + println!("{}", count); } - println!("{}", count); - // should trigger the lint - let text = "banana"; - let mut count = 0; - for ch in text.chars() { - if ch == 'a' { - println!("abc") - } - count += 1; - } - println!("{}", count); - - // should not trigger the lint + // should not trigger the lint because the count is conditional let text = "banana"; let mut count = 0; for ch in text.chars() { if ch == 'a' { count += 1; } + println!("{}", count); } - println!("{}", count); - - // should trigger the lint - let text = "banana"; - let mut count = 0; - for _ch in text.chars() { - count += 1; - } - println!("{}", count); } }