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