_match.rs 44.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use self::Constructor::*;
use self::Usefulness::*;
use self::WitnessPreference::*;

use rustc::middle::const_val::ConstVal;
16

17
use rustc_data_structures::fx::FxHashMap;
18 19
use rustc_data_structures::indexed_vec::Idx;

20 21
use super::{FieldPattern, Pattern, PatternKind};
use super::{PatternFoldable, PatternFolder, compare_const_vals};
22

23
use rustc::hir::def_id::DefId;
24
use rustc::hir::RangeEnd;
25
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
26

27
use rustc::mir::Field;
28 29 30 31
use rustc::util::common::ErrorReported;

use syntax_pos::{Span, DUMMY_SP};

32
use arena::TypedArena;
33

34
use std::cmp::{self, Ordering};
35 36
use std::fmt;
use std::iter::{FromIterator, IntoIterator, repeat};
37

38 39
pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
                                -> &'a Pattern<'tcx>
40
{
41
    cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
42 43
}

44 45 46 47
struct LiteralExpander;
impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
    fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
        match (&pat.ty.sty, &*pat.kind) {
48
            (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
49 50 51 52 53
                Pattern {
                    ty: pat.ty,
                    span: pat.span,
                    kind: box PatternKind::Deref {
                        subpattern: Pattern {
54
                            ty: rty,
55 56 57 58 59 60 61 62 63 64
                            span: pat.span,
                            kind: box PatternKind::Constant { value: value.clone() },
                        }
                    }
                }
            }
            (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
                s.fold_with(self)
            }
            _ => pat.super_fold_with(self)
65 66 67 68
        }
    }
}

69 70 71 72 73 74 75
impl<'tcx> Pattern<'tcx> {
    fn is_wildcard(&self) -> bool {
        match *self.kind {
            PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
                true,
            _ => false
        }
76 77 78
    }
}

79
pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
80 81 82 83 84 85

impl<'a, 'tcx> Matrix<'a, 'tcx> {
    pub fn empty() -> Self {
        Matrix(vec![])
    }

86
    pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        self.0.push(row)
    }
}

/// Pretty-printer for matrices of patterns, example:
/// ++++++++++++++++++++++++++
/// + _     + []             +
/// ++++++++++++++++++++++++++
/// + true  + [First]        +
/// ++++++++++++++++++++++++++
/// + true  + [Second(true)] +
/// ++++++++++++++++++++++++++
/// + false + [_]            +
/// ++++++++++++++++++++++++++
/// + _     + [_, _, ..tail] +
/// ++++++++++++++++++++++++++
impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "\n")?;

        let &Matrix(ref m) = self;
        let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
            row.iter().map(|pat| format!("{:?}", pat)).collect()
        }).collect();

        let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
        assert!(m.iter().all(|row| row.len() == column_count));
        let column_widths: Vec<usize> = (0..column_count).map(|col| {
            pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
        }).collect();

        let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
        let br = repeat('+').take(total_width).collect::<String>();
        write!(f, "{}\n", br)?;
        for row in pretty_printed_matrix {
            write!(f, "+")?;
            for (column, pat_str) in row.into_iter().enumerate() {
                write!(f, " ")?;
                write!(f, "{:1$}", pat_str, column_widths[column])?;
                write!(f, " +")?;
            }
            write!(f, "\n")?;
            write!(f, "{}\n", br)?;
        }
        Ok(())
    }
}

135 136
impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
    fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
137 138 139 140 141 142 143 144
    {
        Matrix(iter.into_iter().collect())
    }
}

//NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
    pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
A
Andrew Cann 已提交
145
    /// The module in which the match occurs. This is necessary for
146 147
    /// checking inhabited-ness of types because whether a type is (visibly)
    /// inhabited can depend on whether it was defined in the current module or
A
Andrew Cann 已提交
148 149 150 151
    /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
    /// outside it's module and should not be matchable with an empty match
    /// statement.
    pub module: DefId,
152
    pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
153
    pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
154 155 156 157 158
}

impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
    pub fn create_and_enter<F, R>(
        tcx: TyCtxt<'a, 'tcx, 'tcx>,
A
Andrew Cann 已提交
159
        module: DefId,
160 161 162 163 164 165
        f: F) -> R
        where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
    {
        let pattern_arena = TypedArena::new();

        f(MatchCheckCtxt {
166 167
            tcx,
            module,
168
            pattern_arena: &pattern_arena,
169
            byte_array_map: FxHashMap(),
170 171
        })
    }
172 173

    // convert a byte-string pattern to a list of u8 patterns.
