Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6791,6 +6791,7 @@ Released 2018-09-13
[`useless_format`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_format
[`useless_let_if_seq`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_let_if_seq
[`useless_nonzero_new_unchecked`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_nonzero_new_unchecked
[`useless_pathbuf_conversion`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_pathbuf_conversion
[`useless_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_transmute
[`useless_vec`]: https://rust-lang.github.io/rust-clippy/master/index.html#useless_vec
[`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,7 @@ pub static LINTS: &[&::declare_clippy_lint::LintInfo] = &[
crate::use_self::USE_SELF_INFO,
crate::useless_concat::USELESS_CONCAT_INFO,
crate::useless_conversion::USELESS_CONVERSION_INFO,
crate::useless_pathbuf_conversion::USELESS_PATHBUF_CONVERSION_INFO,
crate::vec::USELESS_VEC_INFO,
crate::vec_init_then_push::VEC_INIT_THEN_PUSH_INFO,
crate::visibility::NEEDLESS_PUB_SELF_INFO,
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ mod upper_case_acronyms;
mod use_self;
mod useless_concat;
mod useless_conversion;
mod useless_pathbuf_conversion;
mod vec;
mod vec_init_then_push;
mod visibility;
Expand Down Expand Up @@ -580,6 +581,7 @@ pub fn register_lint_passes(store: &mut rustc_lint::LintStore, conf: &'static Co
store.register_late_pass(|_| Box::new(infinite_iter::InfiniteIter));
store.register_late_pass(|_| Box::new(inline_fn_without_body::InlineFnWithoutBody));
store.register_late_pass(|_| Box::<useless_conversion::UselessConversion>::default());
store.register_late_pass(|_| Box::new(useless_pathbuf_conversion::UselessPathbufConversion));
store.register_late_pass(|_| Box::new(implicit_hasher::ImplicitHasher));
store.register_late_pass(|_| Box::new(fallible_impl_from::FallibleImplFrom));
store.register_late_pass(move |_| Box::new(question_mark::QuestionMark::new(conf)));
Expand Down
63 changes: 63 additions & 0 deletions clippy_lints/src/useless_pathbuf_conversion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_path_diagnostic_item;
use clippy_utils::source::snippet_with_context;
use clippy_utils::ty::is_type_diagnostic_item;

use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind, QPath};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::symbol::sym;

declare_clippy_lint! {
/// **What it does:** Detects unnecessary `&PathBuf::from(...)` when `&Path` would suffice.
///
/// **Why is this bad?** `PathBuf::from` allocates a new heap buffer unnecessarily.
///
/// **Example:**
/// ```rust
/// fn use_path(p: &std::path::Path) {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most functions working with Paths will have the parameter specified as impl AsRef<Path>, which this lint unfortunately wouldn't catch right now.

This is very similar to a lint I suggested myself: #14668, and I'm not sure what the interplay between them should be. That lint basically checks two things:

  1. that the implicit generic in impl AsRef<Path> isn't used elsewhere in the function
  2. that the x in Path::new(x) implements all the trait bounds of that generic (notably AsRef, but often also Sized), and therefore could be used directly

So this lint would probably need to copy the first check from that lint; and at this point one could argue that it could go the extra mile and also check the second thing, which would allow it to replace &PathBuf::from(x) directly with x -- otherwise, one would first create Path::new(x), and then need to repeat the entirety of the first check on that.

Now that I've written this out though, the first check isn't actually all that big, and also it's preferable to let the lints compose, so this is probably fine after all.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for breaking it down. I agree, let the lints complement each other.

/// use_path(&std::path::PathBuf::from("abc"));
/// ```
/// Could be written as:
/// ```rust
/// fn use_path(p: &std::path::Path) {}
/// use_path(std::path::Path::new("abc"));
/// ```
#[clippy::version = "1.92.0"]
pub USELESS_PATHBUF_CONVERSION,
complexity,
"creating a `PathBuf` only to take a reference, where `Path::new` would suffice"
}

declare_lint_pass!(UselessPathbufConversion => [USELESS_PATHBUF_CONVERSION]);

impl<'tcx> LateLintPass<'tcx> for UselessPathbufConversion {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::AddrOf(_, _, inner) = &expr.kind
&& let ExprKind::Call(func, [arg]) = &inner.kind
&& let ExprKind::Path(ref qpath) = func.kind
&& let QPath::TypeRelative(pathbuf, from) = qpath
&& is_path_diagnostic_item(cx, *pathbuf, sym::PathBuf)
&& from.ident.name == sym::from
&& let expr_ty = cx.typeck_results().expr_ty_adjusted(expr)
&& let rustc_middle::ty::Ref(_, inner_ty, _) = expr_ty.kind()
&& is_type_diagnostic_item(cx, *inner_ty, sym::Path)
{
let mut app = Applicability::MachineApplicable;
let arg_snippet = snippet_with_context(cx, arg.span, inner.span.ctxt(), "..", &mut app).0;

let sugg = format!("Path::new({arg_snippet})");

span_lint_and_sugg(
cx,
USELESS_PATHBUF_CONVERSION,
expr.span,
"unnecessary `PathBuf::from` when a `&Path` is enough",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, this lint doesn't actually check whether a &Path is enough -- for example, it would falsely warn in a case like:

fn takes_ref_pathbuf(_: &PathBuf) {}

fn main() {
    takes_ref_pathbuf(&PathBuf::from("path"));
}

"consider using",
sugg,
app,
);
}
}
}
3 changes: 3 additions & 0 deletions clippy_utils/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,9 @@ pub fn snippet_block_with_context(
/// would result in `box []`. If given the context of the address of expression, this function will
/// correctly get a snippet of `vec![]`.
///
/// NOTE: Typically the `outer` context should be taken from the parent node, not from the node
/// itself.
///
/// This will also return whether or not the snippet is a macro call.
pub fn snippet_with_context<'a>(
sess: &impl HasSession,
Expand Down
3 changes: 2 additions & 1 deletion tests/ui/unnecessary_to_owned.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
clippy::needless_lifetimes,
clippy::owned_cow,
clippy::ptr_arg,
clippy::uninlined_format_args
clippy::uninlined_format_args,
clippy::useless_pathbuf_conversion
)]
#![warn(clippy::unnecessary_to_owned, clippy::redundant_clone)]

Expand Down
3 changes: 2 additions & 1 deletion tests/ui/unnecessary_to_owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
clippy::needless_lifetimes,
clippy::owned_cow,
clippy::ptr_arg,
clippy::uninlined_format_args
clippy::uninlined_format_args,
clippy::useless_pathbuf_conversion
)]
#![warn(clippy::unnecessary_to_owned, clippy::redundant_clone)]

Expand Down
Loading