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