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