From 8f21bfc774b63389a1359b286cf051a46039ae0f Mon Sep 17 00:00:00 2001 From: Gurinder Singh Date: Mon, 29 Jul 2024 08:00:58 +0530 Subject: [PATCH] Consider const fn with `&self` while checking liveness --- compiler/rustc_passes/src/dead.rs | 5 ++-- ...false-positive-builder-with-self-128272.rs | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 tests/ui/lint/dead-code/false-positive-builder-with-self-128272.rs diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 239bc8e7accfc..bbf38a478f9f0 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -833,8 +833,9 @@ fn check_item<'tcx>( if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(tcx.local_def_id_to_hir_id(local_def_id)) { - may_construct_self = - matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None); + may_construct_self = matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None) + // Also considering const functions with `&self` to fix #128272 + || fn_sig.header.is_const() && matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::RefImm); } // for trait impl blocks, diff --git a/tests/ui/lint/dead-code/false-positive-builder-with-self-128272.rs b/tests/ui/lint/dead-code/false-positive-builder-with-self-128272.rs new file mode 100644 index 0000000000000..bcef76d555e70 --- /dev/null +++ b/tests/ui/lint/dead-code/false-positive-builder-with-self-128272.rs @@ -0,0 +1,25 @@ +// Regression test for #128272 +// Tests that we do not consider a struct +// dead code if it is constructed in a +// const function taking `&self` + + +//@ check-pass + +#![deny(dead_code)] + +pub struct Foo { + _f: i32 +} + +impl Foo { + // This function constructs Foo but in #128272 + // the compiler warned that Foo is never constructed + pub const fn new(&self) -> Foo { + Foo { _f: 5 } + } +} + +fn main() { + static _X: Foo = _X.new(); +}