]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/_match.rs
Merge pull request #20510 from tshepang/patch-6
[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::{Mul, 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_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), offset_left));
634     let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset);
635     let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
636     let slice_len = Sub(bcx, len, slice_len_offset);
637     let slice_ty = ty::mk_slice(bcx.tcx(),
638                                 bcx.tcx().mk_region(ty::ReStatic),
639                                 ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable});
640     let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
641     Store(bcx, slice_begin,
642           GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_ADDR]));
643     Store(bcx, slice_len, GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_EXTRA]));
644     scratch.val
645 }
646
647 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
648                                  left_ty: Ty,
649                                  before: uint,
650                                  after: uint,
651                                  val: ValueRef)
652                                  -> ExtractedBlock<'blk, 'tcx> {
653     let _icx = push_ctxt("match::extract_vec_elems");
654     let vec_datum = match_datum(val, left_ty);
655     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
656     let mut elems = vec![];
657     elems.extend(range(0, before).map(|i| GEPi(bcx, base, &[i])));
658     elems.extend(range(0, after).rev().map(|i| {
659         InBoundsGEP(bcx, base, &[
660             Sub(bcx, len, C_uint(bcx.ccx(), i + 1))
661         ])
662     }));
663     ExtractedBlock { vals: elems, bcx: bcx }
664 }
665
666 // Macro for deciding whether any of the remaining matches fit a given kind of
667 // pattern.  Note that, because the macro is well-typed, either ALL of the
668 // matches should fit that sort of pattern or NONE (however, some of the
669 // matches may be wildcards like _ or identifiers).
670 macro_rules! any_pat {
671     ($m:expr, $col:expr, $pattern:pat) => (
672         ($m).iter().any(|br| {
673             match br.pats[$col].node {
674                 $pattern => true,
675                 _ => false
676             }
677         })
678     )
679 }
680
681 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
682     any_pat!(m, col, ast::PatBox(_))
683 }
684
685 fn any_region_pat(m: &[Match], col: uint) -> bool {
686     any_pat!(m, col, ast::PatRegion(_))
687 }
688
689 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: uint) -> bool {
690     m.iter().any(|br| {
691         let pat = br.pats[col];
692         match pat.node {
693             ast::PatTup(_) => true,
694             ast::PatStruct(..) => {
695                 match tcx.def_map.borrow().get(&pat.id) {
696                     Some(&def::DefVariant(..)) => false,
697                     _ => true,
698                 }
699             }
700             ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
701                 match tcx.def_map.borrow().get(&pat.id) {
702                     Some(&def::DefStruct(..)) => true,
703                     _ => false
704                 }
705             }
706             _ => false
707         }
708     })
709 }
710
711 /// What to do when the pattern match fails.
712 enum FailureHandler {
713     Infallible,
714     JumpToBasicBlock(BasicBlockRef),
715     Unreachable
716 }
717
718 impl FailureHandler {
719     fn is_fallible(&self) -> bool {
720         match *self {
721             Infallible => false,
722             _ => true
723         }
724     }
725
726     fn is_infallible(&self) -> bool {
727         !self.is_fallible()
728     }
729
730     fn handle_fail(&self, bcx: Block) {
731         match *self {
732             Infallible =>
733                 panic!("attempted to panic in a non-panicking panic handler!"),
734             JumpToBasicBlock(basic_block) =>
735                 Br(bcx, basic_block),
736             Unreachable =>
737                 build::Unreachable(bcx)
738         }
739     }
740 }
741
742 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<uint> {
743     fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
744         match pat.node {
745             ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
746             _ if pat_is_refutable(def_map, pat) => 1u,
747             _ => 0u
748         }
749     }
750
751     let column_score = |&: m: &[Match], col: uint| -> uint {
752         let total_score = m.iter()
753             .map(|row| row.pats[col])
754             .map(|pat| pat_score(def_map, pat))
755             .sum();
756
757         // Irrefutable columns always go first, they'd only be duplicated in the branches.
758         if total_score == 0 {
759             std::uint::MAX
760         } else {
761             total_score
762         }
763     };
764
765     let column_contains_any_nonwild_patterns = |&: &col: &uint| -> bool {
766         m.iter().any(|row| match row.pats[col].node {
767             ast::PatWild(_) => false,
768             _ => true
769         })
770     };
771
772     range(0, m[0].pats.len())
773         .filter(column_contains_any_nonwild_patterns)
774         .map(|col| (col, column_score(m, col)))
775         .max_by(|&(_, score)| score)
776         .map(|(col, _)| col)
777 }
778
779 // Compiles a comparison between two things.
780 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
781                               lhs: ValueRef,
782                               rhs: ValueRef,
783                               rhs_t: Ty<'tcx>)
784                               -> Result<'blk, 'tcx> {
785     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
786                                lhs: ValueRef,
787                                rhs: ValueRef,
788                                rhs_t: Ty<'tcx>)
789                                -> Result<'blk, 'tcx> {
790         let did = langcall(cx,
791                            None,
792                            format!("comparison of `{}`",
793                                    cx.ty_to_string(rhs_t))[],
794                            StrEqFnLangItem);
795         callee::trans_lang_call(cx, did, &[lhs, rhs], None)
796     }
797
798     let _icx = push_ctxt("compare_values");
799     if ty::type_is_scalar(rhs_t) {
800         let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
801         return Result::new(rs.bcx, rs.val);
802     }
803
804     match rhs_t.sty {
805         ty::ty_rptr(_, mt) => match mt.ty.sty {
806             ty::ty_str => compare_str(cx, lhs, rhs, rhs_t),
807             ty::ty_vec(ty, _) => match ty.sty {
808                 ty::ty_uint(ast::TyU8) => {
809                     // NOTE: cast &[u8] to &str and abuse the str_eq lang item,
810                     // which calls memcmp().
811                     let t = ty::mk_str_slice(cx.tcx(),
812                                              cx.tcx().mk_region(ty::ReStatic),
813                                              ast::MutImmutable);
814                     let lhs = BitCast(cx, lhs, type_of::type_of(cx.ccx(), t).ptr_to());
815                     let rhs = BitCast(cx, rhs, type_of::type_of(cx.ccx(), t).ptr_to());
816                     compare_str(cx, lhs, rhs, rhs_t)
817                 },
818                 _ => cx.sess().bug("only byte strings supported in compare_values"),
819             },
820             _ => cx.sess().bug("only string and byte strings supported in compare_values"),
821         },
822         _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
823     }
824 }
825
826 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
827 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
828                                bindings_map: &BindingsMap<'tcx>,
829                                cs: Option<cleanup::ScopeId>)
830                                -> Block<'blk, 'tcx> {
831     for (&ident, &binding_info) in bindings_map.iter() {
832         let llval = match binding_info.trmode {
833             // By value mut binding for a copy type: load from the ptr
834             // into the matched value and copy to our alloca
835             TrByCopy(llbinding) => {
836                 let llval = Load(bcx, binding_info.llmatch);
837                 let datum = Datum::new(llval, binding_info.ty, Lvalue);
838                 call_lifetime_start(bcx, llbinding);
839                 bcx = datum.store_to(bcx, llbinding);
840                 if let Some(cs) = cs {
841                     bcx.fcx.schedule_lifetime_end(cs, llbinding);
842                 }
843
844                 llbinding
845             },
846
847             // By value move bindings: load from the ptr into the matched value
848             TrByMove => Load(bcx, binding_info.llmatch),
849
850             // By ref binding: use the ptr into the matched value
851             TrByRef => binding_info.llmatch
852         };
853
854         let datum = Datum::new(llval, binding_info.ty, Lvalue);
855         if let Some(cs) = cs {
856             bcx.fcx.schedule_drop_and_zero_mem(cs, llval, binding_info.ty);
857             bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
858         }
859
860         debug!("binding {} to {}",
861                binding_info.id,
862                bcx.val_to_string(llval));
863         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
864
865         if bcx.sess().opts.debuginfo == FullDebugInfo {
866             debuginfo::create_match_binding_metadata(bcx,
867                                                      ident,
868                                                      binding_info);
869         }
870     }
871     bcx
872 }
873
874 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
875                                      guard_expr: &ast::Expr,
876                                      data: &ArmData<'p, 'blk, 'tcx>,
877                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
878                                      vals: &[ValueRef],
879                                      chk: &FailureHandler,
880                                      has_genuine_default: bool)
881                                      -> Block<'blk, 'tcx> {
882     debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
883            bcx.to_str(),
884            bcx.expr_to_string(guard_expr),
885            m.repr(bcx.tcx()),
886            vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
887     let _indenter = indenter();
888
889     let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
890
891     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
892     let val = val.to_llbool(bcx);
893
894     for (_, &binding_info) in data.bindings_map.iter() {
895         if let TrByCopy(llbinding) = binding_info.trmode {
896             call_lifetime_end(bcx, llbinding);
897         }
898     }
899
900     with_cond(bcx, Not(bcx, val), |bcx| {
901         // Guard does not match: remove all bindings from the lllocals table
902         for (_, &binding_info) in data.bindings_map.iter() {
903             call_lifetime_end(bcx, binding_info.llmatch);
904             bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
905         }
906         match chk {
907             // If the default arm is the only one left, move on to the next
908             // condition explicitly rather than (possibly) falling back to
909             // the default arm.
910             &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
911                 chk.handle_fail(bcx);
912             }
913             _ => {
914                 compile_submatch(bcx, m, vals, chk, has_genuine_default);
915             }
916         };
917         bcx
918     })
919 }
920
921 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
922                                         m: &[Match<'a, 'p, 'blk, 'tcx>],
923                                         vals: &[ValueRef],
924                                         chk: &FailureHandler,
925                                         has_genuine_default: bool) {
926     debug!("compile_submatch(bcx={}, m={}, vals={})",
927            bcx.to_str(),
928            m.repr(bcx.tcx()),
929            vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
930     let _indenter = indenter();
931     let _icx = push_ctxt("match::compile_submatch");
932     let mut bcx = bcx;
933     if m.len() == 0u {
934         if chk.is_fallible() {
935             chk.handle_fail(bcx);
936         }
937         return;
938     }
939
940     let tcx = bcx.tcx();
941     let def_map = &tcx.def_map;
942     match pick_column_to_specialize(def_map, m) {
943         Some(col) => {
944             let val = vals[col];
945             if has_nested_bindings(m, col) {
946                 let expanded = expand_nested_bindings(bcx, m, col, val);
947                 compile_submatch_continue(bcx,
948                                           expanded[],
949                                           vals,
950                                           chk,
951                                           col,
952                                           val,
953                                           has_genuine_default)
954             } else {
955                 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
956             }
957         }
958         None => {
959             let data = &m[0].data;
960             for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
961                 let llmatch = data.bindings_map[*ident].llmatch;
962                 call_lifetime_start(bcx, llmatch);
963                 Store(bcx, *value_ptr, llmatch);
964             }
965             match data.arm.guard {
966                 Some(ref guard_expr) => {
967                     bcx = compile_guard(bcx,
968                                         &**guard_expr,
969                                         m[0].data,
970                                         m[1..m.len()],
971                                         vals,
972                                         chk,
973                                         has_genuine_default);
974                 }
975                 _ => ()
976             }
977             Br(bcx, data.bodycx.llbb);
978         }
979     }
980 }
981
982 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
983                                                  m: &[Match<'a, 'p, 'blk, 'tcx>],
984                                                  vals: &[ValueRef],
985                                                  chk: &FailureHandler,
986                                                  col: uint,
987                                                  val: ValueRef,
988                                                  has_genuine_default: bool) {
989     let fcx = bcx.fcx;
990     let tcx = bcx.tcx();
991     let dm = &tcx.def_map;
992
993     let mut vals_left = vals[0u..col].to_vec();
994     vals_left.push_all(vals[col + 1u..]);
995     let ccx = bcx.fcx.ccx;
996
997     // Find a real id (we're adding placeholder wildcard patterns, but
998     // each column is guaranteed to have at least one real pattern)
999     let pat_id = m.iter().map(|br| br.pats[col].id)
1000                          .find(|&id| id != DUMMY_NODE_ID)
1001                          .unwrap_or(DUMMY_NODE_ID);
1002
1003     let left_ty = if pat_id == DUMMY_NODE_ID {
1004         ty::mk_nil(tcx)
1005     } else {
1006         node_id_type(bcx, pat_id)
1007     };
1008
1009     let mcx = check_match::MatchCheckCtxt {
1010         tcx: bcx.tcx(),
1011         param_env: ty::empty_parameter_environment(bcx.tcx()),
1012     };
1013     let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1014         let repr = adt::represent_type(bcx.ccx(), left_ty);
1015         let arg_count = adt::num_args(&*repr, 0);
1016         let field_vals: Vec<ValueRef> = std::iter::range(0, arg_count).map(|ix|
1017             adt::trans_field_ptr(bcx, &*repr, val, 0, ix)
1018         ).collect();
1019         Some(field_vals)
1020     } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1021         Some(vec!(Load(bcx, val)))
1022     } else {
1023         match left_ty.sty {
1024             ty::ty_vec(_, Some(n)) => {
1025                 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1026                 Some(args.vals)
1027             }
1028             _ => None
1029         }
1030     };
1031
1032     match adt_vals {
1033         Some(field_vals) => {
1034             let pats = enter_match(bcx, dm, m, col, val, |pats|
1035                 check_match::specialize(&mcx, pats,
1036                                         &check_match::Single, col,
1037                                         field_vals.len())
1038             );
1039             let mut vals = field_vals;
1040             vals.push_all(vals_left[]);
1041             compile_submatch(bcx, pats[], vals[], chk, has_genuine_default);
1042             return;
1043         }
1044         _ => ()
1045     }
1046
1047     // Decide what kind of branch we need
1048     let opts = get_branches(bcx, m, col);
1049     debug!("options={}", opts);
1050     let mut kind = NoBranch;
1051     let mut test_val = val;
1052     debug!("test_val={}", bcx.val_to_string(test_val));
1053     if opts.len() > 0u {
1054         match opts[0] {
1055             ConstantValue(_) | ConstantRange(_, _) => {
1056                 test_val = load_if_immediate(bcx, val, left_ty);
1057                 kind = if ty::type_is_integral(left_ty) {
1058                     Switch
1059                 } else {
1060                     Compare
1061                 };
1062             }
1063             Variant(_, ref repr, _) => {
1064                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
1065                 kind = the_kind;
1066                 for &tval in val_opt.iter() { test_val = tval; }
1067             }
1068             SliceLengthEqual(_) | SliceLengthGreaterOrEqual(_, _) => {
1069                 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
1070                 test_val = len;
1071                 kind = Switch;
1072             }
1073         }
1074     }
1075     for o in opts.iter() {
1076         match *o {
1077             ConstantRange(_, _) => { kind = Compare; break },
1078             SliceLengthGreaterOrEqual(_, _) => { kind = CompareSliceLength; break },
1079             _ => ()
1080         }
1081     }
1082     let else_cx = match kind {
1083         NoBranch | Single => bcx,
1084         _ => bcx.fcx.new_temp_block("match_else")
1085     };
1086     let sw = if kind == Switch {
1087         build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1088     } else {
1089         C_int(ccx, 0i) // Placeholder for when not using a switch
1090     };
1091
1092     let defaults = enter_default(else_cx, dm, m, col, val);
1093     let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1094     let len = opts.len();
1095
1096     // Compile subtrees for each option
1097     for (i, opt) in opts.iter().enumerate() {
1098         // In some cases of range and vector pattern matching, we need to
1099         // override the failure case so that instead of failing, it proceeds
1100         // to try more matching. branch_chk, then, is the proper failure case
1101         // for the current conditional branch.
1102         let mut branch_chk = None;
1103         let mut opt_cx = else_cx;
1104         if !exhaustive || i + 1 < len {
1105             opt_cx = bcx.fcx.new_temp_block("match_case");
1106             match kind {
1107                 Single => Br(bcx, opt_cx.llbb),
1108                 Switch => {
1109                     match opt.trans(bcx) {
1110                         SingleResult(r) => {
1111                             AddCase(sw, r.val, opt_cx.llbb);
1112                             bcx = r.bcx;
1113                         }
1114                         _ => {
1115                             bcx.sess().bug(
1116                                 "in compile_submatch, expected \
1117                                  opt.trans() to return a SingleResult")
1118                         }
1119                     }
1120                 }
1121                 Compare | CompareSliceLength => {
1122                     let t = if kind == Compare {
1123                         left_ty
1124                     } else {
1125                         tcx.types.uint // vector length
1126                     };
1127                     let Result { bcx: after_cx, val: matches } = {
1128                         match opt.trans(bcx) {
1129                             SingleResult(Result { bcx, val }) => {
1130                                 compare_values(bcx, test_val, val, t)
1131                             }
1132                             RangeResult(Result { val: vbegin, .. },
1133                                         Result { bcx, val: vend }) => {
1134                                 let Result { bcx, val: llge } =
1135                                     compare_scalar_types(
1136                                     bcx, test_val,
1137                                     vbegin, t, ast::BiGe);
1138                                 let Result { bcx, val: llle } =
1139                                     compare_scalar_types(
1140                                     bcx, test_val, vend,
1141                                     t, ast::BiLe);
1142                                 Result::new(bcx, And(bcx, llge, llle))
1143                             }
1144                             LowerBound(Result { bcx, val }) => {
1145                                 compare_scalar_types(bcx, test_val, val, t, ast::BiGe)
1146                             }
1147                         }
1148                     };
1149                     bcx = fcx.new_temp_block("compare_next");
1150
1151                     // If none of the sub-cases match, and the current condition
1152                     // is guarded or has multiple patterns, move on to the next
1153                     // condition, if there is any, rather than falling back to
1154                     // the default.
1155                     let guarded = m[i].data.arm.guard.is_some();
1156                     let multi_pats = m[i].pats.len() > 1;
1157                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1158                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1159                     }
1160                     CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1161                 }
1162                 _ => ()
1163             }
1164         } else if kind == Compare || kind == CompareSliceLength {
1165             Br(bcx, else_cx.llbb);
1166         }
1167
1168         let mut size = 0u;
1169         let mut unpacked = Vec::new();
1170         match *opt {
1171             Variant(disr_val, ref repr, _) => {
1172                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1173                     extract_variant_args(opt_cx, &**repr, disr_val, val);
1174                 size = argvals.len();
1175                 unpacked = argvals;
1176                 opt_cx = new_bcx;
1177             }
1178             SliceLengthEqual(len) => {
1179                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1180                 size = args.vals.len();
1181                 unpacked = args.vals.clone();
1182                 opt_cx = args.bcx;
1183             }
1184             SliceLengthGreaterOrEqual(before, after) => {
1185                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1186                 size = args.vals.len();
1187                 unpacked = args.vals.clone();
1188                 opt_cx = args.bcx;
1189             }
1190             ConstantValue(_) | ConstantRange(_, _) => ()
1191         }
1192         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1193         let mut opt_vals = unpacked;
1194         opt_vals.push_all(vals_left[]);
1195         compile_submatch(opt_cx,
1196                          opt_ms[],
1197                          opt_vals[],
1198                          branch_chk.as_ref().unwrap_or(chk),
1199                          has_genuine_default);
1200     }
1201
1202     // Compile the fall-through case, if any
1203     if !exhaustive && kind != Single {
1204         if kind == Compare || kind == CompareSliceLength {
1205             Br(bcx, else_cx.llbb);
1206         }
1207         match chk {
1208             // If there is only one default arm left, move on to the next
1209             // condition explicitly rather than (eventually) falling back to
1210             // the last default arm.
1211             &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1212                 chk.handle_fail(else_cx);
1213             }
1214             _ => {
1215                 compile_submatch(else_cx,
1216                                  defaults[],
1217                                  vals_left[],
1218                                  chk,
1219                                  has_genuine_default);
1220             }
1221         }
1222     }
1223 }
1224
1225 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1226                                match_expr: &ast::Expr,
1227                                discr_expr: &ast::Expr,
1228                                arms: &[ast::Arm],
1229                                dest: Dest)
1230                                -> Block<'blk, 'tcx> {
1231     let _icx = push_ctxt("match::trans_match");
1232     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1233 }
1234
1235 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1236 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1237     let (vid, field) = match discr.node {
1238         ast::ExprPath(..) => match bcx.def(discr.id) {
1239             def::DefLocal(vid) | def::DefUpvar(vid, _, _) => (vid, None),
1240             _ => return false
1241         },
1242         ast::ExprField(ref base, field) => {
1243             let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1244                 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1245                 _ => return false
1246             };
1247             (vid, Some(mc::NamedField(field.node.name)))
1248         },
1249         ast::ExprTupField(ref base, field) => {
1250             let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1251                 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1252                 _ => return false
1253             };
1254             (vid, Some(mc::PositionalField(field.node)))
1255         },
1256         _ => return false
1257     };
1258
1259     let mut rc = ReassignmentChecker {
1260         node: vid,
1261         field: field,
1262         reassigned: false
1263     };
1264     {
1265         let mut visitor = euv::ExprUseVisitor::new(&mut rc, bcx);
1266         visitor.walk_expr(body);
1267     }
1268     rc.reassigned
1269 }
1270
1271 struct ReassignmentChecker {
1272     node: ast::NodeId,
1273     field: Option<mc::FieldName>,
1274     reassigned: bool
1275 }
1276
1277 // Determine if the expression we're matching on is reassigned to within
1278 // the body of the match's arm.
1279 // We only care for the `mutate` callback since this check only matters
1280 // for cases where the matched value is moved.
1281 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1282     fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1283     fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1284     fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1285     fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1286               _: ty::BorrowKind, _: euv::LoanCause) {}
1287     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1288
1289     fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1290         match cmt.cat {
1291             mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1292             mc::cat_local(vid) => self.reassigned = self.node == vid,
1293             mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1294                 match base_cmt.cat {
1295                     mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1296                     mc::cat_local(vid) => {
1297                         self.reassigned = self.node == vid && Some(field) == self.field
1298                     },
1299                     _ => {}
1300                 }
1301             },
1302             _ => {}
1303         }
1304     }
1305 }
1306
1307 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1308                                    discr: &ast::Expr, body: &ast::Expr)
1309                                    -> BindingsMap<'tcx> {
1310     // Create the bindings map, which is a mapping from each binding name
1311     // to an alloca() that will be the value for that local variable.
1312     // Note that we use the names because each binding will have many ids
1313     // from the various alternatives.
1314     let ccx = bcx.ccx();
1315     let tcx = bcx.tcx();
1316     let reassigned = is_discr_reassigned(bcx, discr, body);
1317     let mut bindings_map = FnvHashMap::new();
1318     pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1319         let ident = path1.node;
1320         let variable_ty = node_id_type(bcx, p_id);
1321         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1322         let tcx = bcx.tcx();
1323         let param_env = ty::empty_parameter_environment(tcx);
1324
1325         let llmatch;
1326         let trmode;
1327         match bm {
1328             ast::BindByValue(_)
1329                 if !ty::type_moves_by_default(&param_env, span, variable_ty) || reassigned =>
1330             {
1331                 llmatch = alloca_no_lifetime(bcx,
1332                                  llvariable_ty.ptr_to(),
1333                                  "__llmatch");
1334                 trmode = TrByCopy(alloca_no_lifetime(bcx,
1335                                          llvariable_ty,
1336                                          bcx.ident(ident)[]));
1337             }
1338             ast::BindByValue(_) => {
1339                 // in this case, the final type of the variable will be T,
1340                 // but during matching we need to store a *T as explained
1341                 // above
1342                 llmatch = alloca_no_lifetime(bcx,
1343                                  llvariable_ty.ptr_to(),
1344                                  bcx.ident(ident)[]);
1345                 trmode = TrByMove;
1346             }
1347             ast::BindByRef(_) => {
1348                 llmatch = alloca_no_lifetime(bcx,
1349                                  llvariable_ty,
1350                                  bcx.ident(ident)[]);
1351                 trmode = TrByRef;
1352             }
1353         };
1354         bindings_map.insert(ident, BindingInfo {
1355             llmatch: llmatch,
1356             trmode: trmode,
1357             id: p_id,
1358             span: span,
1359             ty: variable_ty
1360         });
1361     });
1362     return bindings_map;
1363 }
1364
1365 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1366                                  match_id: ast::NodeId,
1367                                  discr_expr: &ast::Expr,
1368                                  arms: &[ast::Arm],
1369                                  dest: Dest) -> Block<'blk, 'tcx> {
1370     let _icx = push_ctxt("match::trans_match_inner");
1371     let fcx = scope_cx.fcx;
1372     let mut bcx = scope_cx;
1373     let tcx = bcx.tcx();
1374
1375     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1376                                                                "match"));
1377     if bcx.unreachable.get() {
1378         return bcx;
1379     }
1380
1381     let t = node_id_type(bcx, discr_expr.id);
1382     let chk = if ty::type_is_empty(tcx, t) {
1383         Unreachable
1384     } else {
1385         Infallible
1386     };
1387
1388     let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1389         bodycx: fcx.new_id_block("case_body", arm.body.id),
1390         arm: arm,
1391         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1392     }).collect();
1393
1394     let mut static_inliner = StaticInliner::new(scope_cx.tcx());
1395     let arm_pats: Vec<Vec<P<ast::Pat>>> = arm_datas.iter().map(|arm_data| {
1396         arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1397     }).collect();
1398     let mut matches = Vec::new();
1399     for (arm_data, pats) in arm_datas.iter().zip(arm_pats.iter()) {
1400         matches.extend(pats.iter().map(|p| Match {
1401             pats: vec![&**p],
1402             data: arm_data,
1403             bound_ptrs: Vec::new(),
1404         }));
1405     }
1406
1407     // `compile_submatch` works one column of arm patterns a time and
1408     // then peels that column off. So as we progress, it may become
1409     // impossible to tell whether we have a genuine default arm, i.e.
1410     // `_ => foo` or not. Sometimes it is important to know that in order
1411     // to decide whether moving on to the next condition or falling back
1412     // to the default arm.
1413     let has_default = arms.last().map_or(false, |arm| {
1414         arm.pats.len() == 1
1415         && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1416     });
1417
1418     compile_submatch(bcx, matches[], &[discr_datum.val], &chk, has_default);
1419
1420     let mut arm_cxs = Vec::new();
1421     for arm_data in arm_datas.iter() {
1422         let mut bcx = arm_data.bodycx;
1423
1424         // insert bindings into the lllocals map and add cleanups
1425         let cs = fcx.push_custom_cleanup_scope();
1426         bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1427         bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1428         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1429         arm_cxs.push(bcx);
1430     }
1431
1432     bcx = scope_cx.fcx.join_blocks(match_id, arm_cxs[]);
1433     return bcx;
1434 }
1435
1436 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1437 /// <opt_init_expr>`.
1438 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1439                                local: &ast::Local)
1440                                -> Block<'blk, 'tcx> {
1441     let _icx = push_ctxt("match::store_local");
1442     let mut bcx = bcx;
1443     let tcx = bcx.tcx();
1444     let pat = &*local.pat;
1445
1446     fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1447                                        pat: &ast::Pat)
1448                                        -> Block<'blk, 'tcx> {
1449         // create dummy memory for the variables if we have no
1450         // value to store into them immediately
1451         let tcx = bcx.tcx();
1452         pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1453             let scope = cleanup::var_scope(tcx, p_id);
1454             bcx = mk_binding_alloca(
1455                 bcx, p_id, &path1.node, scope, (),
1456                 |(), bcx, llval, ty| { zero_mem(bcx, llval, ty); bcx });
1457         });
1458         bcx
1459     }
1460
1461     match local.init {
1462         Some(ref init_expr) => {
1463             // Optimize the "let x = expr" case. This just writes
1464             // the result of evaluating `expr` directly into the alloca
1465             // for `x`. Often the general path results in similar or the
1466             // same code post-optimization, but not always. In particular,
1467             // in unsafe code, you can have expressions like
1468             //
1469             //    let x = intrinsics::uninit();
1470             //
1471             // In such cases, the more general path is unsafe, because
1472             // it assumes it is matching against a valid value.
1473             match simple_identifier(&*pat) {
1474                 Some(ident) => {
1475                     let var_scope = cleanup::var_scope(tcx, local.id);
1476                     return mk_binding_alloca(
1477                         bcx, pat.id, ident, var_scope, (),
1478                         |(), bcx, v, _| expr::trans_into(bcx, &**init_expr,
1479                                                          expr::SaveIn(v)));
1480                 }
1481
1482                 None => {}
1483             }
1484
1485             // General path.
1486             let init_datum =
1487                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1488             if bcx.sess().asm_comments() {
1489                 add_comment(bcx, "creating zeroable ref llval");
1490             }
1491             let var_scope = cleanup::var_scope(tcx, local.id);
1492             bind_irrefutable_pat(bcx, pat, init_datum.val, var_scope)
1493         }
1494         None => {
1495             create_dummy_locals(bcx, pat)
1496         }
1497     }
1498 }
1499
1500 /// Generates code for argument patterns like `fn foo(<pat>: T)`.
1501 /// Creates entries in the `lllocals` map for each of the bindings
1502 /// in `pat`.
1503 ///
1504 /// # Arguments
1505 ///
1506 /// - `pat` is the argument pattern
1507 /// - `llval` is a pointer to the argument value (in other words,
1508 ///   if the argument type is `T`, then `llval` is a `T*`). In some
1509 ///   cases, this code may zero out the memory `llval` points at.
1510 pub fn store_arg<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1511                              pat: &ast::Pat,
1512                              arg: Datum<'tcx, Rvalue>,
1513                              arg_scope: cleanup::ScopeId)
1514                              -> Block<'blk, 'tcx> {
1515     let _icx = push_ctxt("match::store_arg");
1516
1517     match simple_identifier(&*pat) {
1518         Some(ident) => {
1519             // Generate nicer LLVM for the common case of fn a pattern
1520             // like `x: T`
1521             let arg_ty = node_id_type(bcx, pat.id);
1522             if type_of::arg_is_indirect(bcx.ccx(), arg_ty)
1523                 && bcx.sess().opts.debuginfo != FullDebugInfo {
1524                 // Don't copy an indirect argument to an alloca, the caller
1525                 // already put it in a temporary alloca and gave it up, unless
1526                 // we emit extra-debug-info, which requires local allocas :(.
1527                 let arg_val = arg.add_clean(bcx.fcx, arg_scope);
1528                 bcx.fcx.lllocals.borrow_mut()
1529                    .insert(pat.id, Datum::new(arg_val, arg_ty, Lvalue));
1530                 bcx
1531             } else {
1532                 mk_binding_alloca(
1533                     bcx, pat.id, ident, arg_scope, arg,
1534                     |arg, bcx, llval, _| arg.store_to(bcx, llval))
1535             }
1536         }
1537
1538         None => {
1539             // General path. Copy out the values that are used in the
1540             // pattern.
1541             let arg = unpack_datum!(
1542                 bcx, arg.to_lvalue_datum_in_scope(bcx, "__arg", arg_scope));
1543             bind_irrefutable_pat(bcx, pat, arg.val, arg_scope)
1544         }
1545     }
1546 }
1547
1548 /// Generates code for the pattern binding in a `for` loop like
1549 /// `for <pat> in <expr> { ... }`.
1550 pub fn store_for_loop_binding<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1551                                           pat: &ast::Pat,
1552                                           llvalue: ValueRef,
1553                                           body_scope: cleanup::ScopeId)
1554                                           -> Block<'blk, 'tcx> {
1555     let _icx = push_ctxt("match::store_for_loop_binding");
1556
1557     if simple_identifier(&*pat).is_some() &&
1558        bcx.sess().opts.debuginfo != FullDebugInfo {
1559         // Generate nicer LLVM for the common case of a `for` loop pattern
1560         // like `for x in blahblah { ... }`.
1561         let binding_type = node_id_type(bcx, pat.id);
1562         bcx.fcx.lllocals.borrow_mut().insert(pat.id,
1563                                              Datum::new(llvalue,
1564                                                         binding_type,
1565                                                         Lvalue));
1566         return bcx
1567     }
1568
1569     // General path. Copy out the values that are used in the pattern.
1570     bind_irrefutable_pat(bcx, pat, llvalue, body_scope)
1571 }
1572
1573 fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
1574                                        p_id: ast::NodeId,
1575                                        ident: &ast::Ident,
1576                                        cleanup_scope: cleanup::ScopeId,
1577                                        arg: A,
1578                                        populate: F)
1579                                        -> Block<'blk, 'tcx> where
1580     F: FnOnce(A, Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
1581 {
1582     let var_ty = node_id_type(bcx, p_id);
1583
1584     // Allocate memory on stack for the binding.
1585     let llval = alloc_ty(bcx, var_ty, bcx.ident(*ident)[]);
1586
1587     // Subtle: be sure that we *populate* the memory *before*
1588     // we schedule the cleanup.
1589     let bcx = populate(arg, bcx, llval, var_ty);
1590     bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1591     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
1592
1593     // Now that memory is initialized and has cleanup scheduled,
1594     // create the datum and insert into the local variable map.
1595     let datum = Datum::new(llval, var_ty, Lvalue);
1596     bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1597     bcx
1598 }
1599
1600 /// A simple version of the pattern matching code that only handles
1601 /// irrefutable patterns. This is used in let/argument patterns,
1602 /// not in match statements. Unifying this code with the code above
1603 /// sounds nice, but in practice it produces very inefficient code,
1604 /// since the match code is so much more general. In most cases,
1605 /// LLVM is able to optimize the code, but it causes longer compile
1606 /// times and makes the generated code nigh impossible to read.
1607 ///
1608 /// # Arguments
1609 /// - bcx: starting basic block context
1610 /// - pat: the irrefutable pattern being matched.
1611 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1612 fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1613                                     pat: &ast::Pat,
1614                                     val: ValueRef,
1615                                     cleanup_scope: cleanup::ScopeId)
1616                                     -> Block<'blk, 'tcx> {
1617     debug!("bind_irrefutable_pat(bcx={}, pat={})",
1618            bcx.to_str(),
1619            pat.repr(bcx.tcx()));
1620
1621     if bcx.sess().asm_comments() {
1622         add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
1623                                  pat.repr(bcx.tcx()))[]);
1624     }
1625
1626     let _indenter = indenter();
1627
1628     let _icx = push_ctxt("match::bind_irrefutable_pat");
1629     let mut bcx = bcx;
1630     let tcx = bcx.tcx();
1631     let ccx = bcx.ccx();
1632     match pat.node {
1633         ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1634             if pat_is_binding(&tcx.def_map, &*pat) {
1635                 // Allocate the stack slot where the value of this
1636                 // binding will live and place it into the appropriate
1637                 // map.
1638                 bcx = mk_binding_alloca(
1639                     bcx, pat.id, &path1.node, cleanup_scope, (),
1640                     |(), bcx, llval, ty| {
1641                         match pat_binding_mode {
1642                             ast::BindByValue(_) => {
1643                                 // By value binding: move the value that `val`
1644                                 // points at into the binding's stack slot.
1645                                 let d = Datum::new(val, ty, Lvalue);
1646                                 d.store_to(bcx, llval)
1647                             }
1648
1649                             ast::BindByRef(_) => {
1650                                 // By ref binding: the value of the variable
1651                                 // is the pointer `val` itself.
1652                                 Store(bcx, val, llval);
1653                                 bcx
1654                             }
1655                         }
1656                     });
1657             }
1658
1659             for inner_pat in inner.iter() {
1660                 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1661             }
1662         }
1663         ast::PatEnum(_, ref sub_pats) => {
1664             let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).cloned();
1665             match opt_def {
1666                 Some(def::DefVariant(enum_id, var_id, _)) => {
1667                     let repr = adt::represent_node(bcx, pat.id);
1668                     let vinfo = ty::enum_variant_with_id(ccx.tcx(),
1669                                                          enum_id,
1670                                                          var_id);
1671                     let args = extract_variant_args(bcx,
1672                                                     &*repr,
1673                                                     vinfo.disr_val,
1674                                                     val);
1675                     for sub_pat in sub_pats.iter() {
1676                         for (i, &argval) in args.vals.iter().enumerate() {
1677                             bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
1678                                                        argval, cleanup_scope);
1679                         }
1680                     }
1681                 }
1682                 Some(def::DefStruct(..)) => {
1683                     match *sub_pats {
1684                         None => {
1685                             // This is a unit-like struct. Nothing to do here.
1686                         }
1687                         Some(ref elems) => {
1688                             // This is the tuple struct case.
1689                             let repr = adt::represent_node(bcx, pat.id);
1690                             for (i, elem) in elems.iter().enumerate() {
1691                                 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1692                                                                   val, 0, i);
1693                                 bcx = bind_irrefutable_pat(bcx, &**elem,
1694                                                            fldptr, cleanup_scope);
1695                             }
1696                         }
1697                     }
1698                 }
1699                 _ => {
1700                     // Nothing to do here.
1701                 }
1702             }
1703         }
1704         ast::PatStruct(_, ref fields, _) => {
1705             let tcx = bcx.tcx();
1706             let pat_ty = node_id_type(bcx, pat.id);
1707             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1708             expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
1709                 for f in fields.iter() {
1710                     let ix = ty::field_idx_strict(tcx, f.node.ident.name, field_tys);
1711                     let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val,
1712                                                       discr, ix);
1713                     bcx = bind_irrefutable_pat(bcx, &*f.node.pat, fldptr, cleanup_scope);
1714                 }
1715             })
1716         }
1717         ast::PatTup(ref elems) => {
1718             let repr = adt::represent_node(bcx, pat.id);
1719             for (i, elem) in elems.iter().enumerate() {
1720                 let fldptr = adt::trans_field_ptr(bcx, &*repr, val, 0, i);
1721                 bcx = bind_irrefutable_pat(bcx, &**elem, fldptr, cleanup_scope);
1722             }
1723         }
1724         ast::PatBox(ref inner) => {
1725             let llbox = Load(bcx, val);
1726             bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
1727         }
1728         ast::PatRegion(ref inner) => {
1729             let loaded_val = Load(bcx, val);
1730             bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
1731         }
1732         ast::PatVec(ref before, ref slice, ref after) => {
1733             let pat_ty = node_id_type(bcx, pat.id);
1734             let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1735             match slice {
1736                 &Some(_) => {
1737                     extracted.vals.insert(
1738                         before.len(),
1739                         bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1740                     );
1741                 }
1742                 &None => ()
1743             }
1744             bcx = before
1745                 .iter()
1746                 .chain(slice.iter())
1747                 .chain(after.iter())
1748                 .zip(extracted.vals.into_iter())
1749                 .fold(bcx, |bcx, (inner, elem)|
1750                     bind_irrefutable_pat(bcx, &**inner, elem, cleanup_scope)
1751                 );
1752         }
1753         ast::PatMac(..) => {
1754             bcx.sess().span_bug(pat.span, "unexpanded macro");
1755         }
1756         ast::PatWild(_) | ast::PatLit(_) | ast::PatRange(_, _) => ()
1757     }
1758     return bcx;
1759 }