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_lint_pass, declare_tool_lint};
8 use rustc_errors::Applicability;
9 use syntax::ast::LitKind;
10 use syntax_pos::symbol::Symbol;
12 declare_clippy_lint! {
13 /// **What it does:** Checks slow zero-filled vector initialization
15 /// **Why is this bad?** These structures are non-idiomatic and less efficient than simply using
18 /// **Known problems:** None.
22 /// let mut vec1 = Vec::with_capacity(len);
23 /// vec1.resize(len, 0);
25 /// let mut vec2 = Vec::with_capacity(len);
26 /// vec2.extend(repeat(0).take(len))
28 pub SLOW_VECTOR_INITIALIZATION,
30 "slow vector initialization"
33 declare_lint_pass!(SlowVectorInit => [SLOW_VECTOR_INITIALIZATION]);
35 /// `VecAllocation` contains data regarding a vector allocated with `with_capacity` and then
36 /// assigned to a variable. For example, `let mut vec = Vec::with_capacity(0)` or
37 /// `vec = Vec::with_capacity(0)`
38 struct VecAllocation<'tcx> {
39 /// Symbol of the local variable name
40 variable_name: Symbol,
42 /// Reference to the expression which allocates the vector
43 allocation_expr: &'tcx Expr,
45 /// Reference to the expression used as argument on `with_capacity` call. This is used
46 /// to only match slow zero-filling idioms of the same length than vector initialization.
50 /// Type of slow initialization
51 enum InitializationType<'tcx> {
52 /// Extend is a slow initialization with the form `vec.extend(repeat(0).take(..))`
55 /// Resize is a slow initialization with the form `vec.resize(.., 0)`
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SlowVectorInit {
60 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
61 // Matches initialization on reassignements. For example: `vec = Vec::with_capacity(100)`
63 if let ExprKind::Assign(ref left, ref right) = expr.node;
65 // Extract variable name
66 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node;
67 if let Some(variable_name) = path.segments.get(0);
69 // Extract len argument
70 if let Some(ref len_arg) = Self::is_vec_with_capacity(right);
73 let vi = VecAllocation {
74 variable_name: variable_name.ident.name,
75 allocation_expr: right,
79 Self::search_initialization(cx, vi, expr.hir_id);
84 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
85 // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
87 if let StmtKind::Local(ref local) = stmt.node;
88 if let PatKind::Binding(BindingAnnotation::Mutable, .., variable_name, None) = local.pat.node;
89 if let Some(ref init) = local.init;
90 if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
93 let vi = VecAllocation {
94 variable_name: variable_name.name,
95 allocation_expr: init,
99 Self::search_initialization(cx, vi, stmt.hir_id);
105 impl SlowVectorInit {
106 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
107 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
108 fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
110 if let ExprKind::Call(ref func, ref args) = expr.node;
111 if let ExprKind::Path(ref path) = func.node;
112 if match_qpath(path, &["Vec", "with_capacity"]);
116 return Some(&args[0]);
123 /// Search initialization for the given vector
124 fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: HirId) {
125 let enclosing_body = get_enclosing_block(cx, parent_node);
127 if enclosing_body.is_none() {
131 let mut v = VectorInitializationVisitor {
134 slow_expression: None,
135 initialization_found: false,
138 v.visit_block(enclosing_body.unwrap());
140 if let Some(ref allocation_expr) = v.slow_expression {
141 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
145 fn lint_initialization<'tcx>(
146 cx: &LateContext<'_, 'tcx>,
147 initialization: &InitializationType<'tcx>,
148 vec_alloc: &VecAllocation<'_>,
150 match initialization {
151 InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
155 "slow zero-filling initialization",
156 SLOW_VECTOR_INITIALIZATION,
162 cx: &LateContext<'_, 'tcx>,
164 vec_alloc: &VecAllocation<'_>,
168 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
170 span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
172 vec_alloc.allocation_expr.span,
173 "consider replace allocation with",
174 format!("vec![0; {}]", len_expr),
175 Applicability::Unspecified,
181 /// `VectorInitializationVisitor` searches for unsafe or slow vector initializations for the given
183 struct VectorInitializationVisitor<'a, 'tcx> {
184 cx: &'a LateContext<'a, 'tcx>,
186 /// Contains the information.
187 vec_alloc: VecAllocation<'tcx>,
189 /// Contains the slow initialization expression, if one was found.
190 slow_expression: Option<InitializationType<'tcx>>,
192 /// `true` if the initialization of the vector has been found on the visited block.
193 initialization_found: bool,
196 impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
197 /// Checks if the given expression is extending a vector with `repeat(0).take(..)`
198 fn search_slow_extend_filling(&mut self, expr: &'tcx Expr) {
200 if self.initialization_found;
201 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
202 if let ExprKind::Path(ref qpath_subj) = args[0].node;
203 if match_qpath(&qpath_subj, &[&*self.vec_alloc.variable_name.as_str()]);
204 if path.ident.name == sym!(extend);
205 if let Some(ref extend_arg) = args.get(1);
206 if self.is_repeat_take(extend_arg);
209 self.slow_expression = Some(InitializationType::Extend(expr));
214 /// Checks if the given expression is resizing a vector with 0
215 fn search_slow_resize_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.as_str()]);
221 if path.ident.name == sym!(resize);
222 if let (Some(ref len_arg), Some(fill_arg)) = (args.get(1), args.get(2));
224 // Check that is filled with 0
225 if let ExprKind::Lit(ref lit) = fill_arg.node;
226 if let LitKind::Int(0, _) = lit.node;
228 // Check that len expression is equals to `with_capacity` expression
229 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
232 self.slow_expression = Some(InitializationType::Resize(expr));
237 /// Returns `true` if give expression is `repeat(0).take(...)`
238 fn is_repeat_take(&self, expr: &Expr) -> bool {
240 if let ExprKind::MethodCall(ref take_path, _, ref take_args) = expr.node;
241 if take_path.ident.name == sym!(take);
243 // Check that take is applied to `repeat(0)`
244 if let Some(ref repeat_expr) = take_args.get(0);
245 if self.is_repeat_zero(repeat_expr);
247 // Check that len expression is equals to `with_capacity` expression
248 if let Some(ref len_arg) = take_args.get(1);
249 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
259 /// Returns `true` if given expression is `repeat(0)`
260 fn is_repeat_zero(&self, expr: &Expr) -> bool {
262 if let ExprKind::Call(ref fn_expr, ref repeat_args) = expr.node;
263 if let ExprKind::Path(ref qpath_repeat) = fn_expr.node;
264 if match_qpath(&qpath_repeat, &["repeat"]);
265 if let Some(ref repeat_arg) = repeat_args.get(0);
266 if let ExprKind::Lit(ref lit) = repeat_arg.node;
267 if let LitKind::Int(0, _) = lit.node;
278 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
279 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
280 if self.initialization_found {
282 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
283 self.search_slow_extend_filling(expr);
284 self.search_slow_resize_filling(expr);
289 self.initialization_found = false;
291 walk_stmt(self, stmt);
295 fn visit_block(&mut self, block: &'tcx Block) {
296 if self.initialization_found {
297 if let Some(ref s) = block.stmts.get(0) {
301 self.initialization_found = false;
303 walk_block(self, block);
307 fn visit_expr(&mut self, expr: &'tcx Expr) {
308 // Skip all the expressions previous to the vector initialization
309 if self.vec_alloc.allocation_expr.hir_id == expr.hir_id {
310 self.initialization_found = true;
313 walk_expr(self, expr);
316 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
317 NestedVisitorMap::None