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