Skip to content

Commit f554fb8

Browse files
authored
Unrolled build for rust-lang#132708
Rollup merge of rust-lang#132708 - estebank:const-as-binding, r=Nadrieril Point at `const` definition when used instead of a binding in a `let` statement Modify `PatKind::InlineConstant` to be `ExpandedConstant` standing in not only for inline `const` blocks but also for `const` items. This allows us to track named `const`s used in patterns when the pattern is a single binding. When we detect that there is a refutable pattern involving a `const` that could have been a binding instead, we point at the `const` item, and suggest renaming. We do this for both `let` bindings and `match` expressions missing a catch-all arm if there's at least one single binding pattern referenced. After: ``` error[E0005]: refutable pattern in local binding --> $DIR/bad-pattern.rs:19:13 | LL | const PAT: u32 = 0; | -------------- missing patterns are not covered because `PAT` is interpreted as a constant pattern, not a new variable ... LL | let PAT = v1; | ^^^ pattern `1_u32..=u32::MAX` not covered | = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html = note: the matched value is of type `u32` help: introduce a variable instead | LL | let PAT_var = v1; | ~~~~~~~ ``` Before: ``` error[E0005]: refutable pattern in local binding --> $DIR/bad-pattern.rs:19:13 | LL | let PAT = v1; | ^^^ | | | pattern `1_u32..=u32::MAX` not covered | missing patterns are not covered because `PAT` is interpreted as a constant pattern, not a new variable | help: introduce a variable instead: `PAT_var` | = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html = note: the matched value is of type `u32` ``` CC rust-lang#132582.
2 parents 3fee0f1 + 29acf8b commit f554fb8

22 files changed

+365
-94
lines changed

compiler/rustc_middle/src/thir.rs

+11-6
Original file line numberDiff line numberDiff line change
@@ -656,7 +656,7 @@ impl<'tcx> Pat<'tcx> {
656656
| Binding { subpattern: Some(subpattern), .. }
657657
| Deref { subpattern }
658658
| DerefPattern { subpattern, .. }
659-
| InlineConstant { subpattern, .. } => subpattern.walk_(it),
659+
| ExpandedConstant { subpattern, .. } => subpattern.walk_(it),
660660
Leaf { subpatterns } | Variant { subpatterns, .. } => {
661661
subpatterns.iter().for_each(|field| field.pattern.walk_(it))
662662
}
@@ -799,12 +799,17 @@ pub enum PatKind<'tcx> {
799799
value: mir::Const<'tcx>,
800800
},
801801

