]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/mod.rs
4d571f4f78296124d665a00d3818c5244e38d0c2
[rust.git] / src / librustc_mir / hair / pattern / mod.rs
1 //! Validation of patterns/matches.
2
3 mod _match;
4 mod check_match;
5
6 pub use self::check_match::check_crate;
7 pub(crate) use self::check_match::check_match;
8
9 use crate::const_eval::{const_field, const_variant_index};
10
11 use crate::hair::util::UserAnnotatedTyHelpers;
12 use crate::hair::constant::*;
13
14 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
15 use rustc::mir::{UserTypeProjection};
16 use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
17 use rustc::ty::{self, Region, TyCtxt, AdtDef, Ty, Lift, UserType};
18 use rustc::ty::{CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations};
19 use rustc::ty::subst::{Substs, Kind};
20 use rustc::ty::layout::VariantIdx;
21 use rustc::hir::{self, PatKind, RangeEnd};
22 use rustc::hir::def::{Def, CtorKind};
23 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
24
25 use rustc_data_structures::indexed_vec::Idx;
26
27 use std::cmp::Ordering;
28 use std::fmt;
29 use syntax::ast;
30 use syntax::ptr::P;
31 use syntax_pos::Span;
32
33 #[derive(Clone, Debug)]
34 pub enum PatternError {
35     AssociatedConstInPattern(Span),
36     StaticInPattern(Span),
37     FloatBug,
38     NonConstPath(Span),
39 }
40
41 #[derive(Copy, Clone, Debug)]
42 pub enum BindingMode {
43     ByValue,
44     ByRef(BorrowKind),
45 }
46
47 #[derive(Clone, Debug)]
48 pub struct FieldPattern<'tcx> {
49     pub field: Field,
50     pub pattern: Pattern<'tcx>,
51 }
52
53 #[derive(Clone, Debug)]
54 pub struct Pattern<'tcx> {
55     pub ty: Ty<'tcx>,
56     pub span: Span,
57     pub kind: Box<PatternKind<'tcx>>,
58 }
59
60
61 #[derive(Copy, Clone, Debug, PartialEq)]
62 pub struct PatternTypeProjection<'tcx> {
63     pub user_ty: CanonicalUserType<'tcx>,
64 }
65
66 impl<'tcx> PatternTypeProjection<'tcx> {
67     pub(crate) fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
68         Self {
69             user_ty: user_annotation,
70         }
71     }
72
73     pub(crate) fn user_ty(
74         self,
75         annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
76         inferred_ty: Ty<'tcx>,
77         span: Span,
78     ) -> UserTypeProjection<'tcx> {
79         UserTypeProjection {
80             base: annotations.push(CanonicalUserTypeAnnotation {
81                 span,
82                 user_ty: self.user_ty,
83                 inferred_ty,
84             }),
85             projs: Vec::new(),
86         }
87     }
88 }
89
90 #[derive(Copy, Clone, Debug, PartialEq)]
91 pub struct Ascription<'tcx> {
92     pub user_ty: PatternTypeProjection<'tcx>,
93     /// Variance to use when relating the type `user_ty` to the **type of the value being
94     /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
95     /// have a type that is some subtype of the ascribed type.
96     ///
97     /// Note that this variance does not apply for any bindings within subpatterns. The type
98     /// assigned to those bindings must be exactly equal to the `user_ty` given here.
99     ///
100     /// The only place where this field is not `Covariant` is when matching constants, where
101     /// we currently use `Contravariant` -- this is because the constant type just needs to
102     /// be "comparable" to the type of the input value. So, for example:
103     ///
104     /// ```text
105     /// match x { "foo" => .. }
106     /// ```
107     ///
108     /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
109     /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
110     /// of the old type-check for now. See #57280 for details.
111     pub variance: ty::Variance,
112     pub user_ty_span: Span,
113 }
114
115 #[derive(Clone, Debug)]
116 pub enum PatternKind<'tcx> {
117     Wild,
118
119     AscribeUserType {
120         ascription: Ascription<'tcx>,
121         subpattern: Pattern<'tcx>,
122     },
123
124     /// `x`, `ref x`, `x @ P`, etc.
125     Binding {
126         mutability: Mutability,
127         name: ast::Name,
128         mode: BindingMode,
129         var: ast::NodeId,
130         ty: Ty<'tcx>,
131         subpattern: Option<Pattern<'tcx>>,
132     },
133
134     /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
135     /// multiple variants.
136     Variant {
137         adt_def: &'tcx AdtDef,
138         substs: &'tcx Substs<'tcx>,
139         variant_index: VariantIdx,
140         subpatterns: Vec<FieldPattern<'tcx>>,
141     },
142
143     /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
144     /// a single variant.
145     Leaf {
146         subpatterns: Vec<FieldPattern<'tcx>>,
147     },
148
149     /// `box P`, `&P`, `&mut P`, etc.
150     Deref {
151         subpattern: Pattern<'tcx>,
152     },
153
154     Constant {
155         value: ty::Const<'tcx>,
156     },
157
158     Range(PatternRange<'tcx>),
159
160     /// Matches against a slice, checking the length and extracting elements.
161     /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
162     /// e.g., `&[ref xs..]`.
163     Slice {
164         prefix: Vec<Pattern<'tcx>>,
165         slice: Option<Pattern<'tcx>>,
166         suffix: Vec<Pattern<'tcx>>,
167     },
168
169     /// Fixed match against an array; irrefutable.
170     Array {
171         prefix: Vec<Pattern<'tcx>>,
172         slice: Option<Pattern<'tcx>>,
173         suffix: Vec<Pattern<'tcx>>,
174     },
175 }
176
177 #[derive(Copy, Clone, Debug, PartialEq)]
178 pub struct PatternRange<'tcx> {
179     pub lo: ty::Const<'tcx>,
180     pub hi: ty::Const<'tcx>,
181     pub ty: Ty<'tcx>,
182     pub end: RangeEnd,
183 }
184
185 impl<'tcx> fmt::Display for Pattern<'tcx> {
186     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187         match *self.kind {
188             PatternKind::Wild => write!(f, "_"),
189             PatternKind::AscribeUserType { ref subpattern, .. } =>
190                 write!(f, "{}: _", subpattern),
191             PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
192                 let is_mut = match mode {
193                     BindingMode::ByValue => mutability == Mutability::Mut,
194                     BindingMode::ByRef(bk) => {
195                         write!(f, "ref ")?;
196                         match bk { BorrowKind::Mut { .. } => true, _ => false }
197                     }
198                 };
199                 if is_mut {
200                     write!(f, "mut ")?;
201                 }
202                 write!(f, "{}", name)?;
203                 if let Some(ref subpattern) = *subpattern {
204                     write!(f, " @ {}", subpattern)?;
205                 }
206                 Ok(())
207             }
208             PatternKind::Variant { ref subpatterns, .. } |
209             PatternKind::Leaf { ref subpatterns } => {
210                 let variant = match *self.kind {
211                     PatternKind::Variant { adt_def, variant_index, .. } => {
212                         Some(&adt_def.variants[variant_index])
213                     }
214                     _ => if let ty::Adt(adt, _) = self.ty.sty {
215                         if !adt.is_enum() {
216                             Some(&adt.variants[VariantIdx::new(0)])
217                         } else {
218                             None
219                         }
220                     } else {
221                         None
222                     }
223                 };
224
225                 let mut first = true;
226                 let mut start_or_continue = || if first { first = false; "" } else { ", " };
227
228                 if let Some(variant) = variant {
229                     write!(f, "{}", variant.ident)?;
230
231                     // Only for Adt we can have `S {...}`,
232                     // which we handle separately here.
233                     if variant.ctor_kind == CtorKind::Fictive {
234                         write!(f, " {{ ")?;
235
236                         let mut printed = 0;
237                         for p in subpatterns {
238                             if let PatternKind::Wild = *p.pattern.kind {
239                                 continue;
240                             }
241                             let name = variant.fields[p.field.index()].ident;
242                             write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
243                             printed += 1;
244                         }
245
246                         if printed < variant.fields.len() {
247                             write!(f, "{}..", start_or_continue())?;
248                         }
249
250                         return write!(f, " }}");
251                     }
252                 }
253
254                 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
255                 if num_fields != 0 || variant.is_none() {
256                     write!(f, "(")?;
257                     for i in 0..num_fields {
258                         write!(f, "{}", start_or_continue())?;
259
260                         // Common case: the field is where we expect it.
261                         if let Some(p) = subpatterns.get(i) {
262                             if p.field.index() == i {
263                                 write!(f, "{}", p.pattern)?;
264                                 continue;
265                             }
266                         }
267
268                         // Otherwise, we have to go looking for it.
269                         if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
270                             write!(f, "{}", p.pattern)?;
271                         } else {
272                             write!(f, "_")?;
273                         }
274                     }
275                     write!(f, ")")?;
276                 }
277
278                 Ok(())
279             }
280             PatternKind::Deref { ref subpattern } => {
281                 match self.ty.sty {
282                     ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
283                     ty::Ref(_, _, mutbl) => {
284                         write!(f, "&")?;
285                         if mutbl == hir::MutMutable {
286                             write!(f, "mut ")?;
287                         }
288                     }
289                     _ => bug!("{} is a bad Deref pattern type", self.ty)
290                 }
291                 write!(f, "{}", subpattern)
292             }
293             PatternKind::Constant { value } => {
294                 fmt_const_val(f, value)
295             }
296             PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
297                 fmt_const_val(f, lo)?;
298                 match end {
299                     RangeEnd::Included => write!(f, "..=")?,
300                     RangeEnd::Excluded => write!(f, "..")?,
301                 }
302                 fmt_const_val(f, hi)
303             }
304             PatternKind::Slice { ref prefix, ref slice, ref suffix } |
305             PatternKind::Array { ref prefix, ref slice, ref suffix } => {
306                 let mut first = true;
307                 let mut start_or_continue = || if first { first = false; "" } else { ", " };
308                 write!(f, "[")?;
309                 for p in prefix {
310                     write!(f, "{}{}", start_or_continue(), p)?;
311                 }
312                 if let Some(ref slice) = *slice {
313                     write!(f, "{}", start_or_continue())?;
314                     match *slice.kind {
315                         PatternKind::Wild => {}
316                         _ => write!(f, "{}", slice)?
317                     }
318                     write!(f, "..")?;
319                 }
320                 for p in suffix {
321                     write!(f, "{}{}", start_or_continue(), p)?;
322                 }
323                 write!(f, "]")
324             }
325         }
326     }
327 }
328
329 pub struct PatternContext<'a, 'tcx: 'a> {
330     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
331     pub param_env: ty::ParamEnv<'tcx>,
332     pub tables: &'a ty::TypeckTables<'tcx>,
333     pub substs: &'tcx Substs<'tcx>,
334     pub errors: Vec<PatternError>,
335 }
336
337 impl<'a, 'tcx> Pattern<'tcx> {
338     pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
339                     param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
340                     tables: &'a ty::TypeckTables<'tcx>,
341                     pat: &'tcx hir::Pat) -> Self {
342         let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
343         let result = pcx.lower_pattern(pat);
344         if !pcx.errors.is_empty() {
345             let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
346             tcx.sess.delay_span_bug(pat.span, &msg);
347         }
348         debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
349         result
350     }
351 }
352
353 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
354     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
355                param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
356                tables: &'a ty::TypeckTables<'tcx>) -> Self {
357         PatternContext {
358             tcx,
359             param_env: param_env_and_substs.param_env,
360             tables,
361             substs: param_env_and_substs.value,
362             errors: vec![]
363         }
364     }
365
366     pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
367         // When implicit dereferences have been inserted in this pattern, the unadjusted lowered
368         // pattern has the type that results *after* dereferencing. For example, in this code:
369         //
370         // ```
371         // match &&Some(0i32) {
372         //     Some(n) => { ... },
373         //     _ => { ... },
374         // }
375         // ```
376         //
377         // the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
378         // determined in rustc_typeck::check::match). The adjustments would be
379         //
380         // `vec![&&Option<i32>, &Option<i32>]`.
381         //
382         // Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
383         // we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
384         // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
385         // gets the least-dereferenced type).
386         let unadjusted_pat = self.lower_pattern_unadjusted(pat);
387         self.tables
388             .pat_adjustments()
389             .get(pat.hir_id)
390             .unwrap_or(&vec![])
391             .iter()
392             .rev()
393             .fold(unadjusted_pat, |pat, ref_ty| {
394                     debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
395                     Pattern {
396                         span: pat.span,
397                         ty: ref_ty,
398                         kind: Box::new(PatternKind::Deref { subpattern: pat }),
399                     }
400                 },
401             )
402     }
403
404     fn lower_range_expr(
405         &mut self,
406         expr: &'tcx hir::Expr,
407     ) -> (PatternKind<'tcx>, Option<Ascription<'tcx>>) {
408         match self.lower_lit(expr) {
409             PatternKind::AscribeUserType {
410                 ascription: lo_ascription,
411                 subpattern: Pattern { kind: box kind, .. },
412             } => (kind, Some(lo_ascription)),
413             kind => (kind, None),
414         }
415     }
416
417     fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
418         let mut ty = self.tables.node_type(pat.hir_id);
419
420         let kind = match pat.node {
421             PatKind::Wild => PatternKind::Wild,
422
423             PatKind::Lit(ref value) => self.lower_lit(value),
424
425             PatKind::Range(ref lo_expr, ref hi_expr, end) => {
426                 let (lo, lo_ascription) = self.lower_range_expr(lo_expr);
427                 let (hi, hi_ascription) = self.lower_range_expr(hi_expr);
428
429                 let mut kind = match (lo, hi) {
430                     (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => {
431                         use std::cmp::Ordering;
432                         let cmp = compare_const_vals(
433                             self.tcx,
434                             lo,
435                             hi,
436                             self.param_env.and(ty),
437                         );
438                         match (end, cmp) {
439                             (RangeEnd::Excluded, Some(Ordering::Less)) =>
440                                 PatternKind::Range(PatternRange { lo, hi, ty, end }),
441                             (RangeEnd::Excluded, _) => {
442                                 span_err!(
443                                     self.tcx.sess,
444                                     lo_expr.span,
445                                     E0579,
446                                     "lower range bound must be less than upper",
447                                 );
448                                 PatternKind::Wild
449                             }
450                             (RangeEnd::Included, Some(Ordering::Equal)) => {
451                                 PatternKind::Constant { value: lo }
452                             }
453                             (RangeEnd::Included, Some(Ordering::Less)) => {
454                                 PatternKind::Range(PatternRange { lo, hi, ty, end })
455                             }
456                             (RangeEnd::Included, _) => {
457                                 let mut err = struct_span_err!(
458                                     self.tcx.sess,
459                                     lo_expr.span,
460                                     E0030,
461                                     "lower range bound must be less than or equal to upper"
462                                 );
463                                 err.span_label(
464                                     lo_expr.span,
465                                     "lower bound larger than upper bound",
466                                 );
467                                 if self.tcx.sess.teach(&err.get_code().unwrap()) {
468                                     err.note("When matching against a range, the compiler \
469                                               verifies that the range is non-empty. Range \
470                                               patterns include both end-points, so this is \
471                                               equivalent to requiring the start of the range \
472                                               to be less than or equal to the end of the range.");
473                                 }
474                                 err.emit();
475                                 PatternKind::Wild
476                             }
477                         }
478                     },
479                     ref pats => {
480                         self.tcx.sess.delay_span_bug(
481                             pat.span,
482                             &format!(
483                                 "found bad range pattern `{:?}` outside of error recovery",
484                                 pats,
485                             ),
486                         );
487
488                         PatternKind::Wild
489                     },
490                 };
491
492                 // If we are handling a range with associated constants (e.g.
493                 // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
494                 // constants somewhere. Have them on the range pattern.
495                 for ascription in &[lo_ascription, hi_ascription] {
496                     if let Some(ascription) = ascription {
497                         kind = PatternKind::AscribeUserType {
498                             ascription: *ascription,
499                             subpattern: Pattern { span: pat.span, ty, kind: Box::new(kind), },
500                         };
501                     }
502                 }
503
504                 kind
505             }
506
507             PatKind::Path(ref qpath) => {
508                 return self.lower_path(qpath, pat.hir_id, pat.span);
509             }
510
511             PatKind::Ref(ref subpattern, _) |
512             PatKind::Box(ref subpattern) => {
513                 PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
514             }
515
516             PatKind::Slice(ref prefix, ref slice, ref suffix) => {
517                 match ty.sty {
518                     ty::Ref(_, ty, _) =>
519                         PatternKind::Deref {
520                             subpattern: Pattern {
521                                 ty,
522                                 span: pat.span,
523                                 kind: Box::new(self.slice_or_array_pattern(
524                                     pat.span, ty, prefix, slice, suffix))
525                             },
526                         },
527                     ty::Slice(..) |
528                     ty::Array(..) =>
529                         self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
530                     ty::Error => { // Avoid ICE
531                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
532                     }
533                     ref sty =>
534                         span_bug!(
535                             pat.span,
536                             "unexpanded type for vector pattern: {:?}",
537                             sty),
538                 }
539             }
540
541             PatKind::Tuple(ref subpatterns, ddpos) => {
542                 match ty.sty {
543                     ty::Tuple(ref tys) => {
544                         let subpatterns =
545                             subpatterns.iter()
546                                        .enumerate_and_adjust(tys.len(), ddpos)
547                                        .map(|(i, subpattern)| FieldPattern {
548                                             field: Field::new(i),
549                                             pattern: self.lower_pattern(subpattern)
550                                        })
551                                        .collect();
552
553                         PatternKind::Leaf { subpatterns }
554                     }
555                     ty::Error => { // Avoid ICE (#50577)
556                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
557                     }
558                     ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
559                 }
560             }
561
562             PatKind::Binding(_, id, _, ident, ref sub) => {
563                 let var_ty = self.tables.node_type(pat.hir_id);
564                 if let ty::Error = var_ty.sty {
565                     // Avoid ICE
566                     return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
567                 };
568                 let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
569                                                          .expect("missing binding mode");
570                 let (mutability, mode) = match bm {
571                     ty::BindByValue(hir::MutMutable) =>
572                         (Mutability::Mut, BindingMode::ByValue),
573                     ty::BindByValue(hir::MutImmutable) =>
574                         (Mutability::Not, BindingMode::ByValue),
575                     ty::BindByReference(hir::MutMutable) =>
576                         (Mutability::Not, BindingMode::ByRef(
577                             BorrowKind::Mut { allow_two_phase_borrow: false })),
578                     ty::BindByReference(hir::MutImmutable) =>
579                         (Mutability::Not, BindingMode::ByRef(
580                             BorrowKind::Shared)),
581                 };
582
583                 // A ref x pattern is the same node used for x, and as such it has
584                 // x's type, which is &T, where we want T (the type being matched).
585                 if let ty::BindByReference(_) = bm {
586                     if let ty::Ref(_, rty, _) = ty.sty {
587                         ty = rty;
588                     } else {
589                         bug!("`ref {}` has wrong type {}", ident, ty);
590                     }
591                 }
592
593                 PatternKind::Binding {
594                     mutability,
595                     mode,
596                     name: ident.name,
597                     var: id,
598                     ty: var_ty,
599                     subpattern: self.lower_opt_pattern(sub),
600                 }
601             }
602
603             PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
604                 let def = self.tables.qpath_def(qpath, pat.hir_id);
605                 let adt_def = match ty.sty {
606                     ty::Adt(adt_def, _) => adt_def,
607                     ty::Error => { // Avoid ICE (#50585)
608                         return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
609                     }
610                     _ => span_bug!(pat.span,
611                                    "tuple struct pattern not applied to an ADT {:?}",
612                                    ty.sty),
613                 };
614                 let variant_def = adt_def.variant_of_def(def);
615
616                 let subpatterns =
617                         subpatterns.iter()
618                                    .enumerate_and_adjust(variant_def.fields.len(), ddpos)
619                                    .map(|(i, field)| FieldPattern {
620                                        field: Field::new(i),
621                                        pattern: self.lower_pattern(field),
622                                    })
623                     .collect();
624
625                 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
626             }
627
628             PatKind::Struct(ref qpath, ref fields, _) => {
629                 let def = self.tables.qpath_def(qpath, pat.hir_id);
630                 let subpatterns =
631                     fields.iter()
632                           .map(|field| {
633                               FieldPattern {
634                                   field: Field::new(self.tcx.field_index(field.node.id,
635                                                                          self.tables)),
636                                   pattern: self.lower_pattern(&field.node.pat),
637                               }
638                           })
639                           .collect();
640
641                 self.lower_variant_or_leaf(def, pat.hir_id, pat.span, ty, subpatterns)
642             }
643         };
644
645         Pattern {
646             span: pat.span,
647             ty,
648             kind: Box::new(kind),
649         }
650     }
651
652     fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
653         pats.iter().map(|p| self.lower_pattern(p)).collect()
654     }
655
656     fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
657     {
658         pat.as_ref().map(|p| self.lower_pattern(p))
659     }
660
661     fn flatten_nested_slice_patterns(
662         &mut self,
663         prefix: Vec<Pattern<'tcx>>,
664         slice: Option<Pattern<'tcx>>,
665         suffix: Vec<Pattern<'tcx>>)
666         -> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
667     {
668         let orig_slice = match slice {
669             Some(orig_slice) => orig_slice,
670             None => return (prefix, slice, suffix)
671         };
672         let orig_prefix = prefix;
673         let orig_suffix = suffix;
674
675         // dance because of intentional borrow-checker stupidity.
676         let kind = *orig_slice.kind;
677         match kind {
678             PatternKind::Slice { prefix, slice, mut suffix } |
679             PatternKind::Array { prefix, slice, mut suffix } => {
680                 let mut orig_prefix = orig_prefix;
681
682                 orig_prefix.extend(prefix);
683                 suffix.extend(orig_suffix);
684
685                 (orig_prefix, slice, suffix)
686             }
687             _ => {
688                 (orig_prefix, Some(Pattern {
689                     kind: box kind, ..orig_slice
690                 }), orig_suffix)
691             }
692         }
693     }
694
695     fn slice_or_array_pattern(
696         &mut self,
697         span: Span,
698         ty: Ty<'tcx>,
699         prefix: &'tcx [P<hir::Pat>],
700         slice: &'tcx Option<P<hir::Pat>>,
701         suffix: &'tcx [P<hir::Pat>])
702         -> PatternKind<'tcx>
703     {
704         let prefix = self.lower_patterns(prefix);
705         let slice = self.lower_opt_pattern(slice);
706         let suffix = self.lower_patterns(suffix);
707         let (prefix, slice, suffix) =
708             self.flatten_nested_slice_patterns(prefix, slice, suffix);
709
710         match ty.sty {
711             ty::Slice(..) => {
712                 // matching a slice or fixed-length array
713                 PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
714             }
715
716             ty::Array(_, len) => {
717                 // fixed-length array
718                 let len = len.unwrap_usize(self.tcx);
719                 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
720                 PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
721             }
722
723             _ => {
724                 span_bug!(span, "bad slice pattern type {:?}", ty);
725             }
726         }
727     }
728
729     fn lower_variant_or_leaf(
730         &mut self,
731         def: Def,
732         hir_id: hir::HirId,
733         span: Span,
734         ty: Ty<'tcx>,
735         subpatterns: Vec<FieldPattern<'tcx>>,
736     ) -> PatternKind<'tcx> {
737         let mut kind = match def {
738             Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
739                 let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
740                 let adt_def = self.tcx.adt_def(enum_id);
741                 if adt_def.is_enum() {
742                     let substs = match ty.sty {
743                         ty::Adt(_, substs) |
744                         ty::FnDef(_, substs) => substs,
745                         ty::Error => {  // Avoid ICE (#50585)
746                             return PatternKind::Wild;
747                         }
748                         _ => bug!("inappropriate type for def: {:?}", ty.sty),
749                     };
750                     PatternKind::Variant {
751                         adt_def,
752                         substs,
753                         variant_index: adt_def.variant_index_with_id(variant_id),
754                         subpatterns,
755                     }
756                 } else {
757                     PatternKind::Leaf { subpatterns }
758                 }
759             }
760
761             Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
762             Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
763                 PatternKind::Leaf { subpatterns }
764             }
765
766             _ => {
767                 self.errors.push(PatternError::NonConstPath(span));
768                 PatternKind::Wild
769             }
770         };
771
772         if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) {
773             debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
774             kind = PatternKind::AscribeUserType {
775                 subpattern: Pattern {
776                     span,
777                     ty,
778                     kind: Box::new(kind),
779                 },
780                 ascription: Ascription {
781                     user_ty: PatternTypeProjection::from_user_type(user_ty),
782                     user_ty_span: span,
783                     variance: ty::Variance::Covariant,
784                 },
785             };
786         }
787
788         kind
789     }
790
791     /// Takes a HIR Path. If the path is a constant, evaluates it and feeds
792     /// it to `const_to_pat`. Any other path (like enum variants without fields)
793     /// is converted to the corresponding pattern via `lower_variant_or_leaf`.
794     fn lower_path(&mut self,
795                   qpath: &hir::QPath,
796                   id: hir::HirId,
797                   span: Span)
798                   -> Pattern<'tcx> {
799         let ty = self.tables.node_type(id);
800         let def = self.tables.qpath_def(qpath, id);
801         let is_associated_const = match def {
802             Def::AssociatedConst(_) => true,
803             _ => false,
804         };
805         let kind = match def {
806             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
807                 let substs = self.tables.node_substs(id);
808                 match ty::Instance::resolve(
809                     self.tcx,
810                     self.param_env,
811                     def_id,
812                     substs,
813                 ) {
814                     Some(instance) => {
815                         let cid = GlobalId {
816                             instance,
817                             promoted: None,
818                         };
819                         match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
820                             Ok(value) => {
821                                 let pattern = self.const_to_pat(instance, value, id, span);
822                                 if !is_associated_const {
823                                     return pattern;
824                                 }
825
826                                 let user_provided_types = self.tables().user_provided_types();
827                                 return if let Some(u_ty) = user_provided_types.get(id) {
828                                     let user_ty = PatternTypeProjection::from_user_type(*u_ty);
829                                     Pattern {
830                                         span,
831                                         kind: Box::new(
832                                             PatternKind::AscribeUserType {
833                                                 subpattern: pattern,
834                                                 ascription: Ascription {
835                                                     /// Note that use `Contravariant` here. See the
836                                                     /// `variance` field documentation for details.
837                                                     variance: ty::Variance::Contravariant,
838                                                     user_ty,
839                                                     user_ty_span: span,
840                                                 },
841                                             }
842                                         ),
843                                         ty: value.ty,
844                                     }
845                                 } else {
846                                     pattern
847                                 }
848                             },
849                             Err(_) => {
850                                 self.tcx.sess.span_err(
851                                     span,
852                                     "could not evaluate constant pattern",
853                                 );
854                                 PatternKind::Wild
855                             }
856                         }
857                     },
858                     None => {
859                         self.errors.push(if is_associated_const {
860                             PatternError::AssociatedConstInPattern(span)
861                         } else {
862                             PatternError::StaticInPattern(span)
863                         });
864                         PatternKind::Wild
865                     },
866                 }
867             }
868             _ => self.lower_variant_or_leaf(def, id, span, ty, vec![]),
869         };
870
871         Pattern {
872             span,
873             ty,
874             kind: Box::new(kind),
875         }
876     }
877
878     /// Converts literals, paths and negation of literals to patterns.
879     /// The special case for negation exists to allow things like `-128_i8`
880     /// which would overflow if we tried to evaluate `128_i8` and then negate
881     /// afterwards.
882     fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
883         match expr.node {
884             hir::ExprKind::Lit(ref lit) => {
885                 let ty = self.tables.expr_ty(expr);
886                 match lit_to_const(&lit.node, self.tcx, ty, false) {
887                     Ok(val) => {
888                         let instance = ty::Instance::new(
889                             self.tables.local_id_root.expect("literal outside any scope"),
890                             self.substs,
891                         );
892                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
893                     },
894                     Err(LitToConstError::UnparseableFloat) => {
895                         self.errors.push(PatternError::FloatBug);
896                         PatternKind::Wild
897                     },
898                     Err(LitToConstError::Reported) => PatternKind::Wild,
899                 }
900             },
901             hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
902             hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
903                 let ty = self.tables.expr_ty(expr);
904                 let lit = match expr.node {
905                     hir::ExprKind::Lit(ref lit) => lit,
906                     _ => span_bug!(expr.span, "not a literal: {:?}", expr),
907                 };
908                 match lit_to_const(&lit.node, self.tcx, ty, true) {
909                     Ok(val) => {
910                         let instance = ty::Instance::new(
911                             self.tables.local_id_root.expect("literal outside any scope"),
912                             self.substs,
913                         );
914                         *self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
915                     },
916                     Err(LitToConstError::UnparseableFloat) => {
917                         self.errors.push(PatternError::FloatBug);
918                         PatternKind::Wild
919                     },
920                     Err(LitToConstError::Reported) => PatternKind::Wild,
921                 }
922             }
923             _ => span_bug!(expr.span, "not a literal: {:?}", expr),
924         }
925     }
926
927     /// Converts an evaluated constant to a pattern (if possible).
928     /// This means aggregate values (like structs and enums) are converted
929     /// to a pattern that matches the value (as if you'd compared via equality).
930     fn const_to_pat(
931         &self,
932         instance: ty::Instance<'tcx>,
933         cv: ty::Const<'tcx>,
934         id: hir::HirId,
935         span: Span,
936     ) -> Pattern<'tcx> {
937         debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
938         let adt_subpattern = |i, variant_opt| {
939             let field = Field::new(i);
940             let val = const_field(
941                 self.tcx, self.param_env,
942                 variant_opt, field, cv,
943             ).expect("field access failed");
944             self.const_to_pat(instance, val, id, span)
945         };
946         let adt_subpatterns = |n, variant_opt| {
947             (0..n).map(|i| {
948                 let field = Field::new(i);
949                 FieldPattern {
950                     field,
951                     pattern: adt_subpattern(i, variant_opt),
952                 }
953             }).collect::<Vec<_>>()
954         };
955         debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
956         let kind = match cv.ty.sty {
957             ty::Float(_) => {
958                 let id = self.tcx.hir().hir_to_node_id(id);
959                 self.tcx.lint_node(
960                     ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
961                     id,
962                     span,
963                     "floating-point types cannot be used in patterns",
964                 );
965                 PatternKind::Constant {
966                     value: cv,
967                 }
968             }
969             ty::Adt(adt_def, _) if adt_def.is_union() => {
970                 // Matching on union fields is unsafe, we can't hide it in constants
971                 self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
972                 PatternKind::Wild
973             }
974             ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
975                 let msg = format!("to use a constant of type `{}` in a pattern, \
976                                     `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
977                                     self.tcx.item_path_str(adt_def.did),
978                                     self.tcx.item_path_str(adt_def.did));
979                 self.tcx.sess.span_err(span, &msg);
980                 PatternKind::Wild
981             }
982             ty::Adt(adt_def, substs) if adt_def.is_enum() => {
983                 let variant_index = const_variant_index(
984                     self.tcx, self.param_env, cv
985                 ).expect("const_variant_index failed");
986                 let subpatterns = adt_subpatterns(
987                     adt_def.variants[variant_index].fields.len(),
988                     Some(variant_index),
989                 );
990                 PatternKind::Variant {
991                     adt_def,
992                     substs,
993                     variant_index,
994                     subpatterns,
995                 }
996             }
997             ty::Adt(adt_def, _) => {
998                 let struct_var = adt_def.non_enum_variant();
999                 PatternKind::Leaf {
1000                     subpatterns: adt_subpatterns(struct_var.fields.len(), None),
1001                 }
1002             }
1003             ty::Tuple(fields) => {
1004                 PatternKind::Leaf {
1005                     subpatterns: adt_subpatterns(fields.len(), None),
1006                 }
1007             }
1008             ty::Array(_, n) => {
1009                 PatternKind::Array {
1010                     prefix: (0..n.unwrap_usize(self.tcx))
1011                         .map(|i| adt_subpattern(i as usize, None))
1012                         .collect(),
1013                     slice: None,
1014                     suffix: Vec::new(),
1015                 }
1016             }
1017             _ => {
1018                 PatternKind::Constant {
1019                     value: cv,
1020                 }
1021             }
1022         };
1023
1024         Pattern {
1025             span,
1026             ty: cv.ty,
1027             kind: Box::new(kind),
1028         }
1029     }
1030 }
1031
1032 impl UserAnnotatedTyHelpers<'tcx, 'tcx> for PatternContext<'_, 'tcx> {
1033     fn tcx(&self) -> TyCtxt<'_, 'tcx, 'tcx> {
1034         self.tcx
1035     }
1036
1037     fn tables(&self) -> &ty::TypeckTables<'tcx> {
1038         self.tables
1039     }
1040 }
1041
1042
1043 pub trait PatternFoldable<'tcx> : Sized {
1044     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1045         self.super_fold_with(folder)
1046     }
1047
1048     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
1049 }
1050
1051 pub trait PatternFolder<'tcx> : Sized {
1052     fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
1053         pattern.super_fold_with(self)
1054     }
1055
1056     fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
1057         kind.super_fold_with(self)
1058     }
1059 }
1060
1061
1062 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
1063     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1064         let content: T = (**self).fold_with(folder);
1065         box content
1066     }
1067 }
1068
1069 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
1070     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1071         self.iter().map(|t| t.fold_with(folder)).collect()
1072     }
1073 }
1074
1075 impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
1076     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
1077         self.as_ref().map(|t| t.fold_with(folder))
1078     }
1079 }
1080
1081 macro_rules! CloneImpls {
1082     (<$lt_tcx:tt> $($ty:ty),+) => {
1083         $(
1084             impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
1085                 fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
1086                     Clone::clone(self)
1087                 }
1088             }
1089         )+
1090     }
1091 }
1092
1093 CloneImpls!{ <'tcx>
1094     Span, Field, Mutability, ast::Name, ast::NodeId, usize, ty::Const<'tcx>,
1095     Region<'tcx>, Ty<'tcx>, BindingMode, &'tcx AdtDef,
1096     &'tcx Substs<'tcx>, &'tcx Kind<'tcx>, UserType<'tcx>,
1097     UserTypeProjection<'tcx>, PatternTypeProjection<'tcx>
1098 }
1099
1100 impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
1101     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1102         FieldPattern {
1103             field: self.field.fold_with(folder),
1104             pattern: self.pattern.fold_with(folder)
1105         }
1106     }
1107 }
1108
1109 impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
1110     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1111         folder.fold_pattern(self)
1112     }
1113
1114     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1115         Pattern {
1116             ty: self.ty.fold_with(folder),
1117             span: self.span.fold_with(folder),
1118             kind: self.kind.fold_with(folder)
1119         }
1120     }
1121 }
1122
1123 impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
1124     fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1125         folder.fold_pattern_kind(self)
1126     }
1127
1128     fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
1129         match *self {
1130             PatternKind::Wild => PatternKind::Wild,
1131             PatternKind::AscribeUserType {
1132                 ref subpattern,
1133                 ascription: Ascription {
1134                     variance,
1135                     ref user_ty,
1136                     user_ty_span,
1137                 },
1138             } => PatternKind::AscribeUserType {
1139                 subpattern: subpattern.fold_with(folder),
1140                 ascription: Ascription {
1141                     user_ty: user_ty.fold_with(folder),
1142                     variance,
1143                     user_ty_span,
1144                 },
1145             },
1146             PatternKind::Binding {
1147                 mutability,
1148                 name,
1149                 mode,
1150                 var,
1151                 ty,
1152                 ref subpattern,
1153             } => PatternKind::Binding {
1154                 mutability: mutability.fold_with(folder),
1155                 name: name.fold_with(folder),
1156                 mode: mode.fold_with(folder),
1157                 var: var.fold_with(folder),
1158                 ty: ty.fold_with(folder),
1159                 subpattern: subpattern.fold_with(folder),
1160             },
1161             PatternKind::Variant {
1162                 adt_def,
1163                 substs,
1164                 variant_index,
1165                 ref subpatterns,
1166             } => PatternKind::Variant {
1167                 adt_def: adt_def.fold_with(folder),
1168                 substs: substs.fold_with(folder),
1169                 variant_index,
1170                 subpatterns: subpatterns.fold_with(folder)
1171             },
1172             PatternKind::Leaf {
1173                 ref subpatterns,
1174             } => PatternKind::Leaf {
1175                 subpatterns: subpatterns.fold_with(folder),
1176             },
1177             PatternKind::Deref {
1178                 ref subpattern,
1179             } => PatternKind::Deref {
1180                 subpattern: subpattern.fold_with(folder),
1181             },
1182             PatternKind::Constant {
1183                 value
1184             } => PatternKind::Constant {
1185                 value: value.fold_with(folder)
1186             },
1187             PatternKind::Range(PatternRange {
1188                 lo,
1189                 hi,
1190                 ty,
1191                 end,
1192             }) => PatternKind::Range(PatternRange {
1193                 lo: lo.fold_with(folder),
1194                 hi: hi.fold_with(folder),
1195                 ty: ty.fold_with(folder),
1196                 end,
1197             }),
1198             PatternKind::Slice {
1199                 ref prefix,
1200                 ref slice,
1201                 ref suffix,
1202             } => PatternKind::Slice {
1203                 prefix: prefix.fold_with(folder),
1204                 slice: slice.fold_with(folder),
1205                 suffix: suffix.fold_with(folder)
1206             },
1207             PatternKind::Array {
1208                 ref prefix,
1209                 ref slice,
1210                 ref suffix
1211             } => PatternKind::Array {
1212                 prefix: prefix.fold_with(folder),
1213                 slice: slice.fold_with(folder),
1214                 suffix: suffix.fold_with(folder)
1215             },
1216         }
1217     }
1218 }
1219
1220 pub fn compare_const_vals<'a, 'gcx, 'tcx>(
1221     tcx: TyCtxt<'a, 'gcx, 'tcx>,
1222     a: ty::Const<'tcx>,
1223     b: ty::Const<'tcx>,
1224     ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
1225 ) -> Option<Ordering> {
1226     trace!("compare_const_vals: {:?}, {:?}", a, b);
1227
1228     let from_bool = |v: bool| {
1229         if v {
1230             Some(Ordering::Equal)
1231         } else {
1232             None
1233         }
1234     };
1235
1236     let fallback = || from_bool(a == b);
1237
1238     // Use the fallback if any type differs
1239     if a.ty != b.ty || a.ty != ty.value {
1240         return fallback();
1241     }
1242
1243     let tcx = tcx.global_tcx();
1244     let (a, b, ty) = (a, b, ty).lift_to_tcx(tcx).unwrap();
1245
1246     // FIXME: This should use assert_bits(ty) instead of use_bits
1247     // but triggers possibly bugs due to mismatching of arrays and slices
1248     if let (Some(a), Some(b)) = (a.to_bits(tcx, ty), b.to_bits(tcx, ty)) {
1249         use ::rustc_apfloat::Float;
1250         return match ty.value.sty {
1251             ty::Float(ast::FloatTy::F32) => {
1252                 let l = ::rustc_apfloat::ieee::Single::from_bits(a);
1253                 let r = ::rustc_apfloat::ieee::Single::from_bits(b);
1254                 l.partial_cmp(&r)
1255             }
1256             ty::Float(ast::FloatTy::F64) => {
1257                 let l = ::rustc_apfloat::ieee::Double::from_bits(a);
1258                 let r = ::rustc_apfloat::ieee::Double::from_bits(b);
1259                 l.partial_cmp(&r)
1260             }
1261             ty::Int(_) => {
1262                 let layout = tcx.layout_of(ty).ok()?;
1263                 assert!(layout.abi.is_signed());
1264                 let a = sign_extend(a, layout.size);
1265                 let b = sign_extend(b, layout.size);
1266                 Some((a as i128).cmp(&(b as i128)))
1267             }
1268             _ => Some(a.cmp(&b)),
1269         }
1270     }
1271
1272     if let ty::Str = ty.value.sty {
1273         match (a.val, b.val) {
1274             (
1275                 ConstValue::Slice(
1276                     Scalar::Ptr(ptr_a),
1277                     len_a,
1278                 ),
1279                 ConstValue::Slice(
1280                     Scalar::Ptr(ptr_b),
1281                     len_b,
1282                 ),
1283             ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
1284                 if len_a == len_b {
1285                     let map = tcx.alloc_map.lock();
1286                     let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
1287                     let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
1288                     if alloc_a.bytes.len() as u64 == len_a {
1289                         return from_bool(alloc_a == alloc_b);
1290                     }
1291                 }
1292             }
1293             _ => (),
1294         }
1295     }
1296
1297     fallback()
1298 }