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