]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/check_match.rs
Rollup merge of #35558 - lukehinds:master, r=nikomatsakis
[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::*;
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             check_exhaustive(cx, scrut.span, &matrix, source);
239         },
240         _ => ()
241     }
242 }
243
244 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
245     pat.walk(|p| {
246         if let PatKind::Binding(hir::BindByValue(hir::MutImmutable), name, None) = p.node {
247             let pat_ty = cx.tcx.pat_ty(p);
248             if let ty::TyEnum(edef, _) = pat_ty.sty {
249                 if let Def::Local(..) = cx.tcx.expect_def(p.id) {
250                     if edef.variants.iter().any(|variant| {
251                         variant.name == name.node && variant.kind == VariantKind::Unit
252                     }) {
253                         let ty_path = cx.tcx.item_path_str(edef.did);
254                         let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
255                             "pattern binding `{}` is named the same as one \
256                              of the variants of the type `{}`",
257                             name.node, ty_path);
258                         help!(err,
259                             "if you meant to match on a variant, \
260                              consider making the path in the pattern qualified: `{}::{}`",
261                             ty_path, name.node);
262                         err.emit();
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                             span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
328                         },
329
330                         hir::MatchSource::ForLoopDesugar => {
331                             // this is a bug, because on `match iter.next()` we cover
332                             // `Some(<head>)` and `None`. It's impossible to have an unreachable
333                             // pattern
334                             // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
335                             span_bug!(pat.span, "unreachable for-loop pattern")
336                         },
337
338                         hir::MatchSource::Normal => {
339                             let mut err = struct_span_err!(cx.tcx.sess, pat.span, E0001,
340                                                            "unreachable pattern");
341                             err.span_label(pat.span, &format!("this is an unreachable pattern"));
342                             // if we had a catchall pattern, hint at that
343                             for row in &seen.0 {
344                                 if pat_is_catchall(&cx.tcx.def_map.borrow(), row[0].0) {
345                                     span_note!(err, row[0].0.span,
346                                                "this pattern matches any value");
347                                 }
348                             }
349                             err.emit();
350                         },
351
352                         hir::MatchSource::TryDesugar => {
353                             span_bug!(pat.span, "unreachable try pattern")
354                         },
355                     }
356                 }
357                 Useful => (),
358                 UsefulWithWitness(_) => bug!()
359             }
360             if guard.is_none() {
361                 let Matrix(mut rows) = seen;
362                 rows.push(v);
363                 seen = Matrix(rows);
364             }
365         }
366     }
367 }
368
369 /// Checks for common cases of "catchall" patterns that may not be intended as such.
370 fn pat_is_catchall(dm: &DefMap, p: &Pat) -> bool {
371     match p.node {
372         PatKind::Binding(_, _, None) => true,
373         PatKind::Binding(_, _, Some(ref s)) => pat_is_catchall(dm, &s),
374         PatKind::Ref(ref s, _) => pat_is_catchall(dm, &s),
375         PatKind::Tuple(ref v, _) => v.iter().all(|p| pat_is_catchall(dm, &p)),
376         _ => false
377     }
378 }
379
380 fn raw_pat(p: &Pat) -> &Pat {
381     match p.node {
382         PatKind::Binding(_, _, Some(ref s)) => raw_pat(&s),
383         _ => p
384     }
385 }
386
387 fn check_exhaustive<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>,
388                               sp: Span,
389                               matrix: &Matrix<'a, 'tcx>,
390                               source: hir::MatchSource) {
391     match is_useful(cx, matrix, &[(DUMMY_WILD_PAT, None)], ConstructWitness) {
392         UsefulWithWitness(pats) => {
393             let witnesses = if pats.is_empty() {
394                 vec![DUMMY_WILD_PAT]
395             } else {
396                 pats.iter().map(|w| &**w).collect()
397             };
398             match source {
399                 hir::MatchSource::ForLoopDesugar => {
400                     // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some`
401                     let witness = match witnesses[0].node {
402                         PatKind::TupleStruct(_, ref pats, _) => match &pats[..] {
403                             &[ref pat] => &**pat,
404                             _ => bug!(),
405                         },
406                         _ => bug!(),
407                     };
408                     span_err!(cx.tcx.sess, sp, E0297,
409                         "refutable pattern in `for` loop binding: \
410                                 `{}` not covered",
411                                 pat_to_string(witness));
412                 },
413                 _ => {
414                     let pattern_strings: Vec<_> = witnesses.iter().map(|w| {
415                         pat_to_string(w)
416                     }).collect();
417                     const LIMIT: usize = 3;
418                     let joined_patterns = match pattern_strings.len() {
419                         0 => bug!(),
420                         1 => format!("`{}`", pattern_strings[0]),
421                         2...LIMIT => {
422                             let (tail, head) = pattern_strings.split_last().unwrap();
423                             format!("`{}`", head.join("`, `") + "` and `" + tail)
424                         },
425                         _ => {
426                             let (head, tail) = pattern_strings.split_at(LIMIT);
427                             format!("`{}` and {} more", head.join("`, `"), tail.len())
428                         }
429                     };
430
431                     let label_text = match pattern_strings.len(){
432                         1 => format!("pattern {} not covered", joined_patterns),
433                         _ => format!("patterns {} not covered", joined_patterns)
434                     };
435                     struct_span_err!(cx.tcx.sess, sp, E0004,
436                         "non-exhaustive patterns: {} not covered",
437                         joined_patterns
438                     ).span_label(sp, &label_text).emit();
439                 },
440             }
441         }
442         NotUseful => {
443             // This is good, wildcard pattern isn't reachable
444         },
445         _ => bug!()
446     }
447 }
448
449 fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> {
450     let node = match value {
451         &ConstVal::Bool(b) => ast::LitKind::Bool(b),
452         _ => bug!()
453     };
454     P(hir::Expr {
455         id: 0,
456         node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
457         span: DUMMY_SP,
458         attrs: ast::ThinVec::new(),
459     })
460 }
461
462 pub struct StaticInliner<'a, 'tcx: 'a> {
463     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
464     pub failed: bool,
465     pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
466 }
467
468 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
469     pub fn new<'b>(tcx: TyCtxt<'b, 'tcx, 'tcx>,
470                    renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
471                    -> StaticInliner<'b, 'tcx> {
472         StaticInliner {
473             tcx: tcx,
474             failed: false,
475             renaming_map: renaming_map
476         }
477     }
478 }
479
480 struct RenamingRecorder<'map> {
481     substituted_node_id: NodeId,
482     origin_span: Span,
483     renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
484 }
485
486 impl<'v, 'map> Visitor<'v> for RenamingRecorder<'map> {
487     fn visit_id(&mut self, node_id: NodeId) {
488         let key = (node_id, self.origin_span);
489         self.renaming_map.insert(key, self.substituted_node_id);
490     }
491 }
492
493 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
494     fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
495         return match pat.node {
496             PatKind::Path(..) => {
497                 match self.tcx.expect_def(pat.id) {
498                     Def::AssociatedConst(did) | Def::Const(did) => {
499                         let substs = Some(self.tcx.node_id_item_substs(pat.id).substs);
500                         if let Some((const_expr, _)) = lookup_const_by_id(self.tcx, did, substs) {
501                             match const_expr_to_pat(self.tcx, const_expr, pat.id, pat.span) {
502                                 Ok(new_pat) => {
503                                     if let Some(ref mut map) = self.renaming_map {
504                                         // Record any renamings we do here
505                                         record_renamings(const_expr, &pat, map);
506                                     }
507                                     new_pat
508                                 }
509                                 Err(def_id) => {
510                                     self.failed = true;
511                                     self.tcx.sess.span_err(
512                                         pat.span,
513                                         &format!("constants of the type `{}` \
514                                                   cannot be used in patterns",
515                                                  self.tcx.item_path_str(def_id)));
516                                     pat
517                                 }
518                             }
519                         } else {
520                             self.failed = true;
521                             span_err!(self.tcx.sess, pat.span, E0158,
522                                 "statics cannot be referenced in patterns");
523                             pat
524                         }
525                     }
526                     _ => noop_fold_pat(pat, self)
527                 }
528             }
529             _ => noop_fold_pat(pat, self)
530         };
531
532         fn record_renamings(const_expr: &hir::Expr,
533                             substituted_pat: &hir::Pat,
534                             renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
535             let mut renaming_recorder = RenamingRecorder {
536                 substituted_node_id: substituted_pat.id,
537                 origin_span: substituted_pat.span,
538                 renaming_map: renaming_map,
539             };
540
541             renaming_recorder.visit_expr(const_expr);
542         }
543     }
544 }
545
546 /// Constructs a partial witness for a pattern given a list of
547 /// patterns expanded by the specialization step.
548 ///
549 /// When a pattern P is discovered to be useful, this function is used bottom-up
550 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
551 /// of values, V, where each value in that set is not covered by any previously
552 /// used patterns and is covered by the pattern P'. Examples:
553 ///
554 /// left_ty: tuple of 3 elements
555 /// pats: [10, 20, _]           => (10, 20, _)
556 ///
557 /// left_ty: struct X { a: (bool, &'static str), b: usize}
558 /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
559 fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
560                               pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> {
561     let pats_len = pats.len();
562     let mut pats = pats.into_iter().map(|p| P((*p).clone()));
563     let pat = match left_ty.sty {
564         ty::TyTuple(..) => PatKind::Tuple(pats.collect(), None),
565
566         ty::TyEnum(adt, _) | ty::TyStruct(adt, _)  => {
567             let v = ctor.variant_for_adt(adt);
568             match v.kind {
569                 VariantKind::Struct => {
570                     let field_pats: hir::HirVec<_> = v.fields.iter()
571                         .zip(pats)
572                         .filter(|&(_, ref pat)| pat.node != PatKind::Wild)
573                         .map(|(field, pat)| Spanned {
574                             span: DUMMY_SP,
575                             node: hir::FieldPat {
576                                 name: field.name,
577                                 pat: pat,
578                                 is_shorthand: false,
579                             }
580                         }).collect();
581                     let has_more_fields = field_pats.len() < pats_len;
582                     PatKind::Struct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
583                 }
584                 VariantKind::Tuple => {
585                     PatKind::TupleStruct(def_to_path(cx.tcx, v.did), pats.collect(), None)
586                 }
587                 VariantKind::Unit => {
588                     PatKind::Path(None, def_to_path(cx.tcx, v.did))
589                 }
590             }
591         }
592
593         ty::TyRef(_, ty::TypeAndMut { mutbl, .. }) => {
594             assert_eq!(pats_len, 1);
595             PatKind::Ref(pats.nth(0).unwrap(), mutbl)
596         }
597
598         ty::TySlice(_) => match ctor {
599             &Slice(n) => {
600                 assert_eq!(pats_len, n);
601                 PatKind::Vec(pats.collect(), None, hir::HirVec::new())
602             },
603             _ => unreachable!()
604         },
605
606         ty::TyArray(_, len) => {
607             assert_eq!(pats_len, len);
608             PatKind::Vec(pats.collect(), None, hir::HirVec::new())
609         }
610
611         _ => {
612             match *ctor {
613                 ConstantValue(ref v) => PatKind::Lit(const_val_to_expr(v)),
614                 _ => PatKind::Wild,
615             }
616         }
617     };
618
619     P(hir::Pat {
620         id: 0,
621         node: pat,
622         span: DUMMY_SP
623     })
624 }
625
626 impl Constructor {
627     fn variant_for_adt<'tcx, 'container, 'a>(&self,
628                                              adt: &'a ty::AdtDefData<'tcx, 'container>)
629                                              -> &'a VariantDefData<'tcx, 'container> {
630         match self {
631             &Variant(vid) => adt.variant_with_id(vid),
632             _ => adt.struct_variant()
633         }
634     }
635 }
636
637 fn missing_constructors(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
638                        left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
639     let used_constructors: Vec<Constructor> = rows.iter()
640         .flat_map(|row| pat_constructors(cx, row[0].0, left_ty, max_slice_length))
641         .collect();
642     all_constructors(cx, left_ty, max_slice_length)
643         .into_iter()
644         .filter(|c| !used_constructors.contains(c))
645         .collect()
646 }
647
648 /// This determines the set of all possible constructors of a pattern matching
649 /// values of type `left_ty`. For vectors, this would normally be an infinite set
650 /// but is instead bounded by the maximum fixed length of slice patterns in
651 /// the column of patterns being analyzed.
652 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
653                     max_slice_length: usize) -> Vec<Constructor> {
654     match left_ty.sty {
655         ty::TyBool =>
656             [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
657         ty::TySlice(_) =>
658             (0..max_slice_length+1).map(|length| Slice(length)).collect(),
659         ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
660         _ => vec![Single]
661     }
662 }
663
664 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
665 //
666 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
667 // vectors `m` is defined as there being a set of inputs that will match `v`
668 // but not any of the sets in `m`.
669 //
670 // This is used both for reachability checking (if a pattern isn't useful in
671 // relation to preceding patterns, it is not reachable) and exhaustiveness
672 // checking (if a wildcard pattern is useful in relation to a matrix, the
673 // matrix isn't exhaustive).
674
675 // Note: is_useful doesn't work on empty types, as the paper notes.
676 // So it assumes that v is non-empty.
677 fn is_useful<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>,
678                        matrix: &Matrix<'a, 'tcx>,
679                        v: &[(&Pat, Option<Ty<'tcx>>)],
680                        witness: WitnessPreference)
681                        -> Usefulness {
682     let &Matrix(ref rows) = matrix;
683     debug!("is_useful({:?}, {:?})", matrix, v);
684     if rows.is_empty() {
685         return match witness {
686             ConstructWitness => UsefulWithWitness(vec!()),
687             LeaveOutWitness => Useful
688         };
689     }
690     if rows[0].is_empty() {
691         return NotUseful;
692     }
693     assert!(rows.iter().all(|r| r.len() == v.len()));
694     let left_ty = match rows.iter().filter_map(|r| r[0].1).next().or_else(|| v[0].1) {
695         Some(ty) => ty,
696         None => {
697             // all patterns are wildcards - we can pick any type we want
698             cx.tcx.types.bool
699         }
700     };
701
702     let max_slice_length = rows.iter().filter_map(|row| match row[0].0.node {
703         PatKind::Vec(ref before, _, ref after) => Some(before.len() + after.len()),
704         _ => None
705     }).max().map_or(0, |v| v + 1);
706
707     let constructors = pat_constructors(cx, v[0].0, left_ty, max_slice_length);
708     debug!("is_useful - pat_constructors = {:?} left_ty = {:?}", constructors,
709            left_ty);
710     if constructors.is_empty() {
711         let constructors = missing_constructors(cx, matrix, left_ty, max_slice_length);
712         debug!("is_useful - missing_constructors = {:?}", constructors);
713         if constructors.is_empty() {
714             all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
715                 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
716                     UsefulWithWitness(pats) => UsefulWithWitness({
717                         let arity = constructor_arity(cx, &c, left_ty);
718                         let mut result = {
719                             let pat_slice = &pats[..];
720                             let subpats: Vec<_> = (0..arity).map(|i| {
721                                 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
722                             }).collect();
723                             vec![construct_witness(cx, &c, subpats, left_ty)]
724                         };
725                         result.extend(pats.into_iter().skip(arity));
726                         result
727                     }),
728                     result => result
729                 }
730             }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
731         } else {
732             let matrix = rows.iter().filter_map(|r| {
733                 match raw_pat(r[0].0).node {
734                     PatKind::Binding(..) | PatKind::Wild => Some(r[1..].to_vec()),
735                     _ => None,
736                 }
737             }).collect();
738             match is_useful(cx, &matrix, &v[1..], witness) {
739                 UsefulWithWitness(pats) => {
740                     let mut new_pats: Vec<_> = constructors.into_iter().map(|constructor| {
741                         let arity = constructor_arity(cx, &constructor, left_ty);
742                         let wild_pats = vec![DUMMY_WILD_PAT; arity];
743                         construct_witness(cx, &constructor, wild_pats, left_ty)
744                     }).collect();
745                     new_pats.extend(pats);
746                     UsefulWithWitness(new_pats)
747                 },
748                 result => result
749             }
750         }
751     } else {
752         constructors.into_iter().map(|c|
753             is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
754         ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
755     }
756 }
757
758 fn is_useful_specialized<'a, 'tcx>(
759     cx: &MatchCheckCtxt<'a, 'tcx>,
760     &Matrix(ref m): &Matrix<'a, 'tcx>,
761     v: &[(&Pat, Option<Ty<'tcx>>)],
762     ctor: Constructor,
763     lty: Ty<'tcx>,
764     witness: WitnessPreference) -> Usefulness
765 {
766     let arity = constructor_arity(cx, &ctor, lty);
767     let matrix = Matrix(m.iter().filter_map(|r| {
768         specialize(cx, &r[..], &ctor, 0, arity)
769     }).collect());
770     match specialize(cx, v, &ctor, 0, arity) {
771         Some(v) => is_useful(cx, &matrix, &v[..], witness),
772         None => NotUseful
773     }
774 }
775
776 /// Determines the constructors that the given pattern can be specialized to.
777 ///
778 /// In most cases, there's only one constructor that a specific pattern
779 /// represents, such as a specific enum variant or a specific literal value.
780 /// Slice patterns, however, can match slices of different lengths. For instance,
781 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
782 ///
783 /// On the other hand, a wild pattern and an identifier pattern cannot be
784 /// specialized in any way.
785 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
786                     left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
787     let pat = raw_pat(p);
788     match pat.node {
789         PatKind::Struct(..) | PatKind::TupleStruct(..) | PatKind::Path(..) =>
790             match cx.tcx.expect_def(pat.id) {
791                 Def::Variant(_, id) => vec![Variant(id)],
792                 Def::Struct(..) | Def::TyAlias(..) | Def::AssociatedTy(..) => vec![Single],
793                 Def::Const(..) | Def::AssociatedConst(..) =>
794                     span_bug!(pat.span, "const pattern should've been rewritten"),
795                 def => span_bug!(pat.span, "pat_constructors: unexpected definition {:?}", def),
796             },
797         PatKind::Lit(ref expr) =>
798             vec![ConstantValue(eval_const_expr(cx.tcx, &expr))],
799         PatKind::Range(ref lo, ref hi) =>
800             vec![ConstantRange(eval_const_expr(cx.tcx, &lo), eval_const_expr(cx.tcx, &hi))],
801         PatKind::Vec(ref before, ref slice, ref after) =>
802             match left_ty.sty {
803                 ty::TyArray(_, _) => vec![Single],
804                 ty::TySlice(_) if slice.is_some() => {
805                     (before.len() + after.len()..max_slice_length+1)
806                         .map(|length| Slice(length))
807                         .collect()
808                 }
809                 ty::TySlice(_) => vec!(Slice(before.len() + after.len())),
810                 _ => span_bug!(pat.span, "pat_constructors: unexpected \
811                                           slice pattern type {:?}", left_ty)
812             },
813         PatKind::Box(..) | PatKind::Tuple(..) | PatKind::Ref(..) =>
814             vec![Single],
815         PatKind::Binding(..) | PatKind::Wild =>
816             vec![],
817     }
818 }
819
820 /// This computes the arity of a constructor. The arity of a constructor
821 /// is how many subpattern patterns of that constructor should be expanded to.
822 ///
823 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
824 /// A struct pattern's arity is the number of fields it contains, etc.
825 pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
826     debug!("constructor_arity({:?}, {:?})", ctor, ty);
827     match ty.sty {
828         ty::TyTuple(ref fs) => fs.len(),
829         ty::TyBox(_) => 1,
830         ty::TySlice(_) => match *ctor {
831             Slice(length) => length,
832             ConstantValue(_) => 0,
833             _ => bug!()
834         },
835         ty::TyRef(..) => 1,
836         ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
837             ctor.variant_for_adt(adt).fields.len()
838         }
839         ty::TyArray(_, n) => n,
840         _ => 0
841     }
842 }
843
844 fn range_covered_by_constructor(tcx: TyCtxt, span: Span,
845                                 ctor: &Constructor,
846                                 from: &ConstVal, to: &ConstVal)
847                                 -> Result<bool, ErrorReported> {
848     let (c_from, c_to) = match *ctor {
849         ConstantValue(ref value)        => (value, value),
850         ConstantRange(ref from, ref to) => (from, to),
851         Single                          => return Ok(true),
852         _                               => bug!()
853     };
854     let cmp_from = compare_const_vals(tcx, span, c_from, from)?;
855     let cmp_to = compare_const_vals(tcx, span, c_to, to)?;
856     Ok(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
857 }
858
859 fn wrap_pat<'a, 'b, 'tcx>(cx: &MatchCheckCtxt<'b, 'tcx>,
860                           pat: &'a Pat)
861                           -> (&'a Pat, Option<Ty<'tcx>>)
862 {
863     let pat_ty = cx.tcx.pat_ty(pat);
864     (pat, Some(match pat.node {
865         PatKind::Binding(hir::BindByRef(..), _, _) => {
866             pat_ty.builtin_deref(false, NoPreference).unwrap().ty
867         }
868         _ => pat_ty
869     }))
870 }
871
872 /// This is the main specialization step. It expands the first pattern in the given row
873 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
874 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
875 ///
876 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
877 /// different patterns.
878 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
879 /// fields filled with wild patterns.
880 pub fn specialize<'a, 'b, 'tcx>(
881     cx: &MatchCheckCtxt<'b, 'tcx>,
882     r: &[(&'a Pat, Option<Ty<'tcx>>)],
883     constructor: &Constructor, col: usize, arity: usize)
884     -> Option<Vec<(&'a Pat, Option<Ty<'tcx>>)>>
885 {
886     let pat = raw_pat(r[col].0);
887     let &Pat {
888         id: pat_id, ref node, span: pat_span
889     } = pat;
890     let wpat = |pat: &'a Pat| wrap_pat(cx, pat);
891     let dummy_pat = (DUMMY_WILD_PAT, None);
892
893     let head: Option<Vec<(&Pat, Option<Ty>)>> = match *node {
894         PatKind::Binding(..) | PatKind::Wild =>
895             Some(vec![dummy_pat; arity]),
896
897         PatKind::Path(..) => {
898             match cx.tcx.expect_def(pat_id) {
899                 Def::Const(..) | Def::AssociatedConst(..) =>
900                     span_bug!(pat_span, "const pattern should've \
901                                          been rewritten"),
902                 Def::Variant(_, id) if *constructor != Variant(id) => None,
903                 Def::Variant(..) | Def::Struct(..) => Some(Vec::new()),
904                 def => span_bug!(pat_span, "specialize: unexpected \
905                                           definition {:?}", def),
906             }
907         }
908
909         PatKind::TupleStruct(_, ref args, ddpos) => {
910             match cx.tcx.expect_def(pat_id) {
911                 Def::Const(..) | Def::AssociatedConst(..) =>
912                     span_bug!(pat_span, "const pattern should've \
913                                          been rewritten"),
914                 Def::Variant(_, id) if *constructor != Variant(id) => None,
915                 Def::Variant(..) | Def::Struct(..) => {
916                     match ddpos {
917                         Some(ddpos) => {
918                             let mut pats: Vec<_> = args[..ddpos].iter().map(|p| {
919                                 wpat(p)
920                             }).collect();
921                             pats.extend(repeat((DUMMY_WILD_PAT, None)).take(arity - args.len()));
922                             pats.extend(args[ddpos..].iter().map(|p| wpat(p)));
923                             Some(pats)
924                         }
925                         None => Some(args.iter().map(|p| wpat(p)).collect())
926                     }
927                 }
928                 _ => None
929             }
930         }
931
932         PatKind::Struct(_, ref pattern_fields, _) => {
933             let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
934             let variant = constructor.variant_for_adt(adt);
935             let def_variant = adt.variant_of_def(cx.tcx.expect_def(pat_id));
936             if variant.did == def_variant.did {
937                 Some(variant.fields.iter().map(|sf| {
938                     match pattern_fields.iter().find(|f| f.node.name == sf.name) {
939                         Some(ref f) => wpat(&f.node.pat),
940                         _ => dummy_pat
941                     }
942                 }).collect())
943             } else {
944                 None
945             }
946         }
947
948         PatKind::Tuple(ref args, Some(ddpos)) => {
949             let mut pats: Vec<_> = args[..ddpos].iter().map(|p| wpat(p)).collect();
950             pats.extend(repeat(dummy_pat).take(arity - args.len()));
951             pats.extend(args[ddpos..].iter().map(|p| wpat(p)));
952             Some(pats)
953         }
954         PatKind::Tuple(ref args, None) =>
955             Some(args.iter().map(|p| wpat(&**p)).collect()),
956
957         PatKind::Box(ref inner) | PatKind::Ref(ref inner, _) =>
958             Some(vec![wpat(&**inner)]),
959
960         PatKind::Lit(ref expr) => {
961             if let Some(&ty::TyS { sty: ty::TyRef(_, mt), .. }) = r[col].1 {
962                 // HACK: handle string literals. A string literal pattern
963                 // serves both as an unary reference pattern and as a
964                 // nullary value pattern, depending on the type.
965                 Some(vec![(pat, Some(mt.ty))])
966             } else {
967                 let expr_value = eval_const_expr(cx.tcx, &expr);
968                 match range_covered_by_constructor(
969                     cx.tcx, expr.span, constructor, &expr_value, &expr_value
970                 ) {
971                     Ok(true) => Some(vec![]),
972                     Ok(false) => None,
973                     Err(ErrorReported) => None,
974                 }
975             }
976         }
977
978         PatKind::Range(ref from, ref to) => {
979             let from_value = eval_const_expr(cx.tcx, &from);
980             let to_value = eval_const_expr(cx.tcx, &to);
981             match range_covered_by_constructor(
982                 cx.tcx, pat_span, constructor, &from_value, &to_value
983             ) {
984                 Ok(true) => Some(vec![]),
985                 Ok(false) => None,
986                 Err(ErrorReported) => None,
987             }
988         }
989
990         PatKind::Vec(ref before, ref slice, ref after) => {
991             let pat_len = before.len() + after.len();
992             match *constructor {
993                 Single => {
994                     // Fixed-length vectors.
995                     Some(
996                         before.iter().map(|p| wpat(p)).chain(
997                         repeat(dummy_pat).take(arity - pat_len).chain(
998                         after.iter().map(|p| wpat(p))
999                     )).collect())
1000                 },
1001                 Slice(length) if pat_len <= length && slice.is_some() => {
1002                     Some(
1003                         before.iter().map(|p| wpat(p)).chain(
1004                         repeat(dummy_pat).take(arity - pat_len).chain(
1005                         after.iter().map(|p| wpat(p))
1006                     )).collect())
1007                 }
1008                 Slice(length) if pat_len == length => {
1009                     Some(
1010                         before.iter().map(|p| wpat(p)).chain(
1011                         after.iter().map(|p| wpat(p))
1012                     ).collect())
1013                 }
1014                 SliceWithSubslice(prefix, suffix)
1015                     if before.len() == prefix
1016                         && after.len() == suffix
1017                         && slice.is_some() => {
1018                     // this is used by trans::_match only
1019                     let mut pats: Vec<_> = before.iter()
1020                         .map(|p| (&**p, None)).collect();
1021                     pats.extend(after.iter().map(|p| (&**p, None)));
1022                     Some(pats)
1023                 }
1024                 _ => None
1025             }
1026         }
1027     };
1028     debug!("specialize({:?}, {:?}) = {:?}", r[col], arity, head);
1029
1030     head.map(|mut head| {
1031         head.extend_from_slice(&r[..col]);
1032         head.extend_from_slice(&r[col + 1..]);
1033         head
1034     })
1035 }
1036
1037 fn check_local(cx: &mut MatchCheckCtxt, loc: &hir::Local) {
1038     intravisit::walk_local(cx, loc);
1039
1040     let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
1041     check_irrefutable(cx, &pat, false);
1042
1043     // Check legality of move bindings and `@` patterns.
1044     check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1045     check_legality_of_bindings_in_at_patterns(cx, &loc.pat);
1046 }
1047
1048 fn check_fn(cx: &mut MatchCheckCtxt,
1049             kind: FnKind,
1050             decl: &hir::FnDecl,
1051             body: &hir::Block,
1052             sp: Span,
1053             fn_id: NodeId) {
1054     match kind {
1055         FnKind::Closure(_) => {}
1056         _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1057     }
1058
1059     intravisit::walk_fn(cx, kind, decl, body, sp, fn_id);
1060
1061     for input in &decl.inputs {
1062         check_irrefutable(cx, &input.pat, true);
1063         check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1064         check_legality_of_bindings_in_at_patterns(cx, &input.pat);
1065     }
1066 }
1067
1068 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1069     let origin = if is_fn_arg {
1070         "function argument"
1071     } else {
1072         "local binding"
1073     };
1074
1075     is_refutable(cx, pat, |uncovered_pat| {
1076         span_err!(cx.tcx.sess, pat.span, E0005,
1077             "refutable pattern in {}: `{}` not covered",
1078             origin,
1079             pat_to_string(uncovered_pat),
1080         );
1081     });
1082 }
1083
1084 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1085     F: FnOnce(&Pat) -> A,
1086 {
1087     let pats = Matrix(vec!(vec!(wrap_pat(cx, pat))));
1088     match is_useful(cx, &pats, &[(DUMMY_WILD_PAT, None)], ConstructWitness) {
1089         UsefulWithWitness(pats) => Some(refutable(&pats[0])),
1090         NotUseful => None,
1091         Useful => bug!()
1092     }
1093 }
1094
1095 // Legality of move bindings checking
1096 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1097                                    has_guard: bool,
1098                                    pats: &[P<Pat>]) {
1099     let mut by_ref_span = None;
1100     for pat in pats {
1101         pat_bindings(&pat, |bm, _, span, _path| {
1102             if let hir::BindByRef(..) = bm {
1103                 by_ref_span = Some(span);
1104             }
1105         })
1106     }
1107
1108     let check_move = |p: &Pat, sub: Option<&Pat>| {
1109         // check legality of moving out of the enum
1110
1111         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1112         if sub.map_or(false, |p| pat_contains_bindings(&p)) {
1113             struct_span_err!(cx.tcx.sess, p.span, E0007,
1114                              "cannot bind by-move with sub-bindings")
1115                 .span_label(p.span, &format!("binds an already bound by-move value by moving it"))
1116                 .emit();
1117         } else if has_guard {
1118             struct_span_err!(cx.tcx.sess, p.span, E0008,
1119                       "cannot bind by-move into a pattern guard")
1120                 .span_label(p.span, &format!("moves value into pattern guard"))
1121                 .emit();
1122         } else if by_ref_span.is_some() {
1123             let mut err = struct_span_err!(cx.tcx.sess, p.span, E0009,
1124                                            "cannot bind by-move and by-ref in the same pattern");
1125             span_note!(&mut err, by_ref_span.unwrap(), "by-ref binding occurs here");
1126             err.emit();
1127         }
1128     };
1129
1130     for pat in pats {
1131         pat.walk(|p| {
1132             if let PatKind::Binding(hir::BindByValue(..), _, ref sub) = p.node {
1133                 let pat_ty = cx.tcx.node_id_to_type(p.id);
1134                 //FIXME: (@jroesch) this code should be floated up as well
1135                 cx.tcx.infer_ctxt(None, Some(cx.param_env.clone()),
1136                                   Reveal::NotSpecializable).enter(|infcx| {
1137                     if infcx.type_moves_by_default(pat_ty, pat.span) {
1138                         check_move(p, sub.as_ref().map(|p| &**p));
1139                     }
1140                 });
1141             }
1142             true
1143         });
1144     }
1145 }
1146
1147 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1148 /// assign.
1149 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1150                                          guard: &hir::Expr) {
1151     cx.tcx.infer_ctxt(None, Some(cx.param_env.clone()),
1152                       Reveal::NotSpecializable).enter(|infcx| {
1153         let mut checker = MutationChecker {
1154             cx: cx,
1155         };
1156         let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1157         visitor.walk_expr(guard);
1158     });
1159 }
1160
1161 struct MutationChecker<'a, 'gcx: 'a> {
1162     cx: &'a MatchCheckCtxt<'a, 'gcx>,
1163 }
1164
1165 impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
1166     fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1167     fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1168     fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1169     fn borrow(&mut self,
1170               _: NodeId,
1171               span: Span,
1172               _: cmt,
1173               _: Region,
1174               kind: BorrowKind,
1175               _: LoanCause) {
1176         match kind {
1177             MutBorrow => {
1178                 span_err!(self.cx.tcx.sess, span, E0301,
1179                           "cannot mutably borrow in a pattern guard")
1180             }
1181             ImmBorrow | UniqueImmBorrow => {}
1182         }
1183     }
1184     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1185     fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1186         match mode {
1187             MutateMode::JustWrite | MutateMode::WriteAndRead => {
1188                 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1189             }
1190             MutateMode::Init => {}
1191         }
1192     }
1193 }
1194
1195 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1196 /// because of the way rvalues are handled in the borrow check. (See issue
1197 /// #14587.)
1198 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1199     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1200 }
1201
1202 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1203     cx: &'a MatchCheckCtxt<'b, 'tcx>,
1204     bindings_allowed: bool
1205 }
1206
1207 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1208     fn visit_pat(&mut self, pat: &Pat) {
1209         match pat.node {
1210             PatKind::Binding(_, _, ref subpat) => {
1211                 if !self.bindings_allowed {
1212                     span_err!(self.cx.tcx.sess, pat.span, E0303,
1213                               "pattern bindings are not allowed after an `@`");
1214                 }
1215
1216                 if subpat.is_some() {
1217                     let bindings_were_allowed = self.bindings_allowed;
1218                     self.bindings_allowed = false;
1219                     intravisit::walk_pat(self, pat);
1220                     self.bindings_allowed = bindings_were_allowed;
1221                 }
1222             }
1223             _ => intravisit::walk_pat(self, pat),
1224         }
1225     }
1226 }