]> git.proxmox.com Git - rustc.git/blame - src/librustc_const_eval/_match.rs
New upstream version 1.20.0+dfsg1
[rustc.git] / src / librustc_const_eval / _match.rs
CommitLineData
c30ab7b3
SL
1// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11use self::Constructor::*;
12use self::Usefulness::*;
13use self::WitnessPreference::*;
14
15use rustc::middle::const_val::ConstVal;
16use eval::{compare_const_vals};
17
18use rustc_const_math::ConstInt;
19
8bb4bdeb 20use rustc_data_structures::fx::FxHashMap;
c30ab7b3
SL
21use rustc_data_structures::indexed_vec::Idx;
22
23use pattern::{FieldPattern, Pattern, PatternKind};
24use pattern::{PatternFoldable, PatternFolder};
25
476ff2be 26use rustc::hir::def_id::DefId;
32a655c1
SL
27use rustc::hir::RangeEnd;
28use rustc::ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable};
c30ab7b3 29
32a655c1 30use rustc::mir::Field;
c30ab7b3
SL
31use rustc::util::common::ErrorReported;
32
c30ab7b3
SL
33use syntax_pos::{Span, DUMMY_SP};
34
35use arena::TypedArena;
36
476ff2be 37use std::cmp::{self, Ordering};
c30ab7b3
SL
38use std::fmt;
39use std::iter::{FromIterator, IntoIterator, repeat};
40
41pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
42 -> &'a Pattern<'tcx>
43{
44 cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
45}
46
47struct LiteralExpander;
48impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
49 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
50 match (&pat.ty.sty, &*pat.kind) {
51 (&ty::TyRef(_, mt), &PatternKind::Constant { ref value }) => {
52 Pattern {
53 ty: pat.ty,
54 span: pat.span,
55 kind: box PatternKind::Deref {
56 subpattern: Pattern {
57 ty: mt.ty,
58 span: pat.span,
59 kind: box PatternKind::Constant { value: value.clone() },
60 }
61 }
62 }
63 }
64 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
65 s.fold_with(self)
66 }
67 _ => pat.super_fold_with(self)
68 }
69 }
70}
71
c30ab7b3
SL
72impl<'tcx> Pattern<'tcx> {
73 fn is_wildcard(&self) -> bool {
74 match *self.kind {
75 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
76 true,
77 _ => false
78 }
79 }
80}
81
82pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
83
84impl<'a, 'tcx> Matrix<'a, 'tcx> {
85 pub fn empty() -> Self {
86 Matrix(vec![])
87 }
88
89 pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
90 self.0.push(row)
91 }
92}
93
94/// Pretty-printer for matrices of patterns, example:
95/// ++++++++++++++++++++++++++
96/// + _ + [] +
97/// ++++++++++++++++++++++++++
98/// + true + [First] +
99/// ++++++++++++++++++++++++++
100/// + true + [Second(true)] +
101/// ++++++++++++++++++++++++++
102/// + false + [_] +
103/// ++++++++++++++++++++++++++
104/// + _ + [_, _, ..tail] +
105/// ++++++++++++++++++++++++++
106impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 write!(f, "\n")?;
109
110 let &Matrix(ref m) = self;
111 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
112 row.iter().map(|pat| format!("{:?}", pat)).collect()
113 }).collect();
114
115 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
116 assert!(m.iter().all(|row| row.len() == column_count));
117 let column_widths: Vec<usize> = (0..column_count).map(|col| {
118 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
119 }).collect();
120
121 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
122 let br = repeat('+').take(total_width).collect::<String>();
123 write!(f, "{}\n", br)?;
124 for row in pretty_printed_matrix {
125 write!(f, "+")?;
126 for (column, pat_str) in row.into_iter().enumerate() {
127 write!(f, " ")?;
128 write!(f, "{:1$}", pat_str, column_widths[column])?;
129 write!(f, " +")?;
130 }
131 write!(f, "\n")?;
132 write!(f, "{}\n", br)?;
133 }
134 Ok(())
135 }
136}
137
138impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
139 fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
140 {
141 Matrix(iter.into_iter().collect())
142 }
143}
144
145//NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
146pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
147 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
32a655c1
SL
148 /// The module in which the match occurs. This is necessary for
149 /// checking inhabited-ness of types because whether a type is (visibly)
150 /// inhabited can depend on whether it was defined in the current module or
151 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
152 /// outside it's module and should not be matchable with an empty match
153 /// statement.
154 pub module: DefId,
c30ab7b3 155 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
476ff2be 156 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
c30ab7b3
SL
157}
158
159impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
160 pub fn create_and_enter<F, R>(
161 tcx: TyCtxt<'a, 'tcx, 'tcx>,
32a655c1 162 module: DefId,
c30ab7b3
SL
163 f: F) -> R
164 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
165 {
c30ab7b3
SL
166 let pattern_arena = TypedArena::new();
167
168 f(MatchCheckCtxt {
169 tcx: tcx,
32a655c1 170 module: module,
c30ab7b3 171 pattern_arena: &pattern_arena,
476ff2be 172 byte_array_map: FxHashMap(),
c30ab7b3
SL
173 })
174 }
175
176 // convert a byte-string pattern to a list of u8 patterns.
32a655c1
SL
177 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
178 where 'a: 'p
179 {
c30ab7b3
SL
180 let pattern_arena = &*self.pattern_arena;
181 let tcx = self.tcx;
182 self.byte_array_map.entry(pat).or_insert_with(|| {
183 match pat.kind {
184 box PatternKind::Constant {
185 value: ConstVal::ByteStr(ref data)
186 } => {
187 data.iter().map(|c| &*pattern_arena.alloc(Pattern {
188 ty: tcx.types.u8,
189 span: pat.span,
190 kind: box PatternKind::Constant {
191 value: ConstVal::Integral(ConstInt::U8(*c))
192 }
193 })).collect()
194 }
195 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
196 }
197 }).clone()
198 }
32a655c1
SL
199
200 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
201 if self.tcx.sess.features.borrow().never_type {
202 ty.is_uninhabited_from(self.module, self.tcx)
203 } else {
204 false
205 }
206 }
207
208 fn is_variant_uninhabited(&self,
209 variant: &'tcx ty::VariantDef,
210 substs: &'tcx ty::subst::Substs<'tcx>) -> bool
211 {
212 if self.tcx.sess.features.borrow().never_type {
213 let forest = variant.uninhabited_from(
8bb4bdeb 214 &mut FxHashMap::default(), self.tcx, substs, AdtKind::Enum
32a655c1
SL
215 );
216 forest.contains(self.tcx, self.module)
217 } else {
218 false
219 }
220 }
c30ab7b3
SL
221}
222
223#[derive(Clone, Debug, PartialEq)]
8bb4bdeb 224pub enum Constructor<'tcx> {
c30ab7b3
SL
225 /// The constructor of all patterns that don't vary by constructor,
226 /// e.g. struct patterns and fixed-length arrays.
227 Single,
228 /// Enum variants.
229 Variant(DefId),
230 /// Literal values.
8bb4bdeb 231 ConstantValue(ConstVal<'tcx>),
32a655c1 232 /// Ranges of literal values (`2...5` and `2..5`).
8bb4bdeb 233 ConstantRange(ConstVal<'tcx>, ConstVal<'tcx>, RangeEnd),
c30ab7b3
SL
234 /// Array patterns of length n.
235 Slice(usize),
236}
237
8bb4bdeb 238impl<'tcx> Constructor<'tcx> {
32a655c1 239 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
c30ab7b3 240 match self {
32a655c1 241 &Variant(vid) => adt.variant_index_with_id(vid),
c30ab7b3
SL
242 &Single => {
243 assert_eq!(adt.variants.len(), 1);
32a655c1 244 0
c30ab7b3
SL
245 }
246 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
247 }
248 }
249}
250
32a655c1
SL
251#[derive(Clone)]
252pub enum Usefulness<'tcx> {
c30ab7b3 253 Useful,
32a655c1 254 UsefulWithWitness(Vec<Witness<'tcx>>),
c30ab7b3
SL
255 NotUseful
256}
257
32a655c1
SL
258impl<'tcx> Usefulness<'tcx> {
259 fn is_useful(&self) -> bool {
260 match *self {
261 NotUseful => false,
262 _ => true
263 }
264 }
265}
266
c30ab7b3
SL
267#[derive(Copy, Clone)]
268pub enum WitnessPreference {
269 ConstructWitness,
270 LeaveOutWitness
271}
272
273#[derive(Copy, Clone, Debug)]
274struct PatternContext<'tcx> {
275 ty: Ty<'tcx>,
276 max_slice_length: usize,
277}
278
c30ab7b3 279/// A stack of patterns in reverse order of construction
32a655c1
SL
280#[derive(Clone)]
281pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
c30ab7b3 282
32a655c1
SL
283impl<'tcx> Witness<'tcx> {
284 pub fn single_pattern(&self) -> &Pattern<'tcx> {
c30ab7b3
SL
285 assert_eq!(self.0.len(), 1);
286 &self.0[0]
287 }
288
32a655c1 289 fn push_wild_constructor<'a>(
c30ab7b3
SL
290 mut self,
291 cx: &MatchCheckCtxt<'a, 'tcx>,
8bb4bdeb 292 ctor: &Constructor<'tcx>,
c30ab7b3
SL
293 ty: Ty<'tcx>)
294 -> Self
295 {
32a655c1
SL
296 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
297 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
298 Pattern {
299 ty: ty,
300 span: DUMMY_SP,
301 kind: box PatternKind::Wild,
302 }
303 }));
c30ab7b3
SL
304 self.apply_constructor(cx, ctor, ty)
305 }
306
307
308 /// Constructs a partial witness for a pattern given a list of
309 /// patterns expanded by the specialization step.
310 ///
311 /// When a pattern P is discovered to be useful, this function is used bottom-up
312 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
313 /// of values, V, where each value in that set is not covered by any previously
314 /// used patterns and is covered by the pattern P'. Examples:
315 ///
316 /// left_ty: tuple of 3 elements
317 /// pats: [10, 20, _] => (10, 20, _)
318 ///
319 /// left_ty: struct X { a: (bool, &'static str), b: usize}
320 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
32a655c1 321 fn apply_constructor<'a>(
c30ab7b3
SL
322 mut self,
323 cx: &MatchCheckCtxt<'a,'tcx>,
8bb4bdeb 324 ctor: &Constructor<'tcx>,
c30ab7b3
SL
325 ty: Ty<'tcx>)
326 -> Self
327 {
328 let arity = constructor_arity(cx, ctor, ty);
329 let pat = {
330 let len = self.0.len();
331 let mut pats = self.0.drain(len-arity..).rev();
332
333 match ty.sty {
32a655c1
SL
334 ty::TyAdt(..) |
335 ty::TyTuple(..) => {
336 let pats = pats.enumerate().map(|(i, p)| {
337 FieldPattern {
338 field: Field::new(i),
339 pattern: p
c30ab7b3 340 }
32a655c1
SL
341 }).collect();
342
343 if let ty::TyAdt(adt, substs) = ty.sty {
344 if adt.variants.len() > 1 {
345 PatternKind::Variant {
346 adt_def: adt,
347 substs: substs,
348 variant_index: ctor.variant_index_for_adt(adt),
349 subpatterns: pats
350 }
351 } else {
352 PatternKind::Leaf { subpatterns: pats }
c30ab7b3 353 }
32a655c1
SL
354 } else {
355 PatternKind::Leaf { subpatterns: pats }
c30ab7b3
SL
356 }
357 }
358
32a655c1
SL
359 ty::TyRef(..) => {
360 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
c30ab7b3
SL
361 }
362
363 ty::TySlice(_) | ty::TyArray(..) => {
32a655c1
SL
364 PatternKind::Slice {
365 prefix: pats.collect(),
366 slice: None,
367 suffix: vec![]
368 }
c30ab7b3
SL
369 }
370
371 _ => {
372 match *ctor {
32a655c1
SL
373 ConstantValue(ref v) => PatternKind::Constant { value: v.clone() },
374 _ => PatternKind::Wild,
c30ab7b3
SL
375 }
376 }
377 }
378 };
379
32a655c1
SL
380 self.0.push(Pattern {
381 ty: ty,
382 span: DUMMY_SP,
383 kind: Box::new(pat),
384 });
c30ab7b3
SL
385
386 self
387 }
388}
389
c30ab7b3
SL
390/// This determines the set of all possible constructors of a pattern matching
391/// values of type `left_ty`. For vectors, this would normally be an infinite set
32a655c1
SL
392/// but is instead bounded by the maximum fixed length of slice patterns in
393/// the column of patterns being analyzed.
c30ab7b3
SL
394///
395/// This intentionally does not list ConstantValue specializations for
396/// non-booleans, because we currently assume that there is always a
397/// "non-standard constant" that matches. See issue #12483.
398///
32a655c1
SL
399/// We make sure to omit constructors that are statically impossible. eg for
400/// Option<!> we do not include Some(_) in the returned list of constructors.
401fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
8bb4bdeb
XL
402 pcx: PatternContext<'tcx>)
403 -> Vec<Constructor<'tcx>>
32a655c1
SL
404{
405 debug!("all_constructors({:?})", pcx.ty);
c30ab7b3
SL
406 match pcx.ty.sty {
407 ty::TyBool =>
408 [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
32a655c1
SL
409 ty::TySlice(ref sub_ty) => {
410 if cx.is_uninhabited(sub_ty) {
411 vec![Slice(0)]
412 } else {
413 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
414 }
415 }
416 ty::TyArray(ref sub_ty, length) => {
417 if length > 0 && cx.is_uninhabited(sub_ty) {
418 vec![]
419 } else {
420 vec![Slice(length)]
421 }
422 }
423 ty::TyAdt(def, substs) if def.is_enum() && def.variants.len() != 1 => {
424 def.variants.iter()
425 .filter(|v| !cx.is_variant_uninhabited(v, substs))
426 .map(|v| Variant(v.did))
427 .collect()
428 }
429 _ => {
430 if cx.is_uninhabited(pcx.ty) {
431 vec![]
432 } else {
433 vec![Single]
434 }
435 }
c30ab7b3
SL
436 }
437}
438
32a655c1 439fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
476ff2be
SL
440 _cx: &mut MatchCheckCtxt<'a, 'tcx>,
441 patterns: I) -> usize
32a655c1 442 where I: Iterator<Item=&'p Pattern<'tcx>>
476ff2be
SL
443{
444 // The exhaustiveness-checking paper does not include any details on
445 // checking variable-length slice patterns. However, they are matched
446 // by an infinite collection of fixed-length array patterns.
447 //
448 // Checking the infinite set directly would take an infinite amount
449 // of time. However, it turns out that for each finite set of
450 // patterns `P`, all sufficiently large array lengths are equivalent:
451 //
452 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
453 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
454 // `sₘ` for each sufficiently-large length `m` that applies to exactly
455 // the same subset of `P`.
456 //
457 // Because of that, each witness for reachability-checking from one
458 // of the sufficiently-large lengths can be transformed to an
459 // equally-valid witness from any other length, so we only have
460 // to check slice lengths from the "minimal sufficiently-large length"
461 // and below.
462 //
463 // Note that the fact that there is a *single* `sₘ` for each `m`
464 // not depending on the specific pattern in `P` is important: if
465 // you look at the pair of patterns
466 // `[true, ..]`
467 // `[.., false]`
468 // Then any slice of length ≥1 that matches one of these two
469 // patterns can be be trivially turned to a slice of any
470 // other length ≥1 that matches them and vice-versa - for
471 // but the slice from length 2 `[false, true]` that matches neither
472 // of these patterns can't be turned to a slice from length 1 that
473 // matches neither of these patterns, so we have to consider
474 // slices from length 2 there.
475 //
476 // Now, to see that that length exists and find it, observe that slice
477 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
478 // "variable-length" patterns (`[_, .., _]`).
479 //
480 // For fixed-length patterns, all slices with lengths *longer* than
481 // the pattern's length have the same outcome (of not matching), so
482 // as long as `L` is greater than the pattern's length we can pick
483 // any `sₘ` from that length and get the same result.
484 //
485 // For variable-length patterns, the situation is more complicated,
486 // because as seen above the precise value of `sₘ` matters.
487 //
488 // However, for each variable-length pattern `p` with a prefix of length
489 // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last
490 // `slâ‚š` elements are examined.
491 //
492 // Therefore, as long as `L` is positive (to avoid concerns about empty
493 // types), all elements after the maximum prefix length and before
494 // the maximum suffix length are not examined by any variable-length
495 // pattern, and therefore can be added/removed without affecting
496 // them - creating equivalent patterns from any sufficiently-large
497 // length.
498 //
499 // Of course, if fixed-length patterns exist, we must be sure
500 // that our length is large enough to miss them all, so
501 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
502 //
503 // for example, with the above pair of patterns, all elements
504 // but the first and last can be added/removed, so any
505 // witness of length ≥2 (say, `[false, false, true]`) can be
506 // turned to a witness from any other length ≥2.
507
508 let mut max_prefix_len = 0;
509 let mut max_suffix_len = 0;
510 let mut max_fixed_len = 0;
511
512 for row in patterns {
513 match *row.kind {
514 PatternKind::Constant { value: ConstVal::ByteStr(ref data) } => {
515 max_fixed_len = cmp::max(max_fixed_len, data.len());
516 }
517 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
518 let fixed_len = prefix.len() + suffix.len();
519 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
520 }
521 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
522 max_prefix_len = cmp::max(max_prefix_len, prefix.len());
523 max_suffix_len = cmp::max(max_suffix_len, suffix.len());
524 }
525 _ => {}
526 }
527 }
528
529 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
530}
531
c30ab7b3 532/// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
32a655c1
SL
533/// The algorithm from the paper has been modified to correctly handle empty
534/// types. The changes are:
535/// (0) We don't exit early if the pattern matrix has zero rows. We just
536/// continue to recurse over columns.
537/// (1) all_constructors will only return constructors that are statically
538/// possible. eg. it will only return Ok for Result<T, !>
c30ab7b3
SL
539///
540/// Whether a vector `v` of patterns is 'useful' in relation to a set of such
541/// vectors `m` is defined as there being a set of inputs that will match `v`
542/// but not any of the sets in `m`.
543///
544/// This is used both for reachability checking (if a pattern isn't useful in
545/// relation to preceding patterns, it is not reachable) and exhaustiveness
546/// checking (if a wildcard pattern is useful in relation to a matrix, the
547/// matrix isn't exhaustive).
32a655c1
SL
548pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
549 matrix: &Matrix<'p, 'tcx>,
550 v: &[&'p Pattern<'tcx>],
c30ab7b3 551 witness: WitnessPreference)
32a655c1 552 -> Usefulness<'tcx> {
c30ab7b3
SL
553 let &Matrix(ref rows) = matrix;
554 debug!("is_useful({:?}, {:?})", matrix, v);
c30ab7b3 555
32a655c1
SL
556 // The base case. We are pattern-matching on () and the return value is
557 // based on whether our matrix has a row or not.
558 // NOTE: This could potentially be optimized by checking rows.is_empty()
559 // first and then, if v is non-empty, the return value is based on whether
560 // the type of the tuple we're checking is inhabited or not.
561 if v.is_empty() {
562 return if rows.is_empty() {
563 match witness {
564 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
565 LeaveOutWitness => Useful,
566 }
567 } else {
568 NotUseful
569 }
570 };
476ff2be 571
32a655c1 572 assert!(rows.iter().all(|r| r.len() == v.len()));
476ff2be 573
c30ab7b3
SL
574 let pcx = PatternContext {
575 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
576 .unwrap_or(v[0].ty),
476ff2be 577 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
c30ab7b3
SL
578 };
579
580 debug!("is_useful_expand_first_col: pcx={:?}, expanding {:?}", pcx, v[0]);
581
582 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
583 debug!("is_useful - expanding constructors: {:?}", constructors);
584 constructors.into_iter().map(|c|
585 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
32a655c1 586 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
c30ab7b3
SL
587 } else {
588 debug!("is_useful - expanding wildcard");
32a655c1
SL
589
590 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
591 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
592 }).collect();
593 debug!("used_ctors = {:?}", used_ctors);
594 let all_ctors = all_constructors(cx, pcx);
595 debug!("all_ctors = {:?}", all_ctors);
596 let missing_ctors: Vec<Constructor> = all_ctors.iter().filter(|c| {
597 !used_ctors.contains(*c)
598 }).cloned().collect();
599
600 // `missing_ctors` is the set of constructors from the same type as the
601 // first column of `matrix` that are matched only by wildcard patterns
602 // from the first column.
603 //
604 // Therefore, if there is some pattern that is unmatched by `matrix`,
605 // it will still be unmatched if the first constructor is replaced by
606 // any of the constructors in `missing_ctors`
607 //
608 // However, if our scrutinee is *privately* an empty enum, we
609 // must treat it as though it had an "unknown" constructor (in
610 // that case, all other patterns obviously can't be variants)
611 // to avoid exposing its emptyness. See the `match_privately_empty`
612 // test for details.
613 //
614 // FIXME: currently the only way I know of something can
615 // be a privately-empty enum is when the never_type
616 // feature flag is not present, so this is only
617 // needed for that case.
618
619 let is_privately_empty =
620 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
621 debug!("missing_ctors={:?} is_privately_empty={:?}", missing_ctors,
622 is_privately_empty);
623 if missing_ctors.is_empty() && !is_privately_empty {
624 all_ctors.into_iter().map(|c| {
c30ab7b3 625 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
32a655c1 626 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
c30ab7b3
SL
627 } else {
628 let matrix = rows.iter().filter_map(|r| {
629 if r[0].is_wildcard() {
630 Some(r[1..].to_vec())
631 } else {
632 None
633 }
634 }).collect();
635 match is_useful(cx, &matrix, &v[1..], witness) {
636 UsefulWithWitness(pats) => {
637 let cx = &*cx;
32a655c1
SL
638 let new_witnesses = if used_ctors.is_empty() {
639 // All constructors are unused. Add wild patterns
640 // rather than each individual constructor
641 pats.into_iter().map(|mut witness| {
642 witness.0.push(Pattern {
643 ty: pcx.ty,
644 span: DUMMY_SP,
645 kind: box PatternKind::Wild,
646 });
647 witness
648 }).collect()
649 } else {
650 pats.into_iter().flat_map(|witness| {
651 missing_ctors.iter().map(move |ctor| {
652 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
653 })
654 }).collect()
655 };
656 UsefulWithWitness(new_witnesses)
c30ab7b3
SL
657 }
658 result => result
659 }
660 }
661 }
662}
663
32a655c1 664fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
c30ab7b3 665 cx: &mut MatchCheckCtxt<'a, 'tcx>,
32a655c1
SL
666 &Matrix(ref m): &Matrix<'p, 'tcx>,
667 v: &[&'p Pattern<'tcx>],
8bb4bdeb 668 ctor: Constructor<'tcx>,
c30ab7b3 669 lty: Ty<'tcx>,
32a655c1 670 witness: WitnessPreference) -> Usefulness<'tcx>
c30ab7b3 671{
32a655c1
SL
672 debug!("is_useful_specialized({:?}, {:?}, {:?})", v, ctor, lty);
673 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
674 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
675 Pattern {
676 ty: ty,
677 span: DUMMY_SP,
678 kind: box PatternKind::Wild,
679 }
680 }).collect();
681 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
c30ab7b3 682 let matrix = Matrix(m.iter().flat_map(|r| {
cc61c64b 683 specialize(cx, &r, &ctor, &wild_patterns)
c30ab7b3 684 }).collect());
32a655c1 685 match specialize(cx, v, &ctor, &wild_patterns) {
cc61c64b 686 Some(v) => match is_useful(cx, &matrix, &v, witness) {
c30ab7b3
SL
687 UsefulWithWitness(witnesses) => UsefulWithWitness(
688 witnesses.into_iter()
689 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
690 .collect()
691 ),
692 result => result
693 },
694 None => NotUseful
695 }
696}
697
698/// Determines the constructors that the given pattern can be specialized to.
699///
700/// In most cases, there's only one constructor that a specific pattern
701/// represents, such as a specific enum variant or a specific literal value.
702/// Slice patterns, however, can match slices of different lengths. For instance,
703/// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
704///
705/// Returns None in case of a catch-all, which can't be specialized.
8bb4bdeb
XL
706fn pat_constructors<'tcx>(_cx: &mut MatchCheckCtxt,
707 pat: &Pattern<'tcx>,
708 pcx: PatternContext)
709 -> Option<Vec<Constructor<'tcx>>>
c30ab7b3
SL
710{
711 match *pat.kind {
712 PatternKind::Binding { .. } | PatternKind::Wild =>
713 None,
714 PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
715 Some(vec![Single]),
716 PatternKind::Variant { adt_def, variant_index, .. } =>
717 Some(vec![Variant(adt_def.variants[variant_index].did)]),
718 PatternKind::Constant { ref value } =>
719 Some(vec![ConstantValue(value.clone())]),
32a655c1
SL
720 PatternKind::Range { ref lo, ref hi, ref end } =>
721 Some(vec![ConstantRange(lo.clone(), hi.clone(), end.clone())]),
c30ab7b3
SL
722 PatternKind::Array { .. } => match pcx.ty.sty {
723 ty::TyArray(_, length) => Some(vec![Slice(length)]),
724 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
725 },
726 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
727 let pat_len = prefix.len() + suffix.len();
728 if slice.is_some() {
729 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
730 } else {
731 Some(vec![Slice(pat_len)])
732 }
733 }
734 }
735}
736
737/// This computes the arity of a constructor. The arity of a constructor
738/// is how many subpattern patterns of that constructor should be expanded to.
739///
740/// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
741/// A struct pattern's arity is the number of fields it contains, etc.
742fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
743 debug!("constructor_arity({:?}, {:?})", ctor, ty);
744 match ty.sty {
8bb4bdeb 745 ty::TyTuple(ref fs, _) => fs.len(),
c30ab7b3
SL
746 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
747 Slice(length) => length,
748 ConstantValue(_) => 0,
749 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
750 },
751 ty::TyRef(..) => 1,
752 ty::TyAdt(adt, _) => {
32a655c1 753 adt.variants[ctor.variant_index_for_adt(adt)].fields.len()
c30ab7b3
SL
754 }
755 _ => 0
756 }
757}
758
32a655c1
SL
759/// This computes the types of the sub patterns that a constructor should be
760/// expanded to.
761///
762/// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
763fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
764 ctor: &Constructor,
765 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
766{
767 debug!("constructor_sub_pattern_tys({:?}, {:?})", ctor, ty);
768 match ty.sty {
8bb4bdeb 769 ty::TyTuple(ref fs, _) => fs.into_iter().map(|t| *t).collect(),
32a655c1
SL
770 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
771 Slice(length) => repeat(ty).take(length).collect(),
772 ConstantValue(_) => vec![],
773 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
774 },
775 ty::TyRef(_, ref ty_and_mut) => vec![ty_and_mut.ty],
776 ty::TyAdt(adt, substs) => {
041b39d2
XL
777 if adt.is_box() {
778 // Use T as the sub pattern type of Box<T>.
779 vec![substs[0].as_type().unwrap()]
780 } else {
781 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
782 let is_visible = adt.is_enum()
783 || field.vis.is_accessible_from(cx.module, cx.tcx);
784 if is_visible {
785 field.ty(cx.tcx, substs)
786 } else {
787 // Treat all non-visible fields as nil. They
788 // can't appear in any other pattern from
789 // this match (because they are private),
790 // so their type does not matter - but
791 // we don't want to know they are
792 // uninhabited.
793 cx.tcx.mk_nil()
794 }
795 }).collect()
796 }
32a655c1
SL
797 }
798 _ => vec![],
799 }
800}
801
c30ab7b3
SL
802fn slice_pat_covered_by_constructor(_tcx: TyCtxt, _span: Span,
803 ctor: &Constructor,
804 prefix: &[Pattern],
805 slice: &Option<Pattern>,
806 suffix: &[Pattern])
807 -> Result<bool, ErrorReported> {
808 let data = match *ctor {
809 ConstantValue(ConstVal::ByteStr(ref data)) => data,
810 _ => bug!()
811 };
812
813 let pat_len = prefix.len() + suffix.len();
814 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
815 return Ok(false);
816 }
817
818 for (ch, pat) in
819 data[..prefix.len()].iter().zip(prefix).chain(
820 data[data.len()-suffix.len()..].iter().zip(suffix))
821 {
822 match pat.kind {
823 box PatternKind::Constant { ref value } => match *value {
824 ConstVal::Integral(ConstInt::U8(u)) => {
825 if u != *ch {
826 return Ok(false);
827 }
828 },
829 _ => span_bug!(pat.span, "bad const u8 {:?}", value)
830 },
831 _ => {}
832 }
833 }
834
835 Ok(true)
836}
837
041b39d2 838fn constructor_covered_by_range(tcx: TyCtxt, span: Span,
c30ab7b3 839 ctor: &Constructor,
32a655c1
SL
840 from: &ConstVal, to: &ConstVal,
841 end: RangeEnd)
c30ab7b3 842 -> Result<bool, ErrorReported> {
32a655c1
SL
843 let cmp_from = |c_from| Ok(compare_const_vals(tcx, span, c_from, from)? != Ordering::Less);
844 let cmp_to = |c_to| compare_const_vals(tcx, span, c_to, to);
845 match *ctor {
846 ConstantValue(ref value) => {
847 let to = cmp_to(value)?;
041b39d2
XL
848 let end = (to == Ordering::Less) ||
849 (end == RangeEnd::Included && to == Ordering::Equal);
32a655c1
SL
850 Ok(cmp_from(value)? && end)
851 },
852 ConstantRange(ref from, ref to, RangeEnd::Included) => {
853 let to = cmp_to(to)?;
041b39d2
XL
854 let end = (to == Ordering::Less) ||
855 (end == RangeEnd::Included && to == Ordering::Equal);
32a655c1
SL
856 Ok(cmp_from(from)? && end)
857 },
858 ConstantRange(ref from, ref to, RangeEnd::Excluded) => {
859 let to = cmp_to(to)?;
860 let end = (to == Ordering::Less) ||
861 (end == RangeEnd::Excluded && to == Ordering::Equal);
862 Ok(cmp_from(from)? && end)
863 }
864 Single => Ok(true),
865 _ => bug!(),
866 }
c30ab7b3
SL
867}
868
32a655c1
SL
869fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
870 subpatterns: &'p [FieldPattern<'tcx>],
871 wild_patterns: &[&'p Pattern<'tcx>])
872 -> Vec<&'p Pattern<'tcx>>
c30ab7b3 873{
32a655c1 874 let mut result = wild_patterns.to_owned();
c30ab7b3
SL
875
876 for subpat in subpatterns {
877 result[subpat.field.index()] = &subpat.pattern;
878 }
879
32a655c1 880 debug!("patterns_for_variant({:?}, {:?}) = {:?}", subpatterns, wild_patterns, result);
c30ab7b3
SL
881 result
882}
883
884/// This is the main specialization step. It expands the first pattern in the given row
885/// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
886/// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
887///
888/// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
889/// different patterns.
890/// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
891/// fields filled with wild patterns.
32a655c1 892fn specialize<'p, 'a: 'p, 'tcx: 'a>(
c30ab7b3 893 cx: &mut MatchCheckCtxt<'a, 'tcx>,
32a655c1
SL
894 r: &[&'p Pattern<'tcx>],
895 constructor: &Constructor,
896 wild_patterns: &[&'p Pattern<'tcx>])
897 -> Option<Vec<&'p Pattern<'tcx>>>
c30ab7b3 898{
32a655c1 899 let pat = &r[0];
c30ab7b3
SL
900
901 let head: Option<Vec<&Pattern>> = match *pat.kind {
32a655c1
SL
902 PatternKind::Binding { .. } | PatternKind::Wild => {
903 Some(wild_patterns.to_owned())
904 },
c30ab7b3 905
32a655c1 906 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
c30ab7b3
SL
907 let ref variant = adt_def.variants[variant_index];
908 if *constructor == Variant(variant.did) {
32a655c1 909 Some(patterns_for_variant(subpatterns, wild_patterns))
c30ab7b3
SL
910 } else {
911 None
912 }
913 }
914
32a655c1
SL
915 PatternKind::Leaf { ref subpatterns } => {
916 Some(patterns_for_variant(subpatterns, wild_patterns))
917 }
918 PatternKind::Deref { ref subpattern } => {
919 Some(vec![subpattern])
920 }
c30ab7b3
SL
921
922 PatternKind::Constant { ref value } => {
923 match *constructor {
924 Slice(..) => match *value {
925 ConstVal::ByteStr(ref data) => {
32a655c1 926 if wild_patterns.len() == data.len() {
c30ab7b3
SL
927 Some(cx.lower_byte_str_pattern(pat))
928 } else {
929 None
930 }
931 }
932 _ => span_bug!(pat.span,
933 "unexpected const-val {:?} with ctor {:?}", value, constructor)
934 },
935 _ => {
041b39d2 936 match constructor_covered_by_range(
32a655c1 937 cx.tcx, pat.span, constructor, value, value, RangeEnd::Included
c30ab7b3
SL
938 ) {
939 Ok(true) => Some(vec![]),
940 Ok(false) => None,
941 Err(ErrorReported) => None,
942 }
943 }
944 }
945 }
946
32a655c1 947 PatternKind::Range { ref lo, ref hi, ref end } => {
041b39d2 948 match constructor_covered_by_range(
32a655c1 949 cx.tcx, pat.span, constructor, lo, hi, end.clone()
c30ab7b3
SL
950 ) {
951 Ok(true) => Some(vec![]),
952 Ok(false) => None,
953 Err(ErrorReported) => None,
954 }
955 }
956
957 PatternKind::Array { ref prefix, ref slice, ref suffix } |
958 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
959 match *constructor {
960 Slice(..) => {
961 let pat_len = prefix.len() + suffix.len();
32a655c1 962 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
c30ab7b3
SL
963 if slice_count == 0 || slice.is_some() {
964 Some(
965 prefix.iter().chain(
32a655c1
SL
966 wild_patterns.iter().map(|p| *p)
967 .skip(prefix.len())
968 .take(slice_count)
969 .chain(
c30ab7b3
SL
970 suffix.iter()
971 )).collect())
972 } else {
973 None
974 }
975 } else {
976 None
977 }
978 }
979 ConstantValue(..) => {
980 match slice_pat_covered_by_constructor(
981 cx.tcx, pat.span, constructor, prefix, slice, suffix
982 ) {
983 Ok(true) => Some(vec![]),
984 Ok(false) => None,
985 Err(ErrorReported) => None
986 }
987 }
988 _ => span_bug!(pat.span,
989 "unexpected ctor {:?} for slice pat", constructor)
990 }
991 }
992 };
32a655c1 993 debug!("specialize({:?}, {:?}) = {:?}", r[0], wild_patterns, head);
c30ab7b3
SL
994
995 head.map(|mut head| {
32a655c1 996 head.extend_from_slice(&r[1 ..]);
c30ab7b3
SL
997 head
998 })
999}