]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_match.rs
Rollup merge of #28788 - tsurai:master, r=bluss
[rust.git] / src / librustc / middle / check_match.rs
1 // Copyright 2012-2014 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
11 pub use self::Constructor::*;
12 use self::Usefulness::*;
13 use self::WitnessPreference::*;
14
15 use middle::const_eval::{compare_const_vals, ConstVal};
16 use middle::const_eval::{eval_const_expr, eval_const_expr_partial};
17 use middle::const_eval::{const_expr_to_pat, lookup_const_by_id};
18 use middle::const_eval::EvalHint::ExprTypeChecked;
19 use middle::def::*;
20 use middle::def_id::{DefId};
21 use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Init};
22 use middle::expr_use_visitor::{JustWrite, LoanCause, MutateMode};
23 use middle::expr_use_visitor::WriteAndRead;
24 use middle::expr_use_visitor as euv;
25 use middle::infer;
26 use middle::mem_categorization::{cmt};
27 use middle::pat_util::*;
28 use middle::ty::*;
29 use middle::ty;
30 use std::cmp::Ordering;
31 use std::fmt;
32 use std::iter::{range_inclusive, FromIterator, IntoIterator, repeat};
33 use std::slice;
34
35 use rustc_front::hir;
36 use rustc_front::hir::Pat;
37 use rustc_front::visit::{self, Visitor, FnKind};
38 use rustc_front::util as front_util;
39
40 use syntax::ast::{self, DUMMY_NODE_ID, NodeId};
41 use syntax::ast_util;
42 use syntax::codemap::{Span, Spanned, DUMMY_SP};
43 use rustc_front::fold::{Folder, noop_fold_pat};
44 use rustc_front::print::pprust::pat_to_string;
45 use syntax::ptr::P;
46 use util::nodemap::FnvHashMap;
47
48 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
49     id: DUMMY_NODE_ID,
50     node: hir::PatWild(hir::PatWildSingle),
51     span: DUMMY_SP
52 };
53
54 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
55
56 /// Pretty-printer for matrices of patterns, example:
57 /// ++++++++++++++++++++++++++
58 /// + _     + []             +
59 /// ++++++++++++++++++++++++++
60 /// + true  + [First]        +
61 /// ++++++++++++++++++++++++++
62 /// + true  + [Second(true)] +
63 /// ++++++++++++++++++++++++++
64 /// + false + [_]            +
65 /// ++++++++++++++++++++++++++
66 /// + _     + [_, _, ..tail] +
67 /// ++++++++++++++++++++++++++
68 impl<'a> fmt::Debug for Matrix<'a> {
69     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70         try!(write!(f, "\n"));
71
72         let &Matrix(ref m) = self;
73         let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
74             row.iter()
75                .map(|&pat| pat_to_string(&*pat))
76                .collect::<Vec<String>>()
77         }).collect();
78
79         let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
80         assert!(m.iter().all(|row| row.len() == column_count));
81         let column_widths: Vec<usize> = (0..column_count).map(|col| {
82             pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
83         }).collect();
84
85         let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
86         let br = repeat('+').take(total_width).collect::<String>();
87         try!(write!(f, "{}\n", br));
88         for row in pretty_printed_matrix {
89             try!(write!(f, "+"));
90             for (column, pat_str) in row.into_iter().enumerate() {
91                 try!(write!(f, " "));
92                 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
93                 try!(write!(f, " +"));
94             }
95             try!(write!(f, "\n"));
96             try!(write!(f, "{}\n", br));
97         }
98         Ok(())
99     }
100 }
101
102 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
103     fn from_iter<T: IntoIterator<Item=Vec<&'a Pat>>>(iter: T) -> Matrix<'a> {
104         Matrix(iter.into_iter().collect())
105     }
106 }
107
108 //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
109 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
110     pub tcx: &'a ty::ctxt<'tcx>,
111     pub param_env: ParameterEnvironment<'a, 'tcx>,
112 }
113
114 #[derive(Clone, PartialEq)]
115 pub enum Constructor {
116     /// The constructor of all patterns that don't vary by constructor,
117     /// e.g. struct patterns and fixed-length arrays.
118     Single,
119     /// Enum variants.
120     Variant(DefId),
121     /// Literal values.
122     ConstantValue(ConstVal),
123     /// Ranges of literal values (2..5).
124     ConstantRange(ConstVal, ConstVal),
125     /// Array patterns of length n.
126     Slice(usize),
127     /// Array patterns with a subslice.
128     SliceWithSubslice(usize, usize)
129 }
130
131 #[derive(Clone, PartialEq)]
132 enum Usefulness {
133     Useful,
134     UsefulWithWitness(Vec<P<Pat>>),
135     NotUseful
136 }
137
138 #[derive(Copy, Clone)]
139 enum WitnessPreference {
140     ConstructWitness,
141     LeaveOutWitness
142 }
143
144 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
145     fn visit_expr(&mut self, ex: &hir::Expr) {
146         check_expr(self, ex);
147     }
148     fn visit_local(&mut self, l: &hir::Local) {
149         check_local(self, l);
150     }
151     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
152                 b: &'v hir::Block, s: Span, n: NodeId) {
153         check_fn(self, fk, fd, b, s, n);
154     }
155 }
156
157 pub fn check_crate(tcx: &ty::ctxt) {
158     visit::walk_crate(&mut MatchCheckCtxt {
159         tcx: tcx,
160         param_env: tcx.empty_parameter_environment(),
161     }, tcx.map.krate());
162     tcx.sess.abort_if_errors();
163 }
164
165 fn check_expr(cx: &mut MatchCheckCtxt, ex: &hir::Expr) {
166     visit::walk_expr(cx, ex);
167     match ex.node {
168         hir::ExprMatch(ref scrut, ref arms, source) => {
169             for arm in arms {
170                 // First, check legality of move bindings.
171                 check_legality_of_move_bindings(cx,
172                                                 arm.guard.is_some(),
173                                                 &arm.pats);
174
175                 // Second, if there is a guard on each arm, make sure it isn't
176                 // assigning or borrowing anything mutably.
177                 match arm.guard {
178                     Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
179                     None => {}
180                 }
181             }
182
183             let mut static_inliner = StaticInliner::new(cx.tcx, None);
184             let inlined_arms = arms.iter().map(|arm| {
185                 (arm.pats.iter().map(|pat| {
186                     static_inliner.fold_pat((*pat).clone())
187                 }).collect(), arm.guard.as_ref().map(|e| &**e))
188             }).collect::<Vec<(Vec<P<Pat>>, Option<&hir::Expr>)>>();
189
190             // Bail out early if inlining failed.
191             if static_inliner.failed {
192                 return;
193             }
194
195             for pat in inlined_arms
196                 .iter()
197                 .flat_map(|&(ref pats, _)| pats) {
198                 // Third, check legality of move bindings.
199                 check_legality_of_bindings_in_at_patterns(cx, &**pat);
200
201                 // Fourth, check if there are any references to NaN that we should warn about.
202                 check_for_static_nan(cx, &**pat);
203
204                 // Fifth, check if for any of the patterns that match an enumerated type
205                 // are bindings with the same name as one of the variants of said type.
206                 check_for_bindings_named_the_same_as_variants(cx, &**pat);
207             }
208
209             // Fourth, check for unreachable arms.
210             check_arms(cx, &inlined_arms[..], source);
211
212             // Finally, check if the whole match expression is exhaustive.
213             // Check for empty enum, because is_useful only works on inhabited types.
214             let pat_ty = cx.tcx.node_id_to_type(scrut.id);
215             if inlined_arms.is_empty() {
216                 if !pat_ty.is_empty(cx.tcx) {
217                     // We know the type is inhabited, so this must be wrong
218                     span_err!(cx.tcx.sess, ex.span, E0002,
219                               "non-exhaustive patterns: type {} is non-empty",
220                               pat_ty);
221                     span_help!(cx.tcx.sess, ex.span,
222                         "Please ensure that all possible cases are being handled; \
223                          possibly adding wildcards or more match arms.");
224                 }
225                 // If the type *is* empty, it's vacuously exhaustive
226                 return;
227             }
228
229             let matrix: Matrix = inlined_arms
230                 .iter()
231                 .filter(|&&(_, guard)| guard.is_none())
232                 .flat_map(|arm| &arm.0)
233                 .map(|pat| vec![&**pat])
234                 .collect();
235             check_exhaustive(cx, ex.span, &matrix, source);
236         },
237         _ => ()
238     }
239 }
240
241 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
242     front_util::walk_pat(pat, |p| {
243         match p.node {
244             hir::PatIdent(hir::BindByValue(hir::MutImmutable), ident, None) => {
245                 let pat_ty = cx.tcx.pat_ty(p);
246                 if let ty::TyEnum(edef, _) = pat_ty.sty {
247                     let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
248                     if let Some(DefLocal(..)) = def {
249                         if edef.variants.iter().any(|variant|
250                             variant.name == ident.node.name
251                                 && variant.kind() == VariantKind::Unit
252                         ) {
253                             span_warn!(cx.tcx.sess, p.span, E0170,
254                                 "pattern binding `{}` is named the same as one \
255                                  of the variants of the type `{}`",
256                                 ident.node, pat_ty);
257                             fileline_help!(cx.tcx.sess, p.span,
258                                 "if you meant to match on a variant, \
259                                  consider making the path in the pattern qualified: `{}::{}`",
260                                 pat_ty, ident.node);
261                         }
262                     }
263                 }
264             }
265             _ => ()
266         }
267         true
268     });
269 }
270
271 // Check that we do not match against a static NaN (#6804)
272 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
273     front_util::walk_pat(pat, |p| {
274         if let hir::PatLit(ref expr) = p.node {
275             match eval_const_expr_partial(cx.tcx, &**expr, ExprTypeChecked) {
276                 Ok(ConstVal::Float(f)) if f.is_nan() => {
277                     span_warn!(cx.tcx.sess, p.span, E0003,
278                                "unmatchable NaN in pattern, \
279                                 use the is_nan method in a guard instead");
280                 }
281                 Ok(_) => {}
282
283                 Err(err) => {
284                     let subspan = p.span.lo <= err.span.lo && err.span.hi <= p.span.hi;
285                     span_err!(cx.tcx.sess, err.span, E0471,
286                               "constant evaluation error: {}",
287                               err.description());
288                     if !subspan {
289                         cx.tcx.sess.span_note(p.span,
290                                               "in pattern here")
291                     }
292                 }
293             }
294         }
295         true
296     });
297 }
298
299 // Check for unreachable patterns
300 fn check_arms(cx: &MatchCheckCtxt,
301               arms: &[(Vec<P<Pat>>, Option<&hir::Expr>)],
302               source: hir::MatchSource) {
303     let mut seen = Matrix(vec![]);
304     let mut printed_if_let_err = false;
305     for &(ref pats, guard) in arms {
306         for pat in pats {
307             let v = vec![&**pat];
308
309             match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
310                 NotUseful => {
311                     match source {
312                         hir::MatchSource::IfLetDesugar { .. } => {
313                             if printed_if_let_err {
314                                 // we already printed an irrefutable if-let pattern error.
315                                 // We don't want two, that's just confusing.
316                             } else {
317                                 // find the first arm pattern so we can use its span
318                                 let &(ref first_arm_pats, _) = &arms[0];
319                                 let first_pat = &first_arm_pats[0];
320                                 let span = first_pat.span;
321                                 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
322                                 printed_if_let_err = true;
323                             }
324                         },
325
326                         hir::MatchSource::WhileLetDesugar => {
327                             // find the first arm pattern so we can use its span
328                             let &(ref first_arm_pats, _) = &arms[0];
329                             let first_pat = &first_arm_pats[0];
330                             let span = first_pat.span;
331                             span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
332                         },
333
334                         hir::MatchSource::ForLoopDesugar => {
335                             // this is a bug, because on `match iter.next()` we cover
336                             // `Some(<head>)` and `None`. It's impossible to have an unreachable
337                             // pattern
338                             // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
339                             cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
340                         },
341
342                         hir::MatchSource::Normal => {
343                             span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
344                         },
345                     }
346                 }
347                 Useful => (),
348                 UsefulWithWitness(_) => unreachable!()
349             }
350             if guard.is_none() {
351                 let Matrix(mut rows) = seen;
352                 rows.push(v);
353                 seen = Matrix(rows);
354             }
355         }
356     }
357 }
358
359 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
360     match p.node {
361         hir::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
362         _ => p
363     }
364 }
365
366 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: hir::MatchSource) {
367     match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
368         UsefulWithWitness(pats) => {
369             let witness = match &pats[..] {
370                 [ref witness] => &**witness,
371                 [] => DUMMY_WILD_PAT,
372                 _ => unreachable!()
373             };
374             match source {
375                 hir::MatchSource::ForLoopDesugar => {
376                     // `witness` has the form `Some(<head>)`, peel off the `Some`
377                     let witness = match witness.node {
378                         hir::PatEnum(_, Some(ref pats)) => match &pats[..] {
379                             [ref pat] => &**pat,
380                             _ => unreachable!(),
381                         },
382                         _ => unreachable!(),
383                     };
384
385                     span_err!(cx.tcx.sess, sp, E0297,
386                         "refutable pattern in `for` loop binding: \
387                                 `{}` not covered",
388                                 pat_to_string(witness));
389                 },
390                 _ => {
391                     span_err!(cx.tcx.sess, sp, E0004,
392                         "non-exhaustive patterns: `{}` not covered",
393                         pat_to_string(witness)
394                     );
395                 },
396             }
397         }
398         NotUseful => {
399             // This is good, wildcard pattern isn't reachable
400         },
401         _ => unreachable!()
402     }
403 }
404
405 fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> {
406     let node = match value {
407         &ConstVal::Bool(b) => ast::LitBool(b),
408         _ => unreachable!()
409     };
410     P(hir::Expr {
411         id: 0,
412         node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
413         span: DUMMY_SP
414     })
415 }
416
417 pub struct StaticInliner<'a, 'tcx: 'a> {
418     pub tcx: &'a ty::ctxt<'tcx>,
419     pub failed: bool,
420     pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
421 }
422
423 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
424     pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
425                    renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
426                    -> StaticInliner<'b, 'tcx> {
427         StaticInliner {
428             tcx: tcx,
429             failed: false,
430             renaming_map: renaming_map
431         }
432     }
433 }
434
435 struct RenamingRecorder<'map> {
436     substituted_node_id: NodeId,
437     origin_span: Span,
438     renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
439 }
440
441 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
442     fn visit_id(&mut self, node_id: NodeId) {
443         let key = (node_id, self.origin_span);
444         self.renaming_map.insert(key, self.substituted_node_id);
445     }
446 }
447
448 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
449     fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
450         return match pat.node {
451             hir::PatIdent(..) | hir::PatEnum(..) | hir::PatQPath(..) => {
452                 let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def());
453                 match def {
454                     Some(DefAssociatedConst(did)) |
455                     Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did, Some(pat.id)) {
456                         Some(const_expr) => {
457                             const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
458
459                                 if let Some(ref mut renaming_map) = self.renaming_map {
460                                     // Record any renamings we do here
461                                     record_renamings(const_expr, &pat, renaming_map);
462                                 }
463
464                                 new_pat
465                             })
466                         }
467                         None => {
468                             self.failed = true;
469                             span_err!(self.tcx.sess, pat.span, E0158,
470                                 "statics cannot be referenced in patterns");
471                             pat
472                         }
473                     },
474                     _ => noop_fold_pat(pat, self)
475                 }
476             }
477             _ => noop_fold_pat(pat, self)
478         };
479
480         fn record_renamings(const_expr: &hir::Expr,
481                             substituted_pat: &hir::Pat,
482                             renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
483             let mut renaming_recorder = RenamingRecorder {
484                 substituted_node_id: substituted_pat.id,
485                 origin_span: substituted_pat.span,
486                 renaming_map: renaming_map,
487             };
488
489             let mut id_visitor = front_util::IdVisitor {
490                 operation: &mut renaming_recorder,
491                 pass_through_items: true,
492                 visited_outermost: false,
493             };
494
495             id_visitor.visit_expr(const_expr);
496         }
497     }
498 }
499
500 /// Constructs a partial witness for a pattern given a list of
501 /// patterns expanded by the specialization step.
502 ///
503 /// When a pattern P is discovered to be useful, this function is used bottom-up
504 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
505 /// of values, V, where each value in that set is not covered by any previously
506 /// used patterns and is covered by the pattern P'. Examples:
507 ///
508 /// left_ty: tuple of 3 elements
509 /// pats: [10, 20, _]           => (10, 20, _)
510 ///
511 /// left_ty: struct X { a: (bool, &'static str), b: usize}
512 /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
513 fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
514                               pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> {
515     let pats_len = pats.len();
516     let mut pats = pats.into_iter().map(|p| P((*p).clone()));
517     let pat = match left_ty.sty {
518         ty::TyTuple(_) => hir::PatTup(pats.collect()),
519
520         ty::TyEnum(adt, _) | ty::TyStruct(adt, _)  => {
521             let v = adt.variant_of_ctor(ctor);
522             if let VariantKind::Dict = v.kind() {
523                 let field_pats: Vec<_> = v.fields.iter()
524                     .zip(pats)
525                     .filter(|&(_, ref pat)| pat.node != hir::PatWild(hir::PatWildSingle))
526                     .map(|(field, pat)| Spanned {
527                         span: DUMMY_SP,
528                         node: hir::FieldPat {
529                             name: field.name,
530                             pat: pat,
531                             is_shorthand: false,
532                         }
533                     }).collect();
534                 let has_more_fields = field_pats.len() < pats_len;
535                 hir::PatStruct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
536             } else {
537                 hir::PatEnum(def_to_path(cx.tcx, v.did), Some(pats.collect()))
538             }
539         }
540
541         ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
542             match ty.sty {
543                ty::TyArray(_, n) => match ctor {
544                     &Single => {
545                         assert_eq!(pats_len, n);
546                         hir::PatVec(pats.collect(), None, vec!())
547                     },
548                     _ => unreachable!()
549                 },
550                 ty::TySlice(_) => match ctor {
551                     &Slice(n) => {
552                         assert_eq!(pats_len, n);
553                         hir::PatVec(pats.collect(), None, vec!())
554                     },
555                     _ => unreachable!()
556                 },
557                 ty::TyStr => hir::PatWild(hir::PatWildSingle),
558
559                 _ => {
560                     assert_eq!(pats_len, 1);
561                     hir::PatRegion(pats.nth(0).unwrap(), mutbl)
562                 }
563             }
564         }
565
566         ty::TyArray(_, len) => {
567             assert_eq!(pats_len, len);
568             hir::PatVec(pats.collect(), None, vec![])
569         }
570
571         _ => {
572             match *ctor {
573                 ConstantValue(ref v) => hir::PatLit(const_val_to_expr(v)),
574                 _ => hir::PatWild(hir::PatWildSingle),
575             }
576         }
577     };
578
579     P(hir::Pat {
580         id: 0,
581         node: pat,
582         span: DUMMY_SP
583     })
584 }
585
586 impl<'tcx, 'container> ty::AdtDefData<'tcx, 'container> {
587     fn variant_of_ctor(&self,
588                        ctor: &Constructor)
589                        -> &VariantDefData<'tcx, 'container> {
590         match ctor {
591             &Variant(vid) => self.variant_with_id(vid),
592             _ => self.struct_variant()
593         }
594     }
595 }
596
597 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
598                        left_ty: Ty, max_slice_length: usize) -> Option<Constructor> {
599     let used_constructors: Vec<Constructor> = rows.iter()
600         .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
601         .collect();
602     all_constructors(cx, left_ty, max_slice_length)
603         .into_iter()
604         .find(|c| !used_constructors.contains(c))
605 }
606
607 /// This determines the set of all possible constructors of a pattern matching
608 /// values of type `left_ty`. For vectors, this would normally be an infinite set
609 /// but is instead bounded by the maximum fixed length of slice patterns in
610 /// the column of patterns being analyzed.
611 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
612                     max_slice_length: usize) -> Vec<Constructor> {
613     match left_ty.sty {
614         ty::TyBool =>
615             [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
616
617         ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
618             ty::TySlice(_) =>
619                 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
620             _ => vec![Single]
621         },
622
623         ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
624         _ => vec![Single]
625     }
626 }
627
628 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
629 //
630 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
631 // vectors `m` is defined as there being a set of inputs that will match `v`
632 // but not any of the sets in `m`.
633 //
634 // This is used both for reachability checking (if a pattern isn't useful in
635 // relation to preceding patterns, it is not reachable) and exhaustiveness
636 // checking (if a wildcard pattern is useful in relation to a matrix, the
637 // matrix isn't exhaustive).
638
639 // Note: is_useful doesn't work on empty types, as the paper notes.
640 // So it assumes that v is non-empty.
641 fn is_useful(cx: &MatchCheckCtxt,
642              matrix: &Matrix,
643              v: &[&Pat],
644              witness: WitnessPreference)
645              -> Usefulness {
646     let &Matrix(ref rows) = matrix;
647     debug!("{:?}", matrix);
648     if rows.is_empty() {
649         return match witness {
650             ConstructWitness => UsefulWithWitness(vec!()),
651             LeaveOutWitness => Useful
652         };
653     }
654     if rows[0].is_empty() {
655         return NotUseful;
656     }
657     assert!(rows.iter().all(|r| r.len() == v.len()));
658     let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
659         Some(r) => raw_pat(r[0]),
660         None if v.is_empty() => return NotUseful,
661         None => v[0]
662     };
663     let left_ty = if real_pat.id == DUMMY_NODE_ID {
664         cx.tcx.mk_nil()
665     } else {
666         let left_ty = cx.tcx.pat_ty(&*real_pat);
667
668         match real_pat.node {
669             hir::PatIdent(hir::BindByRef(..), _, _) => {
670                 left_ty.builtin_deref(false, NoPreference).unwrap().ty
671             }
672             _ => left_ty,
673         }
674     };
675
676     let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
677         hir::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
678         _ => None
679     }).max().map_or(0, |v| v + 1);
680
681     let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
682     if constructors.is_empty() {
683         match missing_constructor(cx, matrix, left_ty, max_slice_length) {
684             None => {
685                 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
686                     match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
687                         UsefulWithWitness(pats) => UsefulWithWitness({
688                             let arity = constructor_arity(cx, &c, left_ty);
689                             let mut result = {
690                                 let pat_slice = &pats[..];
691                                 let subpats: Vec<_> = (0..arity).map(|i| {
692                                     pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
693                                 }).collect();
694                                 vec![construct_witness(cx, &c, subpats, left_ty)]
695                             };
696                             result.extend(pats.into_iter().skip(arity));
697                             result
698                         }),
699                         result => result
700                     }
701                 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
702             },
703
704             Some(constructor) => {
705                 let matrix = rows.iter().filter_map(|r| {
706                     if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
707                         Some(r[1..].to_vec())
708                     } else {
709                         None
710                     }
711                 }).collect();
712                 match is_useful(cx, &matrix, &v[1..], witness) {
713                     UsefulWithWitness(pats) => {
714                         let arity = constructor_arity(cx, &constructor, left_ty);
715                         let wild_pats = vec![DUMMY_WILD_PAT; arity];
716                         let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
717                         let mut new_pats = vec![enum_pat];
718                         new_pats.extend(pats);
719                         UsefulWithWitness(new_pats)
720                     },
721                     result => result
722                 }
723             }
724         }
725     } else {
726         constructors.into_iter().map(|c|
727             is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
728         ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
729     }
730 }
731
732 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
733                          v: &[&Pat], ctor: Constructor, lty: Ty,
734                          witness: WitnessPreference) -> Usefulness {
735     let arity = constructor_arity(cx, &ctor, lty);
736     let matrix = Matrix(m.iter().filter_map(|r| {
737         specialize(cx, &r[..], &ctor, 0, arity)
738     }).collect());
739     match specialize(cx, v, &ctor, 0, arity) {
740         Some(v) => is_useful(cx, &matrix, &v[..], witness),
741         None => NotUseful
742     }
743 }
744
745 /// Determines the constructors that the given pattern can be specialized to.
746 ///
747 /// In most cases, there's only one constructor that a specific pattern
748 /// represents, such as a specific enum variant or a specific literal value.
749 /// Slice patterns, however, can match slices of different lengths. For instance,
750 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
751 ///
752 /// On the other hand, a wild pattern and an identifier pattern cannot be
753 /// specialized in any way.
754 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
755                     left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
756     let pat = raw_pat(p);
757     match pat.node {
758         hir::PatIdent(..) =>
759             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
760                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
761                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
762                                                     been rewritten"),
763                 Some(DefStruct(_)) => vec!(Single),
764                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
765                 _ => vec!()
766             },
767         hir::PatEnum(..) =>
768             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
769                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
770                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
771                                                     been rewritten"),
772                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
773                 _ => vec!(Single)
774             },
775         hir::PatQPath(..) =>
776             cx.tcx.sess.span_bug(pat.span, "const pattern should've \
777                                             been rewritten"),
778         hir::PatStruct(..) =>
779             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
780                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
781                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
782                                                     been rewritten"),
783                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
784                 _ => vec!(Single)
785             },
786         hir::PatLit(ref expr) =>
787             vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
788         hir::PatRange(ref lo, ref hi) =>
789             vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
790         hir::PatVec(ref before, ref slice, ref after) =>
791             match left_ty.sty {
792                 ty::TyArray(_, _) => vec!(Single),
793                 _                      => if slice.is_some() {
794                     range_inclusive(before.len() + after.len(), max_slice_length)
795                         .map(|length| Slice(length))
796                         .collect()
797                 } else {
798                     vec!(Slice(before.len() + after.len()))
799                 }
800             },
801         hir::PatBox(_) | hir::PatTup(_) | hir::PatRegion(..) =>
802             vec!(Single),
803         hir::PatWild(_) =>
804             vec!(),
805     }
806 }
807
808 /// This computes the arity of a constructor. The arity of a constructor
809 /// is how many subpattern patterns of that constructor should be expanded to.
810 ///
811 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
812 /// A struct pattern's arity is the number of fields it contains, etc.
813 pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
814     match ty.sty {
815         ty::TyTuple(ref fs) => fs.len(),
816         ty::TyBox(_) => 1,
817         ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
818             ty::TySlice(_) => match *ctor {
819                 Slice(length) => length,
820                 ConstantValue(_) => 0,
821                 _ => unreachable!()
822             },
823             ty::TyStr => 0,
824             _ => 1
825         },
826         ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
827             adt.variant_of_ctor(ctor).fields.len()
828         }
829         ty::TyArray(_, n) => n,
830         _ => 0
831     }
832 }
833
834 fn range_covered_by_constructor(ctor: &Constructor,
835                                 from: &ConstVal, to: &ConstVal) -> Option<bool> {
836     let (c_from, c_to) = match *ctor {
837         ConstantValue(ref value)        => (value, value),
838         ConstantRange(ref from, ref to) => (from, to),
839         Single                          => return Some(true),
840         _                               => unreachable!()
841     };
842     let cmp_from = compare_const_vals(c_from, from);
843     let cmp_to = compare_const_vals(c_to, to);
844     match (cmp_from, cmp_to) {
845         (Some(cmp_from), Some(cmp_to)) => {
846             Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
847         }
848         _ => None
849     }
850 }
851
852 /// This is the main specialization step. It expands the first pattern in the given row
853 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
854 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
855 ///
856 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
857 /// different patterns.
858 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
859 /// fields filled with wild patterns.
860 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
861                       constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
862     let &Pat {
863         id: pat_id, ref node, span: pat_span
864     } = raw_pat(r[col]);
865     let head: Option<Vec<&Pat>> = match *node {
866         hir::PatWild(_) =>
867             Some(vec![DUMMY_WILD_PAT; arity]),
868
869         hir::PatIdent(_, _, _) => {
870             let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
871             match opt_def {
872                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
873                     cx.tcx.sess.span_bug(pat_span, "const pattern should've \
874                                                     been rewritten"),
875                 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
876                     Some(vec!())
877                 } else {
878                     None
879                 },
880                 _ => Some(vec![DUMMY_WILD_PAT; arity])
881             }
882         }
883
884         hir::PatEnum(_, ref args) => {
885             let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
886             match def {
887                 DefConst(..) | DefAssociatedConst(..) =>
888                     cx.tcx.sess.span_bug(pat_span, "const pattern should've \
889                                                     been rewritten"),
890                 DefVariant(_, id, _) if *constructor != Variant(id) => None,
891                 DefVariant(..) | DefStruct(..) => {
892                     Some(match args {
893                         &Some(ref args) => args.iter().map(|p| &**p).collect(),
894                         &None => vec![DUMMY_WILD_PAT; arity],
895                     })
896                 }
897                 _ => None
898             }
899         }
900
901         hir::PatQPath(_, _) => {
902             cx.tcx.sess.span_bug(pat_span, "const pattern should've \
903                                             been rewritten")
904         }
905
906         hir::PatStruct(_, ref pattern_fields, _) => {
907             let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
908             let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
909             let variant = adt.variant_of_ctor(constructor);
910             let def_variant = adt.variant_of_def(def);
911             if variant.did == def_variant.did {
912                 Some(variant.fields.iter().map(|sf| {
913                     match pattern_fields.iter().find(|f| f.node.name == sf.name) {
914                         Some(ref f) => &*f.node.pat,
915                         _ => DUMMY_WILD_PAT
916                     }
917                 }).collect())
918             } else {
919                 None
920             }
921         }
922
923         hir::PatTup(ref args) =>
924             Some(args.iter().map(|p| &**p).collect()),
925
926         hir::PatBox(ref inner) | hir::PatRegion(ref inner, _) =>
927             Some(vec![&**inner]),
928
929         hir::PatLit(ref expr) => {
930             let expr_value = eval_const_expr(cx.tcx, &**expr);
931             match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
932                 Some(true) => Some(vec![]),
933                 Some(false) => None,
934                 None => {
935                     span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
936                     None
937                 }
938             }
939         }
940
941         hir::PatRange(ref from, ref to) => {
942             let from_value = eval_const_expr(cx.tcx, &**from);
943             let to_value = eval_const_expr(cx.tcx, &**to);
944             match range_covered_by_constructor(constructor, &from_value, &to_value) {
945                 Some(true) => Some(vec![]),
946                 Some(false) => None,
947                 None => {
948                     span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
949                     None
950                 }
951             }
952         }
953
954         hir::PatVec(ref before, ref slice, ref after) => {
955             match *constructor {
956                 // Fixed-length vectors.
957                 Single => {
958                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
959                     pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
960                     pats.extend(after.iter().map(|p| &**p));
961                     Some(pats)
962                 },
963                 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
964                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
965                     pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
966                     pats.extend(after.iter().map(|p| &**p));
967                     Some(pats)
968                 },
969                 Slice(length) if before.len() + after.len() == length => {
970                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
971                     pats.extend(after.iter().map(|p| &**p));
972                     Some(pats)
973                 },
974                 SliceWithSubslice(prefix, suffix)
975                     if before.len() == prefix
976                         && after.len() == suffix
977                         && slice.is_some() => {
978                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
979                     pats.extend(after.iter().map(|p| &**p));
980                     Some(pats)
981                 }
982                 _ => None
983             }
984         }
985     };
986     head.map(|mut head| {
987         head.push_all(&r[..col]);
988         head.push_all(&r[col + 1..]);
989         head
990     })
991 }
992
993 fn check_local(cx: &mut MatchCheckCtxt, loc: &hir::Local) {
994     visit::walk_local(cx, loc);
995
996     let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
997     check_irrefutable(cx, &pat, false);
998
999     // Check legality of move bindings and `@` patterns.
1000     check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1001     check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1002 }
1003
1004 fn check_fn(cx: &mut MatchCheckCtxt,
1005             kind: FnKind,
1006             decl: &hir::FnDecl,
1007             body: &hir::Block,
1008             sp: Span,
1009             fn_id: NodeId) {
1010     match kind {
1011         FnKind::Closure => {}
1012         _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1013     }
1014
1015     visit::walk_fn(cx, kind, decl, body, sp);
1016
1017     for input in &decl.inputs {
1018         check_irrefutable(cx, &input.pat, true);
1019         check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1020         check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1021     }
1022 }
1023
1024 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1025     let origin = if is_fn_arg {
1026         "function argument"
1027     } else {
1028         "local binding"
1029     };
1030
1031     is_refutable(cx, pat, |uncovered_pat| {
1032         span_err!(cx.tcx.sess, pat.span, E0005,
1033             "refutable pattern in {}: `{}` not covered",
1034             origin,
1035             pat_to_string(uncovered_pat),
1036         );
1037     });
1038 }
1039
1040 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1041     F: FnOnce(&Pat) -> A,
1042 {
1043     let pats = Matrix(vec!(vec!(pat)));
1044     match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1045         UsefulWithWitness(pats) => {
1046             assert_eq!(pats.len(), 1);
1047             Some(refutable(&*pats[0]))
1048         },
1049         NotUseful => None,
1050         Useful => unreachable!()
1051     }
1052 }
1053
1054 // Legality of move bindings checking
1055 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1056                                    has_guard: bool,
1057                                    pats: &[P<Pat>]) {
1058     let tcx = cx.tcx;
1059     let def_map = &tcx.def_map;
1060     let mut by_ref_span = None;
1061     for pat in pats {
1062         pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1063             match bm {
1064                 hir::BindByRef(_) => {
1065                     by_ref_span = Some(span);
1066                 }
1067                 hir::BindByValue(_) => {
1068                 }
1069             }
1070         })
1071     }
1072
1073     let check_move = |p: &Pat, sub: Option<&Pat>| {
1074         // check legality of moving out of the enum
1075
1076         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1077         if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1078             span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1079         } else if has_guard {
1080             span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1081         } else if by_ref_span.is_some() {
1082             span_err!(cx.tcx.sess, p.span, E0009,
1083                 "cannot bind by-move and by-ref in the same pattern");
1084             span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1085         }
1086     };
1087
1088     for pat in pats {
1089         front_util::walk_pat(&**pat, |p| {
1090             if pat_is_binding(def_map, &*p) {
1091                 match p.node {
1092                     hir::PatIdent(hir::BindByValue(_), _, ref sub) => {
1093                         let pat_ty = tcx.node_id_to_type(p.id);
1094                         //FIXME: (@jroesch) this code should be floated up as well
1095                         let infcx = infer::new_infer_ctxt(cx.tcx,
1096                                                           &cx.tcx.tables,
1097                                                           Some(cx.param_env.clone()),
1098                                                           false);
1099                         if infcx.type_moves_by_default(pat_ty, pat.span) {
1100                             check_move(p, sub.as_ref().map(|p| &**p));
1101                         }
1102                     }
1103                     hir::PatIdent(hir::BindByRef(_), _, _) => {
1104                     }
1105                     _ => {
1106                         cx.tcx.sess.span_bug(
1107                             p.span,
1108                             &format!("binding pattern {} is not an \
1109                                      identifier: {:?}",
1110                                     p.id,
1111                                     p.node));
1112                     }
1113                 }
1114             }
1115             true
1116         });
1117     }
1118 }
1119
1120 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1121 /// assign.
1122 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1123                                          guard: &hir::Expr) {
1124     let mut checker = MutationChecker {
1125         cx: cx,
1126     };
1127
1128     let infcx = infer::new_infer_ctxt(cx.tcx,
1129                                       &cx.tcx.tables,
1130                                       Some(checker.cx.param_env.clone()),
1131                                       false);
1132
1133     let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1134     visitor.walk_expr(guard);
1135 }
1136
1137 struct MutationChecker<'a, 'tcx: 'a> {
1138     cx: &'a MatchCheckCtxt<'a, 'tcx>,
1139 }
1140
1141 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1142     fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1143     fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1144     fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1145     fn borrow(&mut self,
1146               _: NodeId,
1147               span: Span,
1148               _: cmt,
1149               _: Region,
1150               kind: BorrowKind,
1151               _: LoanCause) {
1152         match kind {
1153             MutBorrow => {
1154                 span_err!(self.cx.tcx.sess, span, E0301,
1155                           "cannot mutably borrow in a pattern guard")
1156             }
1157             ImmBorrow | UniqueImmBorrow => {}
1158         }
1159     }
1160     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1161     fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1162         match mode {
1163             JustWrite | WriteAndRead => {
1164                 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1165             }
1166             Init => {}
1167         }
1168     }
1169 }
1170
1171 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1172 /// because of the way rvalues are handled in the borrow check. (See issue
1173 /// #14587.)
1174 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1175     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1176 }
1177
1178 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1179     cx: &'a MatchCheckCtxt<'b, 'tcx>,
1180     bindings_allowed: bool
1181 }
1182
1183 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1184     fn visit_pat(&mut self, pat: &Pat) {
1185         if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1186             span_err!(self.cx.tcx.sess, pat.span, E0303,
1187                                       "pattern bindings are not allowed \
1188                                        after an `@`");
1189         }
1190
1191         match pat.node {
1192             hir::PatIdent(_, _, Some(_)) => {
1193                 let bindings_were_allowed = self.bindings_allowed;
1194                 self.bindings_allowed = false;
1195                 visit::walk_pat(self, pat);
1196                 self.bindings_allowed = bindings_were_allowed;
1197             }
1198             _ => visit::walk_pat(self, pat),
1199         }
1200     }
1201 }