2 is_type_diagnostic_item, match_def_path, path_to_local, path_to_local_id, paths, snippet, span_lint_and_sugg,
4 use if_chain::if_chain;
5 use rustc_ast::ast::LitKind;
6 use rustc_errors::Applicability;
7 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, 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::{symbol::sym, Span};
12 use std::convert::TryInto;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for calls to `push` immediately after creating a new `Vec`.
17 /// **Why is this bad?** The `vec![]` macro is both more performant and easier to read than
18 /// multiple `push` calls.
20 /// **Known problems:** None.
25 /// let mut v = Vec::new();
32 pub VEC_INIT_THEN_PUSH,
34 "`push` immediately after `Vec` creation"
37 impl_lint_pass!(VecInitThenPush => [VEC_INIT_THEN_PUSH]);
40 pub struct VecInitThenPush {
41 searcher: Option<VecPushSearcher>,
44 #[derive(Clone, Copy)]
49 struct VecPushSearcher {
57 impl VecPushSearcher {
58 fn display_err(&self, cx: &LateContext<'_>) {
60 _ if self.found == 0 => return,
61 VecInitKind::WithCapacity(x) if x > self.found => return,
65 let mut s = if self.lhs_is_local {
70 s.push_str(&snippet(cx, self.lhs_span, ".."));
71 s.push_str(" = vec![..];");
77 "calls to `push` immediately after creation",
78 "consider using the `vec![]` macro",
80 Applicability::HasPlaceholders,
85 impl LateLintPass<'_> for VecInitThenPush {
86 fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
90 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) {
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);
97 self.searcher = Some(VecPushSearcher {
101 lhs_span: local.ty.map_or(local.pat.span, |t| local.pat.span.to(t.span)),
102 err_span: local.span,
109 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
110 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);
117 self.searcher = Some(VecPushSearcher {
130 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
131 if let Some(searcher) = self.searcher.take() {
133 if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind;
134 if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind;
135 if path_to_local_id(self_arg, searcher.local_id);
136 if path.ident.name.as_str() == "push";
138 self.searcher = Some(VecPushSearcher {
139 found: searcher.found + 1,
140 err_span: searcher.err_span.to(stmt.span),
144 searcher.display_err(cx);
150 fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) {
151 if let Some(searcher) = self.searcher.take() {
152 searcher.display_err(cx);
157 fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> {
158 if let ExprKind::Call(func, args) = expr.kind {
160 ExprKind::Path(QPath::TypeRelative(ty, name))
161 if is_type_diagnostic_item(cx, cx.typeck_results().node_type(ty.hir_id), sym::vec_type) =>
163 if name.ident.name == sym::new {
164 return Some(VecInitKind::New);
165 } else if name.ident.name.as_str() == "with_capacity" {
166 return args.get(0).and_then(|arg| {
168 if let ExprKind::Lit(lit) = &arg.kind;
169 if let LitKind::Int(num, _) = lit.node;
171 Some(VecInitKind::WithCapacity(num.try_into().ok()?))
179 ExprKind::Path(QPath::Resolved(_, path))
180 if match_def_path(cx, path.res.opt_def_id()?, &paths::DEFAULT_TRAIT_METHOD)
181 && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type) =>
183 return Some(VecInitKind::New);