1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::intravisit::{walk_block, walk_expr, walk_stmt, NestedVisitorMap, Visitor};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::syntax::ast::{LitKind, NodeId};
16 use crate::syntax_pos::symbol::Symbol;
17 use crate::utils::sugg::Sugg;
18 use crate::utils::{get_enclosing_block, match_qpath, span_lint_and_then, SpanlessEq};
19 use if_chain::if_chain;
21 /// **What it does:** Checks slow zero-filled vector initialization
23 /// **Why is this bad?** This structures are non-idiomatic and less efficient than simply using
26 /// **Known problems:** None.
30 /// let mut vec1 = Vec::with_capacity(len);
31 /// vec1.resize(len, 0);
33 /// let mut vec2 = Vec::with_capacity(len);
34 /// vec2.extend(repeat(0).take(len))
36 declare_clippy_lint! {
37 pub SLOW_VECTOR_INITIALIZATION,
39 "slow vector initialization"
42 #[derive(Copy, Clone, Default)]
45 impl LintPass for Pass {
46 fn get_lints(&self) -> LintArray {
47 lint_array!(SLOW_VECTOR_INITIALIZATION,)
51 /// `VecAllocation` contains data regarding a vector allocated with `with_capacity` and then
52 /// assigned to a variable. For example, `let mut vec = Vec::with_capacity(0)` or
53 /// `vec = Vec::with_capacity(0)`
54 struct VecAllocation<'tcx> {
55 /// Symbol of the local variable name
56 variable_name: Symbol,
58 /// Reference to the expression which allocates the vector
59 allocation_expr: &'tcx Expr,
61 /// Reference to the expression used as argument on `with_capacity` call. This is used
62 /// to only match slow zero-filling idioms of the same length than vector initialization.
66 /// Type of slow initialization
67 enum InitializationType<'tcx> {
68 /// Extend is a slow initialization with the form `vec.extend(repeat(0).take(..))`
71 /// Resize is a slow initialization with the form `vec.resize(.., 0)`
75 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
76 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
77 // Matches initialization on reassignements. For example: `vec = Vec::with_capacity(100)`
79 if let ExprKind::Assign(ref left, ref right) = expr.node;
81 // Extract variable name
82 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node;
83 if let Some(variable_name) = path.segments.get(0);
85 // Extract len argument
86 if let Some(ref len_arg) = Self::is_vec_with_capacity(right);
89 let vi = VecAllocation {
90 variable_name: variable_name.ident.name,
91 allocation_expr: right,
95 Self::search_initialization(cx, vi, expr.id);
100 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
101 // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
103 if let StmtKind::Decl(ref decl, _) = stmt.node;
104 if let DeclKind::Local(ref local) = decl.node;
105 if let PatKind::Binding(BindingAnnotation::Mutable, _, variable_name, None) = local.pat.node;
106 if let Some(ref init) = local.init;
107 if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
110 let vi = VecAllocation {
111 variable_name: variable_name.name,
112 allocation_expr: init,
116 Self::search_initialization(cx, vi, stmt.node.id());
123 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
124 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
125 fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
127 if let ExprKind::Call(ref func, ref args) = expr.node;
128 if let ExprKind::Path(ref path) = func.node;
129 if match_qpath(path, &["Vec", "with_capacity"]);
133 return Some(&args[0]);
140 /// Search initialization for the given vector
141 fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: NodeId) {
142 let enclosing_body = get_enclosing_block(cx, parent_node);
144 if enclosing_body.is_none() {
148 let mut v = VectorInitializationVisitor {
151 slow_expression: None,
152 initialization_found: false,
155 v.visit_block(enclosing_body.unwrap());
157 if let Some(ref allocation_expr) = v.slow_expression {
158 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
162 fn lint_initialization<'tcx>(
163 cx: &LateContext<'_, 'tcx>,
164 initialization: &InitializationType<'tcx>,
165 vec_alloc: &VecAllocation<'_>,
167 match initialization {
168 InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
172 "slow zero-filling initialization",
173 SLOW_VECTOR_INITIALIZATION,
179 cx: &LateContext<'_, 'tcx>,
181 vec_alloc: &VecAllocation<'_>,
185 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
187 span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
188 db.span_suggestion_with_applicability(
189 vec_alloc.allocation_expr.span,
190 "consider replace allocation with",
191 format!("vec![0; {}]", len_expr),
192 Applicability::Unspecified,
198 /// `VectorInitializationVisitor` searches for unsafe or slow vector initializations for the given
200 struct VectorInitializationVisitor<'a, 'tcx: 'a> {
201 cx: &'a LateContext<'a, 'tcx>,
203 /// Contains the information
204 vec_alloc: VecAllocation<'tcx>,
206 /// Contains, if found, the slow initialization expression
207 slow_expression: Option<InitializationType<'tcx>>,
209 /// true if the initialization of the vector has been found on the visited block
210 initialization_found: bool,
213 impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
214 /// Checks if the given expression is extending a vector with `repeat(0).take(..)`
215 fn search_slow_extend_filling(&mut self, expr: &'tcx Expr) {
217 if self.initialization_found;
218 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
219 if let ExprKind::Path(ref qpath_subj) = args[0].node;
220 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
221 if path.ident.name == "extend";
222 if let Some(ref extend_arg) = args.get(1);
223 if self.is_repeat_take(extend_arg);
226 self.slow_expression = Some(InitializationType::Extend(expr));
231 /// Checks if the given expression is resizing a vector with 0
232 fn search_slow_resize_filling(&mut self, expr: &'tcx Expr) {
234 if self.initialization_found;
235 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
236 if let ExprKind::Path(ref qpath_subj) = args[0].node;
237 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
238 if path.ident.name == "resize";
239 if let (Some(ref len_arg), Some(fill_arg)) = (args.get(1), args.get(2));
241 // Check that is filled with 0
242 if let ExprKind::Lit(ref lit) = fill_arg.node;
243 if let LitKind::Int(0, _) = lit.node;
245 // Check that len expression is equals to `with_capacity` expression
246 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
249 self.slow_expression = Some(InitializationType::Resize(expr));
254 /// Returns `true` if give expression is `repeat(0).take(...)`
255 fn is_repeat_take(&self, expr: &Expr) -> bool {
257 if let ExprKind::MethodCall(ref take_path, _, ref take_args) = expr.node;
258 if take_path.ident.name == "take";
260 // Check that take is applied to `repeat(0)`
261 if let Some(ref repeat_expr) = take_args.get(0);
262 if self.is_repeat_zero(repeat_expr);
264 // Check that len expression is equals to `with_capacity` expression
265 if let Some(ref len_arg) = take_args.get(1);
266 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
276 /// Returns `true` if given expression is `repeat(0)`
277 fn is_repeat_zero(&self, expr: &Expr) -> bool {
279 if let ExprKind::Call(ref fn_expr, ref repeat_args) = expr.node;
280 if let ExprKind::Path(ref qpath_repeat) = fn_expr.node;
281 if match_qpath(&qpath_repeat, &["repeat"]);
282 if let Some(ref repeat_arg) = repeat_args.get(0);
283 if let ExprKind::Lit(ref lit) = repeat_arg.node;
284 if let LitKind::Int(0, _) = lit.node;
295 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
296 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
297 if self.initialization_found {
299 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => {
300 self.search_slow_extend_filling(expr);
301 self.search_slow_resize_filling(expr);
306 self.initialization_found = false;
308 walk_stmt(self, stmt);
312 fn visit_block(&mut self, block: &'tcx Block) {
313 if self.initialization_found {
314 if let Some(ref s) = block.stmts.get(0) {
318 self.initialization_found = false;
320 walk_block(self, block);
324 fn visit_expr(&mut self, expr: &'tcx Expr) {
325 // Skip all the expressions previous to the vector initialization
326 if self.vec_alloc.allocation_expr.id == expr.id {
327 self.initialization_found = true;
330 walk_expr(self, expr);
333 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
334 NestedVisitorMap::None