Skip to content

Commit a76c2b3

Browse files
authored
Fix unnecessary_debug_formatting FP inside Debug impl (#14955)
Closes rust-lang/rust-clippy#14952 The lint suggests using `.display()` on `Path`, which is actually correct. changelog: [`unnecessary_debug_formatting`] fix FP inside `Debug` impl
2 parents ed143af + a4360d6 commit a76c2b3

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

clippy_lints/src/format_args.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use clippy_utils::macros::{
1111
use clippy_utils::msrvs::{self, Msrv};
1212
use clippy_utils::source::{SpanRangeExt, snippet};
1313
use clippy_utils::ty::{implements_trait, is_type_lang_item};
14-
use clippy_utils::{is_diag_trait_item, is_from_proc_macro, is_in_test};
14+
use clippy_utils::{is_diag_trait_item, is_from_proc_macro, is_in_test, trait_ref_of_method};
1515
use itertools::Itertools;
1616
use rustc_ast::{
1717
FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, FormatOptions,
@@ -542,6 +542,16 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> {
542542
&& let ty = cx.typeck_results().expr_ty(value)
543543
&& self.can_display_format(ty)
544544
{
545+
// If the parent function is a method of `Debug`, we don't want to lint
546+
// because it is likely that the user wants to use `Debug` formatting.
547+
let parent_fn = cx.tcx.hir_get_parent_item(value.hir_id);
548+
if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn)
549+
&& let Some(trait_def_id) = trait_ref.trait_def_id()
550+
&& cx.tcx.is_diagnostic_item(sym::Debug, trait_def_id)
551+
{
552+
return;
553+
}
554+
545555
let snippet = snippet(cx.sess(), value.span, "..");
546556
span_lint_and_then(
547557
cx,

tests/ui/format_args.fixed

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,13 @@ mod issue_9256 {
192192
print_substring("Hello, world!");
193193
}
194194
}
195+
196+
mod issue14952 {
197+
use std::path::Path;
198+
struct Foo(Path);
199+
impl std::fmt::Debug for Foo {
200+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201+
write!(f, "{:?}", &self.0)
202+
}
203+
}
204+
}

tests/ui/format_args.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,13 @@ mod issue_9256 {
192192
print_substring("Hello, world!");
193193
}
194194
}
195+
196+
mod issue14952 {
197+
use std::path::Path;
198+
struct Foo(Path);
199+
impl std::fmt::Debug for Foo {
200+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201+
write!(f, "{:?}", &self.0)
202+
}
203+
}
204+
}

0 commit comments

Comments
 (0)