174 175 176
    fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
            where 'a: 'p
    {
177 178 179 180
        let pattern_arena = &*self.pattern_arena;
        let tcx = self.tcx;
        self.byte_array_map.entry(pat).or_insert_with(|| {
            match pat.kind {
O
Oliver Schneider 已提交
181
                box PatternKind::Constant {
182
                    value: const_val
O
Oliver Schneider 已提交
183
                } => {
184 185 186 187 188 189
                    if let Some(ptr) = const_val.to_ptr() {
                        let is_array_ptr = const_val.ty
                            .builtin_deref(true)
                            .and_then(|t| t.ty.builtin_index())
                            .map_or(false, |t| t == tcx.types.u8);
                        assert!(is_array_ptr);
190
                        let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
191
                        assert_eq!(ptr.offset.bytes(), 0);
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
                        // FIXME: check length
                        alloc.bytes.iter().map(|b| {
                            &*pattern_arena.alloc(Pattern {
                                ty: tcx.types.u8,
                                span: pat.span,
                                kind: box PatternKind::Constant {
                                    value: ty::Const::from_bits(
                                        tcx,
                                        *b as u128,
                                        tcx.types.u8)
                                }
                            })
                        }).collect()
                    } else {
                        bug!("not a byte str: {:?}", const_val)
O
Oliver Schneider 已提交
207 208
                    }
                }
209 210 211 212
                _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
            }
        }).clone()
    }
213 214

    fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
A
Andrew Cann 已提交
215
        if self.tcx.features().exhaustive_patterns {
216
            self.tcx.is_ty_uninhabited_from(self.module, ty)
217 218 219 220 221
        } else {
            false
        }
    }

222 223 224 225 226 227 228 229 230 231 232 233 234 235
    fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
        match ty.sty {
            ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
            _ => false,
        }
    }

    fn is_local(&self, ty: Ty<'tcx>) -> bool {
        match ty.sty {
            ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
            _ => false,
        }
    }

236 237
    fn is_variant_uninhabited(&self,
                              variant: &'tcx ty::VariantDef,
238 239
                              substs: &'tcx ty::subst::Substs<'tcx>)
                              -> bool
240
    {
A
Andrew Cann 已提交
241
        if self.tcx.features().exhaustive_patterns {
242
            self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
243 244 245 246
        } else {
            false
        }
    }
247 248 249
}

#[derive(Clone, Debug, PartialEq)]
250
pub enum Constructor<'tcx> {
251 252 253 254 255 256
    /// The constructor of all patterns that don't vary by constructor,
    /// e.g. struct patterns and fixed-length arrays.
    Single,
    /// Enum variants.
    Variant(DefId),
    /// Literal values.
257
    ConstantValue(&'tcx ty::Const<'tcx>),
258
    /// Ranges of literal values (`2...5` and `2..5`).
259
    ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
260
    /// Array patterns of length n.
261
    Slice(u64),
262 263
}

264
impl<'tcx> Constructor<'tcx> {
265
    fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
266
        match self {
267
            &Variant(vid) => adt.variant_index_with_id(vid),
268
            &Single => {
269
                assert!(!adt.is_enum());
270
                0
271 272
            }
            _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
273 274 275 276
        }
    }
}

277 278
#[derive(Clone)]
pub enum Usefulness<'tcx> {
279
    Useful,
280
    UsefulWithWitness(Vec<Witness<'tcx>>),
281 282 283
    NotUseful
}

284 285 286 287 288 289 290 291 292
impl<'tcx> Usefulness<'tcx> {
    fn is_useful(&self) -> bool {
        match *self {
            NotUseful => false,
            _ => true
        }
    }
}

293 294 295 296 297 298
#[derive(Copy, Clone)]
pub enum WitnessPreference {
    ConstructWitness,
    LeaveOutWitness
}

299 300 301
#[derive(Copy, Clone, Debug)]
struct PatternContext<'tcx> {
    ty: Ty<'tcx>,
302
    max_slice_length: u64,
303 304 305
}

/// A stack of patterns in reverse order of construction
306 307
#[derive(Clone)]
pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
308

309 310
impl<'tcx> Witness<'tcx> {
    pub fn single_pattern(&self) -> &Pattern<'tcx> {
311 312 313
        assert_eq!(self.0.len(), 1);
        &self.0[0]
    }
314

315
    fn push_wild_constructor<'a>(
316 317
        mut self,
        cx: &MatchCheckCtxt<'a, 'tcx>,
318
        ctor: &Constructor<'tcx>,
319 320 321
        ty: Ty<'tcx>)
        -> Self
    {
A
Andrew Cann 已提交
322 323 324
        let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
        self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
            Pattern {
325
                ty,
A
Andrew Cann 已提交
326 327 328 329
                span: DUMMY_SP,
                kind: box PatternKind::Wild,
            }
        }));
330 331
        self.apply_constructor(cx, ctor, ty)
    }
332 333


334 335 336 337 338 339 340 341 342 343 344 345 346
    /// Constructs a partial witness for a pattern given a list of
    /// patterns expanded by the specialization step.
    ///
    /// When a pattern P is discovered to be useful, this function is used bottom-up
    /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
    /// of values, V, where each value in that set is not covered by any previously
    /// used patterns and is covered by the pattern P'. Examples:
    ///
    /// left_ty: tuple of 3 elements
    /// pats: [10, 20, _]           => (10, 20, _)
    ///
    /// left_ty: struct X { a: (bool, &'static str), b: usize}
    /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
347
    fn apply_constructor<'a>(
348 349
        mut self,
        cx: &MatchCheckCtxt<'a,'tcx>,
350
        ctor: &Constructor<'tcx>,
