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