]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/slow_vector_initialization.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / slow_vector_initialization.rs
index 2af657a5a6afc3c37b5bdd4a73e64151a8b16196..888405983fd5129a853ccd80f13d5bb1d9f5e520 100644 (file)
@@ -1,71 +1,45 @@
-// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
-use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, Lint};
-use crate::rustc::{declare_tool_lint, lint_array};
-use crate::rustc::hir::*;
-use if_chain::if_chain;
-use crate::syntax_pos::symbol::Symbol;
-use crate::syntax::ast::{LitKind, NodeId};
-use crate::utils::{match_qpath, span_lint_and_then, SpanlessEq, get_enclosing_block};
 use crate::utils::sugg::Sugg;
-use crate::rustc_errors::{Applicability};
-
-/// **What it does:** Checks slow zero-filled vector initialization
-///
-/// **Why is this bad?** This structures are non-idiomatic and less efficient than simply using
-/// `vec![len; 0]`.
-///
-/// **Known problems:** None.
-///
-/// **Example:**
-/// ```rust
-/// let mut vec1 = Vec::with_capacity(len);
-/// vec1.resize(len, 0);
-///
-/// let mut vec2 = Vec::with_capacity(len);
-/// vec2.extend(repeat(0).take(len))
-/// ```
+use crate::utils::{get_enclosing_block, match_qpath, span_lint_and_then, SpanlessEq};
+use if_chain::if_chain;
+use rustc::hir::intravisit::{walk_block, walk_expr, walk_stmt, NestedVisitorMap, Visitor};
+use rustc::hir::*;
+use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
+use rustc::{declare_tool_lint, lint_array};
+use rustc_errors::Applicability;
+use syntax::ast::LitKind;
+use syntax_pos::symbol::Symbol;
+
 declare_clippy_lint! {
+    /// **What it does:** Checks slow zero-filled vector initialization
+    ///
+    /// **Why is this bad?** These structures are non-idiomatic and less efficient than simply using
+    /// `vec![0; len]`.
+    ///
+    /// **Known problems:** None.
+    ///
+    /// **Example:**
+    /// ```rust
+    /// let mut vec1 = Vec::with_capacity(len);
+    /// vec1.resize(len, 0);
+    ///
+    /// let mut vec2 = Vec::with_capacity(len);
+    /// vec2.extend(repeat(0).take(len))
+    /// ```
     pub SLOW_VECTOR_INITIALIZATION,
     perf,
     "slow vector initialization"
 }
 
-/// **What it does:** Checks unsafe vector initialization
-///
-/// **Why is this bad?** Changing the length of a vector may expose uninitialized memory, which
-/// can lead to memory safety issues
-///
-/// **Known problems:** None.
-///
-/// **Example:**
-/// ```rust
-/// let mut vec1 = Vec::with_capacity(len);
-/// unsafe { vec1.set_len(len); }
-/// ```
-declare_clippy_lint! {
-    pub UNSAFE_VECTOR_INITIALIZATION,
-    correctness,
-    "unsafe vector initialization"
-}
-
 #[derive(Copy, Clone, Default)]
 pub struct Pass;
 
 impl LintPass for Pass {
     fn get_lints(&self) -> LintArray {
-        lint_array!(
-            SLOW_VECTOR_INITIALIZATION,
-            UNSAFE_VECTOR_INITIALIZATION,
-        )
+        lint_array!(SLOW_VECTOR_INITIALIZATION,)
+    }
+
+    fn name(&self) -> &'static str {
+        "SlowVectorInit"
     }
 }
 
@@ -91,9 +65,6 @@ enum InitializationType<'tcx> {
 
     /// Resize is a slow initialization with the form `vec.resize(.., 0)`
     Resize(&'tcx Expr),
-
-    /// UnsafeSetLen is a slow initialization with the form `vec.set_len(..)`
-    UnsafeSetLen(&'tcx Expr),
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
@@ -116,7 +87,7 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
                     len_expr: len_arg,
                 };
 
-                Self::search_initialization(cx, vi, expr.id);
+                Self::search_initialization(cx, vi, expr.hir_id);
             }
         }
     }
@@ -124,9 +95,8 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
         // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
         if_chain! {
-            if let StmtKind::Decl(ref decl, _) = stmt.node;
-            if let DeclKind::Local(ref local) = decl.node;
-            if let PatKind::Binding(BindingAnnotation::Mutable, _, variable_name, None) = local.pat.node;
+            if let StmtKind::Local(ref local) = stmt.node;
+            if let PatKind::Binding(BindingAnnotation::Mutable, .., variable_name, None) = local.pat.node;
             if let Some(ref init) = local.init;
             if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
 
@@ -137,7 +107,7 @@ fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
                     len_expr: len_arg,
                 };
 
-                Self::search_initialization(cx, vi, stmt.node.id());
+                Self::search_initialization(cx, vi, stmt.hir_id);
             }
         }
     }
@@ -162,11 +132,7 @@ fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
     }
 
     /// Search initialization for the given vector
-    fn search_initialization<'tcx>(
-        cx: &LateContext<'_, 'tcx>,
-        vec_alloc: VecAllocation<'tcx>,
-        parent_node: NodeId
-    ) {
+    fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: HirId) {
         let enclosing_body = get_enclosing_block(cx, parent_node);
 
         if enclosing_body.is_none() {
@@ -187,26 +153,19 @@ fn search_initialization<'tcx>(
         }
     }
 
