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