1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::sugg::Sugg;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{get_enclosing_block, is_expr_path_def_path, path_to_local, path_to_local_id, paths, SpanlessEq};
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::{walk_block, walk_expr, walk_stmt, NestedVisitorMap, Visitor};
9 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, PatKind, QPath, Stmt, StmtKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::hir::map::Map;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::symbol::sym;
15 declare_clippy_lint! {
17 /// Checks slow zero-filled vector initialization
19 /// ### Why is this bad?
20 /// These structures are non-idiomatic and less efficient than simply using
25 /// # use core::iter::repeat;
29 /// let mut vec1 = Vec::with_capacity(len);
30 /// vec1.resize(len, 0);
32 /// let mut vec2 = Vec::with_capacity(len);
33 /// vec2.extend(repeat(0).take(len));
36 /// let mut vec1 = vec![0; len];
37 /// let mut vec2 = vec![0; len];
39 #[clippy::version = "1.32.0"]
40 pub SLOW_VECTOR_INITIALIZATION,
42 "slow vector initialization"
45 declare_lint_pass!(SlowVectorInit => [SLOW_VECTOR_INITIALIZATION]);
47 /// `VecAllocation` contains data regarding a vector allocated with `with_capacity` and then
48 /// assigned to a variable. For example, `let mut vec = Vec::with_capacity(0)` or
49 /// `vec = Vec::with_capacity(0)`
50 struct VecAllocation<'tcx> {
51 /// HirId of the variable
54 /// Reference to the expression which allocates the vector
55 allocation_expr: &'tcx Expr<'tcx>,
57 /// Reference to the expression used as argument on `with_capacity` call. This is used
58 /// to only match slow zero-filling idioms of the same length than vector initialization.
59 len_expr: &'tcx Expr<'tcx>,
62 /// Type of slow initialization
63 enum InitializationType<'tcx> {
64 /// Extend is a slow initialization with the form `vec.extend(repeat(0).take(..))`
65 Extend(&'tcx Expr<'tcx>),
67 /// Resize is a slow initialization with the form `vec.resize(.., 0)`
68 Resize(&'tcx Expr<'tcx>),
71 impl<'tcx> LateLintPass<'tcx> for SlowVectorInit {
72 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
73 // Matches initialization on reassignements. For example: `vec = Vec::with_capacity(100)`
75 if let ExprKind::Assign(left, right, _) = expr.kind;
78 if let Some(local_id) = path_to_local(left);
80 // Extract len argument
81 if let Some(len_arg) = Self::is_vec_with_capacity(cx, right);
84 let vi = VecAllocation {
86 allocation_expr: right,
90 Self::search_initialization(cx, vi, expr.hir_id);
95 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
96 // Matches statements which initializes vectors. For example: `let mut vec = Vec::with_capacity(10)`
98 if let StmtKind::Local(local) = stmt.kind;
99 if let PatKind::Binding(BindingAnnotation::Mutable, local_id, _, None) = local.pat.kind;
100 if let Some(init) = local.init;
101 if let Some(len_arg) = Self::is_vec_with_capacity(cx, init);
104 let vi = VecAllocation {
106 allocation_expr: init,
110 Self::search_initialization(cx, vi, stmt.hir_id);
116 impl SlowVectorInit {
117 /// Checks if the given expression is `Vec::with_capacity(..)`. It will return the expression
118 /// of the first argument of `with_capacity` call if it matches or `None` if it does not.
119 fn is_vec_with_capacity<'tcx>(cx: &LateContext<'_>, expr: &Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
121 if let ExprKind::Call(func, [arg]) = expr.kind;
122 if let ExprKind::Path(QPath::TypeRelative(ty, name)) = func.kind;
123 if name.ident.as_str() == "with_capacity";
124 if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::Vec);
133 /// Search initialization for the given vector
134 fn search_initialization<'tcx>(cx: &LateContext<'tcx>, vec_alloc: VecAllocation<'tcx>, parent_node: HirId) {
135 let enclosing_body = get_enclosing_block(cx, parent_node);
137 if enclosing_body.is_none() {
141 let mut v = VectorInitializationVisitor {
144 slow_expression: None,
145 initialization_found: false,
148 v.visit_block(enclosing_body.unwrap());
150 if let Some(ref allocation_expr) = v.slow_expression {
151 Self::lint_initialization(cx, allocation_expr, &v.vec_alloc);
155 fn lint_initialization<'tcx>(
156 cx: &LateContext<'tcx>,
157 initialization: &InitializationType<'tcx>,
158 vec_alloc: &VecAllocation<'_>,
160 match initialization {
161 InitializationType::Extend(e) | InitializationType::Resize(e) => {
162 Self::emit_lint(cx, e, vec_alloc, "slow zero-filling initialization");
167 fn emit_lint<'tcx>(cx: &LateContext<'tcx>, slow_fill: &Expr<'_>, vec_alloc: &VecAllocation<'_>, msg: &str) {
168 let len_expr = Sugg::hir(cx, vec_alloc.len_expr, "len");
170 span_lint_and_then(cx, SLOW_VECTOR_INITIALIZATION, slow_fill.span, msg, |diag| {
171 diag.span_suggestion(
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<'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(path, _, [self_arg, extend_arg], _) = expr.kind;
202 if path_to_local_id(self_arg, self.vec_alloc.local_id);
203 if path.ident.name == sym!(extend);
204 if self.is_repeat_take(extend_arg);
207 self.slow_expression = Some(InitializationType::Extend(expr));
212 /// Checks if the given expression is resizing a vector with 0
213 fn search_slow_resize_filling(&mut self, expr: &'tcx Expr<'_>) {
215 if self.initialization_found;
216 if let ExprKind::MethodCall(path, _, [self_arg, len_arg, fill_arg], _) = expr.kind;
217 if path_to_local_id(self_arg, self.vec_alloc.local_id);
218 if path.ident.name == sym!(resize);
220 // Check that is filled with 0
221 if let ExprKind::Lit(ref lit) = fill_arg.kind;
222 if let LitKind::Int(0, _) = lit.node;
224 // Check that len expression is equals to `with_capacity` expression
225 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
228 self.slow_expression = Some(InitializationType::Resize(expr));
233 /// Returns `true` if give expression is `repeat(0).take(...)`
234 fn is_repeat_take(&self, expr: &Expr<'_>) -> bool {
236 if let ExprKind::MethodCall(take_path, _, take_args, _) = expr.kind;
237 if take_path.ident.name == sym!(take);
239 // Check that take is applied to `repeat(0)`
240 if let Some(repeat_expr) = take_args.get(0);
241 if self.is_repeat_zero(repeat_expr);
243 // Check that len expression is equals to `with_capacity` expression
244 if let Some(len_arg) = take_args.get(1);
245 if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr);
255 /// Returns `true` if given expression is `repeat(0)`
256 fn is_repeat_zero(&self, expr: &Expr<'_>) -> bool {
258 if let ExprKind::Call(fn_expr, [repeat_arg]) = expr.kind;
259 if is_expr_path_def_path(self.cx, fn_expr, &paths::ITER_REPEAT);
260 if let ExprKind::Lit(ref lit) = repeat_arg.kind;
261 if let LitKind::Int(0, _) = lit.node;
272 impl<'a, 'tcx> Visitor<'tcx> for VectorInitializationVisitor<'a, 'tcx> {
273 type Map = Map<'tcx>;
275 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
276 if self.initialization_found {
278 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
279 self.search_slow_extend_filling(expr);
280 self.search_slow_resize_filling(expr);
285 self.initialization_found = false;
287 walk_stmt(self, stmt);
291 fn visit_block(&mut self, block: &'tcx Block<'_>) {
292 if self.initialization_found {
293 if let Some(s) = block.stmts.get(0) {
297 self.initialization_found = false;
299 walk_block(self, block);
303 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
304 // Skip all the expressions previous to the vector initialization
305 if self.vec_alloc.allocation_expr.hir_id == expr.hir_id {
306 self.initialization_found = true;
309 walk_expr(self, expr);
312 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
313 NestedVisitorMap::None