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