1 use crate::utils::sugg::Sugg;
3 use crate::utils::{get_enclosing_block, match_qpath, span_lint_and_then, SpanlessEq};
4 use if_chain::if_chain;
5 use rustc::hir::intravisit::{walk_block, walk_expr, walk_stmt, NestedVisitorMap, Visitor};
7 use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
8 use rustc::{declare_lint_pass, declare_tool_lint};
9 use rustc_errors::Applicability;
10 use syntax::ast::LitKind;
11 use syntax_pos::symbol::Symbol;
13 declare_clippy_lint! {
14 /// **What it does:** Checks slow zero-filled vector initialization
16 /// **Why is this bad?** These structures are non-idiomatic and less efficient than simply using
19 /// **Known problems:** None.
23 /// let mut vec1 = Vec::with_capacity(len);
24 /// vec1.resize(len, 0);
26 /// let mut vec2 = Vec::with_capacity(len);
27 /// vec2.extend(repeat(0).take(len))
29 pub SLOW_VECTOR_INITIALIZATION,
31 "slow vector initialization"
34 declare_lint_pass!(SlowVectorInit => [SLOW_VECTOR_INITIALIZATION]);
36 /// `VecAllocation` contains data regarding a vector allocated with `with_capacity` and then
37 /// assigned to a variable. For example, `let mut vec = Vec::with_capacity(0)` or
38 /// `vec = Vec::with_capacity(0)`
39 struct VecAllocation<'tcx> {
40 /// Symbol of the local variable name
41 variable_name: Symbol,
43 /// Reference to the expression which allocates the vector
44 allocation_expr: &'tcx Expr,
46 /// Reference to the expression used as argument on `with_capacity` call. This is used
47 /// to only match slow zero-filling idioms of the same length than vector initialization.
51 /// Type of slow initialization
52 enum InitializationType<'tcx> {
53 /// Extend is a slow initialization with the form `vec.extend(repeat(0).take(..))`
56 /// Resize is a slow initialization with the form `vec.resize(.., 0)`
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SlowVectorInit {
61 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
62 // Matches initialization on reassignements. For example: `vec = Vec::with_capacity(100)`
64 if let ExprKind::Assign(ref left, ref right) = expr.node;
66 // Extract variable name
67 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node;
68 if let Some(variable_name) = path.segments.get(0);
70 // Extract len argument
71 if let Some(ref len_arg) = Self::is_vec_with_capacity(right);
74 let vi = VecAllocation {
75 variable_name: variable_name.ident.name,
76 allocation_expr: right,
80 Self::search_initialization(cx, vi, expr.hir_id);
85 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
86 // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
88 if let StmtKind::Local(ref local) = stmt.node;
89 if let PatKind::Binding(BindingAnnotation::Mutable, .., variable_name, None) = local.pat.node;
90 if let Some(ref init) = local.init;
91 if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
94 let vi = VecAllocation {
95 variable_name: variable_name.name,
96 allocation_expr: init,
100 Self::search_initialization(cx, vi, stmt.hir_id);
106 impl SlowVectorInit {
107 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
108 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
109 fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
111 if let ExprKind::Call(ref func, ref args) = expr.node;
112 if let ExprKind::Path(ref path) = func.node;
113 if match_qpath(path, &[*sym::Vec, *sym::with_capacity]);
117 return Some(&args[0]);
124 /// Search initialization for the given vector
125 fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: HirId) {
126 let enclosing_body = get_enclosing_block(cx, parent_node);
128 if enclosing_body.is_none() {
132 let mut v = VectorInitializationVisitor {
135 slow_expression: None,
136 initialization_found: false,
139 v.visit_block(enclosing_body.unwrap());
141 if let Some(ref allocation_expr) = v.slow_expression {
142 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
146 fn lint_initialization<'tcx>(
147 cx: &LateContext<'_, 'tcx>,
148 initialization: &InitializationType<'tcx>,
149 vec_alloc: &VecAllocation<'_>,
151 match initialization {
152 InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
156 "slow zero-filling initialization",
157 SLOW_VECTOR_INITIALIZATION,
163 cx: &LateContext<'_, 'tcx>,
165 vec_alloc: &VecAllocation<'_>,
169 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
171 span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
173 vec_alloc.allocation_expr.span,
174 "consider replace allocation with",
175 format!("vec![0; {}]", len_expr),
176 Applicability::Unspecified,
182 /// `VectorInitializationVisitor` searches for unsafe or slow vector initializations for the given
184 struct VectorInitializationVisitor<'a, 'tcx: 'a> {
185 cx: &'a LateContext<'a, 'tcx>,
187 /// Contains the information.
188 vec_alloc: VecAllocation<'tcx>,
190 /// Contains the slow initialization expression, if one was found.
191 slow_expression: Option<InitializationType<'tcx>>,
193 /// `true` if the initialization of the vector has been found on the visited block.
194 initialization_found: bool,
197 impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
198 /// Checks if the given expression is extending a vector with `repeat(0).take(..)`
199 fn search_slow_extend_filling(&mut self, expr: &'tcx Expr) {
201 if self.initialization_found;
202 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
203 if let ExprKind::Path(ref qpath_subj) = args[0].node;
204 if match_qpath(&qpath_subj, &[self.vec_alloc.variable_name]);
205 if path.ident.name == *sym::extend;
206 if let Some(ref extend_arg) = args.get(1);
207 if self.is_repeat_take(extend_arg);
210 self.slow_expression = Some(InitializationType::Extend(expr));
215 /// Checks if the given expression is resizing a vector with 0
216 fn search_slow_resize_filling(&mut self, expr: &'tcx Expr) {
218 if self.initialization_found;
219 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
220 if let ExprKind::Path(ref qpath_subj) = args[0].node;
221 if match_qpath(&qpath_subj, &[self.vec_alloc.variable_name]);
222 if path.ident.name == *sym::resize;
223 if let (Some(ref len_arg), Some(fill_arg)) = (args.get(1), args.get(2));
225 // Check that is filled with 0
226 if let ExprKind::Lit(ref lit) = fill_arg.node;
227 if let LitKind::Int(0, _) = lit.node;
229 // Check that len expression is equals to `with_capacity` expression
230 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
233 self.slow_expression = Some(InitializationType::Resize(expr));
238 /// Returns `true` if give expression is `repeat(0).take(...)`
239 fn is_repeat_take(&self, expr: &Expr) -> bool {
241 if let ExprKind::MethodCall(ref take_path, _, ref take_args) = expr.node;
242 if take_path.ident.name == *sym::take;
244 // Check that take is applied to `repeat(0)`
245 if let Some(ref repeat_expr) = take_args.get(0);
246 if self.is_repeat_zero(repeat_expr);
248 // Check that len expression is equals to `with_capacity` expression
249 if let Some(ref len_arg) = take_args.get(1);
250 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
260 /// Returns `true` if given expression is `repeat(0)`
261 fn is_repeat_zero(&self, expr: &Expr) -> bool {
263 if let ExprKind::Call(ref fn_expr, ref repeat_args) = expr.node;
264 if let ExprKind::Path(ref qpath_repeat) = fn_expr.node;
265 if match_qpath(&qpath_repeat, &[*sym::repeat]);
266 if let Some(ref repeat_arg) = repeat_args.get(0);
267 if let ExprKind::Lit(ref lit) = repeat_arg.node;
268 if let LitKind::Int(0, _) = lit.node;
279 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
280 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
281 if self.initialization_found {
283 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
284 self.search_slow_extend_filling(expr);
285 self.search_slow_resize_filling(expr);
290 self.initialization_found = false;
292 walk_stmt(self, stmt);
296 fn visit_block(&mut self, block: &'tcx Block) {
297 if self.initialization_found {
298 if let Some(ref s) = block.stmts.get(0) {
302 self.initialization_found = false;
304 walk_block(self, block);
308 fn visit_expr(&mut self, expr: &'tcx Expr) {
309 // Skip all the expressions previous to the vector initialization
310 if self.vec_alloc.allocation_expr.hir_id == expr.hir_id {
311 self.initialization_found = true;
314 walk_expr(self, expr);
317 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
318 NestedVisitorMap::None