-    fn lint_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, initialization: &InitializationType<'tcx>, vec_alloc: &VecAllocation<'_>) {
+    fn lint_initialization<'tcx>(
+        cx: &LateContext<'_, 'tcx>,
+        initialization: &InitializationType<'tcx>,
+        vec_alloc: &VecAllocation<'_>,
+    ) {
         match initialization {
-            InitializationType::UnsafeSetLen(e) =>
-                Self::emit_lint(
-                    cx,
-                    e,
-                    vec_alloc,
-                    "unsafe vector initialization",
-                    UNSAFE_VECTOR_INITIALIZATION
-                ),
-
-            InitializationType::Extend(e) |
-            InitializationType::Resize(e) =>
-                Self::emit_lint(
-                    cx,
-                    e,
-                    vec_alloc,
-                    "slow zero-filling initialization",
-                    SLOW_VECTOR_INITIALIZATION
-                )
+            InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
+                cx,
+                e,
+                vec_alloc,
+                "slow zero-filling initialization",
+                SLOW_VECTOR_INITIALIZATION,
+            ),
         };
     }
 
@@ -215,24 +174,18 @@ fn emit_lint<'tcx>(
         slow_fill: &Expr,
         vec_alloc: &VecAllocation<'_>,
         msg: &str,
-        lint: &'static Lint
+        lint: &'static Lint,
     ) {
         let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
 
-        span_lint_and_then(
-            cx,
-            lint,
-            slow_fill.span,
-            msg,
-            |db| {
-                db.span_suggestion_with_applicability(
-                    vec_alloc.allocation_expr.span,
-                    "consider replace allocation with",
-                    format!("vec![0; {}]", len_expr),
-                    Applicability::Unspecified
-                );
-            }
-        );
+        span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
+            db.span_suggestion(
+                vec_alloc.allocation_expr.span,
+                "consider replace allocation with",
+                format!("vec![0; {}]", len_expr),
+                Applicability::Unspecified,
+            );
+        });
     }
 }
 
@@ -241,13 +194,13 @@ fn emit_lint<'tcx>(
 struct VectorInitializationVisitor<'a, 'tcx: 'a> {
     cx: &'a LateContext<'a, 'tcx>,
 
-    /// Contains the information
+    /// Contains the information.
     vec_alloc: VecAllocation<'tcx>,
 
-    /// Contains, if found, the slow initialization expression
+    /// Contains the slow initialization expression, if one was found.
     slow_expression: Option<InitializationType<'tcx>>,
 
-    /// true if the initialization of the vector has been found on the visited block
+    /// `true` if the initialization of the vector has been found on the visited block.
     initialization_found: bool,
 }
 
@@ -292,25 +245,6 @@ fn search_slow_resize_filling(&mut self, expr: &'tcx Expr) {
         }
     }
 
-    /// Checks if the given expression is using `set_len` to initialize the vector
-    fn search_unsafe_set_len(&mut self, expr: &'tcx Expr) {
-        if_chain! {
-            if self.initialization_found;
-            if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
-            if let ExprKind::Path(ref qpath_subj) = args[0].node;
-            if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
-            if path.ident.name == "set_len";
-            if let Some(ref len_arg) = args.get(1);
-
-            // Check that len expression is equals to `with_capacity` expression
-            if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
-
-            then {
-                self.slow_expression = Some(InitializationType::UnsafeSetLen(expr));
-            }
-        }
-    }
-
     /// Returns `true` if give expression is `repeat(0).take(...)`
     fn is_repeat_take(&self, expr: &Expr) -> bool {
         if_chain! {
@@ -353,20 +287,39 @@ fn is_repeat_zero(&self, expr: &Expr) -> bool {
 }
 
 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
-    fn visit_expr(&mut self, expr: &'tcx Expr) {
-        // Stop the search if we already found a slow zero-filling initialization
-        if self.slow_expression.is_some() {
-            return
+    fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
+        if self.initialization_found {
+            match stmt.node {
+                StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
+                    self.search_slow_extend_filling(expr);
+                    self.search_slow_resize_filling(expr);
+                },
+                _ => (),
+            }
+
+            self.initialization_found = false;
+        } else {
+            walk_stmt(self, stmt);
+        }
+    }
+
+    fn visit_block(&mut self, block: &'tcx Block) {
+        if self.initialization_found {
+            if let Some(ref s) = block.stmts.get(0) {
+                self.visit_stmt(s)
+            }
+
+            self.initialization_found = false;
+        } else {
+            walk_block(self, block);
         }
+    }
 
+    fn visit_expr(&mut self, expr: &'tcx Expr) {
         // Skip all the expressions previous to the vector initialization
-        if self.vec_alloc.allocation_expr.id == expr.id {
+        if self.vec_alloc.allocation_expr.hir_id == expr.hir_id {
             self.initialization_found = true;
         }
-        
-        self.search_slow_extend_filling(expr);
-        self.search_slow_resize_filling(expr);
-        self.search_unsafe_set_len(expr);
 
         walk_expr(self, expr);
     }