351 352 353 354 355
        ty: Ty<'tcx>)
        -> Self
    {
        let arity = constructor_arity(cx, ctor, ty);
        let pat = {
356 357
            let len = self.0.len() as u64;
            let mut pats = self.0.drain((len-arity) as usize..).rev();
358 359

            match ty.sty {
360 361 362 363 364 365
                ty::TyAdt(..) |
                ty::TyTuple(..) => {
                    let pats = pats.enumerate().map(|(i, p)| {
                        FieldPattern {
                            field: Field::new(i),
                            pattern: p
366
                        }
367 368
                    }).collect();

A
Andrew Cann 已提交
369
                    if let ty::TyAdt(adt, substs) = ty.sty {
370
                        if adt.is_enum() {
371 372
                            PatternKind::Variant {
                                adt_def: adt,
373
                                substs,
374 375 376 377 378
                                variant_index: ctor.variant_index_for_adt(adt),
                                subpatterns: pats
                            }
                        } else {
                            PatternKind::Leaf { subpatterns: pats }
379
                        }
380 381
                    } else {
                        PatternKind::Leaf { subpatterns: pats }
382 383 384
                    }
                }

385 386
                ty::TyRef(..) => {
                    PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
387 388 389
                }

                ty::TySlice(_) | ty::TyArray(..) => {
390 391 392 393 394
                    PatternKind::Slice {
                        prefix: pats.collect(),
                        slice: None,
                        suffix: vec![]
                    }
395
                }
396

397 398
                _ => {
                    match *ctor {
399
                        ConstantValue(value) => PatternKind::Constant { value },
400
                        _ => PatternKind::Wild,
401 402
                    }
                }
403
            }
404
        };
405

406
        self.0.push(Pattern {
407
            ty,
408 409 410
            span: DUMMY_SP,
            kind: Box::new(pat),
        });
411 412 413

        self
    }
414 415 416 417
}

/// This determines the set of all possible constructors of a pattern matching
/// values of type `left_ty`. For vectors, this would normally be an infinite set
418 419
/// but is instead bounded by the maximum fixed length of slice patterns in
/// the column of patterns being analyzed.
420 421 422 423 424
///
/// This intentionally does not list ConstantValue specializations for
/// non-booleans, because we currently assume that there is always a
/// "non-standard constant" that matches. See issue #12483.
///
425 426 427
/// We make sure to omit constructors that are statically impossible. eg for
/// Option<!> we do not include Some(_) in the returned list of constructors.
fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
428 429
                                  pcx: PatternContext<'tcx>)
                                  -> Vec<Constructor<'tcx>>
430
{
431
    debug!("all_constructors({:?})", pcx.ty);
432
    match pcx.ty.sty {
433 434
        ty::TyBool => {
            [true, false].iter().map(|&b| {
435
                ConstantValue(ty::Const::from_bool(cx.tcx, b))
436 437
            }).collect()
        }
438 439
        ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
            let len = len.unwrap_usize(cx.tcx);
440
            if len != 0 && cx.is_uninhabited(sub_ty) {
441
                vec![]
442
            } else {
443
                vec![Slice(len)]
444 445
            }
        }
446 447 448 449 450 451 452 453 454
        // Treat arrays of a constant but unknown length like slices.
        ty::TyArray(ref sub_ty, _) |
        ty::TySlice(ref sub_ty) => {
            if cx.is_uninhabited(sub_ty) {
                vec![Slice(0)]
            } else {
                (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
            }
        }
455
        ty::TyAdt(def, substs) if def.is_enum() => {
456 457 458 459
            def.variants.iter()
                .filter(|v| !cx.is_variant_uninhabited(v, substs))
                .map(|v| Variant(v.did))
                .collect()
460 461
        }
        _ => {
462
            if cx.is_uninhabited(pcx.ty) {
463 464 465 466 467
                vec![]
            } else {
                vec![Single]
            }
        }
468 469 470
    }
}

471
fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
O
Oliver Schneider 已提交
472
    cx: &mut MatchCheckCtxt<'a, 'tcx>,
473
    patterns: I) -> u64
474
    where I: Iterator<Item=&'p Pattern<'tcx>>
