]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/mod.rs
b02b6b6f5ca62c490ceaa566597819f1d13a991f
[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 pub(crate) enum PatternError {
33     AssocConstInPattern(Span),
34     ConstParamInPattern(Span),
35     StaticInPattern(Span),
36     NonConstPath(Span),
37 }
38
39 pub(crate) struct PatCtxt<'a, 'tcx> {
40     pub(crate) tcx: TyCtxt<'tcx>,
41     pub(crate) param_env: ty::ParamEnv<'tcx>,
42     pub(crate) typeck_results: &'a ty::TypeckResults<'tcx>,
43     pub(crate) errors: Vec<PatternError>,
44     include_lint_checks: bool,
45 }
46
47 pub(crate) 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     pub(crate) 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     pub(crate) fn include_lint_checks(&mut self) -> &mut Self {
73         self.include_lint_checks = true;
74         self
75     }
76
77     pub(crate) 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
206         let kind = match pat.kind {
207             hir::PatKind::Wild => PatKind::Wild,
208
209             hir::PatKind::Lit(value) => self.lower_lit(value),
210
211             hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
212                 let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref());
213                 let lo_span = lo_expr.map_or(pat.span, |e| e.span);
214                 let lo = lo_expr.map(|e| self.lower_range_expr(e));
215                 let hi = hi_expr.map(|e| self.lower_range_expr(e));
216
217                 let (lp, hp) = (lo.as_ref().map(|x| &x.0), hi.as_ref().map(|x| &x.0));
218                 let mut kind = match self.normalize_range_pattern_ends(ty, lp, hp) {
219                     Some((lc, hc)) => self.lower_pattern_range(ty, lc, hc, end, lo_span),
220                     None => {
221                         let msg = &format!(
222                             "found bad range pattern `{:?}` outside of error recovery",
223                             (&lo, &hi),
224                         );
225                         self.tcx.sess.delay_span_bug(pat.span, msg);
226                         PatKind::Wild
227                     }
228                 };
229
230                 // If we are handling a range with associated constants (e.g.
231                 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
232                 // constants somewhere. Have them on the range pattern.
233                 for end in &[lo, hi] {
234                     if let Some((_, Some(ascription))) = end {
235                         let subpattern = Box::new(Pat { span: pat.span, ty, kind });
236                         kind =
237                             PatKind::AscribeUserType { ascription: ascription.clone(), subpattern };
238                     }
239                 }
240
241                 kind
242             }
243
244             hir::PatKind::Path(ref qpath) => {
245                 return self.lower_path(qpath, pat.hir_id, pat.span);
246             }
247
248             hir::PatKind::Ref(ref subpattern, _) | hir::PatKind::Box(ref subpattern) => {
249                 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
250             }
251
252             hir::PatKind::Slice(ref prefix, ref slice, ref suffix) => {
253                 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
254             }
255
256             hir::PatKind::Tuple(ref pats, ddpos) => {
257                 let ty::Tuple(ref tys) = ty.kind() else {
258                     span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
259                 };
260                 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
261                 PatKind::Leaf { subpatterns }
262             }
263
264             hir::PatKind::Binding(_, id, ident, ref sub) => {
265                 let bm = *self
266                     .typeck_results
267                     .pat_binding_modes()
268                     .get(pat.hir_id)
269                     .expect("missing binding mode");
270                 let (mutability, mode) = match bm {
271                     ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue),
272                     ty::BindByReference(hir::Mutability::Mut) => (
273                         Mutability::Not,
274                         BindingMode::ByRef(BorrowKind::Mut { allow_two_phase_borrow: false }),
275                     ),
276                     ty::BindByReference(hir::Mutability::Not) => {
277                         (Mutability::Not, BindingMode::ByRef(BorrowKind::Shared))
278                     }
279                 };
280
281                 // A ref x pattern is the same node used for x, and as such it has
282                 // x's type, which is &T, where we want T (the type being matched).
283                 let var_ty = ty;
284                 if let ty::BindByReference(_) = bm {
285                     if let ty::Ref(_, rty, _) = ty.kind() {
286                         ty = *rty;
287                     } else {
288                         bug!("`ref {}` has wrong type {}", ident, ty);
289                     }
290                 };
291
292                 PatKind::Binding {
293                     mutability,
294                     mode,
295                     name: ident.name,
296                     var: LocalVarId(id),
297                     ty: var_ty,
298                     subpattern: self.lower_opt_pattern(sub),
299                     is_primary: id == pat.hir_id,
300                 }
301             }
302
303             hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => {
304                 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
305                 let ty::Adt(adt_def, _) = ty.kind() else {
306                     span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
307                 };
308                 let variant_def = adt_def.variant_of_res(res);
309                 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
310                 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
311             }
312
313             hir::PatKind::Struct(ref qpath, ref fields, _) => {
314                 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
315                 let subpatterns = fields
316                     .iter()
317                     .map(|field| FieldPat {
318                         field: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)),
319                         pattern: self.lower_pattern(&field.pat),
320                     })
321                     .collect();
322
323                 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
324             }
325
326             hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) },
327         };
328
329         Box::new(Pat { span: pat.span, ty, kind })
330     }
331
332     fn lower_tuple_subpats(
333         &mut self,
334         pats: &'tcx [hir::Pat<'tcx>],
335         expected_len: usize,
336         gap_pos: Option<usize>,
337     ) -> Vec<FieldPat<'tcx>> {
338         pats.iter()
339             .enumerate_and_adjust(expected_len, gap_pos)
340             .map(|(i, subpattern)| FieldPat {
341                 field: Field::new(i),
342                 pattern: self.lower_pattern(subpattern),
343             })
344             .collect()
345     }
346
347     fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Vec<Box<Pat<'tcx>>> {
348         pats.iter().map(|p| self.lower_pattern(p)).collect()
349     }
350
351     fn lower_opt_pattern(
352         &mut self,
353         pat: &'tcx Option<&'tcx hir::Pat<'tcx>>,
354     ) -> Option<Box<Pat<'tcx>>> {
355         pat.as_ref().map(|p| self.lower_pattern(p))
356     }
357
358     fn slice_or_array_pattern(
359         &mut self,
360         span: Span,
361         ty: Ty<'tcx>,
362         prefix: &'tcx [hir::Pat<'tcx>],
363         slice: &'tcx Option<&'tcx hir::Pat<'tcx>>,
364         suffix: &'tcx [hir::Pat<'tcx>],
365     ) -> PatKind<'tcx> {
366         let prefix = self.lower_patterns(prefix);
367         let slice = self.lower_opt_pattern(slice);
368         let suffix = self.lower_patterns(suffix);
369         match ty.kind() {
370             // Matching a slice, `[T]`.
371             ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
372             // Fixed-length array, `[T; len]`.
373             ty::Array(_, len) => {
374                 let len = len.eval_usize(self.tcx, self.param_env);
375                 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
376                 PatKind::Array { prefix, slice, suffix }
377             }
378             _ => span_bug!(span, "bad slice pattern type {:?}", ty),
379         }
380     }
381
382     fn lower_variant_or_leaf(
383         &mut self,
384         res: Res,
385         hir_id: hir::HirId,
386         span: Span,
387         ty: Ty<'tcx>,
388         subpatterns: Vec<FieldPat<'tcx>>,
389     ) -> PatKind<'tcx> {
390         let res = match res {
391             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
392                 let variant_id = self.tcx.parent(variant_ctor_id);
393                 Res::Def(DefKind::Variant, variant_id)
394             }
395             res => res,
396         };
397
398         let mut kind = match res {
399             Res::Def(DefKind::Variant, variant_id) => {
400                 let enum_id = self.tcx.parent(variant_id);
401                 let adt_def = self.tcx.adt_def(enum_id);
402                 if adt_def.is_enum() {
403                     let substs = match ty.kind() {
404                         ty::Adt(_, substs) | ty::FnDef(_, substs) => substs,
405                         ty::Error(_) => {
406                             // Avoid ICE (#50585)
407                             return PatKind::Wild;
408                         }
409                         _ => bug!("inappropriate type for def: {:?}", ty),
410                     };
411                     PatKind::Variant {
412                         adt_def,
413                         substs,
414                         variant_index: adt_def.variant_index_with_id(variant_id),
415                         subpatterns,
416                     }
417                 } else {
418                     PatKind::Leaf { subpatterns }
419                 }
420             }
421
422             Res::Def(
423                 DefKind::Struct
424                 | DefKind::Ctor(CtorOf::Struct, ..)
425                 | DefKind::Union
426                 | DefKind::TyAlias
427                 | DefKind::AssocTy,
428                 _,
429             )
430             | Res::SelfTy { .. }
431             | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
432             _ => {
433                 let pattern_error = match res {
434                     Res::Def(DefKind::ConstParam, _) => PatternError::ConstParamInPattern(span),
435                     Res::Def(DefKind::Static(_), _) => PatternError::StaticInPattern(span),
436                     _ => PatternError::NonConstPath(span),
437                 };
438                 self.errors.push(pattern_error);
439                 PatKind::Wild
440             }
441         };
442
443         if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
444             debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
445             let annotation = CanonicalUserTypeAnnotation {
446                 user_ty,
447                 span,
448                 inferred_ty: self.typeck_results.node_type(hir_id),
449             };
450             kind = PatKind::AscribeUserType {
451                 subpattern: Box::new(Pat { span, ty, kind }),
452                 ascription: Ascription { annotation, variance: ty::Variance::Covariant },
453             };
454         }
455
456         kind
457     }
458
459     /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
460     /// it to `const_to_pat`. Any other path (like enum variants without fields)
461     /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
462     #[instrument(skip(self), level = "debug")]
463     fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
464         let ty = self.typeck_results.node_type(id);
465         let res = self.typeck_results.qpath_res(qpath, id);
466
467         let pat_from_kind = |kind| Box::new(Pat { span, ty, kind });
468
469         let (def_id, is_associated_const) = match res {
470             Res::Def(DefKind::Const, def_id) => (def_id, false),
471             Res::Def(DefKind::AssocConst, def_id) => (def_id, true),
472
473             _ => return pat_from_kind(self.lower_variant_or_leaf(res, id, span, ty, vec![])),
474         };
475
476         // Use `Reveal::All` here because patterns are always monomorphic even if their function
477         // isn't.
478         let param_env_reveal_all = self.param_env.with_reveal_all_normalized(self.tcx);
479         let substs = self.typeck_results.node_substs(id);
480         let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) {
481             Ok(Some(i)) => i,
482             Ok(None) => {
483                 // It should be assoc consts if there's no error but we cannot resolve it.
484                 debug_assert!(is_associated_const);
485
486                 self.errors.push(PatternError::AssocConstInPattern(span));
487
488                 return pat_from_kind(PatKind::Wild);
489             }
490
491             Err(_) => {
492                 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
493                 return pat_from_kind(PatKind::Wild);
494             }
495         };
496
497         // `mir_const_qualif` must be called with the `DefId` of the item where the const is
498         // defined, not where it is declared. The difference is significant for associated
499         // constants.
500         let mir_structural_match_violation = self.tcx.mir_const_qualif(instance.def_id()).custom_eq;
501         debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation);
502
503         match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
504             Ok(literal) => {
505                 let const_ = mir::ConstantKind::Val(literal, ty);
506                 let pattern = self.const_to_pat(const_, id, span, mir_structural_match_violation);
507
508                 if !is_associated_const {
509                     return pattern;
510                 }
511
512                 let user_provided_types = self.typeck_results().user_provided_types();
513                 if let Some(&user_ty) = user_provided_types.get(id) {
514                     let annotation = CanonicalUserTypeAnnotation {
515                         user_ty,
516                         span,
517                         inferred_ty: self.typeck_results().node_type(id),
518                     };
519                     Box::new(Pat {
520                         span,
521                         kind: PatKind::AscribeUserType {
522                             subpattern: pattern,
523                             ascription: Ascription {
524                                 annotation,
525                                 /// Note that use `Contravariant` here. See the
526                                 /// `variance` field documentation for details.
527                                 variance: ty::Variance::Contravariant,
528                             },
529                         },
530                         ty: const_.ty(),
531                     })
532                 } else {
533                     pattern
534                 }
535             }
536             Err(ErrorHandled::TooGeneric) => {
537                 // While `Reported | Linted` cases will have diagnostics emitted already
538                 // it is not true for TooGeneric case, so we need to give user more information.
539                 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
540                 pat_from_kind(PatKind::Wild)
541             }
542             Err(_) => {
543                 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
544                 pat_from_kind(PatKind::Wild)
545             }
546         }
547     }
548
549     /// Converts inline const patterns.
550     fn lower_inline_const(
551         &mut self,
552         anon_const: &'tcx hir::AnonConst,
553         id: hir::HirId,
554         span: Span,
555     ) -> PatKind<'tcx> {
556         let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
557         let value = mir::ConstantKind::from_inline_const(self.tcx, anon_const_def_id);
558
559         // Evaluate early like we do in `lower_path`.
560         let value = value.eval(self.tcx, self.param_env);
561
562         match value {
563             mir::ConstantKind::Ty(c) => {
564                 match c.kind() {
565                     ConstKind::Param(_) => {
566                         self.errors.push(PatternError::ConstParamInPattern(span));
567                         return PatKind::Wild;
568                     }
569                     ConstKind::Unevaluated(_) => {
570                         // If we land here it means the const can't be evaluated because it's `TooGeneric`.
571                         self.tcx
572                             .sess
573                             .span_err(span, "constant pattern depends on a generic parameter");
574                         return PatKind::Wild;
575                     }
576                     _ => bug!("Expected either ConstKind::Param or ConstKind::Unevaluated"),
577                 }
578             }
579             mir::ConstantKind::Val(_, _) => self.const_to_pat(value, id, span, false).kind,
580         }
581     }
582
583     /// Converts literals, paths and negation of literals to patterns.
584     /// The special case for negation exists to allow things like `-128_i8`
585     /// which would overflow if we tried to evaluate `128_i8` and then negate
586     /// afterwards.
587     fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
588         let (lit, neg) = match expr.kind {
589             hir::ExprKind::Path(ref qpath) => {
590                 return self.lower_path(qpath, expr.hir_id, expr.span).kind;
591             }
592             hir::ExprKind::ConstBlock(ref anon_const) => {
593                 return self.lower_inline_const(anon_const, expr.hir_id, expr.span);
594             }
595             hir::ExprKind::Lit(ref lit) => (lit, false),
596             hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => {
597                 let hir::ExprKind::Lit(ref lit) = expr.kind else {
598                     span_bug!(expr.span, "not a literal: {:?}", expr);
599                 };
600                 (lit, true)
601             }
602             _ => span_bug!(expr.span, "not a literal: {:?}", expr),
603         };
604
605         let lit_input =
606             LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
607         match self.tcx.at(expr.span).lit_to_mir_constant(lit_input) {
608             Ok(constant) => self.const_to_pat(constant, expr.hir_id, lit.span, false).kind,
609             Err(LitToConstError::Reported) => PatKind::Wild,
610             Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
611         }
612     }
613 }
614
615 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
616     fn tcx(&self) -> TyCtxt<'tcx> {
617         self.tcx
618     }
619
620     fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
621         self.typeck_results
622     }
623 }
624
625 pub(crate) trait PatternFoldable<'tcx>: Sized {
626     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
627         self.super_fold_with(folder)
628     }
629
630     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
631 }
632
633 pub(crate) trait PatternFolder<'tcx>: Sized {
634     fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
635         pattern.super_fold_with(self)
636     }
637
638     fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
639         kind.super_fold_with(self)
640     }
641 }
642
643 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
644     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
645         let content: T = (**self).fold_with(folder);
646         Box::new(content)
647     }
648 }
649
650 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
651     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
652         self.iter().map(|t| t.fold_with(folder)).collect()
653     }
654 }
655
656 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
657     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
658         self.as_ref().map(|t| t.fold_with(folder))
659     }
660 }
661
662 macro_rules! ClonePatternFoldableImpls {
663     (<$lt_tcx:tt> $($ty:ty),+) => {
664         $(
665             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
666                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
667                     Clone::clone(self)
668                 }
669             }
670         )+
671     }
672 }
673
674 ClonePatternFoldableImpls! { <'tcx>
675     Span, Field, Mutability, Symbol, LocalVarId, usize, ty::Const<'tcx>,
676     Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>,
677     SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
678     UserTypeProjection, CanonicalUserTypeAnnotation<'tcx>
679 }
680
681 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
682     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
683         FieldPat { field: self.field.fold_with(folder), pattern: self.pattern.fold_with(folder) }
684     }
685 }
686
687 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
688     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
689         folder.fold_pattern(self)
690     }
691
692     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
693         Pat {
694             ty: self.ty.fold_with(folder),
695             span: self.span.fold_with(folder),
696             kind: self.kind.fold_with(folder),
697         }
698     }
699 }
700
701 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
702     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
703         folder.fold_pattern_kind(self)
704     }
705
706     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
707         match *self {
708             PatKind::Wild => PatKind::Wild,
709             PatKind::AscribeUserType {
710                 ref subpattern,
711                 ascription: Ascription { ref annotation, variance },
712             } => PatKind::AscribeUserType {
713                 subpattern: subpattern.fold_with(folder),
714                 ascription: Ascription { annotation: annotation.fold_with(folder), variance },
715             },
716             PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, is_primary } => {
717                 PatKind::Binding {
718                     mutability: mutability.fold_with(folder),
719                     name: name.fold_with(folder),
720                     mode: mode.fold_with(folder),
721                     var: var.fold_with(folder),
722                     ty: ty.fold_with(folder),
723                     subpattern: subpattern.fold_with(folder),
724                     is_primary,
725                 }
726             }
727             PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
728                 PatKind::Variant {
729                     adt_def: adt_def.fold_with(folder),
730                     substs: substs.fold_with(folder),
731                     variant_index,
732                     subpatterns: subpatterns.fold_with(folder),
733                 }
734             }
735             PatKind::Leaf { ref subpatterns } => {
736                 PatKind::Leaf { subpatterns: subpatterns.fold_with(folder) }
737             }
738             PatKind::Deref { ref subpattern } => {
739                 PatKind::Deref { subpattern: subpattern.fold_with(folder) }
740             }
741             PatKind::Constant { value } => PatKind::Constant { value },
742             PatKind::Range(ref range) => PatKind::Range(range.clone()),
743             PatKind::Slice { ref prefix, ref slice, ref suffix } => PatKind::Slice {
744                 prefix: prefix.fold_with(folder),
745                 slice: slice.fold_with(folder),
746                 suffix: suffix.fold_with(folder),
747             },
748             PatKind::Array { ref prefix, ref slice, ref suffix } => PatKind::Array {
749                 prefix: prefix.fold_with(folder),
750                 slice: slice.fold_with(folder),
751                 suffix: suffix.fold_with(folder),
752             },
753             PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
754         }
755     }
756 }
757
758 #[instrument(skip(tcx), level = "debug")]
759 pub(crate) fn compare_const_vals<'tcx>(
760     tcx: TyCtxt<'tcx>,
761     a: mir::ConstantKind<'tcx>,
762     b: mir::ConstantKind<'tcx>,
763     param_env: ty::ParamEnv<'tcx>,
764 ) -> Option<Ordering> {
765     assert_eq!(a.ty(), b.ty());
766
767     let ty = a.ty();
768
769     // This code is hot when compiling matches with many ranges. So we
770     // special-case extraction of evaluated scalars for speed, for types where
771     // raw data comparisons are appropriate. E.g. `unicode-normalization` has
772     // many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
773     // in this way.
774     match ty.kind() {
775         ty::Float(_) | ty::Int(_) => {} // require special handling, see below
776         _ => match (a, b) {
777             (
778                 mir::ConstantKind::Val(ConstValue::Scalar(Scalar::Int(a)), _a_ty),
779                 mir::ConstantKind::Val(ConstValue::Scalar(Scalar::Int(b)), _b_ty),
780             ) => return Some(a.cmp(&b)),
781             _ => {}
782         },
783     }
784
785     let a = a.eval_bits(tcx, param_env, ty);
786     let b = b.eval_bits(tcx, param_env, ty);
787
788     use rustc_apfloat::Float;
789     match *ty.kind() {
790         ty::Float(ty::FloatTy::F32) => {
791             let a = rustc_apfloat::ieee::Single::from_bits(a);
792             let b = rustc_apfloat::ieee::Single::from_bits(b);
793             a.partial_cmp(&b)
794         }
795         ty::Float(ty::FloatTy::F64) => {
796             let a = rustc_apfloat::ieee::Double::from_bits(a);
797             let b = rustc_apfloat::ieee::Double::from_bits(b);
798             a.partial_cmp(&b)
799         }
800         ty::Int(ity) => {
801             use rustc_middle::ty::layout::IntegerExt;
802             let size = rustc_target::abi::Integer::from_int_ty(&tcx, ity).size();
803             let a = size.sign_extend(a);
804             let b = size.sign_extend(b);
805             Some((a as i128).cmp(&(b as i128)))
806         }
807         _ => Some(a.cmp(&b)),
808     }
809 }