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