Skip to content

Commit 2ce8ec0

Browse files
Rollup merge of #166113 - tehforsch:fix-ignore-variant-stack-self-type, r=mu001999
Fix dead-code marking dead enum variants as live This fixes a bug with the dead-code lint. Constructing an enum variant inside a match arm that matches on the same enum variant should not count to it being marked as live. This behavior was already implemented, but it only worked when the pattern matches on the enum type directly, not via the `Self` type alias. As an example, see: ```rust enum Enum { Variant1, // This is marked as dead Variant2, // This isnt } impl Clone for Enum { fn clone(&self) -> Self { match self { Enum::Variant1 => Enum::Variant1, Self::Variant2 => Self::Variant2, } } } fn main() { // keep enum itself live let _: Enum = todo!(); } ``` This PR fixes this by resolving the `QPath` of the pattern properly. As a result, the derived `Clone` impl for an enum like the above now doesn't result in the variants being kept alive at all. Previously, we'd get a note saying that a variant is constructed in the `Clone` impl but that this was being intentionally ignored (due to `#[rustc_trivial_field_reads]`), but now this note does not appear anymore. Additionally, this PR also adds a test which actually uses the `ignore_variant_stack` (i.e. the mechanism responsible for preventing enum variants from being marked live in arms where we match on them). The original PR (#25961) which added the `ignore_variant_stack` also added a test that uses `#[derive(Clone)]` to test the ignored variant stack. However, after `rustc_trivial_field_reads` was added (in #85200), this test didn't actually run into the dead variant stack anymore, since the derived `Clone` impl was ignored for dead-code analysis. So on current `main` it was possible to remove the `ignore_variant_stack` entirely without a single test failing. r? @mu001999
2 parents 0d331a8 + d88bc8a commit 2ce8ec0

7 files changed

Lines changed: 108 additions & 28 deletions

File tree

‎compiler/rustc_hir/src/pat_util.rs‎

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ use std::iter::Enumerate;
33
use rustc_hir_id::HirId;
44
use rustc_span::{Ident, Span};
55

6-
use crate::def::{CtorOf, DefKind, Res};
7-
use crate::def_id::{DefId, DefIdSet};
6+
use crate::QPath;
87
use crate::hir::{self, BindingMode, ByRef, PatKind};
98
pub struct EnumerateAndAdjust<I> {
109
enumerate: Enumerate<I>,
@@ -100,31 +99,20 @@ impl hir::Pat<'_> {
10099
}
101100
}
102101

