Skip to content

Commit 7488bdb

Browse files
committed
fix(use_debug): don't get confused by nested Debug impls
1 parent 21d3b9d commit 7488bdb

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

clippy_lints/src/write.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -240,18 +240,22 @@ declare_clippy_lint! {
240240

241241
pub struct Write {
242242
format_args: FormatArgsStorage,
243-
in_debug_impl: bool,
243+
debug_impl_depth: u32, // overkill, but the alignment allows it so why not
244244
allow_print_in_tests: bool,
245245
}
246246

247247
impl Write {
248248
pub fn new(conf: &'static Conf, format_args: FormatArgsStorage) -> Self {
249249
Self {
250250
format_args,
251-
in_debug_impl: false,
251+
debug_impl_depth: 0,
252252
allow_print_in_tests: conf.allow_print_in_tests,
253253
}
254254
}
255+
256+
fn in_debug_impl(&self) -> bool {
257+
self.debug_impl_depth != 0
258+
}
255259
}
256260

257261
impl_lint_pass!(Write => [
@@ -269,13 +273,13 @@ impl_lint_pass!(Write => [
269273
impl<'tcx> LateLintPass<'tcx> for Write {
270274
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
271275
if is_debug_impl(cx, item) {
272-
self.in_debug_impl = true;
276+
self.debug_impl_depth += 1;
273277
}
274278
}
275279

276280
fn check_item_post(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
277281
if is_debug_impl(cx, item) {
278-
self.in_debug_impl = false;
282+
self.debug_impl_depth -= 1;
279283
}
280284
}
281285

@@ -329,7 +333,7 @@ impl<'tcx> LateLintPass<'tcx> for Write {
329333

330334
check_literal(cx, format_args, name);
331335

332-
if !self.in_debug_impl {
336+
if !self.in_debug_impl() {
333337
for piece in &format_args.template {
334338
if let &FormatArgsPiece::Placeholder(FormatPlaceholder {
335339
span: Some(span),

tests/ui/use_debug.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,22 @@ fn main() {
2929

3030
vec![1, 2];
3131
}
32+
33+
// don't get confused by nested impls
34+
fn issue15942() {
35+
struct Bar;
36+
impl Debug for Bar {
37+
fn fmt(&self, f: &mut Formatter) -> Result {
38+
struct Baz;
39+
impl Debug for Baz {
40+
fn fmt(&self, f: &mut Formatter) -> Result {
41+
// ok, we can use `Debug` formatting in `Debug` implementations
42+
write!(f, "{:?}", 42.718)
43+
}
44+
}
45+
46+
// ok, we can use `Debug` formatting in `Debug` implementations
47+
write!(f, "{:?}", 42.718)
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)