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 /// **What it does:** Checks unsafe vector initialization
44 /// **Why is this bad?** Changing the length of a vector may expose uninitialized memory, which
45 /// can lead to memory safety issues
47 /// **Known problems:** None.
51 /// let mut vec1 = Vec::with_capacity(len);
53 /// vec1.set_len(len);
56 declare_clippy_lint! {
57 pub UNSAFE_VECTOR_INITIALIZATION,
59 "unsafe vector initialization"
62 #[derive(Copy, Clone, Default)]
65 impl LintPass for Pass {
66 fn get_lints(&self) -> LintArray {
67 lint_array!(SLOW_VECTOR_INITIALIZATION, UNSAFE_VECTOR_INITIALIZATION,)
71 /// `VecAllocation` contains data regarding a vector allocated with `with_capacity` and then
72 /// assigned to a variable. For example, `let mut vec = Vec::with_capacity(0)` or
73 /// `vec = Vec::with_capacity(0)`
74 struct VecAllocation<'tcx> {
75 /// Symbol of the local variable name
76 variable_name: Symbol,
78 /// Reference to the expression which allocates the vector
79 allocation_expr: &'tcx Expr,
81 /// Reference to the expression used as argument on `with_capacity` call. This is used
82 /// to only match slow zero-filling idioms of the same length than vector initialization.
86 /// Type of slow initialization
87 enum InitializationType<'tcx> {
88 /// Extend is a slow initialization with the form `vec.extend(repeat(0).take(..))`
91 /// Resize is a slow initialization with the form `vec.resize(.., 0)`
94 /// UnsafeSetLen is a slow initialization with the form `vec.set_len(..)`
95 UnsafeSetLen(&'tcx Expr),
98 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
99 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
100 // Matches initialization on reassignements. For example: `vec = Vec::with_capacity(100)`
102 if let ExprKind::Assign(ref left, ref right) = expr.node;
104 // Extract variable name
105 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node;
106 if let Some(variable_name) = path.segments.get(0);
108 // Extract len argument
109 if let Some(ref len_arg) = Self::is_vec_with_capacity(right);
112 let vi = VecAllocation {
113 variable_name: variable_name.ident.name,
114 allocation_expr: right,
118 Self::search_initialization(cx, vi, expr.id);
123 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
124 // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
126 if let StmtKind::Decl(ref decl, _) = stmt.node;
127 if let DeclKind::Local(ref local) = decl.node;
128 if let PatKind::Binding(BindingAnnotation::Mutable, _, variable_name, None) = local.pat.node;
129 if let Some(ref init) = local.init;
130 if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
133 let vi = VecAllocation {
134 variable_name: variable_name.name,
135 allocation_expr: init,
139 Self::search_initialization(cx, vi, stmt.node.id());
146 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
147 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
148 fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
150 if let ExprKind::Call(ref func, ref args) = expr.node;
151 if let ExprKind::Path(ref path) = func.node;
152 if match_qpath(path, &["Vec", "with_capacity"]);
156 return Some(&args[0]);
163 /// Search initialization for the given vector
164 fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: NodeId) {
165 let enclosing_body = get_enclosing_block(cx, parent_node);
167 if enclosing_body.is_none() {
171 let mut v = VectorInitializationVisitor {
174 slow_expression: None,
175 initialization_found: false,
178 v.visit_block(enclosing_body.unwrap());
180 if let Some(ref allocation_expr) = v.slow_expression {
181 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
185 fn lint_initialization<'tcx>(
186 cx: &LateContext<'_, 'tcx>,
187 initialization: &InitializationType<'tcx>,
188 vec_alloc: &VecAllocation<'_>,
190 match initialization {
191 InitializationType::UnsafeSetLen(e) => Self::emit_lint(
195 "unsafe vector initialization",
196 UNSAFE_VECTOR_INITIALIZATION,
199 InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
203 "slow zero-filling initialization",
204 SLOW_VECTOR_INITIALIZATION,
210 cx: &LateContext<'_, 'tcx>,
212 vec_alloc: &VecAllocation<'_>,
216 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
218 span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
219 db.span_suggestion_with_applicability(
220 vec_alloc.allocation_expr.span,
221 "consider replace allocation with",
222 format!("vec![0; {}]", len_expr),
223 Applicability::Unspecified,
229 /// `VectorInitializationVisitor` searches for unsafe or slow vector initializations for the given
231 struct VectorInitializationVisitor<'a, 'tcx: 'a> {
232 cx: &'a LateContext<'a, 'tcx>,
234 /// Contains the information
235 vec_alloc: VecAllocation<'tcx>,
237 /// Contains, if found, the slow initialization expression
238 slow_expression: Option<InitializationType<'tcx>>,
240 /// true if the initialization of the vector has been found on the visited block
241 initialization_found: bool,
244 impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
245 /// Checks if the given expression is extending a vector with `repeat(0).take(..)`
246 fn search_slow_extend_filling(&mut self, expr: &'tcx Expr) {
248 if self.initialization_found;
249 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
250 if let ExprKind::Path(ref qpath_subj) = args[0].node;
251 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
252 if path.ident.name == "extend";
253 if let Some(ref extend_arg) = args.get(1);
254 if self.is_repeat_take(extend_arg);
257 self.slow_expression = Some(InitializationType::Extend(expr));
262 /// Checks if the given expression is resizing a vector with 0
263 fn search_slow_resize_filling(&mut self, expr: &'tcx Expr) {
265 if self.initialization_found;
266 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
267 if let ExprKind::Path(ref qpath_subj) = args[0].node;
268 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
269 if path.ident.name == "resize";
270 if let (Some(ref len_arg), Some(fill_arg)) = (args.get(1), args.get(2));
272 // Check that is filled with 0
273 if let ExprKind::Lit(ref lit) = fill_arg.node;
274 if let LitKind::Int(0, _) = lit.node;
276 // Check that len expression is equals to `with_capacity` expression
277 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
280 self.slow_expression = Some(InitializationType::Resize(expr));
285 /// Checks if the given expression is using `set_len` to initialize the vector
286 fn search_unsafe_set_len(&mut self, expr: &'tcx Expr) {
288 if self.initialization_found;
289 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
290 if let ExprKind::Path(ref qpath_subj) = args[0].node;
291 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
292 if path.ident.name == "set_len";
293 if let Some(ref len_arg) = args.get(1);
295 // Check that len expression is equals to `with_capacity` expression
296 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
299 self.slow_expression = Some(InitializationType::UnsafeSetLen(expr));
304 /// Returns `true` if give expression is `repeat(0).take(...)`
305 fn is_repeat_take(&self, expr: &Expr) -> bool {
307 if let ExprKind::MethodCall(ref take_path, _, ref take_args) = expr.node;
308 if take_path.ident.name == "take";
310 // Check that take is applied to `repeat(0)`
311 if let Some(ref repeat_expr) = take_args.get(0);
312 if self.is_repeat_zero(repeat_expr);
314 // Check that len expression is equals to `with_capacity` expression
315 if let Some(ref len_arg) = take_args.get(1);
316 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
326 /// Returns `true` if given expression is `repeat(0)`
327 fn is_repeat_zero(&self, expr: &Expr) -> bool {
329 if let ExprKind::Call(ref fn_expr, ref repeat_args) = expr.node;
330 if let ExprKind::Path(ref qpath_repeat) = fn_expr.node;
331 if match_qpath(&qpath_repeat, &["repeat"]);
332 if let Some(ref repeat_arg) = repeat_args.get(0);
333 if let ExprKind::Lit(ref lit) = repeat_arg.node;
334 if let LitKind::Int(0, _) = lit.node;
345 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
346 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
347 if self.initialization_found {
349 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => {
350 self.search_slow_extend_filling(expr);
351 self.search_slow_resize_filling(expr);
352 self.search_unsafe_set_len(expr);
357 self.initialization_found = false;
359 walk_stmt(self, stmt);
363 fn visit_block(&mut self, block: &'tcx Block) {
364 if self.initialization_found {
365 if let Some(ref s) = block.stmts.get(0) {
369 self.initialization_found = false;
371 walk_block(self, block);
375 fn visit_expr(&mut self, expr: &'tcx Expr) {
376 // Skip all the expressions previous to the vector initialization
377 if self.vec_alloc.allocation_expr.id == expr.id {
378 self.initialization_found = true;
381 walk_expr(self, expr);
384 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
385 NestedVisitorMap::None