1 use crate::utils::sugg::Sugg;
2 use crate::utils::{get_enclosing_block, match_qpath, span_lint_and_then, SpanlessEq};
3 use if_chain::if_chain;
4 use rustc::hir::intravisit::{walk_block, walk_expr, walk_stmt, NestedVisitorMap, Visitor};
6 use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
9 use syntax::ast::{LitKind, NodeId};
10 use syntax_pos::symbol::Symbol;
12 /// **What it does:** Checks slow zero-filled vector initialization
14 /// **Why is this bad?** This structures are non-idiomatic and less efficient than simply using
17 /// **Known problems:** None.
21 /// let mut vec1 = Vec::with_capacity(len);
22 /// vec1.resize(len, 0);
24 /// let mut vec2 = Vec::with_capacity(len);
25 /// vec2.extend(repeat(0).take(len))
27 declare_clippy_lint! {
28 pub SLOW_VECTOR_INITIALIZATION,
30 "slow vector initialization"
33 #[derive(Copy, Clone, Default)]
36 impl LintPass for Pass {
37 fn get_lints(&self) -> LintArray {
38 lint_array!(SLOW_VECTOR_INITIALIZATION,)
42 /// `VecAllocation` contains data regarding a vector allocated with `with_capacity` and then
43 /// assigned to a variable. For example, `let mut vec = Vec::with_capacity(0)` or
44 /// `vec = Vec::with_capacity(0)`
45 struct VecAllocation<'tcx> {
46 /// Symbol of the local variable name
47 variable_name: Symbol,
49 /// Reference to the expression which allocates the vector
50 allocation_expr: &'tcx Expr,
52 /// Reference to the expression used as argument on `with_capacity` call. This is used
53 /// to only match slow zero-filling idioms of the same length than vector initialization.
57 /// Type of slow initialization
58 enum InitializationType<'tcx> {
59 /// Extend is a slow initialization with the form `vec.extend(repeat(0).take(..))`
62 /// Resize is a slow initialization with the form `vec.resize(.., 0)`
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
67 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
68 // Matches initialization on reassignements. For example: `vec = Vec::with_capacity(100)`
70 if let ExprKind::Assign(ref left, ref right) = expr.node;
72 // Extract variable name
73 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node;
74 if let Some(variable_name) = path.segments.get(0);
76 // Extract len argument
77 if let Some(ref len_arg) = Self::is_vec_with_capacity(right);
80 let vi = VecAllocation {
81 variable_name: variable_name.ident.name,
82 allocation_expr: right,
86 Self::search_initialization(cx, vi, expr.id);
91 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
92 // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
94 if let StmtKind::Decl(ref decl, _) = stmt.node;
95 if let DeclKind::Local(ref local) = decl.node;
96 if let PatKind::Binding(BindingAnnotation::Mutable, _, variable_name, None) = local.pat.node;
97 if let Some(ref init) = local.init;
98 if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
101 let vi = VecAllocation {
102 variable_name: variable_name.name,
103 allocation_expr: init,
107 Self::search_initialization(cx, vi, stmt.node.id());
114 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
115 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
116 fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
118 if let ExprKind::Call(ref func, ref args) = expr.node;
119 if let ExprKind::Path(ref path) = func.node;
120 if match_qpath(path, &["Vec", "with_capacity"]);
124 return Some(&args[0]);
131 /// Search initialization for the given vector
132 fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: NodeId) {
133 let enclosing_body = get_enclosing_block(cx, parent_node);
135 if enclosing_body.is_none() {
139 let mut v = VectorInitializationVisitor {
142 slow_expression: None,
143 initialization_found: false,
146 v.visit_block(enclosing_body.unwrap());
148 if let Some(ref allocation_expr) = v.slow_expression {
149 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
153 fn lint_initialization<'tcx>(
154 cx: &LateContext<'_, 'tcx>,
155 initialization: &InitializationType<'tcx>,
156 vec_alloc: &VecAllocation<'_>,
158 match initialization {
159 InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
163 "slow zero-filling initialization",
164 SLOW_VECTOR_INITIALIZATION,
170 cx: &LateContext<'_, 'tcx>,
172 vec_alloc: &VecAllocation<'_>,
176 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
178 span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
179 db.span_suggestion_with_applicability(
180 vec_alloc.allocation_expr.span,
181 "consider replace allocation with",
182 format!("vec![0; {}]", len_expr),
183 Applicability::Unspecified,
189 /// `VectorInitializationVisitor` searches for unsafe or slow vector initializations for the given
191 struct VectorInitializationVisitor<'a, 'tcx: 'a> {
192 cx: &'a LateContext<'a, 'tcx>,
194 /// Contains the information
195 vec_alloc: VecAllocation<'tcx>,
197 /// Contains, if found, the slow initialization expression
198 slow_expression: Option<InitializationType<'tcx>>,
200 /// true if the initialization of the vector has been found on the visited block
201 initialization_found: bool,
204 impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
205 /// Checks if the given expression is extending a vector with `repeat(0).take(..)`
206 fn search_slow_extend_filling(&mut self, expr: &'tcx Expr) {
208 if self.initialization_found;
209 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
210 if let ExprKind::Path(ref qpath_subj) = args[0].node;
211 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
212 if path.ident.name == "extend";
213 if let Some(ref extend_arg) = args.get(1);
214 if self.is_repeat_take(extend_arg);
217 self.slow_expression = Some(InitializationType::Extend(expr));
222 /// Checks if the given expression is resizing a vector with 0
223 fn search_slow_resize_filling(&mut self, expr: &'tcx Expr) {
225 if self.initialization_found;
226 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
227 if let ExprKind::Path(ref qpath_subj) = args[0].node;
228 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
229 if path.ident.name == "resize";
230 if let (Some(ref len_arg), Some(fill_arg)) = (args.get(1), args.get(2));
232 // Check that is filled with 0
233 if let ExprKind::Lit(ref lit) = fill_arg.node;
234 if let LitKind::Int(0, _) = lit.node;
236 // Check that len expression is equals to `with_capacity` expression
237 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
240 self.slow_expression = Some(InitializationType::Resize(expr));
245 /// Returns `true` if give expression is `repeat(0).take(...)`
246 fn is_repeat_take(&self, expr: &Expr) -> bool {
248 if let ExprKind::MethodCall(ref take_path, _, ref take_args) = expr.node;
249 if take_path.ident.name == "take";
251 // Check that take is applied to `repeat(0)`
252 if let Some(ref repeat_expr) = take_args.get(0);
253 if self.is_repeat_zero(repeat_expr);
255 // Check that len expression is equals to `with_capacity` expression
256 if let Some(ref len_arg) = take_args.get(1);
257 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
267 /// Returns `true` if given expression is `repeat(0)`
268 fn is_repeat_zero(&self, expr: &Expr) -> bool {
270 if let ExprKind::Call(ref fn_expr, ref repeat_args) = expr.node;
271 if let ExprKind::Path(ref qpath_repeat) = fn_expr.node;
272 if match_qpath(&qpath_repeat, &["repeat"]);
273 if let Some(ref repeat_arg) = repeat_args.get(0);
274 if let ExprKind::Lit(ref lit) = repeat_arg.node;
275 if let LitKind::Int(0, _) = lit.node;
286 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
287 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
288 if self.initialization_found {
290 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => {
291 self.search_slow_extend_filling(expr);
292 self.search_slow_resize_filling(expr);
297 self.initialization_found = false;
299 walk_stmt(self, stmt);
303 fn visit_block(&mut self, block: &'tcx Block) {
304 if self.initialization_found {
305 if let Some(ref s) = block.stmts.get(0) {
309 self.initialization_found = false;
311 walk_block(self, block);
315 fn visit_expr(&mut self, expr: &'tcx Expr) {
316 // Skip all the expressions previous to the vector initialization
317 if self.vec_alloc.allocation_expr.id == expr.id {
318 self.initialization_found = true;
321 walk_expr(self, expr);
324 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
325 NestedVisitorMap::None