475 476 477 478 479
{
    // The exhaustiveness-checking paper does not include any details on
    // checking variable-length slice patterns. However, they are matched
    // by an infinite collection of fixed-length array patterns.
    //
A
Ariel Ben-Yehuda 已提交
480 481 482
    // Checking the infinite set directly would take an infinite amount
    // of time. However, it turns out that for each finite set of
    // patterns `P`, all sufficiently large array lengths are equivalent:
483
    //
A
Ariel Ben-Yehuda 已提交
484 485 486 487
    // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
    // to exactly the subset `Pₜ` of `P` can be transformed to a slice
    // `sₘ` for each sufficiently-large length `m` that applies to exactly
    // the same subset of `P`.
488
    //
A
Ariel Ben-Yehuda 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    // Because of that, each witness for reachability-checking from one
    // of the sufficiently-large lengths can be transformed to an
    // equally-valid witness from any other length, so we only have
    // to check slice lengths from the "minimal sufficiently-large length"
    // and below.
    //
    // Note that the fact that there is a *single* `sₘ` for each `m`
    // not depending on the specific pattern in `P` is important: if
    // you look at the pair of patterns
    //     `[true, ..]`
    //     `[.., false]`
    // Then any slice of length ≥1 that matches one of these two
    // patterns can be  be trivially turned to a slice of any
    // other length ≥1 that matches them and vice-versa - for
    // but the slice from length 2 `[false, true]` that matches neither
    // of these patterns can't be turned to a slice from length 1 that
    // matches neither of these patterns, so we have to consider
    // slices from length 2 there.
    //
    // Now, to see that that length exists and find it, observe that slice
    // patterns are either "fixed-length" patterns (`[_, _, _]`) or
    // "variable-length" patterns (`[_, .., _]`).
    //
    // For fixed-length patterns, all slices with lengths *longer* than
    // the pattern's length have the same outcome (of not matching), so
    // as long as `L` is greater than the pattern's length we can pick
    // any `sₘ` from that length and get the same result.
    //
    // For variable-length patterns, the situation is more complicated,
    // because as seen above the precise value of `sₘ` matters.
    //
    // However, for each variable-length pattern `p` with a prefix of length
    // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
    // `slₚ` elements are examined.
    //
    // Therefore, as long as `L` is positive (to avoid concerns about empty
    // types), all elements after the maximum prefix length and before
    // the maximum suffix length are not examined by any variable-length
    // pattern, and therefore can be added/removed without affecting
    // them - creating equivalent patterns from any sufficiently-large
    // length.
    //
    // Of course, if fixed-length patterns exist, we must be sure
    // that our length is large enough to miss them all, so
    // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
    //
    // for example, with the above pair of patterns, all elements
    // but the first and last can be added/removed, so any
    // witness of length ≥2 (say, `[false, false, true]`) can be
    // turned to a witness from any other length ≥2.
539 540 541 542 543 544

    let mut max_prefix_len = 0;
    let mut max_suffix_len = 0;
    let mut max_fixed_len = 0;

    for row in patterns {
A
Ariel Ben-Yehuda 已提交
545
        match *row.kind {
O
Oliver Schneider 已提交
546
            PatternKind::Constant {
547 548 549
                value: const_val @ &ty::Const {
                    val: ConstVal::Value(..),
                    ..
O
Oliver Schneider 已提交
550 551
                }
            } => {
552 553 554 555 556 557
                if let Some(ptr) = const_val.to_ptr() {
                    let is_array_ptr = const_val.ty
                        .builtin_deref(true)
                        .and_then(|t| t.ty.builtin_index())
                        .map_or(false, |t| t == cx.tcx.types.u8);
                    if is_array_ptr {
558
                        let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
559 560
                        max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
                    }
O
Oliver Schneider 已提交
561 562
                }
            }
563
            PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
564
                let fixed_len = prefix.len() as u64 + suffix.len() as u64;
565 566 567
                max_fixed_len = cmp::max(max_fixed_len, fixed_len);
            }
            PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
568 569
                max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
                max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
570 571 572 573 574 575 576 577
            }
            _ => {}
        }
    }

    cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
}

578
/// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
579 580 581 582 583 584
/// The algorithm from the paper has been modified to correctly handle empty
/// types. The changes are:
///   (0) We don't exit early if the pattern matrix has zero rows. We just
///       continue to recurse over columns.
///   (1) all_constructors will only return constructors that are statically
///       possible. eg. it will only return Ok for Result<T, !>
585
///
586
/// This finds whether a (row) vector `v` of patterns is 'useful' in relation
A
Ariel Ben-Yehuda 已提交
587 588
/// to a set of such vectors `m` - this is defined as there being a set of
/// inputs that will match `v` but not any of the sets in `m`.
589 590 591 592 593 594
///
/// All the patterns at each column of the `matrix ++ v` matrix must
/// have the same type, except that wildcard (PatternKind::Wild) patterns
/// with type TyErr are also allowed, even if the "type of the column"
/// is not TyErr. That is used to represent private fields, as using their
/// real type would assert that they are inhabited.
595 596 597 598 599
///
/// This is used both for reachability checking (if a pattern isn't useful in
/// relation to preceding patterns, it is not reachable) and exhaustiveness
/// checking (if a wildcard pattern is useful in relation to a matrix, the
/// matrix isn't exhaustive).
600
pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
601 602 603 604
                                       matrix: &Matrix<'p, 'tcx>,
                                       v: &[&'p Pattern<'tcx>],
                                       witness: WitnessPreference)
                                       -> Usefulness<'tcx> {
605
    let &Matrix(ref rows) = matrix;
O
Oliver Schneider 已提交
606
    debug!("is_useful({:#?}, {:#?})", matrix, v);
607

608 609 610 611 612 613 614 615 616 617 618
    // The base case. We are pattern-matching on () and the return value is
    // based on whether our matrix has a row or not.
    // NOTE: This could potentially be optimized by checking rows.is_empty()
    // first and then, if v is non-empty, the return value is based on whether
    // the type of the tuple we're checking is inhabited or not.
    if v.is_empty() {
        return if rows.is_empty() {
            match witness {
                ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
                LeaveOutWitness => Useful,
            }
A
Andrew Cann 已提交
619
        } else {
620 621 622 623
            NotUseful
        }
    };

