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