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