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