]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/_match.rs
rollup merge of #21396: japaric/no-parens-in-range
[rust.git] / src / librustc_trans / trans / _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 //! # Compilation of match statements
12 //!
13 //! I will endeavor to explain the code as best I can.  I have only a loose
14 //! understanding of some parts of it.
15 //!
16 //! ## Matching
17 //!
18 //! The basic state of the code is maintained in an array `m` of `Match`
19 //! objects.  Each `Match` describes some list of patterns, all of which must
20 //! match against the current list of values.  If those patterns match, then
21 //! the arm listed in the match is the correct arm.  A given arm may have
22 //! multiple corresponding match entries, one for each alternative that
23 //! remains.  As we proceed these sets of matches are adjusted by the various
24 //! `enter_XXX()` functions, each of which adjusts the set of options given
25 //! some information about the value which has been matched.
26 //!
27 //! So, initially, there is one value and N matches, each of which have one
28 //! constituent pattern.  N here is usually the number of arms but may be
29 //! greater, if some arms have multiple alternatives.  For example, here:
30 //!
31 //!     enum Foo { A, B(int), C(uint, uint) }
32 //!     match foo {
33 //!         A => ...,
34 //!         B(x) => ...,
35 //!         C(1u, 2) => ...,
36 //!         C(_) => ...
37 //!     }
38 //!
39 //! The value would be `foo`.  There would be four matches, each of which
40 //! contains one pattern (and, in one case, a guard).  We could collect the
41 //! various options and then compile the code for the case where `foo` is an
42 //! `A`, a `B`, and a `C`.  When we generate the code for `C`, we would (1)
43 //! drop the two matches that do not match a `C` and (2) expand the other two
44 //! into two patterns each.  In the first case, the two patterns would be `1u`
45 //! and `2`, and the in the second case the _ pattern would be expanded into
46 //! `_` and `_`.  The two values are of course the arguments to `C`.
47 //!
48 //! Here is a quick guide to the various functions:
49 //!
50 //! - `compile_submatch()`: The main workhouse.  It takes a list of values and
51 //!   a list of matches and finds the various possibilities that could occur.
52 //!
53 //! - `enter_XXX()`: modifies the list of matches based on some information
54 //!   about the value that has been matched.  For example,
55 //!   `enter_rec_or_struct()` adjusts the values given that a record or struct
56 //!   has been matched.  This is an infallible pattern, so *all* of the matches
57 //!   must be either wildcards or record/struct patterns.  `enter_opt()`
58 //!   handles the fallible cases, and it is correspondingly more complex.
59 //!
60 //! ## Bindings
61 //!
62 //! We store information about the bound variables for each arm as part of the
63 //! per-arm `ArmData` struct.  There is a mapping from identifiers to
64 //! `BindingInfo` structs.  These structs contain the mode/id/type of the
65 //! binding, but they also contain an LLVM value which points at an alloca
66 //! called `llmatch`. For by value bindings that are Copy, we also create
67 //! an extra alloca that we copy the matched value to so that any changes
68 //! we do to our copy is not reflected in the original and vice-versa.
69 //! We don't do this if it's a move since the original value can't be used
70 //! and thus allowing us to cheat in not creating an extra alloca.
71 //!
72 //! The `llmatch` binding always stores a pointer into the value being matched
73 //! which points at the data for the binding.  If the value being matched has
74 //! type `T`, then, `llmatch` will point at an alloca of type `T*` (and hence
75 //! `llmatch` has type `T**`).  So, if you have a pattern like:
76 //!
77 //!    let a: A = ...;
78 //!    let b: B = ...;
79 //!    match (a, b) { (ref c, d) => { ... } }
80 //!
81 //! For `c` and `d`, we would generate allocas of type `C*` and `D*`
82 //! respectively.  These are called the `llmatch`.  As we match, when we come
83 //! up against an identifier, we store the current pointer into the
84 //! corresponding alloca.
85 //!
86 //! Once a pattern is completely matched, and assuming that there is no guard
87 //! pattern, we will branch to a block that leads to the body itself.  For any
88 //! by-value bindings, this block will first load the ptr from `llmatch` (the
89 //! one of type `D*`) and then load a second time to get the actual value (the
90 //! one of type `D`). For by ref bindings, the value of the local variable is
91 //! simply the first alloca.
92 //!
93 //! So, for the example above, we would generate a setup kind of like this:
94 //!
95 //!        +-------+
96 //!        | Entry |
97 //!        +-------+
98 //!            |
99 //!        +--------------------------------------------+
100 //!        | llmatch_c = (addr of first half of tuple)  |
101 //!        | llmatch_d = (addr of second half of tuple) |
102 //!        +--------------------------------------------+
103 //!            |
104 //!        +--------------------------------------+
105 //!        | *llbinding_d = **llmatch_d           |
106 //!        +--------------------------------------+
107 //!
108 //! If there is a guard, the situation is slightly different, because we must
109 //! execute the guard code.  Moreover, we need to do so once for each of the
110 //! alternatives that lead to the arm, because if the guard fails, they may
111 //! have different points from which to continue the search. Therefore, in that
112 //! case, we generate code that looks more like:
113 //!
114 //!        +-------+
115 //!        | Entry |
116 //!        +-------+
117 //!            |
118 //!        +-------------------------------------------+
119 //!        | llmatch_c = (addr of first half of tuple) |
120 //!        | llmatch_d = (addr of first half of tuple) |
121 //!        +-------------------------------------------+
122 //!            |
123 //!        +-------------------------------------------------+
124 //!        | *llbinding_d = **llmatch_d                      |
125 //!        | check condition                                 |
126 //!        | if false { goto next case }                     |
127 //!        | if true { goto body }                           |
128 //!        +-------------------------------------------------+
129 //!
130 //! The handling for the cleanups is a bit... sensitive.  Basically, the body
131 //! is the one that invokes `add_clean()` for each binding.  During the guard
132 //! evaluation, we add temporary cleanups and revoke them after the guard is
133 //! evaluated (it could fail, after all). Note that guards and moves are
134 //! just plain incompatible.
135 //!
136 //! Some relevant helper functions that manage bindings:
137 //! - `create_bindings_map()`
138 //! - `insert_lllocals()`
139 //!
140 //!
141 //! ## Notes on vector pattern matching.
142 //!
143 //! Vector pattern matching is surprisingly tricky. The problem is that
144 //! the structure of the vector isn't fully known, and slice matches
145 //! can be done on subparts of it.
146 //!
147 //! The way that vector pattern matches are dealt with, then, is as
148 //! follows. First, we make the actual condition associated with a
149 //! vector pattern simply a vector length comparison. So the pattern
150 //! [1, .. x] gets the condition "vec len >= 1", and the pattern
151 //! [.. x] gets the condition "vec len >= 0". The problem here is that
152 //! having the condition "vec len >= 1" hold clearly does not mean that
153 //! only a pattern that has exactly that condition will match. This
154 //! means that it may well be the case that a condition holds, but none
155 //! of the patterns matching that condition match; to deal with this,
156 //! when doing vector length matches, we have match failures proceed to
157 //! the next condition to check.
158 //!
159 //! There are a couple more subtleties to deal with. While the "actual"
160 //! condition associated with vector length tests is simply a test on
161 //! the vector length, the actual vec_len Opt entry contains more
162 //! information used to restrict which matches are associated with it.
163 //! So that all matches in a submatch are matching against the same
164 //! values from inside the vector, they are split up by how many
165 //! elements they match at the front and at the back of the vector. In
166 //! order to make sure that arms are properly checked in order, even
167 //! with the overmatching conditions, each vec_len Opt entry is
168 //! associated with a range of matches.
169 //! Consider the following:
170 //!
171 //!   match &[1, 2, 3] {
172 //!       [1, 1, .. _] => 0,
173 //!       [1, 2, 2, .. _] => 1,
174 //!       [1, 2, 3, .. _] => 2,
175 //!       [1, 2, .. _] => 3,
176 //!       _ => 4
177 //!   }
178 //! The proper arm to match is arm 2, but arms 0 and 3 both have the
179 //! condition "len >= 2". If arm 3 was lumped in with arm 0, then the
180 //! wrong branch would be taken. Instead, vec_len Opts are associated
181 //! with a contiguous range of matches that have the same "shape".
182 //! This is sort of ugly and requires a bunch of special handling of
183 //! vec_len options.
184
185 pub use self::BranchKind::*;
186 pub use self::OptResult::*;
187 pub use self::TransBindingMode::*;
188 use self::Opt::*;
189 use self::FailureHandler::*;
190
191 use back::abi;
192 use llvm::{ValueRef, BasicBlockRef};
193 use middle::check_match::StaticInliner;
194 use middle::check_match;
195 use middle::const_eval;
196 use middle::def::{self, DefMap};
197 use middle::expr_use_visitor as euv;
198 use middle::lang_items::StrEqFnLangItem;
199 use middle::mem_categorization as mc;
200 use middle::pat_util::*;
201 use trans::adt;
202 use trans::base::*;
203 use trans::build::{AddCase, And, BitCast, Br, CondBr, GEPi, InBoundsGEP, Load};
204 use trans::build::{Not, Store, Sub, add_comment};
205 use trans::build;
206 use trans::callee;
207 use trans::cleanup::{self, CleanupMethods};
208 use trans::common::*;
209 use trans::consts;
210 use trans::datum::*;
211 use trans::expr::{self, Dest};
212 use trans::tvec;
213 use trans::type_of;
214 use trans::debuginfo;
215 use middle::ty::{self, Ty};
216 use session::config::FullDebugInfo;
217 use util::common::indenter;
218 use util::nodemap::FnvHashMap;
219 use util::ppaux::{Repr, vec_map_to_string};
220
221 use std;
222 use std::iter::AdditiveIterator;
223 use std::rc::Rc;
224 use syntax::ast;
225 use syntax::ast::{DUMMY_NODE_ID, Ident};
226 use syntax::codemap::Span;
227 use syntax::fold::Folder;
228 use syntax::ptr::P;
229
230 #[derive(Copy, Show)]
231 struct ConstantExpr<'a>(&'a ast::Expr);
232
233 impl<'a> ConstantExpr<'a> {
234     fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
235         let ConstantExpr(expr) = self;
236         let ConstantExpr(other_expr) = other;
237         match const_eval::compare_lit_exprs(tcx, expr, other_expr) {
238             Some(val1) => val1 == 0,
239             None => panic!("compare_list_exprs: type mismatch"),
240         }
241     }
242 }
243
244 // An option identifying a branch (either a literal, an enum variant or a range)
245 #[derive(Show)]
246 enum Opt<'a, 'tcx> {
247     ConstantValue(ConstantExpr<'a>),
248     ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>),
249     Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId),
250     SliceLengthEqual(uint),
251     SliceLengthGreaterOrEqual(/* prefix length */ uint, /* suffix length */ uint),
252 }
253
254 impl<'a, 'tcx> Opt<'a, 'tcx> {
255     fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
256         match (self, other) {
257             (&ConstantValue(a), &ConstantValue(b)) => a.eq(b, tcx),
258             (&ConstantRange(a1, a2), &ConstantRange(b1, b2)) => {
259                 a1.eq(b1, tcx) && a2.eq(b2, tcx)
260             }
261             (&Variant(a_disr, ref a_repr, a_def), &Variant(b_disr, ref b_repr, b_def)) => {
262                 a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
263             }
264             (&SliceLengthEqual(a), &SliceLengthEqual(b)) => a == b,
265             (&SliceLengthGreaterOrEqual(a1, a2), &SliceLengthGreaterOrEqual(b1, b2)) => {
266                 a1 == b1 && a2 == b2
267             }
268             _ => false
269         }
270     }
271
272     fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
273         let _icx = push_ctxt("match::trans_opt");
274         let ccx = bcx.ccx();
275         match *self {
276             ConstantValue(ConstantExpr(lit_expr)) => {
277                 let lit_ty = ty::node_id_to_type(bcx.tcx(), lit_expr.id);
278                 let (llval, _) = consts::const_expr(ccx, &*lit_expr);
279                 let lit_datum = immediate_rvalue(llval, lit_ty);
280                 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
281                 SingleResult(Result::new(bcx, lit_datum.val))
282             }
283             ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2)) => {
284                 let (l1, _) = consts::const_expr(ccx, &**l1);
285                 let (l2, _) = consts::const_expr(ccx, &**l2);
286                 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
287             }
288             Variant(disr_val, ref repr, _) => {
289                 adt::trans_case(bcx, &**repr, disr_val)
290             }
291             SliceLengthEqual(length) => {
292                 SingleResult(Result::new(bcx, C_uint(ccx, length)))
293             }
294             SliceLengthGreaterOrEqual(prefix, suffix) => {
295                 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
296             }
297         }
298     }
299 }
300
301 #[derive(Copy, PartialEq)]
302 pub enum BranchKind {
303     NoBranch,
304     Single,
305     Switch,
306     Compare,
307     CompareSliceLength
308 }
309
310 pub enum OptResult<'blk, 'tcx: 'blk> {
311     SingleResult(Result<'blk, 'tcx>),
312     RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
313     LowerBound(Result<'blk, 'tcx>)
314 }
315
316 #[derive(Clone, Copy)]
317 pub enum TransBindingMode {
318     TrByCopy(/* llbinding */ ValueRef),
319     TrByMove,
320     TrByRef,
321 }
322
323 /// Information about a pattern binding:
324 /// - `llmatch` is a pointer to a stack slot.  The stack slot contains a
325 ///   pointer into the value being matched.  Hence, llmatch has type `T**`
326 ///   where `T` is the value being matched.
327 /// - `trmode` is the trans binding mode
328 /// - `id` is the node id of the binding
329 /// - `ty` is the Rust type of the binding
330 #[derive(Clone, Copy)]
331 pub struct BindingInfo<'tcx> {
332     pub llmatch: ValueRef,
333     pub trmode: TransBindingMode,
334     pub id: ast::NodeId,
335     pub span: Span,
336     pub ty: Ty<'tcx>,
337 }
338
339 type BindingsMap<'tcx> = FnvHashMap<Ident, BindingInfo<'tcx>>;
340
341 struct ArmData<'p, 'blk, 'tcx: 'blk> {
342     bodycx: Block<'blk, 'tcx>,
343     arm: &'p ast::Arm,
344     bindings_map: BindingsMap<'tcx>
345 }
346
347 /// Info about Match.
348 /// If all `pats` are matched then arm `data` will be executed.
349 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
350 /// these pointers are stored in llmatch variables just before executing `data` arm.
351 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
352     pats: Vec<&'p ast::Pat>,
353     data: &'a ArmData<'p, 'blk, 'tcx>,
354     bound_ptrs: Vec<(Ident, ValueRef)>,
355 }
356
357 impl<'a, 'p, 'blk, 'tcx> Repr<'tcx> for Match<'a, 'p, 'blk, 'tcx> {
358     fn repr(&self, tcx: &ty::ctxt) -> String {
359         if tcx.sess.verbose() {
360             // for many programs, this just take too long to serialize
361             self.pats.repr(tcx)
362         } else {
363             format!("{} pats", self.pats.len())
364         }
365     }
366 }
367
368 fn has_nested_bindings(m: &[Match], col: uint) -> bool {
369     for br in m.iter() {
370         match br.pats[col].node {
371             ast::PatIdent(_, _, Some(_)) => return true,
372             _ => ()
373         }
374     }
375     return false;
376 }
377
378 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
379                                               m: &[Match<'a, 'p, 'blk, 'tcx>],
380                                               col: uint,
381                                               val: ValueRef)
382                                               -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
383     debug!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
384            bcx.to_str(),
385            m.repr(bcx.tcx()),
386            col,
387            bcx.val_to_string(val));
388     let _indenter = indenter();
389
390     m.iter().map(|br| {
391         let mut bound_ptrs = br.bound_ptrs.clone();
392         let mut pat = br.pats[col];
393         loop {
394             pat = match pat.node {
395                 ast::PatIdent(_, ref path, Some(ref inner)) => {
396                     bound_ptrs.push((path.node, val));
397                     &**inner
398                 },
399                 _ => break
400             }
401         }
402
403         let mut pats = br.pats.clone();
404         pats[col] = pat;
405         Match {
406             pats: pats,
407             data: &*br.data,
408             bound_ptrs: bound_ptrs
409         }
410     }).collect()
411 }
412
413 fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
414                                           dm: &DefMap,
415                                           m: &[Match<'a, 'p, 'blk, 'tcx>],
416                                           col: uint,
417                                           val: ValueRef,
418                                           mut e: F)
419                                           -> Vec<Match<'a, 'p, 'blk, 'tcx>> where
420     F: FnMut(&[&'p ast::Pat]) -> Option<Vec<&'p ast::Pat>>,
421 {
422     debug!("enter_match(bcx={}, m={}, col={}, val={})",
423            bcx.to_str(),
424            m.repr(bcx.tcx()),
425            col,
426            bcx.val_to_string(val));
427     let _indenter = indenter();
428
429     m.iter().filter_map(|br| {
430         e(&br.pats[]).map(|pats| {
431             let this = br.pats[col];
432             let mut bound_ptrs = br.bound_ptrs.clone();
433             match this.node {
434                 ast::PatIdent(_, ref path, None) => {
435                     if pat_is_binding(dm, &*this) {
436                         bound_ptrs.push((path.node, val));
437                     }
438                 }
439                 ast::PatVec(ref before, Some(ref slice), ref after) => {
440                     if let ast::PatIdent(_, ref path, None) = slice.node {
441                         let subslice_val = bind_subslice_pat(
442                             bcx, this.id, val,
443                             before.len(), after.len());
444                         bound_ptrs.push((path.node, subslice_val));
445                     }
446                 }
447                 _ => {}
448             }
449             Match {
450                 pats: pats,
451                 data: br.data,
452                 bound_ptrs: bound_ptrs
453             }
454         })
455     }).collect()
456 }
457
458 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
459                                      dm: &DefMap,
460                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
461                                      col: uint,
462                                      val: ValueRef)
463                                      -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
464     debug!("enter_default(bcx={}, m={}, col={}, val={})",
465            bcx.to_str(),
466            m.repr(bcx.tcx()),
467            col,
468            bcx.val_to_string(val));
469     let _indenter = indenter();
470
471     // Collect all of the matches that can match against anything.
472     enter_match(bcx, dm, m, col, val, |pats| {
473         if pat_is_binding_or_wild(dm, &*pats[col]) {
474             let mut r = pats[..col].to_vec();
475             r.push_all(&pats[col + 1..]);
476             Some(r)
477         } else {
478             None
479         }
480     })
481 }
482
483 // <pcwalton> nmatsakis: what does enter_opt do?
484 // <pcwalton> in trans/match
485 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
486 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
487 //             patterns as needed
488 // <nmatsakis> yeah, at some point I kind of achieved some level of
489 //             understanding
490 // <nmatsakis> anyhow, they adjust the patterns given that something of that
491 //             kind has been found
492 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
493 //             said
494 // <nmatsakis> enter_match() kind of embodies the generic code
495 // <nmatsakis> it is provided with a function that tests each pattern to see
496 //             if it might possibly apply and so forth
497 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
498 // <nmatsakis> then _ would be expanded to (_, _)
499 // <nmatsakis> one spot for each of the sub-patterns
500 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
501 //             cases
502 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
503 //             are infallible patterns
504 // <nmatsakis> so all patterns must either be records (resp. tuples) or
505 //             wildcards
506
507 /// The above is now outdated in that enter_match() now takes a function that
508 /// takes the complete row of patterns rather than just the first one.
509 /// Also, most of the enter_() family functions have been unified with
510 /// the check_match specialization step.
511 fn enter_opt<'a, 'p, 'blk, 'tcx>(
512              bcx: Block<'blk, 'tcx>,
513              _: ast::NodeId,
514              dm: &DefMap,
515              m: &[Match<'a, 'p, 'blk, 'tcx>],
516              opt: &Opt,
517              col: uint,
518              variant_size: uint,
519              val: ValueRef)
520              -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
521     debug!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})",
522            bcx.to_str(),
523            m.repr(bcx.tcx()),
524            *opt,
525            col,
526            bcx.val_to_string(val));
527     let _indenter = indenter();
528
529     let ctor = match opt {
530         &ConstantValue(ConstantExpr(expr)) => check_match::ConstantValue(
531             const_eval::eval_const_expr(bcx.tcx(), &*expr)
532         ),
533         &ConstantRange(ConstantExpr(lo), ConstantExpr(hi)) => check_match::ConstantRange(
534             const_eval::eval_const_expr(bcx.tcx(), &*lo),
535             const_eval::eval_const_expr(bcx.tcx(), &*hi)
536         ),
537         &SliceLengthEqual(n) =>
538             check_match::Slice(n),
539         &SliceLengthGreaterOrEqual(before, after) =>
540             check_match::SliceWithSubslice(before, after),
541         &Variant(_, _, def_id) =>
542             check_match::Constructor::Variant(def_id)
543     };
544
545     let param_env = ty::empty_parameter_environment(bcx.tcx());
546     let mcx = check_match::MatchCheckCtxt {
547         tcx: bcx.tcx(),
548         param_env: param_env,
549     };
550     enter_match(bcx, dm, m, col, val, |pats|
551         check_match::specialize(&mcx, &pats[], &ctor, col, variant_size)
552     )
553 }
554
555 // Returns the options in one column of matches. An option is something that
556 // needs to be conditionally matched at runtime; for example, the discriminant
557 // on a set of enum variants or a literal.
558 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
559                                     m: &[Match<'a, 'p, 'blk, 'tcx>], col: uint)
560                                     -> Vec<Opt<'p, 'tcx>> {
561     let tcx = bcx.tcx();
562
563     let mut found: Vec<Opt> = vec![];
564     for br in m.iter() {
565         let cur = br.pats[col];
566         let opt = match cur.node {
567             ast::PatLit(ref l) => ConstantValue(ConstantExpr(&**l)),
568             ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
569                 // This is either an enum variant or a variable binding.
570                 let opt_def = tcx.def_map.borrow().get(&cur.id).cloned();
571                 match opt_def {
572                     Some(def::DefVariant(enum_id, var_id, _)) => {
573                         let variant = ty::enum_variant_with_id(tcx, enum_id, var_id);
574                         Variant(variant.disr_val, adt::represent_node(bcx, cur.id), var_id)
575                     }
576                     _ => continue
577                 }
578             }
579             ast::PatRange(ref l1, ref l2) => {
580                 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2))
581             }
582             ast::PatVec(ref before, None, ref after) => {
583                 SliceLengthEqual(before.len() + after.len())
584             }
585             ast::PatVec(ref before, Some(_), ref after) => {
586                 SliceLengthGreaterOrEqual(before.len(), after.len())
587             }
588             _ => continue
589         };
590
591         if !found.iter().any(|x| x.eq(&opt, tcx)) {
592             found.push(opt);
593         }
594     }
595     found
596 }
597
598 struct ExtractedBlock<'blk, 'tcx: 'blk> {
599     vals: Vec<ValueRef>,
600     bcx: Block<'blk, 'tcx>,
601 }
602
603 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
604                                     repr: &adt::Repr<'tcx>,
605                                     disr_val: ty::Disr,
606                                     val: ValueRef)
607                                     -> ExtractedBlock<'blk, 'tcx> {
608     let _icx = push_ctxt("match::extract_variant_args");
609     let args = range(0, adt::num_args(repr, disr_val)).map(|i| {
610         adt::trans_field_ptr(bcx, repr, val, disr_val, i)
611     }).collect();
612
613     ExtractedBlock { vals: args, bcx: bcx }
614 }
615
616 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
617 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
618 fn match_datum<'tcx>(val: ValueRef, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
619     Datum::new(val, left_ty, Lvalue)
620 }
621
622 fn bind_subslice_pat(bcx: Block,
623                      pat_id: ast::NodeId,
624                      val: ValueRef,
625                      offset_left: uint,
626                      offset_right: uint) -> ValueRef {
627     let _icx = push_ctxt("match::bind_subslice_pat");
628     let vec_ty = node_id_type(bcx, pat_id);
629     let vt = tvec::vec_types(bcx, ty::sequence_element_type(bcx.tcx(), ty::type_content(vec_ty)));
630     let vec_datum = match_datum(val, vec_ty);
631     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
632
633     let slice_begin = InBoundsGEP(bcx, base, &[C_uint(bcx.ccx(), offset_left)]);
634     let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
635     let slice_len = Sub(bcx, len, slice_len_offset);
636     let slice_ty = ty::mk_slice(bcx.tcx(),
637                                 bcx.tcx().mk_region(ty::ReStatic),
638                                 ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable});
639     let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
640     Store(bcx, slice_begin,
641           GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_ADDR]));
642     Store(bcx, slice_len, GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_EXTRA]));
643     scratch.val
644 }
645
646 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
647                                  left_ty: Ty,
648                                  before: uint,
649                                  after: uint,
650                                  val: ValueRef)
651                                  -> ExtractedBlock<'blk, 'tcx> {
652     let _icx = push_ctxt("match::extract_vec_elems");
653     let vec_datum = match_datum(val, left_ty);
654     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
655     let mut elems = vec![];
656     elems.extend(range(0, before).map(|i| GEPi(bcx, base, &[i])));
657     elems.extend(range(0, after).rev().map(|i| {
658         InBoundsGEP(bcx, base, &[
659             Sub(bcx, len, C_uint(bcx.ccx(), i + 1))
660         ])
661     }));
662     ExtractedBlock { vals: elems, bcx: bcx }
663 }
664
665 // Macro for deciding whether any of the remaining matches fit a given kind of
666 // pattern.  Note that, because the macro is well-typed, either ALL of the
667 // matches should fit that sort of pattern or NONE (however, some of the
668 // matches may be wildcards like _ or identifiers).
669 macro_rules! any_pat {
670     ($m:expr, $col:expr, $pattern:pat) => (
671         ($m).iter().any(|br| {
672             match br.pats[$col].node {
673                 $pattern => true,
674                 _ => false
675             }
676         })
677     )
678 }
679
680 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
681     any_pat!(m, col, ast::PatBox(_))
682 }
683
684 fn any_region_pat(m: &[Match], col: uint) -> bool {
685     any_pat!(m, col, ast::PatRegion(..))
686 }
687
688 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: uint) -> bool {
689     m.iter().any(|br| {
690         let pat = br.pats[col];
691         match pat.node {
692             ast::PatTup(_) => true,
693             ast::PatStruct(..) => {
694                 match tcx.def_map.borrow().get(&pat.id) {
695                     Some(&def::DefVariant(..)) => false,
696                     _ => true,
697                 }
698             }
699             ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
700                 match tcx.def_map.borrow().get(&pat.id) {
701                     Some(&def::DefStruct(..)) => true,
702                     _ => false
703                 }
704             }
705             _ => false
706         }
707     })
708 }
709
710 /// What to do when the pattern match fails.
711 enum FailureHandler {
712     Infallible,
713     JumpToBasicBlock(BasicBlockRef),
714     Unreachable
715 }
716
717 impl FailureHandler {
718     fn is_fallible(&self) -> bool {
719         match *self {
720             Infallible => false,
721             _ => true
722         }
723     }
724
725     fn is_infallible(&self) -> bool {
726         !self.is_fallible()
727     }
728
729     fn handle_fail(&self, bcx: Block) {
730         match *self {
731             Infallible =>
732                 panic!("attempted to panic in a non-panicking panic handler!"),
733             JumpToBasicBlock(basic_block) =>
734                 Br(bcx, basic_block),
735             Unreachable =>
736                 build::Unreachable(bcx)
737         }
738     }
739 }
740
741 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<uint> {
742     fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
743         match pat.node {
744             ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
745             _ if pat_is_refutable(def_map, pat) => 1u,
746             _ => 0u
747         }
748     }
749
750     let column_score = |&: m: &[Match], col: uint| -> uint {
751         let total_score = m.iter()
752             .map(|row| row.pats[col])
753             .map(|pat| pat_score(def_map, pat))
754             .sum();
755
756         // Irrefutable columns always go first, they'd only be duplicated in the branches.
757         if total_score == 0 {
758             std::uint::MAX
759         } else {
760             total_score
761         }
762     };
763
764     let column_contains_any_nonwild_patterns = |&: &col: &uint| -> bool {
765         m.iter().any(|row| match row.pats[col].node {
766             ast::PatWild(_) => false,
767             _ => true
768         })
769     };
770
771     range(0, m[0].pats.len())
772         .filter(column_contains_any_nonwild_patterns)
773         .map(|col| (col, column_score(m, col)))
774         .max_by(|&(_, score)| score)
775         .map(|(col, _)| col)
776 }
777
778 // Compiles a comparison between two things.
779 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
780                               lhs: ValueRef,
781                               rhs: ValueRef,
782                               rhs_t: Ty<'tcx>)
783                               -> Result<'blk, 'tcx> {
784     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
785                                lhs: ValueRef,
786                                rhs: ValueRef,
787                                rhs_t: Ty<'tcx>)
788                                -> Result<'blk, 'tcx> {
789         let did = langcall(cx,
790                            None,
791                            &format!("comparison of `{}`",
792                                    cx.ty_to_string(rhs_t))[],
793                            StrEqFnLangItem);
794         callee::trans_lang_call(cx, did, &[lhs, rhs], None)
795     }
796
797     let _icx = push_ctxt("compare_values");
798     if ty::type_is_scalar(rhs_t) {
799         let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
800         return Result::new(rs.bcx, rs.val);
801     }
802
803     match rhs_t.sty {
804         ty::ty_rptr(_, mt) => match mt.ty.sty {
805             ty::ty_str => compare_str(cx, lhs, rhs, rhs_t),
806             ty::ty_vec(ty, _) => match ty.sty {
807                 ty::ty_uint(ast::TyU8) => {
808                     // NOTE: cast &[u8] to &str and abuse the str_eq lang item,
809                     // which calls memcmp().
810                     let t = ty::mk_str_slice(cx.tcx(),
811                                              cx.tcx().mk_region(ty::ReStatic),
812                                              ast::MutImmutable);
813                     let lhs = BitCast(cx, lhs, type_of::type_of(cx.ccx(), t).ptr_to());
814                     let rhs = BitCast(cx, rhs, type_of::type_of(cx.ccx(), t).ptr_to());
815                     compare_str(cx, lhs, rhs, rhs_t)
816                 },
817                 _ => cx.sess().bug("only byte strings supported in compare_values"),
818             },
819             _ => cx.sess().bug("only string and byte strings supported in compare_values"),
820         },
821         _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
822     }
823 }
824
825 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
826 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
827                                bindings_map: &BindingsMap<'tcx>,
828                                cs: Option<cleanup::ScopeId>)
829                                -> Block<'blk, 'tcx> {
830     for (&ident, &binding_info) in bindings_map.iter() {
831         let llval = match binding_info.trmode {
832             // By value mut binding for a copy type: load from the ptr
833             // into the matched value and copy to our alloca
834             TrByCopy(llbinding) => {
835                 let llval = Load(bcx, binding_info.llmatch);
836                 let datum = Datum::new(llval, binding_info.ty, Lvalue);
837                 call_lifetime_start(bcx, llbinding);
838                 bcx = datum.store_to(bcx, llbinding);
839                 if let Some(cs) = cs {
840                     bcx.fcx.schedule_lifetime_end(cs, llbinding);
841                 }
842
843                 llbinding
844             },
845
846             // By value move bindings: load from the ptr into the matched value
847             TrByMove => Load(bcx, binding_info.llmatch),
848
849             // By ref binding: use the ptr into the matched value
850             TrByRef => binding_info.llmatch
851         };
852
853         let datum = Datum::new(llval, binding_info.ty, Lvalue);
854         if let Some(cs) = cs {
855             bcx.fcx.schedule_drop_and_zero_mem(cs, llval, binding_info.ty);
856             bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
857         }
858
859         debug!("binding {} to {}", binding_info.id, bcx.val_to_string(llval));
860         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
861         debuginfo::create_match_binding_metadata(bcx, ident, binding_info);
862     }
863     bcx
864 }
865
866 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
867                                      guard_expr: &ast::Expr,
868                                      data: &ArmData<'p, 'blk, 'tcx>,
869                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
870                                      vals: &[ValueRef],
871                                      chk: &FailureHandler,
872                                      has_genuine_default: bool)
873                                      -> Block<'blk, 'tcx> {
874     debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
875            bcx.to_str(),
876            bcx.expr_to_string(guard_expr),
877            m.repr(bcx.tcx()),
878            vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
879     let _indenter = indenter();
880
881     let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
882
883     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
884     let val = val.to_llbool(bcx);
885
886     for (_, &binding_info) in data.bindings_map.iter() {
887         if let TrByCopy(llbinding) = binding_info.trmode {
888             call_lifetime_end(bcx, llbinding);
889         }
890     }
891
892     with_cond(bcx, Not(bcx, val), |bcx| {
893         // Guard does not match: remove all bindings from the lllocals table
894         for (_, &binding_info) in data.bindings_map.iter() {
895             call_lifetime_end(bcx, binding_info.llmatch);
896             bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
897         }
898         match chk {
899             // If the default arm is the only one left, move on to the next
900             // condition explicitly rather than (possibly) falling back to
901             // the default arm.
902             &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
903                 chk.handle_fail(bcx);
904             }
905             _ => {
906                 compile_submatch(bcx, m, vals, chk, has_genuine_default);
907             }
908         };
909         bcx
910     })
911 }
912
913 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
914                                         m: &[Match<'a, 'p, 'blk, 'tcx>],
915                                         vals: &[ValueRef],
916                                         chk: &FailureHandler,
917                                         has_genuine_default: bool) {
918     debug!("compile_submatch(bcx={}, m={}, vals={})",
919            bcx.to_str(),
920            m.repr(bcx.tcx()),
921            vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
922     let _indenter = indenter();
923     let _icx = push_ctxt("match::compile_submatch");
924     let mut bcx = bcx;
925     if m.len() == 0u {
926         if chk.is_fallible() {
927             chk.handle_fail(bcx);
928         }
929         return;
930     }
931
932     let tcx = bcx.tcx();
933     let def_map = &tcx.def_map;
934     match pick_column_to_specialize(def_map, m) {
935         Some(col) => {
936             let val = vals[col];
937             if has_nested_bindings(m, col) {
938                 let expanded = expand_nested_bindings(bcx, m, col, val);
939                 compile_submatch_continue(bcx,
940                                           &expanded[],
941                                           vals,
942                                           chk,
943                                           col,
944                                           val,
945                                           has_genuine_default)
946             } else {
947                 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
948             }
949         }
950         None => {
951             let data = &m[0].data;
952             for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
953                 let llmatch = data.bindings_map[*ident].llmatch;
954                 call_lifetime_start(bcx, llmatch);
955                 Store(bcx, *value_ptr, llmatch);
956             }
957             match data.arm.guard {
958                 Some(ref guard_expr) => {
959                     bcx = compile_guard(bcx,
960                                         &**guard_expr,
961                                         m[0].data,
962                                         &m[1..m.len()],
963                                         vals,
964                                         chk,
965                                         has_genuine_default);
966                 }
967                 _ => ()
968             }
969             Br(bcx, data.bodycx.llbb);
970         }
971     }
972 }
973
974 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
975                                                  m: &[Match<'a, 'p, 'blk, 'tcx>],
976                                                  vals: &[ValueRef],
977                                                  chk: &FailureHandler,
978                                                  col: uint,
979                                                  val: ValueRef,
980                                                  has_genuine_default: bool) {
981     let fcx = bcx.fcx;
982     let tcx = bcx.tcx();
983     let dm = &tcx.def_map;
984
985     let mut vals_left = vals[0u..col].to_vec();
986     vals_left.push_all(&vals[col + 1u..]);
987     let ccx = bcx.fcx.ccx;
988
989     // Find a real id (we're adding placeholder wildcard patterns, but
990     // each column is guaranteed to have at least one real pattern)
991     let pat_id = m.iter().map(|br| br.pats[col].id)
992                          .find(|&id| id != DUMMY_NODE_ID)
993                          .unwrap_or(DUMMY_NODE_ID);
994
995     let left_ty = if pat_id == DUMMY_NODE_ID {
996         ty::mk_nil(tcx)
997     } else {
998         node_id_type(bcx, pat_id)
999     };
1000
1001     let mcx = check_match::MatchCheckCtxt {
1002         tcx: bcx.tcx(),
1003         param_env: ty::empty_parameter_environment(bcx.tcx()),
1004     };
1005     let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1006         let repr = adt::represent_type(bcx.ccx(), left_ty);
1007         let arg_count = adt::num_args(&*repr, 0);
1008         let field_vals: Vec<ValueRef> = std::iter::range(0, arg_count).map(|ix|
1009             adt::trans_field_ptr(bcx, &*repr, val, 0, ix)
1010         ).collect();
1011         Some(field_vals)
1012     } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1013         Some(vec!(Load(bcx, val)))
1014     } else {
1015         match left_ty.sty {
1016             ty::ty_vec(_, Some(n)) => {
1017                 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1018                 Some(args.vals)
1019             }
1020             _ => None
1021         }
1022     };
1023
1024     match adt_vals {
1025         Some(field_vals) => {
1026             let pats = enter_match(bcx, dm, m, col, val, |pats|
1027                 check_match::specialize(&mcx, pats,
1028                                         &check_match::Single, col,
1029                                         field_vals.len())
1030             );
1031             let mut vals = field_vals;
1032             vals.push_all(vals_left.as_slice());
1033             compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
1034             return;
1035         }
1036         _ => ()
1037     }
1038
1039     // Decide what kind of branch we need
1040     let opts = get_branches(bcx, m, col);
1041     debug!("options={:?}", opts);
1042     let mut kind = NoBranch;
1043     let mut test_val = val;
1044     debug!("test_val={}", bcx.val_to_string(test_val));
1045     if opts.len() > 0u {
1046         match opts[0] {
1047             ConstantValue(_) | ConstantRange(_, _) => {
1048                 test_val = load_if_immediate(bcx, val, left_ty);
1049                 kind = if ty::type_is_integral(left_ty) {
1050                     Switch
1051                 } else {
1052                     Compare
1053                 };
1054             }
1055             Variant(_, ref repr, _) => {
1056                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
1057                 kind = the_kind;
1058                 for &tval in val_opt.iter() { test_val = tval; }
1059             }
1060             SliceLengthEqual(_) | SliceLengthGreaterOrEqual(_, _) => {
1061                 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
1062                 test_val = len;
1063                 kind = Switch;
1064             }
1065         }
1066     }
1067     for o in opts.iter() {
1068         match *o {
1069             ConstantRange(_, _) => { kind = Compare; break },
1070             SliceLengthGreaterOrEqual(_, _) => { kind = CompareSliceLength; break },
1071             _ => ()
1072         }
1073     }
1074     let else_cx = match kind {
1075         NoBranch | Single => bcx,
1076         _ => bcx.fcx.new_temp_block("match_else")
1077     };
1078     let sw = if kind == Switch {
1079         build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1080     } else {
1081         C_int(ccx, 0i) // Placeholder for when not using a switch
1082     };
1083
1084     let defaults = enter_default(else_cx, dm, m, col, val);
1085     let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1086     let len = opts.len();
1087
1088     // Compile subtrees for each option
1089     for (i, opt) in opts.iter().enumerate() {
1090         // In some cases of range and vector pattern matching, we need to
1091         // override the failure case so that instead of failing, it proceeds
1092         // to try more matching. branch_chk, then, is the proper failure case
1093         // for the current conditional branch.
1094         let mut branch_chk = None;
1095         let mut opt_cx = else_cx;
1096         if !exhaustive || i + 1 < len {
1097             opt_cx = bcx.fcx.new_temp_block("match_case");
1098             match kind {
1099                 Single => Br(bcx, opt_cx.llbb),
1100                 Switch => {
1101                     match opt.trans(bcx) {
1102                         SingleResult(r) => {
1103                             AddCase(sw, r.val, opt_cx.llbb);
1104                             bcx = r.bcx;
1105                         }
1106                         _ => {
1107                             bcx.sess().bug(
1108                                 "in compile_submatch, expected \
1109                                  opt.trans() to return a SingleResult")
1110                         }
1111                     }
1112                 }
1113                 Compare | CompareSliceLength => {
1114                     let t = if kind == Compare {
1115                         left_ty
1116                     } else {
1117                         tcx.types.uint // vector length
1118                     };
1119                     let Result { bcx: after_cx, val: matches } = {
1120                         match opt.trans(bcx) {
1121                             SingleResult(Result { bcx, val }) => {
1122                                 compare_values(bcx, test_val, val, t)
1123                             }
1124                             RangeResult(Result { val: vbegin, .. },
1125                                         Result { bcx, val: vend }) => {
1126                                 let Result { bcx, val: llge } =
1127                                     compare_scalar_types(
1128                                     bcx, test_val,
1129                                     vbegin, t, ast::BiGe);
1130                                 let Result { bcx, val: llle } =
1131                                     compare_scalar_types(
1132                                     bcx, test_val, vend,
1133                                     t, ast::BiLe);
1134                                 Result::new(bcx, And(bcx, llge, llle))
1135                             }
1136                             LowerBound(Result { bcx, val }) => {
1137                                 compare_scalar_types(bcx, test_val, val, t, ast::BiGe)
1138                             }
1139                         }
1140                     };
1141                     bcx = fcx.new_temp_block("compare_next");
1142
1143                     // If none of the sub-cases match, and the current condition
1144                     // is guarded or has multiple patterns, move on to the next
1145                     // condition, if there is any, rather than falling back to
1146                     // the default.
1147                     let guarded = m[i].data.arm.guard.is_some();
1148                     let multi_pats = m[i].pats.len() > 1;
1149                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1150                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1151                     }
1152                     CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1153                 }
1154                 _ => ()
1155             }
1156         } else if kind == Compare || kind == CompareSliceLength {
1157             Br(bcx, else_cx.llbb);
1158         }
1159
1160         let mut size = 0u;
1161         let mut unpacked = Vec::new();
1162         match *opt {
1163             Variant(disr_val, ref repr, _) => {
1164                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1165                     extract_variant_args(opt_cx, &**repr, disr_val, val);
1166                 size = argvals.len();
1167                 unpacked = argvals;
1168                 opt_cx = new_bcx;
1169             }
1170             SliceLengthEqual(len) => {
1171                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1172                 size = args.vals.len();
1173                 unpacked = args.vals.clone();
1174                 opt_cx = args.bcx;
1175             }
1176             SliceLengthGreaterOrEqual(before, after) => {
1177                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1178                 size = args.vals.len();
1179                 unpacked = args.vals.clone();
1180                 opt_cx = args.bcx;
1181             }
1182             ConstantValue(_) | ConstantRange(_, _) => ()
1183         }
1184         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1185         let mut opt_vals = unpacked;
1186         opt_vals.push_all(&vals_left[]);
1187         compile_submatch(opt_cx,
1188                          &opt_ms[],
1189                          &opt_vals[],
1190                          branch_chk.as_ref().unwrap_or(chk),
1191                          has_genuine_default);
1192     }
1193
1194     // Compile the fall-through case, if any
1195     if !exhaustive && kind != Single {
1196         if kind == Compare || kind == CompareSliceLength {
1197             Br(bcx, else_cx.llbb);
1198         }
1199         match chk {
1200             // If there is only one default arm left, move on to the next
1201             // condition explicitly rather than (eventually) falling back to
1202             // the last default arm.
1203             &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1204                 chk.handle_fail(else_cx);
1205             }
1206             _ => {
1207                 compile_submatch(else_cx,
1208                                  &defaults[],
1209                                  &vals_left[],
1210                                  chk,
1211                                  has_genuine_default);
1212             }
1213         }
1214     }
1215 }
1216
1217 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1218                                match_expr: &ast::Expr,
1219                                discr_expr: &ast::Expr,
1220                                arms: &[ast::Arm],
1221                                dest: Dest)
1222                                -> Block<'blk, 'tcx> {
1223     let _icx = push_ctxt("match::trans_match");
1224     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1225 }
1226
1227 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1228 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1229     let (vid, field) = match discr.node {
1230         ast::ExprPath(_) | ast::ExprQPath(_) => match bcx.def(discr.id) {
1231             def::DefLocal(vid) | def::DefUpvar(vid, _, _) => (vid, None),
1232             _ => return false
1233         },
1234         ast::ExprField(ref base, field) => {
1235             let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1236                 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1237                 _ => return false
1238             };
1239             (vid, Some(mc::NamedField(field.node.name)))
1240         },
1241         ast::ExprTupField(ref base, field) => {
1242             let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1243                 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1244                 _ => return false
1245             };
1246             (vid, Some(mc::PositionalField(field.node)))
1247         },
1248         _ => return false
1249     };
1250
1251     let mut rc = ReassignmentChecker {
1252         node: vid,
1253         field: field,
1254         reassigned: false
1255     };
1256     {
1257         let mut visitor = euv::ExprUseVisitor::new(&mut rc, bcx);
1258         visitor.walk_expr(body);
1259     }
1260     rc.reassigned
1261 }
1262
1263 struct ReassignmentChecker {
1264     node: ast::NodeId,
1265     field: Option<mc::FieldName>,
1266     reassigned: bool
1267 }
1268
1269 // Determine if the expression we're matching on is reassigned to within
1270 // the body of the match's arm.
1271 // We only care for the `mutate` callback since this check only matters
1272 // for cases where the matched value is moved.
1273 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1274     fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1275     fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1276     fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1277     fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1278               _: ty::BorrowKind, _: euv::LoanCause) {}
1279     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1280
1281     fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1282         match cmt.cat {
1283             mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1284             mc::cat_local(vid) => self.reassigned = self.node == vid,
1285             mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1286                 match base_cmt.cat {
1287                     mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1288                     mc::cat_local(vid) => {
1289                         self.reassigned = self.node == vid && Some(field) == self.field
1290                     },
1291                     _ => {}
1292                 }
1293             },
1294             _ => {}
1295         }
1296     }
1297 }
1298
1299 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1300                                    discr: &ast::Expr, body: &ast::Expr)
1301                                    -> BindingsMap<'tcx> {
1302     // Create the bindings map, which is a mapping from each binding name
1303     // to an alloca() that will be the value for that local variable.
1304     // Note that we use the names because each binding will have many ids
1305     // from the various alternatives.
1306     let ccx = bcx.ccx();
1307     let tcx = bcx.tcx();
1308     let reassigned = is_discr_reassigned(bcx, discr, body);
1309     let mut bindings_map = FnvHashMap();
1310     pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1311         let ident = path1.node;
1312         let variable_ty = node_id_type(bcx, p_id);
1313         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1314         let tcx = bcx.tcx();
1315         let param_env = ty::empty_parameter_environment(tcx);
1316
1317         let llmatch;
1318         let trmode;
1319         match bm {
1320             ast::BindByValue(_)
1321                 if !ty::type_moves_by_default(&param_env, span, variable_ty) || reassigned =>
1322             {
1323                 llmatch = alloca_no_lifetime(bcx,
1324                                  llvariable_ty.ptr_to(),
1325                                  "__llmatch");
1326                 trmode = TrByCopy(alloca_no_lifetime(bcx,
1327                                          llvariable_ty,
1328                                          &bcx.ident(ident)[]));
1329             }
1330             ast::BindByValue(_) => {
1331                 // in this case, the final type of the variable will be T,
1332                 // but during matching we need to store a *T as explained
1333                 // above
1334                 llmatch = alloca_no_lifetime(bcx,
1335                                  llvariable_ty.ptr_to(),
1336                                  &bcx.ident(ident)[]);
1337                 trmode = TrByMove;
1338             }
1339             ast::BindByRef(_) => {
1340                 llmatch = alloca_no_lifetime(bcx,
1341                                  llvariable_ty,
1342                                  &bcx.ident(ident)[]);
1343                 trmode = TrByRef;
1344             }
1345         };
1346         bindings_map.insert(ident, BindingInfo {
1347             llmatch: llmatch,
1348             trmode: trmode,
1349             id: p_id,
1350             span: span,
1351             ty: variable_ty
1352         });
1353     });
1354     return bindings_map;
1355 }
1356
1357 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1358                                  match_id: ast::NodeId,
1359                                  discr_expr: &ast::Expr,
1360                                  arms: &[ast::Arm],
1361                                  dest: Dest) -> Block<'blk, 'tcx> {
1362     let _icx = push_ctxt("match::trans_match_inner");
1363     let fcx = scope_cx.fcx;
1364     let mut bcx = scope_cx;
1365     let tcx = bcx.tcx();
1366
1367     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1368                                                                "match"));
1369     if bcx.unreachable.get() {
1370         return bcx;
1371     }
1372
1373     let t = node_id_type(bcx, discr_expr.id);
1374     let chk = if ty::type_is_empty(tcx, t) {
1375         Unreachable
1376     } else {
1377         Infallible
1378     };
1379
1380     let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1381         bodycx: fcx.new_id_block("case_body", arm.body.id),
1382         arm: arm,
1383         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1384     }).collect();
1385
1386     let mut static_inliner = StaticInliner::new(scope_cx.tcx());
1387     let arm_pats: Vec<Vec<P<ast::Pat>>> = arm_datas.iter().map(|arm_data| {
1388         arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1389     }).collect();
1390     let mut matches = Vec::new();
1391     for (arm_data, pats) in arm_datas.iter().zip(arm_pats.iter()) {
1392         matches.extend(pats.iter().map(|p| Match {
1393             pats: vec![&**p],
1394             data: arm_data,
1395             bound_ptrs: Vec::new(),
1396         }));
1397     }
1398
1399     // `compile_submatch` works one column of arm patterns a time and
1400     // then peels that column off. So as we progress, it may become
1401     // impossible to tell whether we have a genuine default arm, i.e.
1402     // `_ => foo` or not. Sometimes it is important to know that in order
1403     // to decide whether moving on to the next condition or falling back
1404     // to the default arm.
1405     let has_default = arms.last().map_or(false, |arm| {
1406         arm.pats.len() == 1
1407         && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1408     });
1409
1410     compile_submatch(bcx, &matches[], &[discr_datum.val], &chk, has_default);
1411
1412     let mut arm_cxs = Vec::new();
1413     for arm_data in arm_datas.iter() {
1414         let mut bcx = arm_data.bodycx;
1415
1416         // insert bindings into the lllocals map and add cleanups
1417         let cs = fcx.push_custom_cleanup_scope();
1418         bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1419         bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1420         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1421         arm_cxs.push(bcx);
1422     }
1423
1424     bcx = scope_cx.fcx.join_blocks(match_id, &arm_cxs[]);
1425     return bcx;
1426 }
1427
1428 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1429 /// <opt_init_expr>`.
1430 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1431                                local: &ast::Local)
1432                                -> Block<'blk, 'tcx> {
1433     let _icx = push_ctxt("match::store_local");
1434     let mut bcx = bcx;
1435     let tcx = bcx.tcx();
1436     let pat = &*local.pat;
1437
1438     fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1439                                        pat: &ast::Pat)
1440                                        -> Block<'blk, 'tcx> {
1441         // create dummy memory for the variables if we have no
1442         // value to store into them immediately
1443         let tcx = bcx.tcx();
1444         pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1445             let scope = cleanup::var_scope(tcx, p_id);
1446             bcx = mk_binding_alloca(
1447                 bcx, p_id, &path1.node, scope, (),
1448                 |(), bcx, llval, ty| { zero_mem(bcx, llval, ty); bcx });
1449         });
1450         bcx
1451     }
1452
1453     match local.init {
1454         Some(ref init_expr) => {
1455             // Optimize the "let x = expr" case. This just writes
1456             // the result of evaluating `expr` directly into the alloca
1457             // for `x`. Often the general path results in similar or the
1458             // same code post-optimization, but not always. In particular,
1459             // in unsafe code, you can have expressions like
1460             //
1461             //    let x = intrinsics::uninit();
1462             //
1463             // In such cases, the more general path is unsafe, because
1464             // it assumes it is matching against a valid value.
1465             match simple_identifier(&*pat) {
1466                 Some(ident) => {
1467                     let var_scope = cleanup::var_scope(tcx, local.id);
1468                     return mk_binding_alloca(
1469                         bcx, pat.id, ident, var_scope, (),
1470                         |(), bcx, v, _| expr::trans_into(bcx, &**init_expr,
1471                                                          expr::SaveIn(v)));
1472                 }
1473
1474                 None => {}
1475             }
1476
1477             // General path.
1478             let init_datum =
1479                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1480             if bcx.sess().asm_comments() {
1481                 add_comment(bcx, "creating zeroable ref llval");
1482             }
1483             let var_scope = cleanup::var_scope(tcx, local.id);
1484             bind_irrefutable_pat(bcx, pat, init_datum.val, var_scope)
1485         }
1486         None => {
1487             create_dummy_locals(bcx, pat)
1488         }
1489     }
1490 }
1491
1492 /// Generates code for argument patterns like `fn foo(<pat>: T)`.
1493 /// Creates entries in the `lllocals` map for each of the bindings
1494 /// in `pat`.
1495 ///
1496 /// # Arguments
1497 ///
1498 /// - `pat` is the argument pattern
1499 /// - `llval` is a pointer to the argument value (in other words,
1500 ///   if the argument type is `T`, then `llval` is a `T*`). In some
1501 ///   cases, this code may zero out the memory `llval` points at.
1502 pub fn store_arg<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1503                              pat: &ast::Pat,
1504                              arg: Datum<'tcx, Rvalue>,
1505                              arg_scope: cleanup::ScopeId)
1506                              -> Block<'blk, 'tcx> {
1507     let _icx = push_ctxt("match::store_arg");
1508
1509     match simple_identifier(&*pat) {
1510         Some(ident) => {
1511             // Generate nicer LLVM for the common case of fn a pattern
1512             // like `x: T`
1513             let arg_ty = node_id_type(bcx, pat.id);
1514             if type_of::arg_is_indirect(bcx.ccx(), arg_ty)
1515                 && bcx.sess().opts.debuginfo != FullDebugInfo {
1516                 // Don't copy an indirect argument to an alloca, the caller
1517                 // already put it in a temporary alloca and gave it up, unless
1518                 // we emit extra-debug-info, which requires local allocas :(.
1519                 let arg_val = arg.add_clean(bcx.fcx, arg_scope);
1520                 bcx.fcx.lllocals.borrow_mut()
1521                    .insert(pat.id, Datum::new(arg_val, arg_ty, Lvalue));
1522                 bcx
1523             } else {
1524                 mk_binding_alloca(
1525                     bcx, pat.id, ident, arg_scope, arg,
1526                     |arg, bcx, llval, _| arg.store_to(bcx, llval))
1527             }
1528         }
1529
1530         None => {
1531             // General path. Copy out the values that are used in the
1532             // pattern.
1533             let arg = unpack_datum!(
1534                 bcx, arg.to_lvalue_datum_in_scope(bcx, "__arg", arg_scope));
1535             bind_irrefutable_pat(bcx, pat, arg.val, arg_scope)
1536         }
1537     }
1538 }
1539
1540 /// Generates code for the pattern binding in a `for` loop like
1541 /// `for <pat> in <expr> { ... }`.
1542 pub fn store_for_loop_binding<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1543                                           pat: &ast::Pat,
1544                                           llvalue: ValueRef,
1545                                           body_scope: cleanup::ScopeId)
1546                                           -> Block<'blk, 'tcx> {
1547     let _icx = push_ctxt("match::store_for_loop_binding");
1548
1549     if simple_identifier(&*pat).is_some() &&
1550        bcx.sess().opts.debuginfo != FullDebugInfo {
1551         // Generate nicer LLVM for the common case of a `for` loop pattern
1552         // like `for x in blahblah { ... }`.
1553         let binding_type = node_id_type(bcx, pat.id);
1554         bcx.fcx.lllocals.borrow_mut().insert(pat.id,
1555                                              Datum::new(llvalue,
1556                                                         binding_type,
1557                                                         Lvalue));
1558         return bcx
1559     }
1560
1561     // General path. Copy out the values that are used in the pattern.
1562     bind_irrefutable_pat(bcx, pat, llvalue, body_scope)
1563 }
1564
1565 fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
1566                                        p_id: ast::NodeId,
1567                                        ident: &ast::Ident,
1568                                        cleanup_scope: cleanup::ScopeId,
1569                                        arg: A,
1570                                        populate: F)
1571                                        -> Block<'blk, 'tcx> where
1572     F: FnOnce(A, Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
1573 {
1574     let var_ty = node_id_type(bcx, p_id);
1575
1576     // Allocate memory on stack for the binding.
1577     let llval = alloc_ty(bcx, var_ty, &bcx.ident(*ident)[]);
1578
1579     // Subtle: be sure that we *populate* the memory *before*
1580     // we schedule the cleanup.
1581     let bcx = populate(arg, bcx, llval, var_ty);
1582     bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1583     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
1584
1585     // Now that memory is initialized and has cleanup scheduled,
1586     // create the datum and insert into the local variable map.
1587     let datum = Datum::new(llval, var_ty, Lvalue);
1588     bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1589     bcx
1590 }
1591
1592 /// A simple version of the pattern matching code that only handles
1593 /// irrefutable patterns. This is used in let/argument patterns,
1594 /// not in match statements. Unifying this code with the code above
1595 /// sounds nice, but in practice it produces very inefficient code,
1596 /// since the match code is so much more general. In most cases,
1597 /// LLVM is able to optimize the code, but it causes longer compile
1598 /// times and makes the generated code nigh impossible to read.
1599 ///
1600 /// # Arguments
1601 /// - bcx: starting basic block context
1602 /// - pat: the irrefutable pattern being matched.
1603 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1604 fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1605                                     pat: &ast::Pat,
1606                                     val: ValueRef,
1607                                     cleanup_scope: cleanup::ScopeId)
1608                                     -> Block<'blk, 'tcx> {
1609     debug!("bind_irrefutable_pat(bcx={}, pat={})",
1610            bcx.to_str(),
1611            pat.repr(bcx.tcx()));
1612
1613     if bcx.sess().asm_comments() {
1614         add_comment(bcx, &format!("bind_irrefutable_pat(pat={})",
1615                                  pat.repr(bcx.tcx()))[]);
1616     }
1617
1618     let _indenter = indenter();
1619
1620     let _icx = push_ctxt("match::bind_irrefutable_pat");
1621     let mut bcx = bcx;
1622     let tcx = bcx.tcx();
1623     let ccx = bcx.ccx();
1624     match pat.node {
1625         ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1626             if pat_is_binding(&tcx.def_map, &*pat) {
1627                 // Allocate the stack slot where the value of this
1628                 // binding will live and place it into the appropriate
1629                 // map.
1630                 bcx = mk_binding_alloca(
1631                     bcx, pat.id, &path1.node, cleanup_scope, (),
1632                     |(), bcx, llval, ty| {
1633                         match pat_binding_mode {
1634                             ast::BindByValue(_) => {
1635                                 // By value binding: move the value that `val`
1636                                 // points at into the binding's stack slot.
1637                                 let d = Datum::new(val, ty, Lvalue);
1638                                 d.store_to(bcx, llval)
1639                             }
1640
1641                             ast::BindByRef(_) => {
1642                                 // By ref binding: the value of the variable
1643                                 // is the pointer `val` itself.
1644                                 Store(bcx, val, llval);
1645                                 bcx
1646                             }
1647                         }
1648                     });
1649             }
1650
1651             for inner_pat in inner.iter() {
1652                 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1653             }
1654         }
1655         ast::PatEnum(_, ref sub_pats) => {
1656             let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).cloned();
1657             match opt_def {
1658                 Some(def::DefVariant(enum_id, var_id, _)) => {
1659                     let repr = adt::represent_node(bcx, pat.id);
1660                     let vinfo = ty::enum_variant_with_id(ccx.tcx(),
1661                                                          enum_id,
1662                                                          var_id);
1663                     let args = extract_variant_args(bcx,
1664                                                     &*repr,
1665                                                     vinfo.disr_val,
1666                                                     val);
1667                     for sub_pat in sub_pats.iter() {
1668                         for (i, &argval) in args.vals.iter().enumerate() {
1669                             bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
1670                                                        argval, cleanup_scope);
1671                         }
1672                     }
1673                 }
1674                 Some(def::DefStruct(..)) => {
1675                     match *sub_pats {
1676                         None => {
1677                             // This is a unit-like struct. Nothing to do here.
1678                         }
1679                         Some(ref elems) => {
1680                             // This is the tuple struct case.
1681                             let repr = adt::represent_node(bcx, pat.id);
1682                             for (i, elem) in elems.iter().enumerate() {
1683                                 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1684                                                                   val, 0, i);
1685                                 bcx = bind_irrefutable_pat(bcx, &**elem,
1686                                                            fldptr, cleanup_scope);
1687                             }
1688                         }
1689                     }
1690                 }
1691                 _ => {
1692                     // Nothing to do here.
1693                 }
1694             }
1695         }
1696         ast::PatStruct(_, ref fields, _) => {
1697             let tcx = bcx.tcx();
1698             let pat_ty = node_id_type(bcx, pat.id);
1699             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1700             expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
1701                 for f in fields.iter() {
1702                     let ix = ty::field_idx_strict(tcx, f.node.ident.name, field_tys);
1703                     let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val,
1704                                                       discr, ix);
1705                     bcx = bind_irrefutable_pat(bcx, &*f.node.pat, fldptr, cleanup_scope);
1706                 }
1707             })
1708         }
1709         ast::PatTup(ref elems) => {
1710             let repr = adt::represent_node(bcx, pat.id);
1711             for (i, elem) in elems.iter().enumerate() {
1712                 let fldptr = adt::trans_field_ptr(bcx, &*repr, val, 0, i);
1713                 bcx = bind_irrefutable_pat(bcx, &**elem, fldptr, cleanup_scope);
1714             }
1715         }
1716         ast::PatBox(ref inner) => {
1717             let llbox = Load(bcx, val);
1718             bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
1719         }
1720         ast::PatRegion(ref inner, _) => {
1721             let loaded_val = Load(bcx, val);
1722             bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
1723         }
1724         ast::PatVec(ref before, ref slice, ref after) => {
1725             let pat_ty = node_id_type(bcx, pat.id);
1726             let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1727             match slice {
1728                 &Some(_) => {
1729                     extracted.vals.insert(
1730                         before.len(),
1731                         bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1732                     );
1733                 }
1734                 &None => ()
1735             }
1736             bcx = before
1737                 .iter()
1738                 .chain(slice.iter())
1739                 .chain(after.iter())
1740                 .zip(extracted.vals.into_iter())
1741                 .fold(bcx, |bcx, (inner, elem)|
1742                     bind_irrefutable_pat(bcx, &**inner, elem, cleanup_scope)
1743                 );
1744         }
1745         ast::PatMac(..) => {
1746             bcx.sess().span_bug(pat.span, "unexpanded macro");
1747         }
1748         ast::PatWild(_) | ast::PatLit(_) | ast::PatRange(_, _) => ()
1749     }
1750     return bcx;
1751 }