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