Skip to content

Commit a4360d6

Browse files
committed
fix: unnecessary_debug_formatting FP inside Debug impl
1 parent 57cbadd commit a4360d6

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
@@ -9,7 +9,7 @@ use clippy_utils::macros::{
99
use clippy_utils::msrvs::{self, Msrv};
1010
use clippy_utils::source::{SpanRangeExt, snippet};
1111
use clippy_utils::ty::{implements_trait, is_type_lang_item};
12-
use clippy_utils::{is_diag_trait_item, is_from_proc_macro, is_in_test};
12+
use clippy_utils::{is_diag_trait_item, is_from_proc_macro, is_in_test, trait_ref_of_method};
1313
use itertools::Itertools;
1414
use rustc_ast::{
1515
FormatArgPosition, FormatArgPositionKind, FormatArgsPiece, FormatArgumentKind, FormatCount, FormatOptions,
@@ -490,6 +490,16 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> {
490490
&& let ty = cx.typeck_results().expr_ty(value)
491491
&& self.can_display_format(ty)
492492
{
493+
// If the parent function is a method of `Debug`, we don't want to lint
494+
// because it is likely that the user wants to use `Debug` formatting.
495+
let parent_fn = cx.tcx.hir_get_parent_item(value.hir_id);
496+
if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn)
497+
&& let Some(trait_def_id) = trait_ref.trait_def_id()
498+
&& cx.tcx.is_diagnostic_item(sym::Debug, trait_def_id)
499+
{
500+
return;
501+
}
502+
493503
let snippet = snippet(cx.sess(), value.span, "..");
494504
span_lint_and_then(
495505
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)