624
    assert!(rows.iter().all(|r| r.len() == v.len()));
625

626
    let pcx = PatternContext {
A
Ariel Ben-Yehuda 已提交
627 628 629 630 631
        // TyErr is used to represent the type of wildcard patterns matching
        // against inaccessible (private) fields of structs, so that we won't
        // be able to observe whether the types of the struct's fields are
        // inhabited.
        //
632
        // If the field is truly inaccessible, then all the patterns
A
Ariel Ben-Yehuda 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645
        // matching against it must be wildcard patterns, so its type
        // does not matter.
        //
        // However, if we are matching against non-wildcard patterns, we
        // need to know the real type of the field so we can specialize
        // against it. This primarily occurs through constants - they
        // can include contents for fields that are inaccessible at the
        // location of the match. In that case, the field's type is
        // inhabited - by the constant - so we can just use it.
        //
        // FIXME: this might lead to "unstable" behavior with macro hygiene
        // introducing uninhabited patterns for inaccessible fields. We
        // need to figure out how to model that.
646 647
        ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
            .unwrap_or(v[0].ty),
A
Ariel Ben-Yehuda 已提交
648
        max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
649 650
    };

O
Oliver Schneider 已提交
651
    debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
652

653
    if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
O
Oliver Schneider 已提交
654
        debug!("is_useful - expanding constructors: {:#?}", constructors);
655 656
        constructors.into_iter().map(|c|
            is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
657
        ).find(|result| result.is_useful()).unwrap_or(NotUseful)
658 659
    } else {
        debug!("is_useful - expanding wildcard");
660 661 662 663

        let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
            pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
        }).collect();
O
Oliver Schneider 已提交
664
        debug!("used_ctors = {:#?}", used_ctors);
665
        let all_ctors = all_constructors(cx, pcx);
O
Oliver Schneider 已提交
666
        debug!("all_ctors = {:#?}", all_ctors);
667 668 669 670 671 672 673 674 675 676 677
        let missing_ctors: Vec<Constructor> = all_ctors.iter().filter(|c| {
            !used_ctors.contains(*c)
        }).cloned().collect();

        // `missing_ctors` is the set of constructors from the same type as the
        // first column of `matrix` that are matched only by wildcard patterns
        // from the first column.
        //
        // Therefore, if there is some pattern that is unmatched by `matrix`,
        // it will still be unmatched if the first constructor is replaced by
        // any of the constructors in `missing_ctors`
678 679 680 681 682 683 684 685
        //
        // However, if our scrutinee is *privately* an empty enum, we
        // must treat it as though it had an "unknown" constructor (in
        // that case, all other patterns obviously can't be variants)
        // to avoid exposing its emptyness. See the `match_privately_empty`
        // test for details.
        //
        // FIXME: currently the only way I know of something can
A
Andrew Cann 已提交
686
        // be a privately-empty enum is when the exhaustive_patterns
687 688 689 690 691
        // feature flag is not present, so this is only
        // needed for that case.

        let is_privately_empty =
            all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
692 693
        let is_declared_nonexhaustive =
            cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
O
Oliver Schneider 已提交
694
        debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
695 696 697 698 699 700 701
               missing_ctors, is_privately_empty, is_declared_nonexhaustive);

        // For privately empty and non-exhaustive enums, we work as if there were an "extra"
        // `_` constructor for the type, so we can never match over all constructors.
        let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;

        if missing_ctors.is_empty() && !is_non_exhaustive {
702
            all_ctors.into_iter().map(|c| {
703
                is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
704
            }).find(|result| result.is_useful()).unwrap_or(NotUseful)
705 706
        } else {
            let matrix = rows.iter().filter_map(|r| {
707 708 709 710
                if r[0].is_wildcard() {
                    Some(r[1..].to_vec())
                } else {
                    None
711 712 713 714
                }
            }).collect();
            match is_useful(cx, &matrix, &v[1..], witness) {
                UsefulWithWitness(pats) => {
715
                    let cx = &*cx;
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
                    // In this case, there's at least one "free"
                    // constructor that is only matched against by
                    // wildcard patterns.
                    //
                    // There are 2 ways we can report a witness here.
                    // Commonly, we can report all the "free"
                    // constructors as witnesses, e.g. if we have:
                    //
                    // ```
                    //     enum Direction { N, S, E, W }
                    //     let Direction::N = ...;
                    // ```
                    //
                    // we can report 3 witnesses: `S`, `E`, and `W`.
                    //
                    // However, there are 2 cases where we don't want
                    // to do this and instead report a single `_` witness:
                    //
                    // 1) If the user is matching against a non-exhaustive
                    // enum, there is no point in enumerating all possible
                    // variants, because the user can't actually match
                    // against them himself, e.g. in an example like:
                    // ```
                    //     let err: io::ErrorKind = ...;
                    //     match err {
                    //         io::ErrorKind::NotFound => {},
                    //     }
                    // ```
                    // we don't want to show every possible IO error,
                    // but instead have `_` as the witness (this is
                    // actually *required* if the user specified *all*
                    // IO errors, but is probably what we want in every
                    // case).
                    //
                    // 2) If the user didn't actually specify a constructor
                    // in this arm, e.g. in
                    // ```
                    //     let x: (Direction, Direction, bool) = ...;
                    //     let (_, _, false) = x;
                    // ```
                    // we don't want to show all 16 possible witnesses
                    // `(<direction-1>, <direction-2>, true)` - we are
                    // satisfied with `(_, _, true)`. In this case,
                    // `used_ctors` is empty.
                    let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
761 762 763
                        // All constructors are unused. Add wild patterns
                        // rather than each individual constructor
                        pats.into_iter().map(|mut witness| {
A
Andrew Cann 已提交
764 765
                            witness.0.push(Pattern {
                                ty: pcx.ty,
766
                                span: DUMMY_SP,
A
Andrew Cann 已提交
767 768
                                kind: box PatternKind::Wild,
                            });
769 770 771 772 773 774 775 776 777 778
                            witness
                        }).collect()
                    } else {
                        pats.into_iter().flat_map(|witness| {
                            missing_ctors.iter().map(move |ctor| {
                                witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
                            })
                        }).collect()
                    };
                    UsefulWithWitness(new_witnesses)
779
                }
780 781 782 783 784 785
                result => result
            }
        }
    }
}

