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 
pat_from_hir<'a, 'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, typeck_results: &'a ty::TypeckResults<'tcx>, pat: &'tcx hir::Pat<'tcx>, ) -> Pat<'tcx>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> {
new( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, typeck_results: &'a ty::TypeckResults<'tcx>, ) -> Self62     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 
include_lint_checks(&mut self) -> &mut Self70     crate fn include_lint_checks(&mut self) -> &mut Self {
71         self.include_lint_checks = true;
72         self
73     }
74 
lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx>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 
lower_range_expr( &mut self, expr: &'tcx hir::Expr<'tcx>, ) -> (PatKind<'tcx>, Option<Ascription<'tcx>>)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 
lower_pattern_range( &mut self, ty: Ty<'tcx>, lo: &'tcx ty::Const<'tcx>, hi: &'tcx ty::Const<'tcx>, end: RangeEnd, span: Span, ) -> PatKind<'tcx>121     fn lower_pattern_range(
122         &mut self,
123         ty: Ty<'tcx>,
124         lo: &'tcx ty::Const<'tcx>,
125         hi: &'tcx 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 
normalize_range_pattern_ends( &self, ty: Ty<'tcx>, lo: Option<&PatKind<'tcx>>, hi: Option<&PatKind<'tcx>>, ) -> Option<(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>)>175     fn normalize_range_pattern_ends(
176         &self,
177         ty: Ty<'tcx>,
178         lo: Option<&PatKind<'tcx>>,
179         hi: Option<&PatKind<'tcx>>,
180     ) -> Option<(&'tcx ty::Const<'tcx>, &'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 
lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx>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(ref 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 tys = match ty.kind() {
249                     ty::Tuple(ref tys) => tys,
250                     _ => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty),
251                 };
252                 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
253                 PatKind::Leaf { subpatterns }
254             }
255 
256             hir::PatKind::Binding(_, id, ident, ref sub) => {
257                 let bm = *self
258                     .typeck_results
259                     .pat_binding_modes()
260                     .get(pat.hir_id)
261                     .expect("missing binding mode");
262                 let (mutability, mode) = match bm {
263                     ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue),
264                     ty::BindByReference(hir::Mutability::Mut) => (
265                         Mutability::Not,
266                         BindingMode::ByRef(BorrowKind::Mut { allow_two_phase_borrow: false }),
267                     ),
268                     ty::BindByReference(hir::Mutability::Not) => {
269                         (Mutability::Not, BindingMode::ByRef(BorrowKind::Shared))
270                     }
271                 };
272 
273                 // A ref x pattern is the same node used for x, and as such it has
274                 // x's type, which is &T, where we want T (the type being matched).
275                 let var_ty = ty;
276                 if let ty::BindByReference(_) = bm {
277                     if let ty::Ref(_, rty, _) = ty.kind() {
278                         ty = rty;
279                     } else {
280                         bug!("`ref {}` has wrong type {}", ident, ty);
281                     }
282                 };
283 
284                 PatKind::Binding {
285                     mutability,
286                     mode,
287                     name: ident.name,
288                     var: id,
289                     ty: var_ty,
290                     subpattern: self.lower_opt_pattern(sub),
291                     is_primary: id == pat.hir_id,
292                 }
293             }
294 
295             hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => {
296                 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
297                 let adt_def = match ty.kind() {
298                     ty::Adt(adt_def, _) => adt_def,
299                     _ => span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty),
300                 };
301                 let variant_def = adt_def.variant_of_res(res);
302                 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
303                 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
304             }
305 
306             hir::PatKind::Struct(ref qpath, ref fields, _) => {
307                 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
308                 let subpatterns = fields
309                     .iter()
310                     .map(|field| FieldPat {
311                         field: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)),
312                         pattern: self.lower_pattern(&field.pat),
313                     })
314                     .collect();
315 
316                 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
317             }
318 
319             hir::PatKind::Or(ref pats) => PatKind::Or { pats: self.lower_patterns(pats) },
320         };
321 
322         Pat { span: pat.span, ty, kind: Box::new(kind) }
323     }
324 
lower_tuple_subpats( &mut self, pats: &'tcx [hir::Pat<'tcx>], expected_len: usize, gap_pos: Option<usize>, ) -> Vec<FieldPat<'tcx>>325     fn lower_tuple_subpats(
326         &mut self,
327         pats: &'tcx [hir::Pat<'tcx>],
328         expected_len: usize,
329         gap_pos: Option<usize>,
330     ) -> Vec<FieldPat<'tcx>> {
331         pats.iter()
332             .enumerate_and_adjust(expected_len, gap_pos)
333             .map(|(i, subpattern)| FieldPat {
334                 field: Field::new(i),
335                 pattern: self.lower_pattern(subpattern),
336             })
337             .collect()
338     }
339 
lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Vec<Pat<'tcx>>340     fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Vec<Pat<'tcx>> {
341         pats.iter().map(|p| self.lower_pattern(p)).collect()
342     }
343 
lower_opt_pattern(&mut self, pat: &'tcx Option<&'tcx hir::Pat<'tcx>>) -> Option<Pat<'tcx>>344     fn lower_opt_pattern(&mut self, pat: &'tcx Option<&'tcx hir::Pat<'tcx>>) -> Option<Pat<'tcx>> {
345         pat.as_ref().map(|p| self.lower_pattern(p))
346     }
347 
slice_or_array_pattern( &mut self, span: Span, ty: Ty<'tcx>, prefix: &'tcx [hir::Pat<'tcx>], slice: &'tcx Option<&'tcx hir::Pat<'tcx>>, suffix: &'tcx [hir::Pat<'tcx>], ) -> PatKind<'tcx>348     fn slice_or_array_pattern(
349         &mut self,
350         span: Span,
351         ty: Ty<'tcx>,
352         prefix: &'tcx [hir::Pat<'tcx>],
353         slice: &'tcx Option<&'tcx hir::Pat<'tcx>>,
354         suffix: &'tcx [hir::Pat<'tcx>],
355     ) -> PatKind<'tcx> {
356         let prefix = self.lower_patterns(prefix);
357         let slice = self.lower_opt_pattern(slice);
358         let suffix = self.lower_patterns(suffix);
359         match ty.kind() {
360             // Matching a slice, `[T]`.
361             ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
362             // Fixed-length array, `[T; len]`.
363             ty::Array(_, len) => {
364                 let len = len.eval_usize(self.tcx, self.param_env);
365                 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
366                 PatKind::Array { prefix, slice, suffix }
367             }
368             _ => span_bug!(span, "bad slice pattern type {:?}", ty),
369         }
370     }
371 
lower_variant_or_leaf( &mut self, res: Res, hir_id: hir::HirId, span: Span, ty: Ty<'tcx>, subpatterns: Vec<FieldPat<'tcx>>, ) -> PatKind<'tcx>372     fn lower_variant_or_leaf(
373         &mut self,
374         res: Res,
375         hir_id: hir::HirId,
376         span: Span,
377         ty: Ty<'tcx>,
378         subpatterns: Vec<FieldPat<'tcx>>,
379     ) -> PatKind<'tcx> {
380         let res = match res {
381             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
382                 let variant_id = self.tcx.parent(variant_ctor_id).unwrap();
383                 Res::Def(DefKind::Variant, variant_id)
384             }
385             res => res,
386         };
387 
388         let mut kind = match res {
389             Res::Def(DefKind::Variant, variant_id) => {
390                 let enum_id = self.tcx.parent(variant_id).unwrap();
391                 let adt_def = self.tcx.adt_def(enum_id);
392                 if adt_def.is_enum() {
393                     let substs = match ty.kind() {
394                         ty::Adt(_, substs) | ty::FnDef(_, substs) => substs,
395                         ty::Error(_) => {
396                             // Avoid ICE (#50585)
397                             return PatKind::Wild;
398                         }
399                         _ => bug!("inappropriate type for def: {:?}", ty),
400                     };
401                     PatKind::Variant {
402                         adt_def,
403                         substs,
404                         variant_index: adt_def.variant_index_with_id(variant_id),
405                         subpatterns,
406                     }
407                 } else {
408                     PatKind::Leaf { subpatterns }
409                 }
410             }
411 
412             Res::Def(
413                 DefKind::Struct
414                 | DefKind::Ctor(CtorOf::Struct, ..)
415                 | DefKind::Union
416                 | DefKind::TyAlias
417                 | DefKind::AssocTy,
418                 _,
419             )
420             | Res::SelfTy(..)
421             | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
422             _ => {
423                 let pattern_error = match res {
424                     Res::Def(DefKind::ConstParam, _) => PatternError::ConstParamInPattern(span),
425                     Res::Def(DefKind::Static, _) => PatternError::StaticInPattern(span),
426                     _ => PatternError::NonConstPath(span),
427                 };
428                 self.errors.push(pattern_error);
429                 PatKind::Wild
430             }
431         };
432 
433         if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
434             debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
435             kind = PatKind::AscribeUserType {
436                 subpattern: Pat { span, ty, kind: Box::new(kind) },
437                 ascription: Ascription {
438                     user_ty: PatTyProj::from_user_type(user_ty),
439                     user_ty_span: span,
440                     variance: ty::Variance::Covariant,
441                 },
442             };
443         }
444 
445         kind
446     }
447 
448     /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
449     /// it to `const_to_pat`. Any other path (like enum variants without fields)
450     /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Pat<'tcx>451     fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Pat<'tcx> {
452         let ty = self.typeck_results.node_type(id);
453         let res = self.typeck_results.qpath_res(qpath, id);
454 
455         let pat_from_kind = |kind| Pat { span, ty, kind: Box::new(kind) };
456 
457         let (def_id, is_associated_const) = match res {
458             Res::Def(DefKind::Const, def_id) => (def_id, false),
459             Res::Def(DefKind::AssocConst, def_id) => (def_id, true),
460 
461             _ => return pat_from_kind(self.lower_variant_or_leaf(res, id, span, ty, vec![])),
462         };
463 
464         // Use `Reveal::All` here because patterns are always monomorphic even if their function
465         // isn't.
466         let param_env_reveal_all = self.param_env.with_reveal_all_normalized(self.tcx);
467         let substs = self.typeck_results.node_substs(id);
468         let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) {
469             Ok(Some(i)) => i,
470             Ok(None) => {
471                 // It should be assoc consts if there's no error but we cannot resolve it.
472                 debug_assert!(is_associated_const);
473 
474                 self.errors.push(PatternError::AssocConstInPattern(span));
475 
476                 return pat_from_kind(PatKind::Wild);
477             }
478 
479             Err(_) => {
480                 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
481                 return pat_from_kind(PatKind::Wild);
482             }
483         };
484 
485         // `mir_const_qualif` must be called with the `DefId` of the item where the const is
486         // defined, not where it is declared. The difference is significant for associated
487         // constants.
488         let mir_structural_match_violation = self.tcx.mir_const_qualif(instance.def_id()).custom_eq;
489         debug!("mir_structural_match_violation({:?}) -> {}", qpath, mir_structural_match_violation);
490 
491         match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) {
492             Ok(value) => {
493                 let const_ =
494                     ty::Const::from_value(self.tcx, value, self.typeck_results.node_type(id));
495 
496                 let pattern = self.const_to_pat(&const_, id, span, mir_structural_match_violation);
497 
498                 if !is_associated_const {
499                     return pattern;
500                 }
501 
502                 let user_provided_types = self.typeck_results().user_provided_types();
503                 if let Some(u_ty) = user_provided_types.get(id) {
504                     let user_ty = PatTyProj::from_user_type(*u_ty);
505                     Pat {
506                         span,
507                         kind: Box::new(PatKind::AscribeUserType {
508                             subpattern: pattern,
509                             ascription: Ascription {
510                                 /// Note that use `Contravariant` here. See the
511                                 /// `variance` field documentation for details.
512                                 variance: ty::Variance::Contravariant,
513                                 user_ty,
514                                 user_ty_span: span,
515                             },
516                         }),
517                         ty: const_.ty,
518                     }
519                 } else {
520                     pattern
521                 }
522             }
523             Err(ErrorHandled::TooGeneric) => {
524                 // While `Reported | Linted` cases will have diagnostics emitted already
525                 // it is not true for TooGeneric case, so we need to give user more information.
526                 self.tcx.sess.span_err(span, "constant pattern depends on a generic parameter");
527                 pat_from_kind(PatKind::Wild)
528             }
529             Err(_) => {
530                 self.tcx.sess.span_err(span, "could not evaluate constant pattern");
531                 pat_from_kind(PatKind::Wild)
532             }
533         }
534     }
535 
536     /// Converts literals, paths and negation of literals to patterns.
537     /// The special case for negation exists to allow things like `-128_i8`
538     /// which would overflow if we tried to evaluate `128_i8` and then negate
539     /// afterwards.
lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx>540     fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
541         if let hir::ExprKind::Path(ref qpath) = expr.kind {
542             *self.lower_path(qpath, expr.hir_id, expr.span).kind
543         } else {
544             let (lit, neg) = match expr.kind {
545                 hir::ExprKind::ConstBlock(ref anon_const) => {
546                     let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
547                     let value = ty::Const::from_inline_const(self.tcx, anon_const_def_id);
548                     if matches!(value.val, ConstKind::Param(_)) {
549                         let span = self.tcx.hir().span(anon_const.hir_id);
550                         self.errors.push(PatternError::ConstParamInPattern(span));
551                         return PatKind::Wild;
552                     }
553                     return *self.const_to_pat(value, expr.hir_id, expr.span, false).kind;
554                 }
555                 hir::ExprKind::Lit(ref lit) => (lit, false),
556                 hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => {
557                     let lit = match expr.kind {
558                         hir::ExprKind::Lit(ref lit) => lit,
559                         _ => span_bug!(expr.span, "not a literal: {:?}", expr),
560                     };
561                     (lit, true)
562                 }
563                 _ => span_bug!(expr.span, "not a literal: {:?}", expr),
564             };
565 
566             let lit_input =
567                 LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg };
568             match self.tcx.at(expr.span).lit_to_const(lit_input) {
569                 Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind,
570                 Err(LitToConstError::Reported) => PatKind::Wild,
571                 Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
572             }
573         }
574     }
575 }
576 
577 impl<'tcx> UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> {
tcx(&self) -> TyCtxt<'tcx>578     fn tcx(&self) -> TyCtxt<'tcx> {
579         self.tcx
580     }
581 
typeck_results(&self) -> &ty::TypeckResults<'tcx>582     fn typeck_results(&self) -> &ty::TypeckResults<'tcx> {
583         self.typeck_results
584     }
585 }
586 
587 crate trait PatternFoldable<'tcx>: Sized {
fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self588     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
589         self.super_fold_with(folder)
590     }
591 
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self592     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
593 }
594 
595 crate trait PatternFolder<'tcx>: Sized {
fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx>596     fn fold_pattern(&mut self, pattern: &Pat<'tcx>) -> Pat<'tcx> {
597         pattern.super_fold_with(self)
598     }
599 
fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx>600     fn fold_pattern_kind(&mut self, kind: &PatKind<'tcx>) -> PatKind<'tcx> {
601         kind.super_fold_with(self)
602     }
603 }
604 
605 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self606     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
607         let content: T = (**self).fold_with(folder);
608         Box::new(content)
609     }
610 }
611 
612 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self613     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
614         self.iter().map(|t| t.fold_with(folder)).collect()
615     }
616 }
617 
618 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self619     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
620         self.as_ref().map(|t| t.fold_with(folder))
621     }
622 }
623 
624 macro_rules! CloneImpls {
625     (<$lt_tcx:tt> $($ty:ty),+) => {
626         $(
627             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
628                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
629                     Clone::clone(self)
630                 }
631             }
632         )+
633     }
634 }
635 
636 CloneImpls! { <'tcx>
637     Span, Field, Mutability, Symbol, hir::HirId, usize, ty::Const<'tcx>,
638     Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
639     SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
640     UserTypeProjection, PatTyProj<'tcx>
641 }
642 
643 impl<'tcx> PatternFoldable<'tcx> for FieldPat<'tcx> {
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self644     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
645         FieldPat { field: self.field.fold_with(folder), pattern: self.pattern.fold_with(folder) }
646     }
647 }
648 
649 impl<'tcx> PatternFoldable<'tcx> for Pat<'tcx> {
fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self650     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
651         folder.fold_pattern(self)
652     }
653 
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self654     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
655         Pat {
656             ty: self.ty.fold_with(folder),
657             span: self.span.fold_with(folder),
658             kind: self.kind.fold_with(folder),
659         }
660     }
661 }
662 
663 impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> {
fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self664     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
665         folder.fold_pattern_kind(self)
666     }
667 
super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self668     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
669         match *self {
670             PatKind::Wild => PatKind::Wild,
671             PatKind::AscribeUserType {
672                 ref subpattern,
673                 ascription: Ascription { variance, ref user_ty, user_ty_span },
674             } => PatKind::AscribeUserType {
675                 subpattern: subpattern.fold_with(folder),
676                 ascription: Ascription {
677                     user_ty: user_ty.fold_with(folder),
678                     variance,
679                     user_ty_span,
680                 },
681             },
682             PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, is_primary } => {
683                 PatKind::Binding {
684                     mutability: mutability.fold_with(folder),
685                     name: name.fold_with(folder),
686                     mode: mode.fold_with(folder),
687                     var: var.fold_with(folder),
688                     ty: ty.fold_with(folder),
689                     subpattern: subpattern.fold_with(folder),
690                     is_primary,
691                 }
692             }
693             PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
694                 PatKind::Variant {
695                     adt_def: adt_def.fold_with(folder),
696                     substs: substs.fold_with(folder),
697                     variant_index,
698                     subpatterns: subpatterns.fold_with(folder),
699                 }
700             }
701             PatKind::Leaf { ref subpatterns } => {
702                 PatKind::Leaf { subpatterns: subpatterns.fold_with(folder) }
703             }
704             PatKind::Deref { ref subpattern } => {
705                 PatKind::Deref { subpattern: subpattern.fold_with(folder) }
706             }
707             PatKind::Constant { value } => PatKind::Constant { value },
708             PatKind::Range(range) => PatKind::Range(range),
709             PatKind::Slice { ref prefix, ref slice, ref suffix } => PatKind::Slice {
710                 prefix: prefix.fold_with(folder),
711                 slice: slice.fold_with(folder),
712                 suffix: suffix.fold_with(folder),
713             },
714             PatKind::Array { ref prefix, ref slice, ref suffix } => PatKind::Array {
715                 prefix: prefix.fold_with(folder),
716                 slice: slice.fold_with(folder),
717                 suffix: suffix.fold_with(folder),
718             },
719             PatKind::Or { ref pats } => PatKind::Or { pats: pats.fold_with(folder) },
720         }
721     }
722 }
723 
compare_const_vals<'tcx>( tcx: TyCtxt<'tcx>, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>, ) -> Option<Ordering>724 crate fn compare_const_vals<'tcx>(
725     tcx: TyCtxt<'tcx>,
726     a: &'tcx ty::Const<'tcx>,
727     b: &'tcx ty::Const<'tcx>,
728     param_env: ty::ParamEnv<'tcx>,
729     ty: Ty<'tcx>,
730 ) -> Option<Ordering> {
731     trace!("compare_const_vals: {:?}, {:?}", a, b);
732 
733     let from_bool = |v: bool| v.then_some(Ordering::Equal);
734 
735     let fallback = || from_bool(a == b);
736 
737     // Use the fallback if any type differs
738     if a.ty != b.ty || a.ty != ty {
739         return fallback();
740     }
741 
742     // Early return for equal constants (so e.g. references to ZSTs can be compared, even if they
743     // are just integer addresses).
744     if a.val == b.val {
745         return from_bool(true);
746     }
747 
748     let a_bits = a.try_eval_bits(tcx, param_env, ty);
749     let b_bits = b.try_eval_bits(tcx, param_env, ty);
750 
751     if let (Some(a), Some(b)) = (a_bits, b_bits) {
752         use rustc_apfloat::Float;
753         return match *ty.kind() {
754             ty::Float(ty::FloatTy::F32) => {
755                 let l = rustc_apfloat::ieee::Single::from_bits(a);
756                 let r = rustc_apfloat::ieee::Single::from_bits(b);
757                 l.partial_cmp(&r)
758             }
759             ty::Float(ty::FloatTy::F64) => {
760                 let l = rustc_apfloat::ieee::Double::from_bits(a);
761                 let r = rustc_apfloat::ieee::Double::from_bits(b);
762                 l.partial_cmp(&r)
763             }
764             ty::Int(ity) => {
765                 use rustc_middle::ty::layout::IntegerExt;
766                 let size = rustc_target::abi::Integer::from_int_ty(&tcx, ity).size();
767                 let a = size.sign_extend(a);
768                 let b = size.sign_extend(b);
769                 Some((a as i128).cmp(&(b as i128)))
770             }
771             _ => Some(a.cmp(&b)),
772         };
773     }
774 
775     if let ty::Str = ty.kind() {
776         if let (
777             ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }),
778             ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }),
779         ) = (a.val, b.val)
780         {
781             let a_bytes = get_slice_bytes(&tcx, a_val);
782             let b_bytes = get_slice_bytes(&tcx, b_val);
783             return from_bool(a_bytes == b_bytes);
784         }
785     }
786     fallback()
787 }
788