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