786
fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
787
    cx: &mut MatchCheckCtxt<'a, 'tcx>,
788 789
    &Matrix(ref m): &Matrix<'p, 'tcx>,
    v: &[&'p Pattern<'tcx>],
790
    ctor: Constructor<'tcx>,
791
    lty: Ty<'tcx>,
792
    witness: WitnessPreference) -> Usefulness<'tcx>
793
{
O
Oliver Schneider 已提交
794
    debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
795 796 797
    let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
    let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
        Pattern {
798
            ty,
799 800 801 802 803
            span: DUMMY_SP,
            kind: box PatternKind::Wild,
        }
    }).collect();
    let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
804
    let matrix = Matrix(m.iter().flat_map(|r| {
805
        specialize(cx, &r, &ctor, &wild_patterns)
806
    }).collect());
807
    match specialize(cx, v, &ctor, &wild_patterns) {
808
        Some(v) => match is_useful(cx, &matrix, &v, witness) {
809 810 811 812 813 814 815
            UsefulWithWitness(witnesses) => UsefulWithWitness(
                witnesses.into_iter()
                    .map(|witness| witness.apply_constructor(cx, &ctor, lty))
                    .collect()
            ),
            result => result
        },
816 817 818 819 820 821 822 823 824 825 826
        None => NotUseful
    }
}

/// Determines the constructors that the given pattern can be specialized to.
///
/// In most cases, there's only one constructor that a specific pattern
/// represents, such as a specific enum variant or a specific literal value.
/// Slice patterns, however, can match slices of different lengths. For instance,
/// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
///
827
/// Returns None in case of a catch-all, which can't be specialized.
828
fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
829 830 831
                          pat: &Pattern<'tcx>,
                          pcx: PatternContext)
                          -> Option<Vec<Constructor<'tcx>>>
832
{
833 834
    match *pat.kind {
        PatternKind::Binding { .. } | PatternKind::Wild =>
835
            None,
836
        PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
837 838 839
            Some(vec![Single]),
        PatternKind::Variant { adt_def, variant_index, .. } =>
            Some(vec![Variant(adt_def.variants[variant_index].did)]),
840 841 842 843
        PatternKind::Constant { value } =>
            Some(vec![ConstantValue(value)]),
        PatternKind::Range { lo, hi, end } =>
            Some(vec![ConstantRange(lo, hi, end)]),
844
        PatternKind::Array { .. } => match pcx.ty.sty {
845
            ty::TyArray(_, length) => Some(vec![
846
                Slice(length.unwrap_usize(cx.tcx))
847
            ]),
848 849
            _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
        },
850
        PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
851
            let pat_len = prefix.len() as u64 + suffix.len() as u64;
852 853 854 855 856 857
            if slice.is_some() {
                Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
            } else {
                Some(vec![Slice(pat_len)])
            }
        }
858 859 860 861 862 863 864 865
    }
}

/// This computes the arity of a constructor. The arity of a constructor
/// is how many subpattern patterns of that constructor should be expanded to.
///
/// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
/// A struct pattern's arity is the number of fields it contains, etc.
866
fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
O
Oliver Schneider 已提交
867
    debug!("constructor_arity({:#?}, {:?})", ctor, ty);
868
    match ty.sty {
A
Andrew Cann 已提交
869
        ty::TyTuple(ref fs) => fs.len() as u64,
870
        ty::TySlice(..) | ty::TyArray(..) => match *ctor {
871
            Slice(length) => length,
872
            ConstantValue(_) => 0,
873 874 875 876
            _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
        },
        ty::TyRef(..) => 1,
        ty::TyAdt(adt, _) => {
877
            adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
878 879 880 881 882
        }
        _ => 0
    }
}

883 884 885 886 887 888 889 890
/// This computes the types of the sub patterns that a constructor should be
/// expanded to.
///
/// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
                                             ctor: &Constructor,
                                             ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
{
O
Oliver Schneider 已提交
891
    debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
892
    match ty.sty {
A
Andrew Cann 已提交
893
        ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
894
        ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
895
            Slice(length) => (0..length).map(|_| ty).collect(),
896 897 898
            ConstantValue(_) => vec![],
            _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
        },
899
        ty::TyRef(_, rty, _) => vec![rty],
900
        ty::TyAdt(adt, substs) => {
901 902
            if adt.is_box() {
                // Use T as the sub pattern type of Box<T>.
V
varkor 已提交
903
                vec![substs.type_at(0)]
904 905 906 907 908 909 910
            } else {
                adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
                    let is_visible = adt.is_enum()
                        || field.vis.is_accessible_from(cx.module, cx.tcx);
                    if is_visible {
                        field.ty(cx.tcx, substs)
                    } else {
911
                        // Treat all non-visible fields as TyErr. They
912 913 914 915 916
                        // can't appear in any other pattern from
                        // this match (because they are private),
                        // so their type does not matter - but
                        // we don't want to know they are
                        // uninhabited.
917
                        cx.tcx.types.err
918 919 920
                    }
                }).collect()
            }
921 922 923 924 925
        }
        _ => vec![],
    }
}

926 927 928 929 930 931 932 933
fn slice_pat_covered_by_constructor<'tcx>(
    tcx: TyCtxt<'_, 'tcx, '_>,
    _span: Span,
    ctor: &Constructor,
    prefix: &[Pattern<'tcx>],
    slice: &Option<Pattern<'tcx>>,
    suffix: &[Pattern<'tcx>]
) -> Result<bool, ErrorReported> {
O
Oliver Schneider 已提交
934
    let data: &[u8] = match *ctor {
935 936 937 938 939 940 941
        ConstantValue(const_val @ &ty::Const { val: ConstVal::Value(..), .. }) => {
            if let Some(ptr) = const_val.to_ptr() {
                let is_array_ptr = const_val.ty
                    .builtin_deref(true)
                    .and_then(|t| t.ty.builtin_index())
                    .map_or(false, |t| t == tcx.types.u8);
                assert!(is_array_ptr);
942
                tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
943 944 945
            } else {
                bug!()
            }
O
Oliver Schneider 已提交
946
        }
947 948 949 950 951 952 953 954 955 956 957 958 959
        _ => bug!()
    };

    let pat_len = prefix.len() + suffix.len();
    if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
        return Ok(false);
    }

    for (ch, pat) in
        data[..prefix.len()].iter().zip(prefix).chain(
            data[data.len()-suffix.len()..].iter().zip(suffix))
    {
        match pat.kind {
960
            box PatternKind::Constant { value } => {
961
                let b = value.unwrap_bits(tcx, pat.ty);
962 963 964
                assert_eq!(b as u8 as u128, b);
                if b as u8 != *ch {
                    return Ok(false);
O
Oliver Schneider 已提交
965
                }
966
            }
967 968 969 970 971 972 973
            _ => {}
        }
    }

    Ok(true)
}

974 975
fn constructor_covered_by_range<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
976 977
    ctor: &Constructor<'tcx>,
    from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
978 979 980
    end: RangeEnd,
    ty: Ty<'tcx>,
) -> Result<bool, ErrorReported> {
O
Oliver Schneider 已提交
981
    trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
982
    let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty)
O
Oliver Schneider 已提交
983
        .map(|res| res != Ordering::Less);
984
    let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty);
O
Oliver Schneider 已提交
985 986 987 988 989 990 991 992
    macro_rules! some_or_ok {
        ($e:expr) => {
            match $e {
                Some(to) => to,
                None => return Ok(false), // not char or int
            }
        };
    }
993
    match *ctor {
994
        ConstantValue(value) => {
995
            let to = some_or_ok!(cmp_to(value));
996 997
            let end = (to == Ordering::Less) ||
                      (end == RangeEnd::Included && to == Ordering::Equal);
998
            Ok(some_or_ok!(cmp_from(value)) && end)
999
        },
1000
        ConstantRange(from, to, RangeEnd::Included) => {
1001
            let to = some_or_ok!(cmp_to(to));
1002 1003
            let end = (to == Ordering::Less) ||
                      (end == RangeEnd::Included && to == Ordering::Equal);
1004
            Ok(some_or_ok!(cmp_from(from)) && end)
1005
        },
1006
        ConstantRange(from, to, RangeEnd::Excluded) => {
1007
            let to = some_or_ok!(cmp_to(to));
1008 1009
            let end = (to == Ordering::Less) ||
                      (end == RangeEnd::Excluded && to == Ordering::Equal);
1010
            Ok(some_or_ok!(cmp_from(from)) && end)
1011 1012 1013 1014
        }
        Single => Ok(true),
        _ => bug!(),
    }
1015 1016
}

1017 1018 1019 1020
fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
    subpatterns: &'p [FieldPattern<'tcx>],
    wild_patterns: &[&'p Pattern<'tcx>])
    -> Vec<&'p Pattern<'tcx>>
1021
{
1022
    let mut result = wild_patterns.to_owned();
1023 1024 1025

    for subpat in subpatterns {
        result[subpat.field.index()] = &subpat.pattern;
1026
    }
1027

O
Oliver Schneider 已提交
1028
    debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1029
    result
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
}

/// This is the main specialization step. It expands the first pattern in the given row
/// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
/// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
///
/// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
/// different patterns.
/// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
/// fields filled with wild patterns.
1040
fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1041
    cx: &mut MatchCheckCtxt<'a, 'tcx>,
1042
    r: &[&'p Pattern<'tcx>],
O
Oliver Schneider 已提交
1043
    constructor: &Constructor<'tcx>,
1044 1045
    wild_patterns: &[&'p Pattern<'tcx>])
    -> Option<Vec<&'p Pattern<'tcx>>>
1046
{
1047
    let pat = &r[0];
1048

1049
    let head: Option<Vec<&Pattern>> = match *pat.kind {
1050 1051 1052
        PatternKind::Binding { .. } | PatternKind::Wild => {
            Some(wild_patterns.to_owned())
        },
1053

1054
        PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1055 1056
            let ref variant = adt_def.variants[variant_index];
            if *constructor == Variant(variant.did) {
1057
                Some(patterns_for_variant(subpatterns, wild_patterns))
1058 1059 1060 1061 1062
            } else {
                None
            }
        }

1063 1064 1065 1066 1067 1068
        PatternKind::Leaf { ref subpatterns } => {
            Some(patterns_for_variant(subpatterns, wild_patterns))
        }
        PatternKind::Deref { ref subpattern } => {
            Some(vec![subpattern])
        }
1069

1070
        PatternKind::Constant { value } => {
1071
            match *constructor {
1072 1073
                Slice(..) => {
                    if let Some(ptr) = value.to_ptr() {
O
Oliver Schneider 已提交
1074
                        let is_array_ptr = value.ty
O
Oliver Schneider 已提交
1075
                            .builtin_deref(true)
O
Oliver Schneider 已提交
1076 1077 1078 1079
                            .and_then(|t| t.ty.builtin_index())
                            .map_or(false, |t| t == cx.tcx.types.u8);
                        assert!(is_array_ptr);
                        let data_len = cx.tcx
1080 1081 1082
                            .alloc_map
                            .lock()
                            .unwrap_memory(ptr.alloc_id)
O
Oliver Schneider 已提交
1083 1084 1085 1086 1087 1088 1089
                            .bytes
                            .len();
                        if wild_patterns.len() == data_len {
                            Some(cx.lower_byte_str_pattern(pat))
                        } else {
                            None
                        }
1090 1091
                    } else {
                        span_bug!(pat.span,
1092
                        "unexpected const-val {:?} with ctor {:?}", value, constructor)
1093
                    }
1094 1095
                },
                _ => {
1096
                    match constructor_covered_by_range(
1097
                        cx.tcx,
1098
                        constructor, value, value, RangeEnd::Included,
O
Oliver Schneider 已提交
1099
                        value.ty,
1100 1101 1102 1103 1104 1105
                            ) {
                        Ok(true) => Some(vec![]),
                        Ok(false) => None,
                        Err(ErrorReported) => None,
                    }
                }
1106 1107 1108
            }
        }

1109
        PatternKind::Range { lo, hi, ref end } => {
1110
            match constructor_covered_by_range(
1111
                cx.tcx,
1112
                constructor, lo, hi, end.clone(), lo.ty,
1113 1114 1115 1116 1117 1118 1119
            ) {
                Ok(true) => Some(vec![]),
                Ok(false) => None,
                Err(ErrorReported) => None,
            }
        }

1120
        PatternKind::Array { ref prefix, ref slice, ref suffix } |
1121
        PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1122 1123 1124
            match *constructor {
                Slice(..) => {
                    let pat_len = prefix.len() + suffix.len();
1125
                    if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1126 1127 1128
                        if slice_count == 0 || slice.is_some() {
                            Some(
                                prefix.iter().chain(
1129 1130 1131 1132
                                wild_patterns.iter().map(|p| *p)
                                                    .skip(prefix.len())
                                                    .take(slice_count)
                                                    .chain(
1133 1134 1135 1136 1137 1138 1139 1140
                                suffix.iter()
                            )).collect())
                        } else {
                            None
                        }
                    } else {
                        None
                    }
1141
                }
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
                ConstantValue(..) => {
                    match slice_pat_covered_by_constructor(
                        cx.tcx, pat.span, constructor, prefix, slice, suffix
                            ) {
                        Ok(true) => Some(vec![]),
                        Ok(false) => None,
                        Err(ErrorReported) => None
                    }
                }
                _ => span_bug!(pat.span,
                    "unexpected ctor {:?} for slice pat", constructor)
1153 1154 1155
            }
        }
    };
O
Oliver Schneider 已提交
1156
    debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1157 1158

    head.map(|mut head| {
1159
        head.extend_from_slice(&r[1 ..]);
1160 1161 1162
        head
    })
}