802-
/// Inline constant found while lowering a pattern.
803-
InlineConstant {
804-
/// [LocalDefId] of the constant, we need this so that we have a
802+
/// Pattern obtained by converting a constant (inline or named) to its pattern
803+
/// representation using `const_to_pat`.
804+
ExpandedConstant {
805+
/// [DefId] of the constant, we need this so that we have a
805806
/// reference that can be used by unsafety checking to visit nested
806-
/// unevaluated constants.
807-
def: LocalDefId,
807+
/// unevaluated constants and for diagnostics. If the `DefId` doesn't
808+
/// correspond to a local crate, it points at the `const` item.
809+
def_id: DefId,
810+
/// If `false`, then `def_id` points at a `const` item, otherwise it
811+
/// corresponds to a local inline const.
812+
is_inline: bool,
808813
/// If the inline constant is used in a range pattern, this subpattern
809814
/// represents the range (if both ends are inline constants, there will
810815
/// be multiple InlineConstant wrappers).

compiler/rustc_middle/src/thir/visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ pub fn walk_pat<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>(
247247
}
248248
}
249249
Constant { value: _ } => {}
250-
InlineConstant { def: _, subpattern } => visitor.visit_pat(subpattern),
250+
ExpandedConstant { def_id: _, is_inline: _, subpattern } => visitor.visit_pat(subpattern),
251251
Range(_) => {}
252252
Slice { prefix, slice, suffix } | Array { prefix, slice, suffix } => {
253253
for subpattern in prefix.iter() {

compiler/rustc_mir_build/src/build/custom/parse/instruction.rs

+14-6
Original file line numberDiff line numberDiff line change
@@ -144,12 +144,20 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> {
144144
let mut targets = Vec::new();
145145
for arm in rest {
146146
let arm = &self.thir[*arm];
147-
let PatKind::Constant { value } = arm.pattern.kind else {
148-
return Err(ParseError {
149-
span: arm.pattern.span,
150-
item_description: format!("{:?}", arm.pattern.kind),
151-
expected: "constant pattern".to_string(),
152-
});
147+
let value = match arm.pattern.kind {
148+
PatKind::Constant { value } => value,
149+
PatKind::ExpandedConstant { ref subpattern, def_id: _, is_inline: false }
150+
if let PatKind::Constant { value } = subpattern.kind =>
151+
{
152+
value
153+
}
154+
_ => {
155+
return Err(ParseError {
156+
span: arm.pattern.span,
157+
item_description: format!("{:?}", arm.pattern.kind),
158+
expected: "constant pattern".to_string(),
159+
});
160+
}
153161
};
154162
values.push(value.eval_bits(self.tcx, self.typing_env));
155163
targets.push(self.parse_block(arm.body)?);

compiler/rustc_mir_build/src/build/matches/match_pair.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,11 @@ impl<'pat, 'tcx> MatchPairTree<'pat, 'tcx> {
162162
TestCase::Irrefutable { ascription: None, binding }
163163
}
164164

165-
PatKind::InlineConstant { subpattern: ref pattern, def, .. } => {
165+
PatKind::ExpandedConstant { subpattern: ref pattern, def_id: _, is_inline: false } => {
166+
subpairs.push(MatchPairTree::for_pattern(place_builder, pattern, cx));
167+
default_irrefutable()
168+
}
169+
PatKind::ExpandedConstant { subpattern: ref pattern, def_id, is_inline: true } => {
166170
// Apply a type ascription for the inline constant to the value at `match_pair.place`
167171
let ascription = place.map(|source| {
168172
let span = pattern.span;
@@ -173,7 +177,7 @@ impl<'pat, 'tcx> MatchPairTree<'pat, 'tcx> {
173177
})
174178
.args;
175179
let user_ty = cx.infcx.canonicalize_user_type_annotation(ty::UserType::TypeOf(
176-
def.to_def_id(),
180+
def_id,
177181
ty::UserArgs { args, user_self_ty: None },
178182
));
179183
let annotation = ty::CanonicalUserTypeAnnotation {

compiler/rustc_mir_build/src/build/matches/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
926926
self.visit_primary_bindings(subpattern, subpattern_user_ty, f)
927927
}
928928

929-
PatKind::InlineConstant { ref subpattern, .. } => {
929+
PatKind::ExpandedConstant { ref subpattern, .. } => {
930930
self.visit_primary_bindings(subpattern, pattern_user_ty, f)
931931
}
932932

compiler/rustc_mir_build/src/check_unsafety.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
332332
PatKind::Wild |
333333
// these just wrap other patterns, which we recurse on below.
334334
PatKind::Or { .. } |
335-
PatKind::InlineConstant { .. } |
335+
PatKind::ExpandedConstant { .. } |
336336
PatKind::AscribeUserType { .. } |
337337
PatKind::Error(_) => {}
338338
}
@@ -386,8 +386,12 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
386386
visit::walk_pat(self, pat);
387387
self.inside_adt = old_inside_adt;
388388
}
389-
PatKind::InlineConstant { def, .. } => {
390-
self.visit_inner_body(*def);
389+
PatKind::ExpandedConstant { def_id, is_inline, .. } => {
390+
if let Some(def) = def_id.as_local()
391+
&& *is_inline
392+
{
393+
self.visit_inner_body(def);
394+
}
391395
visit::walk_pat(self, pat);
392396
}
393397
_ => {

compiler/rustc_mir_build/src/errors.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -860,8 +860,10 @@ pub(crate) struct PatternNotCovered<'s, 'tcx> {
860860
pub(crate) uncovered: Uncovered,
861861
#[subdiagnostic]
862862
pub(crate) inform: Option<Inform>,
863+
#[label(mir_build_confused)]
864+
pub(crate) interpreted_as_const: Option<Span>,
863865
#[subdiagnostic]
864-
pub(crate) interpreted_as_const: Option<InterpretedAsConst>,
866+
pub(crate) interpreted_as_const_sugg: Option<InterpretedAsConst>,
865867
#[subdiagnostic]
866868
pub(crate) adt_defined_here: Option<AdtDefinedHere<'tcx>>,
867869
#[note(mir_build_privately_uninhabited)]
@@ -911,9 +913,9 @@ impl<'tcx> Subdiagnostic for AdtDefinedHere<'tcx> {
911913
#[suggestion(
912914
mir_build_interpreted_as_const,
913915
code = "{variable}_var",
914-
applicability = "maybe-incorrect"
916+
applicability = "maybe-incorrect",
917+
style = "verbose"
915918
)]
916-
#[label(mir_build_confused)]
917919
pub(crate) struct InterpretedAsConst {
918920
#[primary_span]
919921
pub(crate) span: Span,

compiler/rustc_mir_build/src/thir/pattern/check_match.rs

+48-8
Original file line numberDiff line numberDiff line change
@@ -678,8 +678,25 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
678678
let mut let_suggestion = None;
679679
let mut misc_suggestion = None;
680680
let mut interpreted_as_const = None;
681+
let mut interpreted_as_const_sugg = None;
681682

682-
if let PatKind::Constant { .. }
683+
if let PatKind::ExpandedConstant { def_id, is_inline: false, .. }
684+
| PatKind::AscribeUserType {
685+
subpattern:
686+
box Pat { kind: PatKind::ExpandedConstant { def_id, is_inline: false, .. }, .. },
687+
..
688+
} = pat.kind
689+
&& let DefKind::Const = self.tcx.def_kind(def_id)
690+
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
691+
// We filter out paths with multiple path::segments.
692+
&& snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
693+
{
694+
let span = self.tcx.def_span(def_id);
695+
let variable = self.tcx.item_name(def_id).to_string();
696+
// When we encounter a constant as the binding name, point at the `const` definition.
697+
interpreted_as_const = Some(span);
698+
interpreted_as_const_sugg = Some(InterpretedAsConst { span: pat.span, variable });
699+
} else if let PatKind::Constant { .. }
683700
| PatKind::AscribeUserType {
684701
subpattern: box Pat { kind: PatKind::Constant { .. }, .. },
685702
..
@@ -692,9 +709,6 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
692709
misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
693710
start_span: pat.span.shrink_to_lo(),
694711
});
695-
} else if snippet.chars().all(|c| c.is_alphanumeric() || c == '_') {
696-
interpreted_as_const =
697-
Some(InterpretedAsConst { span: pat.span, variable: snippet });
698712
}
699713
}
700714

@@ -743,6 +757,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
743757
uncovered: Uncovered::new(pat.span, &cx, witnesses),
744758
inform,
745759
interpreted_as_const,
760+
interpreted_as_const_sugg,
746761
witness_1_is_privately_uninhabited,
747762
_p: (),
748763
pattern_ty,
@@ -1112,13 +1127,13 @@ fn report_non_exhaustive_match<'p, 'tcx>(
11121127
if ty.is_ptr_sized_integral() {
11131128
if ty.inner() == cx.tcx.types.usize {
11141129
err.note(format!(
1115-
"`{ty}` does not have a fixed maximum value, so half-open ranges are necessary to match \
1116-
exhaustively",
1130+
"`{ty}` does not have a fixed maximum value, so half-open ranges are \
1131+
necessary to match exhaustively",
11171132
));
11181133
} else if ty.inner() == cx.tcx.types.isize {
11191134
err.note(format!(
1120-
"`{ty}` does not have fixed minimum and maximum values, so half-open ranges are necessary to match \
1121-
exhaustively",
1135+
"`{ty}` does not have fixed minimum and maximum values, so half-open \
1136+
ranges are necessary to match exhaustively",
11221137
));
11231138
}
11241139
} else if ty.inner() == cx.tcx.types.str_ {
@@ -1139,6 +1154,31 @@ fn report_non_exhaustive_match<'p, 'tcx>(
11391154
}
11401155
}
11411156

1157+
for &arm in arms {
1158+
let arm = &thir.arms[arm];
1159+
if let PatKind::ExpandedConstant { def_id, is_inline: false, .. } = arm.pattern.kind
1160+
&& let Ok(snippet) = cx.tcx.sess.source_map().span_to_snippet(arm.pattern.span)
1161+
// We filter out paths with multiple path::segments.
1162+
&& snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
1163+
{
1164+
let const_name = cx.tcx.item_name(def_id);
1165+
err.span_label(
1166+
arm.pattern.span,
1167+
format!(
1168+
"this pattern doesn't introduce a new catch-all binding, but rather pattern \
1169+
matches against the value of constant `{const_name}`",
1170+
),
1171+
);
1172+
err.span_note(cx.tcx.def_span(def_id), format!("constant `{const_name}` defined here"));
1173+
err.span_suggestion_verbose(
1174+
arm.pattern.span.shrink_to_hi(),
1175+
"if you meant to introduce a binding, use a different name",
1176+
"_var".to_string(),
1177+
Applicability::MaybeIncorrect,
1178+
);
1179+
}
1180+
}
1181+
11421182
// Whether we suggest the actual missing patterns or `_`.
11431183
let suggest_the_witnesses = witnesses.len() < 4;
11441184
let suggested_arm = if suggest_the_witnesses {

compiler/rustc_mir_build/src/thir/pattern/mod.rs

+30-12
Original file line numberDiff line numberDiff line change
@@ -149,21 +149,30 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
149149
None => Ok((None, None, None)),
150150
Some(expr) => {
151151
let (kind, ascr, inline_const) = match self.lower_lit(expr) {
152-
PatKind::InlineConstant { subpattern, def } => {
153-
(subpattern.kind, None, Some(def))
152+
PatKind::ExpandedConstant { subpattern, def_id, is_inline: true } => {
153+
(subpattern.kind, None, def_id.as_local())
154+
}
155+
PatKind::ExpandedConstant { subpattern, is_inline: false, .. } => {
156+
(subpattern.kind, None, None)
154157
}
155158
PatKind::AscribeUserType { ascription, subpattern: box Pat { kind, .. } } => {
156159
(kind, Some(ascription), None)
157160
}
158161
kind => (kind, None, None),
159162
};
160-
let value = if let PatKind::Constant { value } = kind {
161-
value
162-
} else {
163-
let msg = format!(
164-
"found bad range pattern endpoint `{expr:?}` outside of error recovery"
165-
);
166-
return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
163+
let value = match kind {
164+
PatKind::Constant { value } => value,
165+
PatKind::ExpandedConstant { subpattern, .. }
166+
if let PatKind::Constant { value } = subpattern.kind =>
167+
{
168+
value
169+
}
170+
_ => {
171+
let msg = format!(
172+
"found bad range pattern endpoint `{expr:?}` outside of error recovery"
173+
);
174+
return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
175+
}
167176
};
168177
Ok((Some(PatRangeBoundary::Finite(value)), ascr, inline_const))
169178
}
@@ -288,7 +297,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
288297
};
289298
}
290299
for def in [lo_inline, hi_inline].into_iter().flatten() {
291-
kind = PatKind::InlineConstant { def, subpattern: Box::new(Pat { span, ty, kind }) };
300+
kind = PatKind::ExpandedConstant {
301+
def_id: def.to_def_id(),
302+
is_inline: true,
303+
subpattern: Box::new(Pat { span, ty, kind }),
304+
};
292305
}
293306
Ok(kind)
294307
}
@@ -562,7 +575,12 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
562575

563576
let args = self.typeck_results.node_args(id);
564577
let c = ty::Const::new_unevaluated(self.tcx, ty::UnevaluatedConst { def: def_id, args });
565-
let pattern = self.const_to_pat(c, ty, id, span);
578+
let subpattern = self.const_to_pat(c, ty, id, span);
579+
let pattern = Box::new(Pat {
580+
span,
581+
ty,
582+
kind: PatKind::ExpandedConstant { subpattern, def_id, is_inline: false },
583+
});
566584

567585
if !is_associated_const {
568586
return pattern;
@@ -637,7 +655,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
637655

638656
let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), args };
639657
let subpattern = self.const_to_pat(ty::Const::new_unevaluated(self.tcx, ct), ty, id, span);
640-
PatKind::InlineConstant { subpattern, def: def_id }
658+
PatKind::ExpandedConstant { subpattern, def_id: def_id.to_def_id(), is_inline: true }
641659
}
642660

643661
/// Converts literals, paths and negation of literals to patterns.

compiler/rustc_mir_build/src/thir/print.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -707,9 +707,10 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> {
707707
print_indented!(self, format!("value: {:?}", value), depth_lvl + 2);
708708
print_indented!(self, "}", depth_lvl + 1);
709709
}
710-
PatKind::InlineConstant { def, subpattern } => {
711-
print_indented!(self, "InlineConstant {", depth_lvl + 1);
712-
print_indented!(self, format!("def: {:?}", def), depth_lvl + 2);
710+
PatKind::ExpandedConstant { def_id, is_inline, subpattern } => {
711+
print_indented!(self, "ExpandedConstant {", depth_lvl + 1);
712+
print_indented!(self, format!("def_id: {def_id:?}"), depth_lvl + 2);
713+
print_indented!(self, format!("is_inline: {is_inline:?}"), depth_lvl + 2);
713714
print_indented!(self, "subpattern:", depth_lvl + 2);
714715
self.print_pat(subpattern, depth_lvl + 2);
715716
print_indented!(self, "}", depth_lvl + 1);

compiler/rustc_pattern_analysis/src/rustc.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> {
465465
let fields: Vec<_>;
466466
match &pat.kind {
467467
PatKind::AscribeUserType { subpattern, .. }
468-
| PatKind::InlineConstant { subpattern, .. } => return self.lower_pat(subpattern),
468+
| PatKind::ExpandedConstant { subpattern, .. } => return self.lower_pat(subpattern),
469469
PatKind::Binding { subpattern: Some(subpat), .. } => return self.lower_pat(subpat),
470470
PatKind::Binding { subpattern: None, .. } | PatKind::Wild => {
471471
ctor = Wildcard;

tests/ui/closures/2229_closure_analysis/bad-pattern.stderr

+8-5
Original file line numberDiff line numberDiff line change
@@ -97,16 +97,19 @@ LL | if let Refutable::A = v3 { todo!() };
9797
error[E0005]: refutable pattern in local binding
9898
--> $DIR/bad-pattern.rs:19:13
9999
|
100+
LL | const PAT: u32 = 0;
101+
| -------------- missing patterns are not covered because `PAT` is interpreted as a constant pattern, not a new variable
102+
...
100103
LL | let PAT = v1;
101-
| ^^^
102-
| |
103-
| pattern `1_u32..=u32::MAX` not covered
104-
| missing patterns are not covered because `PAT` is interpreted as a constant pattern, not a new variable
105-
| help: introduce a variable instead: `PAT_var`
104+
| ^^^ pattern `1_u32..=u32::MAX` not covered
106105
|
107106
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
108107
= note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html
109108
= note: the matched value is of type `u32`
109+
help: introduce a variable instead
110+
|
111+
LL | let PAT_var = v1;
112+
| ~~~~~~~
110113

111114
error: aborting due to 7 previous errors
112115

0 commit comments

Comments
 (0)