]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec_init_then_push.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[rust.git] / clippy_lints / src / vec_init_then_push.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{match_def_path, path_to_local, path_to_local_id, paths};
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, Stmt, StmtKind};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::{symbol::sym, Span};
13 use std::convert::TryInto;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for calls to `push` immediately after creating a new `Vec`.
17     ///
18     /// **Why is this bad?** The `vec![]` macro is both more performant and easier to read than
19     /// multiple `push` calls.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     ///
25     /// ```rust
26     /// let mut v = Vec::new();
27     /// v.push(0);
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// let v = vec![0];
32     /// ```
33     pub VEC_INIT_THEN_PUSH,
34     perf,
35     "`push` immediately after `Vec` creation"
36 }
37
38 impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
39
40 #[derive(Default)]
41 pub struct VecInitThenPush {
42     searcher: Option<VecPushSearcher>,
43 }
44
45 #[derive(Clone, Copy)]
46 enum VecInitKind {
47     New,
48     WithCapacity(u64),
49 }
50 struct VecPushSearcher {
51     local_id: HirId,
52     init: VecInitKind,
53     lhs_is_local: bool,
54     lhs_span: Span,
55     err_span: Span,
56     found: u64,
57 }
58 impl VecPushSearcher {
59     fn display_err(&self, cx: &LateContext<'_>) {
60         match self.init {
61             _ if self.found == 0 => return,
62             VecInitKind::WithCapacity(x) if x > self.found => return,
63             _ => (),
64         };
65
66         let mut s = if self.lhs_is_local {
67             String::from("let ")
68         } else {
69             String::new()
70         };
71         s.push_str(&snippet(cx, self.lhs_span, ".."));
72         s.push_str(" = vec![..];");
73
74         span_lint_and_sugg(
75             cx,
76             VEC_INIT_THEN_PUSH,
77             self.err_span,
78             "calls to `push` immediately after creation",
79             "consider using the `vec![]` macro",
80             s,
81             Applicability::HasPlaceholders,
82         );
83     }
84 }
85
86 impl LateLintPass<'_> for VecInitThenPush {
87     fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
88         self.searcher = None;
89     }
90
91     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
92         if_chain! {
93             if !in_external_macro(cx.sess(), local.span);
94             if let Some(init) = local.init;
95             if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind;
96             if let Some(init_kind) = get_vec_init_kind(cx, init);
97             then {
98                 self.searcher = Some(VecPushSearcher {
99                         local_id: id,
100                         init: init_kind,
101                         lhs_is_local: true,
102                         lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)),
103                         err_span: local.span,
104                         found: 0,
105                     });
106             }
107         }
108     }
109
110     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
111         if self.searcher.is_none() {
112             if_chain! {
113                 if !in_external_macro(cx.sess(), expr.span);
114                 if let ExprKind::Assign(left, right, _) = expr.kind;
115                 if let Some(id) = path_to_local(left);
116                 if let Some(init_kind) = get_vec_init_kind(cx, right);
117                 then {
118                     self.searcher = Some(VecPushSearcher {
119                         local_id: id,
120                         init: init_kind,
121                         lhs_is_local: false,
122                         lhs_span: left.span,
123                         err_span: expr.span,
124                         found: 0,
125                     });
126                 }
127             }
128         }
129     }
130
131     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
132         if let Some(searcher) = self.searcher.take() {
133             if_chain! {
134                 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
135                 if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind;
136                 if path_to_local_id(self_arg, searcher.local_id);
137                 if path.ident.name.as_str() == "push";
138                 then {
139                     self.searcher = Some(VecPushSearcher {
140                         found: searcher.found + 1,
141                         err_span: searcher.err_span.to(stmt.span),
142                         .. searcher
143                     });
144                 } else {
145                     searcher.display_err(cx);
146                 }
147             }
148         }
149     }
150
151     fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
152         if let Some(searcher) = self.searcher.take() {
153             searcher.display_err(cx);
154         }
155     }
156 }
157
158 fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> {
159     if let ExprKind::Call(func, args) = expr.kind {
160         match func.kind {
161             ExprKind::Path(QPath::TypeRelative(ty, name))
162                 if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::vec_type) =>
163             {
164                 if name.ident.name == sym::new {
165                     return Some(VecInitKind::New);
166                 } else if name.ident.name.as_str() == "with_capacity" {
167                     return args.get(0).and_then(|arg| {
168                         if_chain! {
169                             if let ExprKind::Lit(lit) = &arg.kind;
170                             if let LitKind::Int(num, _) = lit.node;
171                             then {
172                                 Some(VecInitKind::WithCapacity(num.try_into().ok()?))
173                             } else {
174                                 None
175                             }
176                         }
177                     });
178                 }
179             }
180             ExprKind::Path(QPath::Resolved(_, path))
181                 if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)
182                     && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type) =>
183             {
184                 return Some(VecInitKind::New);
185             }
186             _ => (),
187         }
188     }
189     None
190 }