rustc_mir_build/thir/pattern/
mod.rs

1//! Validation of patterns/matches.
2
3mod check_match;
4mod const_to_pat;
5mod migration;
6
7use std::cmp::Ordering;
8use std::sync::Arc;
9
10use rustc_abi::{FieldIdx, Integer};
11use rustc_errors::codes::*;
12use rustc_hir::def::{CtorOf, DefKind, Res};
13use rustc_hir::pat_util::EnumerateAndAdjustIterator;
14use rustc_hir::{self as hir, LangItem, RangeEnd};
15use rustc_index::Idx;
16use rustc_infer::infer::TyCtxtInferExt;
17use rustc_middle::mir::interpret::LitToConstInput;
18use rustc_middle::thir::{
19    Ascription, FieldPat, LocalVarId, Pat, PatKind, PatRange, PatRangeBoundary,
20};
21use rustc_middle::ty::adjustment::{PatAdjust, PatAdjustment};
22use rustc_middle::ty::layout::IntegerExt;
23use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, TypingMode};
24use rustc_middle::{bug, span_bug};
25use rustc_span::def_id::DefId;
26use rustc_span::{ErrorGuaranteed, Span};
27use tracing::{debug, instrument};
28
29pub(crate) use self::check_match::check_match;
30use self::migration::PatMigration;
31use crate::errors::*;
32
33struct PatCtxt<'a, 'tcx> {
34    tcx: TyCtxt<'tcx>,
35    typing_env: ty::TypingEnv<'tcx>,
36    typeck_results: &'a ty::TypeckResults<'tcx>,
37
38    /// Used by the Rust 2024 migration lint.
39    rust_2024_migration: Option<PatMigration<'a>>,
40}
41
42pub(super) fn pat_from_hir<'a, 'tcx>(
43    tcx: TyCtxt<'tcx>,
44    typing_env: ty::TypingEnv<'tcx>,
45    typeck_results: &'a ty::TypeckResults<'tcx>,
46    pat: &'tcx hir::Pat<'tcx>,
47) -> Box<Pat<'tcx>> {
48    let mut pcx = PatCtxt {
49        tcx,
50        typing_env,
51        typeck_results,
52        rust_2024_migration: typeck_results
53            .rust_2024_migration_desugared_pats()
54            .get(pat.hir_id)
55            .map(PatMigration::new),
56    };
57    let result = pcx.lower_pattern(pat);
58    debug!("pat_from_hir({:?}) = {:?}", pat, result);
59    if let Some(m) = pcx.rust_2024_migration {
60        m.emit(tcx, pat.hir_id);
61    }
62    result
63}
64
65impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
66    fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
67        let adjustments: &[PatAdjustment<'tcx>] =
68            self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v);
69
70        // Track the default binding mode for the Rust 2024 migration suggestion.
71        // Implicitly dereferencing references changes the default binding mode, but implicit deref
72        // patterns do not. Only track binding mode changes if a ref type is in the adjustments.
73        let mut opt_old_mode_span = None;
74        if let Some(s) = &mut self.rust_2024_migration
75            && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref)
76        {
77            opt_old_mode_span = s.visit_implicit_derefs(pat.span, adjustments);
78        }
79
80        // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
81        // pattern has the type that results *after* dereferencing. For example, in this code:
82        //
83        // ```
84        // match &&Some(0i32) {
85        //     Some(n) => { ... },
86        //     _ => { ... },
87        // }
88        // ```
89        //
90        // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
91        // determined in rustc_hir_analysis::check::match). The adjustments would be
92        //
93        // `vec![&&Option<i32>, &Option<i32>]`.
94        //
95        // Applying the adjustments, we want to instead output `&&Some(n)` (as a THIR pattern). So
96        // we wrap the unadjusted pattern in `PatKind::Deref` repeatedly, consuming the
97        // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
98        // gets the least-dereferenced type).
99        let unadjusted_pat = match pat.kind {
100            hir::PatKind::Ref(inner, _)
101                if self.typeck_results.skipped_ref_pats().contains(pat.hir_id) =>
102            {
103                self.lower_pattern(inner)
104            }
105            _ => self.lower_pattern_unadjusted(pat),
106        };
107
108        let adjusted_pat = adjustments.iter().rev().fold(unadjusted_pat, |thir_pat, adjust| {
109            debug!("{:?}: wrapping pattern with adjustment {:?}", thir_pat, adjust);
110            let span = thir_pat.span;
111            let kind = match adjust.kind {
112                PatAdjust::BuiltinDeref => PatKind::Deref { subpattern: thir_pat },
113                PatAdjust::OverloadedDeref => {
114                    let borrow = self.typeck_results.deref_pat_borrow_mode(adjust.source, pat);
115                    PatKind::DerefPattern { subpattern: thir_pat, borrow }
116                }
117            };
118            Box::new(Pat { span, ty: adjust.source, kind })
119        });
120
121        if let Some(s) = &mut self.rust_2024_migration
122            && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref)
123        {
124            s.leave_ref(opt_old_mode_span);
125        }
126
127        adjusted_pat
128    }
129
130    fn lower_pattern_range_endpoint(
131        &mut self,
132        expr: Option<&'tcx hir::PatExpr<'tcx>>,
133        // Out-parameters collecting extra data to be reapplied by the caller
134        ascriptions: &mut Vec<Ascription<'tcx>>,
135        expanded_consts: &mut Vec<DefId>,
136    ) -> Result<Option<PatRangeBoundary<'tcx>>, ErrorGuaranteed> {
137        let Some(expr) = expr else { return Ok(None) };
138
139        // Lower the endpoint into a temporary `PatKind` that will then be
140        // deconstructed to obtain the constant value and other data.
141        let mut kind: PatKind<'tcx> = self.lower_pat_expr(expr, None);
142
143        // Unpeel any ascription or inline-const wrapper nodes.
144        loop {
145            match kind {
146                PatKind::AscribeUserType { ascription, subpattern } => {
147                    ascriptions.push(ascription);
148                    kind = subpattern.kind;
149                }
150                PatKind::ExpandedConstant { def_id, subpattern } => {
151                    expanded_consts.push(def_id);
152                    kind = subpattern.kind;
153                }
154                _ => break,
155            }
156        }
157
158        // The unpeeled kind should now be a constant, giving us the endpoint value.
159        let PatKind::Constant { value } = kind else {
160            let msg =
161                format!("found bad range pattern endpoint `{expr:?}` outside of error recovery");
162            return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
163        };
164
165        Ok(Some(PatRangeBoundary::Finite(value)))
166    }
167
168    /// Overflowing literals are linted against in a late pass. This is mostly fine, except when we
169    /// encounter a range pattern like `-130i8..2`: if we believe `eval_bits`, this looks like a
170    /// range where the endpoints are in the wrong order. To avoid a confusing error message, we
171    /// check for overflow then.
172    /// This is only called when the range is already known to be malformed.
173    fn error_on_literal_overflow(
174        &self,
175        expr: Option<&'tcx hir::PatExpr<'tcx>>,
176        ty: Ty<'tcx>,
177    ) -> Result<(), ErrorGuaranteed> {
178        use rustc_ast::ast::LitKind;
179
180        let Some(expr) = expr else {
181            return Ok(());
182        };
183        let span = expr.span;
184
185        // We need to inspect the original expression, because if we only inspect the output of
186        // `eval_bits`, an overflowed value has already been wrapped around.
187        // We mostly copy the logic from the `rustc_lint::OVERFLOWING_LITERALS` lint.
188        let hir::PatExprKind::Lit { lit, negated } = expr.kind else {
189            return Ok(());
190        };
191        let LitKind::Int(lit_val, _) = lit.node else {
192            return Ok(());
193        };
194        let (min, max): (i128, u128) = match ty.kind() {
195            ty::Int(ity) => {
196                let size = Integer::from_int_ty(&self.tcx, *ity).size();
197                (size.signed_int_min(), size.signed_int_max() as u128)
198            }
199            ty::Uint(uty) => {
200                let size = Integer::from_uint_ty(&self.tcx, *uty).size();
201                (0, size.unsigned_int_max())
202            }
203            _ => {
204                return Ok(());
205            }
206        };
207        // Detect literal value out of range `[min, max]` inclusive, avoiding use of `-min` to
208        // prevent overflow/panic.
209        if (negated && lit_val > max + 1) || (!negated && lit_val > max) {
210            return Err(self.tcx.dcx().emit_err(LiteralOutOfRange { span, ty, min, max }));
211        }
212        Ok(())
213    }
214
215    fn lower_pattern_range(
216        &mut self,
217        lo_expr: Option<&'tcx hir::PatExpr<'tcx>>,
218        hi_expr: Option<&'tcx hir::PatExpr<'tcx>>,
219        end: RangeEnd,
220        ty: Ty<'tcx>,
221        span: Span,
222    ) -> Result<PatKind<'tcx>, ErrorGuaranteed> {
223        if lo_expr.is_none() && hi_expr.is_none() {
224            let msg = "found twice-open range pattern (`..`) outside of error recovery";
225            self.tcx.dcx().span_bug(span, msg);
226        }
227
228        // Collect extra data while lowering the endpoints, to be reapplied later.
229        let mut ascriptions = vec![];
230        let mut expanded_consts = vec![];
231
232        let mut lower_endpoint =
233            |expr| self.lower_pattern_range_endpoint(expr, &mut ascriptions, &mut expanded_consts);
234
235        let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity);
236        let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity);
237
238        let cmp = lo.compare_with(hi, ty, self.tcx, self.typing_env);
239        let mut kind = PatKind::Range(Arc::new(PatRange { lo, hi, end, ty }));
240        match (end, cmp) {
241            // `x..y` where `x < y`.
242            (RangeEnd::Excluded, Some(Ordering::Less)) => {}
243            // `x..=y` where `x < y`.
244            (RangeEnd::Included, Some(Ordering::Less)) => {}
245            // `x..=y` where `x == y` and `x` and `y` are finite.
246            (RangeEnd::Included, Some(Ordering::Equal)) if lo.is_finite() && hi.is_finite() => {
247                kind = PatKind::Constant { value: lo.as_finite().unwrap() };
248            }
249            // `..=x` where `x == ty::MIN`.
250            (RangeEnd::Included, Some(Ordering::Equal)) if !lo.is_finite() => {}
251            // `x..` where `x == ty::MAX` (yes, `x..` gives `RangeEnd::Included` since it is meant
252            // to include `ty::MAX`).
253            (RangeEnd::Included, Some(Ordering::Equal)) if !hi.is_finite() => {}
254            // `x..y` where `x >= y`, or `x..=y` where `x > y`. The range is empty => error.
255            _ => {
256                // Emit a more appropriate message if there was overflow.
257                self.error_on_literal_overflow(lo_expr, ty)?;
258                self.error_on_literal_overflow(hi_expr, ty)?;
259                let e = match end {
260                    RangeEnd::Included => {
261                        self.tcx.dcx().emit_err(LowerRangeBoundMustBeLessThanOrEqualToUpper {
262                            span,
263                            teach: self.tcx.sess.teach(E0030),
264                        })
265                    }
266                    RangeEnd::Excluded => {
267                        self.tcx.dcx().emit_err(LowerRangeBoundMustBeLessThanUpper { span })
268                    }
269                };
270                return Err(e);
271            }
272        }
273
274        // If we are handling a range with associated constants (e.g.
275        // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
276        // constants somewhere. Have them on the range pattern.
277        for ascription in ascriptions {
278            let subpattern = Box::new(Pat { span, ty, kind });
279            kind = PatKind::AscribeUserType { ascription, subpattern };
280        }
281        for def_id in expanded_consts {
282            let subpattern = Box::new(Pat { span, ty, kind });
283            kind = PatKind::ExpandedConstant { def_id, subpattern };
284        }
285        Ok(kind)
286    }
287
288    #[instrument(skip(self), level = "debug")]
289    fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
290        let mut ty = self.typeck_results.node_type(pat.hir_id);
291        let mut span = pat.span;
292
293        let kind = match pat.kind {
294            hir::PatKind::Missing => PatKind::Missing,
295
296            hir::PatKind::Wild => PatKind::Wild,
297
298            hir::PatKind::Never => PatKind::Never,
299
300            hir::PatKind::Expr(value) => self.lower_pat_expr(value, Some(ty)),
301
302            hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
303                let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref());
304                self.lower_pattern_range(lo_expr, hi_expr, end, ty, span)
305                    .unwrap_or_else(PatKind::Error)
306            }
307
308            hir::PatKind::Deref(subpattern) => {
309                let borrow = self.typeck_results.deref_pat_borrow_mode(ty, subpattern);
310                PatKind::DerefPattern { subpattern: self.lower_pattern(subpattern), borrow }
311            }
312            hir::PatKind::Ref(subpattern, _) => {
313                // Track the default binding mode for the Rust 2024 migration suggestion.
314                let opt_old_mode_span =
315                    self.rust_2024_migration.as_mut().and_then(|s| s.visit_explicit_deref());
316                let subpattern = self.lower_pattern(subpattern);
317                if let Some(s) = &mut self.rust_2024_migration {
318                    s.leave_ref(opt_old_mode_span);
319                }
320                PatKind::Deref { subpattern }
321            }
322            hir::PatKind::Box(subpattern) => PatKind::DerefPattern {
323                subpattern: self.lower_pattern(subpattern),
324                borrow: hir::ByRef::No,
325            },
326
327            hir::PatKind::Slice(prefix, slice, suffix) => {
328                self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
329            }
330
331            hir::PatKind::Tuple(pats, ddpos) => {
332                let ty::Tuple(tys) = ty.kind() else {
333                    span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
334                };
335                let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
336                PatKind::Leaf { subpatterns }
337            }
338
339            hir::PatKind::Binding(explicit_ba, id, ident, sub) => {
340                if let Some(ident_span) = ident.span.find_ancestor_inside(span) {
341                    span = span.with_hi(ident_span.hi());
342                }
343
344                let mode = *self
345                    .typeck_results
346                    .pat_binding_modes()
347                    .get(pat.hir_id)
348                    .expect("missing binding mode");
349
350                if let Some(s) = &mut self.rust_2024_migration {
351                    s.visit_binding(pat.span, mode, explicit_ba, ident);
352                }
353
354                // A ref x pattern is the same node used for x, and as such it has
355                // x's type, which is &T, where we want T (the type being matched).
356                let var_ty = ty;
357                if let hir::ByRef::Yes(_) = mode.0 {
358                    if let ty::Ref(_, rty, _) = ty.kind() {
359                        ty = *rty;
360                    } else {
361                        bug!("`ref {}` has wrong type {}", ident, ty);
362                    }
363                };
364
365                PatKind::Binding {
366                    mode,
367                    name: ident.name,
368                    var: LocalVarId(id),
369                    ty: var_ty,
370                    subpattern: self.lower_opt_pattern(sub),
371                    is_primary: id == pat.hir_id,
372                }
373            }
374
375            hir::PatKind::TupleStruct(ref qpath, pats, ddpos) => {
376                let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
377                let ty::Adt(adt_def, _) = ty.kind() else {
378                    span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
379                };
380                let variant_def = adt_def.variant_of_res(res);
381                let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
382                self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
383            }
384
385            hir::PatKind::Struct(ref qpath, fields, _) => {
386                let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
387                let subpatterns = fields
388                    .iter()
389                    .map(|field| FieldPat {
390                        field: self.typeck_results.field_index(field.hir_id),
391                        pattern: *self.lower_pattern(field.pat),
392                    })
393                    .collect();
394
395                self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
396            }
397
398            hir::PatKind::Or(pats) => PatKind::Or { pats: self.lower_patterns(pats) },
399
400            // FIXME(guard_patterns): implement guard pattern lowering
401            hir::PatKind::Guard(pat, _) => self.lower_pattern(pat).kind,
402
403            hir::PatKind::Err(guar) => PatKind::Error(guar),
404        };
405
406        Box::new(Pat { span, ty, kind })
407    }
408
409    fn lower_tuple_subpats(
410        &mut self,
411        pats: &'tcx [hir::Pat<'tcx>],
412        expected_len: usize,
413        gap_pos: hir::DotDotPos,
414    ) -> Vec<FieldPat<'tcx>> {
415        pats.iter()
416            .enumerate_and_adjust(expected_len, gap_pos)
417            .map(|(i, subpattern)| FieldPat {
418                field: FieldIdx::new(i),
419                pattern: *self.lower_pattern(subpattern),
420            })
421            .collect()
422    }
423
424    fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Pat<'tcx>]> {
425        pats.iter().map(|p| *self.lower_pattern(p)).collect()
426    }
427
428    fn lower_opt_pattern(&mut self, pat: Option<&'tcx hir::Pat<'tcx>>) -> Option<Box<Pat<'tcx>>> {
429        pat.map(|p| self.lower_pattern(p))
430    }
431
432    fn slice_or_array_pattern(
433        &mut self,
434        span: Span,
435        ty: Ty<'tcx>,
436        prefix: &'tcx [hir::Pat<'tcx>],
437        slice: Option<&'tcx hir::Pat<'tcx>>,
438        suffix: &'tcx [hir::Pat<'tcx>],
439    ) -> PatKind<'tcx> {
440        let prefix = self.lower_patterns(prefix);
441        let slice = self.lower_opt_pattern(slice);
442        let suffix = self.lower_patterns(suffix);
443        match ty.kind() {
444            // Matching a slice, `[T]`.
445            ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
446            // Fixed-length array, `[T; len]`.
447            ty::Array(_, len) => {
448                let len = len
449                    .try_to_target_usize(self.tcx)
450                    .expect("expected len of array pat to be definite");
451                assert!(len >= prefix.len() as u64 + suffix.len() as u64);
452                PatKind::Array { prefix, slice, suffix }
453            }
454            _ => span_bug!(span, "bad slice pattern type {:?}", ty),
455        }
456    }
457
458    fn lower_variant_or_leaf(
459        &mut self,
460        res: Res,
461        hir_id: hir::HirId,
462        span: Span,
463        ty: Ty<'tcx>,
464        subpatterns: Vec<FieldPat<'tcx>>,
465    ) -> PatKind<'tcx> {
466        let res = match res {
467            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
468                let variant_id = self.tcx.parent(variant_ctor_id);
469                Res::Def(DefKind::Variant, variant_id)
470            }
471            res => res,
472        };
473
474        let mut kind = match res {
475            Res::Def(DefKind::Variant, variant_id) => {
476                let enum_id = self.tcx.parent(variant_id);
477                let adt_def = self.tcx.adt_def(enum_id);
478                if adt_def.is_enum() {
479                    let args = match ty.kind() {
480                        ty::Adt(_, args) | ty::FnDef(_, args) => args,
481                        ty::Error(e) => {
482                            // Avoid ICE (#50585)
483                            return PatKind::Error(*e);
484                        }
485                        _ => bug!("inappropriate type for def: {:?}", ty),
486                    };
487                    PatKind::Variant {
488                        adt_def,
489                        args,
490                        variant_index: adt_def.variant_index_with_id(variant_id),
491                        subpatterns,
492                    }
493                } else {
494                    PatKind::Leaf { subpatterns }
495                }
496            }
497
498            Res::Def(
499                DefKind::Struct
500                | DefKind::Ctor(CtorOf::Struct, ..)
501                | DefKind::Union
502                | DefKind::TyAlias
503                | DefKind::AssocTy,
504                _,
505            )
506            | Res::SelfTyParam { .. }
507            | Res::SelfTyAlias { .. }
508            | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
509            _ => {
510                let e = match res {
511                    Res::Def(DefKind::ConstParam, def_id) => {
512                        let const_span = self.tcx.def_span(def_id);
513                        self.tcx.dcx().emit_err(ConstParamInPattern { span, const_span })
514                    }
515                    Res::Def(DefKind::Static { .. }, def_id) => {
516                        let static_span = self.tcx.def_span(def_id);
517                        self.tcx.dcx().emit_err(StaticInPattern { span, static_span })
518                    }
519                    _ => self.tcx.dcx().emit_err(NonConstPath { span }),
520                };
521                PatKind::Error(e)
522            }
523        };
524
525        if let Some(user_ty) = self.user_args_applied_to_ty_of_hir_id(hir_id) {
526            debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
527            let annotation = CanonicalUserTypeAnnotation {
528                user_ty: Box::new(user_ty),
529                span,
530                inferred_ty: self.typeck_results.node_type(hir_id),
531            };
532            kind = PatKind::AscribeUserType {
533                subpattern: Box::new(Pat { span, ty, kind }),
534                ascription: Ascription { annotation, variance: ty::Covariant },
535            };
536        }
537
538        kind
539    }
540
541    fn user_args_applied_to_ty_of_hir_id(
542        &self,
543        hir_id: hir::HirId,
544    ) -> Option<ty::CanonicalUserType<'tcx>> {
545        crate::thir::util::user_args_applied_to_ty_of_hir_id(self.tcx, self.typeck_results, hir_id)
546    }
547
548    /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
549    /// it to `const_to_pat`. Any other path (like enum variants without fields)
550    /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
551    #[instrument(skip(self), level = "debug")]
552    fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
553        let ty = self.typeck_results.node_type(id);
554        let res = self.typeck_results.qpath_res(qpath, id);
555
556        let (def_id, user_ty) = match res {
557            Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
558                (def_id, self.typeck_results.user_provided_types().get(id))
559            }
560
561            _ => {
562                // The path isn't the name of a constant, so it must actually
563                // be a unit struct or unit variant (e.g. `Option::None`).
564                let kind = self.lower_variant_or_leaf(res, id, span, ty, vec![]);
565                return Box::new(Pat { span, ty, kind });
566            }
567        };
568
569        // Lower the named constant to a THIR pattern.
570        let args = self.typeck_results.node_args(id);
571        // FIXME(mgca): we will need to special case IACs here to have type system compatible
572        // generic args, instead of how we represent them in body expressions.
573        let c = ty::Const::new_unevaluated(self.tcx, ty::UnevaluatedConst { def: def_id, args });
574        let mut pattern = self.const_to_pat(c, ty, id, span);
575
576        // If this is an associated constant with an explicit user-written
577        // type, add an ascription node (e.g. `<Foo<'a> as MyTrait>::CONST`).
578        if let Some(&user_ty) = user_ty {
579            let annotation = CanonicalUserTypeAnnotation {
580                user_ty: Box::new(user_ty),
581                span,
582                inferred_ty: self.typeck_results.node_type(id),
583            };
584            let kind = PatKind::AscribeUserType {
585                subpattern: pattern,
586                ascription: Ascription {
587                    annotation,
588                    // Note that we use `Contravariant` here. See the
589                    // `variance` field documentation for details.
590                    variance: ty::Contravariant,
591                },
592            };
593            pattern = Box::new(Pat { span, kind, ty });
594        }
595
596        pattern
597    }
598
599    /// Lowers an inline const block (e.g. `const { 1 + 1 }`) to a pattern.
600    fn lower_inline_const(
601        &mut self,
602        block: &'tcx hir::ConstBlock,
603        id: hir::HirId,
604        span: Span,
605    ) -> PatKind<'tcx> {
606        let tcx = self.tcx;
607        let def_id = block.def_id;
608        let ty = tcx.typeck(def_id).node_type(block.hir_id);
609
610        let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
611        let parent_args = ty::GenericArgs::identity_for_item(tcx, typeck_root_def_id);
612        let args = ty::InlineConstArgs::new(tcx, ty::InlineConstArgsParts { parent_args, ty }).args;
613
614        let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), args };
615        let c = ty::Const::new_unevaluated(self.tcx, ct);
616        let pattern = self.const_to_pat(c, ty, id, span);
617
618        // Apply a type ascription for the inline constant.
619        let annotation = {
620            let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
621            let args = ty::InlineConstArgs::new(
622                tcx,
623                ty::InlineConstArgsParts { parent_args, ty: infcx.next_ty_var(span) },
624            )
625            .args;
626            infcx.canonicalize_user_type_annotation(ty::UserType::new(ty::UserTypeKind::TypeOf(
627                def_id.to_def_id(),
628                ty::UserArgs { args, user_self_ty: None },
629            )))
630        };
631        let annotation =
632            CanonicalUserTypeAnnotation { user_ty: Box::new(annotation), span, inferred_ty: ty };
633        PatKind::AscribeUserType {
634            subpattern: pattern,
635            ascription: Ascription {
636                annotation,
637                // Note that we use `Contravariant` here. See the `variance` field documentation
638                // for details.
639                variance: ty::Contravariant,
640            },
641        }
642    }
643
644    /// Lowers the kinds of "expression" that can appear in a HIR pattern:
645    /// - Paths (e.g. `FOO`, `foo::BAR`, `Option::None`)
646    /// - Inline const blocks (e.g. `const { 1 + 1 }`)
647    /// - Literals, possibly negated (e.g. `-128u8`, `"hello"`)
648    fn lower_pat_expr(
649        &mut self,
650        expr: &'tcx hir::PatExpr<'tcx>,
651        pat_ty: Option<Ty<'tcx>>,
652    ) -> PatKind<'tcx> {
653        match &expr.kind {
654            hir::PatExprKind::Path(qpath) => self.lower_path(qpath, expr.hir_id, expr.span).kind,
655            hir::PatExprKind::ConstBlock(anon_const) => {
656                self.lower_inline_const(anon_const, expr.hir_id, expr.span)
657            }
658            hir::PatExprKind::Lit { lit, negated } => {
659                // We handle byte string literal patterns by using the pattern's type instead of the
660                // literal's type in `const_to_pat`: if the literal `b"..."` matches on a slice reference,
661                // the pattern's type will be `&[u8]` whereas the literal's type is `&[u8; 3]`; using the
662                // pattern's type means we'll properly translate it to a slice reference pattern. This works
663                // because slices and arrays have the same valtree representation.
664                // HACK: As an exception, use the literal's type if `pat_ty` is `String`; this can happen if
665                // `string_deref_patterns` is enabled. There's a special case for that when lowering to MIR.
666                // FIXME(deref_patterns): This hack won't be necessary once `string_deref_patterns` is
667                // superseded by a more general implementation of deref patterns.
668                let ct_ty = match pat_ty {
669                    Some(pat_ty)
670                        if let ty::Adt(def, _) = *pat_ty.kind()
671                            && self.tcx.is_lang_item(def.did(), LangItem::String) =>
672                    {
673                        if !self.tcx.features().string_deref_patterns() {
674                            span_bug!(
675                                expr.span,
676                                "matching on `String` went through without enabling string_deref_patterns"
677                            );
678                        }
679                        self.typeck_results.node_type(expr.hir_id)
680                    }
681                    Some(pat_ty) => pat_ty,
682                    None => self.typeck_results.node_type(expr.hir_id),
683                };
684                let lit_input = LitToConstInput { lit: lit.node, ty: ct_ty, neg: *negated };
685                let constant = self.tcx.at(expr.span).lit_to_const(lit_input);
686                self.const_to_pat(constant, ct_ty, expr.hir_id, lit.span).kind
687            }
688        }
689    }
690}