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