From a42be8589a0b380da18a78da4c81205ff8086243 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Fri, 5 Feb 2021 16:28:13 -0600 Subject: [PATCH] Fix vec_init_then_push FP --- clippy_lints/src/vec_init_then_push.rs | 5 ++++- tests/ui/vec_init_then_push.rs | 25 +++++++++++++++++++++++++ tests/ui/vec_init_then_push.stderr | 2 +- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/clippy_lints/src/vec_init_then_push.rs b/clippy_lints/src/vec_init_then_push.rs index 4768cb4830b8..8d111f98add9 100644 --- a/clippy_lints/src/vec_init_then_push.rs +++ b/clippy_lints/src/vec_init_then_push.rs @@ -83,8 +83,11 @@ impl VecPushSearcher { } impl LateLintPass<'_> for VecInitThenPush { - fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) { + fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) { self.searcher = None; + } + + fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) { if_chain! { if !in_external_macro(cx.sess(), local.span); if let Some(init) = local.init; diff --git a/tests/ui/vec_init_then_push.rs b/tests/ui/vec_init_then_push.rs index 642ce5040096..5099aad83bcb 100644 --- a/tests/ui/vec_init_then_push.rs +++ b/tests/ui/vec_init_then_push.rs @@ -12,10 +12,35 @@ fn main() { cap_err.push(0); cap_err.push(1); cap_err.push(2); + if true { + // don't include this one + cap_err.push(3); + } let mut cap_ok = Vec::with_capacity(10); cap_ok.push(0); new_err = Vec::new(); new_err.push(0); + + let mut vec = Vec::new(); + // control flow at block final expression + if true { + // no lint + vec.push(1); + } +} + +pub fn no_lint() -> Vec { + let mut p = Some(1); + let mut vec = Vec::new(); + loop { + match p { + None => return vec, + Some(i) => { + vec.push(i); + p = None; + }, + } + } } diff --git a/tests/ui/vec_init_then_push.stderr b/tests/ui/vec_init_then_push.stderr index 819ed47d0991..9ec3e10e6247 100644 --- a/tests/ui/vec_init_then_push.stderr +++ b/tests/ui/vec_init_then_push.stderr @@ -24,7 +24,7 @@ LL | | cap_err.push(2); | |____________________^ help: consider using the `vec![]` macro: `let mut cap_err = vec![..];` error: calls to `push` immediately after creation - --> $DIR/vec_init_then_push.rs:19:5 + --> $DIR/vec_init_then_push.rs:23:5 | LL | / new_err = Vec::new(); LL | | new_err.push(0);