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