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