|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::path_to_local_id; |
| 3 | +use clippy_utils::source::{snippet, snippet_opt}; |
| 4 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 5 | +use rustc_ast::{LitKind, StrStyle}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::def::Res; |
| 8 | +use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, Stmt, StmtKind, TyKind}; |
| 9 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 10 | +use rustc_middle::lint::in_external_macro; |
| 11 | +use rustc_session::impl_lint_pass; |
| 12 | +use rustc_span::{sym, Span, Symbol}; |
| 13 | + |
| 14 | +declare_clippy_lint! { |
| 15 | + /// ### What it does |
| 16 | + /// Checks for calls to `push` immediately after creating a new `PathBuf`. |
| 17 | + /// |
| 18 | + /// ### Why is this bad? |
| 19 | + /// The `.join()` is easier to read than multiple `push` calls. |
| 20 | + /// |
| 21 | + /// ### Known problems |
| 22 | + /// `.join()` introduces an implicit `clone()` |
| 23 | + /// |
| 24 | + /// ### Example |
| 25 | + /// ```rust |
| 26 | + /// use std::path::PathBuf; |
| 27 | + /// let mut path_buf = PathBuf::new(); |
| 28 | + /// path_buf.push("foo"); |
| 29 | + /// ``` |
| 30 | + /// Use instead: |
| 31 | + /// ```rust |
| 32 | + /// use std::path::PathBuf; |
| 33 | + /// let path_buf = PathBuf::new().join("foo"); |
| 34 | + /// ``` |
| 35 | + #[clippy::version = "1.78.0"] |
| 36 | + pub PATHBUF_INIT_THEN_PUSH, |
| 37 | + complexity, |
| 38 | + "`push` immediately after `PathBuf` creation" |
| 39 | +} |
| 40 | + |
| 41 | +impl_lint_pass!(PathbufThenPush<'_> => [PATHBUF_INIT_THEN_PUSH]); |
| 42 | + |
| 43 | +#[derive(Default)] |
| 44 | +pub struct PathbufThenPush<'tcx> { |
| 45 | + searcher: Option<PathbufPushSearcher<'tcx>>, |
| 46 | +} |
| 47 | + |
| 48 | +struct PathbufPushSearcher<'tcx> { |
| 49 | + local_id: HirId, |
| 50 | + lhs_is_let: bool, |
| 51 | + let_ty_span: Option<Span>, |
| 52 | + init_val: Expr<'tcx>, |
| 53 | + arg: Option<Expr<'tcx>>, |
| 54 | + name: Symbol, |
| 55 | + err_span: Span, |
| 56 | +} |
| 57 | + |
| 58 | +impl<'tcx> PathbufPushSearcher<'tcx> { |
| 59 | + // try to generate `PathBuf::from` |
| 60 | + fn gen_pathbuf_from(&self, cx: &LateContext<'_>) -> Option<String> { |
| 61 | + if let ExprKind::Call(iter_expr, []) = &self.init_val.kind |
| 62 | + && let ExprKind::Path(QPath::TypeRelative(ty, segment)) = &iter_expr.kind |
| 63 | + && let TyKind::Path(ty_path) = &ty.kind |
| 64 | + && let QPath::Resolved(None, path) = ty_path |
| 65 | + && let Res::Def(_, def_id) = &path.res |
| 66 | + && cx.tcx.is_diagnostic_item(sym::PathBuf, *def_id) |
| 67 | + && segment.ident.name == sym::new |
| 68 | + && let Some(arg) = self.arg |
| 69 | + && let ExprKind::Lit(x) = arg.kind |
| 70 | + && let LitKind::Str(_, StrStyle::Cooked) = x.node |
| 71 | + && let Some(s) = snippet_opt(cx, arg.span) |
| 72 | + { |
| 73 | + Some(format!(" = PathBuf::from({s});")) |
| 74 | + } else { |
| 75 | + None |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + fn gen_pathbuf_join(&self, cx: &LateContext<'_>) -> Option<String> { |
| 80 | + let arg = self.arg?; |
| 81 | + let arg_str = snippet_opt(cx, arg.span)?; |
| 82 | + let init_val = snippet_opt(cx, self.init_val.span)?; |
| 83 | + Some(format!(" = {init_val}.join({arg_str});")) |
| 84 | + } |
| 85 | + |
| 86 | + fn display_err(&self, cx: &LateContext<'_>) { |
| 87 | + let mut sugg = if self.lhs_is_let { |
| 88 | + String::from("let mut ") |
| 89 | + } else { |
| 90 | + String::new() |
| 91 | + }; |
| 92 | + sugg.push_str(self.name.as_str()); |
| 93 | + if let Some(span) = self.let_ty_span { |
| 94 | + sugg.push_str(": "); |
| 95 | + sugg.push_str(&snippet(cx, span, "_")); |
| 96 | + } |
| 97 | + match self.gen_pathbuf_from(cx) { |
| 98 | + Some(value) => { |
| 99 | + sugg.push_str(&value); |
| 100 | + }, |
| 101 | + None => { |
| 102 | + if let Some(value) = self.gen_pathbuf_join(cx) { |
| 103 | + sugg.push_str(&value); |
| 104 | + } else { |
| 105 | + return; |
| 106 | + } |
| 107 | + }, |
| 108 | + } |
| 109 | + |
| 110 | + span_lint_and_sugg( |
| 111 | + cx, |
| 112 | + PATHBUF_INIT_THEN_PUSH, |
| 113 | + self.err_span, |
| 114 | + "calls to `push` immediately after creation", |
| 115 | + "consider using the `.join()`", |
| 116 | + sugg, |
| 117 | + Applicability::HasPlaceholders, |
| 118 | + ); |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +impl<'tcx> LateLintPass<'tcx> for PathbufThenPush<'tcx> { |
| 123 | + fn check_block(&mut self, _: &LateContext<'tcx>, _: &'tcx Block<'tcx>) { |
| 124 | + self.searcher = None; |
| 125 | + } |
| 126 | + |
| 127 | + fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'tcx>) { |
| 128 | + if let Some(init_expr) = local.init |
| 129 | + && let PatKind::Binding(BindingAnnotation::MUT, id, name, None) = local.pat.kind |
| 130 | + && !in_external_macro(cx.sess(), local.span) |
| 131 | + && let ty = cx.typeck_results().pat_ty(local.pat) |
| 132 | + && is_type_diagnostic_item(cx, ty, sym::PathBuf) |
| 133 | + { |
| 134 | + self.searcher = Some(PathbufPushSearcher { |
| 135 | + local_id: id, |
| 136 | + lhs_is_let: true, |
| 137 | + name: name.name, |
| 138 | + let_ty_span: local.ty.map(|ty| ty.span), |
| 139 | + err_span: local.span, |
| 140 | + init_val: *init_expr, |
| 141 | + arg: None, |
| 142 | + }); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 147 | + if self.searcher.is_none() |
| 148 | + && let ExprKind::Assign(left, right, _) = expr.kind |
| 149 | + && let ExprKind::Path(QPath::Resolved(None, path)) = left.kind |
| 150 | + && let [name] = &path.segments |
| 151 | + && let Res::Local(id) = path.res |
| 152 | + && !in_external_macro(cx.sess(), expr.span) |
| 153 | + && let ty = cx.typeck_results().expr_ty(left) |
| 154 | + && is_type_diagnostic_item(cx, ty, sym::PathBuf) |
| 155 | + { |
| 156 | + self.searcher = Some(PathbufPushSearcher { |
| 157 | + local_id: id, |
| 158 | + lhs_is_let: false, |
| 159 | + let_ty_span: None, |
| 160 | + name: name.ident.name, |
| 161 | + err_span: expr.span, |
| 162 | + init_val: *right, |
| 163 | + arg: None, |
| 164 | + }); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { |
| 169 | + if let Some(mut searcher) = self.searcher.take() { |
| 170 | + if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind |
| 171 | + && let ExprKind::MethodCall(name, self_arg, [arg_expr], _) = expr.kind |
| 172 | + && path_to_local_id(self_arg, searcher.local_id) |
| 173 | + && name.ident.as_str() == "push" |
| 174 | + { |
| 175 | + searcher.err_span = searcher.err_span.to(stmt.span); |
| 176 | + searcher.arg = Some(*arg_expr); |
| 177 | + searcher.display_err(cx); |
| 178 | + } |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) { |
| 183 | + if let Some(searcher) = self.searcher.take() { |
| 184 | + searcher.display_err(cx); |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments