]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/vec_init_then_push.rs
Rollup merge of #89839 - jkugelman:must-use-mem-ptr-functions, r=joshtriplett
[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     pub VEC_INIT_THEN_PUSH,
31     perf,
32     "`push` immediately after `Vec` creation"
33 }
34
35 impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
36
37 #[derive(Default)]
38 pub struct VecInitThenPush {
39     searcher: Option<VecPushSearcher>,
40 }
41
42 struct VecPushSearcher {
43     local_id: HirId,
44     init: VecInitKind,
45     lhs_is_local: bool,
46     lhs_span: Span,
47     err_span: Span,
48     found: u64,
49 }
50 impl VecPushSearcher {
51     fn display_err(&self, cx: &LateContext<'_>) {
52         match self.init {
53             _ if self.found == 0 => return,
54             VecInitKind::WithLiteralCapacity(x) if x > self.found => return,
55             VecInitKind::WithExprCapacity(_) => return,
56             _ => (),
57         };
58
59         let mut s = if self.lhs_is_local {
60             String::from("let ")
61         } else {
62             String::new()
63         };
64         s.push_str(&snippet(cx, self.lhs_span, ".."));
65         s.push_str(" = vec![..];");
66
67         span_lint_and_sugg(
68             cx,
69             VEC_INIT_THEN_PUSH,
70             self.err_span,
71             "calls to `push` immediately after creation",
72             "consider using the `vec![]` macro",
73             s,
74             Applicability::HasPlaceholders,
75         );
76     }
77 }
78
79 impl LateLintPass<'_> for VecInitThenPush {
80     fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
81         self.searcher = None;
82     }
83
84     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
85         if_chain! {
86             if !in_external_macro(cx.sess(), local.span);
87             if let Some(init) = local.init;
88             if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind;
89             if let Some(init_kind) = get_vec_init_kind(cx, init);
90             then {
91                 self.searcher = Some(VecPushSearcher {
92                         local_id: id,
93                         init: init_kind,
94                         lhs_is_local: true,
95                         lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)),
96                         err_span: local.span,
97                         found: 0,
98                     });
99             }
100         }
101     }
102
103     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
104         if_chain! {
105             if self.searcher.is_none();
106             if !in_external_macro(cx.sess(), expr.span);
107             if let ExprKind::Assign(left, right, _) = expr.kind;
108             if let Some(id) = path_to_local(left);
109             if let Some(init_kind) = get_vec_init_kind(cx, right);
110             then {
111                 self.searcher = Some(VecPushSearcher {
112                     local_id: id,
113                     init: init_kind,
114                     lhs_is_local: false,
115                     lhs_span: left.span,
116                     err_span: expr.span,
117                     found: 0,
118                 });
119             }
120         }
121     }
122
123     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
124         if let Some(searcher) = self.searcher.take() {
125             if_chain! {
126                 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
127                 if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind;
128                 if path_to_local_id(self_arg, searcher.local_id);
129                 if path.ident.name.as_str() == "push";
130                 then {
131                     self.searcher = Some(VecPushSearcher {
132                         found: searcher.found + 1,
133                         err_span: searcher.err_span.to(stmt.span),
134                         .. searcher
135                     });
136                 } else {
137                     searcher.display_err(cx);
138                 }
139             }
140         }
141     }
142
143     fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
144         if let Some(searcher) = self.searcher.take() {
145             searcher.display_err(cx);
146         }
147     }
148 }