]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_match.rs
Auto merge of #26848 - oli-obk:const_fn_const_eval, r=pnkfelix
[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::{FromIterator, IntoIterator, repeat};
33
34 use rustc_front::hir;
35 use rustc_front::hir::Pat;
36 use rustc_front::visit::{self, Visitor, FnKind};
37 use rustc_front::util as front_util;
38 use rustc_back::slice;
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, None) {
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                     span_err!(cx.tcx.sess, err.span, E0471,
285                               "constant evaluation error: {}",
286                               err.description());
287                     if !p.span.contains(err.span) {
288                         cx.tcx.sess.span_note(p.span,
289                                               "in pattern here")
290                     }
291                 }
292             }
293         }
294         true
295     });
296 }
297
298 // Check for unreachable patterns
299 fn check_arms(cx: &MatchCheckCtxt,
300               arms: &[(Vec<P<Pat>>, Option<&hir::Expr>)],
301               source: hir::MatchSource) {
302     let mut seen = Matrix(vec![]);
303     let mut printed_if_let_err = false;
304     for &(ref pats, guard) in arms {
305         for pat in pats {
306             let v = vec![&**pat];
307
308             match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
309                 NotUseful => {
310                     match source {
311                         hir::MatchSource::IfLetDesugar { .. } => {
312                             if printed_if_let_err {
313                                 // we already printed an irrefutable if-let pattern error.
314                                 // We don't want two, that's just confusing.
315                             } else {
316                                 // find the first arm pattern so we can use its span
317                                 let &(ref first_arm_pats, _) = &arms[0];
318                                 let first_pat = &first_arm_pats[0];
319                                 let span = first_pat.span;
320                                 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
321                                 printed_if_let_err = true;
322                             }
323                         },
324
325                         hir::MatchSource::WhileLetDesugar => {
326                             // find the first arm pattern so we can use its span
327                             let &(ref first_arm_pats, _) = &arms[0];
328                             let first_pat = &first_arm_pats[0];
329                             let span = first_pat.span;
330                             span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
331                         },
332
333                         hir::MatchSource::ForLoopDesugar => {
334                             // this is a bug, because on `match iter.next()` we cover
335                             // `Some(<head>)` and `None`. It's impossible to have an unreachable
336                             // pattern
337                             // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
338                             cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
339                         },
340
341                         hir::MatchSource::Normal => {
342                             span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
343                         },
344                     }
345                 }
346                 Useful => (),
347                 UsefulWithWitness(_) => unreachable!()
348             }
349             if guard.is_none() {
350                 let Matrix(mut rows) = seen;
351                 rows.push(v);
352                 seen = Matrix(rows);
353             }
354         }
355     }
356 }
357
358 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
359     match p.node {
360         hir::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
361         _ => p
362     }
363 }
364
365 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: hir::MatchSource) {
366     match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
367         UsefulWithWitness(pats) => {
368             let witness = match &pats[..] {
369                 [ref witness] => &**witness,
370                 [] => DUMMY_WILD_PAT,
371                 _ => unreachable!()
372             };
373             match source {
374                 hir::MatchSource::ForLoopDesugar => {
375                     // `witness` has the form `Some(<head>)`, peel off the `Some`
376                     let witness = match witness.node {
377                         hir::PatEnum(_, Some(ref pats)) => match &pats[..] {
378                             [ref pat] => &**pat,
379                             _ => unreachable!(),
380                         },
381                         _ => unreachable!(),
382                     };
383
384                     span_err!(cx.tcx.sess, sp, E0297,
385                         "refutable pattern in `for` loop binding: \
386                                 `{}` not covered",
387                                 pat_to_string(witness));
388                 },
389                 _ => {
390                     span_err!(cx.tcx.sess, sp, E0004,
391                         "non-exhaustive patterns: `{}` not covered",
392                         pat_to_string(witness)
393                     );
394                 },
395             }
396         }
397         NotUseful => {
398             // This is good, wildcard pattern isn't reachable
399         },
400         _ => unreachable!()
401     }
402 }
403
404 fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> {
405     let node = match value {
406         &ConstVal::Bool(b) => ast::LitBool(b),
407         _ => unreachable!()
408     };
409     P(hir::Expr {
410         id: 0,
411         node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
412         span: DUMMY_SP
413     })
414 }
415
416 pub struct StaticInliner<'a, 'tcx: 'a> {
417     pub tcx: &'a ty::ctxt<'tcx>,
418     pub failed: bool,
419     pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
420 }
421
422 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
423     pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
424                    renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
425                    -> StaticInliner<'b, 'tcx> {
426         StaticInliner {
427             tcx: tcx,
428             failed: false,
429             renaming_map: renaming_map
430         }
431     }
432 }
433
434 struct RenamingRecorder<'map> {
435     substituted_node_id: NodeId,
436     origin_span: Span,
437     renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
438 }
439
440 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
441     fn visit_id(&mut self, node_id: NodeId) {
442         let key = (node_id, self.origin_span);
443         self.renaming_map.insert(key, self.substituted_node_id);
444     }
445 }
446
447 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
448     fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
449         return match pat.node {
450             hir::PatIdent(..) | hir::PatEnum(..) | hir::PatQPath(..) => {
451                 let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def());
452                 match def {
453                     Some(DefAssociatedConst(did)) |
454                     Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did, Some(pat.id)) {
455                         Some(const_expr) => {
456                             const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
457
458                                 if let Some(ref mut renaming_map) = self.renaming_map {
459                                     // Record any renamings we do here
460                                     record_renamings(const_expr, &pat, renaming_map);
461                                 }
462
463                                 new_pat
464                             })
465                         }
466                         None => {
467                             self.failed = true;
468                             span_err!(self.tcx.sess, pat.span, E0158,
469                                 "statics cannot be referenced in patterns");
470                             pat
471                         }
472                     },
473                     _ => noop_fold_pat(pat, self)
474                 }
475             }
476             _ => noop_fold_pat(pat, self)
477         };
478
479         fn record_renamings(const_expr: &hir::Expr,
480                             substituted_pat: &hir::Pat,
481                             renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
482             let mut renaming_recorder = RenamingRecorder {
483                 substituted_node_id: substituted_pat.id,
484                 origin_span: substituted_pat.span,
485                 renaming_map: renaming_map,
486             };
487
488             let mut id_visitor = front_util::IdVisitor {
489                 operation: &mut renaming_recorder,
490                 pass_through_items: true,
491                 visited_outermost: false,
492             };
493
494             id_visitor.visit_expr(const_expr);
495         }
496     }
497 }
498
499 /// Constructs a partial witness for a pattern given a list of
500 /// patterns expanded by the specialization step.
501 ///
502 /// When a pattern P is discovered to be useful, this function is used bottom-up
503 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
504 /// of values, V, where each value in that set is not covered by any previously
505 /// used patterns and is covered by the pattern P'. Examples:
506 ///
507 /// left_ty: tuple of 3 elements
508 /// pats: [10, 20, _]           => (10, 20, _)
509 ///
510 /// left_ty: struct X { a: (bool, &'static str), b: usize}
511 /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
512 fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
513                               pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> {
514     let pats_len = pats.len();
515     let mut pats = pats.into_iter().map(|p| P((*p).clone()));
516     let pat = match left_ty.sty {
517         ty::TyTuple(_) => hir::PatTup(pats.collect()),
518
519         ty::TyEnum(adt, _) | ty::TyStruct(adt, _)  => {
520             let v = adt.variant_of_ctor(ctor);
521             if let VariantKind::Struct = v.kind() {
522                 let field_pats: Vec<_> = v.fields.iter()
523                     .zip(pats)
524                     .filter(|&(_, ref pat)| pat.node != hir::PatWild(hir::PatWildSingle))
525                     .map(|(field, pat)| Spanned {
526                         span: DUMMY_SP,
527                         node: hir::FieldPat {
528                             name: field.name,
529                             pat: pat,
530                             is_shorthand: false,
531                         }
532                     }).collect();
533                 let has_more_fields = field_pats.len() < pats_len;
534                 hir::PatStruct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
535             } else {
536                 hir::PatEnum(def_to_path(cx.tcx, v.did), Some(pats.collect()))
537             }
538         }
539
540         ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
541             match ty.sty {
542                ty::TyArray(_, n) => match ctor {
543                     &Single => {
544                         assert_eq!(pats_len, n);
545                         hir::PatVec(pats.collect(), None, vec!())
546                     },
547                     _ => unreachable!()
548                 },
549                 ty::TySlice(_) => match ctor {
550                     &Slice(n) => {
551                         assert_eq!(pats_len, n);
552                         hir::PatVec(pats.collect(), None, vec!())
553                     },
554                     _ => unreachable!()
555                 },
556                 ty::TyStr => hir::PatWild(hir::PatWildSingle),
557
558                 _ => {
559                     assert_eq!(pats_len, 1);
560                     hir::PatRegion(pats.nth(0).unwrap(), mutbl)
561                 }
562             }
563         }
564
565         ty::TyArray(_, len) => {
566             assert_eq!(pats_len, len);
567             hir::PatVec(pats.collect(), None, vec![])
568         }
569
570         _ => {
571             match *ctor {
572                 ConstantValue(ref v) => hir::PatLit(const_val_to_expr(v)),
573                 _ => hir::PatWild(hir::PatWildSingle),
574             }
575         }
576     };
577
578     P(hir::Pat {
579         id: 0,
580         node: pat,
581         span: DUMMY_SP
582     })
583 }
584
585 impl<'tcx, 'container> ty::AdtDefData<'tcx, 'container> {
586     fn variant_of_ctor(&self,
587                        ctor: &Constructor)
588                        -> &VariantDefData<'tcx, 'container> {
589         match ctor {
590             &Variant(vid) => self.variant_with_id(vid),
591             _ => self.struct_variant()
592         }
593     }
594 }
595
596 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
597                        left_ty: Ty, max_slice_length: usize) -> Option<Constructor> {
598     let used_constructors: Vec<Constructor> = rows.iter()
599         .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
600         .collect();
601     all_constructors(cx, left_ty, max_slice_length)
602         .into_iter()
603         .find(|c| !used_constructors.contains(c))
604 }
605
606 /// This determines the set of all possible constructors of a pattern matching
607 /// values of type `left_ty`. For vectors, this would normally be an infinite set
608 /// but is instead bounded by the maximum fixed length of slice patterns in
609 /// the column of patterns being analyzed.
610 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
611                     max_slice_length: usize) -> Vec<Constructor> {
612     match left_ty.sty {
613         ty::TyBool =>
614             [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
615
616         ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
617             ty::TySlice(_) =>
618                 (0..max_slice_length+1).map(|length| Slice(length)).collect(),
619             _ => vec![Single]
620         },
621
622         ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
623         _ => vec![Single]
624     }
625 }
626
627 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
628 //
629 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
630 // vectors `m` is defined as there being a set of inputs that will match `v`
631 // but not any of the sets in `m`.
632 //
633 // This is used both for reachability checking (if a pattern isn't useful in
634 // relation to preceding patterns, it is not reachable) and exhaustiveness
635 // checking (if a wildcard pattern is useful in relation to a matrix, the
636 // matrix isn't exhaustive).
637
638 // Note: is_useful doesn't work on empty types, as the paper notes.
639 // So it assumes that v is non-empty.
640 fn is_useful(cx: &MatchCheckCtxt,
641              matrix: &Matrix,
642              v: &[&Pat],
643              witness: WitnessPreference)
644              -> Usefulness {
645     let &Matrix(ref rows) = matrix;
646     debug!("{:?}", matrix);
647     if rows.is_empty() {
648         return match witness {
649             ConstructWitness => UsefulWithWitness(vec!()),
650             LeaveOutWitness => Useful
651         };
652     }
653     if rows[0].is_empty() {
654         return NotUseful;
655     }
656     assert!(rows.iter().all(|r| r.len() == v.len()));
657     let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
658         Some(r) => raw_pat(r[0]),
659         None if v.is_empty() => return NotUseful,
660         None => v[0]
661     };
662     let left_ty = if real_pat.id == DUMMY_NODE_ID {
663         cx.tcx.mk_nil()
664     } else {
665         let left_ty = cx.tcx.pat_ty(&*real_pat);
666
667         match real_pat.node {
668             hir::PatIdent(hir::BindByRef(..), _, _) => {
669                 left_ty.builtin_deref(false, NoPreference).unwrap().ty
670             }
671             _ => left_ty,
672         }
673     };
674
675     let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
676         hir::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
677         _ => None
678     }).max().map_or(0, |v| v + 1);
679
680     let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
681     if constructors.is_empty() {
682         match missing_constructor(cx, matrix, left_ty, max_slice_length) {
683             None => {
684                 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
685                     match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
686                         UsefulWithWitness(pats) => UsefulWithWitness({
687                             let arity = constructor_arity(cx, &c, left_ty);
688                             let mut result = {
689                                 let pat_slice = &pats[..];
690                                 let subpats: Vec<_> = (0..arity).map(|i| {
691                                     pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
692                                 }).collect();
693                                 vec![construct_witness(cx, &c, subpats, left_ty)]
694                             };
695                             result.extend(pats.into_iter().skip(arity));
696                             result
697                         }),
698                         result => result
699                     }
700                 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
701             },
702
703             Some(constructor) => {
704                 let matrix = rows.iter().filter_map(|r| {
705                     if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
706                         Some(r[1..].to_vec())
707                     } else {
708                         None
709                     }
710                 }).collect();
711                 match is_useful(cx, &matrix, &v[1..], witness) {
712                     UsefulWithWitness(pats) => {
713                         let arity = constructor_arity(cx, &constructor, left_ty);
714                         let wild_pats = vec![DUMMY_WILD_PAT; arity];
715                         let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
716                         let mut new_pats = vec![enum_pat];
717                         new_pats.extend(pats);
718                         UsefulWithWitness(new_pats)
719                     },
720                     result => result
721                 }
722             }
723         }
724     } else {
725         constructors.into_iter().map(|c|
726             is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
727         ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
728     }
729 }
730
731 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
732                          v: &[&Pat], ctor: Constructor, lty: Ty,
733                          witness: WitnessPreference) -> Usefulness {
734     let arity = constructor_arity(cx, &ctor, lty);
735     let matrix = Matrix(m.iter().filter_map(|r| {
736         specialize(cx, &r[..], &ctor, 0, arity)
737     }).collect());
738     match specialize(cx, v, &ctor, 0, arity) {
739         Some(v) => is_useful(cx, &matrix, &v[..], witness),
740         None => NotUseful
741     }
742 }
743
744 /// Determines the constructors that the given pattern can be specialized to.
745 ///
746 /// In most cases, there's only one constructor that a specific pattern
747 /// represents, such as a specific enum variant or a specific literal value.
748 /// Slice patterns, however, can match slices of different lengths. For instance,
749 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
750 ///
751 /// On the other hand, a wild pattern and an identifier pattern cannot be
752 /// specialized in any way.
753 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
754                     left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
755     let pat = raw_pat(p);
756     match pat.node {
757         hir::PatIdent(..) =>
758             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
759                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
760                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
761                                                     been rewritten"),
762                 Some(DefStruct(_)) => vec!(Single),
763                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
764                 _ => vec!()
765             },
766         hir::PatEnum(..) =>
767             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
768                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
769                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
770                                                     been rewritten"),
771                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
772                 _ => vec!(Single)
773             },
774         hir::PatQPath(..) =>
775             cx.tcx.sess.span_bug(pat.span, "const pattern should've \
776                                             been rewritten"),
777         hir::PatStruct(..) =>
778             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
779                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
780                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
781                                                     been rewritten"),
782                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
783                 _ => vec!(Single)
784             },
785         hir::PatLit(ref expr) =>
786             vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
787         hir::PatRange(ref lo, ref hi) =>
788             vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
789         hir::PatVec(ref before, ref slice, ref after) =>
790             match left_ty.sty {
791                 ty::TyArray(_, _) => vec!(Single),
792                 _                      => if slice.is_some() {
793                     (before.len() + after.len()..max_slice_length+1)
794                         .map(|length| Slice(length))
795                         .collect()
796                 } else {
797                     vec!(Slice(before.len() + after.len()))
798                 }
799             },
800         hir::PatBox(_) | hir::PatTup(_) | hir::PatRegion(..) =>
801             vec!(Single),
802         hir::PatWild(_) =>
803             vec!(),
804     }
805 }
806
807 /// This computes the arity of a constructor. The arity of a constructor
808 /// is how many subpattern patterns of that constructor should be expanded to.
809 ///
810 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
811 /// A struct pattern's arity is the number of fields it contains, etc.
812 pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
813     match ty.sty {
814         ty::TyTuple(ref fs) => fs.len(),
815         ty::TyBox(_) => 1,
816         ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
817             ty::TySlice(_) => match *ctor {
818                 Slice(length) => length,
819                 ConstantValue(_) => 0,
820                 _ => unreachable!()
821             },
822             ty::TyStr => 0,
823             _ => 1
824         },
825         ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
826             adt.variant_of_ctor(ctor).fields.len()
827         }
828         ty::TyArray(_, n) => n,
829         _ => 0
830     }
831 }
832
833 fn range_covered_by_constructor(ctor: &Constructor,
834                                 from: &ConstVal, to: &ConstVal) -> Option<bool> {
835     let (c_from, c_to) = match *ctor {
836         ConstantValue(ref value)        => (value, value),
837         ConstantRange(ref from, ref to) => (from, to),
838         Single                          => return Some(true),
839         _                               => unreachable!()
840     };
841     let cmp_from = compare_const_vals(c_from, from);
842     let cmp_to = compare_const_vals(c_to, to);
843     match (cmp_from, cmp_to) {
844         (Some(cmp_from), Some(cmp_to)) => {
845             Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
846         }
847         _ => None
848     }
849 }
850
851 /// This is the main specialization step. It expands the first pattern in the given row
852 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
853 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
854 ///
855 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
856 /// different patterns.
857 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
858 /// fields filled with wild patterns.
859 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
860                       constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
861     let &Pat {
862         id: pat_id, ref node, span: pat_span
863     } = raw_pat(r[col]);
864     let head: Option<Vec<&Pat>> = match *node {
865         hir::PatWild(_) =>
866             Some(vec![DUMMY_WILD_PAT; arity]),
867
868         hir::PatIdent(_, _, _) => {
869             let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
870             match opt_def {
871                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
872                     cx.tcx.sess.span_bug(pat_span, "const pattern should've \
873                                                     been rewritten"),
874                 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
875                     Some(vec!())
876                 } else {
877                     None
878                 },
879                 _ => Some(vec![DUMMY_WILD_PAT; arity])
880             }
881         }
882
883         hir::PatEnum(_, ref args) => {
884             let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
885             match def {
886                 DefConst(..) | DefAssociatedConst(..) =>
887                     cx.tcx.sess.span_bug(pat_span, "const pattern should've \
888                                                     been rewritten"),
889                 DefVariant(_, id, _) if *constructor != Variant(id) => None,
890                 DefVariant(..) | DefStruct(..) => {
891                     Some(match args {
892                         &Some(ref args) => args.iter().map(|p| &**p).collect(),
893                         &None => vec![DUMMY_WILD_PAT; arity],
894                     })
895                 }
896                 _ => None
897             }
898         }
899
900         hir::PatQPath(_, _) => {
901             cx.tcx.sess.span_bug(pat_span, "const pattern should've \
902                                             been rewritten")
903         }
904
905         hir::PatStruct(_, ref pattern_fields, _) => {
906             let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
907             let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
908             let variant = adt.variant_of_ctor(constructor);
909             let def_variant = adt.variant_of_def(def);
910             if variant.did == def_variant.did {
911                 Some(variant.fields.iter().map(|sf| {
912                     match pattern_fields.iter().find(|f| f.node.name == sf.name) {
913                         Some(ref f) => &*f.node.pat,
914                         _ => DUMMY_WILD_PAT
915                     }
916                 }).collect())
917             } else {
918                 None
919             }
920         }
921
922         hir::PatTup(ref args) =>
923             Some(args.iter().map(|p| &**p).collect()),
924
925         hir::PatBox(ref inner) | hir::PatRegion(ref inner, _) =>
926             Some(vec![&**inner]),
927
928         hir::PatLit(ref expr) => {
929             let expr_value = eval_const_expr(cx.tcx, &**expr);
930             match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
931                 Some(true) => Some(vec![]),
932                 Some(false) => None,
933                 None => {
934                     span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
935                     None
936                 }
937             }
938         }
939
940         hir::PatRange(ref from, ref to) => {
941             let from_value = eval_const_expr(cx.tcx, &**from);
942             let to_value = eval_const_expr(cx.tcx, &**to);
943             match range_covered_by_constructor(constructor, &from_value, &to_value) {
944                 Some(true) => Some(vec![]),
945                 Some(false) => None,
946                 None => {
947                     span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
948                     None
949                 }
950             }
951         }
952
953         hir::PatVec(ref before, ref slice, ref after) => {
954             match *constructor {
955                 // Fixed-length vectors.
956                 Single => {
957                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
958                     pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
959                     pats.extend(after.iter().map(|p| &**p));
960                     Some(pats)
961                 },
962                 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
963                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
964                     pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
965                     pats.extend(after.iter().map(|p| &**p));
966                     Some(pats)
967                 },
968                 Slice(length) if before.len() + after.len() == length => {
969                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
970                     pats.extend(after.iter().map(|p| &**p));
971                     Some(pats)
972                 },
973                 SliceWithSubslice(prefix, suffix)
974                     if before.len() == prefix
975                         && after.len() == suffix
976                         && slice.is_some() => {
977                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
978                     pats.extend(after.iter().map(|p| &**p));
979                     Some(pats)
980                 }
981                 _ => None
982             }
983         }
984     };
985     head.map(|mut head| {
986         head.push_all(&r[..col]);
987         head.push_all(&r[col + 1..]);
988         head
989     })
990 }
991
992 fn check_local(cx: &mut MatchCheckCtxt, loc: &hir::Local) {
993     visit::walk_local(cx, loc);
994
995     let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
996     check_irrefutable(cx, &pat, false);
997
998     // Check legality of move bindings and `@` patterns.
999     check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1000     check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1001 }
1002
1003 fn check_fn(cx: &mut MatchCheckCtxt,
1004             kind: FnKind,
1005             decl: &hir::FnDecl,
1006             body: &hir::Block,
1007             sp: Span,
1008             fn_id: NodeId) {
1009     match kind {
1010         FnKind::Closure => {}
1011         _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1012     }
1013
1014     visit::walk_fn(cx, kind, decl, body, sp);
1015
1016     for input in &decl.inputs {
1017         check_irrefutable(cx, &input.pat, true);
1018         check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1019         check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1020     }
1021 }
1022
1023 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1024     let origin = if is_fn_arg {
1025         "function argument"
1026     } else {
1027         "local binding"
1028     };
1029
1030     is_refutable(cx, pat, |uncovered_pat| {
1031         span_err!(cx.tcx.sess, pat.span, E0005,
1032             "refutable pattern in {}: `{}` not covered",
1033             origin,
1034             pat_to_string(uncovered_pat),
1035         );
1036     });
1037 }
1038
1039 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1040     F: FnOnce(&Pat) -> A,
1041 {
1042     let pats = Matrix(vec!(vec!(pat)));
1043     match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1044         UsefulWithWitness(pats) => {
1045             assert_eq!(pats.len(), 1);
1046             Some(refutable(&*pats[0]))
1047         },
1048         NotUseful => None,
1049         Useful => unreachable!()
1050     }
1051 }
1052
1053 // Legality of move bindings checking
1054 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1055                                    has_guard: bool,
1056                                    pats: &[P<Pat>]) {
1057     let tcx = cx.tcx;
1058     let def_map = &tcx.def_map;
1059     let mut by_ref_span = None;
1060     for pat in pats {
1061         pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1062             match bm {
1063                 hir::BindByRef(_) => {
1064                     by_ref_span = Some(span);
1065                 }
1066                 hir::BindByValue(_) => {
1067                 }
1068             }
1069         })
1070     }
1071
1072     let check_move = |p: &Pat, sub: Option<&Pat>| {
1073         // check legality of moving out of the enum
1074
1075         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1076         if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1077             span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1078         } else if has_guard {
1079             span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1080         } else if by_ref_span.is_some() {
1081             span_err!(cx.tcx.sess, p.span, E0009,
1082                 "cannot bind by-move and by-ref in the same pattern");
1083             span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1084         }
1085     };
1086
1087     for pat in pats {
1088         front_util::walk_pat(&**pat, |p| {
1089             if pat_is_binding(def_map, &*p) {
1090                 match p.node {
1091                     hir::PatIdent(hir::BindByValue(_), _, ref sub) => {
1092                         let pat_ty = tcx.node_id_to_type(p.id);
1093                         //FIXME: (@jroesch) this code should be floated up as well
1094                         let infcx = infer::new_infer_ctxt(cx.tcx,
1095                                                           &cx.tcx.tables,
1096                                                           Some(cx.param_env.clone()),
1097                                                           false);
1098                         if infcx.type_moves_by_default(pat_ty, pat.span) {
1099                             check_move(p, sub.as_ref().map(|p| &**p));
1100                         }
1101                     }
1102                     hir::PatIdent(hir::BindByRef(_), _, _) => {
1103                     }
1104                     _ => {
1105                         cx.tcx.sess.span_bug(
1106                             p.span,
1107                             &format!("binding pattern {} is not an \
1108                                      identifier: {:?}",
1109                                     p.id,
1110                                     p.node));
1111                     }
1112                 }
1113             }
1114             true
1115         });
1116     }
1117 }
1118
1119 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1120 /// assign.
1121 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1122                                          guard: &hir::Expr) {
1123     let mut checker = MutationChecker {
1124         cx: cx,
1125     };
1126
1127     let infcx = infer::new_infer_ctxt(cx.tcx,
1128                                       &cx.tcx.tables,
1129                                       Some(checker.cx.param_env.clone()),
1130                                       false);
1131
1132     let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1133     visitor.walk_expr(guard);
1134 }
1135
1136 struct MutationChecker<'a, 'tcx: 'a> {
1137     cx: &'a MatchCheckCtxt<'a, 'tcx>,
1138 }
1139
1140 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1141     fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1142     fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1143     fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1144     fn borrow(&mut self,
1145               _: NodeId,
1146               span: Span,
1147               _: cmt,
1148               _: Region,
1149               kind: BorrowKind,
1150               _: LoanCause) {
1151         match kind {
1152             MutBorrow => {
1153                 span_err!(self.cx.tcx.sess, span, E0301,
1154                           "cannot mutably borrow in a pattern guard")
1155             }
1156             ImmBorrow | UniqueImmBorrow => {}
1157         }
1158     }
1159     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1160     fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1161         match mode {
1162             JustWrite | WriteAndRead => {
1163                 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1164             }
1165             Init => {}
1166         }
1167     }
1168 }
1169
1170 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1171 /// because of the way rvalues are handled in the borrow check. (See issue
1172 /// #14587.)
1173 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1174     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1175 }
1176
1177 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1178     cx: &'a MatchCheckCtxt<'b, 'tcx>,
1179     bindings_allowed: bool
1180 }
1181
1182 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1183     fn visit_pat(&mut self, pat: &Pat) {
1184         if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1185             span_err!(self.cx.tcx.sess, pat.span, E0303,
1186                                       "pattern bindings are not allowed \
1187                                        after an `@`");
1188         }
1189
1190         match pat.node {
1191             hir::PatIdent(_, _, Some(_)) => {
1192                 let bindings_were_allowed = self.bindings_allowed;
1193                 self.bindings_allowed = false;
1194                 visit::walk_pat(self, pat);
1195                 self.bindings_allowed = bindings_were_allowed;
1196             }
1197             _ => visit::walk_pat(self, pat),
1198         }
1199     }
1200 }