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::Local(ref local) = stmt.node;
95 if let PatKind::Binding(BindingAnnotation::Mutable, _, variable_name, None) = local.pat.node;
96 if let Some(ref init) = local.init;
97 if let Some(ref len_arg) = Self::is_vec_with_capacity(init);
100 let vi = VecAllocation {
101 variable_name: variable_name.name,
102 allocation_expr: init,
106 Self::search_initialization(cx, vi, stmt.id);
113 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
114 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
115 fn is_vec_with_capacity(expr: &Expr) -> Option<&Expr> {
117 if let ExprKind::Call(ref func, ref args) = expr.node;
118 if let ExprKind::Path(ref path) = func.node;
119 if match_qpath(path, &["Vec", "with_capacity"]);
123 return Some(&args[0]);
130 /// Search initialization for the given vector
131 fn search_initialization<'tcx>(cx: &LateContext<'_, 'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: NodeId) {
132 let enclosing_body = get_enclosing_block(cx, parent_node);
134 if enclosing_body.is_none() {
138 let mut v = VectorInitializationVisitor {
141 slow_expression: None,
142 initialization_found: false,
145 v.visit_block(enclosing_body.unwrap());
147 if let Some(ref allocation_expr) = v.slow_expression {
148 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
152 fn lint_initialization<'tcx>(
153 cx: &LateContext<'_, 'tcx>,
154 initialization: &InitializationType<'tcx>,
155 vec_alloc: &VecAllocation<'_>,
157 match initialization {
158 InitializationType::Extend(e) | InitializationType::Resize(e) => Self::emit_lint(
162 "slow zero-filling initialization",
163 SLOW_VECTOR_INITIALIZATION,
169 cx: &LateContext<'_, 'tcx>,
171 vec_alloc: &VecAllocation<'_>,
175 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
177 span_lint_and_then(cx, lint, slow_fill.span, msg, |db| {
178 db.span_suggestion_with_applicability(
179 vec_alloc.allocation_expr.span,
180 "consider replace allocation with",
181 format!("vec![0; {}]", len_expr),
182 Applicability::Unspecified,
188 /// `VectorInitializationVisitor` searches for unsafe or slow vector initializations for the given
190 struct VectorInitializationVisitor<'a, 'tcx: 'a> {
191 cx: &'a LateContext<'a, 'tcx>,
193 /// Contains the information
194 vec_alloc: VecAllocation<'tcx>,
196 /// Contains, if found, the slow initialization expression
197 slow_expression: Option<InitializationType<'tcx>>,
199 /// true if the initialization of the vector has been found on the visited block
200 initialization_found: bool,
203 impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
204 /// Checks if the given expression is extending a vector with `repeat(0).take(..)`
205 fn search_slow_extend_filling(&mut self, expr: &'tcx Expr) {
207 if self.initialization_found;
208 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
209 if let ExprKind::Path(ref qpath_subj) = args[0].node;
210 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
211 if path.ident.name == "extend";
212 if let Some(ref extend_arg) = args.get(1);
213 if self.is_repeat_take(extend_arg);
216 self.slow_expression = Some(InitializationType::Extend(expr));
221 /// Checks if the given expression is resizing a vector with 0
222 fn search_slow_resize_filling(&mut self, expr: &'tcx Expr) {
224 if self.initialization_found;
225 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
226 if let ExprKind::Path(ref qpath_subj) = args[0].node;
227 if match_qpath(&qpath_subj, &[&self.vec_alloc.variable_name.to_string()]);
228 if path.ident.name == "resize";
229 if let (Some(ref len_arg), Some(fill_arg)) = (args.get(1), args.get(2));
231 // Check that is filled with 0
232 if let ExprKind::Lit(ref lit) = fill_arg.node;
233 if let LitKind::Int(0, _) = lit.node;
235 // Check that len expression is equals to `with_capacity` expression
236 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
239 self.slow_expression = Some(InitializationType::Resize(expr));
244 /// Returns `true` if give expression is `repeat(0).take(...)`
245 fn is_repeat_take(&self, expr: &Expr) -> bool {
247 if let ExprKind::MethodCall(ref take_path, _, ref take_args) = expr.node;
248 if take_path.ident.name == "take";
250 // Check that take is applied to `repeat(0)`
251 if let Some(ref repeat_expr) = take_args.get(0);
252 if self.is_repeat_zero(repeat_expr);
254 // Check that len expression is equals to `with_capacity` expression
255 if let Some(ref len_arg) = take_args.get(1);
256 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
266 /// Returns `true` if given expression is `repeat(0)`
267 fn is_repeat_zero(&self, expr: &Expr) -> bool {
269 if let ExprKind::Call(ref fn_expr, ref repeat_args) = expr.node;
270 if let ExprKind::Path(ref qpath_repeat) = fn_expr.node;
271 if match_qpath(&qpath_repeat, &["repeat"]);
272 if let Some(ref repeat_arg) = repeat_args.get(0);
273 if let ExprKind::Lit(ref lit) = repeat_arg.node;
274 if let LitKind::Int(0, _) = lit.node;
285 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
286 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
287 if self.initialization_found {
289 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => {
290 self.search_slow_extend_filling(expr);
291 self.search_slow_resize_filling(expr);
296 self.initialization_found = false;
298 walk_stmt(self, stmt);
302 fn visit_block(&mut self, block: &'tcx Block) {
303 if self.initialization_found {
304 if let Some(ref s) = block.stmts.get(0) {
308 self.initialization_found = false;
310 walk_block(self, block);
314 fn visit_expr(&mut self, expr: &'tcx Expr) {
315 // Skip all the expressions previous to the vector initialization
316 if self.vec_alloc.allocation_expr.id == expr.id {
317 self.initialization_found = true;
320 walk_expr(self, expr);
323 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
324 NestedVisitorMap::None