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