|
| 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 rustc_hir::{Expr, ExprKind}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | +use rustc_span::symbol::sym; |
| 8 | + |
| 9 | +declare_clippy_lint! { |
| 10 | + /// **What it does:** Detects unnecessary `&PathBuf::from(...)` when `&Path` would suffice. |
| 11 | + /// |
| 12 | + /// **Why is this bad?** `PathBuf::from` allocates a new heap buffer unnecessarily. |
| 13 | + /// |
| 14 | + /// **Example:** |
| 15 | + /// ```rust |
| 16 | + /// fn use_path(p: &std::path::Path) {} |
| 17 | + /// use_path(&std::path::PathBuf::from("abc")); |
| 18 | + /// ``` |
| 19 | + /// Could be written as: |
| 20 | + /// ```rust |
| 21 | + /// fn use_path(p: &std::path::Path) {} |
| 22 | + /// use_path(std::path::Path::new("abc")); |
| 23 | + /// ``` |
| 24 | + #[clippy::version = "1.91.0"] |
| 25 | + pub USELESS_PATHBUF_CONVERSION, |
| 26 | + complexity, |
| 27 | + "creating a PathBuf only to take a reference, where Path::new would suffice" |
| 28 | +} |
| 29 | + |
| 30 | +declare_lint_pass!(UselessPathbufConversion => [USELESS_PATHBUF_CONVERSION]); |
| 31 | + |
| 32 | +impl<'tcx> LateLintPass<'tcx> for UselessPathbufConversion { |
| 33 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 34 | + // Only care about &PathBuf::from(...) |
| 35 | + if let ExprKind::AddrOf(_, _, inner) = &expr.kind { |
| 36 | + if let ExprKind::Call(func, args) = &inner.kind { |
| 37 | + if let ExprKind::Path(ref qpath) = func.kind { |
| 38 | + if let Some(def_id) = cx.qpath_res(qpath, func.hir_id).opt_def_id() { |
| 39 | + // check that the function is `from` |
| 40 | + if cx.tcx.item_name(def_id) != sym::from { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + // get the type of the function's return value |
| 45 | + let ty = cx.typeck_results().expr_ty(inner); |
| 46 | + |
| 47 | + if is_type_diagnostic_item(cx, ty, sym::PathBuf) { |
| 48 | + if let Some(arg) = args.get(0) { |
| 49 | + let sugg = format!("Path::new({})", snippet(cx, arg.span, "..")); |
| 50 | + span_lint_and_sugg( |
| 51 | + cx, |
| 52 | + USELESS_PATHBUF_CONVERSION, |
| 53 | + expr.span, |
| 54 | + "unnecessary `PathBuf::from` when a `&Path` is enough", |
| 55 | + "consider using", |
| 56 | + sugg, |
| 57 | + rustc_errors::Applicability::MachineApplicable, |
| 58 | + ); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments