]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/pat.rs
Rollup merge of #87960 - hkmatsumoto:suggest-inexisting-field-for-unmentioned-field...
[rust.git] / compiler / rustc_typeck / src / check / pat.rs
1 use crate::check::FnCtxt;
2 use rustc_ast as ast;
3
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
6 use rustc_hir as hir;
7 use rustc_hir::def::{CtorKind, DefKind, Res};
8 use rustc_hir::pat_util::EnumerateAndAdjustIterator;
9 use rustc_hir::{HirId, Pat, PatKind};
10 use rustc_infer::infer;
11 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
12 use rustc_middle::ty::subst::GenericArg;
13 use rustc_middle::ty::{self, Adt, BindingMode, Ty, TypeFoldable};
14 use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
15 use rustc_span::hygiene::DesugaringKind;
16 use rustc_span::lev_distance::find_best_match_for_name;
17 use rustc_span::source_map::{Span, Spanned};
18 use rustc_span::symbol::Ident;
19 use rustc_span::{BytePos, MultiSpan, DUMMY_SP};
20 use rustc_trait_selection::autoderef::Autoderef;
21 use rustc_trait_selection::traits::{ObligationCause, Pattern};
22 use ty::VariantDef;
23
24 use std::cmp;
25 use std::collections::hash_map::Entry::{Occupied, Vacant};
26
27 use super::report_unexpected_variant_res;
28
29 const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
30 This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
31 pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
32 this type has no compile-time size. Therefore, all accesses to trait types must be through \
33 pointers. If you encounter this error you should try to avoid dereferencing the pointer.
34
35 You can read more about trait objects in the Trait Objects section of the Reference: \
36 https://doc.rust-lang.org/reference/types.html#trait-objects";
37
38 /// Information about the expected type at the top level of type checking a pattern.
39 ///
40 /// **NOTE:** This is only for use by diagnostics. Do NOT use for type checking logic!
41 #[derive(Copy, Clone)]
42 struct TopInfo<'tcx> {
43     /// The `expected` type at the top level of type checking a pattern.
44     expected: Ty<'tcx>,
45     /// Was the origin of the `span` from a scrutinee expression?
46     ///
47     /// Otherwise there is no scrutinee and it could be e.g. from the type of a formal parameter.
48     origin_expr: bool,
49     /// The span giving rise to the `expected` type, if one could be provided.
50     ///
51     /// If `origin_expr` is `true`, then this is the span of the scrutinee as in:
52     ///
53     /// - `match scrutinee { ... }`
54     /// - `let _ = scrutinee;`
55     ///
56     /// This is used to point to add context in type errors.
57     /// In the following example, `span` corresponds to the `a + b` expression:
58     ///
59     /// ```text
60     /// error[E0308]: mismatched types
61     ///  --> src/main.rs:L:C
62     ///   |
63     /// L |    let temp: usize = match a + b {
64     ///   |                            ----- this expression has type `usize`
65     /// L |         Ok(num) => num,
66     ///   |         ^^^^^^^ expected `usize`, found enum `std::result::Result`
67     ///   |
68     ///   = note: expected type `usize`
69     ///              found type `std::result::Result<_, _>`
70     /// ```
71     span: Option<Span>,
72     /// This refers to the parent pattern. Used to provide extra diagnostic information on errors.
73     /// ```text
74     /// error[E0308]: mismatched types
75     ///   --> $DIR/const-in-struct-pat.rs:8:17
76     ///   |
77     /// L | struct f;
78     ///   | --------- unit struct defined here
79     /// ...
80     /// L |     let Thing { f } = t;
81     ///   |                 ^
82     ///   |                 |
83     ///   |                 expected struct `std::string::String`, found struct `f`
84     ///   |                 `f` is interpreted as a unit struct, not a new binding
85     ///   |                 help: bind the struct field to a different name instead: `f: other_f`
86     /// ```
87     parent_pat: Option<&'tcx Pat<'tcx>>,
88 }
89
90 impl<'tcx> FnCtxt<'_, 'tcx> {
91     fn pattern_cause(&self, ti: TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
92         let code = Pattern { span: ti.span, root_ty: ti.expected, origin_expr: ti.origin_expr };
93         self.cause(cause_span, code)
94     }
95
96     fn demand_eqtype_pat_diag(
97         &self,
98         cause_span: Span,
99         expected: Ty<'tcx>,
100         actual: Ty<'tcx>,
101         ti: TopInfo<'tcx>,
102     ) -> Option<DiagnosticBuilder<'tcx>> {
103         self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
104     }
105
106     fn demand_eqtype_pat(
107         &self,
108         cause_span: Span,
109         expected: Ty<'tcx>,
110         actual: Ty<'tcx>,
111         ti: TopInfo<'tcx>,
112     ) {
113         if let Some(mut err) = self.demand_eqtype_pat_diag(cause_span, expected, actual, ti) {
114             err.emit();
115         }
116     }
117 }
118
119 const INITIAL_BM: BindingMode = BindingMode::BindByValue(hir::Mutability::Not);
120
121 /// Mode for adjusting the expected type and binding mode.
122 enum AdjustMode {
123     /// Peel off all immediate reference types.
124     Peel,
125     /// Reset binding mode to the initial mode.
126     Reset,
127     /// Pass on the input binding mode and expected type.
128     Pass,
129 }
130
131 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
132     /// Type check the given top level pattern against the `expected` type.
133     ///
134     /// If a `Some(span)` is provided and `origin_expr` holds,
135     /// then the `span` represents the scrutinee's span.
136     /// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.
137     ///
138     /// Otherwise, `Some(span)` represents the span of a type expression
139     /// which originated the `expected` type.
140     pub fn check_pat_top(
141         &self,
142         pat: &'tcx Pat<'tcx>,
143         expected: Ty<'tcx>,
144         span: Option<Span>,
145         origin_expr: bool,
146     ) {
147         let info = TopInfo { expected, origin_expr, span, parent_pat: None };
148         self.check_pat(pat, expected, INITIAL_BM, info);
149     }
150
151     /// Type check the given `pat` against the `expected` type
152     /// with the provided `def_bm` (default binding mode).
153     ///
154     /// Outside of this module, `check_pat_top` should always be used.
155     /// Conversely, inside this module, `check_pat_top` should never be used.
156     #[instrument(level = "debug", skip(self, ti))]
157     fn check_pat(
158         &self,
159         pat: &'tcx Pat<'tcx>,
160         expected: Ty<'tcx>,
161         def_bm: BindingMode,
162         ti: TopInfo<'tcx>,
163     ) {
164         let path_res = match &pat.kind {
165             PatKind::Path(qpath) => {
166                 Some(self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span))
167             }
168             _ => None,
169         };
170         let adjust_mode = self.calc_adjust_mode(pat, path_res.map(|(res, ..)| res));
171         let (expected, def_bm) = self.calc_default_binding_mode(pat, expected, def_bm, adjust_mode);
172
173         let ty = match pat.kind {
174             PatKind::Wild => expected,
175             PatKind::Lit(lt) => self.check_pat_lit(pat.span, lt, expected, ti),
176             PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat.span, lhs, rhs, expected, ti),
177             PatKind::Binding(ba, var_id, _, sub) => {
178                 self.check_pat_ident(pat, ba, var_id, sub, expected, def_bm, ti)
179             }
180             PatKind::TupleStruct(ref qpath, subpats, ddpos) => {
181                 self.check_pat_tuple_struct(pat, qpath, subpats, ddpos, expected, def_bm, ti)
182             }
183             PatKind::Path(_) => self.check_pat_path(pat, path_res.unwrap(), expected, ti),
184             PatKind::Struct(ref qpath, fields, etc) => {
185                 self.check_pat_struct(pat, qpath, fields, etc, expected, def_bm, ti)
186             }
187             PatKind::Or(pats) => {
188                 let parent_pat = Some(pat);
189                 for pat in pats {
190                     self.check_pat(pat, expected, def_bm, TopInfo { parent_pat, ..ti });
191                 }
192                 expected
193             }
194             PatKind::Tuple(elements, ddpos) => {
195                 self.check_pat_tuple(pat.span, elements, ddpos, expected, def_bm, ti)
196             }
197             PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, def_bm, ti),
198             PatKind::Ref(inner, mutbl) => {
199                 self.check_pat_ref(pat, inner, mutbl, expected, def_bm, ti)
200             }
201             PatKind::Slice(before, slice, after) => {
202                 self.check_pat_slice(pat.span, before, slice, after, expected, def_bm, ti)
203             }
204         };
205
206         self.write_ty(pat.hir_id, ty);
207
208         // (note_1): In most of the cases where (note_1) is referenced
209         // (literals and constants being the exception), we relate types
210         // using strict equality, even though subtyping would be sufficient.
211         // There are a few reasons for this, some of which are fairly subtle
212         // and which cost me (nmatsakis) an hour or two debugging to remember,
213         // so I thought I'd write them down this time.
214         //
215         // 1. There is no loss of expressiveness here, though it does
216         // cause some inconvenience. What we are saying is that the type
217         // of `x` becomes *exactly* what is expected. This can cause unnecessary
218         // errors in some cases, such as this one:
219         //
220         // ```
221         // fn foo<'x>(x: &'x i32) {
222         //    let a = 1;
223         //    let mut z = x;
224         //    z = &a;
225         // }
226         // ```
227         //
228         // The reason we might get an error is that `z` might be
229         // assigned a type like `&'x i32`, and then we would have
230         // a problem when we try to assign `&a` to `z`, because
231         // the lifetime of `&a` (i.e., the enclosing block) is
232         // shorter than `'x`.
233         //
234         // HOWEVER, this code works fine. The reason is that the
235         // expected type here is whatever type the user wrote, not
236         // the initializer's type. In this case the user wrote
237         // nothing, so we are going to create a type variable `Z`.
238         // Then we will assign the type of the initializer (`&'x i32`)
239         // as a subtype of `Z`: `&'x i32 <: Z`. And hence we
240         // will instantiate `Z` as a type `&'0 i32` where `'0` is
241         // a fresh region variable, with the constraint that `'x : '0`.
242         // So basically we're all set.
243         //
244         // Note that there are two tests to check that this remains true
245         // (`regions-reassign-{match,let}-bound-pointer.rs`).
246         //
247         // 2. Things go horribly wrong if we use subtype. The reason for
248         // THIS is a fairly subtle case involving bound regions. See the
249         // `givens` field in `region_constraints`, as well as the test
250         // `regions-relate-bound-regions-on-closures-to-inference-variables.rs`,
251         // for details. Short version is that we must sometimes detect
252         // relationships between specific region variables and regions
253         // bound in a closure signature, and that detection gets thrown
254         // off when we substitute fresh region variables here to enable
255         // subtyping.
256     }
257
258     /// Compute the new expected type and default binding mode from the old ones
259     /// as well as the pattern form we are currently checking.
260     fn calc_default_binding_mode(
261         &self,
262         pat: &'tcx Pat<'tcx>,
263         expected: Ty<'tcx>,
264         def_bm: BindingMode,
265         adjust_mode: AdjustMode,
266     ) -> (Ty<'tcx>, BindingMode) {
267         match adjust_mode {
268             AdjustMode::Pass => (expected, def_bm),
269             AdjustMode::Reset => (expected, INITIAL_BM),
270             AdjustMode::Peel => self.peel_off_references(pat, expected, def_bm),
271         }
272     }
273
274     /// How should the binding mode and expected type be adjusted?
275     ///
276     /// When the pattern is a path pattern, `opt_path_res` must be `Some(res)`.
277     fn calc_adjust_mode(&self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Res>) -> AdjustMode {
278         // When we perform destructuring assignment, we disable default match bindings, which are
279         // unintuitive in this context.
280         if !pat.default_binding_modes {
281             return AdjustMode::Reset;
282         }
283         match &pat.kind {
284             // Type checking these product-like types successfully always require
285             // that the expected type be of those types and not reference types.
286             PatKind::Struct(..)
287             | PatKind::TupleStruct(..)
288             | PatKind::Tuple(..)
289             | PatKind::Box(_)
290             | PatKind::Range(..)
291             | PatKind::Slice(..) => AdjustMode::Peel,
292             // String and byte-string literals result in types `&str` and `&[u8]` respectively.
293             // All other literals result in non-reference types.
294             // As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo {}`.
295             PatKind::Lit(lt) => match self.check_expr(lt).kind() {
296                 ty::Ref(..) => AdjustMode::Pass,
297                 _ => AdjustMode::Peel,
298             },
299             PatKind::Path(_) => match opt_path_res.unwrap() {
300                 // These constants can be of a reference type, e.g. `const X: &u8 = &0;`.
301                 // Peeling the reference types too early will cause type checking failures.
302                 // Although it would be possible to *also* peel the types of the constants too.
303                 Res::Def(DefKind::Const | DefKind::AssocConst, _) => AdjustMode::Pass,
304                 // In the `ValueNS`, we have `SelfCtor(..) | Ctor(_, Const), _)` remaining which
305                 // could successfully compile. The former being `Self` requires a unit struct.
306                 // In either case, and unlike constants, the pattern itself cannot be
307                 // a reference type wherefore peeling doesn't give up any expressivity.
308                 _ => AdjustMode::Peel,
309             },
310             // When encountering a `& mut? pat` pattern, reset to "by value".
311             // This is so that `x` and `y` here are by value, as they appear to be:
312             //
313             // ```
314             // match &(&22, &44) {
315             //   (&x, &y) => ...
316             // }
317             // ```
318             //
319             // See issue #46688.
320             PatKind::Ref(..) => AdjustMode::Reset,
321             // A `_` pattern works with any expected type, so there's no need to do anything.
322             PatKind::Wild
323             // Bindings also work with whatever the expected type is,
324             // and moreover if we peel references off, that will give us the wrong binding type.
325             // Also, we can have a subpattern `binding @ pat`.
326             // Each side of the `@` should be treated independently (like with OR-patterns).
327             | PatKind::Binding(..)
328             // An OR-pattern just propagates to each individual alternative.
329             // This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`.
330             // In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`.
331             | PatKind::Or(_) => AdjustMode::Pass,
332         }
333     }
334
335     /// Peel off as many immediately nested `& mut?` from the expected type as possible
336     /// and return the new expected type and binding default binding mode.
337     /// The adjustments vector, if non-empty is stored in a table.
338     fn peel_off_references(
339         &self,
340         pat: &'tcx Pat<'tcx>,
341         expected: Ty<'tcx>,
342         mut def_bm: BindingMode,
343     ) -> (Ty<'tcx>, BindingMode) {
344         let mut expected = self.resolve_vars_with_obligations(&expected);
345
346         // Peel off as many `&` or `&mut` from the scrutinee type as possible. For example,
347         // for `match &&&mut Some(5)` the loop runs three times, aborting when it reaches
348         // the `Some(5)` which is not of type Ref.
349         //
350         // For each ampersand peeled off, update the binding mode and push the original
351         // type into the adjustments vector.
352         //
353         // See the examples in `ui/match-defbm*.rs`.
354         let mut pat_adjustments = vec![];
355         while let ty::Ref(_, inner_ty, inner_mutability) = *expected.kind() {
356             debug!("inspecting {:?}", expected);
357
358             debug!("current discriminant is Ref, inserting implicit deref");
359             // Preserve the reference type. We'll need it later during THIR lowering.
360             pat_adjustments.push(expected);
361
362             expected = inner_ty;
363             def_bm = ty::BindByReference(match def_bm {
364                 // If default binding mode is by value, make it `ref` or `ref mut`
365                 // (depending on whether we observe `&` or `&mut`).
366                 ty::BindByValue(_) |
367                 // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`).
368                 ty::BindByReference(hir::Mutability::Mut) => inner_mutability,
369                 // Once a `ref`, always a `ref`.
370                 // This is because a `& &mut` cannot mutate the underlying value.
371                 ty::BindByReference(m @ hir::Mutability::Not) => m,
372             });
373         }
374
375         if !pat_adjustments.is_empty() {
376             debug!("default binding mode is now {:?}", def_bm);
377             self.inh
378                 .typeck_results
379                 .borrow_mut()
380                 .pat_adjustments_mut()
381                 .insert(pat.hir_id, pat_adjustments);
382         }
383
384         (expected, def_bm)
385     }
386
387     fn check_pat_lit(
388         &self,
389         span: Span,
390         lt: &hir::Expr<'tcx>,
391         expected: Ty<'tcx>,
392         ti: TopInfo<'tcx>,
393     ) -> Ty<'tcx> {
394         // We've already computed the type above (when checking for a non-ref pat),
395         // so avoid computing it again.
396         let ty = self.node_ty(lt.hir_id);
397
398         // Byte string patterns behave the same way as array patterns
399         // They can denote both statically and dynamically-sized byte arrays.
400         let mut pat_ty = ty;
401         if let hir::ExprKind::Lit(Spanned { node: ast::LitKind::ByteStr(_), .. }) = lt.kind {
402             let expected = self.structurally_resolved_type(span, expected);
403             if let ty::Ref(_, inner_ty, _) = expected.kind() {
404                 if matches!(inner_ty.kind(), ty::Slice(_)) {
405                     let tcx = self.tcx;
406                     trace!(?lt.hir_id.local_id, "polymorphic byte string lit");
407                     self.typeck_results
408                         .borrow_mut()
409                         .treat_byte_string_as_slice
410                         .insert(lt.hir_id.local_id);
411                     pat_ty = tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_slice(tcx.types.u8));
412                 }
413             }
414         }
415
416         // Somewhat surprising: in this case, the subtyping relation goes the
417         // opposite way as the other cases. Actually what we really want is not
418         // a subtyping relation at all but rather that there exists a LUB
419         // (so that they can be compared). However, in practice, constants are
420         // always scalars or strings. For scalars subtyping is irrelevant,
421         // and for strings `ty` is type is `&'static str`, so if we say that
422         //
423         //     &'static str <: expected
424         //
425         // then that's equivalent to there existing a LUB.
426         let cause = self.pattern_cause(ti, span);
427         if let Some(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
428             err.emit_unless(
429                 ti.span
430                     .filter(|&s| {
431                         // In the case of `if`- and `while`-expressions we've already checked
432                         // that `scrutinee: bool`. We know that the pattern is `true`,
433                         // so an error here would be a duplicate and from the wrong POV.
434                         s.is_desugaring(DesugaringKind::CondTemporary)
435                     })
436                     .is_some(),
437             );
438         }
439
440         pat_ty
441     }
442
443     fn check_pat_range(
444         &self,
445         span: Span,
446         lhs: Option<&'tcx hir::Expr<'tcx>>,
447         rhs: Option<&'tcx hir::Expr<'tcx>>,
448         expected: Ty<'tcx>,
449         ti: TopInfo<'tcx>,
450     ) -> Ty<'tcx> {
451         let calc_side = |opt_expr: Option<&'tcx hir::Expr<'tcx>>| match opt_expr {
452             None => (None, None),
453             Some(expr) => {
454                 let ty = self.check_expr(expr);
455                 // Check that the end-point is of numeric or char type.
456                 let fail = !(ty.is_numeric() || ty.is_char() || ty.references_error());
457                 (Some(ty), Some((fail, ty, expr.span)))
458             }
459         };
460         let (lhs_ty, lhs) = calc_side(lhs);
461         let (rhs_ty, rhs) = calc_side(rhs);
462
463         if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
464             // There exists a side that didn't meet our criteria that the end-point
465             // be of a numeric or char type, as checked in `calc_side` above.
466             self.emit_err_pat_range(span, lhs, rhs);
467             return self.tcx.ty_error();
468         }
469
470         // Now that we know the types can be unified we find the unified type
471         // and use it to type the entire expression.
472         let common_type = self.resolve_vars_if_possible(lhs_ty.or(rhs_ty).unwrap_or(expected));
473
474         // Subtyping doesn't matter here, as the value is some kind of scalar.
475         let demand_eqtype = |x, y| {
476             if let Some((_, x_ty, x_span)) = x {
477                 if let Some(mut err) = self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti) {
478                     if let Some((_, y_ty, y_span)) = y {
479                         self.endpoint_has_type(&mut err, y_span, y_ty);
480                     }
481                     err.emit();
482                 };
483             }
484         };
485         demand_eqtype(lhs, rhs);
486         demand_eqtype(rhs, lhs);
487
488         common_type
489     }
490
491     fn endpoint_has_type(&self, err: &mut DiagnosticBuilder<'_>, span: Span, ty: Ty<'_>) {
492         if !ty.references_error() {
493             err.span_label(span, &format!("this is of type `{}`", ty));
494         }
495     }
496
497     fn emit_err_pat_range(
498         &self,
499         span: Span,
500         lhs: Option<(bool, Ty<'tcx>, Span)>,
501         rhs: Option<(bool, Ty<'tcx>, Span)>,
502     ) {
503         let span = match (lhs, rhs) {
504             (Some((true, ..)), Some((true, ..))) => span,
505             (Some((true, _, sp)), _) => sp,
506             (_, Some((true, _, sp))) => sp,
507             _ => span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
508         };
509         let mut err = struct_span_err!(
510             self.tcx.sess,
511             span,
512             E0029,
513             "only `char` and numeric types are allowed in range patterns"
514         );
515         let msg = |ty| format!("this is of type `{}` but it should be `char` or numeric", ty);
516         let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
517             err.span_label(first_span, &msg(first_ty));
518             if let Some((_, ty, sp)) = second {
519                 self.endpoint_has_type(&mut err, sp, ty);
520             }
521         };
522         match (lhs, rhs) {
523             (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
524                 err.span_label(lhs_sp, &msg(lhs_ty));
525                 err.span_label(rhs_sp, &msg(rhs_ty));
526             }
527             (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
528             (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
529             _ => span_bug!(span, "Impossible, verified above."),
530         }
531         if self.tcx.sess.teach(&err.get_code().unwrap()) {
532             err.note(
533                 "In a match expression, only numbers and characters can be matched \
534                     against a range. This is because the compiler checks that the range \
535                     is non-empty at compile-time, and is unable to evaluate arbitrary \
536                     comparison functions. If you want to capture values of an orderable \
537                     type between two end-points, you can use a guard.",
538             );
539         }
540         err.emit();
541     }
542
543     fn check_pat_ident(
544         &self,
545         pat: &'tcx Pat<'tcx>,
546         ba: hir::BindingAnnotation,
547         var_id: HirId,
548         sub: Option<&'tcx Pat<'tcx>>,
549         expected: Ty<'tcx>,
550         def_bm: BindingMode,
551         ti: TopInfo<'tcx>,
552     ) -> Ty<'tcx> {
553         // Determine the binding mode...
554         let bm = match ba {
555             hir::BindingAnnotation::Unannotated => def_bm,
556             _ => BindingMode::convert(ba),
557         };
558         // ...and store it in a side table:
559         self.inh.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
560
561         debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
562
563         let local_ty = self.local_ty(pat.span, pat.hir_id).decl_ty;
564         let eq_ty = match bm {
565             ty::BindByReference(mutbl) => {
566                 // If the binding is like `ref x | ref mut x`,
567                 // then `x` is assigned a value of type `&M T` where M is the
568                 // mutability and T is the expected type.
569                 //
570                 // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)`
571                 // is required. However, we use equality, which is stronger.
572                 // See (note_1) for an explanation.
573                 self.new_ref_ty(pat.span, mutbl, expected)
574             }
575             // Otherwise, the type of x is the expected type `T`.
576             ty::BindByValue(_) => {
577                 // As above, `T <: typeof(x)` is required, but we use equality, see (note_1).
578                 expected
579             }
580         };
581         self.demand_eqtype_pat(pat.span, eq_ty, local_ty, ti);
582
583         // If there are multiple arms, make sure they all agree on
584         // what the type of the binding `x` ought to be.
585         if var_id != pat.hir_id {
586             self.check_binding_alt_eq_ty(pat.span, var_id, local_ty, ti);
587         }
588
589         if let Some(p) = sub {
590             self.check_pat(&p, expected, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
591         }
592
593         local_ty
594     }
595
596     fn check_binding_alt_eq_ty(&self, span: Span, var_id: HirId, ty: Ty<'tcx>, ti: TopInfo<'tcx>) {
597         let var_ty = self.local_ty(span, var_id).decl_ty;
598         if let Some(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
599             let hir = self.tcx.hir();
600             let var_ty = self.resolve_vars_with_obligations(var_ty);
601             let msg = format!("first introduced with type `{}` here", var_ty);
602             err.span_label(hir.span(var_id), msg);
603             let in_match = hir.parent_iter(var_id).any(|(_, n)| {
604                 matches!(
605                     n,
606                     hir::Node::Expr(hir::Expr {
607                         kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
608                         ..
609                     })
610                 )
611             });
612             let pre = if in_match { "in the same arm, " } else { "" };
613             err.note(&format!("{}a binding must have the same type in all alternatives", pre));
614             err.emit();
615         }
616     }
617
618     fn borrow_pat_suggestion(
619         &self,
620         err: &mut DiagnosticBuilder<'_>,
621         pat: &Pat<'_>,
622         inner: &Pat<'_>,
623         expected: Ty<'tcx>,
624     ) {
625         let tcx = self.tcx;
626         if let PatKind::Binding(..) = inner.kind {
627             let binding_parent_id = tcx.hir().get_parent_node(pat.hir_id);
628             let binding_parent = tcx.hir().get(binding_parent_id);
629             debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent);
630             match binding_parent {
631                 hir::Node::Param(hir::Param { span, .. })
632                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) =>
633                 {
634                     err.span_suggestion(
635                         *span,
636                         &format!("did you mean `{}`", snippet),
637                         format!(" &{}", expected),
638                         Applicability::MachineApplicable,
639                     );
640                 }
641                 hir::Node::Arm(_) | hir::Node::Pat(_) => {
642                     // rely on match ergonomics or it might be nested `&&pat`
643                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) {
644                         err.span_suggestion(
645                             pat.span,
646                             "you can probably remove the explicit borrow",
647                             snippet,
648                             Applicability::MaybeIncorrect,
649                         );
650                     }
651                 }
652                 _ => {} // don't provide suggestions in other cases #55175
653             }
654         }
655     }
656
657     pub fn check_dereferenceable(&self, span: Span, expected: Ty<'tcx>, inner: &Pat<'_>) -> bool {
658         if let PatKind::Binding(..) = inner.kind {
659             if let Some(mt) = self.shallow_resolve(expected).builtin_deref(true) {
660                 if let ty::Dynamic(..) = mt.ty.kind() {
661                     // This is "x = SomeTrait" being reduced from
662                     // "let &x = &SomeTrait" or "let box x = Box<SomeTrait>", an error.
663                     let type_str = self.ty_to_string(expected);
664                     let mut err = struct_span_err!(
665                         self.tcx.sess,
666                         span,
667                         E0033,
668                         "type `{}` cannot be dereferenced",
669                         type_str
670                     );
671                     err.span_label(span, format!("type `{}` cannot be dereferenced", type_str));
672                     if self.tcx.sess.teach(&err.get_code().unwrap()) {
673                         err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
674                     }
675                     err.emit();
676                     return false;
677                 }
678             }
679         }
680         true
681     }
682
683     fn check_pat_struct(
684         &self,
685         pat: &'tcx Pat<'tcx>,
686         qpath: &hir::QPath<'_>,
687         fields: &'tcx [hir::PatField<'tcx>],
688         etc: bool,
689         expected: Ty<'tcx>,
690         def_bm: BindingMode,
691         ti: TopInfo<'tcx>,
692     ) -> Ty<'tcx> {
693         // Resolve the path and check the definition for errors.
694         let (variant, pat_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, pat.hir_id)
695         {
696             variant_ty
697         } else {
698             let err = self.tcx.ty_error();
699             for field in fields {
700                 let ti = TopInfo { parent_pat: Some(&pat), ..ti };
701                 self.check_pat(&field.pat, err, def_bm, ti);
702             }
703             return err;
704         };
705
706         // Type-check the path.
707         self.demand_eqtype_pat(pat.span, expected, pat_ty, ti);
708
709         // Type-check subpatterns.
710         if self.check_struct_pat_fields(pat_ty, &pat, variant, fields, etc, def_bm, ti) {
711             pat_ty
712         } else {
713             self.tcx.ty_error()
714         }
715     }
716
717     fn check_pat_path(
718         &self,
719         pat: &Pat<'_>,
720         path_resolution: (Res, Option<Ty<'tcx>>, &'b [hir::PathSegment<'b>]),
721         expected: Ty<'tcx>,
722         ti: TopInfo<'tcx>,
723     ) -> Ty<'tcx> {
724         let tcx = self.tcx;
725
726         // We have already resolved the path.
727         let (res, opt_ty, segments) = path_resolution;
728         match res {
729             Res::Err => {
730                 self.set_tainted_by_errors();
731                 return tcx.ty_error();
732             }
733             Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fictive | CtorKind::Fn), _) => {
734                 report_unexpected_variant_res(tcx, res, pat.span);
735                 return tcx.ty_error();
736             }
737             Res::SelfCtor(..)
738             | Res::Def(
739                 DefKind::Ctor(_, CtorKind::Const)
740                 | DefKind::Const
741                 | DefKind::AssocConst
742                 | DefKind::ConstParam,
743                 _,
744             ) => {} // OK
745             _ => bug!("unexpected pattern resolution: {:?}", res),
746         }
747
748         // Type-check the path.
749         let (pat_ty, pat_res) =
750             self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id);
751         if let Some(err) =
752             self.demand_suptype_with_origin(&self.pattern_cause(ti, pat.span), expected, pat_ty)
753         {
754             self.emit_bad_pat_path(err, pat.span, res, pat_res, pat_ty, segments, ti.parent_pat);
755         }
756         pat_ty
757     }
758
759     fn maybe_suggest_range_literal(
760         &self,
761         e: &mut DiagnosticBuilder<'_>,
762         opt_def_id: Option<hir::def_id::DefId>,
763         ident: Ident,
764     ) -> bool {
765         match opt_def_id {
766             Some(def_id) => match self.tcx.hir().get_if_local(def_id) {
767                 Some(hir::Node::Item(hir::Item {
768                     kind: hir::ItemKind::Const(_, body_id), ..
769                 })) => match self.tcx.hir().get(body_id.hir_id) {
770                     hir::Node::Expr(expr) => {
771                         if hir::is_range_literal(expr) {
772                             let span = self.tcx.hir().span(body_id.hir_id);
773                             if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
774                                 e.span_suggestion_verbose(
775                                     ident.span,
776                                     "you may want to move the range into the match block",
777                                     snip,
778                                     Applicability::MachineApplicable,
779                                 );
780                                 return true;
781                             }
782                         }
783                     }
784                     _ => (),
785                 },
786                 _ => (),
787             },
788             _ => (),
789         }
790         false
791     }
792
793     fn emit_bad_pat_path(
794         &self,
795         mut e: DiagnosticBuilder<'_>,
796         pat_span: Span,
797         res: Res,
798         pat_res: Res,
799         pat_ty: Ty<'tcx>,
800         segments: &'b [hir::PathSegment<'b>],
801         parent_pat: Option<&Pat<'_>>,
802     ) {
803         if let Some(span) = self.tcx.hir().res_span(pat_res) {
804             e.span_label(span, &format!("{} defined here", res.descr()));
805             if let [hir::PathSegment { ident, .. }] = &*segments {
806                 e.span_label(
807                     pat_span,
808                     &format!(
809                         "`{}` is interpreted as {} {}, not a new binding",
810                         ident,
811                         res.article(),
812                         res.descr(),
813                     ),
814                 );
815                 match parent_pat {
816                     Some(Pat { kind: hir::PatKind::Struct(..), .. }) => {
817                         e.span_suggestion_verbose(
818                             ident.span.shrink_to_hi(),
819                             "bind the struct field to a different name instead",
820                             format!(": other_{}", ident.as_str().to_lowercase()),
821                             Applicability::HasPlaceholders,
822                         );
823                     }
824                     _ => {
825                         let (type_def_id, item_def_id) = match pat_ty.kind() {
826                             Adt(def, _) => match res {
827                                 Res::Def(DefKind::Const, def_id) => (Some(def.did), Some(def_id)),
828                                 _ => (None, None),
829                             },
830                             _ => (None, None),
831                         };
832
833                         let ranges = &[
834                             self.tcx.lang_items().range_struct(),
835                             self.tcx.lang_items().range_from_struct(),
836                             self.tcx.lang_items().range_to_struct(),
837                             self.tcx.lang_items().range_full_struct(),
838                             self.tcx.lang_items().range_inclusive_struct(),
839                             self.tcx.lang_items().range_to_inclusive_struct(),
840                         ];
841                         if type_def_id != None && ranges.contains(&type_def_id) {
842                             if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
843                                 let msg = "constants only support matching by type, \
844                                     if you meant to match against a range of values, \
845                                     consider using a range pattern like `min ..= max` in the match block";
846                                 e.note(msg);
847                             }
848                         } else {
849                             let msg = "introduce a new binding instead";
850                             let sugg = format!("other_{}", ident.as_str().to_lowercase());
851                             e.span_suggestion(
852                                 ident.span,
853                                 msg,
854                                 sugg,
855                                 Applicability::HasPlaceholders,
856                             );
857                         }
858                     }
859                 };
860             }
861         }
862         e.emit();
863     }
864
865     fn check_pat_tuple_struct(
866         &self,
867         pat: &'tcx Pat<'tcx>,
868         qpath: &'tcx hir::QPath<'tcx>,
869         subpats: &'tcx [Pat<'tcx>],
870         ddpos: Option<usize>,
871         expected: Ty<'tcx>,
872         def_bm: BindingMode,
873         ti: TopInfo<'tcx>,
874     ) -> Ty<'tcx> {
875         let tcx = self.tcx;
876         let on_error = || {
877             let parent_pat = Some(pat);
878             for pat in subpats {
879                 self.check_pat(&pat, tcx.ty_error(), def_bm, TopInfo { parent_pat, ..ti });
880             }
881         };
882         let report_unexpected_res = |res: Res| {
883             let sm = tcx.sess.source_map();
884             let path_str = sm
885                 .span_to_snippet(sm.span_until_char(pat.span, '('))
886                 .map_or_else(|_| String::new(), |s| format!(" `{}`", s.trim_end()));
887             let msg = format!(
888                 "expected tuple struct or tuple variant, found {}{}",
889                 res.descr(),
890                 path_str
891             );
892
893             let mut err = struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg);
894             match res {
895                 Res::Def(DefKind::Fn | DefKind::AssocFn, _) => {
896                     err.span_label(pat.span, "`fn` calls are not allowed in patterns");
897                     err.help(
898                         "for more information, visit \
899                               https://doc.rust-lang.org/book/ch18-00-patterns.html",
900                     );
901                 }
902                 _ => {
903                     err.span_label(pat.span, "not a tuple variant or struct");
904                 }
905             }
906             err.emit();
907             on_error();
908         };
909
910         // Resolve the path and check the definition for errors.
911         let (res, opt_ty, segments) =
912             self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span);
913         if res == Res::Err {
914             self.set_tainted_by_errors();
915             on_error();
916             return self.tcx.ty_error();
917         }
918
919         // Type-check the path.
920         let (pat_ty, res) =
921             self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id);
922         if !pat_ty.is_fn() {
923             report_unexpected_res(res);
924             return tcx.ty_error();
925         }
926
927         let variant = match res {
928             Res::Err => {
929                 self.set_tainted_by_errors();
930                 on_error();
931                 return tcx.ty_error();
932             }
933             Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => {
934                 report_unexpected_res(res);
935                 return tcx.ty_error();
936             }
937             Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
938             _ => bug!("unexpected pattern resolution: {:?}", res),
939         };
940
941         // Replace constructor type with constructed type for tuple struct patterns.
942         let pat_ty = pat_ty.fn_sig(tcx).output();
943         let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
944
945         // Type-check the tuple struct pattern against the expected type.
946         let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, ti);
947         let had_err = if let Some(mut err) = diag {
948             err.emit();
949             true
950         } else {
951             false
952         };
953
954         // Type-check subpatterns.
955         if subpats.len() == variant.fields.len()
956             || subpats.len() < variant.fields.len() && ddpos.is_some()
957         {
958             let substs = match pat_ty.kind() {
959                 ty::Adt(_, substs) => substs,
960                 _ => bug!("unexpected pattern type {:?}", pat_ty),
961             };
962             for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
963                 let field_ty = self.field_ty(subpat.span, &variant.fields[i], substs);
964                 self.check_pat(&subpat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
965
966                 self.tcx.check_stability(
967                     variant.fields[i].did,
968                     Some(pat.hir_id),
969                     subpat.span,
970                     None,
971                 );
972             }
973         } else {
974             // Pattern has wrong number of fields.
975             self.e0023(pat.span, res, qpath, subpats, &variant.fields, expected, had_err);
976             on_error();
977             return tcx.ty_error();
978         }
979         pat_ty
980     }
981
982     fn e0023(
983         &self,
984         pat_span: Span,
985         res: Res,
986         qpath: &hir::QPath<'_>,
987         subpats: &'tcx [Pat<'tcx>],
988         fields: &'tcx [ty::FieldDef],
989         expected: Ty<'tcx>,
990         had_err: bool,
991     ) {
992         let subpats_ending = pluralize!(subpats.len());
993         let fields_ending = pluralize!(fields.len());
994
995         let subpat_spans = if subpats.is_empty() {
996             vec![pat_span]
997         } else {
998             subpats.iter().map(|p| p.span).collect()
999         };
1000         let last_subpat_span = *subpat_spans.last().unwrap();
1001         let res_span = self.tcx.def_span(res.def_id());
1002         let def_ident_span = self.tcx.def_ident_span(res.def_id()).unwrap_or(res_span);
1003         let field_def_spans = if fields.is_empty() {
1004             vec![res_span]
1005         } else {
1006             fields.iter().map(|f| f.ident.span).collect()
1007         };
1008         let last_field_def_span = *field_def_spans.last().unwrap();
1009
1010         let mut err = struct_span_err!(
1011             self.tcx.sess,
1012             MultiSpan::from_spans(subpat_spans),
1013             E0023,
1014             "this pattern has {} field{}, but the corresponding {} has {} field{}",
1015             subpats.len(),
1016             subpats_ending,
1017             res.descr(),
1018             fields.len(),
1019             fields_ending,
1020         );
1021         err.span_label(
1022             last_subpat_span,
1023             &format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len()),
1024         );
1025         if self.tcx.sess.source_map().is_multiline(qpath.span().between(last_subpat_span)) {
1026             err.span_label(qpath.span(), "");
1027         }
1028         if self.tcx.sess.source_map().is_multiline(def_ident_span.between(last_field_def_span)) {
1029             err.span_label(def_ident_span, format!("{} defined here", res.descr()));
1030         }
1031         for span in &field_def_spans[..field_def_spans.len() - 1] {
1032             err.span_label(*span, "");
1033         }
1034         err.span_label(
1035             last_field_def_span,
1036             &format!("{} has {} field{}", res.descr(), fields.len(), fields_ending),
1037         );
1038
1039         // Identify the case `Some(x, y)` where the expected type is e.g. `Option<(T, U)>`.
1040         // More generally, the expected type wants a tuple variant with one field of an
1041         // N-arity-tuple, e.g., `V_i((p_0, .., p_N))`. Meanwhile, the user supplied a pattern
1042         // with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`.
1043         let missing_parentheses = match (&expected.kind(), fields, had_err) {
1044             // #67037: only do this if we could successfully type-check the expected type against
1045             // the tuple struct pattern. Otherwise the substs could get out of range on e.g.,
1046             // `let P() = U;` where `P != U` with `struct P<T>(T);`.
1047             (ty::Adt(_, substs), [field], false) => {
1048                 let field_ty = self.field_ty(pat_span, field, substs);
1049                 match field_ty.kind() {
1050                     ty::Tuple(_) => field_ty.tuple_fields().count() == subpats.len(),
1051                     _ => false,
1052                 }
1053             }
1054             _ => false,
1055         };
1056         if missing_parentheses {
1057             let (left, right) = match subpats {
1058                 // This is the zero case; we aim to get the "hi" part of the `QPath`'s
1059                 // span as the "lo" and then the "hi" part of the pattern's span as the "hi".
1060                 // This looks like:
1061                 //
1062                 // help: missing parentheses
1063                 //   |
1064                 // L |     let A(()) = A(());
1065                 //   |          ^  ^
1066                 [] => (qpath.span().shrink_to_hi(), pat_span),
1067                 // Easy case. Just take the "lo" of the first sub-pattern and the "hi" of the
1068                 // last sub-pattern. In the case of `A(x)` the first and last may coincide.
1069                 // This looks like:
1070                 //
1071                 // help: missing parentheses
1072                 //   |
1073                 // L |     let A((x, y)) = A((1, 2));
1074                 //   |           ^    ^
1075                 [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
1076             };
1077             err.multipart_suggestion(
1078                 "missing parentheses",
1079                 vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())],
1080                 Applicability::MachineApplicable,
1081             );
1082         } else if fields.len() > subpats.len() && pat_span != DUMMY_SP {
1083             let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi();
1084             let all_fields_span = match subpats {
1085                 [] => after_fields_span,
1086                 [field] => field.span,
1087                 [first, .., last] => first.span.to(last.span),
1088             };
1089
1090             // Check if all the fields in the pattern are wildcards.
1091             let all_wildcards = subpats.iter().all(|pat| matches!(pat.kind, PatKind::Wild));
1092             let first_tail_wildcard =
1093                 subpats.iter().enumerate().fold(None, |acc, (pos, pat)| match (acc, &pat.kind) {
1094                     (None, PatKind::Wild) => Some(pos),
1095                     (Some(_), PatKind::Wild) => acc,
1096                     _ => None,
1097                 });
1098             let tail_span = match first_tail_wildcard {
1099                 None => after_fields_span,
1100                 Some(0) => subpats[0].span.to(after_fields_span),
1101                 Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span),
1102             };
1103
1104             // FIXME: heuristic-based suggestion to check current types for where to add `_`.
1105             let mut wildcard_sugg = vec!["_"; fields.len() - subpats.len()].join(", ");
1106             if !subpats.is_empty() {
1107                 wildcard_sugg = String::from(", ") + &wildcard_sugg;
1108             }
1109
1110             err.span_suggestion_verbose(
1111                 after_fields_span,
1112                 "use `_` to explicitly ignore each field",
1113                 wildcard_sugg,
1114                 Applicability::MaybeIncorrect,
1115             );
1116
1117             // Only suggest `..` if more than one field is missing
1118             // or the pattern consists of all wildcards.
1119             if fields.len() - subpats.len() > 1 || all_wildcards {
1120                 if subpats.is_empty() || all_wildcards {
1121                     err.span_suggestion_verbose(
1122                         all_fields_span,
1123                         "use `..` to ignore all fields",
1124                         String::from(".."),
1125                         Applicability::MaybeIncorrect,
1126                     );
1127                 } else {
1128                     err.span_suggestion_verbose(
1129                         tail_span,
1130                         "use `..` to ignore the rest of the fields",
1131                         String::from(", .."),
1132                         Applicability::MaybeIncorrect,
1133                     );
1134                 }
1135             }
1136         }
1137
1138         err.emit();
1139     }
1140
1141     fn check_pat_tuple(
1142         &self,
1143         span: Span,
1144         elements: &'tcx [Pat<'tcx>],
1145         ddpos: Option<usize>,
1146         expected: Ty<'tcx>,
1147         def_bm: BindingMode,
1148         ti: TopInfo<'tcx>,
1149     ) -> Ty<'tcx> {
1150         let tcx = self.tcx;
1151         let mut expected_len = elements.len();
1152         if ddpos.is_some() {
1153             // Require known type only when `..` is present.
1154             if let ty::Tuple(ref tys) = self.structurally_resolved_type(span, expected).kind() {
1155                 expected_len = tys.len();
1156             }
1157         }
1158         let max_len = cmp::max(expected_len, elements.len());
1159
1160         let element_tys_iter = (0..max_len).map(|_| {
1161             GenericArg::from(self.next_ty_var(
1162                 // FIXME: `MiscVariable` for now -- obtaining the span and name information
1163                 // from all tuple elements isn't trivial.
1164                 TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span },
1165             ))
1166         });
1167         let element_tys = tcx.mk_substs(element_tys_iter);
1168         let pat_ty = tcx.mk_ty(ty::Tuple(element_tys));
1169         if let Some(mut err) = self.demand_eqtype_pat_diag(span, expected, pat_ty, ti) {
1170             err.emit();
1171             // Walk subpatterns with an expected type of `err` in this case to silence
1172             // further errors being emitted when using the bindings. #50333
1173             let element_tys_iter = (0..max_len).map(|_| tcx.ty_error());
1174             for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1175                 self.check_pat(elem, &tcx.ty_error(), def_bm, ti);
1176             }
1177             tcx.mk_tup(element_tys_iter)
1178         } else {
1179             for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1180                 self.check_pat(elem, &element_tys[i].expect_ty(), def_bm, ti);
1181             }
1182             pat_ty
1183         }
1184     }
1185
1186     fn check_struct_pat_fields(
1187         &self,
1188         adt_ty: Ty<'tcx>,
1189         pat: &'tcx Pat<'tcx>,
1190         variant: &'tcx ty::VariantDef,
1191         fields: &'tcx [hir::PatField<'tcx>],
1192         etc: bool,
1193         def_bm: BindingMode,
1194         ti: TopInfo<'tcx>,
1195     ) -> bool {
1196         let tcx = self.tcx;
1197
1198         let (substs, adt) = match adt_ty.kind() {
1199             ty::Adt(adt, substs) => (substs, adt),
1200             _ => span_bug!(pat.span, "struct pattern is not an ADT"),
1201         };
1202
1203         // Index the struct fields' types.
1204         let field_map = variant
1205             .fields
1206             .iter()
1207             .enumerate()
1208             .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
1209             .collect::<FxHashMap<_, _>>();
1210
1211         // Keep track of which fields have already appeared in the pattern.
1212         let mut used_fields = FxHashMap::default();
1213         let mut no_field_errors = true;
1214
1215         let mut inexistent_fields = vec![];
1216         // Typecheck each field.
1217         for field in fields {
1218             let span = field.span;
1219             let ident = tcx.adjust_ident(field.ident, variant.def_id);
1220             let field_ty = match used_fields.entry(ident) {
1221                 Occupied(occupied) => {
1222                     self.error_field_already_bound(span, field.ident, *occupied.get());
1223                     no_field_errors = false;
1224                     tcx.ty_error()
1225                 }
1226                 Vacant(vacant) => {
1227                     vacant.insert(span);
1228                     field_map
1229                         .get(&ident)
1230                         .map(|(i, f)| {
1231                             self.write_field_index(field.hir_id, *i);
1232                             self.tcx.check_stability(f.did, Some(pat.hir_id), span, None);
1233                             self.field_ty(span, f, substs)
1234                         })
1235                         .unwrap_or_else(|| {
1236                             inexistent_fields.push(field.ident);
1237                             no_field_errors = false;
1238                             tcx.ty_error()
1239                         })
1240                 }
1241             };
1242
1243             self.check_pat(&field.pat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
1244         }
1245
1246         let mut unmentioned_fields = variant
1247             .fields
1248             .iter()
1249             .map(|field| (field, field.ident.normalize_to_macros_2_0()))
1250             .filter(|(_, ident)| !used_fields.contains_key(&ident))
1251             .collect::<Vec<_>>();
1252
1253         let inexistent_fields_err = if !(inexistent_fields.is_empty() || variant.is_recovered()) {
1254             Some(self.error_inexistent_fields(
1255                 adt.variant_descr(),
1256                 &inexistent_fields,
1257                 &mut unmentioned_fields,
1258                 variant,
1259             ))
1260         } else {
1261             None
1262         };
1263
1264         // Require `..` if struct has non_exhaustive attribute.
1265         let non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did.is_local();
1266         if non_exhaustive && !etc {
1267             self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
1268         }
1269
1270         let mut unmentioned_err = None;
1271         // Report an error if an incorrect number of fields was specified.
1272         if adt.is_union() {
1273             if fields.len() != 1 {
1274                 tcx.sess
1275                     .struct_span_err(pat.span, "union patterns should have exactly one field")
1276                     .emit();
1277             }
1278             if etc {
1279                 tcx.sess.struct_span_err(pat.span, "`..` cannot be used in union patterns").emit();
1280             }
1281         } else if !unmentioned_fields.is_empty() {
1282             let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
1283                 .iter()
1284                 .copied()
1285                 .filter(|(field, _)| {
1286                     field.vis.is_accessible_from(tcx.parent_module(pat.hir_id).to_def_id(), tcx)
1287                 })
1288                 .collect();
1289             if non_exhaustive {
1290                 self.non_exhaustive_reachable_pattern(pat, &accessible_unmentioned_fields, adt_ty)
1291             } else if !etc {
1292                 if accessible_unmentioned_fields.is_empty() {
1293                     unmentioned_err = Some(self.error_no_accessible_fields(pat, &fields));
1294                 } else {
1295                     unmentioned_err = Some(self.error_unmentioned_fields(
1296                         pat,
1297                         &accessible_unmentioned_fields,
1298                         accessible_unmentioned_fields.len() != unmentioned_fields.len(),
1299                         &fields,
1300                     ));
1301                 }
1302             }
1303         }
1304         match (inexistent_fields_err, unmentioned_err) {
1305             (Some(mut i), Some(mut u)) => {
1306                 if let Some(mut e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
1307                     // We don't want to show the inexistent fields error when this was
1308                     // `Foo { a, b }` when it should have been `Foo(a, b)`.
1309                     i.delay_as_bug();
1310                     u.delay_as_bug();
1311                     e.emit();
1312                 } else {
1313                     i.emit();
1314                     u.emit();
1315                 }
1316             }
1317             (None, Some(mut u)) => {
1318                 if let Some(mut e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
1319                     u.delay_as_bug();
1320                     e.emit();
1321                 } else {
1322                     u.emit();
1323                 }
1324             }
1325             (Some(mut err), None) => {
1326                 err.emit();
1327             }
1328             (None, None) if let Some(mut err) =
1329                     self.error_tuple_variant_index_shorthand(variant, pat, fields) =>
1330             {
1331                 err.emit();
1332             }
1333             (None, None) => {}
1334         }
1335         no_field_errors
1336     }
1337
1338     fn error_tuple_variant_index_shorthand(
1339         &self,
1340         variant: &VariantDef,
1341         pat: &'_ Pat<'_>,
1342         fields: &[hir::PatField<'_>],
1343     ) -> Option<DiagnosticBuilder<'_>> {
1344         // if this is a tuple struct, then all field names will be numbers
1345         // so if any fields in a struct pattern use shorthand syntax, they will
1346         // be invalid identifiers (for example, Foo { 0, 1 }).
1347         if let (CtorKind::Fn, PatKind::Struct(qpath, field_patterns, ..)) =
1348             (variant.ctor_kind, &pat.kind)
1349         {
1350             let has_shorthand_field_name = field_patterns.iter().any(|field| field.is_shorthand);
1351             if has_shorthand_field_name {
1352                 let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
1353                     s.print_qpath(qpath, false)
1354                 });
1355                 let mut err = struct_span_err!(
1356                     self.tcx.sess,
1357                     pat.span,
1358                     E0769,
1359                     "tuple variant `{}` written as struct variant",
1360                     path
1361                 );
1362                 err.span_suggestion_verbose(
1363                     qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
1364                     "use the tuple variant pattern syntax instead",
1365                     format!("({})", self.get_suggested_tuple_struct_pattern(fields, variant)),
1366                     Applicability::MaybeIncorrect,
1367                 );
1368                 return Some(err);
1369             }
1370         }
1371         None
1372     }
1373
1374     fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
1375         let sess = self.tcx.sess;
1376         let sm = sess.source_map();
1377         let sp_brace = sm.end_point(pat.span);
1378         let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
1379         let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
1380
1381         let mut err = struct_span_err!(
1382             sess,
1383             pat.span,
1384             E0638,
1385             "`..` required with {} marked as non-exhaustive",
1386             descr
1387         );
1388         err.span_suggestion_verbose(
1389             sp_comma,
1390             "add `..` at the end of the field list to ignore all other fields",
1391             sugg.to_string(),
1392             Applicability::MachineApplicable,
1393         );
1394         err.emit();
1395     }
1396
1397     fn error_field_already_bound(&self, span: Span, ident: Ident, other_field: Span) {
1398         struct_span_err!(
1399             self.tcx.sess,
1400             span,
1401             E0025,
1402             "field `{}` bound multiple times in the pattern",
1403             ident
1404         )
1405         .span_label(span, format!("multiple uses of `{}` in pattern", ident))
1406         .span_label(other_field, format!("first use of `{}`", ident))
1407         .emit();
1408     }
1409
1410     fn error_inexistent_fields(
1411         &self,
1412         kind_name: &str,
1413         inexistent_fields: &[Ident],
1414         unmentioned_fields: &mut Vec<(&ty::FieldDef, Ident)>,
1415         variant: &ty::VariantDef,
1416     ) -> DiagnosticBuilder<'tcx> {
1417         let tcx = self.tcx;
1418         let (field_names, t, plural) = if inexistent_fields.len() == 1 {
1419             (format!("a field named `{}`", inexistent_fields[0]), "this", "")
1420         } else {
1421             (
1422                 format!(
1423                     "fields named {}",
1424                     inexistent_fields
1425                         .iter()
1426                         .map(|ident| format!("`{}`", ident))
1427                         .collect::<Vec<String>>()
1428                         .join(", ")
1429                 ),
1430                 "these",
1431                 "s",
1432             )
1433         };
1434         let spans = inexistent_fields.iter().map(|ident| ident.span).collect::<Vec<_>>();
1435         let mut err = struct_span_err!(
1436             tcx.sess,
1437             spans,
1438             E0026,
1439             "{} `{}` does not have {}",
1440             kind_name,
1441             tcx.def_path_str(variant.def_id),
1442             field_names
1443         );
1444         if let Some(ident) = inexistent_fields.last() {
1445             err.span_label(
1446                 ident.span,
1447                 format!(
1448                     "{} `{}` does not have {} field{}",
1449                     kind_name,
1450                     tcx.def_path_str(variant.def_id),
1451                     t,
1452                     plural
1453                 ),
1454             );
1455
1456             if unmentioned_fields.len() == 1 {
1457                 let input =
1458                     unmentioned_fields.iter().map(|(_, field)| field.name).collect::<Vec<_>>();
1459                 let suggested_name = find_best_match_for_name(&input, ident.name, None);
1460                 if let Some(suggested_name) = suggested_name {
1461                     err.span_suggestion(
1462                         ident.span,
1463                         "a field with a similar name exists",
1464                         suggested_name.to_string(),
1465                         Applicability::MaybeIncorrect,
1466                     );
1467
1468                     // When we have a tuple struct used with struct we don't want to suggest using
1469                     // the (valid) struct syntax with numeric field names. Instead we want to
1470                     // suggest the expected syntax. We infer that this is the case by parsing the
1471                     // `Ident` into an unsized integer. The suggestion will be emitted elsewhere in
1472                     // `smart_resolve_context_dependent_help`.
1473                     if suggested_name.to_ident_string().parse::<usize>().is_err() {
1474                         // We don't want to throw `E0027` in case we have thrown `E0026` for them.
1475                         unmentioned_fields.retain(|&(_, x)| x.name != suggested_name);
1476                     }
1477                 } else if inexistent_fields.len() == 1 {
1478                     let unmentioned_field = unmentioned_fields[0].1.name;
1479                     err.span_suggestion_short(
1480                         ident.span,
1481                         &format!(
1482                             "`{}` has a field named `{}`",
1483                             tcx.def_path_str(variant.def_id),
1484                             unmentioned_field
1485                         ),
1486                         unmentioned_field.to_string(),
1487                         Applicability::MaybeIncorrect,
1488                     );
1489                 }
1490             }
1491         }
1492         if tcx.sess.teach(&err.get_code().unwrap()) {
1493             err.note(
1494                 "This error indicates that a struct pattern attempted to \
1495                  extract a non-existent field from a struct. Struct fields \
1496                  are identified by the name used before the colon : so struct \
1497                  patterns should resemble the declaration of the struct type \
1498                  being matched.\n\n\
1499                  If you are using shorthand field patterns but want to refer \
1500                  to the struct field by a different name, you should rename \
1501                  it explicitly.",
1502             );
1503         }
1504         err
1505     }
1506
1507     fn error_tuple_variant_as_struct_pat(
1508         &self,
1509         pat: &Pat<'_>,
1510         fields: &'tcx [hir::PatField<'tcx>],
1511         variant: &ty::VariantDef,
1512     ) -> Option<DiagnosticBuilder<'tcx>> {
1513         if let (CtorKind::Fn, PatKind::Struct(qpath, ..)) = (variant.ctor_kind, &pat.kind) {
1514             let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
1515                 s.print_qpath(qpath, false)
1516             });
1517             let mut err = struct_span_err!(
1518                 self.tcx.sess,
1519                 pat.span,
1520                 E0769,
1521                 "tuple variant `{}` written as struct variant",
1522                 path
1523             );
1524             let (sugg, appl) = if fields.len() == variant.fields.len() {
1525                 (
1526                     self.get_suggested_tuple_struct_pattern(fields, variant),
1527                     Applicability::MachineApplicable,
1528                 )
1529             } else {
1530                 (
1531                     variant.fields.iter().map(|_| "_").collect::<Vec<&str>>().join(", "),
1532                     Applicability::MaybeIncorrect,
1533                 )
1534             };
1535             err.span_suggestion_verbose(
1536                 qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
1537                 "use the tuple variant pattern syntax instead",
1538                 format!("({})", sugg),
1539                 appl,
1540             );
1541             return Some(err);
1542         }
1543         None
1544     }
1545
1546     fn get_suggested_tuple_struct_pattern(
1547         &self,
1548         fields: &[hir::PatField<'_>],
1549         variant: &VariantDef,
1550     ) -> String {
1551         let variant_field_idents = variant.fields.iter().map(|f| f.ident).collect::<Vec<Ident>>();
1552         fields
1553             .iter()
1554             .map(|field| {
1555                 match self.tcx.sess.source_map().span_to_snippet(field.pat.span) {
1556                     Ok(f) => {
1557                         // Field names are numbers, but numbers
1558                         // are not valid identifiers
1559                         if variant_field_idents.contains(&field.ident) {
1560                             String::from("_")
1561                         } else {
1562                             f
1563                         }
1564                     }
1565                     Err(_) => rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
1566                         s.print_pat(field.pat)
1567                     }),
1568                 }
1569             })
1570             .collect::<Vec<String>>()
1571             .join(", ")
1572     }
1573
1574     /// Returns a diagnostic reporting a struct pattern which is missing an `..` due to
1575     /// inaccessible fields.
1576     ///
1577     /// ```text
1578     /// error: pattern requires `..` due to inaccessible fields
1579     ///   --> src/main.rs:10:9
1580     ///    |
1581     /// LL |     let foo::Foo {} = foo::Foo::default();
1582     ///    |         ^^^^^^^^^^^
1583     ///    |
1584     /// help: add a `..`
1585     ///    |
1586     /// LL |     let foo::Foo { .. } = foo::Foo::default();
1587     ///    |                  ^^^^^^
1588     /// ```
1589     fn error_no_accessible_fields(
1590         &self,
1591         pat: &Pat<'_>,
1592         fields: &'tcx [hir::PatField<'tcx>],
1593     ) -> DiagnosticBuilder<'tcx> {
1594         let mut err = self
1595             .tcx
1596             .sess
1597             .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
1598
1599         if let Some(field) = fields.last() {
1600             err.span_suggestion_verbose(
1601                 field.span.shrink_to_hi(),
1602                 "ignore the inaccessible and unused fields",
1603                 ", ..".to_string(),
1604                 Applicability::MachineApplicable,
1605             );
1606         } else {
1607             let qpath_span = if let PatKind::Struct(qpath, ..) = &pat.kind {
1608                 qpath.span()
1609             } else {
1610                 bug!("`error_no_accessible_fields` called on non-struct pattern");
1611             };
1612
1613             // Shrink the span to exclude the `foo:Foo` in `foo::Foo { }`.
1614             let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi());
1615             err.span_suggestion_verbose(
1616                 span,
1617                 "ignore the inaccessible and unused fields",
1618                 " { .. }".to_string(),
1619                 Applicability::MachineApplicable,
1620             );
1621         }
1622         err
1623     }
1624
1625     /// Report that a pattern for a `#[non_exhaustive]` struct marked with `non_exhaustive_omitted_patterns`
1626     /// is not exhaustive enough.
1627     ///
1628     /// Nb: the partner lint for enums lives in `compiler/rustc_mir_build/src/thir/pattern/usefulness.rs`.
1629     fn non_exhaustive_reachable_pattern(
1630         &self,
1631         pat: &Pat<'_>,
1632         unmentioned_fields: &[(&ty::FieldDef, Ident)],
1633         ty: Ty<'tcx>,
1634     ) {
1635         fn joined_uncovered_patterns(witnesses: &[&Ident]) -> String {
1636             const LIMIT: usize = 3;
1637             match witnesses {
1638                 [] => bug!(),
1639                 [witness] => format!("`{}`", witness),
1640                 [head @ .., tail] if head.len() < LIMIT => {
1641                     let head: Vec<_> = head.iter().map(<_>::to_string).collect();
1642                     format!("`{}` and `{}`", head.join("`, `"), tail)
1643                 }
1644                 _ => {
1645                     let (head, tail) = witnesses.split_at(LIMIT);
1646                     let head: Vec<_> = head.iter().map(<_>::to_string).collect();
1647                     format!("`{}` and {} more", head.join("`, `"), tail.len())
1648                 }
1649             }
1650         }
1651         let joined_patterns = joined_uncovered_patterns(
1652             &unmentioned_fields.iter().map(|(_, i)| i).collect::<Vec<_>>(),
1653         );
1654
1655         self.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, pat.hir_id, pat.span, |build| {
1656         let mut lint = build.build("some fields are not explicitly listed");
1657         lint.span_label(pat.span, format!("field{} {} not listed", rustc_errors::pluralize!(unmentioned_fields.len()), joined_patterns));
1658
1659         lint.help(
1660             "ensure that all fields are mentioned explicitly by adding the suggested fields",
1661         );
1662         lint.note(&format!(
1663             "the pattern is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
1664             ty,
1665         ));
1666         lint.emit();
1667     });
1668     }
1669
1670     /// Returns a diagnostic reporting a struct pattern which does not mention some fields.
1671     ///
1672     /// ```text
1673     /// error[E0027]: pattern does not mention field `bar`
1674     ///   --> src/main.rs:15:9
1675     ///    |
1676     /// LL |     let foo::Foo {} = foo::Foo::new();
1677     ///    |         ^^^^^^^^^^^ missing field `bar`
1678     /// ```
1679     fn error_unmentioned_fields(
1680         &self,
1681         pat: &Pat<'_>,
1682         unmentioned_fields: &[(&ty::FieldDef, Ident)],
1683         have_inaccessible_fields: bool,
1684         fields: &'tcx [hir::PatField<'tcx>],
1685     ) -> DiagnosticBuilder<'tcx> {
1686         let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
1687         let field_names = if unmentioned_fields.len() == 1 {
1688             format!("field `{}`{}", unmentioned_fields[0].1, inaccessible)
1689         } else {
1690             let fields = unmentioned_fields
1691                 .iter()
1692                 .map(|(_, name)| format!("`{}`", name))
1693                 .collect::<Vec<String>>()
1694                 .join(", ");
1695             format!("fields {}{}", fields, inaccessible)
1696         };
1697         let mut err = struct_span_err!(
1698             self.tcx.sess,
1699             pat.span,
1700             E0027,
1701             "pattern does not mention {}",
1702             field_names
1703         );
1704         err.span_label(pat.span, format!("missing {}", field_names));
1705         let len = unmentioned_fields.len();
1706         let (prefix, postfix, sp) = match fields {
1707             [] => match &pat.kind {
1708                 PatKind::Struct(path, [], false) => {
1709                     (" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi()))
1710                 }
1711                 _ => return err,
1712             },
1713             [.., field] => {
1714                 // Account for last field having a trailing comma or parse recovery at the tail of
1715                 // the pattern to avoid invalid suggestion (#78511).
1716                 let tail = field.span.shrink_to_hi().with_hi(pat.span.hi());
1717                 match &pat.kind {
1718                     PatKind::Struct(..) => (", ", " }", tail),
1719                     _ => return err,
1720                 }
1721             }
1722         };
1723         err.span_suggestion(
1724             sp,
1725             &format!(
1726                 "include the missing field{} in the pattern{}",
1727                 if len == 1 { "" } else { "s" },
1728                 if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
1729             ),
1730             format!(
1731                 "{}{}{}{}",
1732                 prefix,
1733                 unmentioned_fields
1734                     .iter()
1735                     .map(|(_, name)| name.to_string())
1736                     .collect::<Vec<_>>()
1737                     .join(", "),
1738                 if have_inaccessible_fields { ", .." } else { "" },
1739                 postfix,
1740             ),
1741             Applicability::MachineApplicable,
1742         );
1743         err.span_suggestion(
1744             sp,
1745             &format!(
1746                 "if you don't care about {} missing field{}, you can explicitly ignore {}",
1747                 if len == 1 { "this" } else { "these" },
1748                 if len == 1 { "" } else { "s" },
1749                 if len == 1 { "it" } else { "them" },
1750             ),
1751             format!("{}..{}", prefix, postfix),
1752             Applicability::MachineApplicable,
1753         );
1754         err
1755     }
1756
1757     fn check_pat_box(
1758         &self,
1759         span: Span,
1760         inner: &'tcx Pat<'tcx>,
1761         expected: Ty<'tcx>,
1762         def_bm: BindingMode,
1763         ti: TopInfo<'tcx>,
1764     ) -> Ty<'tcx> {
1765         let tcx = self.tcx;
1766         let (box_ty, inner_ty) = if self.check_dereferenceable(span, expected, &inner) {
1767             // Here, `demand::subtype` is good enough, but I don't
1768             // think any errors can be introduced by using `demand::eqtype`.
1769             let inner_ty = self.next_ty_var(TypeVariableOrigin {
1770                 kind: TypeVariableOriginKind::TypeInference,
1771                 span: inner.span,
1772             });
1773             let box_ty = tcx.mk_box(inner_ty);
1774             self.demand_eqtype_pat(span, expected, box_ty, ti);
1775             (box_ty, inner_ty)
1776         } else {
1777             let err = tcx.ty_error();
1778             (err, err)
1779         };
1780         self.check_pat(&inner, inner_ty, def_bm, ti);
1781         box_ty
1782     }
1783
1784     fn check_pat_ref(
1785         &self,
1786         pat: &'tcx Pat<'tcx>,
1787         inner: &'tcx Pat<'tcx>,
1788         mutbl: hir::Mutability,
1789         expected: Ty<'tcx>,
1790         def_bm: BindingMode,
1791         ti: TopInfo<'tcx>,
1792     ) -> Ty<'tcx> {
1793         let tcx = self.tcx;
1794         let expected = self.shallow_resolve(expected);
1795         let (rptr_ty, inner_ty) = if self.check_dereferenceable(pat.span, expected, &inner) {
1796             // `demand::subtype` would be good enough, but using `eqtype` turns
1797             // out to be equally general. See (note_1) for details.
1798
1799             // Take region, inner-type from expected type if we can,
1800             // to avoid creating needless variables. This also helps with
1801             // the bad  interactions of the given hack detailed in (note_1).
1802             debug!("check_pat_ref: expected={:?}", expected);
1803             match *expected.kind() {
1804                 ty::Ref(_, r_ty, r_mutbl) if r_mutbl == mutbl => (expected, r_ty),
1805                 _ => {
1806                     let inner_ty = self.next_ty_var(TypeVariableOrigin {
1807                         kind: TypeVariableOriginKind::TypeInference,
1808                         span: inner.span,
1809                     });
1810                     let rptr_ty = self.new_ref_ty(pat.span, mutbl, inner_ty);
1811                     debug!("check_pat_ref: demanding {:?} = {:?}", expected, rptr_ty);
1812                     let err = self.demand_eqtype_pat_diag(pat.span, expected, rptr_ty, ti);
1813
1814                     // Look for a case like `fn foo(&foo: u32)` and suggest
1815                     // `fn foo(foo: &u32)`
1816                     if let Some(mut err) = err {
1817                         self.borrow_pat_suggestion(&mut err, &pat, &inner, &expected);
1818                         err.emit();
1819                     }
1820                     (rptr_ty, inner_ty)
1821                 }
1822             }
1823         } else {
1824             let err = tcx.ty_error();
1825             (err, err)
1826         };
1827         self.check_pat(&inner, inner_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
1828         rptr_ty
1829     }
1830
1831     /// Create a reference type with a fresh region variable.
1832     fn new_ref_ty(&self, span: Span, mutbl: hir::Mutability, ty: Ty<'tcx>) -> Ty<'tcx> {
1833         let region = self.next_region_var(infer::PatternRegion(span));
1834         let mt = ty::TypeAndMut { ty, mutbl };
1835         self.tcx.mk_ref(region, mt)
1836     }
1837
1838     /// Type check a slice pattern.
1839     ///
1840     /// Syntactically, these look like `[pat_0, ..., pat_n]`.
1841     /// Semantically, we are type checking a pattern with structure:
1842     /// ```
1843     /// [before_0, ..., before_n, (slice, after_0, ... after_n)?]
1844     /// ```
1845     /// The type of `slice`, if it is present, depends on the `expected` type.
1846     /// If `slice` is missing, then so is `after_i`.
1847     /// If `slice` is present, it can still represent 0 elements.
1848     fn check_pat_slice(
1849         &self,
1850         span: Span,
1851         before: &'tcx [Pat<'tcx>],
1852         slice: Option<&'tcx Pat<'tcx>>,
1853         after: &'tcx [Pat<'tcx>],
1854         expected: Ty<'tcx>,
1855         def_bm: BindingMode,
1856         ti: TopInfo<'tcx>,
1857     ) -> Ty<'tcx> {
1858         let expected = self.structurally_resolved_type(span, expected);
1859         let (element_ty, opt_slice_ty, inferred) = match *expected.kind() {
1860             // An array, so we might have something like `let [a, b, c] = [0, 1, 2];`.
1861             ty::Array(element_ty, len) => {
1862                 let min = before.len() as u64 + after.len() as u64;
1863                 let (opt_slice_ty, expected) =
1864                     self.check_array_pat_len(span, element_ty, expected, slice, len, min);
1865                 // `opt_slice_ty.is_none()` => `slice.is_none()`.
1866                 // Note, though, that opt_slice_ty could be `Some(error_ty)`.
1867                 assert!(opt_slice_ty.is_some() || slice.is_none());
1868                 (element_ty, opt_slice_ty, expected)
1869             }
1870             ty::Slice(element_ty) => (element_ty, Some(expected), expected),
1871             // The expected type must be an array or slice, but was neither, so error.
1872             _ => {
1873                 if !expected.references_error() {
1874                     self.error_expected_array_or_slice(span, expected, ti);
1875                 }
1876                 let err = self.tcx.ty_error();
1877                 (err, Some(err), err)
1878             }
1879         };
1880
1881         // Type check all the patterns before `slice`.
1882         for elt in before {
1883             self.check_pat(&elt, element_ty, def_bm, ti);
1884         }
1885         // Type check the `slice`, if present, against its expected type.
1886         if let Some(slice) = slice {
1887             self.check_pat(&slice, opt_slice_ty.unwrap(), def_bm, ti);
1888         }
1889         // Type check the elements after `slice`, if present.
1890         for elt in after {
1891             self.check_pat(&elt, element_ty, def_bm, ti);
1892         }
1893         inferred
1894     }
1895
1896     /// Type check the length of an array pattern.
1897     ///
1898     /// Returns both the type of the variable length pattern (or `None`), and the potentially
1899     /// inferred array type. We only return `None` for the slice type if `slice.is_none()`.
1900     fn check_array_pat_len(
1901         &self,
1902         span: Span,
1903         element_ty: Ty<'tcx>,
1904         arr_ty: Ty<'tcx>,
1905         slice: Option<&'tcx Pat<'tcx>>,
1906         len: &ty::Const<'tcx>,
1907         min_len: u64,
1908     ) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
1909         if let Some(len) = len.try_eval_usize(self.tcx, self.param_env) {
1910             // Now we know the length...
1911             if slice.is_none() {
1912                 // ...and since there is no variable-length pattern,
1913                 // we require an exact match between the number of elements
1914                 // in the array pattern and as provided by the matched type.
1915                 if min_len == len {
1916                     return (None, arr_ty);
1917                 }
1918
1919                 self.error_scrutinee_inconsistent_length(span, min_len, len);
1920             } else if let Some(pat_len) = len.checked_sub(min_len) {
1921                 // The variable-length pattern was there,
1922                 // so it has an array type with the remaining elements left as its size...
1923                 return (Some(self.tcx.mk_array(element_ty, pat_len)), arr_ty);
1924             } else {
1925                 // ...however, in this case, there were no remaining elements.
1926                 // That is, the slice pattern requires more than the array type offers.
1927                 self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len);
1928             }
1929         } else if slice.is_none() {
1930             // We have a pattern with a fixed length,
1931             // which we can use to infer the length of the array.
1932             let updated_arr_ty = self.tcx.mk_array(element_ty, min_len);
1933             self.demand_eqtype(span, updated_arr_ty, arr_ty);
1934             return (None, updated_arr_ty);
1935         } else {
1936             // We have a variable-length pattern and don't know the array length.
1937             // This happens if we have e.g.,
1938             // `let [a, b, ..] = arr` where `arr: [T; N]` where `const N: usize`.
1939             self.error_scrutinee_unfixed_length(span);
1940         }
1941
1942         // If we get here, we must have emitted an error.
1943         (Some(self.tcx.ty_error()), arr_ty)
1944     }
1945
1946     fn error_scrutinee_inconsistent_length(&self, span: Span, min_len: u64, size: u64) {
1947         struct_span_err!(
1948             self.tcx.sess,
1949             span,
1950             E0527,
1951             "pattern requires {} element{} but array has {}",
1952             min_len,
1953             pluralize!(min_len),
1954             size,
1955         )
1956         .span_label(span, format!("expected {} element{}", size, pluralize!(size)))
1957         .emit();
1958     }
1959
1960     fn error_scrutinee_with_rest_inconsistent_length(&self, span: Span, min_len: u64, size: u64) {
1961         struct_span_err!(
1962             self.tcx.sess,
1963             span,
1964             E0528,
1965             "pattern requires at least {} element{} but array has {}",
1966             min_len,
1967             pluralize!(min_len),
1968             size,
1969         )
1970         .span_label(
1971             span,
1972             format!("pattern cannot match array of {} element{}", size, pluralize!(size),),
1973         )
1974         .emit();
1975     }
1976
1977     fn error_scrutinee_unfixed_length(&self, span: Span) {
1978         struct_span_err!(
1979             self.tcx.sess,
1980             span,
1981             E0730,
1982             "cannot pattern-match on an array without a fixed length",
1983         )
1984         .emit();
1985     }
1986
1987     fn error_expected_array_or_slice(&self, span: Span, expected_ty: Ty<'tcx>, ti: TopInfo<'tcx>) {
1988         let mut err = struct_span_err!(
1989             self.tcx.sess,
1990             span,
1991             E0529,
1992             "expected an array or slice, found `{}`",
1993             expected_ty
1994         );
1995         if let ty::Ref(_, ty, _) = expected_ty.kind() {
1996             if let ty::Array(..) | ty::Slice(..) = ty.kind() {
1997                 err.help("the semantics of slice patterns changed recently; see issue #62254");
1998             }
1999         } else if Autoderef::new(&self.infcx, self.param_env, self.body_id, span, expected_ty, span)
2000             .any(|(ty, _)| matches!(ty.kind(), ty::Slice(..)))
2001         {
2002             if let (Some(span), true) = (ti.span, ti.origin_expr) {
2003                 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2004                     err.span_suggestion(
2005                         span,
2006                         "consider slicing here",
2007                         format!("{}[..]", snippet),
2008                         Applicability::MachineApplicable,
2009                     );
2010                 }
2011             }
2012         }
2013         err.span_label(span, format!("pattern cannot match with input type `{}`", expected_ty));
2014         err.emit();
2015     }
2016 }