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