]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/vec_init_then_push.rs
Rollup merge of #92642 - avborhanian:master, r=Dylan-DPC
[rust.git] / src / tools / clippy / clippy_lints / src / vec_init_then_push.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher::{get_vec_init_kind, VecInitKind};
3 use clippy_utils::source::snippet;
4 use clippy_utils::{path_to_local, path_to_local_id};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, Stmt, StmtKind};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::Span;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for calls to `push` immediately after creating a new `Vec`.
16     ///
17     /// ### Why is this bad?
18     /// The `vec![]` macro is both more performant and easier to read than
19     /// multiple `push` calls.
20     ///
21     /// ### Example
22     /// ```rust
23     /// let mut v = Vec::new();
24     /// v.push(0);
25     /// ```
26     /// Use instead:
27     /// ```rust
28     /// let v = vec![0];
29     /// ```
30     #[clippy::version = "1.51.0"]
31     pub VEC_INIT_THEN_PUSH,
32     perf,
33     "`push` immediately after `Vec` creation"
34 }
35
36 impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
37
38 #[derive(Default)]
39 pub struct VecInitThenPush {
40     searcher: Option<VecPushSearcher>,
41 }
42
43 struct VecPushSearcher {
44     local_id: HirId,
45     init: VecInitKind,
46     lhs_is_local: bool,
47     lhs_span: Span,
48     err_span: Span,
49     found: u64,
50 }
51 impl VecPushSearcher {
52     fn display_err(&self, cx: &LateContext<'_>) {
53         match self.init {
54             _ if self.found == 0 => return,
55             VecInitKind::WithLiteralCapacity(x) if x > self.found => return,
56             VecInitKind::WithExprCapacity(_) => return,
57             _ => (),
58         };
59
60         let mut s = if self.lhs_is_local {
61             String::from("let ")
62         } else {
63             String::new()
64         };
65         s.push_str(&snippet(cx, self.lhs_span, ".."));
66         s.push_str(" = vec![..];");
67
68         span_lint_and_sugg(
69             cx,
70             VEC_INIT_THEN_PUSH,
71             self.err_span,
72             "calls to `push` immediately after creation",
73             "consider using the `vec![]` macro",
74             s,
75             Applicability::HasPlaceholders,
76         );
77     }
78 }
79
80 impl<'tcx> LateLintPass<'tcx> for VecInitThenPush {
81     fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
82         self.searcher = None;
83     }
84
85     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
86         if_chain! {
87             if !in_external_macro(cx.sess(), local.span);
88             if let Some(init) = local.init;
89             if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind;
90             if let Some(init_kind) = get_vec_init_kind(cx, init);
91             then {
92                 self.searcher = Some(VecPushSearcher {
93                         local_id: id,
94                         init: init_kind,
95                         lhs_is_local: true,
96                         lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)),
97                         err_span: local.span,
98                         found: 0,
99                     });
100             }
101         }
102     }
103
104     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
105         if_chain! {
106             if self.searcher.is_none();
107             if !in_external_macro(cx.sess(), expr.span);
108             if let ExprKind::Assign(left, right, _) = expr.kind;
109             if let Some(id) = path_to_local(left);
110             if let Some(init_kind) = get_vec_init_kind(cx, right);
111             then {
112                 self.searcher = Some(VecPushSearcher {
113                     local_id: id,
114                     init: init_kind,
115                     lhs_is_local: false,
116                     lhs_span: left.span,
117                     err_span: expr.span,
118                     found: 0,
119                 });
120             }
121         }
122     }
123
124     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
125         if let Some(searcher) = self.searcher.take() {
126             if_chain! {
127                 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
128                 if let ExprKind::MethodCall(path, [self_arg, _], _) = expr.kind;
129                 if path_to_local_id(self_arg, searcher.local_id);
130                 if path.ident.name.as_str() == "push";
131                 then {
132                     self.searcher = Some(VecPushSearcher {
133                         found: searcher.found + 1,
134                         err_span: searcher.err_span.to(stmt.span),
135                         .. searcher
136                     });
137                 } else {
138                     searcher.display_err(cx);
139                 }
140             }
141         }
142     }
143
144     fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
145         if let Some(searcher) = self.searcher.take() {
146             searcher.display_err(cx);
147         }
148     }
149 }