1use std::collections::hash_map::Entry::{Occupied, Vacant};
2use std::{assert_matches, cmp};
3
4use rustc_abi::FieldIdx;
5use rustc_ast as ast;
6use rustc_data_structures::fx::FxHashMap;
7use rustc_errors::codes::*;
8use rustc_errors::{
9 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan, pluralize,
10 struct_span_code_err,
11};
12use rustc_hir::def::{CtorKind, DefKind, Res};
13use rustc_hir::def_id::DefId;
14use rustc_hir::pat_util::EnumerateAndAdjustIterator;
15use rustc_hir::{
16 self as hir, BindingMode, ByRef, ExprKind, HirId, LangItem, Mutability, Pat, PatExpr,
17 PatExprKind, PatKind, expr_needs_parens,
18};
19use rustc_hir_analysis::autoderef::report_autoderef_recursion_limit_error;
20use rustc_infer::infer::RegionVariableOrigin;
21use rustc_middle::traits::PatternOriginExpr;
22use rustc_middle::ty::{self, Pinnedness, Ty, TypeVisitableExt, Unnormalized};
23use rustc_middle::{bug, span_bug};
24use rustc_session::diagnostics::feature_err;
25use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
26use rustc_span::edit_distance::find_best_match_for_name;
27use rustc_span::edition::Edition;
28use rustc_span::{BytePos, DUMMY_SP, Ident, Span, kw, 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]
impl<'tcx> ::core::clone::Clone for TopInfo<'tcx> {
#[inline]
fn clone(&self) -> TopInfo<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _:
::core::clone::AssertParamIsClone<Option<&'tcx hir::Expr<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<Option<Span>>;
let _: ::core::clone::AssertParamIsClone<HirId>;
*self
}
}Clone)]
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]
impl<'tcx> ::core::clone::Clone for PatInfo<'tcx> {
#[inline]
fn clone(&self) -> PatInfo<'tcx> {
let _: ::core::clone::AssertParamIsClone<ByRef>;
let _: ::core::clone::AssertParamIsClone<PinnednessCap>;
let _: ::core::clone::AssertParamIsClone<MutblCap>;
let _: ::core::clone::AssertParamIsClone<TopInfo<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Option<DeclOrigin<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone)]
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())
160 }
161}
162
163#[derive(#[automatically_derived]
impl ::core::clone::Clone for AdjustMode {
#[inline]
fn clone(&self) -> AdjustMode {
let _: ::core::clone::AssertParamIsClone<PeelKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AdjustMode { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for AdjustMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AdjustMode::Peel { kind: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Peel",
"kind", &__self_0),
AdjustMode::Pass => ::core::fmt::Formatter::write_str(f, "Pass"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AdjustMode {
#[inline]
fn eq(&self, other: &AdjustMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(AdjustMode::Peel { kind: __self_0 }, AdjustMode::Peel {
kind: __arg1_0 }) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AdjustMode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<PeelKind>;
}
}Eq)]
165enum AdjustMode {
166 Peel { kind: PeelKind },
169 Pass,
171}
172
173#[derive(#[automatically_derived]
impl ::core::clone::Clone for PeelKind {
#[inline]
fn clone(&self) -> PeelKind {
let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PeelKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for PeelKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PeelKind::ExplicitDerefPat =>
::core::fmt::Formatter::write_str(f, "ExplicitDerefPat"),
PeelKind::Implicit { until_adt: __self_0, pat_ref_layers: __self_1
} =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Implicit", "until_adt", __self_0, "pat_ref_layers",
&__self_1),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for PeelKind {
#[inline]
fn eq(&self, other: &PeelKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PeelKind::Implicit {
until_adt: __self_0, pat_ref_layers: __self_1 },
PeelKind::Implicit {
until_adt: __arg1_0, pat_ref_layers: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PeelKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<DefId>>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq)]
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]
impl ::core::clone::Clone for MutblCap {
#[inline]
fn clone(&self) -> MutblCap {
let _: ::core::clone::AssertParamIsClone<Option<Span>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MutblCap { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MutblCap {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MutblCap::Not => ::core::fmt::Formatter::write_str(f, "Not"),
MutblCap::WeaklyNot(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"WeaklyNot", &__self_0),
MutblCap::Mut => ::core::fmt::Formatter::write_str(f, "Mut"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MutblCap {
#[inline]
fn eq(&self, other: &MutblCap) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(MutblCap::WeaklyNot(__self_0), MutblCap::WeaklyNot(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MutblCap {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<Span>>;
}
}Eq)]
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]
impl ::core::clone::Clone for PinnednessCap {
#[inline]
fn clone(&self) -> PinnednessCap { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PinnednessCap { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for PinnednessCap {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
PinnednessCap::Not => "Not",
PinnednessCap::Pinned => "Pinned",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for PinnednessCap {
#[inline]
fn eq(&self, other: &PinnednessCap) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PinnednessCap {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
250enum PinnednessCap {
251 Not,
253 Pinned,
255}
256
257#[derive(#[automatically_derived]
impl ::core::clone::Clone for InheritedRefMatchRule {
#[inline]
fn clone(&self) -> InheritedRefMatchRule {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for InheritedRefMatchRule { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InheritedRefMatchRule {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
InheritedRefMatchRule::EatOuter =>
::core::fmt::Formatter::write_str(f, "EatOuter"),
InheritedRefMatchRule::EatInner =>
::core::fmt::Formatter::write_str(f, "EatInner"),
InheritedRefMatchRule::EatBoth { consider_inherited_ref: __self_0
} =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"EatBoth", "consider_inherited_ref", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for InheritedRefMatchRule {
#[inline]
fn eq(&self, other: &InheritedRefMatchRule) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(InheritedRefMatchRule::EatBoth {
consider_inherited_ref: __self_0 },
InheritedRefMatchRule::EatBoth {
consider_inherited_ref: __arg1_0 }) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InheritedRefMatchRule {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq)]
263enum InheritedRefMatchRule {
264 EatOuter,
268 EatInner,
271 EatBoth {
274 consider_inherited_ref: bool,
285 },
286}
287
288#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ResolvedPat<'tcx> {
#[inline]
fn clone(&self) -> ResolvedPat<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ResolvedPatKind<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ResolvedPat<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ResolvedPat<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "ResolvedPat",
"ty", &self.ty, "kind", &&self.kind)
}
}Debug)]
297struct ResolvedPat<'tcx> {
298 ty: Ty<'tcx>,
301 kind: ResolvedPatKind<'tcx>,
302}
303
304#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ResolvedPatKind<'tcx> {
#[inline]
fn clone(&self) -> ResolvedPatKind<'tcx> {
let _: ::core::clone::AssertParamIsClone<Res>;
let _:
::core::clone::AssertParamIsClone<&'tcx [hir::PathSegment<'tcx>]>;
let _: ::core::clone::AssertParamIsClone<&'tcx VariantDef>;
let _: ::core::clone::AssertParamIsClone<&'tcx VariantDef>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ResolvedPatKind<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ResolvedPatKind<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ResolvedPatKind::Path {
res: __self_0, pat_res: __self_1, segments: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f, "Path",
"res", __self_0, "pat_res", __self_1, "segments",
&__self_2),
ResolvedPatKind::Struct { variant: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Struct", "variant", &__self_0),
ResolvedPatKind::TupleStruct { res: __self_0, variant: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TupleStruct", "res", __self_0, "variant", &__self_1),
}
}
}Debug)]
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("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_middle::util::bug::span_bug_fmt(pat.span,
format_args!("Pattern mutability cap violated!"));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.resolve_vars_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 compiler/rustc_hir_typeck/src/pat.rs:514",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(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 compiler/rustc_hir_typeck/src/pat.rs:516",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(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 compiler/rustc_hir_typeck/src/pat.rs:544",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(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 compiler/rustc_hir_typeck/src/pat.rs:567",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(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_middle::util::bug::span_bug_fmt(pat.span,
format_args!("tuple struct pattern resolved to {0:?}", pr))span_bug!(pat.span, "tuple struct pattern resolved to {pr:?}"),
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_middle::util::bug::span_bug_fmt(pat.span,
format_args!("struct pattern resolved to {0:?}", pr))span_bug!(pat.span, "struct pattern resolved to {pr:?}"),
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::Box(inner) => self.check_pat_box(pat.span, inner, expected, pat_info),
656 PatKind::Deref(inner) => self.check_pat_deref(pat.span, inner, expected, pat_info),
657 PatKind::Ref(inner, pinned, mutbl) => {
658 self.check_pat_ref(pat, inner, pinned, mutbl, expected, pat_info)
659 }
660 PatKind::Slice(before, slice, after) => {
661 self.check_pat_slice(pat.span, before, slice, after, expected, pat_info)
662 }
663 }
664 }
665
666 fn adjust_pat_info(
667 &self,
668 inner_pinnedness: Pinnedness,
669 inner_mutability: Mutability,
670 pat_info: PatInfo<'tcx>,
671 ) -> PatInfo<'tcx> {
672 let mut binding_mode = match pat_info.binding_mode {
673 ByRef::No => ByRef::Yes(inner_pinnedness, inner_mutability),
677 ByRef::Yes(pinnedness, mutability) => {
678 let pinnedness = match pinnedness {
679 Pinnedness::Not => inner_pinnedness,
681 Pinnedness::Pinned => Pinnedness::Pinned,
687 };
688
689 let mutability = match mutability {
690 Mutability::Mut => inner_mutability,
692 Mutability::Not => Mutability::Not,
695 };
696 ByRef::Yes(pinnedness, mutability)
697 }
698 };
699
700 let PatInfo { mut max_ref_mutbl, mut max_pinnedness, .. } = pat_info;
701 if self.downgrade_mut_inside_shared() {
702 binding_mode = binding_mode.cap_ref_mutability(max_ref_mutbl.as_mutbl());
703 }
704 match binding_mode {
705 ByRef::Yes(_, Mutability::Not) => max_ref_mutbl = MutblCap::Not,
706 ByRef::Yes(Pinnedness::Pinned, _) => max_pinnedness = PinnednessCap::Pinned,
707 _ => {}
708 }
709 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:709",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(709u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("default binding mode is now {0:?}",
binding_mode) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("default binding mode is now {:?}", binding_mode);
710 PatInfo { binding_mode, max_pinnedness, max_ref_mutbl, ..pat_info }
711 }
712
713 fn check_deref_pattern(
714 &self,
715 pat: &'tcx Pat<'tcx>,
716 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
717 adjust_mode: AdjustMode,
718 expected: Ty<'tcx>,
719 mut inner_ty: Ty<'tcx>,
720 pat_adjust_kind: PatAdjust,
721 pat_info: PatInfo<'tcx>,
722 ) -> Ty<'tcx> {
723 if true {
if !!#[allow(non_exhaustive_omitted_patterns)] match pat_adjust_kind {
PatAdjust::BuiltinDeref => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("unexpected deref pattern for builtin reference type {0:?}",
expected));
}
};
};debug_assert!(
724 !matches!(pat_adjust_kind, PatAdjust::BuiltinDeref),
725 "unexpected deref pattern for builtin reference type {expected:?}",
726 );
727
728 let mut typeck_results = self.typeck_results.borrow_mut();
729 let mut pat_adjustments_table = typeck_results.pat_adjustments_mut();
730 let pat_adjustments = pat_adjustments_table.entry(pat.hir_id).or_default();
731 if self.tcx.recursion_limit().value_within_limit(pat_adjustments.len()) {
738 pat_adjustments.push(PatAdjustment { kind: pat_adjust_kind, source: expected });
740 } else {
741 let guar = report_autoderef_recursion_limit_error(self.tcx, pat.span, expected);
742 inner_ty = Ty::new_error(self.tcx, guar);
743 }
744 drop(typeck_results);
745
746 self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, pat_info)
749 }
750
751 fn calc_adjust_mode(
755 &self,
756 pat: &'tcx Pat<'tcx>,
757 opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
758 ) -> AdjustMode {
759 match &pat.kind {
760 PatKind::Tuple(..) | PatKind::Range(..) | PatKind::Slice(..) => AdjustMode::peel_all(),
763 PatKind::Box(_) | PatKind::Deref(_) => {
767 AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }
768 }
769 PatKind::Never => AdjustMode::peel_all(),
771 PatKind::Struct(..)
773 | PatKind::TupleStruct(..)
774 | PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => {
775 opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode())
777 }
778
779 PatKind::Expr(lt) => {
784 if truecfg!(debug_assertions)
787 && self.tcx.features().deref_patterns()
788 && !#[allow(non_exhaustive_omitted_patterns)] match lt.kind {
PatExprKind::Lit { .. } => true,
_ => false,
}matches!(lt.kind, PatExprKind::Lit { .. })
789 {
790 ::rustc_middle::util::bug::span_bug_fmt(lt.span,
format_args!("FIXME(deref_patterns): adjust mode unimplemented for {0:?}",
lt.kind));span_bug!(
791 lt.span,
792 "FIXME(deref_patterns): adjust mode unimplemented for {:?}",
793 lt.kind
794 );
795 }
796 let lit_ty = self.resolve_vars_if_possible(self.check_pat_expr_unadjusted(lt));
798 if self.tcx.features().deref_patterns() {
800 let mut peeled_ty = lit_ty;
801 let mut pat_ref_layers = 0;
802 while let ty::Ref(_, inner_ty, mutbl) =
803 *self.resolve_vars_with_obligations(peeled_ty).kind()
804 {
805 if true {
if !mutbl.is_not() {
::core::panicking::panic("assertion failed: mutbl.is_not()")
};
};debug_assert!(mutbl.is_not());
807 pat_ref_layers += 1;
808 peeled_ty = inner_ty;
809 }
810 AdjustMode::Peel {
811 kind: PeelKind::Implicit { until_adt: None, pat_ref_layers },
812 }
813 } else {
814 if lit_ty.is_ref() { AdjustMode::Pass } else { AdjustMode::peel_all() }
815 }
816 }
817
818 PatKind::Ref(..)
820 | PatKind::Missing
822 | PatKind::Wild
824 | PatKind::Err(_)
826 | PatKind::Binding(..)
831 | PatKind::Or(_)
835 | PatKind::Guard(..) => AdjustMode::Pass,
837 }
838 }
839
840 fn should_peel_ref(&self, peel_kind: PeelKind, mut expected: Ty<'tcx>) -> bool {
842 if true {
if !expected.is_ref() {
::core::panicking::panic("assertion failed: expected.is_ref()")
};
};debug_assert!(expected.is_ref());
843 let pat_ref_layers = match peel_kind {
844 PeelKind::ExplicitDerefPat => 0,
845 PeelKind::Implicit { pat_ref_layers, .. } => pat_ref_layers,
846 };
847
848 if pat_ref_layers == 0 {
851 return true;
852 }
853 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!(
854 self.tcx.features().deref_patterns(),
855 "Peeling for patterns with reference types is gated by `deref_patterns`."
856 );
857
858 let mut expected_ref_layers = 0;
864 while let ty::Ref(_, inner_ty, mutbl) = *expected.kind() {
865 if mutbl.is_mut() {
866 return true;
869 }
870 expected_ref_layers += 1;
871 expected = inner_ty;
872 }
873 pat_ref_layers < expected_ref_layers || self.should_peel_smart_pointer(peel_kind, expected)
874 }
875
876 fn should_peel_smart_pointer(&self, peel_kind: PeelKind, expected: Ty<'tcx>) -> bool {
878 if let PeelKind::Implicit { until_adt, .. } = peel_kind
880 && let ty::Adt(scrutinee_adt, _) = *expected.kind()
885 && until_adt != Some(scrutinee_adt.did())
888 && let Some(deref_trait) = self.tcx.lang_items().deref_trait()
893 && self.type_implements_trait(deref_trait, [expected], self.param_env).may_apply()
894 {
895 true
896 } else {
897 false
898 }
899 }
900
901 fn check_pat_expr_unadjusted(&self, lt: &'tcx hir::PatExpr<'tcx>) -> Ty<'tcx> {
902 let ty = match <.kind {
903 rustc_hir::PatExprKind::Lit { lit, negated } => {
904 let ty = self.check_expr_lit(lit, lt.hir_id, Expectation::NoExpectation);
905 if *negated {
906 self.register_bound(
907 ty,
908 self.tcx.require_lang_item(LangItem::Neg, lt.span),
909 ObligationCause::dummy_with_span(lt.span),
910 );
911 }
912 ty
913 }
914 rustc_hir::PatExprKind::Path(qpath) => {
915 let (res, opt_ty, segments) =
916 self.resolve_ty_and_res_fully_qualified_call(qpath, lt.hir_id, lt.span);
917 self.instantiate_value_path(segments, opt_ty, res, lt.span, lt.span, lt.hir_id).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.resolve_vars_with_obligations(inner_ty).is_slice() =>
950 {
951 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:951",
"rustc_hir_typeck::pat", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(951u32),
::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");
952 pat_ty = Ty::new_imm_ref(
953 tcx,
954 tcx.lifetimes.re_static,
955 Ty::new_slice(tcx, tcx.types.u8),
956 );
957 }
958 ty::Array(..) if tcx.features().deref_patterns() => {
960 pat_ty = match *ty.kind() {
961 ty::Ref(_, inner_ty, _) => inner_ty,
962 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("found byte string literal with non-ref type {0:?}", ty))span_bug!(span, "found byte string literal with non-ref type {ty:?}"),
963 }
964 }
965 ty::Slice(..) if tcx.features().deref_patterns() => {
967 pat_ty = Ty::new_slice(tcx, tcx.types.u8);
968 }
969 _ => {}
971 }
972 }
973
974 if self.tcx.features().deref_patterns()
977 && #[allow(non_exhaustive_omitted_patterns)] match lit_kind {
ast::LitKind::Str(..) => true,
_ => false,
}matches!(lit_kind, ast::LitKind::Str(..))
978 && self.resolve_vars_with_obligations(expected).is_str()
979 {
980 pat_ty = self.tcx.types.str_;
981 }
982
983 let cause = self.pattern_cause(ti, span);
994 if let Err(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
995 let expected = self.resolve_vars_with_obligations(expected);
997 if let ty::Adt(adt, _) = expected.kind()
998 && self.tcx.is_lang_item(adt.did(), LangItem::String)
999 && pat_ty.is_ref()
1000 && pat_ty.peel_refs().is_str()
1001 && let Some(origin_expr) = ti.origin_expr
1002 {
1003 err.span_suggestion_verbose(
1004 origin_expr.span.shrink_to_hi(),
1005 "consider converting the `String` to a `&str` using `.as_str()`",
1006 ".as_str()",
1007 Applicability::MachineApplicable,
1008 );
1009 }
1010 err.emit();
1011 }
1012
1013 pat_ty
1014 }
1015
1016 fn check_pat_range(
1017 &self,
1018 span: Span,
1019 lhs: Option<&'tcx hir::PatExpr<'tcx>>,
1020 rhs: Option<&'tcx hir::PatExpr<'tcx>>,
1021 expected: Ty<'tcx>,
1022 ti: &TopInfo<'tcx>,
1023 ) -> Ty<'tcx> {
1024 let calc_side = |opt_expr: Option<&'tcx hir::PatExpr<'tcx>>| match opt_expr {
1025 None => None,
1026 Some(expr) => {
1027 let ty = self.check_pat_expr_unadjusted(expr);
1028 let ty = self.resolve_vars_with_obligations(ty);
1035 let fail =
1036 !(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
1037 Some((fail, ty, expr.span))
1038 }
1039 };
1040 let mut lhs = calc_side(lhs);
1041 let mut rhs = calc_side(rhs);
1042
1043 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
1044 let guar = self.emit_err_pat_range(span, lhs, rhs);
1047 return Ty::new_error(self.tcx, guar);
1048 }
1049
1050 let demand_eqtype = |x: &mut _, y| {
1053 if let Some((ref mut fail, x_ty, x_span)) = *x
1054 && let Err(mut err) = self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti)
1055 {
1056 if let Some((_, y_ty, y_span)) = y {
1057 self.endpoint_has_type(&mut err, y_span, y_ty);
1058 }
1059 err.emit();
1060 *fail = true;
1061 }
1062 };
1063 demand_eqtype(&mut lhs, rhs);
1064 demand_eqtype(&mut rhs, lhs);
1065
1066 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
1067 return Ty::new_misc_error(self.tcx);
1068 }
1069
1070 let ty = self.structurally_resolve_type(span, expected);
1075 if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
1076 if let Some((ref mut fail, _, _)) = lhs {
1077 *fail = true;
1078 }
1079 if let Some((ref mut fail, _, _)) = rhs {
1080 *fail = true;
1081 }
1082 let guar = self.emit_err_pat_range(span, lhs, rhs);
1083 return Ty::new_error(self.tcx, guar);
1084 }
1085 ty
1086 }
1087
1088 fn endpoint_has_type(&self, err: &mut Diag<'_>, span: Span, ty: Ty<'_>) {
1089 if !ty.references_error() {
1090 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}`"));
1091 }
1092 }
1093
1094 fn emit_err_pat_range(
1095 &self,
1096 span: Span,
1097 lhs: Option<(bool, Ty<'tcx>, Span)>,
1098 rhs: Option<(bool, Ty<'tcx>, Span)>,
1099 ) -> ErrorGuaranteed {
1100 let span = match (lhs, rhs) {
1101 (Some((true, ..)), Some((true, ..))) => span,
1102 (Some((true, _, sp)), _) => sp,
1103 (_, Some((true, _, sp))) => sp,
1104 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("emit_err_pat_range: no side failed or exists but still error?"))span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
1105 };
1106 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!(
1107 self.dcx(),
1108 span,
1109 E0029,
1110 "only `char` and numeric types are allowed in range patterns"
1111 );
1112 let msg = |ty| {
1113 let ty = self.resolve_vars_if_possible(ty);
1114 ::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")
1115 };
1116 let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
1117 err.span_label(first_span, msg(first_ty));
1118 if let Some((_, ty, sp)) = second {
1119 let ty = self.resolve_vars_if_possible(ty);
1120 self.endpoint_has_type(&mut err, sp, ty);
1121 }
1122 };
1123 match (lhs, rhs) {
1124 (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
1125 err.span_label(lhs_sp, msg(lhs_ty));
1126 err.span_label(rhs_sp, msg(rhs_ty));
1127 }
1128 (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
1129 (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
1130 _ => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Impossible, verified above."))span_bug!(span, "Impossible, verified above."),
1131 }
1132 if (lhs, rhs).references_error() {
1133 err.downgrade_to_delayed_bug();
1134 }
1135 if self.tcx.sess.teach(err.code.unwrap()) {
1136 err.note(
1137 "In a match expression, only numbers and characters can be matched \
1138 against a range. This is because the compiler checks that the range \
1139 is non-empty at compile-time, and is unable to evaluate arbitrary \
1140 comparison functions. If you want to capture values of an orderable \
1141 type between two end-points, you can use a guard.",
1142 );
1143 }
1144 err.emit()
1145 }
1146
1147 fn check_pat_ident(
1148 &self,
1149 pat: &'tcx Pat<'tcx>,
1150 user_bind_annot: BindingMode,
1151 var_id: HirId,
1152 ident: Ident,
1153 sub: Option<&'tcx Pat<'tcx>>,
1154 expected: Ty<'tcx>,
1155 pat_info: PatInfo<'tcx>,
1156 ) -> Ty<'tcx> {
1157 let PatInfo { binding_mode: def_br, top_info: ti, .. } = pat_info;
1158
1159 let bm = match user_bind_annot {
1161 BindingMode(ByRef::No, Mutability::Mut) if let ByRef::Yes(_, def_br_mutbl) = def_br => {
1162 if pat.span.at_least_rust_2024()
1165 && (self.tcx.features().ref_pat_eat_one_layer_2024()
1166 || self.tcx.features().ref_pat_eat_one_layer_2024_structural())
1167 {
1168 if !self.tcx.features().mut_ref() {
1169 feature_err(
1170 self.tcx.sess,
1171 sym::mut_ref,
1172 pat.span.until(ident.span),
1173 "binding cannot be both mutable and by-reference",
1174 )
1175 .emit();
1176 }
1177
1178 BindingMode(def_br, Mutability::Mut)
1179 } else {
1180 self.add_rust_2024_migration_desugared_pat(
1182 pat_info.top_info.hir_id,
1183 pat,
1184 't', def_br_mutbl,
1186 );
1187 BindingMode(ByRef::No, Mutability::Mut)
1188 }
1189 }
1190 BindingMode(ByRef::No, mutbl) => BindingMode(def_br, mutbl),
1191 BindingMode(ByRef::Yes(_, user_br_mutbl), _) => {
1192 if let ByRef::Yes(_, def_br_mutbl) = def_br {
1193 self.add_rust_2024_migration_desugared_pat(
1195 pat_info.top_info.hir_id,
1196 pat,
1197 match user_br_mutbl {
1198 Mutability::Not => 'f', Mutability::Mut => 't', },
1201 def_br_mutbl,
1202 );
1203 }
1204 user_bind_annot
1205 }
1206 };
1207
1208 if pat_info.max_pinnedness == PinnednessCap::Pinned
1211 && #[allow(non_exhaustive_omitted_patterns)] match bm.0 {
ByRef::Yes(Pinnedness::Not, _) => true,
_ => false,
}matches!(bm.0, ByRef::Yes(Pinnedness::Not, _))
1212 {
1213 self.register_bound(
1214 expected,
1215 self.tcx.require_lang_item(hir::LangItem::Unpin, pat.span),
1216 self.misc(pat.span),
1217 )
1218 }
1219
1220 if #[allow(non_exhaustive_omitted_patterns)] match bm.0 {
ByRef::Yes(_, Mutability::Mut) => true,
_ => false,
}matches!(bm.0, ByRef::Yes(_, Mutability::Mut))
1221 && let MutblCap::WeaklyNot(and_pat_span) = pat_info.max_ref_mutbl
1222 {
1223 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!(
1224 self.dcx(),
1225 ident.span,
1226 E0596,
1227 "cannot borrow as mutable inside an `&` pattern"
1228 );
1229
1230 if let Some(span) = and_pat_span {
1231 err.span_suggestion(
1232 span,
1233 "replace this `&` with `&mut`",
1234 "&mut ",
1235 Applicability::MachineApplicable,
1236 );
1237 }
1238 err.emit();
1239 }
1240
1241 self.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
1243
1244 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:1244",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(1244u32),
::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);
1245
1246 let local_ty = self.local_ty(pat.span, pat.hir_id);
1247 let eq_ty = match bm.0 {
1248 ByRef::Yes(pinnedness, mutbl) => {
1249 self.new_ref_ty(pat.span, pinnedness, mutbl, expected)
1261 }
1262 ByRef::No => expected, };
1265
1266 let _ = self.demand_eqtype_pat(pat.span, eq_ty, local_ty, &ti);
1268
1269 if var_id != pat.hir_id {
1272 self.check_binding_alt_eq_ty(user_bind_annot, pat.span, var_id, local_ty, &ti);
1273 }
1274
1275 if let Some(p) = sub {
1276 self.check_pat(p, expected, pat_info);
1277 }
1278
1279 local_ty
1280 }
1281
1282 fn check_binding_alt_eq_ty(
1286 &self,
1287 ba: BindingMode,
1288 span: Span,
1289 var_id: HirId,
1290 ty: Ty<'tcx>,
1291 ti: &TopInfo<'tcx>,
1292 ) {
1293 let var_ty = self.local_ty(span, var_id);
1294 if let Err(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
1295 let var_ty = self.resolve_vars_if_possible(var_ty);
1296 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");
1297 err.span_label(self.tcx.hir_span(var_id), msg);
1298 let in_match = self.tcx.hir_parent_iter(var_id).any(|(_, n)| {
1299 #[allow(non_exhaustive_omitted_patterns)] match n {
hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::Match(.., hir::MatchSource::Normal), .. }) =>
true,
_ => false,
}matches!(
1300 n,
1301 hir::Node::Expr(hir::Expr {
1302 kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
1303 ..
1304 })
1305 )
1306 });
1307 let pre = if in_match { "in the same arm, " } else { "" };
1308 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"));
1309 self.suggest_adding_missing_ref_or_removing_ref(
1310 &mut err,
1311 span,
1312 var_ty,
1313 self.resolve_vars_if_possible(ty),
1314 ba,
1315 );
1316 err.emit();
1317 }
1318 }
1319
1320 fn suggest_adding_missing_ref_or_removing_ref(
1321 &self,
1322 err: &mut Diag<'_>,
1323 span: Span,
1324 expected: Ty<'tcx>,
1325 actual: Ty<'tcx>,
1326 ba: BindingMode,
1327 ) {
1328 match (expected.kind(), actual.kind(), ba) {
1329 (ty::Ref(_, inner_ty, _), _, BindingMode::NONE)
1330 if self.can_eq(self.param_env, *inner_ty, actual) =>
1331 {
1332 err.span_suggestion_verbose(
1333 span.shrink_to_lo(),
1334 "consider adding `ref`",
1335 "ref ",
1336 Applicability::MaybeIncorrect,
1337 );
1338 }
1339 (_, ty::Ref(_, inner_ty, _), BindingMode::REF)
1340 if self.can_eq(self.param_env, expected, *inner_ty) =>
1341 {
1342 err.span_suggestion_verbose(
1343 span.with_hi(span.lo() + BytePos(4)),
1344 "consider removing `ref`",
1345 "",
1346 Applicability::MaybeIncorrect,
1347 );
1348 }
1349 _ => (),
1350 }
1351 }
1352
1353 fn borrow_pat_suggestion(&self, err: &mut Diag<'_>, pat: &Pat<'_>) {
1355 let tcx = self.tcx;
1356 if let PatKind::Ref(inner, pinned, mutbl) = pat.kind
1357 && let PatKind::Binding(_, _, binding, ..) = inner.kind
1358 {
1359 let binding_parent = tcx.parent_hir_node(pat.hir_id);
1360 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:1360",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(1360u32),
::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);
1361
1362 let pin_and_mut = pinned.prefix_str(mutbl).trim_end();
1363
1364 let mut_var_suggestion = 'block: {
1365 if mutbl.is_not() {
1366 break 'block None;
1367 }
1368
1369 let ident_kind = match binding_parent {
1370 hir::Node::Param(_) => "parameter",
1371 hir::Node::LetStmt(_) => "variable",
1372 hir::Node::Arm(_) => "binding",
1373
1374 hir::Node::Pat(Pat { kind, .. }) => match kind {
1377 PatKind::Struct(..)
1378 | PatKind::TupleStruct(..)
1379 | PatKind::Or(..)
1380 | PatKind::Guard(..)
1381 | PatKind::Tuple(..)
1382 | PatKind::Slice(..) => "binding",
1383
1384 PatKind::Missing
1385 | PatKind::Wild
1386 | PatKind::Never
1387 | PatKind::Binding(..)
1388 | PatKind::Box(..)
1389 | PatKind::Deref(_)
1390 | PatKind::Ref(..)
1391 | PatKind::Expr(..)
1392 | PatKind::Range(..)
1393 | PatKind::Err(_) => break 'block None,
1394 },
1395
1396 _ => break 'block None,
1398 };
1399
1400 Some((
1401 pat.span,
1402 ::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"),
1403 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("mut {0}", binding))
})format!("mut {binding}"),
1404 ))
1405 };
1406
1407 match binding_parent {
1408 hir::Node::Param(hir::Param { ty_span, pat, .. })
1409 if pat.span != *ty_span
1410 && pinned.is_pinned()
1411 && !tcx.features().pin_ergonomics() =>
1412 {
1413 }
1416 hir::Node::Param(hir::Param { ty_span, pat, .. }) if pat.span != *ty_span => {
1419 err.multipart_suggestion(
1420 ::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"),
1421 ::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![
1422 (pat.span.until(inner.span), "".to_owned()),
1423 (ty_span.shrink_to_lo(), format!("&{}", pinned.prefix_str(mutbl))),
1424 ],
1425 Applicability::MachineApplicable
1426 );
1427
1428 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1429 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1430 }
1431 }
1432 hir::Node::Pat(pt) if let PatKind::TupleStruct(_, pat_arr, _) = pt.kind => {
1433 for i in pat_arr.iter() {
1434 if let PatKind::Ref(the_ref, _, _) = i.kind
1435 && let PatKind::Binding(mt, _, ident, _) = the_ref.kind
1436 {
1437 let BindingMode(_, mtblty) = mt;
1438 err.span_suggestion_verbose(
1439 i.span,
1440 ::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"),
1441 mtblty.prefix_str().to_string() + &ident.name.to_string(),
1442 Applicability::MaybeIncorrect,
1443 );
1444 }
1445 }
1446 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1447 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1448 }
1449 }
1450 hir::Node::Param(_) | hir::Node::Arm(_) | hir::Node::Pat(_) => {
1451 err.span_suggestion_verbose(
1453 pat.span.until(inner.span),
1454 ::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"),
1455 "",
1456 Applicability::MaybeIncorrect,
1457 );
1458
1459 if let Some((sp, msg, sugg)) = mut_var_suggestion {
1460 err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}`", msg, sugg))
})format!("{msg}: `{sugg}`"));
1461 }
1462 }
1463 _ if let Some((sp, msg, sugg)) = mut_var_suggestion => {
1464 err.span_suggestion(sp, msg, sugg, Applicability::MachineApplicable);
1465 }
1466 _ => {} }
1468 }
1469 }
1470
1471 fn check_dereferenceable(
1472 &self,
1473 span: Span,
1474 expected: Ty<'tcx>,
1475 inner: &Pat<'_>,
1476 ) -> Result<(), ErrorGuaranteed> {
1477 if let PatKind::Binding(..) = inner.kind
1478 && let Some(pointee_ty) = self.shallow_resolve(expected).builtin_deref(true)
1479 && let ty::Dynamic(..) = pointee_ty.kind()
1480 {
1481 let type_str = self.ty_to_string(expected);
1484 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!(
1485 self.dcx(),
1486 span,
1487 E0033,
1488 "type `{}` cannot be dereferenced",
1489 type_str
1490 );
1491 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"));
1492 if self.tcx.sess.teach(err.code.unwrap()) {
1493 err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
1494 }
1495 return Err(err.emit());
1496 }
1497 Ok(())
1498 }
1499
1500 fn resolve_pat_struct(
1501 &self,
1502 pat: &'tcx Pat<'tcx>,
1503 qpath: &hir::QPath<'tcx>,
1504 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1505 let (variant, pat_ty) = self.check_struct_path(qpath, pat.hir_id)?;
1507 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } })
1508 }
1509
1510 fn check_pin_projection(
1521 &self,
1522 pat: &'tcx Pat<'tcx>,
1523 pat_ty: Ty<'tcx>,
1524 pat_info: PatInfo<'tcx>,
1525 ) {
1526 let through_pin = pat_info.max_pinnedness == PinnednessCap::Pinned
1527 || #[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, _));
1528 if through_pin
1529 && let Some(adt) = pat_ty.ty_adt_def()
1530 && !adt.is_pin_project()
1531 && !adt.is_pin()
1532 {
1533 let def_span: Option<Span> = self.tcx.hir_span_if_local(adt.did());
1534 let sugg_span = def_span.map(|span| span.shrink_to_lo());
1535 self.dcx().emit_err(crate::diagnostics::ProjectOnNonPinProjectType {
1536 span: pat.span,
1537 def_span,
1538 sugg_span,
1539 });
1540 }
1541 }
1542
1543 fn check_pat_struct(
1544 &self,
1545 pat: &'tcx Pat<'tcx>,
1546 fields: &'tcx [hir::PatField<'tcx>],
1547 has_rest_pat: bool,
1548 pat_ty: Ty<'tcx>,
1549 variant: &'tcx VariantDef,
1550 expected: Ty<'tcx>,
1551 pat_info: PatInfo<'tcx>,
1552 ) -> Ty<'tcx> {
1553 self.check_pin_projection(pat, pat_ty, pat_info);
1554
1555 let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1557
1558 match self.check_struct_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info) {
1560 Ok(()) => match had_err {
1561 Ok(()) => pat_ty,
1562 Err(guar) => Ty::new_error(self.tcx, guar),
1563 },
1564 Err(guar) => Ty::new_error(self.tcx, guar),
1565 }
1566 }
1567
1568 fn resolve_pat_path(
1569 &self,
1570 path_id: HirId,
1571 span: Span,
1572 qpath: &'tcx hir::QPath<'_>,
1573 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1574 let tcx = self.tcx;
1575
1576 let (res, opt_ty, segments) =
1577 self.resolve_ty_and_res_fully_qualified_call(qpath, path_id, span);
1578 match res {
1579 Res::Err => {
1580 let e =
1581 self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
1582 self.set_tainted_by_errors(e);
1583 return Err(e);
1584 }
1585 Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Variant, _) => {
1586 let expected = "unit struct, unit variant or constant";
1587 let e = self.report_unexpected_variant_res(
1588 res,
1589 None,
1590 &[],
1591 qpath,
1592 span,
1593 E0533,
1594 expected,
1595 );
1596 return Err(e);
1597 }
1598 Res::SelfCtor(def_id) => {
1599 if let ty::Adt(adt_def, _) = *tcx.type_of(def_id).skip_binder().kind()
1600 && adt_def.is_struct()
1601 && let Some((CtorKind::Const, _)) = adt_def.non_enum_variant().ctor
1602 {
1603 } else {
1605 let e = self.report_unexpected_variant_res(
1606 res,
1607 None,
1608 &[],
1609 qpath,
1610 span,
1611 E0533,
1612 "unit struct",
1613 );
1614 return Err(e);
1615 }
1616 }
1617 Res::Def(
1618 DefKind::Ctor(_, CtorKind::Const)
1619 | DefKind::Const { .. }
1620 | DefKind::AssocConst { .. }
1621 | DefKind::ConstParam,
1622 _,
1623 ) => {} _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected pattern resolution: {0:?}",
res))bug!("unexpected pattern resolution: {:?}", res),
1625 }
1626
1627 let (pat_ty, pat_res) =
1629 self.instantiate_value_path(segments, opt_ty, res, span, span, path_id);
1630 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res, pat_res, segments } })
1631 }
1632
1633 fn check_pat_path(
1634 &self,
1635 pat_id_for_diag: HirId,
1636 span: Span,
1637 resolved: &ResolvedPat<'tcx>,
1638 expected: Ty<'tcx>,
1639 ti: &TopInfo<'tcx>,
1640 ) -> Ty<'tcx> {
1641 if let Err(err) =
1642 self.demand_suptype_with_origin(&self.pattern_cause(ti, span), expected, resolved.ty)
1643 {
1644 self.emit_bad_pat_path(err, pat_id_for_diag, span, resolved);
1645 }
1646 resolved.ty
1647 }
1648
1649 fn maybe_suggest_range_literal(
1650 &self,
1651 e: &mut Diag<'_>,
1652 opt_def_id: Option<hir::def_id::DefId>,
1653 ident: Ident,
1654 ) -> bool {
1655 if let Some(def_id) = opt_def_id
1656 && let Some(hir::Node::Item(hir::Item {
1657 kind: hir::ItemKind::Const(_, _, _, ct_rhs),
1658 ..
1659 })) = self.tcx.hir_get_if_local(def_id)
1660 && let hir::Node::Expr(expr) = self.tcx.hir_node(ct_rhs.hir_id())
1661 && hir::is_range_literal(expr)
1662 {
1663 let span = self.tcx.hir_span(ct_rhs.hir_id());
1664 if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
1665 e.span_suggestion_verbose(
1666 ident.span,
1667 "you may want to move the range into the match block",
1668 snip,
1669 Applicability::MachineApplicable,
1670 );
1671 return true;
1672 }
1673 }
1674 false
1675 }
1676
1677 fn emit_bad_pat_path(
1678 &self,
1679 mut e: Diag<'_>,
1680 hir_id: HirId,
1681 pat_span: Span,
1682 resolved_pat: &ResolvedPat<'tcx>,
1683 ) {
1684 let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind else {
1685 ::rustc_middle::util::bug::span_bug_fmt(pat_span,
format_args!("unexpected resolution for path pattern: {0:?}",
resolved_pat));span_bug!(pat_span, "unexpected resolution for path pattern: {resolved_pat:?}");
1686 };
1687
1688 let span = match (self.tcx.hir_res_span(pat_res), res.opt_def_id()) {
1689 (Some(span), _) => span,
1690 (None, Some(def_id)) => self.tcx.def_span(def_id),
1691 (None, None) => {
1692 e.emit();
1693 return;
1694 }
1695 };
1696 if let [hir::PathSegment { ident, args: None, .. }] = segments
1697 && e.suggestions.len() == 0
1698 {
1699 e.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} defined here", res.descr()))
})format!("{} defined here", res.descr()));
1700 e.span_label(
1701 pat_span,
1702 ::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!(
1703 "`{}` is interpreted as {} {}, not a new binding",
1704 ident,
1705 res.article(),
1706 res.descr(),
1707 ),
1708 );
1709 match self.tcx.parent_hir_node(hir_id) {
1710 hir::Node::PatField(..) => {
1711 e.span_suggestion_verbose(
1712 ident.span.shrink_to_hi(),
1713 "bind the struct field to a different name instead",
1714 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": other_{0}",
ident.as_str().to_lowercase()))
})format!(": other_{}", ident.as_str().to_lowercase()),
1715 Applicability::HasPlaceholders,
1716 );
1717 }
1718 _ => {
1719 let (type_def_id, item_def_id) = match resolved_pat.ty.kind() {
1720 ty::Adt(def, _) => match res {
1721 Res::Def(DefKind::Const { .. }, def_id) => {
1722 (Some(def.did()), Some(def_id))
1723 }
1724 _ => (None, None),
1725 },
1726 _ => (None, None),
1727 };
1728
1729 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!(
1730 type_def_id.and_then(|id| self.tcx.as_lang_item(id)),
1731 Some(
1732 LangItem::Range
1733 | LangItem::RangeFrom
1734 | LangItem::RangeTo
1735 | LangItem::RangeFull
1736 | LangItem::RangeInclusiveStruct
1737 | LangItem::RangeToInclusive,
1738 )
1739 );
1740 if is_range {
1741 if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
1742 let msg = "constants only support matching by type, \
1743 if you meant to match against a range of values, \
1744 consider using a range pattern like `min ..= max` in the match block";
1745 e.note(msg);
1746 }
1747 } else {
1748 let msg = "introduce a new binding instead";
1749 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());
1750 e.span_suggestion_verbose(
1751 ident.span,
1752 msg,
1753 sugg,
1754 Applicability::HasPlaceholders,
1755 );
1756 }
1757 }
1758 };
1759 }
1760 e.emit();
1761 }
1762
1763 fn resolve_pat_tuple_struct(
1764 &self,
1765 pat: &'tcx Pat<'tcx>,
1766 qpath: &'tcx hir::QPath<'tcx>,
1767 ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1768 let tcx = self.tcx;
1769 let report_unexpected_res = |res: Res| {
1770 let expected = "tuple struct or tuple variant";
1771 let sub_pats = match pat.kind {
1772 hir::PatKind::TupleStruct(_, sub_pats, _) => sub_pats,
1773 _ => &[],
1774 };
1775 let e = self.report_unexpected_variant_res(
1776 res, None, sub_pats, qpath, pat.span, E0164, expected,
1777 );
1778 Err(e)
1779 };
1780
1781 let (res, opt_ty, segments) =
1783 self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span);
1784 if res == Res::Err {
1785 let e = self.dcx().span_delayed_bug(pat.span, "`Res::Err` but no error emitted");
1786 self.set_tainted_by_errors(e);
1787 return Err(e);
1788 }
1789
1790 let (pat_ty, res) =
1792 self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.span, pat.hir_id);
1793 if !pat_ty.is_fn() {
1794 return report_unexpected_res(res);
1795 }
1796
1797 let variant = match res {
1798 Res::Err => {
1799 self.dcx().span_bug(pat.span, "`Res::Err` but no error emitted");
1800 }
1801 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) => {
1802 return report_unexpected_res(res);
1803 }
1804 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
1805 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected pattern resolution: {0:?}",
res))bug!("unexpected pattern resolution: {:?}", res),
1806 };
1807
1808 let pat_ty = pat_ty.fn_sig(tcx).output();
1810 let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
1811
1812 Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { res, variant } })
1813 }
1814
1815 fn check_pat_tuple_struct(
1816 &self,
1817 pat: &'tcx Pat<'tcx>,
1818 qpath: &'tcx hir::QPath<'tcx>,
1819 subpats: &'tcx [Pat<'tcx>],
1820 ddpos: hir::DotDotPos,
1821 res: Res,
1822 pat_ty: Ty<'tcx>,
1823 variant: &'tcx VariantDef,
1824 expected: Ty<'tcx>,
1825 pat_info: PatInfo<'tcx>,
1826 ) -> Ty<'tcx> {
1827 self.check_pin_projection(pat, pat_ty, pat_info);
1828
1829 let tcx = self.tcx;
1830 let on_error = |e| {
1831 for pat in subpats {
1832 self.check_pat(pat, Ty::new_error(tcx, e), pat_info);
1833 }
1834 };
1835
1836 let had_err = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1838
1839 if subpats.len() == variant.fields.len()
1841 || subpats.len() < variant.fields.len() && ddpos.as_opt_usize().is_some()
1842 {
1843 let ty::Adt(_, args) = pat_ty.kind() else {
1844 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected pattern type {0:?}",
pat_ty));bug!("unexpected pattern type {:?}", pat_ty);
1845 };
1846 for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
1847 let field = &variant.fields[FieldIdx::from_usize(i)];
1848 let field_ty = self.field_ty(subpat.span, field, args);
1849 self.check_pat(subpat, field_ty, pat_info);
1850
1851 self.tcx.check_stability(
1852 variant.fields[FieldIdx::from_usize(i)].did,
1853 Some(subpat.hir_id),
1854 subpat.span,
1855 None,
1856 );
1857 }
1858 if let Err(e) = had_err {
1859 on_error(e);
1860 return Ty::new_error(tcx, e);
1861 }
1862 } else {
1863 let e = self.emit_err_pat_wrong_number_of_fields(
1864 pat.span,
1865 res,
1866 qpath,
1867 subpats,
1868 &variant.fields.raw,
1869 expected,
1870 had_err,
1871 );
1872 on_error(e);
1873 return Ty::new_error(tcx, e);
1874 }
1875 pat_ty
1876 }
1877
1878 fn emit_err_pat_wrong_number_of_fields(
1879 &self,
1880 pat_span: Span,
1881 res: Res,
1882 qpath: &hir::QPath<'_>,
1883 subpats: &'tcx [Pat<'tcx>],
1884 fields: &'tcx [ty::FieldDef],
1885 expected: Ty<'tcx>,
1886 had_err: Result<(), ErrorGuaranteed>,
1887 ) -> ErrorGuaranteed {
1888 let subpats_ending = if subpats.len() == 1 { "" } else { "s" }pluralize!(subpats.len());
1889 let fields_ending = if fields.len() == 1 { "" } else { "s" }pluralize!(fields.len());
1890
1891 let subpat_spans = if subpats.is_empty() {
1892 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[pat_span]))vec![pat_span]
1893 } else {
1894 subpats.iter().map(|p| p.span).collect()
1895 };
1896 let last_subpat_span = *subpat_spans.last().unwrap();
1897 let res_span = self.tcx.def_span(res.def_id());
1898 let def_ident_span = self.tcx.def_ident_span(res.def_id()).unwrap_or(res_span);
1899 let field_def_spans = if fields.is_empty() {
1900 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[res_span]))vec![res_span]
1901 } else {
1902 fields.iter().map(|f| f.ident(self.tcx).span).collect()
1903 };
1904 let last_field_def_span = *field_def_spans.last().unwrap();
1905
1906 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!(
1907 self.dcx(),
1908 MultiSpan::from_spans(subpat_spans),
1909 E0023,
1910 "this pattern has {} field{}, but the corresponding {} has {} field{}",
1911 subpats.len(),
1912 subpats_ending,
1913 res.descr(),
1914 fields.len(),
1915 fields_ending,
1916 );
1917 err.span_label(
1918 last_subpat_span,
1919 ::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()),
1920 );
1921 if self.tcx.sess.source_map().is_multiline(qpath.span().between(last_subpat_span)) {
1922 err.span_label(qpath.span(), "");
1923 }
1924 if self.tcx.sess.source_map().is_multiline(def_ident_span.between(last_field_def_span)) {
1925 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()));
1926 }
1927 for span in &field_def_spans[..field_def_spans.len() - 1] {
1928 err.span_label(*span, "");
1929 }
1930 err.span_label(
1931 last_field_def_span,
1932 ::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),
1933 );
1934
1935 let missing_parentheses = match (expected.kind(), fields, had_err) {
1940 (ty::Adt(_, args), [field], Ok(())) => {
1944 let field_ty = self.field_ty(pat_span, field, args);
1945 match field_ty.kind() {
1946 ty::Tuple(fields) => fields.len() == subpats.len(),
1947 _ => false,
1948 }
1949 }
1950 _ => false,
1951 };
1952 if missing_parentheses {
1953 let (left, right) = match subpats {
1954 [] => (qpath.span().shrink_to_hi(), pat_span),
1963 [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
1972 };
1973 err.multipart_suggestion(
1974 "missing parentheses",
1975 ::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())],
1976 Applicability::MachineApplicable,
1977 );
1978 } else if fields.len() > subpats.len() && pat_span != DUMMY_SP {
1979 let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi();
1980 let all_fields_span = match subpats {
1981 [] => after_fields_span,
1982 [field] => field.span,
1983 [first, .., last] => first.span.to(last.span),
1984 };
1985
1986 let all_wildcards = subpats.iter().all(|pat| #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
PatKind::Wild => true,
_ => false,
}matches!(pat.kind, PatKind::Wild));
1988 let first_tail_wildcard =
1989 subpats.iter().enumerate().fold(None, |acc, (pos, pat)| match (acc, &pat.kind) {
1990 (None, PatKind::Wild) => Some(pos),
1991 (Some(_), PatKind::Wild) => acc,
1992 _ => None,
1993 });
1994 let tail_span = match first_tail_wildcard {
1995 None => after_fields_span,
1996 Some(0) => subpats[0].span.to(after_fields_span),
1997 Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span),
1998 };
1999
2000 let mut wildcard_sugg = ::alloc::vec::from_elem("_", fields.len() - subpats.len())vec!["_"; fields.len() - subpats.len()].join(", ");
2002 if !subpats.is_empty() {
2003 wildcard_sugg = String::from(", ") + &wildcard_sugg;
2004 }
2005
2006 err.span_suggestion_verbose(
2007 after_fields_span,
2008 "use `_` to explicitly ignore each field",
2009 wildcard_sugg,
2010 Applicability::MaybeIncorrect,
2011 );
2012
2013 if fields.len() - subpats.len() > 1 || all_wildcards {
2016 if subpats.is_empty() || all_wildcards {
2017 err.span_suggestion_verbose(
2018 all_fields_span,
2019 "use `..` to ignore all fields",
2020 "..",
2021 Applicability::MaybeIncorrect,
2022 );
2023 } else {
2024 err.span_suggestion_verbose(
2025 tail_span,
2026 "use `..` to ignore the rest of the fields",
2027 ", ..",
2028 Applicability::MaybeIncorrect,
2029 );
2030 }
2031 }
2032 }
2033
2034 err.emit()
2035 }
2036
2037 fn check_pat_tuple(
2038 &self,
2039 span: Span,
2040 elements: &'tcx [Pat<'tcx>],
2041 ddpos: hir::DotDotPos,
2042 expected: Ty<'tcx>,
2043 pat_info: PatInfo<'tcx>,
2044 ) -> Ty<'tcx> {
2045 let tcx = self.tcx;
2046 let mut expected_len = elements.len();
2047 if ddpos.as_opt_usize().is_some() {
2048 if let ty::Tuple(tys) = self.structurally_resolve_type(span, expected).kind() {
2050 expected_len = tys.len();
2051 }
2052 }
2053 let max_len = cmp::max(expected_len, elements.len());
2054
2055 let element_tys_iter = (0..max_len).map(|_| self.next_ty_var(span));
2056 let element_tys = tcx.mk_type_list_from_iter(element_tys_iter);
2057 let pat_ty = Ty::new_tup(tcx, element_tys);
2058 if let Err(reported) = self.demand_eqtype_pat(span, expected, pat_ty, &pat_info.top_info) {
2059 for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
2062 self.check_pat(elem, Ty::new_error(tcx, reported), pat_info);
2063 }
2064 Ty::new_error(tcx, reported)
2065 } else {
2066 for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
2067 self.check_pat(elem, element_tys[i], pat_info);
2068 }
2069 pat_ty
2070 }
2071 }
2072
2073 fn check_struct_pat_fields(
2074 &self,
2075 adt_ty: Ty<'tcx>,
2076 pat: &'tcx Pat<'tcx>,
2077 variant: &'tcx ty::VariantDef,
2078 fields: &'tcx [hir::PatField<'tcx>],
2079 has_rest_pat: bool,
2080 pat_info: PatInfo<'tcx>,
2081 ) -> Result<(), ErrorGuaranteed> {
2082 let tcx = self.tcx;
2083
2084 let ty::Adt(adt, args) = adt_ty.kind() else {
2085 ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("struct pattern is not an ADT"));span_bug!(pat.span, "struct pattern is not an ADT");
2086 };
2087
2088 let field_map = variant
2090 .fields
2091 .iter_enumerated()
2092 .map(|(i, field)| (field.ident(self.tcx).normalize_to_macros_2_0(), (i, field)))
2093 .collect::<FxHashMap<_, _>>();
2094
2095 let mut used_fields = FxHashMap::default();
2097 let mut result = Ok(());
2098
2099 let mut inexistent_fields = ::alloc::vec::Vec::new()vec![];
2100 for field in fields {
2102 let span = field.span;
2103 let ident = tcx.adjust_ident(field.ident, variant.def_id);
2104 let field_ty = match used_fields.entry(ident) {
2105 Occupied(occupied) => {
2106 let guar = self.error_field_already_bound(span, field.ident, *occupied.get());
2107 result = Err(guar);
2108 Ty::new_error(tcx, guar)
2109 }
2110 Vacant(vacant) => {
2111 vacant.insert(span);
2112 field_map
2113 .get(&ident)
2114 .map(|(i, f)| {
2115 self.write_field_index(field.hir_id, *i);
2116 self.tcx.check_stability(f.did, Some(field.hir_id), span, None);
2117 self.field_ty(span, f, args)
2118 })
2119 .unwrap_or_else(|| {
2120 inexistent_fields.push(field);
2121 Ty::new_misc_error(tcx)
2122 })
2123 }
2124 };
2125
2126 self.check_pat(field.pat, field_ty, pat_info);
2127 }
2128
2129 let mut unmentioned_fields = variant
2130 .fields
2131 .iter()
2132 .map(|field| (field, field.ident(self.tcx).normalize_to_macros_2_0()))
2133 .filter(|(_, ident)| !used_fields.contains_key(ident))
2134 .collect::<Vec<_>>();
2135
2136 let inexistent_fields_err = if !inexistent_fields.is_empty()
2137 && !inexistent_fields.iter().any(|field| field.ident.name == kw::Underscore)
2138 {
2139 variant.has_errors()?;
2141 Some(self.error_inexistent_fields(
2142 adt.variant_descr(),
2143 &inexistent_fields,
2144 &mut unmentioned_fields,
2145 pat,
2146 variant,
2147 args,
2148 ))
2149 } else {
2150 None
2151 };
2152
2153 let non_exhaustive = variant.field_list_has_applicable_non_exhaustive();
2155 if non_exhaustive && !has_rest_pat {
2156 self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
2157 }
2158
2159 let mut unmentioned_err = None;
2160 if adt.is_union() {
2162 if fields.len() != 1 {
2163 self.dcx().emit_err(diagnostics::UnionPatMultipleFields { span: pat.span });
2164 }
2165 if has_rest_pat {
2166 self.dcx().emit_err(diagnostics::UnionPatDotDot { span: pat.span });
2167 }
2168 } else if !unmentioned_fields.is_empty() {
2169 let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
2170 .iter()
2171 .copied()
2172 .filter(|(field, _)| self.is_field_suggestable(field, pat.hir_id, pat.span))
2173 .collect();
2174
2175 if !has_rest_pat {
2176 if accessible_unmentioned_fields.is_empty() {
2177 unmentioned_err = Some(self.error_no_accessible_fields(pat, fields));
2178 } else {
2179 unmentioned_err = Some(self.error_unmentioned_fields(
2180 pat,
2181 &accessible_unmentioned_fields,
2182 accessible_unmentioned_fields.len() != unmentioned_fields.len(),
2183 fields,
2184 ));
2185 }
2186 } else if non_exhaustive && !accessible_unmentioned_fields.is_empty() {
2187 self.lint_non_exhaustive_omitted_patterns(
2188 pat,
2189 &accessible_unmentioned_fields,
2190 adt_ty,
2191 )
2192 }
2193 }
2194 match (inexistent_fields_err, unmentioned_err) {
2195 (Some(i), Some(u)) => {
2196 if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2197 i.delay_as_bug();
2200 u.delay_as_bug();
2201 Err(e)
2202 } else {
2203 i.emit();
2204 Err(u.emit())
2205 }
2206 }
2207 (None, Some(u)) => {
2208 if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2209 u.delay_as_bug();
2210 Err(e)
2211 } else {
2212 Err(u.emit())
2213 }
2214 }
2215 (Some(err), None) => Err(err.emit()),
2216 (None, None) => {
2217 self.error_tuple_variant_index_shorthand(variant, pat, fields)?;
2218 result
2219 }
2220 }
2221 }
2222
2223 fn error_tuple_variant_index_shorthand(
2224 &self,
2225 variant: &VariantDef,
2226 pat: &'_ Pat<'_>,
2227 fields: &[hir::PatField<'_>],
2228 ) -> Result<(), ErrorGuaranteed> {
2229 if let (Some(CtorKind::Fn), PatKind::Struct(qpath, field_patterns, ..)) =
2233 (variant.ctor_kind(), &pat.kind)
2234 {
2235 let has_shorthand_field_name = field_patterns.iter().any(|field| field.is_shorthand);
2236 if has_shorthand_field_name {
2237 let path = rustc_hir_pretty::qpath_to_string(self, qpath);
2238 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!(
2239 self.dcx(),
2240 pat.span,
2241 E0769,
2242 "tuple variant `{path}` written as struct variant",
2243 );
2244 err.span_suggestion_verbose(
2245 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2246 "use the tuple variant pattern syntax instead",
2247 ::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)),
2248 Applicability::MaybeIncorrect,
2249 );
2250 return Err(err.emit());
2251 }
2252 }
2253 Ok(())
2254 }
2255
2256 fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
2257 let sess = self.tcx.sess;
2258 let sm = sess.source_map();
2259 let sp_brace = sm.end_point(pat.span);
2260 let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
2261 let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
2262
2263 {
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!(
2264 self.dcx(),
2265 pat.span,
2266 E0638,
2267 "`..` required with {descr} marked as non-exhaustive",
2268 )
2269 .with_span_suggestion_verbose(
2270 sp_comma,
2271 "add `..` at the end of the field list to ignore all other fields",
2272 sugg,
2273 Applicability::MachineApplicable,
2274 )
2275 .emit();
2276 }
2277
2278 fn error_field_already_bound(
2279 &self,
2280 span: Span,
2281 ident: Ident,
2282 other_field: Span,
2283 ) -> ErrorGuaranteed {
2284 {
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!(
2285 self.dcx(),
2286 span,
2287 E0025,
2288 "field `{}` bound multiple times in the pattern",
2289 ident
2290 )
2291 .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"))
2292 .with_span_label(other_field, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("first use of `{0}`", ident))
})format!("first use of `{ident}`"))
2293 .emit()
2294 }
2295
2296 fn error_inexistent_fields(
2297 &self,
2298 kind_name: &str,
2299 inexistent_fields: &[&hir::PatField<'tcx>],
2300 unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>,
2301 pat: &'tcx Pat<'tcx>,
2302 variant: &ty::VariantDef,
2303 args: ty::GenericArgsRef<'tcx>,
2304 ) -> Diag<'a> {
2305 let tcx = self.tcx;
2306 let (field_names, t, plural) = if let [field] = inexistent_fields {
2307 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a field named `{0}`", field.ident))
})format!("a field named `{}`", field.ident), "this", "")
2308 } else {
2309 (
2310 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields named {0}",
inexistent_fields.iter().map(|field|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", field.ident))
})).collect::<Vec<String>>().join(", ")))
})format!(
2311 "fields named {}",
2312 inexistent_fields
2313 .iter()
2314 .map(|field| format!("`{}`", field.ident))
2315 .collect::<Vec<String>>()
2316 .join(", ")
2317 ),
2318 "these",
2319 "s",
2320 )
2321 };
2322 let spans = inexistent_fields.iter().map(|field| field.ident.span).collect::<Vec<_>>();
2323 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!(
2324 self.dcx(),
2325 spans,
2326 E0026,
2327 "{} `{}` does not have {}",
2328 kind_name,
2329 tcx.def_path_str(variant.def_id),
2330 field_names
2331 );
2332 if let Some(pat_field) = inexistent_fields.last() {
2333 err.span_label(
2334 pat_field.ident.span,
2335 ::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!(
2336 "{} `{}` does not have {} field{}",
2337 kind_name,
2338 tcx.def_path_str(variant.def_id),
2339 t,
2340 plural
2341 ),
2342 );
2343
2344 if let [(field_def, field)] = unmentioned_fields.as_slice()
2345 && self.is_field_suggestable(field_def, pat.hir_id, pat.span)
2346 {
2347 let suggested_name =
2348 find_best_match_for_name(&[field.name], pat_field.ident.name, None);
2349 if let Some(suggested_name) = suggested_name {
2350 err.span_suggestion_verbose(
2351 pat_field.ident.span,
2352 "a field with a similar name exists",
2353 suggested_name,
2354 Applicability::MaybeIncorrect,
2355 );
2356
2357 if suggested_name.to_ident_string().parse::<usize>().is_err() {
2363 unmentioned_fields.retain(|&(_, x)| x.name != suggested_name);
2365 }
2366 } else if inexistent_fields.len() == 1 {
2367 match pat_field.pat.kind {
2368 PatKind::Expr(_)
2369 if !self.may_coerce(
2370 self.typeck_results.borrow().node_type(pat_field.pat.hir_id),
2371 self.field_ty(field.span, field_def, args),
2372 ) => {}
2373 _ => {
2374 err.span_suggestion_short(
2375 pat_field.ident.span,
2376 ::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!(
2377 "`{}` has a field named `{}`",
2378 tcx.def_path_str(variant.def_id),
2379 field.name,
2380 ),
2381 field.name,
2382 Applicability::MaybeIncorrect,
2383 );
2384 }
2385 }
2386 }
2387 }
2388 }
2389 if tcx.sess.teach(err.code.unwrap()) {
2390 err.note(
2391 "This error indicates that a struct pattern attempted to \
2392 extract a nonexistent field from a struct. Struct fields \
2393 are identified by the name used before the colon : so struct \
2394 patterns should resemble the declaration of the struct type \
2395 being matched.\n\n\
2396 If you are using shorthand field patterns but want to refer \
2397 to the struct field by a different name, you should rename \
2398 it explicitly.",
2399 );
2400 }
2401 err
2402 }
2403
2404 fn error_tuple_variant_as_struct_pat(
2405 &self,
2406 pat: &Pat<'_>,
2407 fields: &'tcx [hir::PatField<'tcx>],
2408 variant: &ty::VariantDef,
2409 ) -> Result<(), ErrorGuaranteed> {
2410 if let (Some(CtorKind::Fn), PatKind::Struct(qpath, pattern_fields, ..)) =
2411 (variant.ctor_kind(), &pat.kind)
2412 {
2413 let is_tuple_struct_match = !pattern_fields.is_empty()
2414 && pattern_fields.iter().map(|field| field.ident.name.as_str()).all(is_number);
2415 if is_tuple_struct_match {
2416 return Ok(());
2417 }
2418
2419 variant.has_errors()?;
2421
2422 let path = rustc_hir_pretty::qpath_to_string(self, qpath);
2423 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!(
2424 self.dcx(),
2425 pat.span,
2426 E0769,
2427 "tuple variant `{}` written as struct variant",
2428 path
2429 );
2430 let (sugg, appl) = if fields.len() == variant.fields.len() {
2431 (
2432 self.get_suggested_tuple_struct_pattern(fields, variant),
2433 Applicability::MachineApplicable,
2434 )
2435 } else {
2436 (
2437 variant.fields.iter().map(|_| "_").collect::<Vec<&str>>().join(", "),
2438 Applicability::MaybeIncorrect,
2439 )
2440 };
2441 err.span_suggestion_verbose(
2442 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2443 "use the tuple variant pattern syntax instead",
2444 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", sugg))
})format!("({sugg})"),
2445 appl,
2446 );
2447 return Err(err.emit());
2448 }
2449 Ok(())
2450 }
2451
2452 fn get_suggested_tuple_struct_pattern(
2453 &self,
2454 fields: &[hir::PatField<'_>],
2455 variant: &VariantDef,
2456 ) -> String {
2457 let variant_field_idents =
2458 variant.fields.iter().map(|f| f.ident(self.tcx)).collect::<Vec<Ident>>();
2459 fields
2460 .iter()
2461 .map(|field| {
2462 match self.tcx.sess.source_map().span_to_snippet(field.pat.span) {
2463 Ok(f) => {
2464 if variant_field_idents.contains(&field.ident) {
2467 String::from("_")
2468 } else {
2469 f
2470 }
2471 }
2472 Err(_) => rustc_hir_pretty::pat_to_string(self, field.pat),
2473 }
2474 })
2475 .collect::<Vec<String>>()
2476 .join(", ")
2477 }
2478
2479 fn error_no_accessible_fields(
2495 &self,
2496 pat: &Pat<'_>,
2497 fields: &'tcx [hir::PatField<'tcx>],
2498 ) -> Diag<'a> {
2499 let mut err = self
2500 .dcx()
2501 .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
2502
2503 if let Some(field) = fields.last() {
2504 let tail_span = field.span.shrink_to_hi().to(pat.span.shrink_to_hi());
2505 let comma_hi_offset =
2506 self.tcx.sess.source_map().span_to_snippet(tail_span).ok().and_then(|snippet| {
2507 let trimmed = snippet.trim_start();
2508 trimmed.starts_with(',').then(|| (snippet.len() - trimmed.len() + 1) as u32)
2509 });
2510 err.span_suggestion_verbose(
2511 if let Some(comma_hi_offset) = comma_hi_offset {
2512 tail_span.with_hi(tail_span.lo() + BytePos(comma_hi_offset)).shrink_to_hi()
2513 } else {
2514 field.span.shrink_to_hi()
2515 },
2516 "ignore the inaccessible and unused fields",
2517 if comma_hi_offset.is_some() { " .." } else { ", .." },
2518 Applicability::MachineApplicable,
2519 );
2520 } else {
2521 let qpath_span = if let PatKind::Struct(qpath, ..) = &pat.kind {
2522 qpath.span()
2523 } else {
2524 ::rustc_middle::util::bug::bug_fmt(format_args!("`error_no_accessible_fields` called on non-struct pattern"));bug!("`error_no_accessible_fields` called on non-struct pattern");
2525 };
2526
2527 let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi());
2529 err.span_suggestion_verbose(
2530 span,
2531 "ignore the inaccessible and unused fields",
2532 " { .. }",
2533 Applicability::MachineApplicable,
2534 );
2535 }
2536 err
2537 }
2538
2539 fn lint_non_exhaustive_omitted_patterns(
2544 &self,
2545 pat: &Pat<'_>,
2546 unmentioned_fields: &[(&ty::FieldDef, Ident)],
2547 ty: Ty<'tcx>,
2548 ) {
2549 struct FieldsNotListed<'a, 'b, 'tcx> {
2550 pat_span: Span,
2551 unmentioned_fields: &'a [(&'b ty::FieldDef, Ident)],
2552 joined_patterns: String,
2553 ty: Ty<'tcx>,
2554 }
2555
2556 impl<'a, 'b, 'c, 'tcx> Diagnostic<'a, ()> for FieldsNotListed<'b, 'c, 'tcx> {
2557 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
2558 let Self { pat_span, unmentioned_fields, joined_patterns, ty } = self;
2559 Diag::new(dcx, level, "some fields are not explicitly listed")
2560 .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))
2561 .with_help(
2562 "ensure that all fields are mentioned explicitly by adding the suggested fields",
2563 )
2564 .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!(
2565 "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
2566 ))
2567 }
2568 }
2569
2570 fn joined_uncovered_patterns(witnesses: &[&Ident]) -> String {
2571 const LIMIT: usize = 3;
2572 match witnesses {
2573 [] => {
2574 {
::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!(
2575 "expected an uncovered pattern, otherwise why are we emitting an error?"
2576 )
2577 }
2578 [witness] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", witness))
})format!("`{witness}`"),
2579 [head @ .., tail] if head.len() < LIMIT => {
2580 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2581 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`",
head.join("`, `"), tail))
})format!("`{}` and `{}`", head.join("`, `"), tail)
2582 }
2583 _ => {
2584 let (head, tail) = witnesses.split_at(LIMIT);
2585 let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2586 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and {1} more",
head.join("`, `"), tail.len()))
})format!("`{}` and {} more", head.join("`, `"), tail.len())
2587 }
2588 }
2589 }
2590 let joined_patterns = joined_uncovered_patterns(
2591 &unmentioned_fields.iter().map(|(_, i)| i).collect::<Vec<_>>(),
2592 );
2593
2594 self.tcx.emit_node_span_lint(
2595 NON_EXHAUSTIVE_OMITTED_PATTERNS,
2596 pat.hir_id,
2597 pat.span,
2598 FieldsNotListed { pat_span: pat.span, unmentioned_fields, joined_patterns, ty },
2599 );
2600 }
2601
2602 fn error_unmentioned_fields(
2612 &self,
2613 pat: &Pat<'_>,
2614 unmentioned_fields: &[(&ty::FieldDef, Ident)],
2615 have_inaccessible_fields: bool,
2616 fields: &'tcx [hir::PatField<'tcx>],
2617 ) -> Diag<'a> {
2618 let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
2619 let field_names = if let [(_, field)] = unmentioned_fields {
2620 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}`{1}", field,
inaccessible))
})format!("field `{field}`{inaccessible}")
2621 } else {
2622 let fields = unmentioned_fields
2623 .iter()
2624 .map(|(_, name)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})format!("`{name}`"))
2625 .collect::<Vec<String>>()
2626 .join(", ");
2627 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("fields {0}{1}", fields,
inaccessible))
})format!("fields {fields}{inaccessible}")
2628 };
2629 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!(
2630 self.dcx(),
2631 pat.span,
2632 E0027,
2633 "pattern does not mention {}",
2634 field_names
2635 );
2636 err.span_label(pat.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing {0}", field_names))
})format!("missing {field_names}"));
2637 let len = unmentioned_fields.len();
2638 let (prefix, postfix, sp) = match fields {
2639 [] => match &pat.kind {
2640 PatKind::Struct(path, [], None) => {
2641 (" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi()))
2642 }
2643 _ => return err,
2644 },
2645 [.., field] => {
2646 let tail = field.span.shrink_to_hi().with_hi(pat.span.hi());
2649 match &pat.kind {
2650 PatKind::Struct(..) => (", ", " }", tail),
2651 _ => return err,
2652 }
2653 }
2654 };
2655 err.span_suggestion(
2656 sp,
2657 ::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!(
2658 "include the missing field{} in the pattern{}",
2659 pluralize!(len),
2660 if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
2661 ),
2662 ::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!(
2663 "{}{}{}{}",
2664 prefix,
2665 unmentioned_fields
2666 .iter()
2667 .map(|(_, name)| {
2668 let field_name = name.to_string();
2669 if is_number(&field_name) { format!("{field_name}: _") } else { field_name }
2670 })
2671 .collect::<Vec<_>>()
2672 .join(", "),
2673 if have_inaccessible_fields { ", .." } else { "" },
2674 postfix,
2675 ),
2676 Applicability::MachineApplicable,
2677 );
2678 err.span_suggestion(
2679 sp,
2680 ::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!(
2681 "if you don't care about {these} missing field{s}, you can explicitly ignore {them}",
2682 these = pluralize!("this", len),
2683 s = pluralize!(len),
2684 them = if len == 1 { "it" } else { "them" },
2685 ),
2686 ::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!(
2687 "{}{}{}{}",
2688 prefix,
2689 unmentioned_fields
2690 .iter()
2691 .map(|(_, name)| {
2692 let field_name = name.to_string();
2693 format!("{field_name}: _")
2694 })
2695 .collect::<Vec<_>>()
2696 .join(", "),
2697 if have_inaccessible_fields { ", .." } else { "" },
2698 postfix,
2699 ),
2700 Applicability::MachineApplicable,
2701 );
2702 err.span_suggestion(
2703 sp,
2704 "or always ignore missing fields here",
2705 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}..{1}", prefix, postfix))
})format!("{prefix}..{postfix}"),
2706 Applicability::MachineApplicable,
2707 );
2708 err
2709 }
2710
2711 fn check_pat_box(
2712 &self,
2713 span: Span,
2714 inner: &'tcx Pat<'tcx>,
2715 expected: Ty<'tcx>,
2716 pat_info: PatInfo<'tcx>,
2717 ) -> Ty<'tcx> {
2718 let tcx = self.tcx;
2719 let (box_ty, inner_ty) = self
2720 .check_dereferenceable(span, expected, inner)
2721 .and_then(|()| {
2722 let inner_ty = self.next_ty_var(inner.span);
2725 let box_ty = Ty::new_box(tcx, inner_ty);
2726 self.demand_eqtype_pat(span, expected, box_ty, &pat_info.top_info)?;
2727 Ok((box_ty, inner_ty))
2728 })
2729 .unwrap_or_else(|guar| {
2730 let err = Ty::new_error(tcx, guar);
2731 (err, err)
2732 });
2733 self.check_pat(inner, inner_ty, pat_info);
2734 box_ty
2735 }
2736
2737 fn check_pat_deref(
2738 &self,
2739 span: Span,
2740 inner: &'tcx Pat<'tcx>,
2741 expected: Ty<'tcx>,
2742 pat_info: PatInfo<'tcx>,
2743 ) -> Ty<'tcx> {
2744 let target_ty = self.deref_pat_target(span, expected);
2745 self.check_pat(inner, target_ty, pat_info);
2746 self.register_deref_mut_bounds_if_needed(span, inner, [expected]);
2747 expected
2748 }
2749
2750 fn deref_pat_target(&self, span: Span, source_ty: Ty<'tcx>) -> Ty<'tcx> {
2751 let tcx = self.tcx;
2753 self.register_bound(
2754 source_ty,
2755 tcx.require_lang_item(hir::LangItem::DerefPure, span),
2756 self.misc(span),
2757 );
2758 let target_ty = Ty::new_projection(
2760 tcx,
2761 ty::IsRigid::No,
2762 tcx.require_lang_item(hir::LangItem::DerefTarget, span),
2763 [source_ty],
2764 );
2765 let target_ty = self.normalize(span, Unnormalized::new_wip(target_ty));
2766 self.resolve_vars_with_obligations(target_ty)
2767 }
2768
2769 fn register_deref_mut_bounds_if_needed(
2774 &self,
2775 span: Span,
2776 inner: &'tcx Pat<'tcx>,
2777 derefed_tys: impl IntoIterator<Item = Ty<'tcx>>,
2778 ) {
2779 if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) {
2780 for mutably_derefed_ty in derefed_tys {
2781 self.register_bound(
2782 mutably_derefed_ty,
2783 self.tcx.require_lang_item(hir::LangItem::DerefMut, span),
2784 self.misc(span),
2785 );
2786 }
2787 }
2788 }
2789
2790 fn check_pat_ref(
2792 &self,
2793 pat: &'tcx Pat<'tcx>,
2794 inner: &'tcx Pat<'tcx>,
2795 pat_pinned: Pinnedness,
2796 pat_mutbl: Mutability,
2797 mut expected: Ty<'tcx>,
2798 mut pat_info: PatInfo<'tcx>,
2799 ) -> Ty<'tcx> {
2800 let tcx = self.tcx;
2801
2802 let pat_prefix_span =
2803 inner.span.find_ancestor_inside(pat.span).map(|end| pat.span.until(end));
2804
2805 let ref_pat_matches_mut_ref = self.ref_pat_matches_mut_ref();
2806 if ref_pat_matches_mut_ref && pat_mutbl == Mutability::Not {
2807 pat_info.max_ref_mutbl = pat_info.max_ref_mutbl.cap_to_weakly_not(pat_prefix_span);
2812 }
2813
2814 expected = self.resolve_vars_with_obligations(expected);
2815 if let ByRef::Yes(inh_pin, inh_mut) = pat_info.binding_mode
2818 && pat_pinned == inh_pin
2819 {
2820 match self.ref_pat_matches_inherited_ref(pat.span.edition()) {
2821 InheritedRefMatchRule::EatOuter => {
2822 if pat_mutbl > inh_mut {
2824 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);
2829 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2830 }
2831
2832 pat_info.binding_mode = ByRef::No;
2833 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2834 self.check_pat(inner, expected, pat_info);
2835 return expected;
2836 }
2837 InheritedRefMatchRule::EatInner => {
2838 if let ty::Ref(_, _, r_mutbl) = *expected.kind()
2839 && pat_mutbl <= r_mutbl
2840 {
2841 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);
2848 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());
2852 let mutbl_cap = cmp::min(r_mutbl, pat_info.max_ref_mutbl.as_mutbl());
2853 pat_info.binding_mode = pat_info.binding_mode.cap_ref_mutability(mutbl_cap);
2854 } else {
2855 if pat_mutbl > inh_mut {
2858 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);
2867 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2868 }
2869
2870 pat_info.binding_mode = ByRef::No;
2871 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2872 self.check_pat(inner, expected, pat_info);
2873 return expected;
2874 }
2875 }
2876 InheritedRefMatchRule::EatBoth { consider_inherited_ref: true } => {
2877 pat_info.binding_mode = ByRef::No;
2879
2880 if let ty::Ref(_, inner_ty, _) = *expected.kind() {
2881 if pat_mutbl.is_mut() && inh_mut.is_mut() {
2883 self.check_pat(inner, inner_ty, pat_info);
2890 return expected;
2891 } else {
2892 }
2899 } else {
2900 if pat_mutbl > inh_mut {
2903 self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2905 }
2906
2907 self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2908 self.check_pat(inner, expected, pat_info);
2909 return expected;
2910 }
2911 }
2912 InheritedRefMatchRule::EatBoth { consider_inherited_ref: false } => {
2913 pat_info.binding_mode = ByRef::No;
2916 self.add_rust_2024_migration_desugared_pat(
2917 pat_info.top_info.hir_id,
2918 pat,
2919 match pat_mutbl {
2920 Mutability::Not => '&', Mutability::Mut => 't', },
2923 inh_mut,
2924 )
2925 }
2926 }
2927 }
2928
2929 let (ref_ty, inner_ty) = match self.check_dereferenceable(pat.span, expected, inner) {
2930 Ok(()) => {
2931 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:2937",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(2937u32),
::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);
2938 match expected.maybe_pinned_ref() {
2939 Some((r_ty, r_pinned, r_mutbl, _))
2940 if ((ref_pat_matches_mut_ref && r_mutbl >= pat_mutbl)
2941 || r_mutbl == pat_mutbl)
2942 && pat_pinned == r_pinned =>
2943 {
2944 if r_mutbl == Mutability::Not {
2945 pat_info.max_ref_mutbl = MutblCap::Not;
2946 }
2947 if r_pinned == Pinnedness::Pinned {
2948 pat_info.max_pinnedness = PinnednessCap::Pinned;
2949 }
2950
2951 (expected, r_ty)
2952 }
2953 _ => {
2954 let inner_ty = self.next_ty_var(inner.span);
2955 let ref_ty = self.new_ref_ty(pat.span, pat_pinned, pat_mutbl, inner_ty);
2956 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:2956",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(2956u32),
::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);
2957 let err = self.demand_eqtype_pat_diag(
2958 pat.span,
2959 expected,
2960 ref_ty,
2961 &pat_info.top_info,
2962 );
2963
2964 if let Err(mut err) = err {
2967 self.borrow_pat_suggestion(&mut err, pat);
2968 err.emit();
2969 }
2970 (ref_ty, inner_ty)
2971 }
2972 }
2973 }
2974 Err(guar) => {
2975 let err = Ty::new_error(tcx, guar);
2976 (err, err)
2977 }
2978 };
2979
2980 self.check_pat(inner, inner_ty, pat_info);
2981 ref_ty
2982 }
2983
2984 fn new_ref_ty(
2986 &self,
2987 span: Span,
2988 pinnedness: Pinnedness,
2989 mutbl: Mutability,
2990 ty: Ty<'tcx>,
2991 ) -> Ty<'tcx> {
2992 let region = self.next_region_var(RegionVariableOrigin::PatternRegion(span));
2993 let ref_ty = Ty::new_ref(self.tcx, region, ty, mutbl);
2994 if pinnedness.is_pinned() {
2995 return self.new_pinned_ty(span, ref_ty);
2996 }
2997 ref_ty
2998 }
2999
3000 fn new_pinned_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
3002 Ty::new_adt(
3003 self.tcx,
3004 self.tcx.adt_def(self.tcx.require_lang_item(LangItem::Pin, span)),
3005 self.tcx.mk_args(&[ty.into()]),
3006 )
3007 }
3008
3009 fn error_inherited_ref_mutability_mismatch(
3010 &self,
3011 pat: &'tcx Pat<'tcx>,
3012 pat_prefix_span: Option<Span>,
3013 ) -> ErrorGuaranteed {
3014 let err_msg = "mismatched types";
3015 let err = if let Some(span) = pat_prefix_span {
3016 let mut err = self.dcx().struct_span_err(span, err_msg);
3017 err.code(E0308);
3018 err.note("cannot match inherited `&` with `&mut` pattern");
3019 err.span_suggestion_verbose(
3020 span,
3021 "replace this `&mut` pattern with `&`",
3022 "&",
3023 Applicability::MachineApplicable,
3024 );
3025 err
3026 } else {
3027 self.dcx().struct_span_err(pat.span, err_msg)
3028 };
3029 err.emit()
3030 }
3031
3032 fn try_resolve_slice_ty_to_array_ty(
3033 &self,
3034 before: &'tcx [Pat<'tcx>],
3035 slice: Option<&'tcx Pat<'tcx>>,
3036 span: Span,
3037 ) -> Option<Ty<'tcx>> {
3038 if slice.is_some() {
3039 return None;
3040 }
3041
3042 let tcx = self.tcx;
3043 let len = before.len();
3044 let inner_ty = self.next_ty_var(span);
3045
3046 Some(Ty::new_array(tcx, inner_ty, len.try_into().unwrap()))
3047 }
3048
3049 fn pat_is_irrefutable(&self, decl_origin: Option<DeclOrigin<'_>>) -> bool {
3080 match decl_origin {
3081 Some(DeclOrigin::LocalDecl { els: None }) => true,
3082 Some(DeclOrigin::LocalDecl { els: Some(_) } | DeclOrigin::LetExpr) | None => false,
3083 }
3084 }
3085
3086 fn check_pat_slice(
3097 &self,
3098 span: Span,
3099 before: &'tcx [Pat<'tcx>],
3100 slice: Option<&'tcx Pat<'tcx>>,
3101 after: &'tcx [Pat<'tcx>],
3102 expected: Ty<'tcx>,
3103 pat_info: PatInfo<'tcx>,
3104 ) -> Ty<'tcx> {
3105 let expected = self.resolve_vars_with_obligations(expected);
3106
3107 if self.pat_is_irrefutable(pat_info.decl_origin) && expected.is_ty_var() {
3110 if let Some(resolved_arr_ty) =
3111 self.try_resolve_slice_ty_to_array_ty(before, slice, span)
3112 {
3113 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:3113",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(3113u32),
::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);
3114 let _ = self.demand_eqtype(span, expected, resolved_arr_ty);
3115 }
3116 }
3117
3118 let expected = self.structurally_resolve_type(span, expected);
3119 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/pat.rs:3119",
"rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/pat.rs"),
::tracing_core::__macro_support::Option::Some(3119u32),
::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);
3120
3121 let (element_ty, opt_slice_ty, inferred) = match *expected.kind() {
3122 ty::Array(element_ty, len) => {
3124 let min = before.len() as u64 + after.len() as u64;
3125 let (opt_slice_ty, expected) =
3126 self.check_array_pat_len(span, element_ty, expected, slice, len, min);
3127 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());
3130 (element_ty, opt_slice_ty, expected)
3131 }
3132 ty::Slice(element_ty) => (element_ty, Some(expected), expected),
3133 _ => {
3135 let guar = expected.error_reported().err().unwrap_or_else(|| {
3136 self.error_expected_array_or_slice(span, expected, pat_info)
3137 });
3138 let err = Ty::new_error(self.tcx, guar);
3139 (err, Some(err), err)
3140 }
3141 };
3142
3143 for elt in before {
3145 self.check_pat(elt, element_ty, pat_info);
3146 }
3147 if let Some(slice) = slice {
3149 self.check_pat(slice, opt_slice_ty.unwrap(), pat_info);
3150 }
3151 for elt in after {
3153 self.check_pat(elt, element_ty, pat_info);
3154 }
3155 inferred
3156 }
3157
3158 fn check_array_pat_len(
3163 &self,
3164 span: Span,
3165 element_ty: Ty<'tcx>,
3166 arr_ty: Ty<'tcx>,
3167 slice: Option<&'tcx Pat<'tcx>>,
3168 len: ty::Const<'tcx>,
3169 min_len: u64,
3170 ) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
3171 let len = self.try_structurally_resolve_const(span, len).try_to_target_usize(self.tcx);
3172
3173 let guar = if let Some(len) = len {
3174 if slice.is_none() {
3176 if min_len == len {
3180 return (None, arr_ty);
3181 }
3182
3183 self.error_scrutinee_inconsistent_length(span, min_len, len)
3184 } else if let Some(pat_len) = len.checked_sub(min_len) {
3185 return (Some(Ty::new_array(self.tcx, element_ty, pat_len)), arr_ty);
3188 } else {
3189 self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len)
3192 }
3193 } else if slice.is_none() {
3194 let updated_arr_ty = Ty::new_array(self.tcx, element_ty, min_len);
3197 self.demand_eqtype(span, updated_arr_ty, arr_ty);
3198 return (None, updated_arr_ty);
3199 } else {
3200 self.error_scrutinee_unfixed_length(span)
3204 };
3205
3206 (Some(Ty::new_error(self.tcx, guar)), arr_ty)
3208 }
3209
3210 fn error_scrutinee_inconsistent_length(
3211 &self,
3212 span: Span,
3213 min_len: u64,
3214 size: u64,
3215 ) -> ErrorGuaranteed {
3216 {
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!(
3217 self.dcx(),
3218 span,
3219 E0527,
3220 "pattern requires {} element{} but array has {}",
3221 min_len,
3222 pluralize!(min_len),
3223 size,
3224 )
3225 .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)))
3226 .emit()
3227 }
3228
3229 fn error_scrutinee_with_rest_inconsistent_length(
3230 &self,
3231 span: Span,
3232 min_len: u64,
3233 size: u64,
3234 ) -> ErrorGuaranteed {
3235 {
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!(
3236 self.dcx(),
3237 span,
3238 E0528,
3239 "pattern requires at least {} element{} but array has {}",
3240 min_len,
3241 pluralize!(min_len),
3242 size,
3243 )
3244 .with_span_label(
3245 span,
3246 ::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),),
3247 )
3248 .emit()
3249 }
3250
3251 fn error_scrutinee_unfixed_length(&self, span: Span) -> ErrorGuaranteed {
3252 {
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!(
3253 self.dcx(),
3254 span,
3255 E0730,
3256 "cannot pattern-match on an array without a fixed length",
3257 )
3258 .emit()
3259 }
3260
3261 fn error_expected_array_or_slice(
3262 &self,
3263 span: Span,
3264 expected_ty: Ty<'tcx>,
3265 pat_info: PatInfo<'tcx>,
3266 ) -> ErrorGuaranteed {
3267 let PatInfo { top_info: ti, current_depth, .. } = pat_info;
3268
3269 let mut slice_pat_semantics = false;
3270 let mut as_deref = None;
3271 let mut slicing = None;
3272 if let ty::Ref(_, ty, _) = expected_ty.kind()
3273 && let ty::Array(..) | ty::Slice(..) = ty.kind()
3274 {
3275 slice_pat_semantics = true;
3276 } else if self
3277 .autoderef(span, expected_ty)
3278 .silence_errors()
3279 .any(|(ty, _)| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Slice(..) | ty::Array(..) => true,
_ => false,
}matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
3280 && let Some(span) = ti.span
3281 && let Some(_) = ti.origin_expr
3282 {
3283 let resolved_ty = self.resolve_vars_if_possible(ti.expected);
3284 let (is_slice_or_array_or_vector, resolved_ty) =
3285 self.is_slice_or_array_or_vector(resolved_ty);
3286 match resolved_ty.kind() {
3287 ty::Adt(adt_def, _)
3288 if self.tcx.is_diagnostic_item(sym::Option, adt_def.did())
3289 || self.tcx.is_diagnostic_item(sym::Result, adt_def.did()) =>
3290 {
3291 as_deref = Some(diagnostics::AsDerefSuggestion { span: span.shrink_to_hi() });
3293 }
3294 _ => (),
3295 }
3296
3297 let is_top_level = current_depth <= 1;
3298 if is_slice_or_array_or_vector && is_top_level {
3299 slicing = Some(diagnostics::SlicingSuggestion { span: span.shrink_to_hi() });
3300 }
3301 }
3302 self.dcx().emit_err(diagnostics::ExpectedArrayOrSlice {
3303 span,
3304 ty: expected_ty,
3305 slice_pat_semantics,
3306 as_deref,
3307 slicing,
3308 })
3309 }
3310
3311 fn is_slice_or_array_or_vector(&self, ty: Ty<'tcx>) -> (bool, Ty<'tcx>) {
3312 match ty.kind() {
3313 ty::Adt(adt_def, _) if self.tcx.is_diagnostic_item(sym::Vec, adt_def.did()) => {
3314 (true, ty)
3315 }
3316 ty::Ref(_, ty, _) => self.is_slice_or_array_or_vector(*ty),
3317 ty::Slice(..) | ty::Array(..) => (true, ty),
3318 _ => (false, ty),
3319 }
3320 }
3321
3322 fn add_rust_2024_migration_desugared_pat(
3325 &self,
3326 pat_id: HirId,
3327 subpat: &'tcx Pat<'tcx>,
3328 final_char: char,
3329 def_br_mutbl: Mutability,
3330 ) {
3331 let from_expansion = subpat.span.from_expansion();
3333 let trimmed_span = if from_expansion {
3334 subpat.span
3336 } else {
3337 let trimmed = self.tcx.sess.source_map().span_through_char(subpat.span, final_char);
3338 trimmed.with_ctxt(subpat.span.ctxt())
3341 };
3342
3343 let mut typeck_results = self.typeck_results.borrow_mut();
3344 let mut table = typeck_results.rust_2024_migration_desugared_pats_mut();
3345 let info = table.entry(pat_id).or_insert_with(|| ty::Rust2024IncompatiblePatInfo {
3350 primary_labels: Vec::new(),
3351 bad_ref_modifiers: false,
3352 bad_mut_modifiers: false,
3353 bad_ref_pats: false,
3354 suggest_eliding_modes: !self.tcx.features().ref_pat_eat_one_layer_2024()
3355 && !self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
3356 });
3357
3358 let pat_kind = if let PatKind::Binding(user_bind_annot, _, _, _) = subpat.kind {
3359 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!(
3363 user_bind_annot,
3364 BindingMode(ByRef::Yes(_, mutbl), Mutability::Not) if mutbl == def_br_mutbl
3365 );
3366 if user_bind_annot == BindingMode(ByRef::No, Mutability::Mut) {
3367 info.bad_mut_modifiers = true;
3368 "`mut` binding modifier"
3369 } else {
3370 info.bad_ref_modifiers = true;
3371 match user_bind_annot.1 {
3372 Mutability::Not => "explicit `ref` binding modifier",
3373 Mutability::Mut => "explicit `ref mut` binding modifier",
3374 }
3375 }
3376 } else {
3377 info.bad_ref_pats = true;
3378 info.suggest_eliding_modes = false;
3382 "reference pattern"
3383 };
3384 let primary_label = if from_expansion {
3387 info.suggest_eliding_modes = false;
3389 "occurs within macro expansion".to_owned()
3393 } else {
3394 ::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")
3395 };
3396 info.primary_labels.push((trimmed_span, primary_label));
3397 }
3398}