]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/vec_init_then_push.rs
modify code
[rust.git] / clippy_lints / src / vec_init_then_push.rs
index 8d111f98add9aac2c7ba145d443bbbf67cb5a594..fbf2b3e081b823220e0c1fbc792de34b1daaeba1 100644 (file)
@@ -1,26 +1,24 @@
-use crate::utils::{
-    is_type_diagnostic_item, match_def_path, path_to_local, path_to_local_id, paths, snippet, span_lint_and_sugg,
-};
+use clippy_utils::diagnostics::span_lint_and_sugg;
+use clippy_utils::higher::{get_vec_init_kind, VecInitKind};
+use clippy_utils::source::snippet;
+use clippy_utils::{path_to_local, path_to_local_id};
 use if_chain::if_chain;
-use rustc_ast::ast::LitKind;
 use rustc_errors::Applicability;
-use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, Stmt, StmtKind};
+use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, Stmt, StmtKind};
 use rustc_lint::{LateContext, LateLintPass, LintContext};
 use rustc_middle::lint::in_external_macro;
 use rustc_session::{declare_tool_lint, impl_lint_pass};
-use rustc_span::{symbol::sym, Span};
-use std::convert::TryInto;
+use rustc_span::Span;
 
 declare_clippy_lint! {
-    /// **What it does:** Checks for calls to `push` immediately after creating a new `Vec`.
+    /// ### What it does
+    /// Checks for calls to `push` immediately after creating a new `Vec`.
     ///
-    /// **Why is this bad?** The `vec![]` macro is both more performant and easier to read than
+    /// ### Why is this bad?
+    /// The `vec![]` macro is both more performant and easier to read than
     /// multiple `push` calls.
     ///
-    /// **Known problems:** None.
-    ///
-    /// **Example:**
-    ///
+    /// ### Example
     /// ```rust
     /// let mut v = Vec::new();
     /// v.push(0);
@@ -29,6 +27,7 @@
     /// ```rust
     /// let v = vec![0];
     /// ```
+    #[clippy::version = "1.51.0"]
     pub VEC_INIT_THEN_PUSH,
     perf,
     "`push` immediately after `Vec` creation"
@@ -41,11 +40,6 @@ pub struct VecInitThenPush {
     searcher: Option<VecPushSearcher>,
 }
 
-#[derive(Clone, Copy)]
-enum VecInitKind {
-    New,
-    WithCapacity(u64),
-}
 struct VecPushSearcher {
     local_id: HirId,
     init: VecInitKind,
@@ -58,7 +52,8 @@ impl VecPushSearcher {
     fn display_err(&self, cx: &LateContext<'_>) {
         match self.init {
             _ if self.found == 0 => return,
-            VecInitKind::WithCapacity(x) if x > self.found => return,
+            VecInitKind::WithLiteralCapacity(x) if x > self.found => return,
+            VecInitKind::WithExprCapacity(_) => return,
             _ => (),
         };
 
@@ -82,7 +77,7 @@ fn display_err(&self, cx: &LateContext<'_>) {
     }
 }
 
-impl LateLintPass<'_> for VecInitThenPush {
+impl<'tcx> LateLintPass<'tcx> for VecInitThenPush {
     fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
         self.searcher = None;
     }
@@ -107,22 +102,21 @@ fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
     }
 
     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
-        if self.searcher.is_none() {
-            if_chain! {
-                if !in_external_macro(cx.sess(), expr.span);
-                if let ExprKind::Assign(left, right, _) = expr.kind;
-                if let Some(id) = path_to_local(left);
-                if let Some(init_kind) = get_vec_init_kind(cx, right);
-                then {
-                    self.searcher = Some(VecPushSearcher {
-                        local_id: id,
-                        init: init_kind,
-                        lhs_is_local: false,
-                        lhs_span: left.span,
-                        err_span: expr.span,
-                        found: 0,
-                    });
-                }
+        if_chain! {
+            if self.searcher.is_none();
+            if !in_external_macro(cx.sess(), expr.span);
+            if let ExprKind::Assign(left, right, _) = expr.kind;
+            if let Some(id) = path_to_local(left);
+            if let Some(init_kind) = get_vec_init_kind(cx, right);
+            then {
+                self.searcher = Some(VecPushSearcher {
+                    local_id: id,
+                    init: init_kind,
+                    lhs_is_local: false,
+                    lhs_span: left.span,
+                    err_span: expr.span,
+                    found: 0,
+                });
             }
         }
     }
@@ -131,7 +125,7 @@ fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
         if let Some(searcher) = self.searcher.take() {
             if_chain! {
                 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
-                if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind;
+                if let ExprKind::MethodCall(path, [self_arg, _], _) = expr.kind;
                 if path_to_local_id(self_arg, searcher.local_id);
                 if path.ident.name.as_str() == "push";
                 then {
@@ -153,37 +147,3 @@ fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
         }
     }
 }
-
-fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> {
-    if let ExprKind::Call(func, args) = expr.kind {
-        match func.kind {
-            ExprKind::Path(QPath::TypeRelative(ty, name))
-                if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::vec_type) =>
-            {
-                if name.ident.name == sym::new {
-                    return Some(VecInitKind::New);
-                } else if name.ident.name.as_str() == "with_capacity" {
-                    return args.get(0).and_then(|arg| {
-                        if_chain! {
-                            if let ExprKind::Lit(lit) = &arg.kind;
-                            if let LitKind::Int(num, _) = lit.node;
-                            then {
-                                Some(VecInitKind::WithCapacity(num.try_into().ok()?))
-                            } else {
-                                None
-                            }
-                        }
-                    });
-                }
-            }
-            ExprKind::Path(QPath::Resolved(_, path))
-                if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)
-                    && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type) =>
-            {
-                return Some(VecInitKind::New);
-            }
-            _ => (),
-        }
-    }
-    None
-}