1 use crate::check::FnCtxt;
3 use rustc_ast::util::lev_distance::find_best_match_for_name;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
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, BindingMode, Ty, TypeFoldable};
14 use rustc_span::hygiene::DesugaringKind;
15 use rustc_span::source_map::{Span, Spanned};
16 use rustc_trait_selection::traits::{ObligationCause, Pattern};
19 use std::collections::hash_map::Entry::{Occupied, Vacant};
21 use super::report_unexpected_variant_res;
23 const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
24 This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
25 pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
26 this type has no compile-time size. Therefore, all accesses to trait types must be through \
27 pointers. If you encounter this error you should try to avoid dereferencing the pointer.
29 You can read more about trait objects in the Trait Objects section of the Reference: \
30 https://doc.rust-lang.org/reference/types.html#trait-objects";
32 /// Information about the expected type at the top level of type checking a pattern.
34 /// **NOTE:** This is only for use by diagnostics. Do NOT use for type checking logic!
35 #[derive(Copy, Clone)]
36 struct TopInfo<'tcx> {
37 /// The `expected` type at the top level of type checking a pattern.
39 /// Was the origin of the `span` from a scrutinee expression?
41 /// Otherwise there is no scrutinee and it could be e.g. from the type of a formal parameter.
43 /// The span giving rise to the `expected` type, if one could be provided.
45 /// If `origin_expr` is `true`, then this is the span of the scrutinee as in:
47 /// - `match scrutinee { ... }`
48 /// - `let _ = scrutinee;`
50 /// This is used to point to add context in type errors.
51 /// In the following example, `span` corresponds to the `a + b` expression:
54 /// error[E0308]: mismatched types
55 /// --> src/main.rs:L:C
57 /// L | let temp: usize = match a + b {
58 /// | ----- this expression has type `usize`
59 /// L | Ok(num) => num,
60 /// | ^^^^^^^ expected `usize`, found enum `std::result::Result`
62 /// = note: expected type `usize`
63 /// found type `std::result::Result<_, _>`
66 /// This refers to the parent pattern. Used to provide extra diagnostic information on errors.
68 /// error[E0308]: mismatched types
69 /// --> $DIR/const-in-struct-pat.rs:8:17
72 /// | --------- unit struct defined here
74 /// L | let Thing { f } = t;
77 /// | expected struct `std::string::String`, found struct `f`
78 /// | `f` is interpreted as a unit struct, not a new binding
79 /// | help: bind the struct field to a different name instead: `f: other_f`
81 parent_pat: Option<&'tcx Pat<'tcx>>,
84 impl<'tcx> FnCtxt<'_, 'tcx> {
85 fn pattern_cause(&self, ti: TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
86 let code = Pattern { span: ti.span, root_ty: ti.expected, origin_expr: ti.origin_expr };
87 self.cause(cause_span, code)
90 fn demand_eqtype_pat_diag(
96 ) -> Option<DiagnosticBuilder<'tcx>> {
97 self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
100 fn demand_eqtype_pat(
107 self.demand_eqtype_pat_diag(cause_span, expected, actual, ti).map(|mut err| err.emit());
111 const INITIAL_BM: BindingMode = BindingMode::BindByValue(hir::Mutability::Not);
113 /// Mode for adjusting the expected type and binding mode.
115 /// Peel off all immediate reference types.
117 /// Reset binding mode to the initial mode.
119 /// Pass on the input binding mode and expected type.
123 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
124 /// Type check the given top level pattern against the `expected` type.
126 /// If a `Some(span)` is provided and `origin_expr` holds,
127 /// then the `span` represents the scrutinee's span.
128 /// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.
130 /// Otherwise, `Some(span)` represents the span of a type expression
131 /// which originated the `expected` type.
132 pub fn check_pat_top(
134 pat: &'tcx Pat<'tcx>,
139 let info = TopInfo { expected, origin_expr, span, parent_pat: None };
140 self.check_pat(pat, expected, INITIAL_BM, info);
143 /// Type check the given `pat` against the `expected` type
144 /// with the provided `def_bm` (default binding mode).
146 /// Outside of this module, `check_pat_top` should always be used.
147 /// Conversely, inside this module, `check_pat_top` should never be used.
150 pat: &'tcx Pat<'tcx>,
155 debug!("check_pat(pat={:?},expected={:?},def_bm={:?})", pat, expected, def_bm);
157 let path_res = match &pat.kind {
158 PatKind::Path(qpath) => Some(self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span)),
161 let adjust_mode = self.calc_adjust_mode(pat, path_res.map(|(res, ..)| res));
162 let (expected, def_bm) = self.calc_default_binding_mode(pat, expected, def_bm, adjust_mode);
164 let ty = match pat.kind {
165 PatKind::Wild => expected,
166 PatKind::Lit(lt) => self.check_pat_lit(pat.span, lt, expected, ti),
167 PatKind::Range(lhs, rhs, _) => self.check_pat_range(pat.span, lhs, rhs, expected, ti),
168 PatKind::Binding(ba, var_id, _, sub) => {
169 self.check_pat_ident(pat, ba, var_id, sub, expected, def_bm, ti)
171 PatKind::TupleStruct(ref qpath, subpats, ddpos) => {
172 self.check_pat_tuple_struct(pat, qpath, subpats, ddpos, expected, def_bm, ti)
174 PatKind::Path(_) => self.check_pat_path(pat, path_res.unwrap(), expected, ti),
175 PatKind::Struct(ref qpath, fields, etc) => {
176 self.check_pat_struct(pat, qpath, fields, etc, expected, def_bm, ti)
178 PatKind::Or(pats) => {
179 let parent_pat = Some(pat);
181 self.check_pat(pat, expected, def_bm, TopInfo { parent_pat, ..ti });
185 PatKind::Tuple(elements, ddpos) => {
186 self.check_pat_tuple(pat.span, elements, ddpos, expected, def_bm, ti)
188 PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, def_bm, ti),
189 PatKind::Ref(inner, mutbl) => {
190 self.check_pat_ref(pat, inner, mutbl, expected, def_bm, ti)
192 PatKind::Slice(before, slice, after) => {
193 self.check_pat_slice(pat.span, before, slice, after, expected, def_bm, ti)
197 self.write_ty(pat.hir_id, ty);
199 // (note_1): In most of the cases where (note_1) is referenced
200 // (literals and constants being the exception), we relate types
201 // using strict equality, even though subtyping would be sufficient.
202 // There are a few reasons for this, some of which are fairly subtle
203 // and which cost me (nmatsakis) an hour or two debugging to remember,
204 // so I thought I'd write them down this time.
206 // 1. There is no loss of expressiveness here, though it does
207 // cause some inconvenience. What we are saying is that the type
208 // of `x` becomes *exactly* what is expected. This can cause unnecessary
209 // errors in some cases, such as this one:
212 // fn foo<'x>(x: &'x int) {
219 // The reason we might get an error is that `z` might be
220 // assigned a type like `&'x int`, and then we would have
221 // a problem when we try to assign `&a` to `z`, because
222 // the lifetime of `&a` (i.e., the enclosing block) is
223 // shorter than `'x`.
225 // HOWEVER, this code works fine. The reason is that the
226 // expected type here is whatever type the user wrote, not
227 // the initializer's type. In this case the user wrote
228 // nothing, so we are going to create a type variable `Z`.
229 // Then we will assign the type of the initializer (`&'x
230 // int`) as a subtype of `Z`: `&'x int <: Z`. And hence we
231 // will instantiate `Z` as a type `&'0 int` where `'0` is
232 // a fresh region variable, with the constraint that `'x :
233 // '0`. So basically we're all set.
235 // Note that there are two tests to check that this remains true
236 // (`regions-reassign-{match,let}-bound-pointer.rs`).
238 // 2. Things go horribly wrong if we use subtype. The reason for
239 // THIS is a fairly subtle case involving bound regions. See the
240 // `givens` field in `region_constraints`, as well as the test
241 // `regions-relate-bound-regions-on-closures-to-inference-variables.rs`,
242 // for details. Short version is that we must sometimes detect
243 // relationships between specific region variables and regions
244 // bound in a closure signature, and that detection gets thrown
245 // off when we substitute fresh region variables here to enable
249 /// Compute the new expected type and default binding mode from the old ones
250 /// as well as the pattern form we are currently checking.
251 fn calc_default_binding_mode(
253 pat: &'tcx Pat<'tcx>,
256 adjust_mode: AdjustMode,
257 ) -> (Ty<'tcx>, BindingMode) {
259 AdjustMode::Pass => (expected, def_bm),
260 AdjustMode::Reset => (expected, INITIAL_BM),
261 AdjustMode::Peel => self.peel_off_references(pat, expected, def_bm),
265 /// How should the binding mode and expected type be adjusted?
267 /// When the pattern is a path pattern, `opt_path_res` must be `Some(res)`.
268 fn calc_adjust_mode(&self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Res>) -> AdjustMode {
270 // Type checking these product-like types successfully always require
271 // that the expected type be of those types and not reference types.
273 | PatKind::TupleStruct(..)
277 | PatKind::Slice(..) => AdjustMode::Peel,
278 // String and byte-string literals result in types `&str` and `&[u8]` respectively.
279 // All other literals result in non-reference types.
280 // As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo {}`.
281 PatKind::Lit(lt) => match self.check_expr(lt).kind {
282 ty::Ref(..) => AdjustMode::Pass,
283 _ => AdjustMode::Peel,
285 PatKind::Path(_) => match opt_path_res.unwrap() {
286 // These constants can be of a reference type, e.g. `const X: &u8 = &0;`.
287 // Peeling the reference types too early will cause type checking failures.
288 // Although it would be possible to *also* peel the types of the constants too.
289 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => AdjustMode::Pass,
290 // In the `ValueNS`, we have `SelfCtor(..) | Ctor(_, Const), _)` remaining which
291 // could successfully compile. The former being `Self` requires a unit struct.
292 // In either case, and unlike constants, the pattern itself cannot be
293 // a reference type wherefore peeling doesn't give up any expressivity.
294 _ => AdjustMode::Peel,
296 // When encountering a `& mut? pat` pattern, reset to "by value".
297 // This is so that `x` and `y` here are by value, as they appear to be:
300 // match &(&22, &44) {
306 PatKind::Ref(..) => AdjustMode::Reset,
307 // A `_` pattern works with any expected type, so there's no need to do anything.
309 // Bindings also work with whatever the expected type is,
310 // and moreover if we peel references off, that will give us the wrong binding type.
311 // Also, we can have a subpattern `binding @ pat`.
312 // Each side of the `@` should be treated independently (like with OR-patterns).
313 | PatKind::Binding(..)
314 // An OR-pattern just propagates to each individual alternative.
315 // This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`.
316 // In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`.
317 | PatKind::Or(_) => AdjustMode::Pass,
321 /// Peel off as many immediately nested `& mut?` from the expected type as possible
322 /// and return the new expected type and binding default binding mode.
323 /// The adjustments vector, if non-empty is stored in a table.
324 fn peel_off_references(
326 pat: &'tcx Pat<'tcx>,
328 mut def_bm: BindingMode,
329 ) -> (Ty<'tcx>, BindingMode) {
330 let mut expected = self.resolve_vars_with_obligations(&expected);
332 // Peel off as many `&` or `&mut` from the scrutinee type as possible. For example,
333 // for `match &&&mut Some(5)` the loop runs three times, aborting when it reaches
334 // the `Some(5)` which is not of type Ref.
336 // For each ampersand peeled off, update the binding mode and push the original
337 // type into the adjustments vector.
339 // See the examples in `ui/match-defbm*.rs`.
340 let mut pat_adjustments = vec![];
341 while let ty::Ref(_, inner_ty, inner_mutability) = expected.kind {
342 debug!("inspecting {:?}", expected);
344 debug!("current discriminant is Ref, inserting implicit deref");
345 // Preserve the reference type. We'll need it later during HAIR lowering.
346 pat_adjustments.push(expected);
349 def_bm = ty::BindByReference(match def_bm {
350 // If default binding mode is by value, make it `ref` or `ref mut`
351 // (depending on whether we observe `&` or `&mut`).
353 // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`).
354 ty::BindByReference(hir::Mutability::Mut) => inner_mutability,
355 // Once a `ref`, always a `ref`.
356 // This is because a `& &mut` cannot mutate the underlying value.
357 ty::BindByReference(m @ hir::Mutability::Not) => m,
361 if !pat_adjustments.is_empty() {
362 debug!("default binding mode is now {:?}", def_bm);
363 self.inh.tables.borrow_mut().pat_adjustments_mut().insert(pat.hir_id, pat_adjustments);
372 lt: &hir::Expr<'tcx>,
376 // We've already computed the type above (when checking for a non-ref pat),
377 // so avoid computing it again.
378 let ty = self.node_ty(lt.hir_id);
380 // Byte string patterns behave the same way as array patterns
381 // They can denote both statically and dynamically-sized byte arrays.
383 if let hir::ExprKind::Lit(Spanned { node: ast::LitKind::ByteStr(_), .. }) = lt.kind {
384 let expected = self.structurally_resolved_type(span, expected);
385 if let ty::Ref(_, ty::TyS { kind: ty::Slice(_), .. }, _) = expected.kind {
387 pat_ty = tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_slice(tcx.types.u8));
391 // Somewhat surprising: in this case, the subtyping relation goes the
392 // opposite way as the other cases. Actually what we really want is not
393 // a subtyping relation at all but rather that there exists a LUB
394 // (so that they can be compared). However, in practice, constants are
395 // always scalars or strings. For scalars subtyping is irrelevant,
396 // and for strings `ty` is type is `&'static str`, so if we say that
398 // &'static str <: expected
400 // then that's equivalent to there existing a LUB.
401 let cause = self.pattern_cause(ti, span);
402 if let Some(mut err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
406 // In the case of `if`- and `while`-expressions we've already checked
407 // that `scrutinee: bool`. We know that the pattern is `true`,
408 // so an error here would be a duplicate and from the wrong POV.
409 s.is_desugaring(DesugaringKind::CondTemporary)
421 lhs: Option<&'tcx hir::Expr<'tcx>>,
422 rhs: Option<&'tcx hir::Expr<'tcx>>,
426 let calc_side = |opt_expr: Option<&'tcx hir::Expr<'tcx>>| match opt_expr {
427 None => (None, None),
429 let ty = self.check_expr(expr);
430 // Check that the end-point is of numeric or char type.
431 let fail = !(ty.is_numeric() || ty.is_char() || ty.references_error());
432 (Some(ty), Some((fail, ty, expr.span)))
435 let (lhs_ty, lhs) = calc_side(lhs);
436 let (rhs_ty, rhs) = calc_side(rhs);
438 if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
439 // There exists a side that didn't meet our criteria that the end-point
440 // be of a numeric or char type, as checked in `calc_side` above.
441 self.emit_err_pat_range(span, lhs, rhs);
442 return self.tcx.types.err;
445 // Now that we know the types can be unified we find the unified type
446 // and use it to type the entire expression.
447 let common_type = self.resolve_vars_if_possible(&lhs_ty.or(rhs_ty).unwrap_or(expected));
449 // Subtyping doesn't matter here, as the value is some kind of scalar.
450 let demand_eqtype = |x, y| {
451 if let Some((_, x_ty, x_span)) = x {
452 self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti).map(|mut err| {
453 if let Some((_, y_ty, y_span)) = y {
454 self.endpoint_has_type(&mut err, y_span, y_ty);
460 demand_eqtype(lhs, rhs);
461 demand_eqtype(rhs, lhs);
466 fn endpoint_has_type(&self, err: &mut DiagnosticBuilder<'_>, span: Span, ty: Ty<'_>) {
467 if !ty.references_error() {
468 err.span_label(span, &format!("this is of type `{}`", ty));
472 fn emit_err_pat_range(
475 lhs: Option<(bool, Ty<'tcx>, Span)>,
476 rhs: Option<(bool, Ty<'tcx>, Span)>,
478 let span = match (lhs, rhs) {
479 (Some((true, ..)), Some((true, ..))) => span,
480 (Some((true, _, sp)), _) => sp,
481 (_, Some((true, _, sp))) => sp,
482 _ => span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
484 let mut err = struct_span_err!(
488 "only char and numeric types are allowed in range patterns"
490 let msg = |ty| format!("this is of type `{}` but it should be `char` or numeric", ty);
491 let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
492 err.span_label(first_span, &msg(first_ty));
493 if let Some((_, ty, sp)) = second {
494 self.endpoint_has_type(&mut err, sp, ty);
498 (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
499 err.span_label(lhs_sp, &msg(lhs_ty));
500 err.span_label(rhs_sp, &msg(rhs_ty));
502 (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
503 (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
504 _ => span_bug!(span, "Impossible, verified above."),
506 if self.tcx.sess.teach(&err.get_code().unwrap()) {
508 "In a match expression, only numbers and characters can be matched \
509 against a range. This is because the compiler checks that the range \
510 is non-empty at compile-time, and is unable to evaluate arbitrary \
511 comparison functions. If you want to capture values of an orderable \
512 type between two end-points, you can use a guard.",
520 pat: &'tcx Pat<'tcx>,
521 ba: hir::BindingAnnotation,
523 sub: Option<&'tcx Pat<'tcx>>,
528 // Determine the binding mode...
530 hir::BindingAnnotation::Unannotated => def_bm,
531 _ => BindingMode::convert(ba),
533 // ...and store it in a side table:
534 self.inh.tables.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
536 debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
538 let local_ty = self.local_ty(pat.span, pat.hir_id).decl_ty;
539 let eq_ty = match bm {
540 ty::BindByReference(mutbl) => {
541 // If the binding is like `ref x | ref mut x`,
542 // then `x` is assigned a value of type `&M T` where M is the
543 // mutability and T is the expected type.
545 // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)`
546 // is required. However, we use equality, which is stronger.
547 // See (note_1) for an explanation.
548 self.new_ref_ty(pat.span, mutbl, expected)
550 // Otherwise, the type of x is the expected type `T`.
551 ty::BindByValue(_) => {
552 // As above, `T <: typeof(x)` is required, but we use equality, see (note_1).
556 self.demand_eqtype_pat(pat.span, eq_ty, local_ty, ti);
558 // If there are multiple arms, make sure they all agree on
559 // what the type of the binding `x` ought to be.
560 if var_id != pat.hir_id {
561 self.check_binding_alt_eq_ty(pat.span, var_id, local_ty, ti);
564 if let Some(p) = sub {
565 self.check_pat(&p, expected, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
571 fn check_binding_alt_eq_ty(&self, span: Span, var_id: HirId, ty: Ty<'tcx>, ti: TopInfo<'tcx>) {
572 let var_ty = self.local_ty(span, var_id).decl_ty;
573 if let Some(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
574 let hir = self.tcx.hir();
575 let var_ty = self.resolve_vars_with_obligations(var_ty);
576 let msg = format!("first introduced with type `{}` here", var_ty);
577 err.span_label(hir.span(var_id), msg);
578 let in_match = hir.parent_iter(var_id).any(|(_, n)| {
581 hir::Node::Expr(hir::Expr {
582 kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
587 let pre = if in_match { "in the same arm, " } else { "" };
588 err.note(&format!("{}a binding must have the same type in all alternatives", pre));
593 fn borrow_pat_suggestion(
595 err: &mut DiagnosticBuilder<'_>,
601 if let PatKind::Binding(..) = inner.kind {
602 let binding_parent_id = tcx.hir().get_parent_node(pat.hir_id);
603 let binding_parent = tcx.hir().get(binding_parent_id);
604 debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent);
605 match binding_parent {
606 hir::Node::Param(hir::Param { span, .. }) => {
607 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) {
610 &format!("did you mean `{}`", snippet),
611 format!(" &{}", expected),
612 Applicability::MachineApplicable,
616 hir::Node::Arm(_) | hir::Node::Pat(_) => {
617 // rely on match ergonomics or it might be nested `&&pat`
618 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) {
621 "you can probably remove the explicit borrow",
623 Applicability::MaybeIncorrect,
627 _ => {} // don't provide suggestions in other cases #55175
632 pub fn check_dereferenceable(&self, span: Span, expected: Ty<'tcx>, inner: &Pat<'_>) -> bool {
633 if let PatKind::Binding(..) = inner.kind {
634 if let Some(mt) = self.shallow_resolve(expected).builtin_deref(true) {
635 if let ty::Dynamic(..) = mt.ty.kind {
636 // This is "x = SomeTrait" being reduced from
637 // "let &x = &SomeTrait" or "let box x = Box<SomeTrait>", an error.
638 let type_str = self.ty_to_string(expected);
639 let mut err = struct_span_err!(
643 "type `{}` cannot be dereferenced",
646 err.span_label(span, format!("type `{}` cannot be dereferenced", type_str));
647 if self.tcx.sess.teach(&err.get_code().unwrap()) {
648 err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
660 pat: &'tcx Pat<'tcx>,
661 qpath: &hir::QPath<'_>,
662 fields: &'tcx [hir::FieldPat<'tcx>],
668 // Resolve the path and check the definition for errors.
669 let (variant, pat_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, pat.hir_id)
673 for field in fields {
674 let ti = TopInfo { parent_pat: Some(&pat), ..ti };
675 self.check_pat(&field.pat, self.tcx.types.err, def_bm, ti);
677 return self.tcx.types.err;
680 // Type-check the path.
681 self.demand_eqtype_pat(pat.span, expected, pat_ty, ti);
683 // Type-check subpatterns.
684 if self.check_struct_pat_fields(pat_ty, &pat, variant, fields, etc, def_bm, ti) {
694 path_resolution: (Res, Option<Ty<'tcx>>, &'b [hir::PathSegment<'b>]),
700 // We have already resolved the path.
701 let (res, opt_ty, segments) = path_resolution;
704 self.set_tainted_by_errors();
705 return tcx.types.err;
707 Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fictive | CtorKind::Fn), _) => {
708 report_unexpected_variant_res(tcx, res, pat.span);
709 return tcx.types.err;
713 DefKind::Ctor(_, CtorKind::Const)
715 | DefKind::AssocConst
716 | DefKind::ConstParam,
719 _ => bug!("unexpected pattern resolution: {:?}", res),
722 // Type-check the path.
723 let (pat_ty, pat_res) =
724 self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id);
726 self.demand_suptype_with_origin(&self.pattern_cause(ti, pat.span), expected, pat_ty)
728 self.emit_bad_pat_path(err, pat.span, res, pat_res, segments, ti.parent_pat);
733 fn emit_bad_pat_path(
735 mut e: DiagnosticBuilder<'_>,
739 segments: &'b [hir::PathSegment<'b>],
740 parent_pat: Option<&Pat<'_>>,
742 if let Some(span) = self.tcx.hir().res_span(pat_res) {
743 e.span_label(span, &format!("{} defined here", res.descr()));
744 if let [hir::PathSegment { ident, .. }] = &*segments {
748 "`{}` is interpreted as {} {}, not a new binding",
755 Some(Pat { kind: hir::PatKind::Struct(..), .. }) => {
756 e.span_suggestion_verbose(
757 ident.span.shrink_to_hi(),
758 "bind the struct field to a different name instead",
759 format!(": other_{}", ident.as_str().to_lowercase()),
760 Applicability::HasPlaceholders,
764 let msg = "introduce a new binding instead";
765 let sugg = format!("other_{}", ident.as_str().to_lowercase());
766 e.span_suggestion(ident.span, msg, sugg, Applicability::HasPlaceholders);
774 fn check_pat_tuple_struct(
776 pat: &'tcx Pat<'tcx>,
777 qpath: &hir::QPath<'_>,
778 subpats: &'tcx [&'tcx Pat<'tcx>],
779 ddpos: Option<usize>,
786 let parent_pat = Some(pat);
788 self.check_pat(&pat, tcx.types.err, def_bm, TopInfo { parent_pat, ..ti });
791 let report_unexpected_res = |res: Res| {
792 let sm = tcx.sess.source_map();
794 .span_to_snippet(sm.span_until_char(pat.span, '('))
795 .map_or(String::new(), |s| format!(" `{}`", s.trim_end()));
797 "expected tuple struct or tuple variant, found {}{}",
802 let mut err = struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg);
804 Res::Def(DefKind::Fn | DefKind::AssocFn, _) => {
805 err.span_label(pat.span, "`fn` calls are not allowed in patterns");
807 "for more information, visit \
808 https://doc.rust-lang.org/book/ch18-00-patterns.html",
812 err.span_label(pat.span, "not a tuple variant or struct");
819 // Resolve the path and check the definition for errors.
820 let (res, opt_ty, segments) = self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span);
822 self.set_tainted_by_errors();
824 return self.tcx.types.err;
827 // Type-check the path.
829 self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.hir_id);
831 report_unexpected_res(res);
832 return tcx.types.err;
835 let variant = match res {
837 self.set_tainted_by_errors();
839 return tcx.types.err;
841 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => {
842 report_unexpected_res(res);
843 return tcx.types.err;
845 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
846 _ => bug!("unexpected pattern resolution: {:?}", res),
849 // Replace constructor type with constructed type for tuple struct patterns.
850 let pat_ty = pat_ty.fn_sig(tcx).output();
851 let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
853 // Type-check the tuple struct pattern against the expected type.
854 let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, ti);
855 let had_err = diag.is_some();
856 diag.map(|mut err| err.emit());
858 // Type-check subpatterns.
859 if subpats.len() == variant.fields.len()
860 || subpats.len() < variant.fields.len() && ddpos.is_some()
862 let substs = match pat_ty.kind {
863 ty::Adt(_, substs) => substs,
864 _ => bug!("unexpected pattern type {:?}", pat_ty),
866 for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
867 let field_ty = self.field_ty(subpat.span, &variant.fields[i], substs);
868 self.check_pat(&subpat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
870 self.tcx.check_stability(variant.fields[i].did, Some(pat.hir_id), subpat.span);
873 // Pattern has wrong number of fields.
874 self.e0023(pat.span, res, qpath, subpats, &variant.fields, expected, had_err);
876 return tcx.types.err;
885 qpath: &hir::QPath<'_>,
886 subpats: &'tcx [&'tcx Pat<'tcx>],
887 fields: &'tcx [ty::FieldDef],
891 let subpats_ending = pluralize!(subpats.len());
892 let fields_ending = pluralize!(fields.len());
893 let res_span = self.tcx.def_span(res.def_id());
894 let mut err = struct_span_err!(
898 "this pattern has {} field{}, but the corresponding {} has {} field{}",
907 format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len(),),
909 .span_label(res_span, format!("{} defined here", res.descr()));
911 // Identify the case `Some(x, y)` where the expected type is e.g. `Option<(T, U)>`.
912 // More generally, the expected type wants a tuple variant with one field of an
913 // N-arity-tuple, e.g., `V_i((p_0, .., p_N))`. Meanwhile, the user supplied a pattern
914 // with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`.
915 let missing_parenthesis = match (&expected.kind, fields, had_err) {
916 // #67037: only do this if we could successfully type-check the expected type against
917 // the tuple struct pattern. Otherwise the substs could get out of range on e.g.,
918 // `let P() = U;` where `P != U` with `struct P<T>(T);`.
919 (ty::Adt(_, substs), [field], false) => {
920 let field_ty = self.field_ty(pat_span, field, substs);
921 match field_ty.kind {
922 ty::Tuple(_) => field_ty.tuple_fields().count() == subpats.len(),
928 if missing_parenthesis {
929 let (left, right) = match subpats {
930 // This is the zero case; we aim to get the "hi" part of the `QPath`'s
931 // span as the "lo" and then the "hi" part of the pattern's span as the "hi".
934 // help: missing parenthesis
936 // L | let A(()) = A(());
939 let qpath_span = match qpath {
940 hir::QPath::Resolved(_, path) => path.span,
941 hir::QPath::TypeRelative(_, ps) => ps.ident.span,
943 (qpath_span.shrink_to_hi(), pat_span)
945 // Easy case. Just take the "lo" of the first sub-pattern and the "hi" of the
946 // last sub-pattern. In the case of `A(x)` the first and last may coincide.
949 // help: missing parenthesis
951 // L | let A((x, y)) = A((1, 2));
953 [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
955 err.multipart_suggestion(
956 "missing parenthesis",
957 vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())],
958 Applicability::MachineApplicable,
968 elements: &'tcx [&'tcx Pat<'tcx>],
969 ddpos: Option<usize>,
975 let mut expected_len = elements.len();
977 // Require known type only when `..` is present.
978 if let ty::Tuple(ref tys) = self.structurally_resolved_type(span, expected).kind {
979 expected_len = tys.len();
982 let max_len = cmp::max(expected_len, elements.len());
984 let element_tys_iter = (0..max_len).map(|_| {
985 GenericArg::from(self.next_ty_var(
986 // FIXME: `MiscVariable` for now -- obtaining the span and name information
987 // from all tuple elements isn't trivial.
988 TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span },
991 let element_tys = tcx.mk_substs(element_tys_iter);
992 let pat_ty = tcx.mk_ty(ty::Tuple(element_tys));
993 if let Some(mut err) = self.demand_eqtype_pat_diag(span, expected, pat_ty, ti) {
995 // Walk subpatterns with an expected type of `err` in this case to silence
996 // further errors being emitted when using the bindings. #50333
997 let element_tys_iter = (0..max_len).map(|_| tcx.types.err);
998 for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
999 self.check_pat(elem, &tcx.types.err, def_bm, ti);
1001 tcx.mk_tup(element_tys_iter)
1003 for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1004 self.check_pat(elem, &element_tys[i].expect_ty(), def_bm, ti);
1010 fn check_struct_pat_fields(
1013 pat: &'tcx Pat<'tcx>,
1014 variant: &'tcx ty::VariantDef,
1015 fields: &'tcx [hir::FieldPat<'tcx>],
1017 def_bm: BindingMode,
1022 let (substs, adt) = match adt_ty.kind {
1023 ty::Adt(adt, substs) => (substs, adt),
1024 _ => span_bug!(pat.span, "struct pattern is not an ADT"),
1027 // Index the struct fields' types.
1028 let field_map = variant
1032 .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
1033 .collect::<FxHashMap<_, _>>();
1035 // Keep track of which fields have already appeared in the pattern.
1036 let mut used_fields = FxHashMap::default();
1037 let mut no_field_errors = true;
1039 let mut inexistent_fields = vec![];
1040 // Typecheck each field.
1041 for field in fields {
1042 let span = field.span;
1043 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1044 let field_ty = match used_fields.entry(ident) {
1045 Occupied(occupied) => {
1046 self.error_field_already_bound(span, field.ident, *occupied.get());
1047 no_field_errors = false;
1051 vacant.insert(span);
1055 self.write_field_index(field.hir_id, *i);
1056 self.tcx.check_stability(f.did, Some(pat.hir_id), span);
1057 self.field_ty(span, f, substs)
1059 .unwrap_or_else(|| {
1060 inexistent_fields.push(field.ident);
1061 no_field_errors = false;
1067 self.check_pat(&field.pat, field_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
1070 let mut unmentioned_fields = variant
1073 .map(|field| field.ident.normalize_to_macros_2_0())
1074 .filter(|ident| !used_fields.contains_key(&ident))
1075 .collect::<Vec<_>>();
1077 if !inexistent_fields.is_empty() && !variant.recovered {
1078 self.error_inexistent_fields(
1079 adt.variant_descr(),
1081 &mut unmentioned_fields,
1086 // Require `..` if struct has non_exhaustive attribute.
1087 if variant.is_field_list_non_exhaustive() && !adt.did.is_local() && !etc {
1088 self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
1091 // Report an error if incorrect number of the fields were specified.
1093 if fields.len() != 1 {
1095 .struct_span_err(pat.span, "union patterns should have exactly one field")
1099 tcx.sess.struct_span_err(pat.span, "`..` cannot be used in union patterns").emit();
1101 } else if !etc && !unmentioned_fields.is_empty() {
1102 self.error_unmentioned_fields(pat.span, &unmentioned_fields, variant);
1107 fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
1108 let sess = self.tcx.sess;
1109 let sm = sess.source_map();
1110 let sp_brace = sm.end_point(pat.span);
1111 let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
1112 let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
1114 let mut err = struct_span_err!(
1118 "`..` required with {} marked as non-exhaustive",
1121 err.span_suggestion_verbose(
1123 "add `..` at the end of the field list to ignore all other fields",
1125 Applicability::MachineApplicable,
1130 fn error_field_already_bound(&self, span: Span, ident: ast::Ident, other_field: Span) {
1135 "field `{}` bound multiple times in the pattern",
1138 .span_label(span, format!("multiple uses of `{}` in pattern", ident))
1139 .span_label(other_field, format!("first use of `{}`", ident))
1143 fn error_inexistent_fields(
1146 inexistent_fields: &[ast::Ident],
1147 unmentioned_fields: &mut Vec<ast::Ident>,
1148 variant: &ty::VariantDef,
1151 let (field_names, t, plural) = if inexistent_fields.len() == 1 {
1152 (format!("a field named `{}`", inexistent_fields[0]), "this", "")
1159 .map(|ident| format!("`{}`", ident))
1160 .collect::<Vec<String>>()
1167 let spans = inexistent_fields.iter().map(|ident| ident.span).collect::<Vec<_>>();
1168 let mut err = struct_span_err!(
1172 "{} `{}` does not have {}",
1174 tcx.def_path_str(variant.def_id),
1177 if let Some(ident) = inexistent_fields.last() {
1181 "{} `{}` does not have {} field{}",
1183 tcx.def_path_str(variant.def_id),
1189 let input = unmentioned_fields.iter().map(|field| &field.name);
1190 let suggested_name = find_best_match_for_name(input, &ident.as_str(), None);
1191 if let Some(suggested_name) = suggested_name {
1192 err.span_suggestion(
1194 "a field with a similar name exists",
1195 suggested_name.to_string(),
1196 Applicability::MaybeIncorrect,
1199 // we don't want to throw `E0027` in case we have thrown `E0026` for them
1200 unmentioned_fields.retain(|&x| x.name != suggested_name);
1204 if tcx.sess.teach(&err.get_code().unwrap()) {
1206 "This error indicates that a struct pattern attempted to \
1207 extract a non-existent field from a struct. Struct fields \
1208 are identified by the name used before the colon : so struct \
1209 patterns should resemble the declaration of the struct type \
1211 If you are using shorthand field patterns but want to refer \
1212 to the struct field by a different name, you should rename \
1219 fn error_unmentioned_fields(
1222 unmentioned_fields: &[ast::Ident],
1223 variant: &ty::VariantDef,
1225 let field_names = if unmentioned_fields.len() == 1 {
1226 format!("field `{}`", unmentioned_fields[0])
1228 let fields = unmentioned_fields
1230 .map(|name| format!("`{}`", name))
1231 .collect::<Vec<String>>()
1233 format!("fields {}", fields)
1235 let mut diag = struct_span_err!(
1239 "pattern does not mention {}",
1242 diag.span_label(span, format!("missing {}", field_names));
1243 if variant.ctor_kind == CtorKind::Fn {
1244 diag.note("trying to match a tuple variant with a struct variant pattern");
1246 if self.tcx.sess.teach(&diag.get_code().unwrap()) {
1248 "This error indicates that a pattern for a struct fails to specify a \
1249 sub-pattern for every one of the struct's fields. Ensure that each field \
1250 from the struct's definition is mentioned in the pattern, or use `..` to \
1251 ignore unwanted fields.",
1260 inner: &'tcx Pat<'tcx>,
1262 def_bm: BindingMode,
1266 let (box_ty, inner_ty) = if self.check_dereferenceable(span, expected, &inner) {
1267 // Here, `demand::subtype` is good enough, but I don't
1268 // think any errors can be introduced by using `demand::eqtype`.
1269 let inner_ty = self.next_ty_var(TypeVariableOrigin {
1270 kind: TypeVariableOriginKind::TypeInference,
1273 let box_ty = tcx.mk_box(inner_ty);
1274 self.demand_eqtype_pat(span, expected, box_ty, ti);
1277 (tcx.types.err, tcx.types.err)
1279 self.check_pat(&inner, inner_ty, def_bm, ti);
1285 pat: &'tcx Pat<'tcx>,
1286 inner: &'tcx Pat<'tcx>,
1287 mutbl: hir::Mutability,
1289 def_bm: BindingMode,
1293 let expected = self.shallow_resolve(expected);
1294 let (rptr_ty, inner_ty) = if self.check_dereferenceable(pat.span, expected, &inner) {
1295 // `demand::subtype` would be good enough, but using `eqtype` turns
1296 // out to be equally general. See (note_1) for details.
1298 // Take region, inner-type from expected type if we can,
1299 // to avoid creating needless variables. This also helps with
1300 // the bad interactions of the given hack detailed in (note_1).
1301 debug!("check_pat_ref: expected={:?}", expected);
1302 match expected.kind {
1303 ty::Ref(_, r_ty, r_mutbl) if r_mutbl == mutbl => (expected, r_ty),
1305 let inner_ty = self.next_ty_var(TypeVariableOrigin {
1306 kind: TypeVariableOriginKind::TypeInference,
1309 let rptr_ty = self.new_ref_ty(pat.span, mutbl, inner_ty);
1310 debug!("check_pat_ref: demanding {:?} = {:?}", expected, rptr_ty);
1311 let err = self.demand_eqtype_pat_diag(pat.span, expected, rptr_ty, ti);
1313 // Look for a case like `fn foo(&foo: u32)` and suggest
1314 // `fn foo(foo: &u32)`
1315 if let Some(mut err) = err {
1316 self.borrow_pat_suggestion(&mut err, &pat, &inner, &expected);
1323 (tcx.types.err, tcx.types.err)
1325 self.check_pat(&inner, inner_ty, def_bm, TopInfo { parent_pat: Some(&pat), ..ti });
1329 /// Create a reference type with a fresh region variable.
1330 fn new_ref_ty(&self, span: Span, mutbl: hir::Mutability, ty: Ty<'tcx>) -> Ty<'tcx> {
1331 let region = self.next_region_var(infer::PatternRegion(span));
1332 let mt = ty::TypeAndMut { ty, mutbl };
1333 self.tcx.mk_ref(region, mt)
1336 /// Type check a slice pattern.
1338 /// Syntactically, these look like `[pat_0, ..., pat_n]`.
1339 /// Semantically, we are type checking a pattern with structure:
1341 /// [before_0, ..., before_n, (slice, after_0, ... after_n)?]
1343 /// The type of `slice`, if it is present, depends on the `expected` type.
1344 /// If `slice` is missing, then so is `after_i`.
1345 /// If `slice` is present, it can still represent 0 elements.
1349 before: &'tcx [&'tcx Pat<'tcx>],
1350 slice: Option<&'tcx Pat<'tcx>>,
1351 after: &'tcx [&'tcx Pat<'tcx>],
1353 def_bm: BindingMode,
1356 let err = self.tcx.types.err;
1357 let expected = self.structurally_resolved_type(span, expected);
1358 let (element_ty, slice_ty, expected) = match expected.kind {
1359 // An array, so we might have something like `let [a, b, c] = [0, 1, 2];`.
1360 ty::Array(element_ty, len) => {
1361 let min = before.len() as u64 + after.len() as u64;
1362 let (slice_ty, expected) =
1363 self.check_array_pat_len(span, element_ty, expected, slice, len, min);
1364 (element_ty, slice_ty, expected)
1366 ty::Slice(element_ty) => (element_ty, expected, expected),
1367 // The expected type must be an array or slice, but was neither, so error.
1369 if !expected.references_error() {
1370 self.error_expected_array_or_slice(span, expected);
1376 // Type check all the patterns before `slice`.
1378 self.check_pat(&elt, element_ty, def_bm, ti);
1380 // Type check the `slice`, if present, against its expected type.
1381 if let Some(slice) = slice {
1382 self.check_pat(&slice, slice_ty, def_bm, ti);
1384 // Type check the elements after `slice`, if present.
1386 self.check_pat(&elt, element_ty, def_bm, ti);
1391 /// Type check the length of an array pattern.
1393 /// Returns both the type of the variable length pattern
1394 /// (or `tcx.err` in case there is none),
1395 /// and the potentially inferred array type.
1396 fn check_array_pat_len(
1399 element_ty: Ty<'tcx>,
1401 slice: Option<&'tcx Pat<'tcx>>,
1402 len: &ty::Const<'tcx>,
1404 ) -> (Ty<'tcx>, Ty<'tcx>) {
1405 if let Some(len) = len.try_eval_usize(self.tcx, self.param_env) {
1406 // Now we know the length...
1407 if slice.is_none() {
1408 // ...and since there is no variable-length pattern,
1409 // we require an exact match between the number of elements
1410 // in the array pattern and as provided by the matched type.
1412 self.error_scrutinee_inconsistent_length(span, min_len, len);
1414 } else if let Some(pat_len) = len.checked_sub(min_len) {
1415 // The variable-length pattern was there,
1416 // so it has an array type with the remaining elements left as its size...
1417 return (self.tcx.mk_array(element_ty, pat_len), arr_ty);
1419 // ...however, in this case, there were no remaining elements.
1420 // That is, the slice pattern requires more than the array type offers.
1421 self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len);
1423 } else if slice.is_none() {
1424 // We have a pattern with a fixed length,
1425 // which we can use to infer the length of the array.
1426 let updated_arr_ty = self.tcx.mk_array(element_ty, min_len);
1427 self.demand_eqtype(span, updated_arr_ty, arr_ty);
1428 return (self.tcx.types.err, updated_arr_ty);
1430 // We have a variable-length pattern and don't know the array length.
1431 // This happens if we have e.g.,
1432 // `let [a, b, ..] = arr` where `arr: [T; N]` where `const N: usize`.
1433 self.error_scrutinee_unfixed_length(span);
1435 (self.tcx.types.err, arr_ty)
1438 fn error_scrutinee_inconsistent_length(&self, span: Span, min_len: u64, size: u64) {
1443 "pattern requires {} element{} but array has {}",
1445 pluralize!(min_len),
1448 .span_label(span, format!("expected {} element{}", size, pluralize!(size)))
1452 fn error_scrutinee_with_rest_inconsistent_length(&self, span: Span, min_len: u64, size: u64) {
1457 "pattern requires at least {} element{} but array has {}",
1459 pluralize!(min_len),
1464 format!("pattern cannot match array of {} element{}", size, pluralize!(size),),
1469 fn error_scrutinee_unfixed_length(&self, span: Span) {
1474 "cannot pattern-match on an array without a fixed length",
1479 fn error_expected_array_or_slice(&self, span: Span, expected_ty: Ty<'tcx>) {
1480 let mut err = struct_span_err!(
1484 "expected an array or slice, found `{}`",
1487 if let ty::Ref(_, ty, _) = expected_ty.kind {
1488 if let ty::Array(..) | ty::Slice(..) = ty.kind {
1489 err.help("the semantics of slice patterns changed recently; see issue #62254");
1492 err.span_label(span, format!("pattern cannot match with input type `{}`", expected_ty));