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_attr_ir::lang_items::LangItem;
7use rustc_data_structures::fx::FxHashMap;
8use rustc_errors::codes::*;
9use rustc_errors::{
10 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan, pluralize,
11 struct_span_code_err,
12};
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_session::diagnostics::feature_err;
26use rustc_span::edit_distance::find_best_match_for_name;
27use rustc_span::edition::Edition;
28use rustc_span::{BytePos, DUMMY_SP, Ident, Span, bug, kw, span_bug, sym};
29use rustc_trait_selection::infer::InferCtxtExt;
30use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
31use tracing::{debug, instrument, trace};
32use ty::VariantDef;
33use ty::adjustment::{PatAdjust, PatAdjustment};
34
35use crate::expectation::Expectation;
36use crate::gather_locals::DeclOrigin;
37use crate::{FnCtxt, diagnostics};
38
39const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
40This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
41pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
42this type has no compile-time size. Therefore, all accesses to trait types must be through \
43pointers. If you encounter this error you should try to avoid dereferencing the pointer.
44
45You can read more about trait objects in the Trait Objects section of the Reference: \
46https://doc.rust-lang.org/reference/types.html#trait-objects";
47
48fn is_number(text: &str) -> bool {
49 text.chars().all(|c: char| c.is_ascii_digit())
50}
51
52#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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)]
56struct TopInfo<'tcx> {
57 expected: Ty<'tcx>,
59 origin_expr: Option<&'tcx hir::Expr<'tcx>>,
63 span: Option<Span>,
86 hir_id: HirId,
88}
89
90#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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)]
91struct PatInfo<'tcx> {
92 binding_mode: ByRef,
93 max_pinnedness: PinnednessCap,
94 max_ref_mutbl: MutblCap,
95 top_info: TopInfo<'tcx>,
96 decl_origin: Option<DeclOrigin<'tcx>>,
97
98 current_depth: u32,
100}
101
102impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
103 fn pattern_cause(&self, ti: &TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
104 let origin_expr_info = ti.origin_expr.map(|mut cur_expr| {
109 let mut count = 0;
110
111 while let ExprKind::AddrOf(.., inner) = &cur_expr.kind {
115 cur_expr = inner;
116 count += 1;
117 }
118
119 PatternOriginExpr {
120 peeled_span: cur_expr.span,
121 peeled_count: count,
122 peeled_prefix_suggestion_parentheses: expr_needs_parens(cur_expr),
123 }
124 });
125
126 let code = ObligationCauseCode::Pattern {
127 span: ti.span,
128 root_ty: ti.expected,
129 origin_expr: origin_expr_info,
130 };
131 self.cause(cause_span, code)
132 }
133
134 fn demand_eqtype_pat_diag(
135 &'a self,
136 cause_span: Span,
137 expected: Ty<'tcx>,
138 actual: Ty<'tcx>,
139 ti: &TopInfo<'tcx>,
140 ) -> Result<(), Diag<'a>> {
141 self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
142 .map_err(|mut diag| {
143 if let Some(expr) = ti.origin_expr {
144 self.suggest_fn_call(&mut diag, expr, expected, |output| {
145 self.can_eq(self.param_env, output, actual)
146 });
147 }
148 diag
149 })
150 }
151
152 fn demand_eqtype_pat(
153 &self,
154 cause_span: Span,
155 expected: Ty<'tcx>,
156 actual: Ty<'tcx>,
157 ti: &TopInfo<'tcx>,
158 ) -> Result<(), ErrorGuaranteed> {
159 self.demand_eqtype_pat_diag(cause_span, expected, actual, ti).map_err(|err| err.emit_err())
160 }
161}
162
163#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AdjustMode {
}
#[automatically_derived]impl ::core::clone::Clone for AdjustMode {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Peel { kind: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Peel kind", &__self_0),
Self::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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Peel { kind: __self_0 }, Self::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)]
165enum AdjustMode {
166 Peel { kind: PeelKind },
169 Pass,
171}
172
173#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for PeelKind {
}
#[automatically_derived]impl ::core::clone::Clone for PeelKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::ExplicitDerefPat =>
::core::fmt::Formatter::write_str(f, "ExplicitDerefPat"),
Self::Implicit { until_adt: __self_0, pat_ref_layers: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Implicit until_adt pat_ref_layers", __self_0, &__self_1),
}
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for PeelKind
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for PeelKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Implicit {
until_adt: __self_0, pat_ref_layers: __self_1 },
Self::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)]
175enum PeelKind {
176 ExplicitDerefPat,
179 Implicit {
181 until_adt: Option<DefId>,
184 pat_ref_layers: usize,
187 },
188}
189
190impl AdjustMode {
191 const fn peel_until_adt(opt_adt_def: Option<DefId>) -> AdjustMode {
192 AdjustMode::Peel { kind: PeelKind::Implicit { until_adt: opt_adt_def, pat_ref_layers: 0 } }
193 }
194 const fn peel_all() -> AdjustMode {
195 AdjustMode::peel_until_adt(None)
196 }
197}
198
199#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for MutblCap {
}
#[automatically_derived]impl ::core::clone::Clone for MutblCap {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Not => ::core::fmt::Formatter::write_str(f, "Not"),
Self::WeaklyNot(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"WeaklyNot", &__self_0),
Self::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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::WeaklyNot(__self_0), Self::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)]
210enum MutblCap {
211 Not,
213
214 WeaklyNot(Option<Span>),
221
222 Mut,
224}
225
226impl MutblCap {
227 #[must_use]
228 fn cap_to_weakly_not(self, span: Option<Span>) -> Self {
229 match self {
230 MutblCap::Not => MutblCap::Not,
231 _ => MutblCap::WeaklyNot(span),
232 }
233 }
234
235 #[must_use]
236 fn as_mutbl(self) -> Mutability {
237 match self {
238 MutblCap::Not | MutblCap::WeaklyNot(_) => Mutability::Not,
239 MutblCap::Mut => Mutability::Mut,
240 }
241 }
242}
243
244#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for PinnednessCap {
}
#[automatically_derived]impl ::core::clone::Clone for PinnednessCap {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PinnednessCap { }Copy, #[automatically_derived]impl ::core::fmt::Debug for PinnednessCap {
#[inline]
#[rustc_trivial_field_reads]
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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PinnednessCap { }Eq)]
250enum PinnednessCap {
251 Not,
253 Pinned,
255}
256
257#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for InheritedRefMatchRule {
}
#[automatically_derived]impl ::core::clone::Clone for InheritedRefMatchRule {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::EatOuter =>
::core::fmt::Formatter::write_str(f, "EatOuter"),
Self::EatInner =>
::core::fmt::Formatter::write_str(f, "EatInner"),
Self::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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::EatBoth { consider_inherited_ref: __self_0 },
Self::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)]
263enum InheritedRefMatchRule {
264 EatOuter,
268 EatInner,
271 EatBoth {
274 consider_inherited_ref: bool,
285 },
286}
287
288#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ResolvedPat ty kind", &self.ty, &&self.kind)
}
}Debug)]
297struct ResolvedPat<'tcx> {
298 ty: Ty<'tcx>,
301 kind: ResolvedPatKind<'tcx>,
302}
303
304#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Path { res: __self_0, pat_res: __self_1, segments: __self_2
} =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"Path res pat_res segments", __self_0, __self_1, &__self_2),
Self::Struct { variant: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Struct variant", &__self_0),
Self::TupleStruct { res: __self_0, variant: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TupleStruct res variant", __self_0, &__self_1),
}
}
}Debug)]
305enum ResolvedPatKind<'tcx> {
306 Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] },
307 Struct { variant: &'tcx VariantDef },
308 TupleStruct { res: Res, variant: &'tcx VariantDef },
309}
310
311impl<'tcx> ResolvedPat<'tcx> {
312 fn adjust_mode(&self) -> AdjustMode {
313 if let ResolvedPatKind::Path { res, .. } = self.kind
314 && #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Const | DefKind::AssocConst, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
315 {
316 AdjustMode::Pass
320 } else {
321 AdjustMode::peel_until_adt(self.ty.ty_adt_def().map(|adt| adt.did()))
325 }
326 }
327}
328
329impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
330 fn downgrade_mut_inside_shared(&self) -> bool {
334 self.tcx.features().ref_pat_eat_one_layer_2024_structural()
337 }
338
339 fn ref_pat_matches_inherited_ref(&self, edition: Edition) -> InheritedRefMatchRule {
342 if edition.at_least_rust_2024() {
345 if self.tcx.features().ref_pat_eat_one_layer_2024() {
346 InheritedRefMatchRule::EatOuter
347 } else if self.tcx.features().ref_pat_eat_one_layer_2024_structural() {
348 InheritedRefMatchRule::EatInner
349 } else {
350 InheritedRefMatchRule::EatBoth { consider_inherited_ref: false }
353 }
354 } else {
355 InheritedRefMatchRule::EatBoth {
356 consider_inherited_ref: self.tcx.features().ref_pat_eat_one_layer_2024()
357 || self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
358 }
359 }
360 }
361
362 fn ref_pat_matches_mut_ref(&self) -> bool {
365 self.tcx.features().ref_pat_eat_one_layer_2024()
368 || self.tcx.features().ref_pat_eat_one_layer_2024_structural()
369 }
370
371 pub(crate) fn check_pat_top(
380 &self,
381 pat: &'tcx Pat<'tcx>,
382 expected: Ty<'tcx>,
383 span: Option<Span>,
384 origin_expr: Option<&'tcx hir::Expr<'tcx>>,
385 decl_origin: Option<DeclOrigin<'tcx>>,
386 ) {
387 let top_info = TopInfo { expected, origin_expr, span, hir_id: pat.hir_id };
388 let pat_info = PatInfo {
389 binding_mode: ByRef::No,
390 max_pinnedness: PinnednessCap::Not,
391 max_ref_mutbl: MutblCap::Mut,
392 top_info,
393 decl_origin,
394 current_depth: 0,
395 };
396 self.check_pat(pat, expected, pat_info);
397 }
398
399 {}
#[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("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(404u32),
::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))]
405 fn check_pat(&self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>) {
406 let opt_path_res = match pat.kind {
409 PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => {
410 Some(self.resolve_pat_path(*hir_id, *span, qpath))
411 }
412 PatKind::Struct(ref qpath, ..) => Some(self.resolve_pat_struct(pat, qpath)),
413 PatKind::TupleStruct(ref qpath, ..) => Some(self.resolve_pat_tuple_struct(pat, qpath)),
414 _ => None,
415 };
416 let adjust_mode = self.calc_adjust_mode(pat, opt_path_res);
417 let ty = self.check_pat_inner(pat, opt_path_res, adjust_mode, expected, pat_info);
418 self.write_ty(pat.hir_id, ty);
419
420 if let Some(derefed_tys) = self.typeck_results.borrow().pat_adjustments().get(pat.hir_id)
423 && derefed_tys.iter().any(|adjust| adjust.kind == PatAdjust::OverloadedDeref)
424 {
425 self.register_deref_mut_bounds_if_needed(
426 pat.span,
427 pat,
428 derefed_tys.iter().filter_map(|adjust| match adjust.kind {
429 PatAdjust::OverloadedDeref => Some(adjust.source),
430 PatAdjust::BuiltinDeref | PatAdjust::PinDeref => None,
431 }),
432 );
433 }
434
435 }
477
478 fn check_pat_inner(
480 &self,
481 pat: &'tcx Pat<'tcx>,
482 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
483 adjust_mode: AdjustMode,
484 expected: Ty<'tcx>,
485 pat_info: PatInfo<'tcx>,
486 ) -> Ty<'tcx> {
487 #[cfg(debug_assertions)]
488 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))
489 && pat_info.max_ref_mutbl != MutblCap::Mut
490 && self.downgrade_mut_inside_shared()
491 {
492 ::rustc_span::macros::bug_impl(Some(pat.span),
format_args!("Pattern mutability cap violated!"), Location::caller());span_bug!(pat.span, "Pattern mutability cap violated!");
493 }
494
495 let expected = if let AdjustMode::Peel { .. } = adjust_mode
497 && pat.default_binding_modes
498 {
499 self.deeply_resolve_ignoring_regions_with_obligations(expected)
500 } else {
501 expected
502 };
503 let old_pat_info = pat_info;
504 let pat_info = PatInfo { current_depth: old_pat_info.current_depth + 1, ..old_pat_info };
505
506 match pat.kind {
507 _ if let AdjustMode::Peel { kind: peel_kind } = adjust_mode
510 && pat.default_binding_modes
511 && let &ty::Ref(_, inner_ty, inner_mutability) = expected.kind()
512 && self.should_peel_ref(peel_kind, expected) =>
513 {
514 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:514",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(514u32),
::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);
515
516 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:516",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(516u32),
::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");
517 self.typeck_results
519 .borrow_mut()
520 .pat_adjustments_mut()
521 .entry(pat.hir_id)
522 .or_default()
523 .push(PatAdjustment { kind: PatAdjust::BuiltinDeref, source: expected });
524
525 let new_pat_info =
527 self.adjust_pat_info(Pinnedness::Not, inner_mutability, old_pat_info);
528
529 self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, new_pat_info)
531 }
532 _ if self.tcx.features().pin_ergonomics()
535 && let AdjustMode::Peel { kind: peel_kind } = adjust_mode
536 && pat.default_binding_modes
537 && self.should_peel_smart_pointer(peel_kind, expected)
538 && let Some(pinned_ty) = expected.pinned_ty()
539 && let &ty::Ref(_, inner_ty, inner_mutability) = pinned_ty.kind() =>
543 {
544 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:544",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(544u32),
::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");
545
546 let new_pat_info =
548 self.adjust_pat_info(Pinnedness::Pinned, inner_mutability, old_pat_info);
549
550 self.check_deref_pattern(
551 pat,
552 opt_path_res,
553 adjust_mode,
554 expected,
555 inner_ty,
556 PatAdjust::PinDeref,
557 new_pat_info,
558 )
559 }
560 _ if self.tcx.features().deref_patterns()
563 && let AdjustMode::Peel { kind: peel_kind } = adjust_mode
564 && pat.default_binding_modes
565 && self.should_peel_smart_pointer(peel_kind, expected) =>
566 {
567 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:567",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(567u32),
::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");
568
569 let inner_ty = self.deref_pat_target(pat.span, expected);
572 self.check_deref_pattern(
576 pat,
577 opt_path_res,
578 adjust_mode,
579 expected,
580 inner_ty,
581 PatAdjust::OverloadedDeref,
582 old_pat_info,
583 )
584 }
585 PatKind::Missing | PatKind::Wild | PatKind::Err(_) => expected,
586 PatKind::Never => expected,
588 PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), hir_id, .. }) => {
589 let ty = match opt_path_res.unwrap() {
590 Ok(ref pr) => {
591 self.check_pat_path(pat.hir_id, pat.span, pr, expected, &pat_info.top_info)
592 }
593 Err(guar) => Ty::new_error(self.tcx, guar),
594 };
595 self.write_ty(*hir_id, ty);
596 ty
597 }
598 PatKind::Expr(expr @ PatExpr { kind: PatExprKind::Lit { lit, .. }, .. }) => {
599 self.check_pat_lit(pat.span, expr, &lit.node, expected, &pat_info.top_info)
600 }
601 PatKind::Range(lhs, rhs, _) => {
602 self.check_pat_range(pat.span, lhs, rhs, expected, &pat_info.top_info)
603 }
604 PatKind::Binding(ba, var_id, ident, sub) => {
605 self.check_pat_ident(pat, ba, var_id, ident, sub, expected, pat_info)
606 }
607 PatKind::TupleStruct(ref qpath, subpats, ddpos) => match opt_path_res.unwrap() {
608 Ok(ResolvedPat { ty, kind: ResolvedPatKind::TupleStruct { res, variant } }) => self
609 .check_pat_tuple_struct(
610 pat, qpath, subpats, ddpos, res, ty, variant, expected, pat_info,
611 ),
612 Err(guar) => {
613 let ty_err = Ty::new_error(self.tcx, guar);
614 for subpat in subpats {
615 self.check_pat(subpat, ty_err, pat_info);
616 }
617 ty_err
618 }
619 Ok(pr) => ::rustc_span::macros::bug_impl(Some(pat.span),
format_args!("tuple struct pattern resolved to {0:?}", pr),
Location::caller())span_bug!(pat.span, "tuple struct pattern resolved to {pr:?}"),
620 },
621 PatKind::Struct(_, fields, has_rest_pat) => match opt_path_res.unwrap() {
622 Ok(ResolvedPat { ty, kind: ResolvedPatKind::Struct { variant } }) => self
623 .check_pat_struct(
624 pat,
625 fields,
626 has_rest_pat.is_some(),
627 ty,
628 variant,
629 expected,
630 pat_info,
631 ),
632 Err(guar) => {
633 let ty_err = Ty::new_error(self.tcx, guar);
634 for field in fields {
635 self.check_pat(field.pat, ty_err, pat_info);
636 }
637 ty_err
638 }
639 Ok(pr) => ::rustc_span::macros::bug_impl(Some(pat.span),
format_args!("struct pattern resolved to {0:?}", pr), Location::caller())span_bug!(pat.span, "struct pattern resolved to {pr:?}"),
640 },
641 PatKind::Guard(pat, cond) => {
642 self.check_pat(pat, expected, pat_info);
643 self.check_expr_has_type_or_error(cond, self.tcx.types.bool, |_| {});
644 expected
645 }
646 PatKind::Or(pats) => {
647 for pat in pats {
648 self.check_pat(pat, expected, pat_info);
649 }
650 expected
651 }
652 PatKind::Tuple(elements, ddpos) => {
653 self.check_pat_tuple(pat.span, elements, ddpos, expected, pat_info)
654 }
655 PatKind::Deref(inner) => self.check_pat_deref(pat.span, inner, expected, pat_info),
656 PatKind::Ref(inner, pinned, mutbl) => {
657 self.check_pat_ref(pat, inner, pinned, mutbl, expected, pat_info)
658 }
659 PatKind::Slice(before, slice, after) => {
660 self.check_pat_slice(pat.span, pat.hir_id, before, slice, after, expected, pat_info)
661 }
662 }
663 }
664
665 fn adjust_pat_info(
666 &self,
667 inner_pinnedness: Pinnedness,
668 inner_mutability: Mutability,
669 pat_info: PatInfo<'tcx>,
670 ) -> PatInfo<'tcx> {
671 let mut binding_mode = match pat_info.binding_mode {
672 ByRef::No => ByRef::Yes(inner_pinnedness, inner_mutability),
676 ByRef::Yes(pinnedness, mutability) => {
677 let pinnedness = match pinnedness {
678 Pinnedness::Not => inner_pinnedness,
680 Pinnedness::Pinned => Pinnedness::Pinned,
686 };
687
688 let mutability = match mutability {
689 Mutability::Mut => inner_mutability,
691 Mutability::Not => Mutability::Not,
694 };
695 ByRef::Yes(pinnedness, mutability)
696 }
697 };
698
699 let PatInfo { mut max_ref_mutbl, mut max_pinnedness, .. } = pat_info;
700 if self.downgrade_mut_inside_shared() {
701 binding_mode = binding_mode.cap_ref_mutability(max_ref_mutbl.as_mutbl());
702 }
703 match binding_mode {
704 ByRef::Yes(_, Mutability::Not) => max_ref_mutbl = MutblCap::Not,
705 ByRef::Yes(Pinnedness::Pinned, _) => max_pinnedness = PinnednessCap::Pinned,
706 _ => {}
707 }
708 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:708",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(708u32),
::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);
709 PatInfo { binding_mode, max_pinnedness, max_ref_mutbl, ..pat_info }
710 }
711
712 fn check_deref_pattern(
713 &self,
714 pat: &'tcx Pat<'tcx>,
715 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
716 adjust_mode: AdjustMode,
717 expected: Ty<'tcx>,
718 mut inner_ty: Ty<'tcx>,
719 pat_adjust_kind: PatAdjust,
720 pat_info: PatInfo<'tcx>,
721 ) -> Ty<'tcx> {
722 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!(
723 !matches!(pat_adjust_kind, PatAdjust::BuiltinDeref),
724 "unexpected deref pattern for builtin reference type {expected:?}",
725 );
726
727 let mut typeck_results = self.typeck_results.borrow_mut();
728 let mut pat_adjustments_table = typeck_results.pat_adjustments_mut();
729 let pat_adjustments = pat_adjustments_table.entry(pat.hir_id).or_default();
730 if self.tcx.recursion_limit().value_within_limit(pat_adjustments.len()) {
737 pat_adjustments.push(PatAdjustment { kind: pat_adjust_kind, source: expected });
739 } else {
740 let guar = report_autoderef_recursion_limit_error(self.tcx, pat.span, expected);
741 inner_ty = Ty::new_error(self.tcx, guar);
742 }
743 drop(typeck_results);
744
745 self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, pat_info)
748 }
749
750 fn calc_adjust_mode(
754 &self,
755 pat: &'tcx Pat<'tcx>,
756 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
757 ) -> AdjustMode {
758 match &pat.kind {
759 PatKind::Tuple(..) | PatKind::Range(..) | PatKind::Slice(..) => AdjustMode::peel_all(),
762 PatKind::Deref(_) => {
764 AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }
765 }
766 PatKind::Never => AdjustMode::peel_all(),
768 PatKind::Struct(..)
770 | PatKind::TupleStruct(..)
771 | PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => {
772 opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode())
774 }
775
776 PatKind::Expr(lt) => {
781 if truecfg!(debug_assertions)
784 && self.tcx.features().deref_patterns()
785 && !#[allow(non_exhaustive_omitted_patterns)] match lt.kind {
PatExprKind::Lit { .. } => true,
_ => false,
}matches!(lt.kind, PatExprKind::Lit { .. })
786 {
787 ::rustc_span::macros::bug_impl(Some(lt.span),
format_args!("FIXME(deref_patterns): adjust mode unimplemented for {0:?}",
lt.kind), Location::caller());span_bug!(
788 lt.span,
789 "FIXME(deref_patterns): adjust mode unimplemented for {:?}",
790 lt.kind
791 );
792 }
793 let lit_ty = self.deeply_resolve_ignoring_regions(self.check_pat_expr_unadjusted(lt));
795 if self.tcx.features().deref_patterns() {
797 let mut peeled_ty = lit_ty;
798 let mut pat_ref_layers = 0;
799 while let ty::Ref(_, inner_ty, mutbl) =
800 *self.deeply_resolve_ignoring_regions_with_obligations(peeled_ty).kind()
801 {
802 if true {
if !mutbl.is_not() {
::core::panicking::panic("assertion failed: mutbl.is_not()")
};
};debug_assert!(mutbl.is_not());
804 pat_ref_layers += 1;
805 peeled_ty = inner_ty;
806 }
807 AdjustMode::Peel {
808 kind: PeelKind::Implicit { until_adt: None, pat_ref_layers },
809 }
810 } else {
811 if lit_ty.is_ref() { AdjustMode::Pass } else { AdjustMode::peel_all() }
812 }
813 }
814
815 PatKind::Ref(..)
817 | PatKind::Missing
819 | PatKind::Wild
821 | PatKind::Err(_)
823 | PatKind::Binding(..)
828 | PatKind::Or(_)
832 | PatKind::Guard(..) => AdjustMode::Pass,
834 }
835 }
836
837 fn should_peel_ref(&self, peel_kind: PeelKind, mut expected: Ty<'tcx>) -> bool {
839 if true {
if !expected.is_ref() {
::core::panicking::panic("assertion failed: expected.is_ref()")
};
};debug_assert!(expected.is_ref());
840 let pat_ref_layers = match peel_kind {
841 PeelKind::ExplicitDerefPat => 0,
842 PeelKind::Implicit { pat_ref_layers, .. } => pat_ref_layers,
843 };
844
845 if pat_ref_layers == 0 {
848 return true;
849 }
850 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!(
851 self.tcx.features().deref_patterns(),
852 "Peeling for patterns with reference types is gated by `deref_patterns`."
853 );
854
855 let mut expected_ref_layers = 0;
861 while let ty::Ref(_, inner_ty, mutbl) = *expected.kind() {
862 if mutbl.is_mut() {
863 return true;
866 }
867 expected_ref_layers += 1;
868 expected = inner_ty;
869 }
870 pat_ref_layers < expected_ref_layers || self.should_peel_smart_pointer(peel_kind, expected)
871 }
872
873 fn should_peel_smart_pointer(&self, peel_kind: PeelKind, expected: Ty<'tcx>) -> bool {
875 if let PeelKind::Implicit { until_adt, .. } = peel_kind
877 && let ty::Adt(scrutinee_adt, _) = *expected.kind()
882 && until_adt != Some(scrutinee_adt.did())
885 && let Some(deref_trait) = self.tcx.lang_items().deref_trait()
890 && self.type_implements_trait(deref_trait, [expected], self.param_env).may_apply()
891 {
892 true
893 } else {
894 false
895 }
896 }
897
898 fn check_pat_expr_unadjusted(&self, lt: &'tcx hir::PatExpr<'tcx>) -> Ty<'tcx> {
899 let ty = match <.kind {
900 rustc_hir::PatExprKind::Lit { lit, negated } => {
901 let ty = self.check_expr_lit(lit, lt.hir_id, Expectation::NoExpectation);
902 if *negated {
903 self.register_bound(
904 ty,
905 self.tcx.require_lang_item(LangItem::Neg, lt.span),
906 ObligationCause::dummy_with_span(lt.span),
907 );
908 }
909 ty
910 }
911 rustc_hir::PatExprKind::Path(qpath) => {
912 let (res, opt_ty, segments) =
913 self.resolve_ty_and_res_fully_qualified_call(qpath, lt.hir_id, lt.span);
914 self.instantiate_value_path(
915 segments, opt_ty, res, lt.span, lt.span, lt.hir_id, None,
916 )
917 .0
918 }
919 };
920 self.write_ty(lt.hir_id, ty);
921 ty
922 }
923
924 fn check_pat_lit(
925 &self,
926 span: Span,
927 expr: &hir::PatExpr<'tcx>,
928 lit_kind: &ast::LitKind,
929 expected: Ty<'tcx>,
930 ti: &TopInfo<'tcx>,
931 ) -> Ty<'tcx> {
932 {
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 { .. });
933
934 let ty = self.node_ty(expr.hir_id);
937
938 let mut pat_ty = ty;
943 if #[allow(non_exhaustive_omitted_patterns)] match lit_kind {
ast::LitKind::ByteStr(..) => true,
_ => false,
}matches!(lit_kind, ast::LitKind::ByteStr(..)) {
944 let tcx = self.tcx;
945 let expected = self.structurally_resolve_type(span, expected);
946 match *expected.kind() {
947 ty::Ref(_, inner_ty, _)
949 if self
950 .deeply_resolve_ignoring_regions_with_obligations(inner_ty)
951 .is_slice() =>
952 {
953 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:953",
"rustc_hir_typeck::pat", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(953u32),
::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");
954 pat_ty = Ty::new_imm_ref(
955 tcx,
956 tcx.lifetimes.re_static,
957 Ty::new_slice(tcx, tcx.types.u8),
958 );
959 }
960 ty::Array(..) if tcx.features().deref_patterns() => {
962 pat_ty = match *ty.kind() {
963 ty::Ref(_, inner_ty, _) => inner_ty,
964 _ => ::rustc_span::macros::bug_impl(Some(span),
format_args!("found byte string literal with non-ref type {0:?}", ty),
Location::caller())span_bug!(span, "found byte string literal with non-ref type {ty:?}"),
965 }
966 }
967 ty::Slice(..) if tcx.features().deref_patterns() => {
969 pat_ty = Ty::new_slice(tcx, tcx.types.u8);
970 }
971 _ => {}
973 }
974 }
975
976 if self.tcx.features().deref_patterns()
979 && #[allow(non_exhaustive_omitted_patterns)] match lit_kind {
ast::LitKind::Str(..) => true,
_ => false,
}matches!(lit_kind, ast::LitKind::Str(..))
980 && self.deeply_resolve_ignoring_regions_with_obligations(expected).is_str()
981 {
982 pat_ty = self.tcx.types.str_;
983 }
984
985 let cause = self.pattern_cause(ti, span);
996 if let Err(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
997 let expected = self.deeply_resolve_ignoring_regions_with_obligations(expected);
999 let top_expected = self.deeply_resolve_ignoring_regions_with_obligations(ti.expected);
1000 if let ty::Adt(adt, _) = expected.kind()
1001 && self.tcx.is_lang_item(adt.did(), LangItem::String)
1002 && top_expected == expected
1003 && pat_ty.is_ref()
1004 && pat_ty.peel_refs().is_str()
1005 && let Some(origin_expr) = ti.origin_expr
1006 {
1007 err.span_suggestion_verbose(
1008 origin_expr.span.shrink_to_hi(),
1009 "consider converting the `String` to a `&str` using `.as_str()`",
1010 ".as_str()",
1011 Applicability::MachineApplicable,
1012 );
1013 }
1014 err.emit();
1015 }
1016
1017 pat_ty
1018 }
1019
1020 fn check_pat_range(
1021 &self,
1022 span: Span,
1023 lhs: Option<&'tcx hir::PatExpr<'tcx>>,
1024 rhs: Option<&'tcx hir::PatExpr<'tcx>>,
1025 expected: Ty<'tcx>,
1026 ti: &TopInfo<'tcx>,
1027 ) -> Ty<'tcx> {
1028 let calc_side = |opt_expr: Option<&'tcx hir::PatExpr<'tcx>>| match opt_expr {
1029 None => None,
1030 Some(expr) => {
1031 let ty = self.check_pat_expr_unadjusted(expr);
1032 let ty = self.deeply_resolve_ignoring_regions_with_obligations(ty);
1039 let fail =
1040 !(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
1041 Some((fail, ty, expr.span))
1042 }
1043 };
1044 let endpoints = [lhs, rhs];
1045 let mut lhs = calc_side(lhs);
1046 let mut rhs = calc_side(rhs);
1047
1048 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
1049 let guar = self.emit_err_pat_range(span, lhs, rhs, endpoints);
1052 return Ty::new_error(self.tcx, guar);
1053 }
1054
1055 let demand_eqtype = |x: &mut _, y| {
1058 if let Some((ref mut fail, x_ty, x_span)) = *x
1059 && let Err(mut err) = self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti)
1060 {
1061 if let Some((_, y_ty, y_span)) = y {
1062 self.endpoint_has_type(&mut err, y_span, y_ty);
1063 }
1064 err.emit();
1065 *fail = true;
1066 }
1067 };
1068 demand_eqtype(&mut lhs, rhs);
1069 demand_eqtype(&mut rhs, lhs);
1070
1071 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
1072 return Ty::new_misc_error(self.tcx);
1073 }
1074
1075 let ty = self.structurally_resolve_type(span, expected);
1080 if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
1081 if let Some((ref mut fail, _, _)) = lhs {
1082 *fail = true;
1083 }
1084 if let Some((ref mut fail, _, _)) = rhs {
1085 *fail = true;
1086 }
1087 let guar = self.emit_err_pat_range(span, lhs, rhs, endpoints);
1088 return Ty::new_error(self.tcx, guar);
1089 }
1090 ty
1091 }
1092
1093 fn endpoint_has_type(&self, err: &mut Diag<'_>, span: Span, ty: Ty<'_>) {
1094 if !ty.references_error() {
1095 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}`"));
1096 }
1097 }
1098
1099 fn emit_err_pat_range(
1100 &self,
1101 span: Span,
1102 lhs: Option<(bool, Ty<'tcx>, Span)>,
1103 rhs: Option<(bool, Ty<'tcx>, Span)>,
1104 endpoints: [Option<&hir::PatExpr<'tcx>>; 2],
1105 ) -> ErrorGuaranteed {
1106 if !(lhs, rhs).references_error() {
1107 let mut spans = Vec::new();
1110 for expr in endpoints.into_iter().flatten() {
1111 if let hir::PatExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind
1112 && #[allow(non_exhaustive_omitted_patterns)] match path.res {
Res::Local(_) => true,
_ => false,
}matches!(path.res, Res::Local(_))
1113 {
1114 spans.push(expr.span);
1115 }
1116 }
1117 if !spans.is_empty() {
1118 return self.dcx().emit_err(diagnostics::NonConstPathInPattern { spans });
1119 }
1120 }
1121
1122 let span = match (lhs, rhs) {
1123 (Some((true, ..)), Some((true, ..))) => span,
1124 (Some((true, _, sp)), _) => sp,
1125 (_, Some((true, _, sp))) => sp,
1126 _ => ::rustc_span::macros::bug_impl(Some(span),
format_args!("emit_err_pat_range: no side failed or exists but still error?"),
Location::caller())span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
1127 };
1128 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!(
1129 self.dcx(),
1130 span,
1131 E0029,
1132 "only `char` and numeric types are allowed in range patterns"
1133 );
1134 let msg = |ty| {
1135 let ty = self.deeply_resolve_ignoring_regions(ty);
1136 ::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")
1137 };
1138 let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
1139 err.span_label(first_span, msg(first_ty));
1140 if let Some((_, ty, sp)) = second {
1141 let ty = self.deeply_resolve_ignoring_regions(ty);
1142 self.endpoint_has_type(&mut err, sp, ty);
1143 }
1144 };
1145 match (lhs, rhs) {
1146 (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
1147 err.span_label(lhs_sp, msg(lhs_ty));
1148 err.span_label(rhs_sp, msg(rhs_ty));
1149 }
1150 (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
1151 (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
1152 _ => ::rustc_span::macros::bug_impl(Some(span),
format_args!("Impossible, verified above."), Location::caller())span_bug!(span, "Impossible, verified above."),
1153 }
1154 if (lhs, rhs).references_error() {
1155 err.downgrade_to_delayed_bug();
1156 }
1157 if self.tcx.sess.teach(err.code.unwrap()) {
1158 err.note(
1159 "In a match expression, only numbers and characters can be matched \
1160 against a range. This is because the compiler checks that the range \
1161 is non-empty at compile-time, and is unable to evaluate arbitrary \
1162 comparison functions. If you want to capture values of an orderable \
1163 type between two end-points, you can use a guard.",
1164 );
1165 }
1166 err.emit_err()
1167 }
1168
1169 fn check_pat_ident(
1170 &self,
1171 pat: &'tcx Pat<'tcx>,
1172 user_bind_annot: BindingMode,
1173 var_id: HirId,
1174 ident: Ident,
1175 sub: Option<&'tcx Pat<'tcx>>,
1176 expected: Ty<'tcx>,
1177 pat_info: PatInfo<'tcx>,
1178 ) -> Ty<'tcx> {
1179 let PatInfo { binding_mode: def_br, top_info: ti, .. } = pat_info;
1180
1181 let bm = match user_bind_annot {
1183 BindingMode(ByRef::No, Mutability::Mut) if let ByRef::Yes(_, def_br_mutbl) = def_br => {
1184 if pat.span.at_least_rust_2024()
1187 && (self.tcx.features().ref_pat_eat_one_layer_2024()
1188 || self.tcx.features().ref_pat_eat_one_layer_2024_structural())
1189 {
1190 if !self.tcx.features().mut_ref() {
1191 feature_err(
1192 self.tcx.sess,
1193 sym::mut_ref,
1194 pat.span.until(ident.span),
1195 "binding cannot be both mutable and by-reference",
1196 )
1197 .emit();
1198 }
1199
1200 BindingMode(def_br, Mutability::Mut)
1201 } else {
1202 self.add_rust_2024_migration_desugared_pat(
1204 pat_info.top_info.hir_id,
1205 pat,
1206 't', def_br_mutbl,
1208 );
1209 BindingMode(ByRef::No, Mutability::Mut)
1210 }
1211 }
1212 BindingMode(ByRef::No, mutbl) => BindingMode(def_br, mutbl),
1213 BindingMode(ByRef::Yes(_, user_br_mutbl), _) => {
1214 if let ByRef::Yes(_, def_br_mutbl) = def_br {
1215 self.add_rust_2024_migration_desugared_pat(
1217 pat_info.top_info.hir_id,
1218 pat,
1219 match user_br_mutbl {
1220 Mutability::Not => 'f', Mutability::Mut => 't', },
1223 def_br_mutbl,
1224 );
1225 }
1226 user_bind_annot
1227 }
1228 };
1229
1230 if pat_info.max_pinnedness == PinnednessCap::Pinned
1233 && #[allow(non_exhaustive_omitted_patterns)] match bm.0 {
ByRef::Yes(Pinnedness::Not, _) => true,
_ => false,
}matches!(bm.0, ByRef::Yes(Pinnedness::Not, _))
1234 {
1235 self.register_bound(
1236 expected,
1237 self.tcx.require_lang_item(LangItem::Unpin, pat.span),
1238 self.misc(pat.span),
1239 )
1240 }
1241
1242 if #[allow(non_exhaustive_omitted_patterns)] match bm.0 {
ByRef::Yes(_, Mutability::Mut) => true,
_ => false,
}matches!(bm.0, ByRef::Yes(_, Mutability::Mut))
1243 && let MutblCap::WeaklyNot(and_pat_span) = pat_info.max_ref_mutbl
1244 {
1245 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!(
1246 self.dcx(),
1247 ident.span,
1248 E0596,
1249 "cannot borrow as mutable inside an `&` pattern"
1250 );
1251
1252 if let Some(span) = and_pat_span {
1253 err.span_suggestion_short(
1254 span,
1255 "replace this `&` with `&mut`",
1256 "&mut ",
1257 Applicability::MachineApplicable,
1258 );
1259 }
1260 err.emit();
1261 }
1262
1263 self.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
1265
1266 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:1266",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(1266u32),
::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);
1267
1268 let local_ty = self.local_ty(pat.span, pat.hir_id);
1269 let eq_ty = match bm.0 {
1270 ByRef::Yes(pinnedness, mutbl) => {
1271 self.new_ref_ty(pat.span, pinnedness, mutbl, expected)
1283 }
1284 ByRef::No => expected, };
1287
1288 let _ = self.demand_eqtype_pat(pat.span, eq_ty, local_ty, &ti);
1290
1291 if var_id != pat.hir_id {
1294 self.check_binding_alt_eq_ty(user_bind_annot, pat.span, var_id, local_ty, &ti);
1295 }
1296
1297 if let Some(p) = sub {
1298 self.check_pat(p, expected, pat_info);
1299 }
1300
1301 local_ty
1302 }
1303
1304 fn check_binding_alt_eq_ty(
1308 &self,
1309 ba: BindingMode,
1310 span: Span,
1311 var_id: HirId,
1312 ty: Ty<'tcx>,
1313 ti: &TopInfo<'tcx>,
1314 ) {
1315 let var_ty = self.local_ty(span, var_id);
1316 if let Err(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
1317 let var_ty = self.deeply_resolve_ignoring_regions(var_ty);
1318 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");
1319 err.span_label(self.tcx.hir_span(var_id), msg);
1320 let in_match = self.tcx.hir_parent_iter(var_id).any(|(_, n)| {
1321 #[allow(non_exhaustive_omitted_patterns)] match n {
hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::Match(.., hir::MatchSource::Normal), .. }) =>
true,
_ => false,
}matches!(
1322 n,
1323 hir::Node::Expr(hir::Expr {
1324 kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
1325 ..
1326 })
1327 )
1328 });
1329 let pre = if in_match { "in the same arm, " } else { "" };
1330 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"));
1331 self.suggest_adding_missing_ref_or_removing_ref(
1332 &mut err,
1333 span,
1334 var_ty,
1335 self.deeply_resolve_ignoring_regions(ty),
1336 ba,
1337 );
1338 err.emit();
1339 }
1340 }
1341
1342 fn suggest_adding_missing_ref_or_removing_ref(
1343 &self,
1344 err: &mut Diag<'_>,
1345 span: Span,
1346 expected: Ty<'tcx>,
1347 actual: Ty<'tcx>,
1348 ba: BindingMode,
1349 ) {
1350 match (expected.kind(), actual.kind(), ba) {
1351 (ty::Ref(_, inner_ty, _), _, BindingMode::NONE)
1352 if self.can_eq(self.param_env, *inner_ty, actual) =>
1353 {
1354 err.span_suggestion_verbose(
1355 span.shrink_to_lo(),
1356 "consider adding `ref`",
1357 "ref ",
1358 Applicability::MaybeIncorrect,
1359 );
1360 }
1361 (_, ty::Ref(_, inner_ty, _), BindingMode::REF)
1362 if self.can_eq(self.param_env, expected, *inner_ty) =>
1363 {
1364 err.span_suggestion_verbose(
1365 span.with_hi(span.lo() + BytePos(4)),
1366 "consider removing `ref`",
1367 "",
1368 Applicability::MaybeIncorrect,
1369 );
1370 }
1371 _ => (),
1372 }
1373 }
1374
1375 fn borrow_pat_suggestion(&self, err: &mut Diag<'_>, pat: &Pat<'_>) {
1377 let tcx = self.tcx;
1378 if let PatKind::Ref(inner, pinned, mutbl) = pat.kind
1379 && let PatKind::Binding(_, _, binding, ..) = inner.kind
1380 {
1381 let binding_parent = tcx.parent_hir_node(pat.hir_id);
1382 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:1382",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(1382u32),
::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);
1383
1384 let pin_and_mut = pinned.prefix_str(mutbl).trim_end();
1385
1386 let mut_var_suggestion = 'block: {
1387 if mutbl.is_not() {
1388 break 'block None;
1389 }
1390
1391 let ident_kind = match binding_parent {
1392 hir::Node::Param(_) => "parameter",
1393 hir::Node::LetStmt(_) => "variable",
1394 hir::Node::Arm(_) => "binding",
1395
1396 hir::Node::Pat(Pat { kind, .. }) => match kind {
1399 PatKind::Struct(..)
1400 | PatKind::TupleStruct(..)
1401 | PatKind::Or(..)
1402 | PatKind::Guard(..)
1403 | PatKind::Tuple(..)
1404 | PatKind::Slice(..) => "binding",
1405
1406 PatKind::Missing
1407 | PatKind::Wild
1408 | PatKind::Never
1409 | PatKind::Binding(..)
1410 | PatKind::Deref(_)
1411 | PatKind::Ref(..)
1412 | PatKind::Expr(..)
1413 | PatKind::Range(..)
1414 | PatKind::Err(_) => break 'block None,
1415 },
1416
1417 _ => break 'block None,
1419 };
1420
1421 Some((
1422 pat.span,
1423 ::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"),
1424 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mut {0}", binding))
})format!("mut {binding}"),
1425 ))
1426 };
1427
1428 match binding_parent {
1429 hir::Node::Param(hir::Param { ty_span, pat, .. })
1430 if pat.span != *ty_span
1431 && pinned.is_pinned()
1432 && !tcx.features().pin_ergonomics() =>
1433 {
1434 }
1437 hir::Node::Param(hir::Param { ty_span, pat, .. }) if pat.span != *ty_span => {
1440 err.multipart_suggestion(
1441 ::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"),
1442 ::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![
1443 (pat.span.until(inner.span), "".to_owned()),
1444 (ty_span.shrink_to_lo(), format!("&{}", pinned.prefix_str(mutbl))),
1445 ],
1446 Applicability::MachineApplicable
1447 );
1448
1449 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1450 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1451 }
1452 }
1453 hir::Node::Pat(pt) if let PatKind::TupleStruct(_, pat_arr, _) = pt.kind => {
1454 for i in pat_arr.iter() {
1455 if let PatKind::Ref(the_ref, _, _) = i.kind
1456 && let PatKind::Binding(mt, _, ident, _) = the_ref.kind
1457 {
1458 let BindingMode(_, mtblty) = mt;
1459 err.span_suggestion_verbose(
1460 i.span,
1461 ::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"),
1462 mtblty.prefix_str().to_string() + &ident.name.to_string(),
1463 Applicability::MaybeIncorrect,
1464 );
1465 }
1466 }
1467 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1468 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1469 }
1470 }
1471 hir::Node::Param(_) | hir::Node::Arm(_) | hir::Node::Pat(_) => {
1472 err.span_suggestion_verbose(
1474 pat.span.until(inner.span),
1475 ::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"),
1476 "",
1477 Applicability::MaybeIncorrect,
1478 );
1479
1480 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1481 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1482 }
1483 }
1484 _ if let Some((sp, msg, sugg)) = mut_var_suggestion => {
1485 err.span_suggestion_verbose(sp, msg, sugg, Applicability::MachineApplicable);
1486 }
1487 _ => {} }
1489 }
1490 }
1491
1492 fn check_dereferenceable(
1493 &self,
1494 span: Span,
1495 expected: Ty<'tcx>,
1496 inner: &Pat<'_>,
1497 ) -> Result<(), ErrorGuaranteed> {
1498 if let PatKind::Binding(..) = inner.kind
1499 && let Some(pointee_ty) = self.shallow_resolve(expected).builtin_deref(true)
1500 && let ty::Dynamic(..) = pointee_ty.kind()
1501 {
1502 let type_str = self.ty_to_string(expected);
1505 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!(
1506 self.dcx(),
1507 span,
1508 E0033,
1509 "type `{}` cannot be dereferenced",
1510 type_str
1511 );
1512 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"));
1513 if self.tcx.sess.teach(err.code.unwrap()) {
1514 err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
1515 }
1516 return Err(err.emit_err());
1517 }
1518 Ok(())
1519 }
1520
1521 fn resolve_pat_struct(
1522 &self,
1523 pat: &'tcx Pat<'tcx>,
1524 qpath: &hir::QPath<'tcx>,
1525 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1526 let (variant, pat_ty) = self.check_struct_path(qpath, pat.hir_id)?;
1528 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } })
1529 }
1530
1531 fn check_pin_projection(
1542 &self,
1543 pat: &'tcx Pat<'tcx>,
1544 pat_ty: Ty<'tcx>,
1545 pat_info: PatInfo<'tcx>,
1546 ) {
1547 let through_pin = pat_info.max_pinnedness == PinnednessCap::Pinned
1548 || #[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, _));
1549 if through_pin
1550 && let Some(adt) = pat_ty.ty_adt_def()
1551 && !adt.is_pin_project()
1552 && !adt.is_pin()
1553 {
1554 let def_span: Option<Span> = self.tcx.hir_span_if_local(adt.did());
1555 let sugg_span = def_span.map(|span| span.shrink_to_lo());
1556 self.dcx().emit_err(crate::diagnostics::ProjectOnNonPinProjectType {
1557 span: pat.span,
1558 def_span,
1559 sugg_span,
1560 });
1561 }
1562 }
1563
1564 fn check_pat_struct(
1565 &self,
1566 pat: &'tcx Pat<'tcx>,
1567 fields: &'tcx [hir::PatField<'tcx>],
1568 has_rest_pat: bool,
1569 pat_ty: Ty<'tcx>,
1570 variant: &'tcx VariantDef,
1571 expected: Ty<'tcx>,
1572 pat_info: PatInfo<'tcx>,
1573 ) -> Ty<'tcx> {
1574 self.check_pin_projection(pat, pat_ty, pat_info);
1575
1576 let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1578
1579 match self.check_struct_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info) {
1581 Ok(()) => match had_err {
1582 Ok(()) => pat_ty,
1583 Err(guar) => Ty::new_error(self.tcx, guar),
1584 },
1585 Err(guar) => Ty::new_error(self.tcx, guar),
1586 }
1587 }
1588
1589 fn resolve_pat_path(
1590 &self,
1591 path_id: HirId,
1592 span: Span,
1593 qpath: &'tcx hir::QPath<'_>,
1594 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1595 let tcx = self.tcx;
1596
1597 let (res, opt_ty, segments) =
1598 self.resolve_ty_and_res_fully_qualified_call(qpath, path_id, span);
1599 match res {
1600 Res::Err => {
1601 let e =
1602 self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
1603 self.set_tainted_by_errors(e);
1604 return Err(e);
1605 }
1606 Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Variant, _) => {
1607 let expected = "unit struct, unit variant or constant";
1608 let e = self.report_unexpected_variant_res(
1609 res,
1610 None,
1611 &[],
1612 qpath,
1613 span,
1614 E0533,
1615 expected,
1616 );
1617 return Err(e);
1618 }
1619 Res::SelfCtor(def_id) => {
1620 if let ty::Adt(adt_def, _) = *tcx.type_of(def_id).skip_binder().kind()
1621 && adt_def.is_struct()
1622 && let Some((CtorKind::Const, _)) = adt_def.non_enum_variant().ctor
1623 {
1624 } else {
1626 let e = self.report_unexpected_variant_res(
1627 res,
1628 None,
1629 &[],
1630 qpath,
1631 span,
1632 E0533,
1633 "unit struct",
1634 );
1635 return Err(e);
1636 }
1637 }
1638 Res::Def(
1639 DefKind::Ctor(_, CtorKind::Const)
1640 | DefKind::Const
1641 | DefKind::AssocConst
1642 | DefKind::ConstParam,
1643 _,
1644 ) => {} _ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected pattern resolution: {0:?}", res),
Location::caller())bug!("unexpected pattern resolution: {:?}", res),
1646 }
1647
1648 let (pat_ty, pat_res) =
1650 self.instantiate_value_path(segments, opt_ty, res, span, span, path_id, None);
1651 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res, pat_res, segments } })
1652 }
1653
1654 fn check_pat_path(
1655 &self,
1656 pat_id_for_diag: HirId,
1657 span: Span,
1658 resolved: &ResolvedPat<'tcx>,
1659 expected: Ty<'tcx>,
1660 ti: &TopInfo<'tcx>,
1661 ) -> Ty<'tcx> {
1662 if let Err(err) =
1663 self.demand_suptype_with_origin(&self.pattern_cause(ti, span), expected, resolved.ty)
1664 {
1665 self.emit_bad_pat_path(err, pat_id_for_diag, span, resolved);
1666 }
1667 resolved.ty
1668 }
1669
1670 fn maybe_suggest_range_literal(
1671 &self,
1672 e: &mut Diag<'_>,
1673 opt_def_id: Option<hir::def_id::DefId>,
1674 ident: Ident,
1675 ) -> bool {
1676 if let Some(def_id) = opt_def_id
1677 && let Some(hir::Node::Item(hir::Item {
1678 kind: hir::ItemKind::Const(_, _, _, ct_rhs),
1679 ..
1680 })) = self.tcx.hir_get_if_local(def_id)
1681 && let hir::Node::Expr(expr) = self.tcx.hir_node(ct_rhs.hir_id())
1682 && hir::is_range_literal(expr)
1683 {
1684 let span = self.tcx.hir_span(ct_rhs.hir_id());
1685 if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
1686 e.span_suggestion_verbose(
1687 ident.span,
1688 "you may want to move the range into the match block",
1689 snip,
1690 Applicability::MachineApplicable,
1691 );
1692 return true;
1693 }
1694 }
1695 false
1696 }
1697
1698 fn emit_bad_pat_path(
1699 &self,
1700 mut e: Diag<'_>,
1701 hir_id: HirId,
1702 pat_span: Span,
1703 resolved_pat: &ResolvedPat<'tcx>,
1704 ) {
1705 let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind else {
1706 ::rustc_span::macros::bug_impl(Some(pat_span),
format_args!("unexpected resolution for path pattern: {0:?}",
resolved_pat), Location::caller());span_bug!(pat_span, "unexpected resolution for path pattern: {resolved_pat:?}");
1707 };
1708
1709 let span = match (self.tcx.hir_res_span(pat_res), res.opt_def_id()) {
1710 (Some(span), _) => span,
1711 (None, Some(def_id)) => self.tcx.def_span(def_id),
1712 (None, None) => {
1713 e.emit();
1714 return;
1715 }
1716 };
1717 if let [hir::PathSegment { ident, args: None, .. }] = segments
1718 && e.suggestions.len() == 0
1719 {
1720 e.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} defined here", res.descr()))
})format!("{} defined here", res.descr()));
1721 e.span_label(
1722 pat_span,
1723 ::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!(
1724 "`{}` is interpreted as {} {}, not a new binding",
1725 ident,
1726 res.article(),
1727 res.descr(),
1728 ),
1729 );
1730 match self.tcx.parent_hir_node(hir_id) {
1731 hir::Node::PatField(..) => {
1732 e.span_suggestion_verbose(
1733 ident.span.shrink_to_hi(),
1734 "bind the struct field to a different name instead",
1735 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": other_{0}",
ident.as_str().to_lowercase()))
})format!(": other_{}", ident.as_str().to_lowercase()),
1736 Applicability::HasPlaceholders,
1737 );
1738 }
1739 _ => {
1740 let (type_def_id, item_def_id) = match resolved_pat.ty.kind() {
1741 ty::Adt(def, _) => match res {
1742 Res::Def(DefKind::Const, def_id) => (Some(def.did()), Some(def_id)),
1743 _ => (None, None),
1744 },
1745 _ => (None, None),
1746 };
1747
1748 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!(
1749 type_def_id.and_then(|id| self.tcx.as_lang_item(id)),
1750 Some(
1751 LangItem::Range
1752 | LangItem::RangeFrom
1753 | LangItem::RangeTo
1754 | LangItem::RangeFull
1755 | LangItem::RangeInclusiveStruct
1756 | LangItem::RangeToInclusive,
1757 )
1758 );
1759 if is_range {
1760 if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
1761 let msg = "constants only support matching by type, \
1762 if you meant to match against a range of values, \
1763 consider using a range pattern like `min ..= max` in the match block";
1764 e.note(msg);
1765 }
1766 } else {
1767 let msg = "introduce a new binding instead";
1768 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());
1769 e.span_suggestion_verbose(
1770 ident.span,
1771 msg,
1772 sugg,
1773 Applicability::HasPlaceholders,
1774 );
1775 }
1776 }
1777 };
1778 }
1779 e.emit();
1780 }
1781
1782 fn resolve_pat_tuple_struct(
1783 &self,
1784 pat: &'tcx Pat<'tcx>,
1785 qpath: &'tcx hir::QPath<'tcx>,
1786 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1787 let tcx = self.tcx;
1788 let report_unexpected_res = |res: Res| {
1789 let expected = "tuple struct or tuple variant";
1790 let sub_pats = match pat.kind {
1791 hir::PatKind::TupleStruct(_, sub_pats, _) => sub_pats,
1792 _ => &[],
1793 };
1794 let e = self.report_unexpected_variant_res(
1795 res, None, sub_pats, qpath, pat.span, E0164, expected,
1796 );
1797 Err(e)
1798 };
1799
1800 let (res, opt_ty, segments) =
1802 self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span);
1803 if res == Res::Err {
1804 let e = self.dcx().span_delayed_bug(pat.span, "`Res::Err` but no error emitted");
1805 self.set_tainted_by_errors(e);
1806 return Err(e);
1807 }
1808
1809 let (pat_ty, res) = self
1811 .instantiate_value_path(segments, opt_ty, res, pat.span, pat.span, pat.hir_id, None);
1812 if !pat_ty.is_fn() {
1813 return report_unexpected_res(res);
1814 }
1815
1816 let variant = match res {
1817 Res::Err => {
1818 self.dcx().span_bug(pat.span, "`Res::Err` but no error emitted");
1819 }
1820 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => {
1821 return report_unexpected_res(res);
1822 }
1823 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
1824 _ => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected pattern resolution: {0:?}", res),
Location::caller())bug!("unexpected pattern resolution: {:?}", res),
1825 };
1826
1827 let pat_ty = pat_ty.fn_sig(tcx).output();
1829 let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
1830
1831 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { res, variant } })
1832 }
1833
1834 fn check_pat_tuple_struct(
1835 &self,
1836 pat: &'tcx Pat<'tcx>,
1837 qpath: &'tcx hir::QPath<'tcx>,
1838 subpats: &'tcx [Pat<'tcx>],
1839 ddpos: hir::DotDotPos,
1840 res: Res,
1841 pat_ty: Ty<'tcx>,
1842 variant: &'tcx VariantDef,
1843 expected: Ty<'tcx>,
1844 pat_info: PatInfo<'tcx>,
1845 ) -> Ty<'tcx> {
1846 self.check_pin_projection(pat, pat_ty, pat_info);
1847
1848 let tcx = self.tcx;
1849 let on_error = |e| {
1850 for pat in subpats {
1851 self.check_pat(pat, Ty::new_error(tcx, e), pat_info);
1852 }
1853 };
1854
1855 let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1857
1858 if subpats.len() == variant.fields.len()
1860 || subpats.len() < variant.fields.len() && ddpos.as_opt_usize().is_some()
1861 {
1862 let ty::Adt(_, args) = pat_ty.kind() else {
1863 ::rustc_span::macros::bug_impl(None,
format_args!("unexpected pattern type {0:?}", pat_ty),
Location::caller());bug!("unexpected pattern type {:?}", pat_ty);
1864 };
1865 for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
1866 let field = &variant.fields[FieldIdx::from_usize(i)];
1867 let field_ty = self.field_ty(subpat.span, field, *args);
1868 self.check_pat(subpat, field_ty, pat_info);
1869
1870 self.tcx.check_stability(
1871 variant.fields[FieldIdx::from_usize(i)].did,
1872 Some(subpat.hir_id),
1873 subpat.span,
1874 None,
1875 );
1876 }
1877 if let Err(e) = had_err {
1878 on_error(e);
1879 return Ty::new_error(tcx, e);
1880 }
1881 } else {
1882 let e = self.emit_err_pat_wrong_number_of_fields(
1883 pat.span,
1884 res,
1885 qpath,
1886 subpats,
1887 &variant.fields.raw,
1888 expected,
1889 had_err,
1890 );
1891 on_error(e);
1892 return Ty::new_error(tcx, e);
1893 }
1894 pat_ty
1895 }
1896
1897 fn emit_err_pat_wrong_number_of_fields(
1898 &self,
1899 pat_span: Span,
1900 res: Res,
1901 qpath: &hir::QPath<'_>,
1902 subpats: &'tcx [Pat<'tcx>],
1903 fields: &'tcx [ty::FieldDef],
1904 expected: Ty<'tcx>,
1905 had_err: Result<(), ErrorGuaranteed>,
1906 ) -> ErrorGuaranteed {
1907 let subpats_ending = if subpats.len() == 1 { "" } else { "s" }pluralize!(subpats.len());
1908 let fields_ending = if fields.len() == 1 { "" } else { "s" }pluralize!(fields.len());
1909
1910 let subpat_spans = if subpats.is_empty() {
1911 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[pat_span]))vec![pat_span]
1912 } else {
1913 subpats.iter().map(|p| p.span).collect()
1914 };
1915 let last_subpat_span = *subpat_spans.last().unwrap();
1916 let res_span = self.tcx.def_span(res.def_id());
1917 let def_ident_span = self.tcx.def_ident_span(res.def_id()).unwrap_or(res_span);
1918 let field_def_spans = if fields.is_empty() {
1919 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[res_span]))vec![res_span]
1920 } else {
1921 fields.iter().map(|f| f.ident(self.tcx).span).collect()
1922 };
1923 let last_field_def_span = *field_def_spans.last().unwrap();
1924
1925 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!(
1926 self.dcx(),
1927 MultiSpan::from_spans(subpat_spans),
1928 E0023,
1929 "this pattern has {} field{}, but the corresponding {} has {} field{}",
1930 subpats.len(),
1931 subpats_ending,
1932 res.descr(),
1933 fields.len(),
1934 fields_ending,
1935 );
1936 err.span_label(
1937 last_subpat_span,
1938 ::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()),
1939 );
1940 err.span_context(qpath.span());
1941 if self.tcx.sess.source_map().is_multiline(def_ident_span.between(last_field_def_span)) {
1942 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()));
1943 }
1944 for span in &field_def_spans[..field_def_spans.len() - 1] {
1945 err.span_label(*span, "");
1946 }
1947 err.span_label(
1948 last_field_def_span,
1949 ::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),
1950 );
1951
1952 let missing_parentheses = match (expected.kind(), fields, had_err) {
1957 (ty::Adt(_, args), [field], Ok(())) => {
1961 let field_ty = self.field_ty(pat_span, field, *args);
1962 match field_ty.kind() {
1963 ty::Tuple(fields) => fields.len() == subpats.len(),
1964 _ => false,
1965 }
1966 }
1967 _ => false,
1968 };
1969 if missing_parentheses {
1970 let (left, right) = match subpats {
1971 [] => (qpath.span().shrink_to_hi(), pat_span),
1980 [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
1989 };
1990 err.multipart_suggestion(
1991 "missing parentheses",
1992 ::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())],
1993 Applicability::MachineApplicable,
1994 );
1995 } else if fields.len() > subpats.len() && pat_span != DUMMY_SP {
1996 let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi();
1997 let all_fields_span = match subpats {
1998 [] => after_fields_span,
1999 [field] => field.span,
2000 [first, .., last] => first.span.to(last.span),
2001 };
2002
2003 let all_wildcards = subpats.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
PatKind::Wild => true,
_ => false,
}matches!(pat.kind, PatKind::Wild));
2005 let first_tail_wildcard =
2006 subpats.iter().enumerate().fold(None, |acc, (pos, pat)| match (acc, &pat.kind) {
2007 (None, PatKind::Wild) => Some(pos),
2008 (Some(_), PatKind::Wild) => acc,
2009 _ => None,
2010 });
2011 let tail_span = match first_tail_wildcard {
2012 None => after_fields_span,
2013 Some(0) => subpats[0].span.to(after_fields_span),
2014 Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span),
2015 };
2016
2017 let mut wildcard_sugg = ::alloc::vec::from_elem_global("_", fields.len() - subpats.len())vec!["_"; fields.len() - subpats.len()].join(", ");
2019 if !subpats.is_empty() {
2020 wildcard_sugg = String::from(", ") + &wildcard_sugg;
2021 }
2022
2023 err.span_suggestion_verbose(
2024 after_fields_span,
2025 "use `_` to explicitly ignore each field",
2026 wildcard_sugg,
2027 Applicability::MaybeIncorrect,
2028 );
2029
2030 if fields.len() - subpats.len() > 1 || all_wildcards {
2033 if subpats.is_empty() || all_wildcards {
2034 err.span_suggestion_verbose(
2035 all_fields_span,
2036 "use `..` to ignore all fields",
2037 "..",
2038 Applicability::MaybeIncorrect,
2039 );
2040 } else {
2041 err.span_suggestion_verbose(
2042 tail_span,
2043 "use `..` to ignore the rest of the fields",
2044 ", ..",
2045 Applicability::MaybeIncorrect,
2046 );
2047 }
2048 }
2049 }
2050
2051 err.emit_err()
2052 }
2053
2054 fn check_pat_tuple(
2055 &self,
2056 span: Span,
2057 elements: &'tcx [Pat<'tcx>],
2058 ddpos: hir::DotDotPos,
2059 expected: Ty<'tcx>,
2060 pat_info: PatInfo<'tcx>,
2061 ) -> Ty<'tcx> {
2062 let tcx = self.tcx;
2063 let mut expected_len = elements.len();
2064 if ddpos.as_opt_usize().is_some() {
2065 if let ty::Tuple(tys) = self.structurally_resolve_type(span, expected).kind() {
2067 expected_len = tys.len();
2068 }
2069 }
2070 let max_len = cmp::max(expected_len, elements.len());
2071
2072 let element_tys_iter = (0..max_len).map(|_| self.next_ty_var(span));
2073 let element_tys = tcx.mk_type_list_from_iter(element_tys_iter);
2074 let pat_ty = Ty::new_tup(tcx, element_tys);
2075 if let Err(reported) = self.demand_eqtype_pat(span, expected, pat_ty, &pat_info.top_info) {
2076 for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
2079 self.check_pat(elem, Ty::new_error(tcx, reported), pat_info);
2080 }
2081 Ty::new_error(tcx, reported)
2082 } else {
2083 for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
2084 self.check_pat(elem, element_tys[i], pat_info);
2085 }
2086 pat_ty
2087 }
2088 }
2089
2090 fn check_struct_pat_fields(
2091 &self,
2092 adt_ty: Ty<'tcx>,
2093 pat: &'tcx Pat<'tcx>,
2094 variant: &'tcx ty::VariantDef,
2095 fields: &'tcx [hir::PatField<'tcx>],
2096 has_rest_pat: bool,
2097 pat_info: PatInfo<'tcx>,
2098 ) -> Result<(), ErrorGuaranteed> {
2099 let tcx = self.tcx;
2100
2101 let ty::Adt(adt, args) = adt_ty.kind() else {
2102 ::rustc_span::macros::bug_impl(Some(pat.span),
format_args!("struct pattern is not an ADT"), Location::caller());span_bug!(pat.span, "struct pattern is not an ADT");
2103 };
2104
2105 let field_map = variant
2107 .fields
2108 .iter_enumerated()
2109 .map(|(i, field)| (field.ident(self.tcx).normalize_to_macros_2_0(), (i, field)))
2110 .collect::<FxHashMap<_, _>>();
2111
2112 let mut used_fields = FxHashMap::default();
2114 let mut result = Ok(());
2115
2116 let mut inexistent_fields = ::alloc::vec::Vec::new()vec![];
2117 for field in fields {
2119 let span = field.span;
2120 let ident = tcx.adjust_ident(field.ident, variant.def_id);
2121 let field_ty = match used_fields.entry(ident) {
2122 Occupied(occupied) => {
2123 let guar = self.error_field_already_bound(span, field.ident, *occupied.get());
2124 result = Err(guar);
2125 Ty::new_error(tcx, guar)
2126 }
2127 Vacant(vacant) => {
2128 vacant.insert(span);
2129 field_map
2130 .get(&ident)
2131 .map(|(i, f)| {
2132 self.write_field_index(field.hir_id, *i);
2133 self.tcx.check_stability(f.did, Some(field.hir_id), span, None);
2134 self.field_ty(span, f, *args)
2135 })
2136 .unwrap_or_else(|| {
2137 inexistent_fields.push(field);
2138 Ty::new_misc_error(tcx)
2139 })
2140 }
2141 };
2142
2143 self.check_pat(field.pat, field_ty, pat_info);
2144 }
2145
2146 let mut unmentioned_fields = variant
2147 .fields
2148 .iter()
2149 .map(|field| (field, field.ident(self.tcx).normalize_to_macros_2_0()))
2150 .filter(|(_, ident)| !used_fields.contains_key(ident))
2151 .collect::<Vec<_>>();
2152
2153 let inexistent_fields_err = if !inexistent_fields.is_empty()
2154 && !inexistent_fields.iter().any(|field| field.ident.name == kw::Underscore)
2155 {
2156 variant.has_errors()?;
2158 Some(self.error_inexistent_fields(
2159 adt.variant_descr(),
2160 &inexistent_fields,
2161 &mut unmentioned_fields,
2162 pat,
2163 variant,
2164 *args,
2165 ))
2166 } else {
2167 None
2168 };
2169
2170 let non_exhaustive = variant.field_list_has_applicable_non_exhaustive();
2172 if non_exhaustive && !has_rest_pat {
2173 self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
2174 }
2175
2176 let mut unmentioned_err = None;
2177 if adt.is_union() {
2179 if fields.len() != 1 {
2180 self.dcx().emit_err(diagnostics::UnionPatMultipleFields { span: pat.span });
2181 }
2182 if has_rest_pat {
2183 self.dcx().emit_err(diagnostics::UnionPatDotDot { span: pat.span });
2184 }
2185 } else if !unmentioned_fields.is_empty() {
2186 let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
2187 .iter()
2188 .copied()
2189 .filter(|(field, _)| self.is_field_suggestable(field, pat.span))
2190 .collect();
2191
2192 if !has_rest_pat {
2193 if accessible_unmentioned_fields.is_empty() {
2194 unmentioned_err = Some(self.error_no_accessible_fields(pat, fields));
2195 } else {
2196 unmentioned_err = Some(self.error_unmentioned_fields(
2197 pat,
2198 &accessible_unmentioned_fields,
2199 accessible_unmentioned_fields.len() != unmentioned_fields.len(),
2200 fields,
2201 ));
2202 }
2203 } else if non_exhaustive && !accessible_unmentioned_fields.is_empty() {
2204 self.lint_non_exhaustive_omitted_patterns(
2205 pat,
2206 &accessible_unmentioned_fields,
2207 adt_ty,
2208 )
2209 }
2210 }
2211 match (inexistent_fields_err, unmentioned_err) {
2212 (Some(i), Some(u)) => {
2213 if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2214 i.delay_as_bug();
2217 u.delay_as_bug();
2218 Err(e)
2219 } else {
2220 i.emit();
2221 Err(u.emit_err())
2222 }
2223 }
2224 (None, Some(u)) => {
2225 if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2226 u.delay_as_bug();
2227 Err(e)
2228 } else {
2229 Err(u.emit_err())
2230 }
2231 }
2232 (Some(err), None) => Err(err.emit_err()),
2233 (None, None) => {
2234 self.error_tuple_variant_index_shorthand(variant, pat, fields)?;
2235 result
2236 }
2237 }
2238 }
2239
2240 fn error_tuple_variant_index_shorthand(
2241 &self,
2242 variant: &VariantDef,
2243 pat: &'_ Pat<'_>,
2244 fields: &[hir::PatField<'_>],
2245 ) -> Result<(), ErrorGuaranteed> {
2246 if let (Some(CtorKind::Fn), PatKind::Struct(qpath, field_patterns, ..)) =
2250 (variant.ctor_kind(), &pat.kind)
2251 {
2252 let has_shorthand_field_name = field_patterns.iter().any(|field| field.is_shorthand);
2253 if has_shorthand_field_name {
2254 let path = rustc_hir_pretty::qpath_to_string(self, qpath);
2255 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!(
2256 self.dcx(),
2257 pat.span,
2258 E0769,
2259 "tuple variant `{path}` written as struct variant",
2260 );
2261 err.span_suggestion_verbose(
2262 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2263 "use the tuple variant pattern syntax instead",
2264 ::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)),
2265 Applicability::MaybeIncorrect,
2266 );
2267 return Err(err.emit_err());
2268 }
2269 }
2270 Ok(())
2271 }
2272
2273 fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
2274 let sess = self.tcx.sess;
2275 let sm = sess.source_map();
2276 let sp_brace = sm.end_point(pat.span);
2277 let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
2278 let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
2279
2280 {
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!(
2281 self.dcx(),
2282 pat.span,
2283 E0638,
2284 "`..` required with {descr} marked as non-exhaustive",
2285 )
2286 .with_span_suggestion_verbose(
2287 sp_comma,
2288 "add `..` at the end of the field list to ignore all other fields",
2289 sugg,
2290 Applicability::MachineApplicable,
2291 )
2292 .emit();
2293 }
2294
2295 fn error_field_already_bound(
2296 &self,
2297 span: Span,
2298 ident: Ident,
2299 other_field: Span,
2300 ) -> ErrorGuaranteed {
2301 {
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!(
2302 self.dcx(),
2303 span,
2304 E0025,
2305 "field `{}` bound multiple times in the pattern",
2306 ident
2307 )
2308 .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"))
2309 .with_span_label(other_field, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("first use of `{0}`", ident))
})format!("first use of `{ident}`"))
2310 .emit_err()
2311 }
2312
2313 fn error_inexistent_fields(
2314 &self,
2315 kind_name: &str,
2316 inexistent_fields: &[&hir::PatField<'tcx>],
2317 unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>,
2318 pat: &'tcx Pat<'tcx>,
2319 variant: &ty::VariantDef,
2320 args: ty::GenericArgs<'tcx>,
2321 ) -> Diag<'a> {
2322 let tcx = self.tcx;
2323 let (field_names, t, plural) = match inexistent_fields {
2324 [field] => (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a field named `{0}`", field.ident))
})format!("a field named `{}`", field.ident), "this", ""),
2325 [fields @ .., last] => (
2326 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields named {0} and `{1}`",
fields.iter().map(|field|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", field.ident))
})).collect::<Vec<String>>().join(", "), last.ident))
})format!(
2327 "fields named {} and `{}`",
2328 fields
2329 .iter()
2330 .map(|field| format!("`{}`", field.ident))
2331 .collect::<Vec<String>>()
2332 .join(", "),
2333 last.ident,
2334 ),
2335 "these",
2336 "s",
2337 ),
2338 [] => ::core::panicking::unreachable_default_msg()unreachable!(),
2339 };
2340 let spans = inexistent_fields.iter().map(|field| field.ident.span).collect::<Vec<_>>();
2341 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!(
2342 self.dcx(),
2343 spans,
2344 E0026,
2345 "{} `{}` does not have {}",
2346 kind_name,
2347 tcx.def_path_str(variant.def_id),
2348 field_names
2349 );
2350 if let Some(pat_field) = inexistent_fields.last() {
2351 err.span_label(
2352 pat_field.ident.span,
2353 ::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!(
2354 "{} `{}` does not have {} field{}",
2355 kind_name,
2356 tcx.def_path_str(variant.def_id),
2357 t,
2358 plural
2359 ),
2360 );
2361
2362 if let [(field_def, field)] = unmentioned_fields.as_slice()
2363 && self.is_field_suggestable(field_def, pat.span)
2364 {
2365 let suggested_name =
2366 find_best_match_for_name(&[field.name], pat_field.ident.name, None);
2367 if let Some(suggested_name) = suggested_name {
2368 err.span_suggestion_verbose(
2369 pat_field.ident.span,
2370 "a field with a similar name exists",
2371 suggested_name,
2372 Applicability::MaybeIncorrect,
2373 );
2374
2375 if suggested_name.to_ident_string().parse::<usize>().is_err() {
2381 unmentioned_fields.retain(|&(_, x)| x.name != suggested_name);
2383 }
2384 } else if inexistent_fields.len() == 1 {
2385 match pat_field.pat.kind {
2386 PatKind::Expr(_)
2387 if !self.may_coerce(
2388 self.typeck_results.borrow().node_type(pat_field.pat.hir_id),
2389 self.field_ty(field.span, field_def, args),
2390 ) => {}
2391 _ => {
2392 err.span_suggestion_short(
2393 pat_field.ident.span,
2394 ::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!(
2395 "`{}` has a field named `{}`",
2396 tcx.def_path_str(variant.def_id),
2397 field.name,
2398 ),
2399 field.name,
2400 Applicability::MaybeIncorrect,
2401 );
2402 }
2403 }
2404 }
2405 }
2406 }
2407 if tcx.sess.teach(err.code.unwrap()) {
2408 err.note(
2409 "This error indicates that a struct pattern attempted to \
2410 extract a nonexistent field from a struct. Struct fields \
2411 are identified by the name used before the colon : so struct \
2412 patterns should resemble the declaration of the struct type \
2413 being matched.\n\n\
2414 If you are using shorthand field patterns but want to refer \
2415 to the struct field by a different name, you should rename \
2416 it explicitly.",
2417 );
2418 }
2419 err
2420 }
2421
2422 fn error_tuple_variant_as_struct_pat(
2423 &self,
2424 pat: &Pat<'_>,
2425 fields: &'tcx [hir::PatField<'tcx>],
2426 variant: &ty::VariantDef,
2427 ) -> Result<(), ErrorGuaranteed> {
2428 if let (Some(CtorKind::Fn), PatKind::Struct(qpath, pattern_fields, ..)) =
2429 (variant.ctor_kind(), &pat.kind)
2430 {
2431 let is_tuple_struct_match = !pattern_fields.is_empty()
2432 && pattern_fields.iter().map(|field| field.ident.name.as_str()).all(is_number);
2433 if is_tuple_struct_match {
2434 return Ok(());
2435 }
2436
2437 variant.has_errors()?;
2439
2440 let path = rustc_hir_pretty::qpath_to_string(self, qpath);
2441 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!(
2442 self.dcx(),
2443 pat.span,
2444 E0769,
2445 "tuple variant `{}` written as struct variant",
2446 path
2447 );
2448 let (sugg, appl) = if fields.len() == variant.fields.len() {
2449 (
2450 self.get_suggested_tuple_struct_pattern(fields, variant),
2451 Applicability::MachineApplicable,
2452 )
2453 } else {
2454 (
2455 variant.fields.iter().map(|_| "_").collect::<Vec<&str>>().join(", "),
2456 Applicability::MaybeIncorrect,
2457 )
2458 };
2459 err.span_suggestion_verbose(
2460 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2461 "use the tuple variant pattern syntax instead",
2462 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", sugg))
})format!("({sugg})"),
2463 appl,
2464 );
2465 return Err(err.emit_err());
2466 }
2467 Ok(())
2468 }
2469
2470 fn get_suggested_tuple_struct_pattern(
2471 &self,
2472 fields: &[hir::PatField<'_>],
2473 variant: &VariantDef,
2474 ) -> String {
2475 let variant_field_idents =
2476 variant.fields.iter().map(|f| f.ident(self.tcx)).collect::<Vec<Ident>>();
2477 fields
2478 .iter()
2479 .map(|field| {
2480 match self.tcx.sess.source_map().span_to_snippet(field.pat.span) {
2481 Ok(f) => {
2482 if variant_field_idents.contains(&field.ident) {
2485 String::from("_")
2486 } else {
2487 f
2488 }
2489 }
2490 Err(_) => rustc_hir_pretty::pat_to_string(self, field.pat),
2491 }
2492 })
2493 .collect::<Vec<String>>()
2494 .join(", ")
2495 }
2496
2497 fn error_no_accessible_fields(
2513 &self,
2514 pat: &Pat<'_>,
2515 fields: &'tcx [hir::PatField<'tcx>],
2516 ) -> Diag<'a> {
2517 let mut err = self
2518 .dcx()
2519 .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
2520
2521 if let Some(field) = fields.last() {
2522 let tail_span = field.span.shrink_to_hi().to(pat.span.shrink_to_hi());
2523 let comma_hi_offset =
2524 self.tcx.sess.source_map().span_to_snippet(tail_span).ok().and_then(|snippet| {
2525 let trimmed = snippet.trim_start();
2526 trimmed.starts_with(',').then(|| (snippet.len() - trimmed.len() + 1) as u32)
2527 });
2528 err.span_suggestion_verbose(
2529 if let Some(comma_hi_offset) = comma_hi_offset {
2530 tail_span.with_hi(tail_span.lo() + BytePos(comma_hi_offset)).shrink_to_hi()
2531 } else {
2532 field.span.shrink_to_hi()
2533 },
2534 "ignore the inaccessible and unused fields",
2535 if comma_hi_offset.is_some() { " .." } else { ", .." },
2536 Applicability::MachineApplicable,
2537 );
2538 } else {
2539 let qpath_span = if let PatKind::Struct(qpath, ..) = &pat.kind {
2540 qpath.span()
2541 } else {
2542 ::rustc_span::macros::bug_impl(None,
format_args!("`error_no_accessible_fields` called on non-struct pattern"),
Location::caller());bug!("`error_no_accessible_fields` called on non-struct pattern");
2543 };
2544
2545 let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi());
2547 err.span_suggestion_verbose(
2548 span,
2549 "ignore the inaccessible and unused fields",
2550 " { .. }",
2551 Applicability::MachineApplicable,
2552 );
2553 }
2554 err
2555 }
2556
2557 fn lint_non_exhaustive_omitted_patterns(
2562 &self,
2563 pat: &Pat<'_>,
2564 unmentioned_fields: &[(&ty::FieldDef, Ident)],
2565 ty: Ty<'tcx>,
2566 ) {
2567 struct FieldsNotListed<'a, 'b, 'tcx> {
2568 pat_span: Span,
2569 unmentioned_fields: &'a [(&'b ty::FieldDef, Ident)],
2570 joined_patterns: String,
2571 ty: Ty<'tcx>,
2572 }
2573
2574 impl<'a, 'b, 'c, 'tcx> Diagnostic<'a> for FieldsNotListed<'b, 'c, 'tcx> {
2575 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
2576 let Self { pat_span, unmentioned_fields, joined_patterns, ty } = self;
2577 Diag::new(dcx, level, "some fields are not explicitly listed")
2578 .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))
2579 .with_help(
2580 "ensure that all fields are mentioned explicitly by adding the suggested fields",
2581 )
2582 .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!(
2583 "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
2584 ))
2585 }
2586 }
2587
2588 fn joined_uncovered_patterns(witnesses: &[&Ident]) -> String {
2589 const LIMIT: usize = 3;
2590 match witnesses {
2591 [] => {
2592 {
::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!(
2593 "expected an uncovered pattern, otherwise why are we emitting an error?"
2594 )
2595 }
2596 [witness] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", witness))
})format!("`{witness}`"),
2597 [head @ .., tail] if head.len() < LIMIT => {
2598 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2599 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`",
head.join("`, `"), tail))
})format!("`{}` and `{}`", head.join("`, `"), tail)
2600 }
2601 _ => {
2602 let (head, tail) = witnesses.split_at(LIMIT);
2603 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2604 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and {1} more",
head.join("`, `"), tail.len()))
})format!("`{}` and {} more", head.join("`, `"), tail.len())
2605 }
2606 }
2607 }
2608 let joined_patterns = joined_uncovered_patterns(
2609 &unmentioned_fields.iter().map(|(_, i)| i).collect::<Vec<_>>(),
2610 );
2611
2612 self.tcx.emit_node_span_lint(
2613 NON_EXHAUSTIVE_OMITTED_PATTERNS,
2614 pat.hir_id,
2615 pat.span,
2616 FieldsNotListed { pat_span: pat.span, unmentioned_fields, joined_patterns, ty },
2617 );
2618 }
2619
2620 fn error_unmentioned_fields(
2630 &self,
2631 pat: &Pat<'_>,
2632 unmentioned_fields: &[(&ty::FieldDef, Ident)],
2633 have_inaccessible_fields: bool,
2634 fields: &'tcx [hir::PatField<'tcx>],
2635 ) -> Diag<'a> {
2636 let field_names = match unmentioned_fields {
2637 [(_, field)] if have_inaccessible_fields => {
2638 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}` and inaccessible fields",
field))
})format!("field `{field}` and inaccessible fields")
2639 }
2640 [(_, field)] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}`", field))
})format!("field `{field}`"),
2641 fields if have_inaccessible_fields => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields {0} and inaccessible fields",
fields.iter().map(|(_, name)|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})).collect::<Vec<String>>().join(", ")))
})format!(
2642 "fields {} and inaccessible fields",
2643 fields
2644 .iter()
2645 .map(|(_, name)| format!("`{name}`"))
2646 .collect::<Vec<String>>()
2647 .join(", ")
2648 ),
2649 [fields @ .., (_, last)] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields {0} and `{1}`",
fields.iter().map(|(_, name)|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})).collect::<Vec<String>>().join(", "), last))
})format!(
2650 "fields {} and `{last}`",
2651 fields
2652 .iter()
2653 .map(|(_, name)| format!("`{name}`"))
2654 .collect::<Vec<String>>()
2655 .join(", ")
2656 ),
2657 [] => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?} with unmentioned fields but no fields?",
pat)));
}unreachable!("{pat:?} with unmentioned fields but no fields?"),
2658 };
2659 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!(
2660 self.dcx(),
2661 pat.span,
2662 E0027,
2663 "pattern does not mention {field_names}",
2664 );
2665 err.span_label(pat.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing {0}", field_names))
})format!("missing {field_names}"));
2666 let len = unmentioned_fields.len();
2667 let (prefix, postfix, sp) = match fields {
2668 [] => match &pat.kind {
2669 PatKind::Struct(path, [], None) => {
2670 (" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi()))
2671 }
2672 _ => return err,
2673 },
2674 [.., field] => {
2675 let tail = field.span.shrink_to_hi().with_hi(pat.span.hi());
2678 match &pat.kind {
2679 PatKind::Struct(..) => (", ", " }", tail),
2680 _ => return err,
2681 }
2682 }
2683 };
2684 err.span_suggestion_verbose(
2685 sp,
2686 ::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!(
2687 "include the missing field{} in the pattern{}",
2688 pluralize!(len),
2689 if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
2690 ),
2691 ::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!(
2692 "{}{}{}{}",
2693 prefix,
2694 unmentioned_fields
2695 .iter()
2696 .map(|(_, name)| {
2697 let field_name = name.to_string();
2698 if is_number(&field_name) { format!("{field_name}: _") } else { field_name }
2699 })
2700 .collect::<Vec<_>>()
2701 .join(", "),
2702 if have_inaccessible_fields { ", .." } else { "" },
2703 postfix,
2704 ),
2705 Applicability::MachineApplicable,
2706 );
2707 err.span_suggestion_verbose(
2708 sp,
2709 ::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!(
2710 "if you don't care about {these} missing field{s}, you can explicitly ignore {them}",
2711 these = pluralize!("this", len),
2712 s = pluralize!(len),
2713 them = if len == 1 { "it" } else { "them" },
2714 ),
2715 ::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!(
2716 "{}{}{}{}",
2717 prefix,
2718 unmentioned_fields
2719 .iter()
2720 .map(|(_, name)| {
2721 let field_name = name.to_string();
2722 format!("{field_name}: _")
2723 })
2724 .collect::<Vec<_>>()
2725 .join(", "),
2726 if have_inaccessible_fields { ", .." } else { "" },
2727 postfix,
2728 ),
2729 Applicability::MachineApplicable,
2730 );
2731 err.span_suggestion_verbose(
2732 sp,
2733 "or always ignore missing fields here",
2734 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}..{1}", prefix, postfix))
})format!("{prefix}..{postfix}"),
2735 Applicability::MachineApplicable,
2736 );
2737 err
2738 }
2739
2740 fn check_pat_deref(
2741 &self,
2742 span: Span,
2743 inner: &'tcx Pat<'tcx>,
2744 expected: Ty<'tcx>,
2745 pat_info: PatInfo<'tcx>,
2746 ) -> Ty<'tcx> {
2747 let target_ty = self.deref_pat_target(span, expected);
2748 self.check_pat(inner, target_ty, pat_info);
2749 self.register_deref_mut_bounds_if_needed(span, inner, [expected]);
2750 expected
2751 }
2752
2753 fn deref_pat_target(&self, span: Span, source_ty: Ty<'tcx>) -> Ty<'tcx> {
2754 let tcx = self.tcx;
2756 self.register_bound(
2757 source_ty,
2758 tcx.require_lang_item(LangItem::DerefPure, span),
2759 self.misc(span),
2760 );
2761 let target_ty = Ty::new_projection(
2763 tcx,
2764 ty::IsRigid::No,
2765 tcx.require_lang_item(LangItem::DerefTarget, span),
2766 [source_ty],
2767 );
2768 let target_ty = self.normalize(span, Unnormalized::new_wip(target_ty));
2769 self.deeply_resolve_ignoring_regions_with_obligations(target_ty)
2770 }
2771
2772 fn register_deref_mut_bounds_if_needed(
2777 &self,
2778 span: Span,
2779 inner: &'tcx Pat<'tcx>,
2780 derefed_tys: impl IntoIterator<Item = Ty<'tcx>>,
2781 ) {
2782 if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) {
2783 for mutably_derefed_ty in derefed_tys {
2784 self.register_bound(
2785 mutably_derefed_ty,
2786 self.tcx.require_lang_item(LangItem::DerefMut, span),
2787 self.misc(span),
2788 );
2789 }
2790 }
2791 }
2792
2793 fn check_pat_ref(
2795 &self,
2796 pat: &'tcx Pat<'tcx>,
2797 inner: &'tcx Pat<'tcx>,
2798 pat_pinned: Pinnedness,
2799 pat_mutbl: Mutability,
2800 mut expected: Ty<'tcx>,
2801 mut pat_info: PatInfo<'tcx>,
2802 ) -> Ty<'tcx> {
2803 let tcx = self.tcx;
2804
2805 let pat_prefix_span =
2806 inner.span.find_ancestor_inside(pat.span).map(|end| pat.span.until(end));
2807
2808 let ref_pat_matches_mut_ref = self.ref_pat_matches_mut_ref();
2809 if ref_pat_matches_mut_ref && pat_mutbl == Mutability::Not {
2810 pat_info.max_ref_mutbl = pat_info.max_ref_mutbl.cap_to_weakly_not(pat_prefix_span);
2815 }
2816
2817 expected = self.deeply_resolve_ignoring_regions_with_obligations(expected);
2818 if let ByRef::Yes(inh_pin, inh_mut) = pat_info.binding_mode
2821 && pat_pinned == inh_pin
2822 {
2823 match self.ref_pat_matches_inherited_ref(pat.span.edition()) {
2824 InheritedRefMatchRule::EatOuter => {
2825 if pat_mutbl > inh_mut {
2827 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);
2832 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2833 }
2834
2835 pat_info.binding_mode = ByRef::No;
2836 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2837 self.check_pat(inner, expected, pat_info);
2838 return expected;
2839 }
2840 InheritedRefMatchRule::EatInner => {
2841 if let ty::Ref(_, _, r_mutbl) = *expected.kind()
2842 && pat_mutbl <= r_mutbl
2843 {
2844 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);
2851 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());
2855 let mutbl_cap = cmp::min(r_mutbl, pat_info.max_ref_mutbl.as_mutbl());
2856 pat_info.binding_mode = pat_info.binding_mode.cap_ref_mutability(mutbl_cap);
2857 } else {
2858 if pat_mutbl > inh_mut {
2861 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);
2870 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2871 }
2872
2873 pat_info.binding_mode = ByRef::No;
2874 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2875 self.check_pat(inner, expected, pat_info);
2876 return expected;
2877 }
2878 }
2879 InheritedRefMatchRule::EatBoth { consider_inherited_ref: true } => {
2880 pat_info.binding_mode = ByRef::No;
2882
2883 if let ty::Ref(_, inner_ty, _) = *expected.kind() {
2884 if pat_mutbl.is_mut() && inh_mut.is_mut() {
2886 self.check_pat(inner, inner_ty, pat_info);
2893 return expected;
2894 } else {
2895 }
2902 } else {
2903 if pat_mutbl > inh_mut {
2906 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2908 }
2909
2910 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2911 self.check_pat(inner, expected, pat_info);
2912 return expected;
2913 }
2914 }
2915 InheritedRefMatchRule::EatBoth { consider_inherited_ref: false } => {
2916 pat_info.binding_mode = ByRef::No;
2919 self.add_rust_2024_migration_desugared_pat(
2920 pat_info.top_info.hir_id,
2921 pat,
2922 match pat_mutbl {
2923 Mutability::Not => '&', Mutability::Mut => 't', },
2926 inh_mut,
2927 )
2928 }
2929 }
2930 }
2931
2932 let (ref_ty, inner_ty) = match self.check_dereferenceable(pat.span, expected, inner) {
2933 Ok(()) => {
2934 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:2940",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(2940u32),
::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);
2941 match expected.maybe_pinned_ref() {
2942 Some((r_ty, r_pinned, r_mutbl, _))
2943 if ((ref_pat_matches_mut_ref && r_mutbl >= pat_mutbl)
2944 || r_mutbl == pat_mutbl)
2945 && pat_pinned == r_pinned =>
2946 {
2947 if r_mutbl == Mutability::Not {
2948 pat_info.max_ref_mutbl = MutblCap::Not;
2949 }
2950 if r_pinned == Pinnedness::Pinned {
2951 pat_info.max_pinnedness = PinnednessCap::Pinned;
2952 }
2953
2954 (expected, r_ty)
2955 }
2956 _ => {
2957 let inner_ty = self.next_ty_var(inner.span);
2958 let ref_ty = self.new_ref_ty(pat.span, pat_pinned, pat_mutbl, inner_ty);
2959 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:2959",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(2959u32),
::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);
2960 let err = self.demand_eqtype_pat_diag(
2961 pat.span,
2962 expected,
2963 ref_ty,
2964 &pat_info.top_info,
2965 );
2966
2967 if let Err(mut err) = err {
2970 self.borrow_pat_suggestion(&mut err, pat);
2971 err.emit();
2972 }
2973 (ref_ty, inner_ty)
2974 }
2975 }
2976 }
2977 Err(guar) => {
2978 let err = Ty::new_error(tcx, guar);
2979 (err, err)
2980 }
2981 };
2982
2983 self.check_pat(inner, inner_ty, pat_info);
2984 ref_ty
2985 }
2986
2987 fn new_ref_ty(
2989 &self,
2990 span: Span,
2991 pinnedness: Pinnedness,
2992 mutbl: Mutability,
2993 ty: Ty<'tcx>,
2994 ) -> Ty<'tcx> {
2995 let region = self.next_region_var(RegionVariableOrigin::PatternRegion(span));
2996 let ref_ty = Ty::new_ref(self.tcx, region, ty, mutbl);
2997 if pinnedness.is_pinned() {
2998 return self.new_pinned_ty(span, ref_ty);
2999 }
3000 ref_ty
3001 }
3002
3003 fn new_pinned_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
3005 Ty::new_adt(
3006 self.tcx,
3007 self.tcx.adt_def(self.tcx.require_lang_item(LangItem::Pin, span)),
3008 self.tcx.mk_args(&[ty.into()]),
3009 )
3010 }
3011
3012 fn error_inherited_ref_mutability_mismatch(
3013 &self,
3014 pat: &'tcx Pat<'tcx>,
3015 pat_prefix_span: Option<Span>,
3016 ) -> ErrorGuaranteed {
3017 let err_msg = "mismatched types";
3018 let err = if let Some(span) = pat_prefix_span {
3019 let mut err = self.dcx().struct_span_err(span, err_msg);
3020 err.code(E0308);
3021 err.note("cannot match inherited `&` with `&mut` pattern");
3022 err.span_suggestion_verbose(
3023 span,
3024 "replace this `&mut` pattern with `&`",
3025 "&",
3026 Applicability::MachineApplicable,
3027 );
3028 err
3029 } else {
3030 self.dcx().struct_span_err(pat.span, err_msg)
3031 };
3032 err.emit_err()
3033 }
3034
3035 fn try_resolve_slice_ty_to_array_ty(
3036 &self,
3037 before: &'tcx [Pat<'tcx>],
3038 slice: Option<&'tcx Pat<'tcx>>,
3039 span: Span,
3040 ) -> Option<Ty<'tcx>> {
3041 if slice.is_some() {
3042 return None;
3043 }
3044
3045 let tcx = self.tcx;
3046 let len = before.len();
3047 let inner_ty = self.next_ty_var(span);
3048
3049 Some(Ty::new_array(tcx, inner_ty, len.try_into().unwrap()))
3050 }
3051
3052 fn pat_is_irrefutable(&self, decl_origin: Option<DeclOrigin<'_>>) -> bool {
3083 match decl_origin {
3084 Some(DeclOrigin::LocalDecl { els: None }) => true,
3085 Some(DeclOrigin::LocalDecl { els: Some(_) } | DeclOrigin::LetExpr) | None => false,
3086 }
3087 }
3088
3089 fn check_pat_slice(
3100 &self,
3101 span: Span,
3102 slice_id: HirId,
3103 before: &'tcx [Pat<'tcx>],
3104 slice: Option<&'tcx Pat<'tcx>>,
3105 after: &'tcx [Pat<'tcx>],
3106 expected: Ty<'tcx>,
3107 pat_info: PatInfo<'tcx>,
3108 ) -> Ty<'tcx> {
3109 let expected = self.deeply_resolve_ignoring_regions_with_obligations(expected);
3110
3111 if self.pat_is_irrefutable(pat_info.decl_origin) && expected.is_ty_var() {
3114 if let Some(resolved_arr_ty) =
3115 self.try_resolve_slice_ty_to_array_ty(before, slice, span)
3116 {
3117 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:3117",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(3117u32),
::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);
3118 let _ = self.demand_eqtype(span, expected, resolved_arr_ty);
3119 }
3120 }
3121
3122 let expected = self.structurally_resolve_type(span, expected);
3123 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs:3123",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(3123u32),
::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);
3124
3125 let (element_ty, opt_slice_ty, inferred) = match *expected.kind() {
3126 ty::Array(element_ty, len) => {
3128 let min = before.len() as u64 + after.len() as u64;
3129 let (opt_slice_ty, expected) =
3130 self.check_array_pat_len(span, element_ty, expected, slice, len, min);
3131 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());
3134 (element_ty, opt_slice_ty, expected)
3135 }
3136 ty::Slice(element_ty) => (element_ty, Some(expected), expected),
3137 _ => {
3139 let guar = expected.error_reported().err().unwrap_or_else(|| {
3140 self.error_expected_array_or_slice(span, slice_id, expected, pat_info)
3141 });
3142 let err = Ty::new_error(self.tcx, guar);
3143 (err, Some(err), err)
3144 }
3145 };
3146
3147 for elt in before {
3149 self.check_pat(elt, element_ty, pat_info);
3150 }
3151 if let Some(slice) = slice {
3153 self.check_pat(slice, opt_slice_ty.unwrap(), pat_info);
3154 }
3155 for elt in after {
3157 self.check_pat(elt, element_ty, pat_info);
3158 }
3159 inferred
3160 }
3161
3162 fn check_array_pat_len(
3167 &self,
3168 span: Span,
3169 element_ty: Ty<'tcx>,
3170 arr_ty: Ty<'tcx>,
3171 slice: Option<&'tcx Pat<'tcx>>,
3172 len: ty::Const<'tcx>,
3173 min_len: u64,
3174 ) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
3175 let len = self.try_structurally_resolve_const(span, len).try_to_target_usize(self.tcx);
3176
3177 let guar = if let Some(len) = len {
3178 if slice.is_none() {
3180 if min_len == len {
3184 return (None, arr_ty);
3185 }
3186
3187 self.error_scrutinee_inconsistent_length(span, min_len, len)
3188 } else if let Some(pat_len) = len.checked_sub(min_len) {
3189 return (Some(Ty::new_array(self.tcx, element_ty, pat_len)), arr_ty);
3192 } else {
3193 self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len)
3196 }
3197 } else if slice.is_none() {
3198 let updated_arr_ty = Ty::new_array(self.tcx, element_ty, min_len);
3201 self.demand_eqtype(span, updated_arr_ty, arr_ty);
3202 return (None, updated_arr_ty);
3203 } else {
3204 self.error_scrutinee_unfixed_length(span)
3208 };
3209
3210 (Some(Ty::new_error(self.tcx, guar)), arr_ty)
3212 }
3213
3214 fn error_scrutinee_inconsistent_length(
3215 &self,
3216 span: Span,
3217 min_len: u64,
3218 size: u64,
3219 ) -> ErrorGuaranteed {
3220 {
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!(
3221 self.dcx(),
3222 span,
3223 E0527,
3224 "pattern requires {} element{} but array has {}",
3225 min_len,
3226 pluralize!(min_len),
3227 size,
3228 )
3229 .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)))
3230 .emit_err()
3231 }
3232
3233 fn error_scrutinee_with_rest_inconsistent_length(
3234 &self,
3235 span: Span,
3236 min_len: u64,
3237 size: u64,
3238 ) -> ErrorGuaranteed {
3239 {
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!(
3240 self.dcx(),
3241 span,
3242 E0528,
3243 "pattern requires at least {} element{} but array has {}",
3244 min_len,
3245 pluralize!(min_len),
3246 size,
3247 )
3248 .with_span_label(
3249 span,
3250 ::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),),
3251 )
3252 .emit_err()
3253 }
3254
3255 fn error_scrutinee_unfixed_length(&self, span: Span) -> ErrorGuaranteed {
3256 {
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!(
3257 self.dcx(),
3258 span,
3259 E0730,
3260 "cannot pattern-match on an array without a fixed length",
3261 )
3262 .emit_err()
3263 }
3264
3265 fn error_expected_array_or_slice(
3266 &self,
3267 span: Span,
3268 slice_id: HirId,
3269 expected_ty: Ty<'tcx>,
3270 pat_info: PatInfo<'tcx>,
3271 ) -> ErrorGuaranteed {
3272 let PatInfo { top_info: ti, current_depth, .. } = pat_info;
3273
3274 let mut slice_pat_semantics = false;
3275 let mut as_deref = None;
3276 let mut slicing = None;
3277 if let ty::Ref(_, ty, _) = expected_ty.kind()
3278 && let ty::Array(..) | ty::Slice(..) = ty.kind()
3279 {
3280 slice_pat_semantics = true;
3281 } else if self
3282 .autoderef(span, expected_ty)
3283 .silence_errors()
3284 .any(|(ty, _)| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Slice(..) | ty::Array(..) => true,
_ => false,
}matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
3285 && let Some(span) = ti.span
3286 && let Some(_) = ti.origin_expr
3287 {
3288 let resolved_ty = self.deeply_resolve_ignoring_regions(ti.expected);
3289 let (is_slice_or_array_or_vector, resolved_ty) =
3290 self.is_slice_or_array_or_vector(resolved_ty);
3291 match resolved_ty.kind() {
3292 ty::Adt(adt_def, args)
3293 if self.tcx.is_diagnostic_item(sym::Option, adt_def.did())
3294 || self.tcx.is_diagnostic_item(sym::Result, adt_def.did()) =>
3295 {
3296 let is_option = self.tcx.is_diagnostic_item(sym::Option, adt_def.did());
3297 let deref_ty = args.type_at(0).peel_refs();
3298 if self.can_eq(self.param_env, expected_ty.peel_refs(), deref_ty)
3299 && self.slice_pattern_is_direct_payload(ti.hir_id, slice_id, is_option)
3300 {
3301 as_deref =
3302 Some(diagnostics::AsDerefSuggestion { span: span.shrink_to_hi() });
3303 }
3304 }
3305 _ => (),
3306 }
3307
3308 let is_top_level = current_depth <= 1;
3309 if is_slice_or_array_or_vector && is_top_level {
3310 slicing = Some(diagnostics::SlicingSuggestion { span: span.shrink_to_hi() });
3311 }
3312 }
3313 self.dcx().emit_err(diagnostics::ExpectedArrayOrSlice {
3314 span,
3315 ty: expected_ty,
3316 slice_pat_semantics,
3317 as_deref,
3318 slicing,
3319 })
3320 }
3321
3322 fn slice_pattern_is_direct_payload(
3323 &self,
3324 top_pat_id: HirId,
3325 slice_id: HirId,
3326 is_option: bool,
3327 ) -> bool {
3328 let Some(ctor_id) = self.next_significant_pat(slice_id, top_pat_id) else {
3329 return false;
3330 };
3331 self.hir_pat_is_some_or_ok(ctor_id, is_option)
3332 && self.only_transparent_pats_until(ctor_id, top_pat_id)
3333 }
3334
3335 fn next_significant_pat(&self, start: HirId, top_pat_id: HirId) -> Option<HirId> {
3338 for (id, node) in self.tcx.hir_parent_iter(start) {
3339 let hir::Node::Pat(pat) = node else { return None };
3340 if self.pat_is_transparent(pat) {
3341 if id == top_pat_id {
3342 return None;
3343 }
3344 continue;
3345 }
3346 return Some(id);
3347 }
3348 None
3349 }
3350
3351 fn only_transparent_pats_until(&self, start: HirId, top_pat_id: HirId) -> bool {
3354 if start == top_pat_id {
3355 return true;
3356 }
3357 for (id, node) in self.tcx.hir_parent_iter(start) {
3358 let hir::Node::Pat(pat) = node else { return false };
3359 if !self.pat_is_transparent(pat) {
3360 return false;
3361 }
3362 if id == top_pat_id {
3363 return true;
3364 }
3365 }
3366 false
3367 }
3368
3369 fn pat_is_transparent(&self, pat: &Pat<'_>) -> bool {
3370 #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
PatKind::Ref(..) | PatKind::Guard(..) | PatKind::Binding(..) |
PatKind::Or(..) => true,
_ => false,
}matches!(
3371 pat.kind,
3372 PatKind::Ref(..) | PatKind::Guard(..) | PatKind::Binding(..) | PatKind::Or(..)
3373 )
3374 }
3375
3376 fn hir_pat_is_some_or_ok(&self, hir_id: HirId, is_option: bool) -> bool {
3377 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else { return false };
3378 let PatKind::TupleStruct(ref qpath, ..) = pat.kind else { return false };
3379 self.tuple_struct_is_some_or_ok(qpath, is_option)
3380 }
3381
3382 fn tuple_struct_is_some_or_ok(&self, qpath: &hir::QPath<'tcx>, is_option: bool) -> bool {
3383 let lang_item = if is_option { LangItem::OptionSome } else { LangItem::ResultOk };
3384 let hir::QPath::Resolved(_, path) = qpath else { return false };
3385 let variant_id = match path.res {
3386 Res::Def(DefKind::Ctor(..), ctor_id) => self.tcx.parent(ctor_id),
3387 Res::Def(DefKind::Variant, variant_id) => variant_id,
3388 _ => return false,
3389 };
3390 self.tcx.is_lang_item(variant_id, lang_item)
3391 }
3392
3393 fn is_slice_or_array_or_vector(&self, ty: Ty<'tcx>) -> (bool, Ty<'tcx>) {
3394 match ty.kind() {
3395 ty::Adt(adt_def, _) if self.tcx.is_diagnostic_item(sym::Vec, adt_def.did()) => {
3396 (true, ty)
3397 }
3398 ty::Ref(_, ty, _) => self.is_slice_or_array_or_vector(*ty),
3399 ty::Slice(..) | ty::Array(..) => (true, ty),
3400 _ => (false, ty),
3401 }
3402 }
3403
3404 fn add_rust_2024_migration_desugared_pat(
3407 &self,
3408 pat_id: HirId,
3409 subpat: &'tcx Pat<'tcx>,
3410 final_char: char,
3411 def_br_mutbl: Mutability,
3412 ) {
3413 let from_expansion = subpat.span.from_expansion();
3415 let trimmed_span = if from_expansion {
3416 subpat.span
3418 } else {
3419 let trimmed = self.tcx.sess.source_map().span_through_char(subpat.span, final_char);
3420 trimmed.with_ctxt(subpat.span.ctxt())
3423 };
3424
3425 let mut typeck_results = self.typeck_results.borrow_mut();
3426 let mut table = typeck_results.rust_2024_migration_desugared_pats_mut();
3427 let info = table.entry(pat_id).or_insert_with(|| ty::Rust2024IncompatiblePatInfo {
3432 primary_labels: Vec::new(),
3433 bad_ref_modifiers: false,
3434 bad_mut_modifiers: false,
3435 bad_ref_pats: false,
3436 suggest_eliding_modes: !self.tcx.features().ref_pat_eat_one_layer_2024()
3437 && !self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
3438 });
3439
3440 let pat_kind = if let PatKind::Binding(user_bind_annot, _, _, _) = subpat.kind {
3441 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!(
3445 user_bind_annot,
3446 BindingMode(ByRef::Yes(_, mutbl), Mutability::Not) if mutbl == def_br_mutbl
3447 );
3448 if user_bind_annot == BindingMode(ByRef::No, Mutability::Mut) {
3449 info.bad_mut_modifiers = true;
3450 "`mut` binding modifier"
3451 } else {
3452 info.bad_ref_modifiers = true;
3453 match user_bind_annot.1 {
3454 Mutability::Not => "explicit `ref` binding modifier",
3455 Mutability::Mut => "explicit `ref mut` binding modifier",
3456 }
3457 }
3458 } else {
3459 info.bad_ref_pats = true;
3460 info.suggest_eliding_modes = false;
3464 "reference pattern"
3465 };
3466 let primary_label = if from_expansion {
3469 info.suggest_eliding_modes = false;
3471 "occurs within macro expansion".to_owned()
3475 } else {
3476 ::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")
3477 };
3478 info.primary_labels.push((trimmed_span, primary_label));
3479 }
3480}