Skip to content

Fix unnecessary_debug_formatting FP inside Debug impl #14955

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 4, 2025
Merged
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
12 changes: 11 additions & 1 deletion clippy_lints/src/format_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use clippy_utils::macros::{
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::{SpanRangeExt, snippet};
use clippy_utils::ty::{implements_trait, is_type_lang_item};
use clippy_utils::{is_diag_trait_item, is_from_proc_macro, is_in_test};
use clippy_utils::{is_diag_trait_item, is_from_proc_macro, is_in_test, trait_ref_of_method};
use itertools::Itertools;
use rustc_ast::{
FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, FormatOptions,
Expand Down Expand Up @@ -490,6 +490,16 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> {
&& let ty = cx.typeck_results().expr_ty(value)
&& self.can_display_format(ty)
{
// If the parent function is a method of `Debug`, we don't want to lint
// because it is likely that the user wants to use `Debug` formatting.
let parent_fn = cx.tcx.hir_get_parent_item(value.hir_id);
if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn)
&& let Some(trait_def_id) = trait_ref.trait_def_id()
&& cx.tcx.is_diagnostic_item(sym::Debug, trait_def_id)
{
return;
}

let snippet = snippet(cx.sess(), value.span, "..");
span_lint_and_then(
cx,
Expand Down
10 changes: 10 additions & 0 deletions tests/ui/format_args.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,13 @@ mod issue_9256 {
print_substring("Hello, world!");
}
}

mod issue14952 {
use std::path::Path;
struct Foo(Path);
impl std::fmt::Debug for Foo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", &self.0)
}
}
}
10 changes: 10 additions & 0 deletions tests/ui/format_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,13 @@ mod issue_9256 {
print_substring("Hello, world!");
}
}

mod issue14952 {
use std::path::Path;
struct Foo(Path);
impl std::fmt::Debug for Foo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", &self.0)
}
}
}
Loading