1use std::collections::hash_map::Entry::{Occupied, Vacant};
2use std::{assert_matches, cmp};
3
4use rustc_abi::FieldIdx;
5use rustc_ast as ast;
6use rustc_data_structures::fx::FxHashMap;
7use rustc_errors::codes::*;
8use rustc_errors::{
9 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan, pluralize,
10 struct_span_code_err,
11};
12use rustc_hir::attrs::lang_items::LangItem;
13use rustc_hir::def::{CtorKind, DefKind, Res};
14use rustc_hir::def_id::DefId;
15use rustc_hir::pat_util::EnumerateAndAdjustIterator;
16use rustc_hir::{
17 self as hir, BindingMode, ByRef, ExprKind, HirId, Mutability, Pat, PatExpr, PatExprKind,
18 PatKind, expr_needs_parens,
19};
20use rustc_hir_analysis::autoderef::report_autoderef_recursion_limit_error;
21use rustc_infer::infer::RegionVariableOrigin;
22use rustc_lint_defs::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
23use rustc_middle::traits::PatternOriginExpr;
24use rustc_middle::ty::{self, Pinnedness, Ty, TypeVisitableExt, Unnormalized};
25use rustc_middle::{bug, span_bug};
26use rustc_session::diagnostics::feature_err;
27use rustc_span::edit_distance::find_best_match_for_name;
28use rustc_span::edition::Edition;
29use rustc_span::{BytePos, DUMMY_SP, Ident, Span, kw, sym};
30use rustc_trait_selection::infer::InferCtxtExt;
31use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
32use tracing::{debug, instrument, trace};
33use ty::VariantDef;
34use ty::adjustment::{PatAdjust, PatAdjustment};
35
36use crate::expectation::Expectation;
37use crate::gather_locals::DeclOrigin;
38use crate::{FnCtxt, diagnostics};
39
40const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
41This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
42pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
43this type has no compile-time size. Therefore, all accesses to trait types must be through \
44pointers. If you encounter this error you should try to avoid dereferencing the pointer.
45
46You can read more about trait objects in the Trait Objects section of the Reference: \
47https://doc.rust-lang.org/reference/types.html#trait-objects";
48
49fn is_number(text: &str) -> bool {
50 text.chars().all(|c: char| c.is_ascii_digit())
51}
52
53#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for TopInfo<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for TopInfo<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TopInfo<'tcx> {
#[inline]
fn clone(&self) -> TopInfo<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _:
::core::clone::AssertParamIsClone<Option<&'tcx hir::Expr<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<Option<Span>>;
let _: ::core::clone::AssertParamIsClone<HirId>;
*self
}
}Clone)]
57struct TopInfo<'tcx> {
58 expected: Ty<'tcx>,
60 origin_expr: Option<&'tcx hir::Expr<'tcx>>,
64 span: Option<Span>,
87 hir_id: HirId,
89}
90
91#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for PatInfo<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for PatInfo<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PatInfo<'tcx> {
#[inline]
fn clone(&self) -> PatInfo<'tcx> {
let _: ::core::clone::AssertParamIsClone<ByRef>;
let _: ::core::clone::AssertParamIsClone<PinnednessCap>;
let _: ::core::clone::AssertParamIsClone<MutblCap>;
let _: ::core::clone::AssertParamIsClone<TopInfo<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Option<DeclOrigin<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone)]
92struct PatInfo<'tcx> {
93 binding_mode: ByRef,
94 max_pinnedness: PinnednessCap,
95 max_ref_mutbl: MutblCap,
96 top_info: TopInfo<'tcx>,
97 decl_origin: Option<DeclOrigin<'tcx>>,
98
99 current_depth: u32,
101}
102
103impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
104 fn pattern_cause(&self, ti: &TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
105 let origin_expr_info = ti.origin_expr.map(|mut cur_expr| {
110 let mut count = 0;
111
112 while let ExprKind::AddrOf(.., inner) = &cur_expr.kind {
116 cur_expr = inner;
117 count += 1;
118 }
119
120 PatternOriginExpr {
121 peeled_span: cur_expr.span,
122 peeled_count: count,
123 peeled_prefix_suggestion_parentheses: expr_needs_parens(cur_expr),
124 }
125 });
126
127 let code = ObligationCauseCode::Pattern {
128 span: ti.span,
129 root_ty: ti.expected,
130 origin_expr: origin_expr_info,
131 };
132 self.cause(cause_span, code)
133 }
134
135 fn demand_eqtype_pat_diag(
136 &'a self,
137 cause_span: Span,
138 expected: Ty<'tcx>,
139 actual: Ty<'tcx>,
140 ti: &TopInfo<'tcx>,
141 ) -> Result<(), Diag<'a>> {
142 self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
143 .map_err(|mut diag| {
144 if let Some(expr) = ti.origin_expr {
145 self.suggest_fn_call(&mut diag, expr, expected, |output| {
146 self.can_eq(self.param_env, output, actual)
147 });
148 }
149 diag
150 })
151 }
152
153 fn demand_eqtype_pat(
154 &self,
155 cause_span: Span,
156 expected: Ty<'tcx>,
157 actual: Ty<'tcx>,
158 ti: &TopInfo<'tcx>,
159 ) -> Result<(), ErrorGuaranteed> {
160 self.demand_eqtype_pat_diag(cause_span, expected, actual, ti).map_err(|err| err.emit())
161 }
162}
163
164#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AdjustMode { }
#[automatically_derived]
impl ::core::clone::Clone for AdjustMode {
#[inline]
fn clone(&self) -> AdjustMode {
let _: ::core::clone::AssertParamIsClone<PeelKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AdjustMode { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for AdjustMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AdjustMode::Peel { kind: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Peel",
"kind", &__self_0),
AdjustMode::Pass => ::core::fmt::Formatter::write_str(f, "Pass"),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AdjustMode { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AdjustMode {
#[inline]
fn eq(&self, other: &AdjustMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(AdjustMode::Peel { kind: __self_0 }, AdjustMode::Peel {
kind: __arg1_0 }) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AdjustMode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<PeelKind>;
}
}Eq)]
166enum AdjustMode {
167 Peel { kind: PeelKind },
170 Pass,
172}
173
174#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PeelKind { }
#[automatically_derived]
impl ::core::clone::Clone for PeelKind {
#[inline]
fn clone(&self) -> PeelKind {
let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PeelKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for PeelKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PeelKind::ExplicitDerefPat =>
::core::fmt::Formatter::write_str(f, "ExplicitDerefPat"),
PeelKind::Implicit { until_adt: __self_0, pat_ref_layers: __self_1
} =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Implicit", "until_adt", __self_0, "pat_ref_layers",
&__self_1),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for PeelKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PeelKind {
#[inline]
fn eq(&self, other: &PeelKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PeelKind::Implicit {
until_adt: __self_0, pat_ref_layers: __self_1 },
PeelKind::Implicit {
until_adt: __arg1_0, pat_ref_layers: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PeelKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<DefId>>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq)]
176enum PeelKind {
177 ExplicitDerefPat,
180 Implicit {
182 until_adt: Option<DefId>,
185 pat_ref_layers: usize,
188 },
189}
190
191impl AdjustMode {
192 const fn peel_until_adt(opt_adt_def: Option<DefId>) -> AdjustMode {
193 AdjustMode::Peel { kind: PeelKind::Implicit { until_adt: opt_adt_def, pat_ref_layers: 0 } }
194 }
195 const fn peel_all() -> AdjustMode {
196 AdjustMode::peel_until_adt(None)
197 }
198}
199
200#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MutblCap { }
#[automatically_derived]
impl ::core::clone::Clone for MutblCap {
#[inline]
fn clone(&self) -> MutblCap {
let _: ::core::clone::AssertParamIsClone<Option<Span>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MutblCap { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MutblCap {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MutblCap::Not => ::core::fmt::Formatter::write_str(f, "Not"),
MutblCap::WeaklyNot(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"WeaklyNot", &__self_0),
MutblCap::Mut => ::core::fmt::Formatter::write_str(f, "Mut"),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MutblCap { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MutblCap {
#[inline]
fn eq(&self, other: &MutblCap) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(MutblCap::WeaklyNot(__self_0), MutblCap::WeaklyNot(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MutblCap {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<Span>>;
}
}Eq)]
211enum MutblCap {
212 Not,
214
215 WeaklyNot(Option<Span>),
222
223 Mut,
225}
226
227impl MutblCap {
228 #[must_use]
229 fn cap_to_weakly_not(self, span: Option<Span>) -> Self {
230 match self {
231 MutblCap::Not => MutblCap::Not,
232 _ => MutblCap::WeaklyNot(span),
233 }
234 }
235
236 #[must_use]
237 fn as_mutbl(self) -> Mutability {
238 match self {
239 MutblCap::Not | MutblCap::WeaklyNot(_) => Mutability::Not,
240 MutblCap::Mut => Mutability::Mut,
241 }
242 }
243}
244
245#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PinnednessCap { }
#[automatically_derived]
impl ::core::clone::Clone for PinnednessCap {
#[inline]
fn clone(&self) -> PinnednessCap { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PinnednessCap { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for PinnednessCap {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
PinnednessCap::Not => "Not",
PinnednessCap::Pinned => "Pinned",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for PinnednessCap { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PinnednessCap {
#[inline]
fn eq(&self, other: &PinnednessCap) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PinnednessCap {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
251enum PinnednessCap {
252 Not,
254 Pinned,
256}
257
258#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InheritedRefMatchRule { }
#[automatically_derived]
impl ::core::clone::Clone for InheritedRefMatchRule {
#[inline]
fn clone(&self) -> InheritedRefMatchRule {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for InheritedRefMatchRule { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InheritedRefMatchRule {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InheritedRefMatchRule::EatOuter =>
::core::fmt::Formatter::write_str(f, "EatOuter"),
InheritedRefMatchRule::EatInner =>
::core::fmt::Formatter::write_str(f, "EatInner"),
InheritedRefMatchRule::EatBoth { consider_inherited_ref: __self_0
} =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"EatBoth", "consider_inherited_ref", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for InheritedRefMatchRule { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InheritedRefMatchRule {
#[inline]
fn eq(&self, other: &InheritedRefMatchRule) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(InheritedRefMatchRule::EatBoth {
consider_inherited_ref: __self_0 },
InheritedRefMatchRule::EatBoth {
consider_inherited_ref: __arg1_0 }) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InheritedRefMatchRule {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq)]
264enum InheritedRefMatchRule {
265 EatOuter,
269 EatInner,
272 EatBoth {
275 consider_inherited_ref: bool,
286 },
287}
288
289#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ResolvedPat<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ResolvedPat<'tcx> {
#[inline]
fn clone(&self) -> ResolvedPat<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ResolvedPatKind<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ResolvedPat<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ResolvedPat<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "ResolvedPat",
"ty", &self.ty, "kind", &&self.kind)
}
}Debug)]
298struct ResolvedPat<'tcx> {
299 ty: Ty<'tcx>,
302 kind: ResolvedPatKind<'tcx>,
303}
304
305#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for ResolvedPatKind<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ResolvedPatKind<'tcx> {
#[inline]
fn clone(&self) -> ResolvedPatKind<'tcx> {
let _: ::core::clone::AssertParamIsClone<Res>;
let _:
::core::clone::AssertParamIsClone<&'tcx [hir::PathSegment<'tcx>]>;
let _: ::core::clone::AssertParamIsClone<&'tcx VariantDef>;
let _: ::core::clone::AssertParamIsClone<&'tcx VariantDef>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ResolvedPatKind<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ResolvedPatKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ResolvedPatKind::Path {
res: __self_0, pat_res: __self_1, segments: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f, "Path",
"res", __self_0, "pat_res", __self_1, "segments",
&__self_2),
ResolvedPatKind::Struct { variant: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Struct", "variant", &__self_0),
ResolvedPatKind::TupleStruct { res: __self_0, variant: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TupleStruct", "res", __self_0, "variant", &__self_1),
}
}
}Debug)]
306enum ResolvedPatKind<'tcx> {
307 Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] },
308 Struct { variant: &'tcx VariantDef },
309 TupleStruct { res: Res, variant: &'tcx VariantDef },
310}
311
312impl<'tcx> ResolvedPat<'tcx> {
313 fn adjust_mode(&self) -> AdjustMode {
314 if let ResolvedPatKind::Path { res, .. } = self.kind
315 && #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _))
316 {
317 AdjustMode::Pass
321 } else {
322 AdjustMode::peel_until_adt(self.ty.ty_adt_def().map(|adt| adt.did()))
326 }
327 }
328}
329
330impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
331 fn downgrade_mut_inside_shared(&self) -> bool {
335 self.tcx.features().ref_pat_eat_one_layer_2024_structural()
338 }
339
340 fn ref_pat_matches_inherited_ref(&self, edition: Edition) -> InheritedRefMatchRule {
343 if edition.at_least_rust_2024() {
346 if self.tcx.features().ref_pat_eat_one_layer_2024() {
347 InheritedRefMatchRule::EatOuter
348 } else if self.tcx.features().ref_pat_eat_one_layer_2024_structural() {
349 InheritedRefMatchRule::EatInner
350 } else {
351 InheritedRefMatchRule::EatBoth { consider_inherited_ref: false }
354 }
355 } else {
356 InheritedRefMatchRule::EatBoth {
357 consider_inherited_ref: self.tcx.features().ref_pat_eat_one_layer_2024()
358 || self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
359 }
360 }
361 }
362
363 fn ref_pat_matches_mut_ref(&self) -> bool {
366 self.tcx.features().ref_pat_eat_one_layer_2024()
369 || self.tcx.features().ref_pat_eat_one_layer_2024_structural()
370 }
371
372 pub(crate) fn check_pat_top(
381 &self,
382 pat: &'tcx Pat<'tcx>,
383 expected: Ty<'tcx>,
384 span: Option<Span>,
385 origin_expr: Option<&'tcx hir::Expr<'tcx>>,
386 decl_origin: Option<DeclOrigin<'tcx>>,
387 ) {
388 let top_info = TopInfo { expected, origin_expr, span, hir_id: pat.hir_id };
389 let pat_info = PatInfo {
390 binding_mode: ByRef::No,
391 max_pinnedness: PinnednessCap::Not,
392 max_ref_mutbl: MutblCap::Mut,
393 top_info,
394 decl_origin,
395 current_depth: 0,
396 };
397 self.check_pat(pat, expected, pat_info);
398 }
399
400 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_pat",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(405u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat")
}> =
::tracing::__macro_support::FieldName::new("pat");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let opt_path_res =
match pat.kind {
PatKind::Expr(PatExpr {
kind: PatExprKind::Path(qpath), hir_id, span }) => {
Some(self.resolve_pat_path(*hir_id, *span, qpath))
}
PatKind::Struct(ref qpath, ..) =>
Some(self.resolve_pat_struct(pat, qpath)),
PatKind::TupleStruct(ref qpath, ..) =>
Some(self.resolve_pat_tuple_struct(pat, qpath)),
_ => None,
};
let adjust_mode = self.calc_adjust_mode(pat, opt_path_res);
let ty =
self.check_pat_inner(pat, opt_path_res, adjust_mode, expected,
pat_info);
self.write_ty(pat.hir_id, ty);
if let Some(derefed_tys) =
self.typeck_results.borrow().pat_adjustments().get(pat.hir_id)
&&
derefed_tys.iter().any(|adjust|
adjust.kind == PatAdjust::OverloadedDeref) {
self.register_deref_mut_bounds_if_needed(pat.span, pat,
derefed_tys.iter().filter_map(|adjust|
match adjust.kind {
PatAdjust::OverloadedDeref => Some(adjust.source),
PatAdjust::BuiltinDeref | PatAdjust::PinDeref => None,
}));
}
}
}
}#[instrument(level = "debug", skip(self, pat_info))]
406 fn check_pat(&self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>) {
407 let opt_path_res = match pat.kind {
410 PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => {
411 Some(self.resolve_pat_path(*hir_id, *span, qpath))
412 }
413 PatKind::Struct(ref qpath, ..) => Some(self.resolve_pat_struct(pat, qpath)),
414 PatKind::TupleStruct(ref qpath, ..) => Some(self.resolve_pat_tuple_struct(pat, qpath)),
415 _ => None,
416 };
417 let adjust_mode = self.calc_adjust_mode(pat, opt_path_res);
418 let ty = self.check_pat_inner(pat, opt_path_res, adjust_mode, expected, pat_info);
419 self.write_ty(pat.hir_id, ty);
420
421 if let Some(derefed_tys) = self.typeck_results.borrow().pat_adjustments().get(pat.hir_id)
424 && derefed_tys.iter().any(|adjust| adjust.kind == PatAdjust::OverloadedDeref)
425 {
426 self.register_deref_mut_bounds_if_needed(
427 pat.span,
428 pat,
429 derefed_tys.iter().filter_map(|adjust| match adjust.kind {
430 PatAdjust::OverloadedDeref => Some(adjust.source),
431 PatAdjust::BuiltinDeref | PatAdjust::PinDeref => None,
432 }),
433 );
434 }
435
436 }
478
479 fn check_pat_inner(
481 &self,
482 pat: &'tcx Pat<'tcx>,
483 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
484 adjust_mode: AdjustMode,
485 expected: Ty<'tcx>,
486 pat_info: PatInfo<'tcx>,
487 ) -> Ty<'tcx> {
488 #[cfg(debug_assertions)]
489 if #[allow(non_exhaustive_omitted_patterns)] match pat_info.binding_mode {
ByRef::Yes(_, Mutability::Mut) => true,
_ => false,
}matches!(pat_info.binding_mode, ByRef::Yes(_, Mutability::Mut))
490 && pat_info.max_ref_mutbl != MutblCap::Mut
491 && self.downgrade_mut_inside_shared()
492 {
493 ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("Pattern mutability cap violated!"));span_bug!(pat.span, "Pattern mutability cap violated!");
494 }
495
496 let expected = if let AdjustMode::Peel { .. } = adjust_mode
498 && pat.default_binding_modes
499 {
500 self.resolve_vars_with_obligations(expected)
501 } else {
502 expected
503 };
504 let old_pat_info = pat_info;
505 let pat_info = PatInfo { current_depth: old_pat_info.current_depth + 1, ..old_pat_info };
506
507 match pat.kind {
508 _ if let AdjustMode::Peel { kind: peel_kind } = adjust_mode
511 && pat.default_binding_modes
512 && let &ty::Ref(_, inner_ty, inner_mutability) = expected.kind()
513 && self.should_peel_ref(peel_kind, expected) =>
514 {
515 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:515",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(515u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inspecting {0:?}",
expected) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("inspecting {:?}", expected);
516
517 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:517",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(517u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("current discriminant is Ref, inserting implicit deref")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("current discriminant is Ref, inserting implicit deref");
518 self.typeck_results
520 .borrow_mut()
521 .pat_adjustments_mut()
522 .entry(pat.hir_id)
523 .or_default()
524 .push(PatAdjustment { kind: PatAdjust::BuiltinDeref, source: expected });
525
526 let new_pat_info =
528 self.adjust_pat_info(Pinnedness::Not, inner_mutability, old_pat_info);
529
530 self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, new_pat_info)
532 }
533 _ if self.tcx.features().pin_ergonomics()
536 && let AdjustMode::Peel { kind: peel_kind } = adjust_mode
537 && pat.default_binding_modes
538 && self.should_peel_smart_pointer(peel_kind, expected)
539 && let Some(pinned_ty) = expected.pinned_ty()
540 && let &ty::Ref(_, inner_ty, inner_mutability) = pinned_ty.kind() =>
544 {
545 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:545",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(545u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("scrutinee ty {0:?} is a pinned reference, inserting pin deref",
expected) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("scrutinee ty {expected:?} is a pinned reference, inserting pin deref");
546
547 let new_pat_info =
549 self.adjust_pat_info(Pinnedness::Pinned, inner_mutability, old_pat_info);
550
551 self.check_deref_pattern(
552 pat,
553 opt_path_res,
554 adjust_mode,
555 expected,
556 inner_ty,
557 PatAdjust::PinDeref,
558 new_pat_info,
559 )
560 }
561 _ if self.tcx.features().deref_patterns()
564 && let AdjustMode::Peel { kind: peel_kind } = adjust_mode
565 && pat.default_binding_modes
566 && self.should_peel_smart_pointer(peel_kind, expected) =>
567 {
568 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:568",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(568u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("scrutinee ty {0:?} is a smart pointer, inserting pin deref",
expected) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("scrutinee ty {expected:?} is a smart pointer, inserting pin deref");
569
570 let inner_ty = self.deref_pat_target(pat.span, expected);
573 self.check_deref_pattern(
577 pat,
578 opt_path_res,
579 adjust_mode,
580 expected,
581 inner_ty,
582 PatAdjust::OverloadedDeref,
583 old_pat_info,
584 )
585 }
586 PatKind::Missing | PatKind::Wild | PatKind::Err(_) => expected,
587 PatKind::Never => expected,
589 PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), hir_id, .. }) => {
590 let ty = match opt_path_res.unwrap() {
591 Ok(ref pr) => {
592 self.check_pat_path(pat.hir_id, pat.span, pr, expected, &pat_info.top_info)
593 }
594 Err(guar) => Ty::new_error(self.tcx, guar),
595 };
596 self.write_ty(*hir_id, ty);
597 ty
598 }
599 PatKind::Expr(expr @ PatExpr { kind: PatExprKind::Lit { lit, .. }, .. }) => {
600 self.check_pat_lit(pat.span, expr, &lit.node, expected, &pat_info.top_info)
601 }
602 PatKind::Range(lhs, rhs, _) => {
603 self.check_pat_range(pat.span, lhs, rhs, expected, &pat_info.top_info)
604 }
605 PatKind::Binding(ba, var_id, ident, sub) => {
606 self.check_pat_ident(pat, ba, var_id, ident, sub, expected, pat_info)
607 }
608 PatKind::TupleStruct(ref qpath, subpats, ddpos) => match opt_path_res.unwrap() {
609 Ok(ResolvedPat { ty, kind: ResolvedPatKind::TupleStruct { res, variant } }) => self
610 .check_pat_tuple_struct(
611 pat, qpath, subpats, ddpos, res, ty, variant, expected, pat_info,
612 ),
613 Err(guar) => {
614 let ty_err = Ty::new_error(self.tcx, guar);
615 for subpat in subpats {
616 self.check_pat(subpat, ty_err, pat_info);
617 }
618 ty_err
619 }
620 Ok(pr) => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("tuple struct pattern resolved to {0:?}", pr))span_bug!(pat.span, "tuple struct pattern resolved to {pr:?}"),
621 },
622 PatKind::Struct(_, fields, has_rest_pat) => match opt_path_res.unwrap() {
623 Ok(ResolvedPat { ty, kind: ResolvedPatKind::Struct { variant } }) => self
624 .check_pat_struct(
625 pat,
626 fields,
627 has_rest_pat.is_some(),
628 ty,
629 variant,
630 expected,
631 pat_info,
632 ),
633 Err(guar) => {
634 let ty_err = Ty::new_error(self.tcx, guar);
635 for field in fields {
636 self.check_pat(field.pat, ty_err, pat_info);
637 }
638 ty_err
639 }
640 Ok(pr) => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("struct pattern resolved to {0:?}", pr))span_bug!(pat.span, "struct pattern resolved to {pr:?}"),
641 },
642 PatKind::Guard(pat, cond) => {
643 self.check_pat(pat, expected, pat_info);
644 self.check_expr_has_type_or_error(cond, self.tcx.types.bool, |_| {});
645 expected
646 }
647 PatKind::Or(pats) => {
648 for pat in pats {
649 self.check_pat(pat, expected, pat_info);
650 }
651 expected
652 }
653 PatKind::Tuple(elements, ddpos) => {
654 self.check_pat_tuple(pat.span, elements, ddpos, expected, pat_info)
655 }
656 PatKind::Deref(inner) => self.check_pat_deref(pat.span, inner, expected, pat_info),
657 PatKind::Ref(inner, pinned, mutbl) => {
658 self.check_pat_ref(pat, inner, pinned, mutbl, expected, pat_info)
659 }
660 PatKind::Slice(before, slice, after) => {
661 self.check_pat_slice(pat.span, before, slice, after, expected, pat_info)
662 }
663 }
664 }
665
666 fn adjust_pat_info(
667 &self,
668 inner_pinnedness: Pinnedness,
669 inner_mutability: Mutability,
670 pat_info: PatInfo<'tcx>,
671 ) -> PatInfo<'tcx> {
672 let mut binding_mode = match pat_info.binding_mode {
673 ByRef::No => ByRef::Yes(inner_pinnedness, inner_mutability),
677 ByRef::Yes(pinnedness, mutability) => {
678 let pinnedness = match pinnedness {
679 Pinnedness::Not => inner_pinnedness,
681 Pinnedness::Pinned => Pinnedness::Pinned,
687 };
688
689 let mutability = match mutability {
690 Mutability::Mut => inner_mutability,
692 Mutability::Not => Mutability::Not,
695 };
696 ByRef::Yes(pinnedness, mutability)
697 }
698 };
699
700 let PatInfo { mut max_ref_mutbl, mut max_pinnedness, .. } = pat_info;
701 if self.downgrade_mut_inside_shared() {
702 binding_mode = binding_mode.cap_ref_mutability(max_ref_mutbl.as_mutbl());
703 }
704 match binding_mode {
705 ByRef::Yes(_, Mutability::Not) => max_ref_mutbl = MutblCap::Not,
706 ByRef::Yes(Pinnedness::Pinned, _) => max_pinnedness = PinnednessCap::Pinned,
707 _ => {}
708 }
709 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:709",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(709u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("default binding mode is now {0:?}",
binding_mode) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("default binding mode is now {:?}", binding_mode);
710 PatInfo { binding_mode, max_pinnedness, max_ref_mutbl, ..pat_info }
711 }
712
713 fn check_deref_pattern(
714 &self,
715 pat: &'tcx Pat<'tcx>,
716 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
717 adjust_mode: AdjustMode,
718 expected: Ty<'tcx>,
719 mut inner_ty: Ty<'tcx>,
720 pat_adjust_kind: PatAdjust,
721 pat_info: PatInfo<'tcx>,
722 ) -> Ty<'tcx> {
723 if true {
if !!#[allow(non_exhaustive_omitted_patterns)] match pat_adjust_kind {
PatAdjust::BuiltinDeref => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("unexpected deref pattern for builtin reference type {0:?}",
expected));
}
};
};debug_assert!(
724 !matches!(pat_adjust_kind, PatAdjust::BuiltinDeref),
725 "unexpected deref pattern for builtin reference type {expected:?}",
726 );
727
728 let mut typeck_results = self.typeck_results.borrow_mut();
729 let mut pat_adjustments_table = typeck_results.pat_adjustments_mut();
730 let pat_adjustments = pat_adjustments_table.entry(pat.hir_id).or_default();
731 if self.tcx.recursion_limit().value_within_limit(pat_adjustments.len()) {
738 pat_adjustments.push(PatAdjustment { kind: pat_adjust_kind, source: expected });
740 } else {
741 let guar = report_autoderef_recursion_limit_error(self.tcx, pat.span, expected);
742 inner_ty = Ty::new_error(self.tcx, guar);
743 }
744 drop(typeck_results);
745
746 self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, pat_info)
749 }
750
751 fn calc_adjust_mode(
755 &self,
756 pat: &'tcx Pat<'tcx>,
757 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
758 ) -> AdjustMode {
759 match &pat.kind {
760 PatKind::Tuple(..) | PatKind::Range(..) | PatKind::Slice(..) => AdjustMode::peel_all(),
763 PatKind::Deref(_) => {
765 AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }
766 }
767 PatKind::Never => AdjustMode::peel_all(),
769 PatKind::Struct(..)
771 | PatKind::TupleStruct(..)
772 | PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => {
773 opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode())
775 }
776
777 PatKind::Expr(lt) => {
782 if truecfg!(debug_assertions)
785 && self.tcx.features().deref_patterns()
786 && !#[allow(non_exhaustive_omitted_patterns)] match lt.kind {
PatExprKind::Lit { .. } => true,
_ => false,
}matches!(lt.kind, PatExprKind::Lit { .. })
787 {
788 ::rustc_middle::util::bug::span_bug_fmt(lt.span,
format_args!("FIXME(deref_patterns): adjust mode unimplemented for {0:?}",
lt.kind));span_bug!(
789 lt.span,
790 "FIXME(deref_patterns): adjust mode unimplemented for {:?}",
791 lt.kind
792 );
793 }
794 let lit_ty = self.resolve_vars_if_possible(self.check_pat_expr_unadjusted(lt));
796 if self.tcx.features().deref_patterns() {
798 let mut peeled_ty = lit_ty;
799 let mut pat_ref_layers = 0;
800 while let ty::Ref(_, inner_ty, mutbl) =
801 *self.resolve_vars_with_obligations(peeled_ty).kind()
802 {
803 if true {
if !mutbl.is_not() {
::core::panicking::panic("assertion failed: mutbl.is_not()")
};
};debug_assert!(mutbl.is_not());
805 pat_ref_layers += 1;
806 peeled_ty = inner_ty;
807 }
808 AdjustMode::Peel {
809 kind: PeelKind::Implicit { until_adt: None, pat_ref_layers },
810 }
811 } else {
812 if lit_ty.is_ref() { AdjustMode::Pass } else { AdjustMode::peel_all() }
813 }
814 }
815
816 PatKind::Ref(..)
818 | PatKind::Missing
820 | PatKind::Wild
822 | PatKind::Err(_)
824 | PatKind::Binding(..)
829 | PatKind::Or(_)
833 | PatKind::Guard(..) => AdjustMode::Pass,
835 }
836 }
837
838 fn should_peel_ref(&self, peel_kind: PeelKind, mut expected: Ty<'tcx>) -> bool {
840 if true {
if !expected.is_ref() {
::core::panicking::panic("assertion failed: expected.is_ref()")
};
};debug_assert!(expected.is_ref());
841 let pat_ref_layers = match peel_kind {
842 PeelKind::ExplicitDerefPat => 0,
843 PeelKind::Implicit { pat_ref_layers, .. } => pat_ref_layers,
844 };
845
846 if pat_ref_layers == 0 {
849 return true;
850 }
851 if true {
if !self.tcx.features().deref_patterns() {
{
::core::panicking::panic_fmt(format_args!("Peeling for patterns with reference types is gated by `deref_patterns`."));
}
};
};debug_assert!(
852 self.tcx.features().deref_patterns(),
853 "Peeling for patterns with reference types is gated by `deref_patterns`."
854 );
855
856 let mut expected_ref_layers = 0;
862 while let ty::Ref(_, inner_ty, mutbl) = *expected.kind() {
863 if mutbl.is_mut() {
864 return true;
867 }
868 expected_ref_layers += 1;
869 expected = inner_ty;
870 }
871 pat_ref_layers < expected_ref_layers || self.should_peel_smart_pointer(peel_kind, expected)
872 }
873
874 fn should_peel_smart_pointer(&self, peel_kind: PeelKind, expected: Ty<'tcx>) -> bool {
876 if let PeelKind::Implicit { until_adt, .. } = peel_kind
878 && let ty::Adt(scrutinee_adt, _) = *expected.kind()
883 && until_adt != Some(scrutinee_adt.did())
886 && let Some(deref_trait) = self.tcx.lang_items().deref_trait()
891 && self.type_implements_trait(deref_trait, [expected], self.param_env).may_apply()
892 {
893 true
894 } else {
895 false
896 }
897 }
898
899 fn check_pat_expr_unadjusted(&self, lt: &'tcx hir::PatExpr<'tcx>) -> Ty<'tcx> {
900 let ty = match <.kind {
901 rustc_hir::PatExprKind::Lit { lit, negated } => {
902 let ty = self.check_expr_lit(lit, lt.hir_id, Expectation::NoExpectation);
903 if *negated {
904 self.register_bound(
905 ty,
906 self.tcx.require_lang_item(LangItem::Neg, lt.span),
907 ObligationCause::dummy_with_span(lt.span),
908 );
909 }
910 ty
911 }
912 rustc_hir::PatExprKind::Path(qpath) => {
913 let (res, opt_ty, segments) =
914 self.resolve_ty_and_res_fully_qualified_call(qpath, lt.hir_id, lt.span);
915 self.instantiate_value_path(segments, opt_ty, res, lt.span, lt.span, lt.hir_id).0
916 }
917 };
918 self.write_ty(lt.hir_id, ty);
919 ty
920 }
921
922 fn check_pat_lit(
923 &self,
924 span: Span,
925 expr: &hir::PatExpr<'tcx>,
926 lit_kind: &ast::LitKind,
927 expected: Ty<'tcx>,
928 ti: &TopInfo<'tcx>,
929 ) -> Ty<'tcx> {
930 {
match expr.kind {
hir::PatExprKind::Lit { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"hir::PatExprKind::Lit { .. }", ::core::option::Option::None);
}
}
};assert_matches!(expr.kind, hir::PatExprKind::Lit { .. });
931
932 let ty = self.node_ty(expr.hir_id);
935
936 let mut pat_ty = ty;
941 if #[allow(non_exhaustive_omitted_patterns)] match lit_kind {
ast::LitKind::ByteStr(..) => true,
_ => false,
}matches!(lit_kind, ast::LitKind::ByteStr(..)) {
942 let tcx = self.tcx;
943 let expected = self.structurally_resolve_type(span, expected);
944 match *expected.kind() {
945 ty::Ref(_, inner_ty, _)
947 if self.resolve_vars_with_obligations(inner_ty).is_slice() =>
948 {
949 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:949",
"rustc_hir_typeck::pat", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(949u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expr.hir_id.local_id")
}> =
::tracing::__macro_support::FieldName::new("expr.hir_id.local_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("polymorphic byte string lit")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr.hir_id.local_id)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!(?expr.hir_id.local_id, "polymorphic byte string lit");
950 pat_ty = Ty::new_imm_ref(
951 tcx,
952 tcx.lifetimes.re_static,
953 Ty::new_slice(tcx, tcx.types.u8),
954 );
955 }
956 ty::Array(..) if tcx.features().deref_patterns() => {
958 pat_ty = match *ty.kind() {
959 ty::Ref(_, inner_ty, _) => inner_ty,
960 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("found byte string literal with non-ref type {0:?}", ty))span_bug!(span, "found byte string literal with non-ref type {ty:?}"),
961 }
962 }
963 ty::Slice(..) if tcx.features().deref_patterns() => {
965 pat_ty = Ty::new_slice(tcx, tcx.types.u8);
966 }
967 _ => {}
969 }
970 }
971
972 if self.tcx.features().deref_patterns()
975 && #[allow(non_exhaustive_omitted_patterns)] match lit_kind {
ast::LitKind::Str(..) => true,
_ => false,
}matches!(lit_kind, ast::LitKind::Str(..))
976 && self.resolve_vars_with_obligations(expected).is_str()
977 {
978 pat_ty = self.tcx.types.str_;
979 }
980
981 let cause = self.pattern_cause(ti, span);
992 if let Err(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
993 let expected = self.resolve_vars_with_obligations(expected);
995 if let ty::Adt(adt, _) = expected.kind()
996 && self.tcx.is_lang_item(adt.did(), LangItem::String)
997 && pat_ty.is_ref()
998 && pat_ty.peel_refs().is_str()
999 && let Some(origin_expr) = ti.origin_expr
1000 {
1001 err.span_suggestion_verbose(
1002 origin_expr.span.shrink_to_hi(),
1003 "consider converting the `String` to a `&str` using `.as_str()`",
1004 ".as_str()",
1005 Applicability::MachineApplicable,
1006 );
1007 }
1008 err.emit();
1009 }
1010
1011 pat_ty
1012 }
1013
1014 fn check_pat_range(
1015 &self,
1016 span: Span,
1017 lhs: Option<&'tcx hir::PatExpr<'tcx>>,
1018 rhs: Option<&'tcx hir::PatExpr<'tcx>>,
1019 expected: Ty<'tcx>,
1020 ti: &TopInfo<'tcx>,
1021 ) -> Ty<'tcx> {
1022 let calc_side = |opt_expr: Option<&'tcx hir::PatExpr<'tcx>>| match opt_expr {
1023 None => None,
1024 Some(expr) => {
1025 let ty = self.check_pat_expr_unadjusted(expr);
1026 let ty = self.resolve_vars_with_obligations(ty);
1033 let fail =
1034 !(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
1035 Some((fail, ty, expr.span))
1036 }
1037 };
1038 let mut lhs = calc_side(lhs);
1039 let mut rhs = calc_side(rhs);
1040
1041 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
1042 let guar = self.emit_err_pat_range(span, lhs, rhs);
1045 return Ty::new_error(self.tcx, guar);
1046 }
1047
1048 let demand_eqtype = |x: &mut _, y| {
1051 if let Some((ref mut fail, x_ty, x_span)) = *x
1052 && let Err(mut err) = self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti)
1053 {
1054 if let Some((_, y_ty, y_span)) = y {
1055 self.endpoint_has_type(&mut err, y_span, y_ty);
1056 }
1057 err.emit();
1058 *fail = true;
1059 }
1060 };
1061 demand_eqtype(&mut lhs, rhs);
1062 demand_eqtype(&mut rhs, lhs);
1063
1064 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
1065 return Ty::new_misc_error(self.tcx);
1066 }
1067
1068 let ty = self.structurally_resolve_type(span, expected);
1073 if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
1074 if let Some((ref mut fail, _, _)) = lhs {
1075 *fail = true;
1076 }
1077 if let Some((ref mut fail, _, _)) = rhs {
1078 *fail = true;
1079 }
1080 let guar = self.emit_err_pat_range(span, lhs, rhs);
1081 return Ty::new_error(self.tcx, guar);
1082 }
1083 ty
1084 }
1085
1086 fn endpoint_has_type(&self, err: &mut Diag<'_>, span: Span, ty: Ty<'_>) {
1087 if !ty.references_error() {
1088 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is of type `{0}`", ty))
})format!("this is of type `{ty}`"));
1089 }
1090 }
1091
1092 fn emit_err_pat_range(
1093 &self,
1094 span: Span,
1095 lhs: Option<(bool, Ty<'tcx>, Span)>,
1096 rhs: Option<(bool, Ty<'tcx>, Span)>,
1097 ) -> ErrorGuaranteed {
1098 let span = match (lhs, rhs) {
1099 (Some((true, ..)), Some((true, ..))) => span,
1100 (Some((true, _, sp)), _) => sp,
1101 (_, Some((true, _, sp))) => sp,
1102 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("emit_err_pat_range: no side failed or exists but still error?"))span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
1103 };
1104 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("only `char` and numeric types are allowed in range patterns"))
})).with_code(E0029)
}struct_span_code_err!(
1105 self.dcx(),
1106 span,
1107 E0029,
1108 "only `char` and numeric types are allowed in range patterns"
1109 );
1110 let msg = |ty| {
1111 let ty = self.resolve_vars_if_possible(ty);
1112 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is of type `{0}` but it should be `char` or numeric",
ty))
})format!("this is of type `{ty}` but it should be `char` or numeric")
1113 };
1114 let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
1115 err.span_label(first_span, msg(first_ty));
1116 if let Some((_, ty, sp)) = second {
1117 let ty = self.resolve_vars_if_possible(ty);
1118 self.endpoint_has_type(&mut err, sp, ty);
1119 }
1120 };
1121 match (lhs, rhs) {
1122 (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
1123 err.span_label(lhs_sp, msg(lhs_ty));
1124 err.span_label(rhs_sp, msg(rhs_ty));
1125 }
1126 (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
1127 (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
1128 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Impossible, verified above."))span_bug!(span, "Impossible, verified above."),
1129 }
1130 if (lhs, rhs).references_error() {
1131 err.downgrade_to_delayed_bug();
1132 }
1133 if self.tcx.sess.teach(err.code.unwrap()) {
1134 err.note(
1135 "In a match expression, only numbers and characters can be matched \
1136 against a range. This is because the compiler checks that the range \
1137 is non-empty at compile-time, and is unable to evaluate arbitrary \
1138 comparison functions. If you want to capture values of an orderable \
1139 type between two end-points, you can use a guard.",
1140 );
1141 }
1142 err.emit()
1143 }
1144
1145 fn check_pat_ident(
1146 &self,
1147 pat: &'tcx Pat<'tcx>,
1148 user_bind_annot: BindingMode,
1149 var_id: HirId,
1150 ident: Ident,
1151 sub: Option<&'tcx Pat<'tcx>>,
1152 expected: Ty<'tcx>,
1153 pat_info: PatInfo<'tcx>,
1154 ) -> Ty<'tcx> {
1155 let PatInfo { binding_mode: def_br, top_info: ti, .. } = pat_info;
1156
1157 let bm = match user_bind_annot {
1159 BindingMode(ByRef::No, Mutability::Mut) if let ByRef::Yes(_, def_br_mutbl) = def_br => {
1160 if pat.span.at_least_rust_2024()
1163 && (self.tcx.features().ref_pat_eat_one_layer_2024()
1164 || self.tcx.features().ref_pat_eat_one_layer_2024_structural())
1165 {
1166 if !self.tcx.features().mut_ref() {
1167 feature_err(
1168 self.tcx.sess,
1169 sym::mut_ref,
1170 pat.span.until(ident.span),
1171 "binding cannot be both mutable and by-reference",
1172 )
1173 .emit();
1174 }
1175
1176 BindingMode(def_br, Mutability::Mut)
1177 } else {
1178 self.add_rust_2024_migration_desugared_pat(
1180 pat_info.top_info.hir_id,
1181 pat,
1182 't', def_br_mutbl,
1184 );
1185 BindingMode(ByRef::No, Mutability::Mut)
1186 }
1187 }
1188 BindingMode(ByRef::No, mutbl) => BindingMode(def_br, mutbl),
1189 BindingMode(ByRef::Yes(_, user_br_mutbl), _) => {
1190 if let ByRef::Yes(_, def_br_mutbl) = def_br {
1191 self.add_rust_2024_migration_desugared_pat(
1193 pat_info.top_info.hir_id,
1194 pat,
1195 match user_br_mutbl {
1196 Mutability::Not => 'f', Mutability::Mut => 't', },
1199 def_br_mutbl,
1200 );
1201 }
1202 user_bind_annot
1203 }
1204 };
1205
1206 if pat_info.max_pinnedness == PinnednessCap::Pinned
1209 && #[allow(non_exhaustive_omitted_patterns)] match bm.0 {
ByRef::Yes(Pinnedness::Not, _) => true,
_ => false,
}matches!(bm.0, ByRef::Yes(Pinnedness::Not, _))
1210 {
1211 self.register_bound(
1212 expected,
1213 self.tcx.require_lang_item(LangItem::Unpin, pat.span),
1214 self.misc(pat.span),
1215 )
1216 }
1217
1218 if #[allow(non_exhaustive_omitted_patterns)] match bm.0 {
ByRef::Yes(_, Mutability::Mut) => true,
_ => false,
}matches!(bm.0, ByRef::Yes(_, Mutability::Mut))
1219 && let MutblCap::WeaklyNot(and_pat_span) = pat_info.max_ref_mutbl
1220 {
1221 let mut err = {
self.dcx().struct_span_err(ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot borrow as mutable inside an `&` pattern"))
})).with_code(E0596)
}struct_span_code_err!(
1222 self.dcx(),
1223 ident.span,
1224 E0596,
1225 "cannot borrow as mutable inside an `&` pattern"
1226 );
1227
1228 if let Some(span) = and_pat_span {
1229 err.span_suggestion(
1230 span,
1231 "replace this `&` with `&mut`",
1232 "&mut ",
1233 Applicability::MachineApplicable,
1234 );
1235 }
1236 err.emit();
1237 }
1238
1239 self.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
1241
1242 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:1242",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(1242u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_pat_ident: pat.hir_id={0:?} bm={1:?}",
pat.hir_id, bm) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
1243
1244 let local_ty = self.local_ty(pat.span, pat.hir_id);
1245 let eq_ty = match bm.0 {
1246 ByRef::Yes(pinnedness, mutbl) => {
1247 self.new_ref_ty(pat.span, pinnedness, mutbl, expected)
1259 }
1260 ByRef::No => expected, };
1263
1264 let _ = self.demand_eqtype_pat(pat.span, eq_ty, local_ty, &ti);
1266
1267 if var_id != pat.hir_id {
1270 self.check_binding_alt_eq_ty(user_bind_annot, pat.span, var_id, local_ty, &ti);
1271 }
1272
1273 if let Some(p) = sub {
1274 self.check_pat(p, expected, pat_info);
1275 }
1276
1277 local_ty
1278 }
1279
1280 fn check_binding_alt_eq_ty(
1284 &self,
1285 ba: BindingMode,
1286 span: Span,
1287 var_id: HirId,
1288 ty: Ty<'tcx>,
1289 ti: &TopInfo<'tcx>,
1290 ) {
1291 let var_ty = self.local_ty(span, var_id);
1292 if let Err(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
1293 let var_ty = self.resolve_vars_if_possible(var_ty);
1294 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("first introduced with type `{0}` here",
var_ty))
})format!("first introduced with type `{var_ty}` here");
1295 err.span_label(self.tcx.hir_span(var_id), msg);
1296 let in_match = self.tcx.hir_parent_iter(var_id).any(|(_, n)| {
1297 #[allow(non_exhaustive_omitted_patterns)] match n {
hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::Match(.., hir::MatchSource::Normal), .. }) =>
true,
_ => false,
}matches!(
1298 n,
1299 hir::Node::Expr(hir::Expr {
1300 kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
1301 ..
1302 })
1303 )
1304 });
1305 let pre = if in_match { "in the same arm, " } else { "" };
1306 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}a binding must have the same type in all alternatives",
pre))
})format!("{pre}a binding must have the same type in all alternatives"));
1307 self.suggest_adding_missing_ref_or_removing_ref(
1308 &mut err,
1309 span,
1310 var_ty,
1311 self.resolve_vars_if_possible(ty),
1312 ba,
1313 );
1314 err.emit();
1315 }
1316 }
1317
1318 fn suggest_adding_missing_ref_or_removing_ref(
1319 &self,
1320 err: &mut Diag<'_>,
1321 span: Span,
1322 expected: Ty<'tcx>,
1323 actual: Ty<'tcx>,
1324 ba: BindingMode,
1325 ) {
1326 match (expected.kind(), actual.kind(), ba) {
1327 (ty::Ref(_, inner_ty, _), _, BindingMode::NONE)
1328 if self.can_eq(self.param_env, *inner_ty, actual) =>
1329 {
1330 err.span_suggestion_verbose(
1331 span.shrink_to_lo(),
1332 "consider adding `ref`",
1333 "ref ",
1334 Applicability::MaybeIncorrect,
1335 );
1336 }
1337 (_, ty::Ref(_, inner_ty, _), BindingMode::REF)
1338 if self.can_eq(self.param_env, expected, *inner_ty) =>
1339 {
1340 err.span_suggestion_verbose(
1341 span.with_hi(span.lo() + BytePos(4)),
1342 "consider removing `ref`",
1343 "",
1344 Applicability::MaybeIncorrect,
1345 );
1346 }
1347 _ => (),
1348 }
1349 }
1350
1351 fn borrow_pat_suggestion(&self, err: &mut Diag<'_>, pat: &Pat<'_>) {
1353 let tcx = self.tcx;
1354 if let PatKind::Ref(inner, pinned, mutbl) = pat.kind
1355 && let PatKind::Binding(_, _, binding, ..) = inner.kind
1356 {
1357 let binding_parent = tcx.parent_hir_node(pat.hir_id);
1358 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:1358",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(1358u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("inner")
}> =
::tracing::__macro_support::FieldName::new("inner");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat")
}> =
::tracing::__macro_support::FieldName::new("pat");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("binding_parent")
}> =
::tracing::__macro_support::FieldName::new("binding_parent");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inner)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binding_parent)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?inner, ?pat, ?binding_parent);
1359
1360 let pin_and_mut = pinned.prefix_str(mutbl).trim_end();
1361
1362 let mut_var_suggestion = 'block: {
1363 if mutbl.is_not() {
1364 break 'block None;
1365 }
1366
1367 let ident_kind = match binding_parent {
1368 hir::Node::Param(_) => "parameter",
1369 hir::Node::LetStmt(_) => "variable",
1370 hir::Node::Arm(_) => "binding",
1371
1372 hir::Node::Pat(Pat { kind, .. }) => match kind {
1375 PatKind::Struct(..)
1376 | PatKind::TupleStruct(..)
1377 | PatKind::Or(..)
1378 | PatKind::Guard(..)
1379 | PatKind::Tuple(..)
1380 | PatKind::Slice(..) => "binding",
1381
1382 PatKind::Missing
1383 | PatKind::Wild
1384 | PatKind::Never
1385 | PatKind::Binding(..)
1386 | PatKind::Deref(_)
1387 | PatKind::Ref(..)
1388 | PatKind::Expr(..)
1389 | PatKind::Range(..)
1390 | PatKind::Err(_) => break 'block None,
1391 },
1392
1393 _ => break 'block None,
1395 };
1396
1397 Some((
1398 pat.span,
1399 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to declare a mutable {0} use",
ident_kind))
})format!("to declare a mutable {ident_kind} use"),
1400 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mut {0}", binding))
})format!("mut {binding}"),
1401 ))
1402 };
1403
1404 match binding_parent {
1405 hir::Node::Param(hir::Param { ty_span, pat, .. })
1406 if pat.span != *ty_span
1407 && pinned.is_pinned()
1408 && !tcx.features().pin_ergonomics() =>
1409 {
1410 }
1413 hir::Node::Param(hir::Param { ty_span, pat, .. }) if pat.span != *ty_span => {
1416 err.multipart_suggestion(
1417 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to take parameter `{0}` by reference, move `&{1}` to the type",
binding, pin_and_mut))
})format!("to take parameter `{binding}` by reference, move `&{pin_and_mut}` to the type"),
1418 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(pat.span.until(inner.span), "".to_owned()),
(ty_span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
pinned.prefix_str(mutbl)))
}))]))vec![
1419 (pat.span.until(inner.span), "".to_owned()),
1420 (ty_span.shrink_to_lo(), format!("&{}", pinned.prefix_str(mutbl))),
1421 ],
1422 Applicability::MachineApplicable
1423 );
1424
1425 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1426 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1427 }
1428 }
1429 hir::Node::Pat(pt) if let PatKind::TupleStruct(_, pat_arr, _) = pt.kind => {
1430 for i in pat_arr.iter() {
1431 if let PatKind::Ref(the_ref, _, _) = i.kind
1432 && let PatKind::Binding(mt, _, ident, _) = the_ref.kind
1433 {
1434 let BindingMode(_, mtblty) = mt;
1435 err.span_suggestion_verbose(
1436 i.span,
1437 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing `&{0}` from the pattern",
pin_and_mut))
})format!("consider removing `&{pin_and_mut}` from the pattern"),
1438 mtblty.prefix_str().to_string() + &ident.name.to_string(),
1439 Applicability::MaybeIncorrect,
1440 );
1441 }
1442 }
1443 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1444 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1445 }
1446 }
1447 hir::Node::Param(_) | hir::Node::Arm(_) | hir::Node::Pat(_) => {
1448 err.span_suggestion_verbose(
1450 pat.span.until(inner.span),
1451 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing `&{0}` from the pattern",
pin_and_mut))
})format!("consider removing `&{pin_and_mut}` from the pattern"),
1452 "",
1453 Applicability::MaybeIncorrect,
1454 );
1455
1456 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1457 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1458 }
1459 }
1460 _ if let Some((sp, msg, sugg)) = mut_var_suggestion => {
1461 err.span_suggestion(sp, msg, sugg, Applicability::MachineApplicable);
1462 }
1463 _ => {} }
1465 }
1466 }
1467
1468 fn check_dereferenceable(
1469 &self,
1470 span: Span,
1471 expected: Ty<'tcx>,
1472 inner: &Pat<'_>,
1473 ) -> Result<(), ErrorGuaranteed> {
1474 if let PatKind::Binding(..) = inner.kind
1475 && let Some(pointee_ty) = self.shallow_resolve(expected).builtin_deref(true)
1476 && let ty::Dynamic(..) = pointee_ty.kind()
1477 {
1478 let type_str = self.ty_to_string(expected);
1481 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type `{0}` cannot be dereferenced",
type_str))
})).with_code(E0033)
}struct_span_code_err!(
1482 self.dcx(),
1483 span,
1484 E0033,
1485 "type `{}` cannot be dereferenced",
1486 type_str
1487 );
1488 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type `{0}` cannot be dereferenced",
type_str))
})format!("type `{type_str}` cannot be dereferenced"));
1489 if self.tcx.sess.teach(err.code.unwrap()) {
1490 err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
1491 }
1492 return Err(err.emit());
1493 }
1494 Ok(())
1495 }
1496
1497 fn resolve_pat_struct(
1498 &self,
1499 pat: &'tcx Pat<'tcx>,
1500 qpath: &hir::QPath<'tcx>,
1501 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1502 let (variant, pat_ty) = self.check_struct_path(qpath, pat.hir_id)?;
1504 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } })
1505 }
1506
1507 fn check_pin_projection(
1518 &self,
1519 pat: &'tcx Pat<'tcx>,
1520 pat_ty: Ty<'tcx>,
1521 pat_info: PatInfo<'tcx>,
1522 ) {
1523 let through_pin = pat_info.max_pinnedness == PinnednessCap::Pinned
1524 || #[allow(non_exhaustive_omitted_patterns)] match pat_info.binding_mode {
ByRef::Yes(Pinnedness::Pinned, _) => true,
_ => false,
}matches!(pat_info.binding_mode, ByRef::Yes(Pinnedness::Pinned, _));
1525 if through_pin
1526 && let Some(adt) = pat_ty.ty_adt_def()
1527 && !adt.is_pin_project()
1528 && !adt.is_pin()
1529 {
1530 let def_span: Option<Span> = self.tcx.hir_span_if_local(adt.did());
1531 let sugg_span = def_span.map(|span| span.shrink_to_lo());
1532 self.dcx().emit_err(crate::diagnostics::ProjectOnNonPinProjectType {
1533 span: pat.span,
1534 def_span,
1535 sugg_span,
1536 });
1537 }
1538 }
1539
1540 fn check_pat_struct(
1541 &self,
1542 pat: &'tcx Pat<'tcx>,
1543 fields: &'tcx [hir::PatField<'tcx>],
1544 has_rest_pat: bool,
1545 pat_ty: Ty<'tcx>,
1546 variant: &'tcx VariantDef,
1547 expected: Ty<'tcx>,
1548 pat_info: PatInfo<'tcx>,
1549 ) -> Ty<'tcx> {
1550 self.check_pin_projection(pat, pat_ty, pat_info);
1551
1552 let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1554
1555 match self.check_struct_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info) {
1557 Ok(()) => match had_err {
1558 Ok(()) => pat_ty,
1559 Err(guar) => Ty::new_error(self.tcx, guar),
1560 },
1561 Err(guar) => Ty::new_error(self.tcx, guar),
1562 }
1563 }
1564
1565 fn resolve_pat_path(
1566 &self,
1567 path_id: HirId,
1568 span: Span,
1569 qpath: &'tcx hir::QPath<'_>,
1570 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1571 let tcx = self.tcx;
1572
1573 let (res, opt_ty, segments) =
1574 self.resolve_ty_and_res_fully_qualified_call(qpath, path_id, span);
1575 match res {
1576 Res::Err => {
1577 let e =
1578 self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
1579 self.set_tainted_by_errors(e);
1580 return Err(e);
1581 }
1582 Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Variant, _) => {
1583 let expected = "unit struct, unit variant or constant";
1584 let e = self.report_unexpected_variant_res(
1585 res,
1586 None,
1587 &[],
1588 qpath,
1589 span,
1590 E0533,
1591 expected,
1592 );
1593 return Err(e);
1594 }
1595 Res::SelfCtor(def_id) => {
1596 if let ty::Adt(adt_def, _) = *tcx.type_of(def_id).skip_binder().kind()
1597 && adt_def.is_struct()
1598 && let Some((CtorKind::Const, _)) = adt_def.non_enum_variant().ctor
1599 {
1600 } else {
1602 let e = self.report_unexpected_variant_res(
1603 res,
1604 None,
1605 &[],
1606 qpath,
1607 span,
1608 E0533,
1609 "unit struct",
1610 );
1611 return Err(e);
1612 }
1613 }
1614 Res::Def(
1615 DefKind::Ctor(_, CtorKind::Const)
1616 | DefKind::Const { .. }
1617 | DefKind::AssocConst { .. }
1618 | DefKind::ConstParam,
1619 _,
1620 ) => {} _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected pattern resolution: {0:?}",
res))bug!("unexpected pattern resolution: {:?}", res),
1622 }
1623
1624 let (pat_ty, pat_res) =
1626 self.instantiate_value_path(segments, opt_ty, res, span, span, path_id);
1627 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res, pat_res, segments } })
1628 }
1629
1630 fn check_pat_path(
1631 &self,
1632 pat_id_for_diag: HirId,
1633 span: Span,
1634 resolved: &ResolvedPat<'tcx>,
1635 expected: Ty<'tcx>,
1636 ti: &TopInfo<'tcx>,
1637 ) -> Ty<'tcx> {
1638 if let Err(err) =
1639 self.demand_suptype_with_origin(&self.pattern_cause(ti, span), expected, resolved.ty)
1640 {
1641 self.emit_bad_pat_path(err, pat_id_for_diag, span, resolved);
1642 }
1643 resolved.ty
1644 }
1645
1646 fn maybe_suggest_range_literal(
1647 &self,
1648 e: &mut Diag<'_>,
1649 opt_def_id: Option<hir::def_id::DefId>,
1650 ident: Ident,
1651 ) -> bool {
1652 if let Some(def_id) = opt_def_id
1653 && let Some(hir::Node::Item(hir::Item {
1654 kind: hir::ItemKind::Const(_, _, _, ct_rhs),
1655 ..
1656 })) = self.tcx.hir_get_if_local(def_id)
1657 && let hir::Node::Expr(expr) = self.tcx.hir_node(ct_rhs.hir_id())
1658 && hir::is_range_literal(expr)
1659 {
1660 let span = self.tcx.hir_span(ct_rhs.hir_id());
1661 if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
1662 e.span_suggestion_verbose(
1663 ident.span,
1664 "you may want to move the range into the match block",
1665 snip,
1666 Applicability::MachineApplicable,
1667 );
1668 return true;
1669 }
1670 }
1671 false
1672 }
1673
1674 fn emit_bad_pat_path(
1675 &self,
1676 mut e: Diag<'_>,
1677 hir_id: HirId,
1678 pat_span: Span,
1679 resolved_pat: &ResolvedPat<'tcx>,
1680 ) {
1681 let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind else {
1682 ::rustc_middle::util::bug::span_bug_fmt(pat_span,
format_args!("unexpected resolution for path pattern: {0:?}",
resolved_pat));span_bug!(pat_span, "unexpected resolution for path pattern: {resolved_pat:?}");
1683 };
1684
1685 let span = match (self.tcx.hir_res_span(pat_res), res.opt_def_id()) {
1686 (Some(span), _) => span,
1687 (None, Some(def_id)) => self.tcx.def_span(def_id),
1688 (None, None) => {
1689 e.emit();
1690 return;
1691 }
1692 };
1693 if let [hir::PathSegment { ident, args: None, .. }] = segments
1694 && e.suggestions.len() == 0
1695 {
1696 e.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} defined here", res.descr()))
})format!("{} defined here", res.descr()));
1697 e.span_label(
1698 pat_span,
1699 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is interpreted as {1} {2}, not a new binding",
ident, res.article(), res.descr()))
})format!(
1700 "`{}` is interpreted as {} {}, not a new binding",
1701 ident,
1702 res.article(),
1703 res.descr(),
1704 ),
1705 );
1706 match self.tcx.parent_hir_node(hir_id) {
1707 hir::Node::PatField(..) => {
1708 e.span_suggestion_verbose(
1709 ident.span.shrink_to_hi(),
1710 "bind the struct field to a different name instead",
1711 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": other_{0}",
ident.as_str().to_lowercase()))
})format!(": other_{}", ident.as_str().to_lowercase()),
1712 Applicability::HasPlaceholders,
1713 );
1714 }
1715 _ => {
1716 let (type_def_id, item_def_id) = match resolved_pat.ty.kind() {
1717 ty::Adt(def, _) => match res {
1718 Res::Def(DefKind::Const { .. }, def_id) => {
1719 (Some(def.did()), Some(def_id))
1720 }
1721 _ => (None, None),
1722 },
1723 _ => (None, None),
1724 };
1725
1726 let is_range = #[allow(non_exhaustive_omitted_patterns)] match type_def_id.and_then(|id|
self.tcx.as_lang_item(id)) {
Some(LangItem::Range | LangItem::RangeFrom | LangItem::RangeTo |
LangItem::RangeFull | LangItem::RangeInclusiveStruct |
LangItem::RangeToInclusive) => true,
_ => false,
}matches!(
1727 type_def_id.and_then(|id| self.tcx.as_lang_item(id)),
1728 Some(
1729 LangItem::Range
1730 | LangItem::RangeFrom
1731 | LangItem::RangeTo
1732 | LangItem::RangeFull
1733 | LangItem::RangeInclusiveStruct
1734 | LangItem::RangeToInclusive,
1735 )
1736 );
1737 if is_range {
1738 if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
1739 let msg = "constants only support matching by type, \
1740 if you meant to match against a range of values, \
1741 consider using a range pattern like `min ..= max` in the match block";
1742 e.note(msg);
1743 }
1744 } else {
1745 let msg = "introduce a new binding instead";
1746 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("other_{0}",
ident.as_str().to_lowercase()))
})format!("other_{}", ident.as_str().to_lowercase());
1747 e.span_suggestion_verbose(
1748 ident.span,
1749 msg,
1750 sugg,
1751 Applicability::HasPlaceholders,
1752 );
1753 }
1754 }
1755 };
1756 }
1757 e.emit();
1758 }
1759
1760 fn resolve_pat_tuple_struct(
1761 &self,
1762 pat: &'tcx Pat<'tcx>,
1763 qpath: &'tcx hir::QPath<'tcx>,
1764 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1765 let tcx = self.tcx;
1766 let report_unexpected_res = |res: Res| {
1767 let expected = "tuple struct or tuple variant";
1768 let sub_pats = match pat.kind {
1769 hir::PatKind::TupleStruct(_, sub_pats, _) => sub_pats,
1770 _ => &[],
1771 };
1772 let e = self.report_unexpected_variant_res(
1773 res, None, sub_pats, qpath, pat.span, E0164, expected,
1774 );
1775 Err(e)
1776 };
1777
1778 let (res, opt_ty, segments) =
1780 self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span);
1781 if res == Res::Err {
1782 let e = self.dcx().span_delayed_bug(pat.span, "`Res::Err` but no error emitted");
1783 self.set_tainted_by_errors(e);
1784 return Err(e);
1785 }
1786
1787 let (pat_ty, res) =
1789 self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.span, pat.hir_id);
1790 if !pat_ty.is_fn() {
1791 return report_unexpected_res(res);
1792 }
1793
1794 let variant = match res {
1795 Res::Err => {
1796 self.dcx().span_bug(pat.span, "`Res::Err` but no error emitted");
1797 }
1798 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) => {
1799 return report_unexpected_res(res);
1800 }
1801 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
1802 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected pattern resolution: {0:?}",
res))bug!("unexpected pattern resolution: {:?}", res),
1803 };
1804
1805 let pat_ty = pat_ty.fn_sig(tcx).output();
1807 let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
1808
1809 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { res, variant } })
1810 }
1811
1812 fn check_pat_tuple_struct(
1813 &self,
1814 pat: &'tcx Pat<'tcx>,
1815 qpath: &'tcx hir::QPath<'tcx>,
1816 subpats: &'tcx [Pat<'tcx>],
1817 ddpos: hir::DotDotPos,
1818 res: Res,
1819 pat_ty: Ty<'tcx>,
1820 variant: &'tcx VariantDef,
1821 expected: Ty<'tcx>,
1822 pat_info: PatInfo<'tcx>,
1823 ) -> Ty<'tcx> {
1824 self.check_pin_projection(pat, pat_ty, pat_info);
1825
1826 let tcx = self.tcx;
1827 let on_error = |e| {
1828 for pat in subpats {
1829 self.check_pat(pat, Ty::new_error(tcx, e), pat_info);
1830 }
1831 };
1832
1833 let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1835
1836 if subpats.len() == variant.fields.len()
1838 || subpats.len() < variant.fields.len() && ddpos.as_opt_usize().is_some()
1839 {
1840 let ty::Adt(_, args) = pat_ty.kind() else {
1841 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected pattern type {0:?}",
pat_ty));bug!("unexpected pattern type {:?}", pat_ty);
1842 };
1843 for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
1844 let field = &variant.fields[FieldIdx::from_usize(i)];
1845 let field_ty = self.field_ty(subpat.span, field, args);
1846 self.check_pat(subpat, field_ty, pat_info);
1847
1848 self.tcx.check_stability(
1849 variant.fields[FieldIdx::from_usize(i)].did,
1850 Some(subpat.hir_id),
1851 subpat.span,
1852 None,
1853 );
1854 }
1855 if let Err(e) = had_err {
1856 on_error(e);
1857 return Ty::new_error(tcx, e);
1858 }
1859 } else {
1860 let e = self.emit_err_pat_wrong_number_of_fields(
1861 pat.span,
1862 res,
1863 qpath,
1864 subpats,
1865 &variant.fields.raw,
1866 expected,
1867 had_err,
1868 );
1869 on_error(e);
1870 return Ty::new_error(tcx, e);
1871 }
1872 pat_ty
1873 }
1874
1875 fn emit_err_pat_wrong_number_of_fields(
1876 &self,
1877 pat_span: Span,
1878 res: Res,
1879 qpath: &hir::QPath<'_>,
1880 subpats: &'tcx [Pat<'tcx>],
1881 fields: &'tcx [ty::FieldDef],
1882 expected: Ty<'tcx>,
1883 had_err: Result<(), ErrorGuaranteed>,
1884 ) -> ErrorGuaranteed {
1885 let subpats_ending = if subpats.len() == 1 { "" } else { "s" }pluralize!(subpats.len());
1886 let fields_ending = if fields.len() == 1 { "" } else { "s" }pluralize!(fields.len());
1887
1888 let subpat_spans = if subpats.is_empty() {
1889 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[pat_span]))vec![pat_span]
1890 } else {
1891 subpats.iter().map(|p| p.span).collect()
1892 };
1893 let last_subpat_span = *subpat_spans.last().unwrap();
1894 let res_span = self.tcx.def_span(res.def_id());
1895 let def_ident_span = self.tcx.def_ident_span(res.def_id()).unwrap_or(res_span);
1896 let field_def_spans = if fields.is_empty() {
1897 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[res_span]))vec![res_span]
1898 } else {
1899 fields.iter().map(|f| f.ident(self.tcx).span).collect()
1900 };
1901 let last_field_def_span = *field_def_spans.last().unwrap();
1902
1903 let mut err = {
self.dcx().struct_span_err(MultiSpan::from_spans(subpat_spans),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern has {0} field{1}, but the corresponding {2} has {3} field{4}",
subpats.len(), subpats_ending, res.descr(), fields.len(),
fields_ending))
})).with_code(E0023)
}struct_span_code_err!(
1904 self.dcx(),
1905 MultiSpan::from_spans(subpat_spans),
1906 E0023,
1907 "this pattern has {} field{}, but the corresponding {} has {} field{}",
1908 subpats.len(),
1909 subpats_ending,
1910 res.descr(),
1911 fields.len(),
1912 fields_ending,
1913 );
1914 err.span_label(
1915 last_subpat_span,
1916 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} field{1}, found {2}",
fields.len(), fields_ending, subpats.len()))
})format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len()),
1917 );
1918 if self.tcx.sess.source_map().is_multiline(qpath.span().between(last_subpat_span)) {
1919 err.span_label(qpath.span(), "");
1920 }
1921 if self.tcx.sess.source_map().is_multiline(def_ident_span.between(last_field_def_span)) {
1922 err.span_label(def_ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} defined here", res.descr()))
})format!("{} defined here", res.descr()));
1923 }
1924 for span in &field_def_spans[..field_def_spans.len() - 1] {
1925 err.span_label(*span, "");
1926 }
1927 err.span_label(
1928 last_field_def_span,
1929 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} has {1} field{2}", res.descr(),
fields.len(), fields_ending))
})format!("{} has {} field{}", res.descr(), fields.len(), fields_ending),
1930 );
1931
1932 let missing_parentheses = match (expected.kind(), fields, had_err) {
1937 (ty::Adt(_, args), [field], Ok(())) => {
1941 let field_ty = self.field_ty(pat_span, field, args);
1942 match field_ty.kind() {
1943 ty::Tuple(fields) => fields.len() == subpats.len(),
1944 _ => false,
1945 }
1946 }
1947 _ => false,
1948 };
1949 if missing_parentheses {
1950 let (left, right) = match subpats {
1951 [] => (qpath.span().shrink_to_hi(), pat_span),
1960 [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
1969 };
1970 err.multipart_suggestion(
1971 "missing parentheses",
1972 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())]))vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())],
1973 Applicability::MachineApplicable,
1974 );
1975 } else if fields.len() > subpats.len() && pat_span != DUMMY_SP {
1976 let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi();
1977 let all_fields_span = match subpats {
1978 [] => after_fields_span,
1979 [field] => field.span,
1980 [first, .., last] => first.span.to(last.span),
1981 };
1982
1983 let all_wildcards = subpats.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
PatKind::Wild => true,
_ => false,
}matches!(pat.kind, PatKind::Wild));
1985 let first_tail_wildcard =
1986 subpats.iter().enumerate().fold(None, |acc, (pos, pat)| match (acc, &pat.kind) {
1987 (None, PatKind::Wild) => Some(pos),
1988 (Some(_), PatKind::Wild) => acc,
1989 _ => None,
1990 });
1991 let tail_span = match first_tail_wildcard {
1992 None => after_fields_span,
1993 Some(0) => subpats[0].span.to(after_fields_span),
1994 Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span),
1995 };
1996
1997 let mut wildcard_sugg = ::alloc::vec::from_elem("_", fields.len() - subpats.len())vec!["_"; fields.len() - subpats.len()].join(", ");
1999 if !subpats.is_empty() {
2000 wildcard_sugg = String::from(", ") + &wildcard_sugg;
2001 }
2002
2003 err.span_suggestion_verbose(
2004 after_fields_span,
2005 "use `_` to explicitly ignore each field",
2006 wildcard_sugg,
2007 Applicability::MaybeIncorrect,
2008 );
2009
2010 if fields.len() - subpats.len() > 1 || all_wildcards {
2013 if subpats.is_empty() || all_wildcards {
2014 err.span_suggestion_verbose(
2015 all_fields_span,
2016 "use `..` to ignore all fields",
2017 "..",
2018 Applicability::MaybeIncorrect,
2019 );
2020 } else {
2021 err.span_suggestion_verbose(
2022 tail_span,
2023 "use `..` to ignore the rest of the fields",
2024 ", ..",
2025 Applicability::MaybeIncorrect,
2026 );
2027 }
2028 }
2029 }
2030
2031 err.emit()
2032 }
2033
2034 fn check_pat_tuple(
2035 &self,
2036 span: Span,
2037 elements: &'tcx [Pat<'tcx>],
2038 ddpos: hir::DotDotPos,
2039 expected: Ty<'tcx>,
2040 pat_info: PatInfo<'tcx>,
2041 ) -> Ty<'tcx> {
2042 let tcx = self.tcx;
2043 let mut expected_len = elements.len();
2044 if ddpos.as_opt_usize().is_some() {
2045 if let ty::Tuple(tys) = self.structurally_resolve_type(span, expected).kind() {
2047 expected_len = tys.len();
2048 }
2049 }
2050 let max_len = cmp::max(expected_len, elements.len());
2051
2052 let element_tys_iter = (0..max_len).map(|_| self.next_ty_var(span));
2053 let element_tys = tcx.mk_type_list_from_iter(element_tys_iter);
2054 let pat_ty = Ty::new_tup(tcx, element_tys);
2055 if let Err(reported) = self.demand_eqtype_pat(span, expected, pat_ty, &pat_info.top_info) {
2056 for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
2059 self.check_pat(elem, Ty::new_error(tcx, reported), pat_info);
2060 }
2061 Ty::new_error(tcx, reported)
2062 } else {
2063 for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
2064 self.check_pat(elem, element_tys[i], pat_info);
2065 }
2066 pat_ty
2067 }
2068 }
2069
2070 fn check_struct_pat_fields(
2071 &self,
2072 adt_ty: Ty<'tcx>,
2073 pat: &'tcx Pat<'tcx>,
2074 variant: &'tcx ty::VariantDef,
2075 fields: &'tcx [hir::PatField<'tcx>],
2076 has_rest_pat: bool,
2077 pat_info: PatInfo<'tcx>,
2078 ) -> Result<(), ErrorGuaranteed> {
2079 let tcx = self.tcx;
2080
2081 let ty::Adt(adt, args) = adt_ty.kind() else {
2082 ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("struct pattern is not an ADT"));span_bug!(pat.span, "struct pattern is not an ADT");
2083 };
2084
2085 let field_map = variant
2087 .fields
2088 .iter_enumerated()
2089 .map(|(i, field)| (field.ident(self.tcx).normalize_to_macros_2_0(), (i, field)))
2090 .collect::<FxHashMap<_, _>>();
2091
2092 let mut used_fields = FxHashMap::default();
2094 let mut result = Ok(());
2095
2096 let mut inexistent_fields = ::alloc::vec::Vec::new()vec![];
2097 for field in fields {
2099 let span = field.span;
2100 let ident = tcx.adjust_ident(field.ident, variant.def_id);
2101 let field_ty = match used_fields.entry(ident) {
2102 Occupied(occupied) => {
2103 let guar = self.error_field_already_bound(span, field.ident, *occupied.get());
2104 result = Err(guar);
2105 Ty::new_error(tcx, guar)
2106 }
2107 Vacant(vacant) => {
2108 vacant.insert(span);
2109 field_map
2110 .get(&ident)
2111 .map(|(i, f)| {
2112 self.write_field_index(field.hir_id, *i);
2113 self.tcx.check_stability(f.did, Some(field.hir_id), span, None);
2114 self.field_ty(span, f, args)
2115 })
2116 .unwrap_or_else(|| {
2117 inexistent_fields.push(field);
2118 Ty::new_misc_error(tcx)
2119 })
2120 }
2121 };
2122
2123 self.check_pat(field.pat, field_ty, pat_info);
2124 }
2125
2126 let mut unmentioned_fields = variant
2127 .fields
2128 .iter()
2129 .map(|field| (field, field.ident(self.tcx).normalize_to_macros_2_0()))
2130 .filter(|(_, ident)| !used_fields.contains_key(ident))
2131 .collect::<Vec<_>>();
2132
2133 let inexistent_fields_err = if !inexistent_fields.is_empty()
2134 && !inexistent_fields.iter().any(|field| field.ident.name == kw::Underscore)
2135 {
2136 variant.has_errors()?;
2138 Some(self.error_inexistent_fields(
2139 adt.variant_descr(),
2140 &inexistent_fields,
2141 &mut unmentioned_fields,
2142 pat,
2143 variant,
2144 args,
2145 ))
2146 } else {
2147 None
2148 };
2149
2150 let non_exhaustive = variant.field_list_has_applicable_non_exhaustive();
2152 if non_exhaustive && !has_rest_pat {
2153 self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
2154 }
2155
2156 let mut unmentioned_err = None;
2157 if adt.is_union() {
2159 if fields.len() != 1 {
2160 self.dcx().emit_err(diagnostics::UnionPatMultipleFields { span: pat.span });
2161 }
2162 if has_rest_pat {
2163 self.dcx().emit_err(diagnostics::UnionPatDotDot { span: pat.span });
2164 }
2165 } else if !unmentioned_fields.is_empty() {
2166 let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
2167 .iter()
2168 .copied()
2169 .filter(|(field, _)| self.is_field_suggestable(field, pat.hir_id, pat.span))
2170 .collect();
2171
2172 if !has_rest_pat {
2173 if accessible_unmentioned_fields.is_empty() {
2174 unmentioned_err = Some(self.error_no_accessible_fields(pat, fields));
2175 } else {
2176 unmentioned_err = Some(self.error_unmentioned_fields(
2177 pat,
2178 &accessible_unmentioned_fields,
2179 accessible_unmentioned_fields.len() != unmentioned_fields.len(),
2180 fields,
2181 ));
2182 }
2183 } else if non_exhaustive && !accessible_unmentioned_fields.is_empty() {
2184 self.lint_non_exhaustive_omitted_patterns(
2185 pat,
2186 &accessible_unmentioned_fields,
2187 adt_ty,
2188 )
2189 }
2190 }
2191 match (inexistent_fields_err, unmentioned_err) {
2192 (Some(i), Some(u)) => {
2193 if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2194 i.delay_as_bug();
2197 u.delay_as_bug();
2198 Err(e)
2199 } else {
2200 i.emit();
2201 Err(u.emit())
2202 }
2203 }
2204 (None, Some(u)) => {
2205 if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2206 u.delay_as_bug();
2207 Err(e)
2208 } else {
2209 Err(u.emit())
2210 }
2211 }
2212 (Some(err), None) => Err(err.emit()),
2213 (None, None) => {
2214 self.error_tuple_variant_index_shorthand(variant, pat, fields)?;
2215 result
2216 }
2217 }
2218 }
2219
2220 fn error_tuple_variant_index_shorthand(
2221 &self,
2222 variant: &VariantDef,
2223 pat: &'_ Pat<'_>,
2224 fields: &[hir::PatField<'_>],
2225 ) -> Result<(), ErrorGuaranteed> {
2226 if let (Some(CtorKind::Fn), PatKind::Struct(qpath, field_patterns, ..)) =
2230 (variant.ctor_kind(), &pat.kind)
2231 {
2232 let has_shorthand_field_name = field_patterns.iter().any(|field| field.is_shorthand);
2233 if has_shorthand_field_name {
2234 let path = rustc_hir_pretty::qpath_to_string(self, qpath);
2235 let mut err = {
self.dcx().struct_span_err(pat.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("tuple variant `{0}` written as struct variant",
path))
})).with_code(E0769)
}struct_span_code_err!(
2236 self.dcx(),
2237 pat.span,
2238 E0769,
2239 "tuple variant `{path}` written as struct variant",
2240 );
2241 err.span_suggestion_verbose(
2242 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2243 "use the tuple variant pattern syntax instead",
2244 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})",
self.get_suggested_tuple_struct_pattern(fields, variant)))
})format!("({})", self.get_suggested_tuple_struct_pattern(fields, variant)),
2245 Applicability::MaybeIncorrect,
2246 );
2247 return Err(err.emit());
2248 }
2249 }
2250 Ok(())
2251 }
2252
2253 fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
2254 let sess = self.tcx.sess;
2255 let sm = sess.source_map();
2256 let sp_brace = sm.end_point(pat.span);
2257 let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
2258 let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
2259
2260 {
self.dcx().struct_span_err(pat.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`..` required with {0} marked as non-exhaustive",
descr))
})).with_code(E0638)
}struct_span_code_err!(
2261 self.dcx(),
2262 pat.span,
2263 E0638,
2264 "`..` required with {descr} marked as non-exhaustive",
2265 )
2266 .with_span_suggestion_verbose(
2267 sp_comma,
2268 "add `..` at the end of the field list to ignore all other fields",
2269 sugg,
2270 Applicability::MachineApplicable,
2271 )
2272 .emit();
2273 }
2274
2275 fn error_field_already_bound(
2276 &self,
2277 span: Span,
2278 ident: Ident,
2279 other_field: Span,
2280 ) -> ErrorGuaranteed {
2281 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}` bound multiple times in the pattern",
ident))
})).with_code(E0025)
}struct_span_code_err!(
2282 self.dcx(),
2283 span,
2284 E0025,
2285 "field `{}` bound multiple times in the pattern",
2286 ident
2287 )
2288 .with_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple uses of `{0}` in pattern",
ident))
})format!("multiple uses of `{ident}` in pattern"))
2289 .with_span_label(other_field, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("first use of `{0}`", ident))
})format!("first use of `{ident}`"))
2290 .emit()
2291 }
2292
2293 fn error_inexistent_fields(
2294 &self,
2295 kind_name: &str,
2296 inexistent_fields: &[&hir::PatField<'tcx>],
2297 unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>,
2298 pat: &'tcx Pat<'tcx>,
2299 variant: &ty::VariantDef,
2300 args: ty::GenericArgsRef<'tcx>,
2301 ) -> Diag<'a> {
2302 let tcx = self.tcx;
2303 let (field_names, t, plural) = if let [field] = inexistent_fields {
2304 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a field named `{0}`", field.ident))
})format!("a field named `{}`", field.ident), "this", "")
2305 } else {
2306 (
2307 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields named {0}",
inexistent_fields.iter().map(|field|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", field.ident))
})).collect::<Vec<String>>().join(", ")))
})format!(
2308 "fields named {}",
2309 inexistent_fields
2310 .iter()
2311 .map(|field| format!("`{}`", field.ident))
2312 .collect::<Vec<String>>()
2313 .join(", ")
2314 ),
2315 "these",
2316 "s",
2317 )
2318 };
2319 let spans = inexistent_fields.iter().map(|field| field.ident.span).collect::<Vec<_>>();
2320 let mut err = {
self.dcx().struct_span_err(spans,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` does not have {2}",
kind_name, tcx.def_path_str(variant.def_id), field_names))
})).with_code(E0026)
}struct_span_code_err!(
2321 self.dcx(),
2322 spans,
2323 E0026,
2324 "{} `{}` does not have {}",
2325 kind_name,
2326 tcx.def_path_str(variant.def_id),
2327 field_names
2328 );
2329 if let Some(pat_field) = inexistent_fields.last() {
2330 err.span_label(
2331 pat_field.ident.span,
2332 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` does not have {2} field{3}",
kind_name, tcx.def_path_str(variant.def_id), t, plural))
})format!(
2333 "{} `{}` does not have {} field{}",
2334 kind_name,
2335 tcx.def_path_str(variant.def_id),
2336 t,
2337 plural
2338 ),
2339 );
2340
2341 if let [(field_def, field)] = unmentioned_fields.as_slice()
2342 && self.is_field_suggestable(field_def, pat.hir_id, pat.span)
2343 {
2344 let suggested_name =
2345 find_best_match_for_name(&[field.name], pat_field.ident.name, None);
2346 if let Some(suggested_name) = suggested_name {
2347 err.span_suggestion_verbose(
2348 pat_field.ident.span,
2349 "a field with a similar name exists",
2350 suggested_name,
2351 Applicability::MaybeIncorrect,
2352 );
2353
2354 if suggested_name.to_ident_string().parse::<usize>().is_err() {
2360 unmentioned_fields.retain(|&(_, x)| x.name != suggested_name);
2362 }
2363 } else if inexistent_fields.len() == 1 {
2364 match pat_field.pat.kind {
2365 PatKind::Expr(_)
2366 if !self.may_coerce(
2367 self.typeck_results.borrow().node_type(pat_field.pat.hir_id),
2368 self.field_ty(field.span, field_def, args),
2369 ) => {}
2370 _ => {
2371 err.span_suggestion_short(
2372 pat_field.ident.span,
2373 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has a field named `{1}`",
tcx.def_path_str(variant.def_id), field.name))
})format!(
2374 "`{}` has a field named `{}`",
2375 tcx.def_path_str(variant.def_id),
2376 field.name,
2377 ),
2378 field.name,
2379 Applicability::MaybeIncorrect,
2380 );
2381 }
2382 }
2383 }
2384 }
2385 }
2386 if tcx.sess.teach(err.code.unwrap()) {
2387 err.note(
2388 "This error indicates that a struct pattern attempted to \
2389 extract a nonexistent field from a struct. Struct fields \
2390 are identified by the name used before the colon : so struct \
2391 patterns should resemble the declaration of the struct type \
2392 being matched.\n\n\
2393 If you are using shorthand field patterns but want to refer \
2394 to the struct field by a different name, you should rename \
2395 it explicitly.",
2396 );
2397 }
2398 err
2399 }
2400
2401 fn error_tuple_variant_as_struct_pat(
2402 &self,
2403 pat: &Pat<'_>,
2404 fields: &'tcx [hir::PatField<'tcx>],
2405 variant: &ty::VariantDef,
2406 ) -> Result<(), ErrorGuaranteed> {
2407 if let (Some(CtorKind::Fn), PatKind::Struct(qpath, pattern_fields, ..)) =
2408 (variant.ctor_kind(), &pat.kind)
2409 {
2410 let is_tuple_struct_match = !pattern_fields.is_empty()
2411 && pattern_fields.iter().map(|field| field.ident.name.as_str()).all(is_number);
2412 if is_tuple_struct_match {
2413 return Ok(());
2414 }
2415
2416 variant.has_errors()?;
2418
2419 let path = rustc_hir_pretty::qpath_to_string(self, qpath);
2420 let mut err = {
self.dcx().struct_span_err(pat.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("tuple variant `{0}` written as struct variant",
path))
})).with_code(E0769)
}struct_span_code_err!(
2421 self.dcx(),
2422 pat.span,
2423 E0769,
2424 "tuple variant `{}` written as struct variant",
2425 path
2426 );
2427 let (sugg, appl) = if fields.len() == variant.fields.len() {
2428 (
2429 self.get_suggested_tuple_struct_pattern(fields, variant),
2430 Applicability::MachineApplicable,
2431 )
2432 } else {
2433 (
2434 variant.fields.iter().map(|_| "_").collect::<Vec<&str>>().join(", "),
2435 Applicability::MaybeIncorrect,
2436 )
2437 };
2438 err.span_suggestion_verbose(
2439 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2440 "use the tuple variant pattern syntax instead",
2441 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", sugg))
})format!("({sugg})"),
2442 appl,
2443 );
2444 return Err(err.emit());
2445 }
2446 Ok(())
2447 }
2448
2449 fn get_suggested_tuple_struct_pattern(
2450 &self,
2451 fields: &[hir::PatField<'_>],
2452 variant: &VariantDef,
2453 ) -> String {
2454 let variant_field_idents =
2455 variant.fields.iter().map(|f| f.ident(self.tcx)).collect::<Vec<Ident>>();
2456 fields
2457 .iter()
2458 .map(|field| {
2459 match self.tcx.sess.source_map().span_to_snippet(field.pat.span) {
2460 Ok(f) => {
2461 if variant_field_idents.contains(&field.ident) {
2464 String::from("_")
2465 } else {
2466 f
2467 }
2468 }
2469 Err(_) => rustc_hir_pretty::pat_to_string(self, field.pat),
2470 }
2471 })
2472 .collect::<Vec<String>>()
2473 .join(", ")
2474 }
2475
2476 fn error_no_accessible_fields(
2492 &self,
2493 pat: &Pat<'_>,
2494 fields: &'tcx [hir::PatField<'tcx>],
2495 ) -> Diag<'a> {
2496 let mut err = self
2497 .dcx()
2498 .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
2499
2500 if let Some(field) = fields.last() {
2501 let tail_span = field.span.shrink_to_hi().to(pat.span.shrink_to_hi());
2502 let comma_hi_offset =
2503 self.tcx.sess.source_map().span_to_snippet(tail_span).ok().and_then(|snippet| {
2504 let trimmed = snippet.trim_start();
2505 trimmed.starts_with(',').then(|| (snippet.len() - trimmed.len() + 1) as u32)
2506 });
2507 err.span_suggestion_verbose(
2508 if let Some(comma_hi_offset) = comma_hi_offset {
2509 tail_span.with_hi(tail_span.lo() + BytePos(comma_hi_offset)).shrink_to_hi()
2510 } else {
2511 field.span.shrink_to_hi()
2512 },
2513 "ignore the inaccessible and unused fields",
2514 if comma_hi_offset.is_some() { " .." } else { ", .." },
2515 Applicability::MachineApplicable,
2516 );
2517 } else {
2518 let qpath_span = if let PatKind::Struct(qpath, ..) = &pat.kind {
2519 qpath.span()
2520 } else {
2521 ::rustc_middle::util::bug::bug_fmt(format_args!("`error_no_accessible_fields` called on non-struct pattern"));bug!("`error_no_accessible_fields` called on non-struct pattern");
2522 };
2523
2524 let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi());
2526 err.span_suggestion_verbose(
2527 span,
2528 "ignore the inaccessible and unused fields",
2529 " { .. }",
2530 Applicability::MachineApplicable,
2531 );
2532 }
2533 err
2534 }
2535
2536 fn lint_non_exhaustive_omitted_patterns(
2541 &self,
2542 pat: &Pat<'_>,
2543 unmentioned_fields: &[(&ty::FieldDef, Ident)],
2544 ty: Ty<'tcx>,
2545 ) {
2546 struct FieldsNotListed<'a, 'b, 'tcx> {
2547 pat_span: Span,
2548 unmentioned_fields: &'a [(&'b ty::FieldDef, Ident)],
2549 joined_patterns: String,
2550 ty: Ty<'tcx>,
2551 }
2552
2553 impl<'a, 'b, 'c, 'tcx> Diagnostic<'a, ()> for FieldsNotListed<'b, 'c, 'tcx> {
2554 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
2555 let Self { pat_span, unmentioned_fields, joined_patterns, ty } = self;
2556 Diag::new(dcx, level, "some fields are not explicitly listed")
2557 .with_span_label(pat_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field{0} {1} not listed",
if unmentioned_fields.len() == 1 { "" } else { "s" },
joined_patterns))
})format!("field{} {} not listed", rustc_errors::pluralize!(unmentioned_fields.len()), joined_patterns))
2558 .with_help(
2559 "ensure that all fields are mentioned explicitly by adding the suggested fields",
2560 )
2561 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the pattern is of type `{0}` and the `non_exhaustive_omitted_patterns` attribute was found",
ty))
})format!(
2562 "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
2563 ))
2564 }
2565 }
2566
2567 fn joined_uncovered_patterns(witnesses: &[&Ident]) -> String {
2568 const LIMIT: usize = 3;
2569 match witnesses {
2570 [] => {
2571 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("expected an uncovered pattern, otherwise why are we emitting an error?")));
}unreachable!(
2572 "expected an uncovered pattern, otherwise why are we emitting an error?"
2573 )
2574 }
2575 [witness] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", witness))
})format!("`{witness}`"),
2576 [head @ .., tail] if head.len() < LIMIT => {
2577 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2578 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`",
head.join("`, `"), tail))
})format!("`{}` and `{}`", head.join("`, `"), tail)
2579 }
2580 _ => {
2581 let (head, tail) = witnesses.split_at(LIMIT);
2582 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2583 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and {1} more",
head.join("`, `"), tail.len()))
})format!("`{}` and {} more", head.join("`, `"), tail.len())
2584 }
2585 }
2586 }
2587 let joined_patterns = joined_uncovered_patterns(
2588 &unmentioned_fields.iter().map(|(_, i)| i).collect::<Vec<_>>(),
2589 );
2590
2591 self.tcx.emit_node_span_lint(
2592 NON_EXHAUSTIVE_OMITTED_PATTERNS,
2593 pat.hir_id,
2594 pat.span,
2595 FieldsNotListed { pat_span: pat.span, unmentioned_fields, joined_patterns, ty },
2596 );
2597 }
2598
2599 fn error_unmentioned_fields(
2609 &self,
2610 pat: &Pat<'_>,
2611 unmentioned_fields: &[(&ty::FieldDef, Ident)],
2612 have_inaccessible_fields: bool,
2613 fields: &'tcx [hir::PatField<'tcx>],
2614 ) -> Diag<'a> {
2615 let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
2616 let field_names = if let [(_, field)] = unmentioned_fields {
2617 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}`{1}", field,
inaccessible))
})format!("field `{field}`{inaccessible}")
2618 } else {
2619 let fields = unmentioned_fields
2620 .iter()
2621 .map(|(_, name)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"))
2622 .collect::<Vec<String>>()
2623 .join(", ");
2624 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields {0}{1}", fields,
inaccessible))
})format!("fields {fields}{inaccessible}")
2625 };
2626 let mut err = {
self.dcx().struct_span_err(pat.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pattern does not mention {0}",
field_names))
})).with_code(E0027)
}struct_span_code_err!(
2627 self.dcx(),
2628 pat.span,
2629 E0027,
2630 "pattern does not mention {}",
2631 field_names
2632 );
2633 err.span_label(pat.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing {0}", field_names))
})format!("missing {field_names}"));
2634 let len = unmentioned_fields.len();
2635 let (prefix, postfix, sp) = match fields {
2636 [] => match &pat.kind {
2637 PatKind::Struct(path, [], None) => {
2638 (" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi()))
2639 }
2640 _ => return err,
2641 },
2642 [.., field] => {
2643 let tail = field.span.shrink_to_hi().with_hi(pat.span.hi());
2646 match &pat.kind {
2647 PatKind::Struct(..) => (", ", " }", tail),
2648 _ => return err,
2649 }
2650 }
2651 };
2652 err.span_suggestion(
2653 sp,
2654 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("include the missing field{0} in the pattern{1}",
if len == 1 { "" } else { "s" },
if have_inaccessible_fields {
" and ignore the inaccessible fields"
} else { "" }))
})format!(
2655 "include the missing field{} in the pattern{}",
2656 pluralize!(len),
2657 if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
2658 ),
2659 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}{3}", prefix,
unmentioned_fields.iter().map(|(_, name)|
{
let field_name = name.to_string();
if is_number(&field_name) {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: _", field_name))
})
} else { field_name }
}).collect::<Vec<_>>().join(", "),
if have_inaccessible_fields { ", .." } else { "" }, postfix))
})format!(
2660 "{}{}{}{}",
2661 prefix,
2662 unmentioned_fields
2663 .iter()
2664 .map(|(_, name)| {
2665 let field_name = name.to_string();
2666 if is_number(&field_name) { format!("{field_name}: _") } else { field_name }
2667 })
2668 .collect::<Vec<_>>()
2669 .join(", "),
2670 if have_inaccessible_fields { ", .." } else { "" },
2671 postfix,
2672 ),
2673 Applicability::MachineApplicable,
2674 );
2675 err.span_suggestion(
2676 sp,
2677 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you don\'t care about {0} missing field{1}, you can explicitly ignore {2}",
if len == 1 { "this" } else { "these" },
if len == 1 { "" } else { "s" },
if len == 1 { "it" } else { "them" }))
})format!(
2678 "if you don't care about {these} missing field{s}, you can explicitly ignore {them}",
2679 these = pluralize!("this", len),
2680 s = pluralize!(len),
2681 them = if len == 1 { "it" } else { "them" },
2682 ),
2683 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}{3}", prefix,
unmentioned_fields.iter().map(|(_, name)|
{
let field_name = name.to_string();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: _", field_name))
})
}).collect::<Vec<_>>().join(", "),
if have_inaccessible_fields { ", .." } else { "" }, postfix))
})format!(
2684 "{}{}{}{}",
2685 prefix,
2686 unmentioned_fields
2687 .iter()
2688 .map(|(_, name)| {
2689 let field_name = name.to_string();
2690 format!("{field_name}: _")
2691 })
2692 .collect::<Vec<_>>()
2693 .join(", "),
2694 if have_inaccessible_fields { ", .." } else { "" },
2695 postfix,
2696 ),
2697 Applicability::MachineApplicable,
2698 );
2699 err.span_suggestion(
2700 sp,
2701 "or always ignore missing fields here",
2702 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}..{1}", prefix, postfix))
})format!("{prefix}..{postfix}"),
2703 Applicability::MachineApplicable,
2704 );
2705 err
2706 }
2707
2708 fn check_pat_deref(
2709 &self,
2710 span: Span,
2711 inner: &'tcx Pat<'tcx>,
2712 expected: Ty<'tcx>,
2713 pat_info: PatInfo<'tcx>,
2714 ) -> Ty<'tcx> {
2715 let target_ty = self.deref_pat_target(span, expected);
2716 self.check_pat(inner, target_ty, pat_info);
2717 self.register_deref_mut_bounds_if_needed(span, inner, [expected]);
2718 expected
2719 }
2720
2721 fn deref_pat_target(&self, span: Span, source_ty: Ty<'tcx>) -> Ty<'tcx> {
2722 let tcx = self.tcx;
2724 self.register_bound(
2725 source_ty,
2726 tcx.require_lang_item(LangItem::DerefPure, span),
2727 self.misc(span),
2728 );
2729 let target_ty = Ty::new_projection(
2731 tcx,
2732 ty::IsRigid::No,
2733 tcx.require_lang_item(LangItem::DerefTarget, span),
2734 [source_ty],
2735 );
2736 let target_ty = self.normalize(span, Unnormalized::new_wip(target_ty));
2737 self.resolve_vars_with_obligations(target_ty)
2738 }
2739
2740 fn register_deref_mut_bounds_if_needed(
2745 &self,
2746 span: Span,
2747 inner: &'tcx Pat<'tcx>,
2748 derefed_tys: impl IntoIterator<Item = Ty<'tcx>>,
2749 ) {
2750 if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) {
2751 for mutably_derefed_ty in derefed_tys {
2752 self.register_bound(
2753 mutably_derefed_ty,
2754 self.tcx.require_lang_item(LangItem::DerefMut, span),
2755 self.misc(span),
2756 );
2757 }
2758 }
2759 }
2760
2761 fn check_pat_ref(
2763 &self,
2764 pat: &'tcx Pat<'tcx>,
2765 inner: &'tcx Pat<'tcx>,
2766 pat_pinned: Pinnedness,
2767 pat_mutbl: Mutability,
2768 mut expected: Ty<'tcx>,
2769 mut pat_info: PatInfo<'tcx>,
2770 ) -> Ty<'tcx> {
2771 let tcx = self.tcx;
2772
2773 let pat_prefix_span =
2774 inner.span.find_ancestor_inside(pat.span).map(|end| pat.span.until(end));
2775
2776 let ref_pat_matches_mut_ref = self.ref_pat_matches_mut_ref();
2777 if ref_pat_matches_mut_ref && pat_mutbl == Mutability::Not {
2778 pat_info.max_ref_mutbl = pat_info.max_ref_mutbl.cap_to_weakly_not(pat_prefix_span);
2783 }
2784
2785 expected = self.resolve_vars_with_obligations(expected);
2786 if let ByRef::Yes(inh_pin, inh_mut) = pat_info.binding_mode
2789 && pat_pinned == inh_pin
2790 {
2791 match self.ref_pat_matches_inherited_ref(pat.span.edition()) {
2792 InheritedRefMatchRule::EatOuter => {
2793 if pat_mutbl > inh_mut {
2795 if true {
if !ref_pat_matches_mut_ref {
::core::panicking::panic("assertion failed: ref_pat_matches_mut_ref")
};
};debug_assert!(ref_pat_matches_mut_ref);
2800 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2801 }
2802
2803 pat_info.binding_mode = ByRef::No;
2804 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2805 self.check_pat(inner, expected, pat_info);
2806 return expected;
2807 }
2808 InheritedRefMatchRule::EatInner => {
2809 if let ty::Ref(_, _, r_mutbl) = *expected.kind()
2810 && pat_mutbl <= r_mutbl
2811 {
2812 if true {
if !ref_pat_matches_mut_ref {
::core::panicking::panic("assertion failed: ref_pat_matches_mut_ref")
};
};debug_assert!(ref_pat_matches_mut_ref);
2819 if true {
if !self.downgrade_mut_inside_shared() {
::core::panicking::panic("assertion failed: self.downgrade_mut_inside_shared()")
};
};debug_assert!(self.downgrade_mut_inside_shared());
2823 let mutbl_cap = cmp::min(r_mutbl, pat_info.max_ref_mutbl.as_mutbl());
2824 pat_info.binding_mode = pat_info.binding_mode.cap_ref_mutability(mutbl_cap);
2825 } else {
2826 if pat_mutbl > inh_mut {
2829 if true {
if !ref_pat_matches_mut_ref {
::core::panicking::panic("assertion failed: ref_pat_matches_mut_ref")
};
};debug_assert!(ref_pat_matches_mut_ref);
2838 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2839 }
2840
2841 pat_info.binding_mode = ByRef::No;
2842 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2843 self.check_pat(inner, expected, pat_info);
2844 return expected;
2845 }
2846 }
2847 InheritedRefMatchRule::EatBoth { consider_inherited_ref: true } => {
2848 pat_info.binding_mode = ByRef::No;
2850
2851 if let ty::Ref(_, inner_ty, _) = *expected.kind() {
2852 if pat_mutbl.is_mut() && inh_mut.is_mut() {
2854 self.check_pat(inner, inner_ty, pat_info);
2861 return expected;
2862 } else {
2863 }
2870 } else {
2871 if pat_mutbl > inh_mut {
2874 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2876 }
2877
2878 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2879 self.check_pat(inner, expected, pat_info);
2880 return expected;
2881 }
2882 }
2883 InheritedRefMatchRule::EatBoth { consider_inherited_ref: false } => {
2884 pat_info.binding_mode = ByRef::No;
2887 self.add_rust_2024_migration_desugared_pat(
2888 pat_info.top_info.hir_id,
2889 pat,
2890 match pat_mutbl {
2891 Mutability::Not => '&', Mutability::Mut => 't', },
2894 inh_mut,
2895 )
2896 }
2897 }
2898 }
2899
2900 let (ref_ty, inner_ty) = match self.check_dereferenceable(pat.span, expected, inner) {
2901 Ok(()) => {
2902 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:2908",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(2908u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_pat_ref: expected={0:?}",
expected) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_pat_ref: expected={:?}", expected);
2909 match expected.maybe_pinned_ref() {
2910 Some((r_ty, r_pinned, r_mutbl, _))
2911 if ((ref_pat_matches_mut_ref && r_mutbl >= pat_mutbl)
2912 || r_mutbl == pat_mutbl)
2913 && pat_pinned == r_pinned =>
2914 {
2915 if r_mutbl == Mutability::Not {
2916 pat_info.max_ref_mutbl = MutblCap::Not;
2917 }
2918 if r_pinned == Pinnedness::Pinned {
2919 pat_info.max_pinnedness = PinnednessCap::Pinned;
2920 }
2921
2922 (expected, r_ty)
2923 }
2924 _ => {
2925 let inner_ty = self.next_ty_var(inner.span);
2926 let ref_ty = self.new_ref_ty(pat.span, pat_pinned, pat_mutbl, inner_ty);
2927 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:2927",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(2927u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_pat_ref: demanding {0:?} = {1:?}",
expected, ref_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_pat_ref: demanding {:?} = {:?}", expected, ref_ty);
2928 let err = self.demand_eqtype_pat_diag(
2929 pat.span,
2930 expected,
2931 ref_ty,
2932 &pat_info.top_info,
2933 );
2934
2935 if let Err(mut err) = err {
2938 self.borrow_pat_suggestion(&mut err, pat);
2939 err.emit();
2940 }
2941 (ref_ty, inner_ty)
2942 }
2943 }
2944 }
2945 Err(guar) => {
2946 let err = Ty::new_error(tcx, guar);
2947 (err, err)
2948 }
2949 };
2950
2951 self.check_pat(inner, inner_ty, pat_info);
2952 ref_ty
2953 }
2954
2955 fn new_ref_ty(
2957 &self,
2958 span: Span,
2959 pinnedness: Pinnedness,
2960 mutbl: Mutability,
2961 ty: Ty<'tcx>,
2962 ) -> Ty<'tcx> {
2963 let region = self.next_region_var(RegionVariableOrigin::PatternRegion(span));
2964 let ref_ty = Ty::new_ref(self.tcx, region, ty, mutbl);
2965 if pinnedness.is_pinned() {
2966 return self.new_pinned_ty(span, ref_ty);
2967 }
2968 ref_ty
2969 }
2970
2971 fn new_pinned_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
2973 Ty::new_adt(
2974 self.tcx,
2975 self.tcx.adt_def(self.tcx.require_lang_item(LangItem::Pin, span)),
2976 self.tcx.mk_args(&[ty.into()]),
2977 )
2978 }
2979
2980 fn error_inherited_ref_mutability_mismatch(
2981 &self,
2982 pat: &'tcx Pat<'tcx>,
2983 pat_prefix_span: Option<Span>,
2984 ) -> ErrorGuaranteed {
2985 let err_msg = "mismatched types";
2986 let err = if let Some(span) = pat_prefix_span {
2987 let mut err = self.dcx().struct_span_err(span, err_msg);
2988 err.code(E0308);
2989 err.note("cannot match inherited `&` with `&mut` pattern");
2990 err.span_suggestion_verbose(
2991 span,
2992 "replace this `&mut` pattern with `&`",
2993 "&",
2994 Applicability::MachineApplicable,
2995 );
2996 err
2997 } else {
2998 self.dcx().struct_span_err(pat.span, err_msg)
2999 };
3000 err.emit()
3001 }
3002
3003 fn try_resolve_slice_ty_to_array_ty(
3004 &self,
3005 before: &'tcx [Pat<'tcx>],
3006 slice: Option<&'tcx Pat<'tcx>>,
3007 span: Span,
3008 ) -> Option<Ty<'tcx>> {
3009 if slice.is_some() {
3010 return None;
3011 }
3012
3013 let tcx = self.tcx;
3014 let len = before.len();
3015 let inner_ty = self.next_ty_var(span);
3016
3017 Some(Ty::new_array(tcx, inner_ty, len.try_into().unwrap()))
3018 }
3019
3020 fn pat_is_irrefutable(&self, decl_origin: Option<DeclOrigin<'_>>) -> bool {
3051 match decl_origin {
3052 Some(DeclOrigin::LocalDecl { els: None }) => true,
3053 Some(DeclOrigin::LocalDecl { els: Some(_) } | DeclOrigin::LetExpr) | None => false,
3054 }
3055 }
3056
3057 fn check_pat_slice(
3068 &self,
3069 span: Span,
3070 before: &'tcx [Pat<'tcx>],
3071 slice: Option<&'tcx Pat<'tcx>>,
3072 after: &'tcx [Pat<'tcx>],
3073 expected: Ty<'tcx>,
3074 pat_info: PatInfo<'tcx>,
3075 ) -> Ty<'tcx> {
3076 let expected = self.resolve_vars_with_obligations(expected);
3077
3078 if self.pat_is_irrefutable(pat_info.decl_origin) && expected.is_ty_var() {
3081 if let Some(resolved_arr_ty) =
3082 self.try_resolve_slice_ty_to_array_ty(before, slice, span)
3083 {
3084 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:3084",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(3084u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("resolved_arr_ty")
}> =
::tracing::__macro_support::FieldName::new("resolved_arr_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&resolved_arr_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?resolved_arr_ty);
3085 let _ = self.demand_eqtype(span, expected, resolved_arr_ty);
3086 }
3087 }
3088
3089 let expected = self.structurally_resolve_type(span, expected);
3090 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:3090",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(3090u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?expected);
3091
3092 let (element_ty, opt_slice_ty, inferred) = match *expected.kind() {
3093 ty::Array(element_ty, len) => {
3095 let min = before.len() as u64 + after.len() as u64;
3096 let (opt_slice_ty, expected) =
3097 self.check_array_pat_len(span, element_ty, expected, slice, len, min);
3098 if !(opt_slice_ty.is_some() || slice.is_none()) {
::core::panicking::panic("assertion failed: opt_slice_ty.is_some() || slice.is_none()")
};assert!(opt_slice_ty.is_some() || slice.is_none());
3101 (element_ty, opt_slice_ty, expected)
3102 }
3103 ty::Slice(element_ty) => (element_ty, Some(expected), expected),
3104 _ => {
3106 let guar = expected.error_reported().err().unwrap_or_else(|| {
3107 self.error_expected_array_or_slice(span, expected, pat_info)
3108 });
3109 let err = Ty::new_error(self.tcx, guar);
3110 (err, Some(err), err)
3111 }
3112 };
3113
3114 for elt in before {
3116 self.check_pat(elt, element_ty, pat_info);
3117 }
3118 if let Some(slice) = slice {
3120 self.check_pat(slice, opt_slice_ty.unwrap(), pat_info);
3121 }
3122 for elt in after {
3124 self.check_pat(elt, element_ty, pat_info);
3125 }
3126 inferred
3127 }
3128
3129 fn check_array_pat_len(
3134 &self,
3135 span: Span,
3136 element_ty: Ty<'tcx>,
3137 arr_ty: Ty<'tcx>,
3138 slice: Option<&'tcx Pat<'tcx>>,
3139 len: ty::Const<'tcx>,
3140 min_len: u64,
3141 ) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
3142 let len = self.try_structurally_resolve_const(span, len).try_to_target_usize(self.tcx);
3143
3144 let guar = if let Some(len) = len {
3145 if slice.is_none() {
3147 if min_len == len {
3151 return (None, arr_ty);
3152 }
3153
3154 self.error_scrutinee_inconsistent_length(span, min_len, len)
3155 } else if let Some(pat_len) = len.checked_sub(min_len) {
3156 return (Some(Ty::new_array(self.tcx, element_ty, pat_len)), arr_ty);
3159 } else {
3160 self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len)
3163 }
3164 } else if slice.is_none() {
3165 let updated_arr_ty = Ty::new_array(self.tcx, element_ty, min_len);
3168 self.demand_eqtype(span, updated_arr_ty, arr_ty);
3169 return (None, updated_arr_ty);
3170 } else {
3171 self.error_scrutinee_unfixed_length(span)
3175 };
3176
3177 (Some(Ty::new_error(self.tcx, guar)), arr_ty)
3179 }
3180
3181 fn error_scrutinee_inconsistent_length(
3182 &self,
3183 span: Span,
3184 min_len: u64,
3185 size: u64,
3186 ) -> ErrorGuaranteed {
3187 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pattern requires {0} element{1} but array has {2}",
min_len, if min_len == 1 { "" } else { "s" }, size))
})).with_code(E0527)
}struct_span_code_err!(
3188 self.dcx(),
3189 span,
3190 E0527,
3191 "pattern requires {} element{} but array has {}",
3192 min_len,
3193 pluralize!(min_len),
3194 size,
3195 )
3196 .with_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} element{1}", size,
if size == 1 { "" } else { "s" }))
})format!("expected {} element{}", size, pluralize!(size)))
3197 .emit()
3198 }
3199
3200 fn error_scrutinee_with_rest_inconsistent_length(
3201 &self,
3202 span: Span,
3203 min_len: u64,
3204 size: u64,
3205 ) -> ErrorGuaranteed {
3206 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pattern requires at least {0} element{1} but array has {2}",
min_len, if min_len == 1 { "" } else { "s" }, size))
})).with_code(E0528)
}struct_span_code_err!(
3207 self.dcx(),
3208 span,
3209 E0528,
3210 "pattern requires at least {} element{} but array has {}",
3211 min_len,
3212 pluralize!(min_len),
3213 size,
3214 )
3215 .with_span_label(
3216 span,
3217 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pattern cannot match array of {0} element{1}",
size, if size == 1 { "" } else { "s" }))
})format!("pattern cannot match array of {} element{}", size, pluralize!(size),),
3218 )
3219 .emit()
3220 }
3221
3222 fn error_scrutinee_unfixed_length(&self, span: Span) -> ErrorGuaranteed {
3223 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot pattern-match on an array without a fixed length"))
})).with_code(E0730)
}struct_span_code_err!(
3224 self.dcx(),
3225 span,
3226 E0730,
3227 "cannot pattern-match on an array without a fixed length",
3228 )
3229 .emit()
3230 }
3231
3232 fn error_expected_array_or_slice(
3233 &self,
3234 span: Span,
3235 expected_ty: Ty<'tcx>,
3236 pat_info: PatInfo<'tcx>,
3237 ) -> ErrorGuaranteed {
3238 let PatInfo { top_info: ti, current_depth, .. } = pat_info;
3239
3240 let mut slice_pat_semantics = false;
3241 let mut as_deref = None;
3242 let mut slicing = None;
3243 if let ty::Ref(_, ty, _) = expected_ty.kind()
3244 && let ty::Array(..) | ty::Slice(..) = ty.kind()
3245 {
3246 slice_pat_semantics = true;
3247 } else if self
3248 .autoderef(span, expected_ty)
3249 .silence_errors()
3250 .any(|(ty, _)| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Slice(..) | ty::Array(..) => true,
_ => false,
}matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
3251 && let Some(span) = ti.span
3252 && let Some(_) = ti.origin_expr
3253 {
3254 let resolved_ty = self.resolve_vars_if_possible(ti.expected);
3255 let (is_slice_or_array_or_vector, resolved_ty) =
3256 self.is_slice_or_array_or_vector(resolved_ty);
3257 match resolved_ty.kind() {
3258 ty::Adt(adt_def, _)
3259 if self.tcx.is_diagnostic_item(sym::Option, adt_def.did())
3260 || self.tcx.is_diagnostic_item(sym::Result, adt_def.did()) =>
3261 {
3262 as_deref = Some(diagnostics::AsDerefSuggestion { span: span.shrink_to_hi() });
3264 }
3265 _ => (),
3266 }
3267
3268 let is_top_level = current_depth <= 1;
3269 if is_slice_or_array_or_vector && is_top_level {
3270 slicing = Some(diagnostics::SlicingSuggestion { span: span.shrink_to_hi() });
3271 }
3272 }
3273 self.dcx().emit_err(diagnostics::ExpectedArrayOrSlice {
3274 span,
3275 ty: expected_ty,
3276 slice_pat_semantics,
3277 as_deref,
3278 slicing,
3279 })
3280 }
3281
3282 fn is_slice_or_array_or_vector(&self, ty: Ty<'tcx>) -> (bool, Ty<'tcx>) {
3283 match ty.kind() {
3284 ty::Adt(adt_def, _) if self.tcx.is_diagnostic_item(sym::Vec, adt_def.did()) => {
3285 (true, ty)
3286 }
3287 ty::Ref(_, ty, _) => self.is_slice_or_array_or_vector(*ty),
3288 ty::Slice(..) | ty::Array(..) => (true, ty),
3289 _ => (false, ty),
3290 }
3291 }
3292
3293 fn add_rust_2024_migration_desugared_pat(
3296 &self,
3297 pat_id: HirId,
3298 subpat: &'tcx Pat<'tcx>,
3299 final_char: char,
3300 def_br_mutbl: Mutability,
3301 ) {
3302 let from_expansion = subpat.span.from_expansion();
3304 let trimmed_span = if from_expansion {
3305 subpat.span
3307 } else {
3308 let trimmed = self.tcx.sess.source_map().span_through_char(subpat.span, final_char);
3309 trimmed.with_ctxt(subpat.span.ctxt())
3312 };
3313
3314 let mut typeck_results = self.typeck_results.borrow_mut();
3315 let mut table = typeck_results.rust_2024_migration_desugared_pats_mut();
3316 let info = table.entry(pat_id).or_insert_with(|| ty::Rust2024IncompatiblePatInfo {
3321 primary_labels: Vec::new(),
3322 bad_ref_modifiers: false,
3323 bad_mut_modifiers: false,
3324 bad_ref_pats: false,
3325 suggest_eliding_modes: !self.tcx.features().ref_pat_eat_one_layer_2024()
3326 && !self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
3327 });
3328
3329 let pat_kind = if let PatKind::Binding(user_bind_annot, _, _, _) = subpat.kind {
3330 info.suggest_eliding_modes &= #[allow(non_exhaustive_omitted_patterns)] match user_bind_annot {
BindingMode(ByRef::Yes(_, mutbl), Mutability::Not) if
mutbl == def_br_mutbl => true,
_ => false,
}matches!(
3334 user_bind_annot,
3335 BindingMode(ByRef::Yes(_, mutbl), Mutability::Not) if mutbl == def_br_mutbl
3336 );
3337 if user_bind_annot == BindingMode(ByRef::No, Mutability::Mut) {
3338 info.bad_mut_modifiers = true;
3339 "`mut` binding modifier"
3340 } else {
3341 info.bad_ref_modifiers = true;
3342 match user_bind_annot.1 {
3343 Mutability::Not => "explicit `ref` binding modifier",
3344 Mutability::Mut => "explicit `ref mut` binding modifier",
3345 }
3346 }
3347 } else {
3348 info.bad_ref_pats = true;
3349 info.suggest_eliding_modes = false;
3353 "reference pattern"
3354 };
3355 let primary_label = if from_expansion {
3358 info.suggest_eliding_modes = false;
3360 "occurs within macro expansion".to_owned()
3364 } else {
3365 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} not allowed when implicitly borrowing",
pat_kind))
})format!("{pat_kind} not allowed when implicitly borrowing")
3366 };
3367 info.primary_labels.push((trimmed_span, primary_label));
3368 }
3369}