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