]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/vec_init_then_push.rs
Add 'library/portable-simd/' from commit '1ce1c645cf27c4acdefe6ec8a11d1f0491954a99'
[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::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
17     /// Checks for calls to `push` immediately after creating a new `Vec`.
18     ///
19     /// ### Why is this bad?
20     /// The `vec![]` macro is both more performant and easier to read than
21     /// multiple `push` calls.
22     ///
23     /// ### Example
24     /// ```rust
25     /// let mut v = Vec::new();
26     /// v.push(0);
27     /// ```
28     /// Use instead:
29     /// ```rust
30     /// let v = vec![0];
31     /// ```
32     pub VEC_INIT_THEN_PUSH,
33     perf,
34     "`push` immediately after `Vec` creation"
35 }
36
37 impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
38
39 #[derive(Default)]
40 pub struct VecInitThenPush {
41     searcher: Option<VecPushSearcher>,
42 }
43
44 #[derive(Clone, Copy)]
45 enum VecInitKind {
46     New,
47     WithCapacity(u64),
48 }
49 struct VecPushSearcher {
50     local_id: HirId,
51     init: VecInitKind,
52     lhs_is_local: bool,
53     lhs_span: Span,
54     err_span: Span,
55     found: u64,
56 }
57 impl VecPushSearcher {
58     fn display_err(&self, cx: &LateContext<'_>) {
59         match self.init {
60             _ if self.found == 0 => return,
61             VecInitKind::WithCapacity(x) if x > self.found => return,
62             _ => (),
63         };
64
65         let mut s = if self.lhs_is_local {
66             String::from("let ")
67         } else {
68             String::new()
69         };
70         s.push_str(&snippet(cx, self.lhs_span, ".."));
71         s.push_str(" = vec![..];");
72
73         span_lint_and_sugg(
74             cx,
75             VEC_INIT_THEN_PUSH,
76             self.err_span,
77             "calls to `push` immediately after creation",
78             "consider using the `vec![]` macro",
79             s,
80             Applicability::HasPlaceholders,
81         );
82     }
83 }
84
85 impl LateLintPass<'_> for VecInitThenPush {
86     fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
87         self.searcher = None;
88     }
89
90     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
91         if_chain! {
92             if !in_external_macro(cx.sess(), local.span);
93             if let Some(init) = local.init;
94             if let PatKind::Binding(BindingAnnotation::Mutable, id, _, None) = local.pat.kind;
95             if let Some(init_kind) = get_vec_init_kind(cx, init);
96             then {
97                 self.searcher = Some(VecPushSearcher {
98                         local_id: id,
99                         init: init_kind,
100                         lhs_is_local: true,
101                         lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)),
102                         err_span: local.span,
103                         found: 0,
104                     });
105             }
106         }
107     }
108
109     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
110         if_chain! {
111             if self.searcher.is_none();
112             if !in_external_macro(cx.sess(), expr.span);
113             if let ExprKind::Assign(left, right, _) = expr.kind;
114             if let Some(id) = path_to_local(left);
115             if let Some(init_kind) = get_vec_init_kind(cx, right);
116             then {
117                 self.searcher = Some(VecPushSearcher {
118                     local_id: id,
119                     init: init_kind,
120                     lhs_is_local: false,
121                     lhs_span: left.span,
122                     err_span: expr.span,
123                     found: 0,
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) =>
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) =>
181             {
182                 return Some(VecInitKind::New);
183             }
184             _ => (),
185         }
186     }
187     None
188 }