103-
/// Returns variants that are necessary to exist for the pattern to match.
104-
pub fn necessary_variants(&self) -> Vec<DefId> {
105-
let mut variants = vec![];
102+
/// Call 'f' on every variant which is necessary for the pattern to match
103+
pub fn each_necessary_variant(&self, mut f: impl FnMut(&QPath<'_>, HirId)) {
106104
self.walk(|p| match &p.kind {
107105
PatKind::Or(_) => false,
108-
PatKind::Expr(hir::PatExpr {
109-
kind: hir::PatExprKind::Path(hir::QPath::Resolved(_, path)),
110-
..
111-
})
112-
| PatKind::TupleStruct(hir::QPath::Resolved(_, path), ..)
113-
| PatKind::Struct(hir::QPath::Resolved(_, path), ..) => {
114-
if let Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), id) =
115-
path.res
116-
{
117-
variants.push(id);
118-
}
106+
PatKind::Expr(hir::PatExpr { hir_id, kind: hir::PatExprKind::Path(qpath), .. }) => {
107+
f(qpath, *hir_id);
108+
true
109+
}
110+
PatKind::TupleStruct(qpath, ..) | PatKind::Struct(qpath, ..) => {
111+
f(qpath, p.hir_id);
119112
true
120113
}
121114
_ => true,
122115
});
123-
// We remove duplicates by inserting into a hash set to avoid re-ordering
124-
// the bounds
125-
let mut duplicates = DefIdSet::default();
126-
variants.retain(|def_id| duplicates.insert(*def_id));
127-
variants
128116
}
129117

130118
/// Checks if the pattern contains any `ref` or `ref mut` bindings, and if

‎compiler/rustc_passes/src/dead.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use rustc_attr_ir::find_attr;
1313
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
1414
use rustc_errors::{ErrorGuaranteed, MultiSpan};
1515
use rustc_hir::def::{CtorOf, DefKind, Res};
16-
use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap, LocalModId};
16+
use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId, LocalDefIdMap, LocalModId};
1717
use rustc_hir::intravisit::{self, Visitor};
1818
use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath};
1919
use rustc_lint_defs::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
@@ -860,7 +860,15 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
860860
// necessary for the pattern to match. Those construction sites
861861
// can't be reached unless the variant is constructed elsewhere.
862862
let len = self.ignore_variant_stack.len();
863-
self.ignore_variant_stack.extend(arm.pat.necessary_variants());
863+
let mut seen_variants = DefIdSet::default();
864+
arm.pat.each_necessary_variant(|qpath, hir_id| {
865+
if let Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), id) =
866+
self.typeck_results().qpath_res(qpath, hir_id)
867+
&& seen_variants.insert(id)
868+
{
869+
self.ignore_variant_stack.push(id);
870+
}
871+
});
864872
let result = intravisit::walk_arm(self, arm);
865873
self.ignore_variant_stack.truncate(len);
866874

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#![deny(dead_code)]
2+
3+
enum Enum {
4+
Variant1,
5+
Variant2(i32), //~ ERROR: `Variant2` is never constructed
6+
}
7+
8+
impl Clone for Enum {
9+
fn clone(&self) -> Self {
10+
match (self,) {
11+
(Self::Variant1,) => Self::Variant1,
12+
(Self::Variant2(value),) => Self::Variant2(*value),
13+
}
14+
}
15+
}
16+
17+
fn main() {
18+
let _ = Enum::Variant1;
19+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error: variant `Variant2` is never constructed
2+
--> $DIR/unused-variant-manual-clone-impl-tuple.rs:5:5
3+
|
4+
LL | enum Enum {
5+
| ---- variant in this enum
6+
LL | Variant1,
7+
LL | Variant2(i32),
8+
| ^^^^^^^^
9+
|
10+
note: the lint level is defined here
11+
--> $DIR/unused-variant-manual-clone-impl-tuple.rs:1:9
12+
|
13+
LL | #![deny(dead_code)]
14+
| ^^^^^^^^^
15+
16+
error: aborting due to 1 previous error
17+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#![deny(dead_code)]
2+
3+
enum Enum {
4+
Variant1, //~ ERROR: variants `Variant1`, `Variant2`, `Variant3`, `Variant4`, `Variant5`, and `Variant6` are never constructed
5+
Variant2,
6+
Variant3(i32),
7+
Variant4(i32),
8+
Variant5 { x: i32 },
9+
Variant6 { x: i32 },
10+
}
11+
12+
impl Clone for Enum {
13+
fn clone(&self) -> Enum {
14+
match &self {
15+
Enum::Variant1 => Enum::Variant1,
16+
Self::Variant2 => Self::Variant2,
17+
Enum::Variant3(b) => Enum::Variant3(*b),
18+
Self::Variant4(b) => Self::Variant4(*b),
19+
Enum::Variant5 { x } => Enum::Variant5 { x: *x },
20+
Self::Variant6 { x } => Self::Variant6 { x: *x },
21+
}
22+
}
23+
}
24+
25+
fn main() {
26+
let _: Enum = todo!();
27+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error: variants `Variant1`, `Variant2`, `Variant3`, `Variant4`, `Variant5`, and `Variant6` are never constructed
2+
--> $DIR/unused-variant-manual-clone-impl.rs:4:5
3+
|
4+
LL | enum Enum {
5+
| ---- variants in this enum
6+
LL | Variant1,
7+
| ^^^^^^^^
8+
LL | Variant2,
9+
| ^^^^^^^^
10+
LL | Variant3(i32),
11+
| ^^^^^^^^
12+
LL | Variant4(i32),
13+
| ^^^^^^^^
14+
LL | Variant5 { x: i32 },
15+
| ^^^^^^^^
16+
LL | Variant6 { x: i32 },
17+
| ^^^^^^^^
18+
|
19+
note: the lint level is defined here
20+
--> $DIR/unused-variant-manual-clone-impl.rs:1:9
21+
|
22+
LL | #![deny(dead_code)]
23+
| ^^^^^^^^^
24+
25+
error: aborting due to 1 previous error
26+

‎tests/ui/lint/dead-code/unused-variant.stderr‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,6 @@ LL | enum Enum {
66
LL | Variant1,
77
| ^^^^^^^^
88
|
9-
note: `Variant1` is used in the expansion of the derive macro `Clone`, but this is intentionally ignored during dead code analysis
10-
--> $DIR/unused-variant.rs:3:10
11-
|
12-
LL | #[derive(Clone)]
13-
| ^^^^^
149
note: the lint level is defined here
1510
--> $DIR/unused-variant.rs:1:9
1611
|

0 commit comments

Comments
 (0)