]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/mod.rs
Auto merge of #101857 - lcnr:make-dyn-again, r=jackh726
[rust.git] / compiler / rustc_mir_build / src / thir / pattern / mod.rs
1 //! Validation of patterns/matches.
2
3 mod check_match;
4 mod const_to_pat;
5 mod deconstruct_pat;
6 mod usefulness;
7
8 pub(crate) use self::check_match::check_match;
9
10 use crate::thir::util::UserAnnotatedTyHelpers;
11
12 use rustc_errors::struct_span_err;
13 use rustc_hir as hir;
14 use rustc_hir::def::{CtorOf, DefKind, Res};
15 use rustc_hir::pat_util::EnumerateAndAdjustIterator;
16 use rustc_hir::RangeEnd;
17 use rustc_index::vec::Idx;
18 use rustc_middle::mir::interpret::{
19     ConstValue, ErrorHandled, LitToConstError, LitToConstInput, Scalar,
20 };
21 use rustc_middle::mir::{self, UserTypeProjection};
22 use rustc_middle::mir::{BorrowKind, Field, Mutability};
23 use rustc_middle::thir::{Ascription, BindingMode, FieldPat, LocalVarId, Pat, PatKind, PatRange};
24 use rustc_middle::ty::subst::{GenericArg, SubstsRef};
25 use rustc_middle::ty::CanonicalUserTypeAnnotation;
26 use rustc_middle::ty::{self, AdtDef, ConstKind, DefIdTree, Region, Ty, TyCtxt, UserType};
27 use rustc_span::{Span, Symbol};
28
29 use std::cmp::Ordering;
30
31 #[derive(Clone, Debug)]
32 enum PatternError {
33     AssocConstInPattern(Span),
34     ConstParamInPattern(Span),
35     StaticInPattern(Span),
36     NonConstPath(Span),
37 }
38
39 struct PatCtxt<'a, 'tcx> {
40     tcx: TyCtxt<'tcx>,
41     param_env: ty::ParamEnv<'tcx>,
42     typeck_results: &'a ty::TypeckResults<'tcx>,
43     errors: Vec<PatternError>,
44     include_lint_checks: bool,
45 }
46
47 pub(super) fn pat_from_hir<'a, 'tcx>(
48     tcx: TyCtxt<'tcx>,
49     param_env: ty::ParamEnv<'tcx>,
50     typeck_results: &'a ty::TypeckResults<'tcx>,
51     pat: &'tcx hir::Pat<'tcx>,
52 ) -> Box<Pat<'tcx>> {
53     let mut pcx = PatCtxt::new(tcx, param_env, typeck_results);
54     let result = pcx.lower_pattern(pat);
55     if !pcx.errors.is_empty() {
56         let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
57         tcx.sess.delay_span_bug(pat.span, &msg);
58     }
59     debug!("pat_from_hir({:?}) = {:?}", pat, result);
60     result
61 }
62
63 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
64     fn new(
65         tcx: TyCtxt<'tcx>,
66         param_env: ty::ParamEnv<'tcx>,
67         typeck_results: &'a ty::TypeckResults<'tcx>,
68     ) -> Self {
69         PatCtxt { tcx, param_env, typeck_results, errors: vec![], include_lint_checks: false }
70     }
71
72     fn include_lint_checks(&mut self) -> &mut Self {
73         self.include_lint_checks = true;
74         self
75     }
76
77     fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
78         // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
79         // pattern has the type that results *after* dereferencing. For example, in this code:
80         //
81         // ```
82         // match &&Some(0i32) {
83         //     Some(n) => { ... },
84         //     _ => { ... },
85         // }
86         // ```
87         //
88         // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
89         // determined in rustc_typeck::check::match). The adjustments would be
90         //
91         // `vec![&&Option<i32>, &Option<i32>]`.
92         //
93         // Applying the adjustments, we want to instead output `&&Some(n)` (as a THIR pattern). So
94         // we wrap the unadjusted pattern in `PatKind::Deref` repeatedly, consuming the
95         // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
96         // gets the least-dereferenced type).
97         let unadjusted_pat = self.lower_pattern_unadjusted(pat);
98         self.typeck_results.pat_adjustments().get(pat.hir_id).unwrap_or(&vec![]).iter().rev().fold(
99             unadjusted_pat,
100             |pat: Box<_>, ref_ty| {
101                 debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
102                 Box::new(Pat {
103                     span: pat.span,
104                     ty: *ref_ty,
105                     kind: PatKind::Deref { subpattern: pat },
106                 })
107             },
108         )
109     }
110
111     fn lower_range_expr(
112         &mut self,
113         expr: &'tcx hir::Expr<'tcx>,
114     ) -> (PatKind<'tcx>, Option<Ascription<'tcx>>) {
115         match self.lower_lit(expr) {
116             PatKind::AscribeUserType { ascription, subpattern: box Pat { kind, .. } } => {
117                 (kind, Some(ascription))
118             }
119             kind => (kind, None),
120         }
121     }
122
123     fn lower_pattern_range(
124         &mut self,
125         ty: Ty<'tcx>,
126         lo: mir::ConstantKind<'tcx>,
127         hi: mir::ConstantKind<'tcx>,
128         end: RangeEnd,
129         span: Span,
130     ) -> PatKind<'tcx> {
131         assert_eq!(lo.ty(), ty);
132         assert_eq!(hi.ty(), ty);
133         let cmp = compare_const_vals(self.tcx, lo, hi, self.param_env);
134         match (end, cmp) {
135             // `x..y` where `x < y`.
136             // Non-empty because the range includes at least `x`.
137             (RangeEnd::Excluded, Some(Ordering::Less)) => {
138                 PatKind::Range(Box::new(PatRange { lo, hi, end }))
139             }
140             // `x..y` where `x >= y`. The range is empty => error.
141             (RangeEnd::Excluded, _) => {
142                 struct_span_err!(
143                     self.tcx.sess,
144                     span,
145                     E0579,
146                     "lower range bound must be less than upper"
147                 )
148                 .emit();
149                 PatKind::Wild
150             }
151             // `x..=y` where `x == y`.
152             (RangeEnd::Included, Some(Ordering::Equal)) => PatKind::Constant { value: lo },
153             // `x..=y` where `x < y`.
154             (RangeEnd::Included, Some(Ordering::Less)) => {
155                 PatKind::Range(Box::new(PatRange { lo, hi, end }))
156             }
157             // `x..=y` where `x > y` hence the range is empty => error.
158             (RangeEnd::Included, _) => {
159                 let mut err = struct_span_err!(
160                     self.tcx.sess,
161                     span,
162                     E0030,
163                     "lower range bound must be less than or equal to upper"
164                 );
165                 err.span_label(span, "lower bound larger than upper bound");
166                 if self.tcx.sess.teach(&err.get_code().unwrap()) {
167                     err.note(
168                         "When matching against a range, the compiler \
169                               verifies that the range is non-empty. Range \
170                               patterns include both end-points, so this is \
171                               equivalent to requiring the start of the range \
172                               to be less than or equal to the end of the range.",
173                     );
174                 }
175                 err.emit();
176                 PatKind::Wild
177             }
178         }
179     }
180
181     fn normalize_range_pattern_ends(
182         &self,
183         ty: Ty<'tcx>,
184         lo: Option<&PatKind<'tcx>>,
185         hi: Option<&PatKind<'tcx>>,
186     ) -> Option<(mir::ConstantKind<'tcx>, mir::ConstantKind<'tcx>)> {
187         match (lo, hi) {
188             (Some(PatKind::Constant { value: lo }), Some(PatKind::Constant { value: hi })) => {
189                 Some((*lo, *hi))
190             }
191             (Some(PatKind::Constant { value: lo }), None) => {
192                 let hi = ty.numeric_max_val(self.tcx)?;
193                 Some((*lo, mir::ConstantKind::from_const(hi, self.tcx)))
194             }
195             (None, Some(PatKind::Constant { value: hi })) => {
196                 let lo = ty.numeric_min_val(self.tcx)?;
197                 Some((mir::ConstantKind::from_const(lo, self.tcx), *hi))
198             }
199             _ => None,
200         }
201     }
202
203     fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
204         let mut ty = self.typeck_results.node_type(pat.hir_id);
205         let mut span = pat.span;
206
207         let kind = match pat.kind {
208             hir::PatKind::Wild => PatKind::Wild,
209
210             hir::PatKind::Lit(value) => self.lower_lit(value),
211
212             hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
213                 let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref());
214                 let lo_span = lo_expr.map_or(pat.span, |e| e.span);
215                 let lo = lo_expr.map(|e| self.lower_range_expr(e));
216                 let hi = hi_expr.map(|e| self.lower_range_expr(e));
217
218                 let (lp, hp) = (lo.as_ref().map(|x| &x.0), hi.as_ref().map(|x| &x.0));
219                 let mut kind = match self.normalize_range_pattern_ends(ty, lp, hp) {
220                     Some((lc, hc)) => self.lower_pattern_range(ty, lc, hc, end, lo_span),
221                     None => {
222                         let msg = &format!(
223                             "found bad range pattern `{:?}` outside of error recovery",
224                             (&lo, &hi),
225                         );
226                         self.tcx.sess.delay_span_bug(pat.span, msg);
227                         PatKind::Wild
228                     }
229                 };
230
231                 // If we are handling a range with associated constants (e.g.
232                 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
233                 // constants somewhere. Have them on the range pattern.
234                 for end in &[lo, hi] {
235                     if let Some((_, Some(ascription))) = end {
236                         let subpattern = Box::new(Pat { span: pat.span, ty, kind });
237                         kind =
238                             PatKind::AscribeUserType { ascription: ascription.clone(), subpattern };
239                     }
240                 }
241
242                 kind
243             }
244
245             hir::PatKind::Path(ref qpath) => {
246                 return self.lower_path(qpath, pat.hir_id, pat.span);
247             }
248
249             hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => {
250                 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
251             }
252
253             hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => {
254                 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
255             }
256
257             hir::PatKind::Tuple(ref pats, ddpos) => {
258                 let ty::Tuple(ref tys) = ty.kind() else {
259                     span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
260                 };
261                 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
262                 PatKind::Leaf { subpatterns }
263             }
264
265             hir::PatKind::Binding(_, id, ident, ref sub) => {
266                 if let Some(ident_span) = ident.span.find_ancestor_inside(span) {
267                     span = span.with_hi(ident_span.hi());
268                 }
269
270                 let bm = *self
271                     .typeck_results
272                     .pat_binding_modes()
273                     .get(pat.hir_id)
274                     .expect("missing binding mode");
275                 let (mutability, mode) = match bm {
276                     ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue),
277                     ty::BindByReference(hir::Mutability::Mut) => (
278                         Mutability::Not,
279                         BindingMode::ByRef(BorrowKind::Mut { allow_two_phase_borrow: false }),
280                     ),
281                     ty::BindByReference(hir::Mutability::Not) => {
282                         (Mutability::Not, BindingMode::ByRef(BorrowKind::Shared))
283                     }
284                 };
285
286                 // A ref x pattern is the same node used for x, and as such it has
287                 // x's type, which is &T, where we want T (the type being matched).
288                 let var_ty = ty;
289                 if let ty::BindByReference(_) = bm {
290                     if let ty::Ref(_, rty, _) = ty.kind() {
291                         ty = *rty;
292                     } else {
293                         bug!("`ref {}` has wrong type {}", ident, ty);
294                     }
295                 };
296
297                 PatKind::Binding {
298                     mutability,
299                     mode,
300                     name: ident.name,
301                     var: LocalVarId(id),
302                     ty: var_ty,
303                     subpattern: self.lower_opt_pattern(sub),
304                     is_primary: id == pat.hir_id,
305                 }
306             }
307
308             hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => {
309                 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
310                 let ty::Adt(adt_def, _) = ty.kind() else {
311                     span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
312                 };
313                 let variant_def = adt_def.variant_of_res(res);
314                 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
315                 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
316             }
317
318             hir::PatKind::Struct(ref qpath, ref fields, _) => {
319                 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
320                 let subpatterns = fields
321                     .iter()
322                     .map(|field| FieldPat {
323                         field: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)),
324                         pattern: self.lower_pattern(&field.pat),
325                     })
326                     .collect();
327
328                 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
329             }
330
331             hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) },
332         };
333
334         Box::new(Pat { span, ty, kind })
335     }
336
337     fn lower_tuple_subpats(
338         &mut self,
339         pats: &'tcx [hir::Pat<'tcx>],
340         expected_len: usize,
341         gap_pos: hir::DotDotPos,
342     ) -> Vec<FieldPat<'tcx>> {
343         pats.iter()
344             .enumerate_and_adjust(expected_len, gap_pos)
345             .map(|(i, subpattern)| FieldPat {
346                 field: Field::new(i),
347                 pattern: self.lower_pattern(subpattern),
348             })
349             .collect()
350     }
351
352     fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Box<Pat<'tcx>>]> {
353         pats.iter().map(|p| self.lower_pattern(p)).collect()
354     }
355
356     fn lower_opt_pattern(
357         &mut self,
358         pat: &'tcx Option<&'tcx hir::Pat<'tcx>>,
359     ) -> Option<Box<Pat<'tcx>>> {
360         pat.as_ref().map(|p| self.lower_pattern(p))
361     }
362
363     fn slice_or_array_pattern(
364         &mut self,
365         span: Span,
366         ty: Ty<'tcx>,
367         prefix: &'tcx [hir::Pat<'tcx>],
368         slice: &'tcx Option<&'tcx hir::Pat<'tcx>>,
369         suffix: &'tcx [hir::Pat<'tcx>],
370     ) -> PatKind<'tcx> {
371         let prefix = self.lower_patterns(prefix);
372         let slice = self.lower_opt_pattern(slice);
373         let suffix = self.lower_patterns(suffix);
374         match ty.kind() {
375             // Matching a slice, `[T]`.
376             ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
377             // Fixed-length array, `[T; len]`.
378             ty::Array(_, len) => {
379                 let len = len.eval_usize(self.tcx, self.param_env);
380                 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
381                 PatKind::Array { prefix, slice, suffix }
382             }
383             _ => span_bug!(span, "bad slice pattern type {:?}", ty),
384         }
385     }
386
387     fn lower_variant_or_leaf(
388         &mut self,
389         res: Res,
390         hir_id: hir::HirId,
391         span: Span,
392         ty: Ty<'tcx>,
393         subpatterns: Vec<FieldPat<'tcx>>,
394     ) -> PatKind<'tcx> {
395         let res = match res {
396             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
397                 let variant_id = self.tcx.parent(variant_ctor_id);
398                 Res::Def(DefKind::Variant, variant_id)
399             }
400             res => res,
401         };
402
403         let mut kind = match res {
404             Res::Def(DefKind::Variant, variant_id) => {
405                 let enum_id = self.tcx.parent(variant_id);
406                 let adt_def = self.tcx.adt_def(enum_id);
407                 if adt_def.is_enum() {
408                     let substs = match ty.kind() {
409                         ty::Adt(_, substs) | ty::FnDef(_, substs) => substs,
410                         ty::Error(_) => {
411                             // Avoid ICE (#50585)
412                             return PatKind::Wild;
413                         }
414                         _ => bug!("inappropriate type for def: {:?}", ty),
415                     };
416                     PatKind::Variant {
417                         adt_def,
418                         substs,
419                         variant_index: adt_def.variant_index_with_id(variant_id),
420                         subpatterns,
421                     }
422                 } else {
423                     PatKind::Leaf { subpatterns }
424                 }
425             }
426
427             Res::Def(
428                 DefKind::Struct
429                 | DefKind::Ctor(CtorOf::Struct, ..)
430                 | DefKind::Union
431                 | DefKind::TyAlias
432                 | DefKind::AssocTy,
433                 _,
434             )
435             | Res::SelfTy { .. }
436             | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
437             _ => {
438                 let pattern_error = match res {
439                     Res::Def(DefKind::ConstParam, _) => PatternError::ConstParamInPattern(span),
440                     Res::Def(DefKind::Static(_), _) => PatternError::StaticInPattern(span),
441                     _ => PatternError::NonConstPath(span),
442                 };
443                 self.errors.push(pattern_error);
444                 PatKind::Wild
445             }
446         };
447
448         if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
449             debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
450             let annotation = CanonicalUserTypeAnnotation {
451                 user_ty: Box::new(user_ty),
452                 span,
453                 inferred_ty: self.typeck_results.node_type(hir_id),
454             };
455             kind = PatKind::AscribeUserType {
456                 subpattern: Box::new(Pat { span, ty, kind }),
457                 ascription: Ascription { annotation, variance: ty::Variance::Covariant },
458             };
459         }
460
461         kind
462     }
463
464     /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
465     /// it to `const_to_pat`. Any other path (like enum variants without fields)
466     /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
467     #[instrument(skip(self), level = "debug")]
468     fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
469         let ty = self.typeck_results.node_type(id);
470         let res = self.typeck_results.qpath_res(qpath, id);
471
472         let pat_from_kind = |kind| Box::new(Pat { span, ty, kind });
473
474         let (def_id, is_associated_const) = match res {
475             Res::Def(DefKind::Const, def_id) => (def_id, false),
476             Res::Def(DefKind::AssocConst, def_id) => (def_id, true),
477
478             _ => return pat_from_kind(self.lower_variant_or_leaf(res, id, span, ty, vec![])),
479         };
480
481         // Use `Reveal::All` here because patterns are always monomorphic even if their function
482         // isn't.
483         let param_env_reveal_all = self.param_env.with_reveal_all_normalized(self.tcx);
484         let substs = self.typeck_results.node_substs(id);
485         let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) {
486             Ok(Some(i)) => i,
487             Ok(None) => {
488                 // It should be assoc consts if there's no error but we cannot resolve it.
489                 debug_assert!(is_associated_const);
490
491                 self.errors.push(PatternError::AssocConstInPattern(span));
492
493                 return pat_from_kind(PatKind::Wild);
494             }
495
496             Err(_) => {
497                 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
498                 return pat_from_kind(PatKind::Wild);
499             }
500         };
501
502         // `mir_const_qualif` must be called with the `DefId` of the item where the const is
503         // defined, not where it is declared. The difference is significant for associated
504         // constants.
505         let mir_structural_match_violation = self.tcx.mir_const_qualif(instance.def_id()).custom_eq;
506         debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation);
507
508         match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
509             Ok(literal) => {
510                 let const_ = mir::ConstantKind::Val(literal, ty);
511                 let pattern = self.const_to_pat(const_, id, span, mir_structural_match_violation);
512
513                 if !is_associated_const {
514                     return pattern;
515                 }
516
517                 let user_provided_types = self.typeck_results().user_provided_types();
518                 if let Some(&user_ty) = user_provided_types.get(id) {
519                     let annotation = CanonicalUserTypeAnnotation {
520                         user_ty: Box::new(user_ty),
521                         span,
522                         inferred_ty: self.typeck_results().node_type(id),
523                     };
524                     Box::new(Pat {
525                         span,
526                         kind: PatKind::AscribeUserType {
527                             subpattern: pattern,
528                             ascription: Ascription {
529                                 annotation,
530                                 /// Note that use `Contravariant` here. See the
531                                 /// `variance` field documentation for details.
532                                 variance: ty::Variance::Contravariant,
533                             },
534                         },
535                         ty: const_.ty(),
536                     })
537                 } else {
538                     pattern
539                 }
540             }
541             Err(ErrorHandled::TooGeneric) => {
542                 // While `Reported | Linted` cases will have diagnostics emitted already
543                 // it is not true for TooGeneric case, so we need to give user more information.
544                 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
545                 pat_from_kind(PatKind::Wild)
546             }
547             Err(_) => {
548                 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
549                 pat_from_kind(PatKind::Wild)
550             }
551         }
552     }
553
554     /// Converts inline const patterns.
555     fn lower_inline_const(
556         &mut self,
557         anon_const: &'tcx hir::AnonConst,
558         id: hir::HirId,
559         span: Span,
560     ) -> PatKind<'tcx> {
561         let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
562         let value = mir::ConstantKind::from_inline_const(self.tcx, anon_const_def_id);
563
564         // Evaluate early like we do in `lower_path`.
565         let value = value.eval(self.tcx, self.param_env);
566
567         match value {
568             mir::ConstantKind::Ty(c) => match c.kind() {
569                 ConstKind::Param(_) => {
570                     self.errors.push(PatternError::ConstParamInPattern(span));
571                     return PatKind::Wild;
572                 }
573                 _ => bug!("Expected ConstKind::Param"),
574             },
575             mir::ConstantKind::Val(_, _) => self.const_to_pat(value, id, span, false).kind,
576             mir::ConstantKind::Unevaluated(..) => {
577                 // If we land here it means the const can't be evaluated because it's `TooGeneric`.
578                 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
579                 return PatKind::Wild;
580             }
581         }
582     }
583
584     /// Converts literals, paths and negation of literals to patterns.
585     /// The special case for negation exists to allow things like `-128_i8`
586     /// which would overflow if we tried to evaluate `128_i8` and then negate
587     /// afterwards.
588     fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
589         let (lit, neg) = match expr.kind {
590             hir::ExprKind::Path(ref qpath) => {
591                 return self.lower_path(qpath, expr.hir_id, expr.span).kind;
592             }
593             hir::ExprKind::ConstBlock(ref anon_const) => {
594                 return self.lower_inline_const(anon_const, expr.hir_id, expr.span);
595             }
596             hir::ExprKind::Lit(ref lit) => (lit, false),
597             hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => {
598                 let hir::ExprKind::Lit(ref lit) = expr.kind else {
599                     span_bug!(expr.span, "not a literal: {:?}", expr);
600                 };
601                 (lit, true)
602             }
603             _ => span_bug!(expr.span, "not a literal: {:?}", expr),
604         };
605
606         let lit_input =
607             LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
608         match self.tcx.at(expr.span).lit_to_mir_constant(lit_input) {
609             Ok(constant) => self.const_to_pat(constant, expr.hir_id, lit.span, false).kind,
610             Err(LitToConstError::Reported) => PatKind::Wild,
611             Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
612         }
613     }
614 }
615
616 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
617     fn tcx(&self) -> TyCtxt<'tcx> {
618         self.tcx
619     }
620
621     fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
622         self.typeck_results
623     }
624 }
625
626 trait PatternFoldable<'tcx>: Sized {
627     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
628         self.super_fold_with(folder)
629     }
630
631     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
632 }
633
634 trait PatternFolder<'tcx>: Sized {
635     fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
636         pattern.super_fold_with(self)
637     }
638
639     fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
640         kind.super_fold_with(self)
641     }
642 }
643
644 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
645     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
646         let content: T = (**self).fold_with(folder);
647         Box::new(content)
648     }
649 }
650
651 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
652     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
653         self.iter().map(|t| t.fold_with(folder)).collect()
654     }
655 }
656
657 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<[T]> {
658     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
659         self.iter().map(|t| t.fold_with(folder)).collect()
660     }
661 }
662
663 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
664     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
665         self.as_ref().map(|t| t.fold_with(folder))
666     }
667 }
668
669 macro_rules! ClonePatternFoldableImpls {
670     (<$lt_tcx:tt> $($ty:ty),+) => {
671         $(
672             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
673                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
674                     Clone::clone(self)
675                 }
676             }
677         )+
678     }
679 }
680
681 ClonePatternFoldableImpls! { <'tcx>
682     Span, Field, Mutability, Symbol, LocalVarId, usize, ty::Const<'tcx>,
683     Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>,
684     SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
685     UserTypeProjection, CanonicalUserTypeAnnotation<'tcx>
686 }
687
688 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
689     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
690         FieldPat { field: self.field.fold_with(folder), pattern: self.pattern.fold_with(folder) }
691     }
692 }
693
694 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
695     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
696         folder.fold_pattern(self)
697     }
698
699     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
700         Pat {
701             ty: self.ty.fold_with(folder),
702             span: self.span.fold_with(folder),
703             kind: self.kind.fold_with(folder),
704         }
705     }
706 }
707
708 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
709     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
710         folder.fold_pattern_kind(self)
711     }
712
713     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
714         match *self {
715             PatKind::Wild => PatKind::Wild,
716             PatKind::AscribeUserType {
717                 ref subpattern,
718                 ascription: Ascription { ref annotation, variance },
719             } => PatKind::AscribeUserType {
720                 subpattern: subpattern.fold_with(folder),
721                 ascription: Ascription { annotation: annotation.fold_with(folder), variance },
722             },
723             PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, is_primary } => {
724                 PatKind::Binding {
725                     mutability: mutability.fold_with(folder),
726                     name: name.fold_with(folder),
727                     mode: mode.fold_with(folder),
728                     var: var.fold_with(folder),
729                     ty: ty.fold_with(folder),
730                     subpattern: subpattern.fold_with(folder),
731                     is_primary,
732                 }
733             }
734             PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
735                 PatKind::Variant {
736                     adt_def: adt_def.fold_with(folder),
737                     substs: substs.fold_with(folder),
738                     variant_index,
739                     subpatterns: subpatterns.fold_with(folder),
740                 }
741             }
742             PatKind::Leaf { ref subpatterns } => {
743                 PatKind::Leaf { subpatterns: subpatterns.fold_with(folder) }
744             }
745             PatKind::Deref { ref subpattern } => {
746                 PatKind::Deref { subpattern: subpattern.fold_with(folder) }
747             }
748             PatKind::Constant { value } => PatKind::Constant { value },
749             PatKind::Range(ref range) => PatKind::Range(range.clone()),
750             PatKind::Slice { ref prefix, ref slice, ref suffix } => PatKind::Slice {
751                 prefix: prefix.fold_with(folder),
752                 slice: slice.fold_with(folder),
753                 suffix: suffix.fold_with(folder),
754             },
755             PatKind::Array { ref prefix, ref slice, ref suffix } => PatKind::Array {
756                 prefix: prefix.fold_with(folder),
757                 slice: slice.fold_with(folder),
758                 suffix: suffix.fold_with(folder),
759             },
760             PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
761         }
762     }
763 }
764
765 #[instrument(skip(tcx), level = "debug")]
766 pub(crate) fn compare_const_vals<'tcx>(
767     tcx: TyCtxt<'tcx>,
768     a: mir::ConstantKind<'tcx>,
769     b: mir::ConstantKind<'tcx>,
770     param_env: ty::ParamEnv<'tcx>,
771 ) -> Option<Ordering> {
772     assert_eq!(a.ty(), b.ty());
773
774     let ty = a.ty();
775
776     // This code is hot when compiling matches with many ranges. So we
777     // special-case extraction of evaluated scalars for speed, for types where
778     // raw data comparisons are appropriate. E.g. `unicode-normalization` has
779     // many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
780     // in this way.
781     match ty.kind() {
782         ty::Float(_) | ty::Int(_) => {} // require special handling, see below
783         _ => match (a, b) {
784             (
785                 mir::ConstantKind::Val(ConstValue::Scalar(Scalar::Int(a)), _a_ty),
786                 mir::ConstantKind::Val(ConstValue::Scalar(Scalar::Int(b)), _b_ty),
787             ) => return Some(a.cmp(&b)),
788             _ => {}
789         },
790     }
791
792     let a = a.eval_bits(tcx, param_env, ty);
793     let b = b.eval_bits(tcx, param_env, ty);
794
795     use rustc_apfloat::Float;
796     match *ty.kind() {
797         ty::Float(ty::FloatTy::F32) => {
798             let a = rustc_apfloat::ieee::Single::from_bits(a);
799             let b = rustc_apfloat::ieee::Single::from_bits(b);
800             a.partial_cmp(&b)
801         }
802         ty::Float(ty::FloatTy::F64) => {
803             let a = rustc_apfloat::ieee::Double::from_bits(a);
804             let b = rustc_apfloat::ieee::Double::from_bits(b);
805             a.partial_cmp(&b)
806         }
807         ty::Int(ity) => {
808             use rustc_middle::ty::layout::IntegerExt;
809             let size = rustc_target::abi::Integer::from_int_ty(&tcx, ity).size();
810             let a = size.sign_extend(a);
811             let b = size.sign_extend(b);
812             Some((a as i128).cmp(&(b as i128)))
813         }
814         _ => Some(a.cmp(&b)),
815     }
816 }