]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/_match.rs
Convert most code to new inner attribute syntax.
[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 up to two LLVM values, called `llmatch` and
68  * `llbinding` respectively (the `llbinding`, as will be described shortly, is
69  * optional and only present for by-value bindings---therefore it is bundled
70  * up as part of the `TransBindingMode` type).  Both point at allocas.
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  * In addition, for each by-value binding (copy or move), we will create a
87  * second alloca (`llbinding`) that will hold the final value.  In this
88  * example, that means that `d` would have this second alloca of type `D` (and
89  * hence `llbinding` has type `D*`).
90  *
91  * Once a pattern is completely matched, and assuming that there is no guard
92  * pattern, we will branch to a block that leads to the body itself.  For any
93  * by-value bindings, this block will first load the ptr from `llmatch` (the
94  * one of type `D*`) and copy/move the value into `llbinding` (the one of type
95  * `D`).  The second alloca then becomes the value of the local variable.  For
96  * by ref bindings, the value of the local variable is simply the first
97  * alloca.
98  *
99  * So, for the example above, we would generate a setup kind of like this:
100  *
101  *        +-------+
102  *        | Entry |
103  *        +-------+
104  *            |
105  *        +-------------------------------------------+
106  *        | llmatch_c = (addr of first half of tuple) |
107  *        | llmatch_d = (addr of first half of tuple) |
108  *        +-------------------------------------------+
109  *            |
110  *        +--------------------------------------+
111  *        | *llbinding_d = **llmatch_dlbinding_d |
112  *        +--------------------------------------+
113  *
114  * If there is a guard, the situation is slightly different, because we must
115  * execute the guard code.  Moreover, we need to do so once for each of the
116  * alternatives that lead to the arm, because if the guard fails, they may
117  * have different points from which to continue the search. Therefore, in that
118  * case, we generate code that looks more like:
119  *
120  *        +-------+
121  *        | Entry |
122  *        +-------+
123  *            |
124  *        +-------------------------------------------+
125  *        | llmatch_c = (addr of first half of tuple) |
126  *        | llmatch_d = (addr of first half of tuple) |
127  *        +-------------------------------------------+
128  *            |
129  *        +-------------------------------------------------+
130  *        | *llbinding_d = **llmatch_dlbinding_d            |
131  *        | check condition                                 |
132  *        | if false { free *llbinding_d, goto next case }  |
133  *        | if true { goto body }                           |
134  *        +-------------------------------------------------+
135  *
136  * The handling for the cleanups is a bit... sensitive.  Basically, the body
137  * is the one that invokes `add_clean()` for each binding.  During the guard
138  * evaluation, we add temporary cleanups and revoke them after the guard is
139  * evaluated (it could fail, after all).  Presuming the guard fails, we drop
140  * the various values we copied explicitly.  Note that guards and moves are
141  * just plain incompatible.
142  *
143  * Some relevant helper functions that manage bindings:
144  * - `create_bindings_map()`
145  * - `store_non_ref_bindings()`
146  * - `insert_lllocals()`
147  *
148  *
149  * ## Notes on vector pattern matching.
150  *
151  * Vector pattern matching is surprisingly tricky. The problem is that
152  * the structure of the vector isn't fully known, and slice matches
153  * can be done on subparts of it.
154  *
155  * The way that vector pattern matches are dealt with, then, is as
156  * follows. First, we make the actual condition associated with a
157  * vector pattern simply a vector length comparison. So the pattern
158  * [1, .. x] gets the condition "vec len >= 1", and the pattern
159  * [.. x] gets the condition "vec len >= 0". The problem here is that
160  * having the condition "vec len >= 1" hold clearly does not mean that
161  * only a pattern that has exactly that condition will match. This
162  * means that it may well be the case that a condition holds, but none
163  * of the patterns matching that condition match; to deal with this,
164  * when doing vector length matches, we have match failures proceed to
165  * the next condition to check.
166  *
167  * There are a couple more subtleties to deal with. While the "actual"
168  * condition associated with vector length tests is simply a test on
169  * the vector length, the actual vec_len Opt entry contains more
170  * information used to restrict which matches are associated with it.
171  * So that all matches in a submatch are matching against the same
172  * values from inside the vector, they are split up by how many
173  * elements they match at the front and at the back of the vector. In
174  * order to make sure that arms are properly checked in order, even
175  * with the overmatching conditions, each vec_len Opt entry is
176  * associated with a range of matches.
177  * Consider the following:
178  *
179  *   match &[1, 2, 3] {
180  *       [1, 1, .. _] => 0,
181  *       [1, 2, 2, .. _] => 1,
182  *       [1, 2, 3, .. _] => 2,
183  *       [1, 2, .. _] => 3,
184  *       _ => 4
185  *   }
186  * The proper arm to match is arm 2, but arms 0 and 3 both have the
187  * condition "len >= 2". If arm 3 was lumped in with arm 0, then the
188  * wrong branch would be taken. Instead, vec_len Opts are associated
189  * with a contiguous range of matches that have the same "shape".
190  * This is sort of ugly and requires a bunch of special handling of
191  * vec_len options.
192  *
193  */
194
195 #![allow(non_camel_case_types)]
196
197 use back::abi;
198 use driver::session::FullDebugInfo;
199 use lib::llvm::{llvm, ValueRef, BasicBlockRef};
200 use middle::const_eval;
201 use middle::borrowck::root_map_key;
202 use middle::lang_items::{UniqStrEqFnLangItem, StrEqFnLangItem};
203 use middle::pat_util::*;
204 use middle::resolve::DefMap;
205 use middle::trans::adt;
206 use middle::trans::base::*;
207 use middle::trans::build::*;
208 use middle::trans::callee;
209 use middle::trans::cleanup;
210 use middle::trans::cleanup::CleanupMethods;
211 use middle::trans::common::*;
212 use middle::trans::consts;
213 use middle::trans::controlflow;
214 use middle::trans::datum;
215 use middle::trans::datum::*;
216 use middle::trans::expr::Dest;
217 use middle::trans::expr;
218 use middle::trans::glue;
219 use middle::trans::tvec;
220 use middle::trans::type_of;
221 use middle::trans::debuginfo;
222 use middle::ty;
223 use util::common::indenter;
224 use util::ppaux::{Repr, vec_map_to_str};
225
226 use collections::HashMap;
227 use std::cell::Cell;
228 use std::vec;
229 use syntax::ast;
230 use syntax::ast::Ident;
231 use syntax::ast_util::path_to_ident;
232 use syntax::ast_util;
233 use syntax::codemap::{Span, DUMMY_SP};
234 use syntax::parse::token::InternedString;
235
236 // An option identifying a literal: either a unit-like struct or an
237 // expression.
238 enum Lit {
239     UnitLikeStructLit(ast::NodeId),    // the node ID of the pattern
240     ExprLit(@ast::Expr),
241     ConstLit(ast::DefId),              // the def ID of the constant
242 }
243
244 #[deriving(Eq)]
245 pub enum VecLenOpt {
246     vec_len_eq,
247     vec_len_ge(/* length of prefix */uint)
248 }
249
250 // An option identifying a branch (either a literal, an enum variant or a
251 // range)
252 enum Opt {
253     lit(Lit),
254     var(ty::Disr, @adt::Repr),
255     range(@ast::Expr, @ast::Expr),
256     vec_len(/* length */ uint, VecLenOpt, /*range of matches*/(uint, uint))
257 }
258
259 fn lit_to_expr(tcx: &ty::ctxt, a: &Lit) -> @ast::Expr {
260     match *a {
261         ExprLit(existing_a_expr) => existing_a_expr,
262         ConstLit(a_const) => const_eval::lookup_const_by_id(tcx, a_const).unwrap(),
263         UnitLikeStructLit(_) => fail!("lit_to_expr: unexpected struct lit"),
264     }
265 }
266
267 fn opt_eq(tcx: &ty::ctxt, a: &Opt, b: &Opt) -> bool {
268     match (a, b) {
269         (&lit(UnitLikeStructLit(a)), &lit(UnitLikeStructLit(b))) => a == b,
270         (&lit(a), &lit(b)) => {
271             let a_expr = lit_to_expr(tcx, &a);
272             let b_expr = lit_to_expr(tcx, &b);
273             match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) {
274                 Some(val1) => val1 == 0,
275                 None => fail!("compare_list_exprs: type mismatch"),
276             }
277         }
278         (&range(a1, a2), &range(b1, b2)) => {
279             let m1 = const_eval::compare_lit_exprs(tcx, a1, b1);
280             let m2 = const_eval::compare_lit_exprs(tcx, a2, b2);
281             match (m1, m2) {
282                 (Some(val1), Some(val2)) => (val1 == 0 && val2 == 0),
283                 _ => fail!("compare_list_exprs: type mismatch"),
284             }
285         }
286         (&var(a, _), &var(b, _)) => a == b,
287         (&vec_len(a1, a2, _), &vec_len(b1, b2, _)) =>
288             a1 == b1 && a2 == b2,
289         _ => false
290     }
291 }
292
293 fn opt_overlap(tcx: &ty::ctxt, a: &Opt, b: &Opt) -> bool {
294     match (a, b) {
295         (&lit(a), &lit(b)) => {
296             let a_expr = lit_to_expr(tcx, &a);
297             let b_expr = lit_to_expr(tcx, &b);
298             match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) {
299                 Some(val1) => val1 == 0,
300                 None => fail!("opt_overlap: type mismatch"),
301             }
302         }
303
304         (&range(a1, a2), &range(b1, b2)) => {
305             let m1 = const_eval::compare_lit_exprs(tcx, a1, b2);
306             let m2 = const_eval::compare_lit_exprs(tcx, b1, a2);
307             match (m1, m2) {
308                 // two ranges [a1, a2] and [b1, b2] overlap iff:
309                 //      a1 <= b2 && b1 <= a2
310                 (Some(val1), Some(val2)) => (val1 <= 0 && val2 <= 0),
311                 _ => fail!("opt_overlap: type mismatch"),
312             }
313         }
314
315         (&range(a1, a2), &lit(b)) | (&lit(b), &range(a1, a2)) => {
316             let b_expr = lit_to_expr(tcx, &b);
317             let m1 = const_eval::compare_lit_exprs(tcx, a1, b_expr);
318             let m2 = const_eval::compare_lit_exprs(tcx, a2, b_expr);
319             match (m1, m2) {
320                 // b is in range [a1, a2] iff a1 <= b and b <= a2
321                 (Some(val1), Some(val2)) => (val1 <= 0 && 0 <= val2),
322                 _ => fail!("opt_overlap: type mismatch"),
323             }
324         }
325         _ => fail!("opt_overlap: expect lit or range")
326     }
327 }
328
329 pub enum opt_result<'a> {
330     single_result(Result<'a>),
331     lower_bound(Result<'a>),
332     range_result(Result<'a>, Result<'a>),
333 }
334
335 fn trans_opt<'a>(bcx: &'a Block<'a>, o: &Opt) -> opt_result<'a> {
336     let _icx = push_ctxt("match::trans_opt");
337     let ccx = bcx.ccx();
338     let mut bcx = bcx;
339     match *o {
340         lit(ExprLit(lit_expr)) => {
341             let lit_datum = unpack_datum!(bcx, expr::trans(bcx, lit_expr));
342             let lit_datum = lit_datum.assert_rvalue(bcx); // literals are rvalues
343             let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
344             return single_result(rslt(bcx, lit_datum.val));
345         }
346         lit(UnitLikeStructLit(pat_id)) => {
347             let struct_ty = ty::node_id_to_type(bcx.tcx(), pat_id);
348             let datum = datum::rvalue_scratch_datum(bcx, struct_ty, "");
349             return single_result(rslt(bcx, datum.val));
350         }
351         lit(ConstLit(lit_id)) => {
352             let (llval, _) = consts::get_const_val(bcx.ccx(), lit_id);
353             return single_result(rslt(bcx, llval));
354         }
355         var(disr_val, repr) => {
356             return adt::trans_case(bcx, repr, disr_val);
357         }
358         range(l1, l2) => {
359             let (l1, _) = consts::const_expr(ccx, l1, true);
360             let (l2, _) = consts::const_expr(ccx, l2, true);
361             return range_result(rslt(bcx, l1), rslt(bcx, l2));
362         }
363         vec_len(n, vec_len_eq, _) => {
364             return single_result(rslt(bcx, C_int(ccx, n as int)));
365         }
366         vec_len(n, vec_len_ge(_), _) => {
367             return lower_bound(rslt(bcx, C_int(ccx, n as int)));
368         }
369     }
370 }
371
372 fn variant_opt(bcx: &Block, pat_id: ast::NodeId) -> Opt {
373     let ccx = bcx.ccx();
374     let def = ccx.tcx.def_map.borrow().get_copy(&pat_id);
375     match def {
376         ast::DefVariant(enum_id, var_id, _) => {
377             let variants = ty::enum_variants(ccx.tcx(), enum_id);
378             for v in (*variants).iter() {
379                 if var_id == v.id {
380                     return var(v.disr_val,
381                                adt::represent_node(bcx, pat_id))
382                 }
383             }
384             unreachable!();
385         }
386         ast::DefFn(..) |
387         ast::DefStruct(_) => {
388             return lit(UnitLikeStructLit(pat_id));
389         }
390         _ => {
391             ccx.sess().bug("non-variant or struct in variant_opt()");
392         }
393     }
394 }
395
396 #[deriving(Clone)]
397 enum TransBindingMode {
398     TrByValue(/*llbinding:*/ ValueRef),
399     TrByRef,
400 }
401
402 /**
403  * Information about a pattern binding:
404  * - `llmatch` is a pointer to a stack slot.  The stack slot contains a
405  *   pointer into the value being matched.  Hence, llmatch has type `T**`
406  *   where `T` is the value being matched.
407  * - `trmode` is the trans binding mode
408  * - `id` is the node id of the binding
409  * - `ty` is the Rust type of the binding */
410  #[deriving(Clone)]
411 struct BindingInfo {
412     llmatch: ValueRef,
413     trmode: TransBindingMode,
414     id: ast::NodeId,
415     span: Span,
416     ty: ty::t,
417 }
418
419 type BindingsMap = HashMap<Ident, BindingInfo>;
420
421 struct ArmData<'a,'b> {
422     bodycx: &'b Block<'b>,
423     arm: &'a ast::Arm,
424     bindings_map: @BindingsMap
425 }
426
427 // FIXME #11820: method resolution is unreliable with &
428 impl<'a,'b> Clone for ArmData<'a, 'b> {
429     fn clone(&self) -> ArmData<'a, 'b> { *self }
430 }
431
432 /**
433  * Info about Match.
434  * If all `pats` are matched then arm `data` will be executed.
435  * As we proceed `bound_ptrs` are filled with pointers to values to be bound,
436  * these pointers are stored in llmatch variables just before executing `data` arm.
437  */
438 #[deriving(Clone)]
439 struct Match<'a,'b> {
440     pats: Vec<@ast::Pat> ,
441     data: ArmData<'a,'b>,
442     bound_ptrs: Vec<(Ident, ValueRef)> }
443
444 impl<'a,'b> Repr for Match<'a,'b> {
445     fn repr(&self, tcx: &ty::ctxt) -> ~str {
446         if tcx.sess.verbose() {
447             // for many programs, this just take too long to serialize
448             self.pats.repr(tcx)
449         } else {
450             format!("{} pats", self.pats.len())
451         }
452     }
453 }
454
455 fn has_nested_bindings(m: &[Match], col: uint) -> bool {
456     for br in m.iter() {
457         match br.pats.get(col).node {
458             ast::PatIdent(_, _, Some(_)) => return true,
459             _ => ()
460         }
461     }
462     return false;
463 }
464
465 fn expand_nested_bindings<'r,'b>(
466                           bcx: &'b Block<'b>,
467                           m: &[Match<'r,'b>],
468                           col: uint,
469                           val: ValueRef)
470                           -> Vec<Match<'r,'b>> {
471     debug!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
472            bcx.to_str(),
473            m.repr(bcx.tcx()),
474            col,
475            bcx.val_to_str(val));
476     let _indenter = indenter();
477
478     m.iter().map(|br| {
479         match br.pats.get(col).node {
480             ast::PatIdent(_, ref path, Some(inner)) => {
481                 let pats = vec::append(
482                     Vec::from_slice(br.pats.slice(0u, col)),
483                     vec::append(vec!(inner),
484                                 br.pats.slice(col + 1u,
485                                            br.pats.len())).as_slice());
486
487                 let mut res = Match {
488                     pats: pats,
489                     data: br.data.clone(),
490                     bound_ptrs: br.bound_ptrs.clone()
491                 };
492                 res.bound_ptrs.push((path_to_ident(path), val));
493                 res
494             }
495             _ => (*br).clone(),
496         }
497     }).collect()
498 }
499
500 fn assert_is_binding_or_wild(bcx: &Block, p: @ast::Pat) {
501     if !pat_is_binding_or_wild(bcx.tcx().def_map, p) {
502         bcx.sess().span_bug(
503             p.span,
504             format!("expected an identifier pattern but found p: {}",
505                  p.repr(bcx.tcx())));
506     }
507 }
508
509 type enter_pat<'a> = 'a |@ast::Pat| -> Option<Vec<@ast::Pat>>;
510
511 fn enter_match<'r,'b>(
512                bcx: &'b Block<'b>,
513                dm: DefMap,
514                m: &[Match<'r,'b>],
515                col: uint,
516                val: ValueRef,
517                e: enter_pat)
518                -> Vec<Match<'r,'b>> {
519     debug!("enter_match(bcx={}, m={}, col={}, val={})",
520            bcx.to_str(),
521            m.repr(bcx.tcx()),
522            col,
523            bcx.val_to_str(val));
524     let _indenter = indenter();
525
526     let mut result = Vec::new();
527     for br in m.iter() {
528         match e(*br.pats.get(col)) {
529             Some(sub) => {
530                 let pats =
531                     vec::append(
532                         vec::append(sub, br.pats.slice(0u, col)),
533                         br.pats.slice(col + 1u, br.pats.len()));
534
535                 let this = *br.pats.get(col);
536                 let mut bound_ptrs = br.bound_ptrs.clone();
537                 match this.node {
538                     ast::PatIdent(_, ref path, None) => {
539                         if pat_is_binding(dm, this) {
540                             bound_ptrs.push((path_to_ident(path), val));
541                         }
542                     }
543                     _ => {}
544                 }
545
546                 result.push(Match {
547                     pats: pats,
548                     data: br.data.clone(),
549                     bound_ptrs: bound_ptrs
550                 });
551             }
552             None => ()
553         }
554     }
555
556     debug!("result={}", result.repr(bcx.tcx()));
557
558     return result;
559 }
560
561 fn enter_default<'r,'b>(
562                  bcx: &'b Block<'b>,
563                  dm: DefMap,
564                  m: &[Match<'r,'b>],
565                  col: uint,
566                  val: ValueRef,
567                  chk: &FailureHandler)
568                  -> Vec<Match<'r,'b>> {
569     debug!("enter_default(bcx={}, m={}, col={}, val={})",
570            bcx.to_str(),
571            m.repr(bcx.tcx()),
572            col,
573            bcx.val_to_str(val));
574     let _indenter = indenter();
575
576     // Collect all of the matches that can match against anything.
577     let matches = enter_match(bcx, dm, m, col, val, |p| {
578         match p.node {
579           ast::PatWild | ast::PatWildMulti | ast::PatTup(_) => Some(Vec::new()),
580           ast::PatIdent(_, _, None) if pat_is_binding(dm, p) => Some(Vec::new()),
581           _ => None
582         }
583     });
584
585     // Ok, now, this is pretty subtle. A "default" match is a match
586     // that needs to be considered if none of the actual checks on the
587     // value being considered succeed. The subtlety lies in that sometimes
588     // identifier/wildcard matches are *not* default matches. Consider:
589     // "match x { _ if something => foo, true => bar, false => baz }".
590     // There is a wildcard match, but it is *not* a default case. The boolean
591     // case on the value being considered is exhaustive. If the case is
592     // exhaustive, then there are no defaults.
593     //
594     // We detect whether the case is exhaustive in the following
595     // somewhat kludgy way: if the last wildcard/binding match has a
596     // guard, then by non-redundancy, we know that there aren't any
597     // non guarded matches, and thus by exhaustiveness, we know that
598     // we don't need any default cases. If the check *isn't* nonexhaustive
599     // (because chk is Some), then we need the defaults anyways.
600     let is_exhaustive = match matches.last() {
601         Some(m) if m.data.arm.guard.is_some() && chk.is_infallible() => true,
602         _ => false
603     };
604
605     if is_exhaustive { Vec::new() } else { matches }
606 }
607
608 // <pcwalton> nmatsakis: what does enter_opt do?
609 // <pcwalton> in trans/match
610 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
611 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
612 //             patterns as needed
613 // <nmatsakis> yeah, at some point I kind of achieved some level of
614 //             understanding
615 // <nmatsakis> anyhow, they adjust the patterns given that something of that
616 //             kind has been found
617 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
618 //             said
619 // <nmatsakis> enter_match() kind of embodies the generic code
620 // <nmatsakis> it is provided with a function that tests each pattern to see
621 //             if it might possibly apply and so forth
622 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
623 // <nmatsakis> then _ would be expanded to (_, _)
624 // <nmatsakis> one spot for each of the sub-patterns
625 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
626 //             cases
627 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
628 //             are infallible patterns
629 // <nmatsakis> so all patterns must either be records (resp. tuples) or
630 //             wildcards
631
632 fn enter_opt<'r,'b>(
633              bcx: &'b Block<'b>,
634              m: &[Match<'r,'b>],
635              opt: &Opt,
636              col: uint,
637              variant_size: uint,
638              val: ValueRef)
639              -> Vec<Match<'r,'b>> {
640     debug!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})",
641            bcx.to_str(),
642            m.repr(bcx.tcx()),
643            *opt,
644            col,
645            bcx.val_to_str(val));
646     let _indenter = indenter();
647
648     let tcx = bcx.tcx();
649     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
650     let mut i = 0;
651     // By the virtue of fact that we are in `trans` already, `enter_opt` is able
652     // to prune sub-match tree aggressively based on exact equality. But when it
653     // comes to literal or range, that strategy may lead to wrong result if there
654     // are guard function or multiple patterns inside tuple; in that case, pruning
655     // based on the overlap of patterns is required.
656     //
657     // Ideally, when constructing the sub-match tree for certain arm, only those
658     // arms beneath it matter. But that isn't how algorithm works right now and
659     // all other arms are taken into consideration when computing `guarded` below.
660     // That is ok since each round of `compile_submatch` guarantees to trim one
661     // "column" of arm patterns and the algorithm will converge.
662     let guarded = m.iter().any(|x| x.data.arm.guard.is_some());
663     let multi_pats = m.len() > 0 && m[0].pats.len() > 1;
664     enter_match(bcx, tcx.def_map, m, col, val, |p| {
665         let answer = match p.node {
666             ast::PatEnum(..) |
667             ast::PatIdent(_, _, None) if pat_is_const(tcx.def_map, p) => {
668                 let const_def = tcx.def_map.borrow().get_copy(&p.id);
669                 let const_def_id = ast_util::def_id_of_def(const_def);
670                 let konst = lit(ConstLit(const_def_id));
671                 match guarded || multi_pats {
672                     false if opt_eq(tcx, &konst, opt) => Some(Vec::new()),
673                     true if opt_overlap(tcx, &konst, opt) => Some(Vec::new()),
674                     _ => None,
675                 }
676             }
677             ast::PatEnum(_, ref subpats) => {
678                 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
679                     // FIXME: Must we clone?
680                     match *subpats {
681                         None => Some(Vec::from_elem(variant_size, dummy)),
682                         Some(ref subpats) => {
683                             Some((*subpats).iter().map(|x| *x).collect())
684                         }
685                     }
686                 } else {
687                     None
688                 }
689             }
690             ast::PatIdent(_, _, None)
691                     if pat_is_variant_or_struct(tcx.def_map, p) => {
692                 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
693                     Some(Vec::new())
694                 } else {
695                     None
696                 }
697             }
698             ast::PatLit(l) => {
699                 let lit_expr = lit(ExprLit(l));
700                 match guarded || multi_pats {
701                     false if opt_eq(tcx, &lit_expr, opt) => Some(Vec::new()),
702                     true if opt_overlap(tcx, &lit_expr, opt) => Some(Vec::new()),
703                     _ => None,
704                 }
705             }
706             ast::PatRange(l1, l2) => {
707                 let rng = range(l1, l2);
708                 match guarded || multi_pats {
709                     false if opt_eq(tcx, &rng, opt) => Some(Vec::new()),
710                     true if opt_overlap(tcx, &rng, opt) => Some(Vec::new()),
711                     _ => None,
712                 }
713             }
714             ast::PatStruct(_, ref field_pats, _) => {
715                 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
716                     // Look up the struct variant ID.
717                     let struct_id;
718                     match tcx.def_map.borrow().get_copy(&p.id) {
719                         ast::DefVariant(_, found_struct_id, _) => {
720                             struct_id = found_struct_id;
721                         }
722                         _ => {
723                             tcx.sess.span_bug(p.span, "expected enum variant def");
724                         }
725                     }
726
727                     // Reorder the patterns into the same order they were
728                     // specified in the struct definition. Also fill in
729                     // unspecified fields with dummy.
730                     let mut reordered_patterns = Vec::new();
731                     let r = ty::lookup_struct_fields(tcx, struct_id);
732                     for field in r.iter() {
733                             match field_pats.iter().find(|p| p.ident.name
734                                                          == field.name) {
735                                 None => reordered_patterns.push(dummy),
736                                 Some(fp) => reordered_patterns.push(fp.pat)
737                             }
738                     }
739                     Some(reordered_patterns)
740                 } else {
741                     None
742                 }
743             }
744             ast::PatVec(ref before, slice, ref after) => {
745                 let (lo, hi) = match *opt {
746                     vec_len(_, _, (lo, hi)) => (lo, hi),
747                     _ => tcx.sess.span_bug(p.span,
748                                            "vec pattern but not vec opt")
749                 };
750
751                 match slice {
752                     Some(slice) if i >= lo && i <= hi => {
753                         let n = before.len() + after.len();
754                         let this_opt = vec_len(n, vec_len_ge(before.len()),
755                                                (lo, hi));
756                         if opt_eq(tcx, &this_opt, opt) {
757                             let mut new_before = Vec::new();
758                             for pat in before.iter() {
759                                 new_before.push(*pat);
760                             }
761                             new_before.push(slice);
762                             for pat in after.iter() {
763                                 new_before.push(*pat);
764                             }
765                             Some(new_before)
766                         } else {
767                             None
768                         }
769                     }
770                     None if i >= lo && i <= hi => {
771                         let n = before.len();
772                         if opt_eq(tcx, &vec_len(n, vec_len_eq, (lo,hi)), opt) {
773                             let mut new_before = Vec::new();
774                             for pat in before.iter() {
775                                 new_before.push(*pat);
776                             }
777                             Some(new_before)
778                         } else {
779                             None
780                         }
781                     }
782                     _ => None
783                 }
784             }
785             _ => {
786                 assert_is_binding_or_wild(bcx, p);
787                 // In most cases, a binding/wildcard match be
788                 // considered to match against any Opt. However, when
789                 // doing vector pattern matching, submatches are
790                 // considered even if the eventual match might be from
791                 // a different submatch. Thus, when a submatch fails
792                 // when doing a vector match, we proceed to the next
793                 // submatch. Thus, including a default match would
794                 // cause the default match to fire spuriously.
795                 match *opt {
796                     vec_len(..) => None,
797                     _ => Some(Vec::from_elem(variant_size, dummy))
798                 }
799             }
800         };
801         i += 1;
802         answer
803     })
804 }
805
806 fn enter_rec_or_struct<'r,'b>(
807                        bcx: &'b Block<'b>,
808                        dm: DefMap,
809                        m: &[Match<'r,'b>],
810                        col: uint,
811                        fields: &[ast::Ident],
812                        val: ValueRef)
813                        -> Vec<Match<'r,'b>> {
814     debug!("enter_rec_or_struct(bcx={}, m={}, col={}, val={})",
815            bcx.to_str(),
816            m.repr(bcx.tcx()),
817            col,
818            bcx.val_to_str(val));
819     let _indenter = indenter();
820
821     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
822     enter_match(bcx, dm, m, col, val, |p| {
823         match p.node {
824             ast::PatStruct(_, ref fpats, _) => {
825                 let mut pats = Vec::new();
826                 for fname in fields.iter() {
827                     match fpats.iter().find(|p| p.ident.name == fname.name) {
828                         None => pats.push(dummy),
829                         Some(pat) => pats.push(pat.pat)
830                     }
831                 }
832                 Some(pats)
833             }
834             _ => {
835                 assert_is_binding_or_wild(bcx, p);
836                 Some(Vec::from_elem(fields.len(), dummy))
837             }
838         }
839     })
840 }
841
842 fn enter_tup<'r,'b>(
843              bcx: &'b Block<'b>,
844              dm: DefMap,
845              m: &[Match<'r,'b>],
846              col: uint,
847              val: ValueRef,
848              n_elts: uint)
849              -> Vec<Match<'r,'b>> {
850     debug!("enter_tup(bcx={}, m={}, col={}, val={})",
851            bcx.to_str(),
852            m.repr(bcx.tcx()),
853            col,
854            bcx.val_to_str(val));
855     let _indenter = indenter();
856
857     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
858     enter_match(bcx, dm, m, col, val, |p| {
859         match p.node {
860             ast::PatTup(ref elts) => {
861                 let mut new_elts = Vec::new();
862                 for elt in elts.iter() {
863                     new_elts.push((*elt).clone())
864                 }
865                 Some(new_elts)
866             }
867             _ => {
868                 assert_is_binding_or_wild(bcx, p);
869                 Some(Vec::from_elem(n_elts, dummy))
870             }
871         }
872     })
873 }
874
875 fn enter_tuple_struct<'r,'b>(
876                       bcx: &'b Block<'b>,
877                       dm: DefMap,
878                       m: &[Match<'r,'b>],
879                       col: uint,
880                       val: ValueRef,
881                       n_elts: uint)
882                       -> Vec<Match<'r,'b>> {
883     debug!("enter_tuple_struct(bcx={}, m={}, col={}, val={})",
884            bcx.to_str(),
885            m.repr(bcx.tcx()),
886            col,
887            bcx.val_to_str(val));
888     let _indenter = indenter();
889
890     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
891     enter_match(bcx, dm, m, col, val, |p| {
892         match p.node {
893             ast::PatEnum(_, Some(ref elts)) => {
894                 Some(elts.iter().map(|x| (*x)).collect())
895             }
896             _ => {
897                 assert_is_binding_or_wild(bcx, p);
898                 Some(Vec::from_elem(n_elts, dummy))
899             }
900         }
901     })
902 }
903
904 fn enter_uniq<'r,'b>(
905               bcx: &'b Block<'b>,
906               dm: DefMap,
907               m: &[Match<'r,'b>],
908               col: uint,
909               val: ValueRef)
910               -> Vec<Match<'r,'b>> {
911     debug!("enter_uniq(bcx={}, m={}, col={}, val={})",
912            bcx.to_str(),
913            m.repr(bcx.tcx()),
914            col,
915            bcx.val_to_str(val));
916     let _indenter = indenter();
917
918     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
919     enter_match(bcx, dm, m, col, val, |p| {
920         match p.node {
921             ast::PatUniq(sub) => {
922                 Some(vec!(sub))
923             }
924             _ => {
925                 assert_is_binding_or_wild(bcx, p);
926                 Some(vec!(dummy))
927             }
928         }
929     })
930 }
931
932 fn enter_region<'r,
933                 'b>(
934                 bcx: &'b Block<'b>,
935                 dm: DefMap,
936                 m: &[Match<'r,'b>],
937                 col: uint,
938                 val: ValueRef)
939                 -> Vec<Match<'r,'b>> {
940     debug!("enter_region(bcx={}, m={}, col={}, val={})",
941            bcx.to_str(),
942            m.repr(bcx.tcx()),
943            col,
944            bcx.val_to_str(val));
945     let _indenter = indenter();
946
947     let dummy = @ast::Pat { id: 0, node: ast::PatWild, span: DUMMY_SP };
948     enter_match(bcx, dm, m, col, val, |p| {
949         match p.node {
950             ast::PatRegion(sub) => {
951                 Some(vec!(sub))
952             }
953             _ => {
954                 assert_is_binding_or_wild(bcx, p);
955                 Some(vec!(dummy))
956             }
957         }
958     })
959 }
960
961 // Returns the options in one column of matches. An option is something that
962 // needs to be conditionally matched at runtime; for example, the discriminant
963 // on a set of enum variants or a literal.
964 fn get_options(bcx: &Block, m: &[Match], col: uint) -> Vec<Opt> {
965     let ccx = bcx.ccx();
966     fn add_to_set(tcx: &ty::ctxt, set: &mut Vec<Opt>, val: Opt) {
967         if set.iter().any(|l| opt_eq(tcx, l, &val)) {return;}
968         set.push(val);
969     }
970     // Vector comparisions are special in that since the actual
971     // conditions over-match, we need to be careful about them. This
972     // means that in order to properly handle things in order, we need
973     // to not always merge conditions.
974     fn add_veclen_to_set(set: &mut Vec<Opt> , i: uint,
975                          len: uint, vlo: VecLenOpt) {
976         match set.last() {
977             // If the last condition in the list matches the one we want
978             // to add, then extend its range. Otherwise, make a new
979             // vec_len with a range just covering the new entry.
980             Some(&vec_len(len2, vlo2, (start, end)))
981                  if len == len2 && vlo == vlo2 => {
982                 let length = set.len();
983                  *set.get_mut(length - 1) =
984                      vec_len(len, vlo, (start, end+1))
985             }
986             _ => set.push(vec_len(len, vlo, (i, i)))
987         }
988     }
989
990     let mut found = Vec::new();
991     for (i, br) in m.iter().enumerate() {
992         let cur = *br.pats.get(col);
993         match cur.node {
994             ast::PatLit(l) => {
995                 add_to_set(ccx.tcx(), &mut found, lit(ExprLit(l)));
996             }
997             ast::PatIdent(..) => {
998                 // This is one of: an enum variant, a unit-like struct, or a
999                 // variable binding.
1000                 let opt_def = ccx.tcx.def_map.borrow().find_copy(&cur.id);
1001                 match opt_def {
1002                     Some(ast::DefVariant(..)) => {
1003                         add_to_set(ccx.tcx(), &mut found,
1004                                    variant_opt(bcx, cur.id));
1005                     }
1006                     Some(ast::DefStruct(..)) => {
1007                         add_to_set(ccx.tcx(), &mut found,
1008                                    lit(UnitLikeStructLit(cur.id)));
1009                     }
1010                     Some(ast::DefStatic(const_did, false)) => {
1011                         add_to_set(ccx.tcx(), &mut found,
1012                                    lit(ConstLit(const_did)));
1013                     }
1014                     _ => {}
1015                 }
1016             }
1017             ast::PatEnum(..) | ast::PatStruct(..) => {
1018                 // This could be one of: a tuple-like enum variant, a
1019                 // struct-like enum variant, or a struct.
1020                 let opt_def = ccx.tcx.def_map.borrow().find_copy(&cur.id);
1021                 match opt_def {
1022                     Some(ast::DefFn(..)) |
1023                     Some(ast::DefVariant(..)) => {
1024                         add_to_set(ccx.tcx(), &mut found,
1025                                    variant_opt(bcx, cur.id));
1026                     }
1027                     Some(ast::DefStatic(const_did, false)) => {
1028                         add_to_set(ccx.tcx(), &mut found,
1029                                    lit(ConstLit(const_did)));
1030                     }
1031                     _ => {}
1032                 }
1033             }
1034             ast::PatRange(l1, l2) => {
1035                 add_to_set(ccx.tcx(), &mut found, range(l1, l2));
1036             }
1037             ast::PatVec(ref before, slice, ref after) => {
1038                 let (len, vec_opt) = match slice {
1039                     None => (before.len(), vec_len_eq),
1040                     Some(_) => (before.len() + after.len(),
1041                                 vec_len_ge(before.len()))
1042                 };
1043                 add_veclen_to_set(&mut found, i, len, vec_opt);
1044             }
1045             _ => {}
1046         }
1047     }
1048     return found;
1049 }
1050
1051 struct ExtractedBlock<'a> {
1052     vals: Vec<ValueRef> ,
1053     bcx: &'a Block<'a>,
1054 }
1055
1056 fn extract_variant_args<'a>(
1057                         bcx: &'a Block<'a>,
1058                         repr: &adt::Repr,
1059                         disr_val: ty::Disr,
1060                         val: ValueRef)
1061                         -> ExtractedBlock<'a> {
1062     let _icx = push_ctxt("match::extract_variant_args");
1063     let args = Vec::from_fn(adt::num_args(repr, disr_val), |i| {
1064         adt::trans_field_ptr(bcx, repr, val, disr_val, i)
1065     });
1066
1067     ExtractedBlock { vals: args, bcx: bcx }
1068 }
1069
1070 fn match_datum(bcx: &Block,
1071                val: ValueRef,
1072                pat_id: ast::NodeId)
1073                -> Datum<Lvalue> {
1074     /*!
1075      * Helper for converting from the ValueRef that we pass around in
1076      * the match code, which is always an lvalue, into a Datum. Eventually
1077      * we should just pass around a Datum and be done with it.
1078      */
1079
1080     let ty = node_id_type(bcx, pat_id);
1081     Datum(val, ty, Lvalue)
1082 }
1083
1084
1085 fn extract_vec_elems<'a>(
1086                      bcx: &'a Block<'a>,
1087                      pat_id: ast::NodeId,
1088                      elem_count: uint,
1089                      slice: Option<uint>,
1090                      val: ValueRef,
1091                      count: ValueRef)
1092                      -> ExtractedBlock<'a> {
1093     let _icx = push_ctxt("match::extract_vec_elems");
1094     let vec_datum = match_datum(bcx, val, pat_id);
1095     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
1096     let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id));
1097
1098     let mut elems = Vec::from_fn(elem_count, |i| {
1099         match slice {
1100             None => GEPi(bcx, base, [i]),
1101             Some(n) if i < n => GEPi(bcx, base, [i]),
1102             Some(n) if i > n => {
1103                 InBoundsGEP(bcx, base, [
1104                     Sub(bcx, count,
1105                         C_int(bcx.ccx(), (elem_count - i) as int))])
1106             }
1107             _ => unsafe { llvm::LLVMGetUndef(vt.llunit_ty.to_ref()) }
1108         }
1109     });
1110     if slice.is_some() {
1111         let n = slice.unwrap();
1112         let slice_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), n));
1113         let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset);
1114         let slice_len_offset = C_uint(bcx.ccx(), elem_count - 1u);
1115         let slice_len = Sub(bcx, len, slice_len_offset);
1116         let slice_ty = ty::mk_vec(bcx.tcx(),
1117             ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable},
1118             ty::vstore_slice(ty::ReStatic)
1119         );
1120         let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
1121         Store(bcx, slice_begin,
1122               GEPi(bcx, scratch.val, [0u, abi::slice_elt_base]));
1123         Store(bcx, slice_len, GEPi(bcx, scratch.val, [0u, abi::slice_elt_len]));
1124         *elems.get_mut(n) = scratch.val;
1125     }
1126
1127     ExtractedBlock { vals: elems, bcx: bcx }
1128 }
1129
1130 /// Checks every pattern in `m` at `col` column.
1131 /// If there are a struct pattern among them function
1132 /// returns list of all fields that are matched in these patterns.
1133 /// Function returns None if there is no struct pattern.
1134 /// Function doesn't collect fields from struct-like enum variants.
1135 /// Function can return empty list if there is only wildcard struct pattern.
1136 fn collect_record_or_struct_fields<'a>(
1137                                    bcx: &'a Block<'a>,
1138                                    m: &[Match],
1139                                    col: uint)
1140                                    -> Option<Vec<ast::Ident> > {
1141     let mut fields: Vec<ast::Ident> = Vec::new();
1142     let mut found = false;
1143     for br in m.iter() {
1144         match br.pats.get(col).node {
1145           ast::PatStruct(_, ref fs, _) => {
1146             match ty::get(node_id_type(bcx, br.pats.get(col).id)).sty {
1147               ty::ty_struct(..) => {
1148                    extend(&mut fields, fs.as_slice());
1149                    found = true;
1150               }
1151               _ => ()
1152             }
1153           }
1154           _ => ()
1155         }
1156     }
1157     if found {
1158         return Some(fields);
1159     } else {
1160         return None;
1161     }
1162
1163     fn extend(idents: &mut Vec<ast::Ident> , field_pats: &[ast::FieldPat]) {
1164         for field_pat in field_pats.iter() {
1165             let field_ident = field_pat.ident;
1166             if !idents.iter().any(|x| x.name == field_ident.name) {
1167                 idents.push(field_ident);
1168             }
1169         }
1170     }
1171 }
1172
1173 fn pats_require_rooting(bcx: &Block, m: &[Match], col: uint) -> bool {
1174     m.iter().any(|br| {
1175         let pat_id = br.pats.get(col).id;
1176         let key = root_map_key {id: pat_id, derefs: 0u };
1177         bcx.ccx().maps.root_map.borrow().contains_key(&key)
1178     })
1179 }
1180
1181 // Macro for deciding whether any of the remaining matches fit a given kind of
1182 // pattern.  Note that, because the macro is well-typed, either ALL of the
1183 // matches should fit that sort of pattern or NONE (however, some of the
1184 // matches may be wildcards like _ or identifiers).
1185 macro_rules! any_pat (
1186     ($m:expr, $pattern:pat) => (
1187         ($m).iter().any(|br| {
1188             match br.pats.get(col).node {
1189                 $pattern => true,
1190                 _ => false
1191             }
1192         })
1193     )
1194 )
1195
1196 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
1197     any_pat!(m, ast::PatUniq(_))
1198 }
1199
1200 fn any_region_pat(m: &[Match], col: uint) -> bool {
1201     any_pat!(m, ast::PatRegion(_))
1202 }
1203
1204 fn any_tup_pat(m: &[Match], col: uint) -> bool {
1205     any_pat!(m, ast::PatTup(_))
1206 }
1207
1208 fn any_tuple_struct_pat(bcx: &Block, m: &[Match], col: uint) -> bool {
1209     m.iter().any(|br| {
1210         let pat = *br.pats.get(col);
1211         match pat.node {
1212             ast::PatEnum(_, Some(_)) => {
1213                 match bcx.tcx().def_map.borrow().find(&pat.id) {
1214                     Some(&ast::DefFn(..)) |
1215                     Some(&ast::DefStruct(..)) => true,
1216                     _ => false
1217                 }
1218             }
1219             _ => false
1220         }
1221     })
1222 }
1223
1224 struct DynamicFailureHandler<'a> {
1225     bcx: &'a Block<'a>,
1226     sp: Span,
1227     msg: InternedString,
1228     finished: Cell<Option<BasicBlockRef>>,
1229 }
1230
1231 impl<'a> DynamicFailureHandler<'a> {
1232     fn handle_fail(&self) -> BasicBlockRef {
1233         match self.finished.get() {
1234             Some(bb) => return bb,
1235             _ => (),
1236         }
1237
1238         let fcx = self.bcx.fcx;
1239         let fail_cx = fcx.new_block(false, "case_fallthrough", None);
1240         controlflow::trans_fail(fail_cx, self.sp, self.msg.clone());
1241         self.finished.set(Some(fail_cx.llbb));
1242         fail_cx.llbb
1243     }
1244 }
1245
1246 /// What to do when the pattern match fails.
1247 enum FailureHandler<'a> {
1248     Infallible,
1249     JumpToBasicBlock(BasicBlockRef),
1250     DynamicFailureHandlerClass(~DynamicFailureHandler<'a>),
1251 }
1252
1253 impl<'a> FailureHandler<'a> {
1254     fn is_infallible(&self) -> bool {
1255         match *self {
1256             Infallible => true,
1257             _ => false,
1258         }
1259     }
1260
1261     fn is_fallible(&self) -> bool {
1262         !self.is_infallible()
1263     }
1264
1265     fn handle_fail(&self) -> BasicBlockRef {
1266         match *self {
1267             Infallible => {
1268                 fail!("attempted to fail in infallible failure handler!")
1269             }
1270             JumpToBasicBlock(basic_block) => basic_block,
1271             DynamicFailureHandlerClass(ref dynamic_failure_handler) => {
1272                 dynamic_failure_handler.handle_fail()
1273             }
1274         }
1275     }
1276 }
1277
1278 fn pick_col(m: &[Match]) -> uint {
1279     fn score(p: &ast::Pat) -> uint {
1280         match p.node {
1281           ast::PatLit(_) | ast::PatEnum(_, _) | ast::PatRange(_, _) => 1u,
1282           ast::PatIdent(_, _, Some(p)) => score(p),
1283           _ => 0u
1284         }
1285     }
1286     let mut scores = Vec::from_elem(m[0].pats.len(), 0u);
1287     for br in m.iter() {
1288         for (i, p) in br.pats.iter().enumerate() {
1289             *scores.get_mut(i) += score(*p);
1290         }
1291     }
1292     let mut max_score = 0u;
1293     let mut best_col = 0u;
1294     for (i, score) in scores.iter().enumerate() {
1295         let score = *score;
1296
1297         // Irrefutable columns always go first, they'd only be duplicated in
1298         // the branches.
1299         if score == 0u { return i; }
1300         // If no irrefutable ones are found, we pick the one with the biggest
1301         // branching factor.
1302         if score > max_score { max_score = score; best_col = i; }
1303     }
1304     return best_col;
1305 }
1306
1307 #[deriving(Eq)]
1308 pub enum branch_kind { no_branch, single, switch, compare, compare_vec_len, }
1309
1310 // Compiles a comparison between two things.
1311 //
1312 // NB: This must produce an i1, not a Rust bool (i8).
1313 fn compare_values<'a>(
1314                   cx: &'a Block<'a>,
1315                   lhs: ValueRef,
1316                   rhs: ValueRef,
1317                   rhs_t: ty::t)
1318                   -> Result<'a> {
1319     let _icx = push_ctxt("compare_values");
1320     if ty::type_is_scalar(rhs_t) {
1321       let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
1322       return rslt(rs.bcx, rs.val);
1323     }
1324
1325     match ty::get(rhs_t).sty {
1326         ty::ty_str(ty::vstore_uniq) => {
1327             let scratch_lhs = alloca(cx, val_ty(lhs), "__lhs");
1328             Store(cx, lhs, scratch_lhs);
1329             let scratch_rhs = alloca(cx, val_ty(rhs), "__rhs");
1330             Store(cx, rhs, scratch_rhs);
1331             let did = langcall(cx, None,
1332                                format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
1333                                UniqStrEqFnLangItem);
1334             let result = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], None);
1335             Result {
1336                 bcx: result.bcx,
1337                 val: bool_to_i1(result.bcx, result.val)
1338             }
1339         }
1340         ty::ty_str(_) => {
1341             let did = langcall(cx, None,
1342                                format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
1343                                StrEqFnLangItem);
1344             let result = callee::trans_lang_call(cx, did, [lhs, rhs], None);
1345             Result {
1346                 bcx: result.bcx,
1347                 val: bool_to_i1(result.bcx, result.val)
1348             }
1349         }
1350         _ => {
1351             cx.sess().bug("only scalars and strings supported in compare_values");
1352         }
1353     }
1354 }
1355
1356 fn store_non_ref_bindings<'a>(
1357                           bcx: &'a Block<'a>,
1358                           bindings_map: &BindingsMap,
1359                           opt_cleanup_scope: Option<cleanup::ScopeId>)
1360                           -> &'a Block<'a>
1361 {
1362     /*!
1363      * For each copy/move binding, copy the value from the value being
1364      * matched into its final home.  This code executes once one of
1365      * the patterns for a given arm has completely matched.  It adds
1366      * cleanups to the `opt_cleanup_scope`, if one is provided.
1367      */
1368
1369     let fcx = bcx.fcx;
1370     let mut bcx = bcx;
1371     for (_, &binding_info) in bindings_map.iter() {
1372         match binding_info.trmode {
1373             TrByValue(lldest) => {
1374                 let llval = Load(bcx, binding_info.llmatch); // get a T*
1375                 let datum = Datum(llval, binding_info.ty, Lvalue);
1376                 bcx = datum.store_to(bcx, lldest);
1377
1378                 match opt_cleanup_scope {
1379                     None => {}
1380                     Some(s) => {
1381                         fcx.schedule_drop_mem(s, lldest, binding_info.ty);
1382                     }
1383                 }
1384             }
1385             TrByRef => {}
1386         }
1387     }
1388     return bcx;
1389 }
1390
1391 fn insert_lllocals<'a>(bcx: &'a Block<'a>,
1392                        bindings_map: &BindingsMap,
1393                        cleanup_scope: cleanup::ScopeId)
1394                        -> &'a Block<'a> {
1395     /*!
1396      * For each binding in `data.bindings_map`, adds an appropriate entry into
1397      * the `fcx.lllocals` map, scheduling cleanup in `cleanup_scope`.
1398      */
1399
1400     let fcx = bcx.fcx;
1401
1402     for (&ident, &binding_info) in bindings_map.iter() {
1403         let llval = match binding_info.trmode {
1404             // By value bindings: use the stack slot that we
1405             // copied/moved the value into
1406             TrByValue(lldest) => lldest,
1407
1408             // By ref binding: use the ptr into the matched value
1409             TrByRef => binding_info.llmatch
1410         };
1411
1412         let datum = Datum(llval, binding_info.ty, Lvalue);
1413         fcx.schedule_drop_mem(cleanup_scope, llval, binding_info.ty);
1414
1415         debug!("binding {:?} to {}",
1416                binding_info.id,
1417                bcx.val_to_str(llval));
1418         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
1419
1420         if bcx.sess().opts.debuginfo == FullDebugInfo {
1421             debuginfo::create_match_binding_metadata(bcx,
1422                                                      ident,
1423                                                      binding_info.id,
1424                                                      binding_info.span,
1425                                                      datum);
1426         }
1427     }
1428     bcx
1429 }
1430
1431 fn compile_guard<'r,
1432                  'b>(
1433                  bcx: &'b Block<'b>,
1434                  guard_expr: &ast::Expr,
1435                  data: &ArmData,
1436                  m: &[Match<'r,'b>],
1437                  vals: &[ValueRef],
1438                  chk: &FailureHandler)
1439                  -> &'b Block<'b> {
1440     debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
1441            bcx.to_str(),
1442            bcx.expr_to_str(guard_expr),
1443            m.repr(bcx.tcx()),
1444            vec_map_to_str(vals, |v| bcx.val_to_str(*v)));
1445     let _indenter = indenter();
1446
1447     // Lest the guard itself should fail, introduce a temporary cleanup
1448     // scope for any non-ref bindings we create.
1449     let temp_scope = bcx.fcx.push_custom_cleanup_scope();
1450
1451     let mut bcx = bcx;
1452     bcx = store_non_ref_bindings(bcx, data.bindings_map,
1453                                  Some(cleanup::CustomScope(temp_scope)));
1454     bcx = insert_lllocals(bcx, data.bindings_map,
1455                           cleanup::CustomScope(temp_scope));
1456
1457     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
1458     let val = val.to_llbool(bcx);
1459
1460     // Cancel cleanups now that the guard successfully executed.  If
1461     // the guard was false, we will drop the values explicitly
1462     // below. Otherwise, we'll add lvalue cleanups at the end.
1463     bcx.fcx.pop_custom_cleanup_scope(temp_scope);
1464
1465     return with_cond(bcx, Not(bcx, val), |bcx| {
1466         // Guard does not match: free the values we copied,
1467         // and remove all bindings from the lllocals table
1468         let bcx = drop_bindings(bcx, data);
1469         compile_submatch(bcx, m, vals, chk);
1470         bcx
1471     });
1472
1473     fn drop_bindings<'a>(bcx: &'a Block<'a>, data: &ArmData)
1474                      -> &'a Block<'a> {
1475         let mut bcx = bcx;
1476         for (_, &binding_info) in data.bindings_map.iter() {
1477             match binding_info.trmode {
1478                 TrByValue(llval) => {
1479                     bcx = glue::drop_ty(bcx, llval, binding_info.ty);
1480                 }
1481                 TrByRef => {}
1482             }
1483             bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
1484         }
1485         return bcx;
1486     }
1487 }
1488
1489 fn compile_submatch<'r,
1490                     'b>(
1491                     bcx: &'b Block<'b>,
1492                     m: &[Match<'r,'b>],
1493                     vals: &[ValueRef],
1494                     chk: &FailureHandler) {
1495     debug!("compile_submatch(bcx={}, m={}, vals={})",
1496            bcx.to_str(),
1497            m.repr(bcx.tcx()),
1498            vec_map_to_str(vals, |v| bcx.val_to_str(*v)));
1499     let _indenter = indenter();
1500
1501     /*
1502       For an empty match, a fall-through case must exist
1503      */
1504     assert!((m.len() > 0u || chk.is_fallible()));
1505     let _icx = push_ctxt("match::compile_submatch");
1506     let mut bcx = bcx;
1507     if m.len() == 0u {
1508         Br(bcx, chk.handle_fail());
1509         return;
1510     }
1511     if m[0].pats.len() == 0u {
1512         let data = &m[0].data;
1513         for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
1514             let llmatch = data.bindings_map.get(ident).llmatch;
1515             Store(bcx, *value_ptr, llmatch);
1516         }
1517         match data.arm.guard {
1518             Some(guard_expr) => {
1519                 bcx = compile_guard(bcx,
1520                                     guard_expr,
1521                                     &m[0].data,
1522                                     m.slice(1, m.len()),
1523                                     vals,
1524                                     chk);
1525             }
1526             _ => ()
1527         }
1528         Br(bcx, data.bodycx.llbb);
1529         return;
1530     }
1531
1532     let col = pick_col(m);
1533     let val = vals[col];
1534
1535     if has_nested_bindings(m, col) {
1536         let expanded = expand_nested_bindings(bcx, m, col, val);
1537         compile_submatch_continue(bcx,
1538                                   expanded.as_slice(),
1539                                   vals,
1540                                   chk,
1541                                   col,
1542                                   val)
1543     } else {
1544         compile_submatch_continue(bcx, m, vals, chk, col, val)
1545     }
1546 }
1547
1548 fn compile_submatch_continue<'r,
1549                              'b>(
1550                              mut bcx: &'b Block<'b>,
1551                              m: &[Match<'r,'b>],
1552                              vals: &[ValueRef],
1553                              chk: &FailureHandler,
1554                              col: uint,
1555                              val: ValueRef) {
1556     let fcx = bcx.fcx;
1557     let tcx = bcx.tcx();
1558     let dm = tcx.def_map;
1559
1560     let vals_left = vec::append(Vec::from_slice(vals.slice(0u, col)),
1561                                    vals.slice(col + 1u, vals.len()));
1562     let ccx = bcx.fcx.ccx;
1563     let mut pat_id = 0;
1564     for br in m.iter() {
1565         // Find a real id (we're adding placeholder wildcard patterns, but
1566         // each column is guaranteed to have at least one real pattern)
1567         if pat_id == 0 {
1568             pat_id = br.pats.get(col).id;
1569         }
1570     }
1571
1572     // If we are not matching against an `@T`, we should not be
1573     // required to root any values.
1574     assert!(!pats_require_rooting(bcx, m, col));
1575
1576     match collect_record_or_struct_fields(bcx, m, col) {
1577         Some(ref rec_fields) => {
1578             let pat_ty = node_id_type(bcx, pat_id);
1579             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1580             expr::with_field_tys(tcx, pat_ty, Some(pat_id), |discr, field_tys| {
1581                 let rec_vals = rec_fields.map(|field_name| {
1582                         let ix = ty::field_idx_strict(tcx, field_name.name, field_tys);
1583                         adt::trans_field_ptr(bcx, pat_repr, val, discr, ix)
1584                         });
1585                 compile_submatch(
1586                         bcx,
1587                         enter_rec_or_struct(bcx,
1588                                             dm,
1589                                             m,
1590                                             col,
1591                                             rec_fields.as_slice(),
1592                                             val).as_slice(),
1593                         vec::append(rec_vals,
1594                                        vals_left.as_slice()).as_slice(),
1595                         chk);
1596             });
1597             return;
1598         }
1599         None => {}
1600     }
1601
1602     if any_tup_pat(m, col) {
1603         let tup_ty = node_id_type(bcx, pat_id);
1604         let tup_repr = adt::represent_type(bcx.ccx(), tup_ty);
1605         let n_tup_elts = match ty::get(tup_ty).sty {
1606           ty::ty_tup(ref elts) => elts.len(),
1607           _ => ccx.sess().bug("non-tuple type in tuple pattern")
1608         };
1609         let tup_vals = Vec::from_fn(n_tup_elts, |i| {
1610             adt::trans_field_ptr(bcx, tup_repr, val, 0, i)
1611         });
1612         compile_submatch(bcx,
1613                          enter_tup(bcx,
1614                                    dm,
1615                                    m,
1616                                    col,
1617                                    val,
1618                                    n_tup_elts).as_slice(),
1619                          vec::append(tup_vals,
1620                                         vals_left.as_slice()).as_slice(),
1621                          chk);
1622         return;
1623     }
1624
1625     if any_tuple_struct_pat(bcx, m, col) {
1626         let struct_ty = node_id_type(bcx, pat_id);
1627         let struct_element_count;
1628         match ty::get(struct_ty).sty {
1629             ty::ty_struct(struct_id, _) => {
1630                 struct_element_count =
1631                     ty::lookup_struct_fields(tcx, struct_id).len();
1632             }
1633             _ => {
1634                 ccx.sess().bug("non-struct type in tuple struct pattern");
1635             }
1636         }
1637
1638         let struct_repr = adt::represent_type(bcx.ccx(), struct_ty);
1639         let llstructvals = Vec::from_fn(struct_element_count, |i| {
1640             adt::trans_field_ptr(bcx, struct_repr, val, 0, i)
1641         });
1642         compile_submatch(bcx,
1643                          enter_tuple_struct(bcx, dm, m, col, val,
1644                                             struct_element_count).as_slice(),
1645                          vec::append(llstructvals,
1646                                         vals_left.as_slice()).as_slice(),
1647                          chk);
1648         return;
1649     }
1650
1651     if any_uniq_pat(m, col) {
1652         let llbox = Load(bcx, val);
1653         compile_submatch(bcx,
1654                          enter_uniq(bcx, dm, m, col, val).as_slice(),
1655                          vec::append(vec!(llbox),
1656                                         vals_left.as_slice()).as_slice(),
1657                          chk);
1658         return;
1659     }
1660
1661     if any_region_pat(m, col) {
1662         let loaded_val = Load(bcx, val);
1663         compile_submatch(bcx,
1664                          enter_region(bcx, dm, m, col, val).as_slice(),
1665                          vec::append(vec!(loaded_val),
1666                                         vals_left.as_slice()).as_slice(),
1667                          chk);
1668         return;
1669     }
1670
1671     // Decide what kind of branch we need
1672     let opts = get_options(bcx, m, col);
1673     debug!("options={:?}", opts);
1674     let mut kind = no_branch;
1675     let mut test_val = val;
1676     debug!("test_val={}", bcx.val_to_str(test_val));
1677     if opts.len() > 0u {
1678         match *opts.get(0) {
1679             var(_, repr) => {
1680                 let (the_kind, val_opt) = adt::trans_switch(bcx, repr, val);
1681                 kind = the_kind;
1682                 for &tval in val_opt.iter() { test_val = tval; }
1683             }
1684             lit(_) => {
1685                 let pty = node_id_type(bcx, pat_id);
1686                 test_val = load_if_immediate(bcx, val, pty);
1687                 kind = if ty::type_is_integral(pty) { switch }
1688                 else { compare };
1689             }
1690             range(_, _) => {
1691                 test_val = Load(bcx, val);
1692                 kind = compare;
1693             },
1694             vec_len(..) => {
1695                 let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id));
1696                 let (_, len) = tvec::get_base_and_len(bcx, val, vt.vec_ty);
1697                 test_val = len;
1698                 kind = compare_vec_len;
1699             }
1700         }
1701     }
1702     for o in opts.iter() {
1703         match *o {
1704             range(_, _) => { kind = compare; break }
1705             _ => ()
1706         }
1707     }
1708     let else_cx = match kind {
1709         no_branch | single => bcx,
1710         _ => bcx.fcx.new_temp_block("match_else")
1711     };
1712     let sw = if kind == switch {
1713         Switch(bcx, test_val, else_cx.llbb, opts.len())
1714     } else {
1715         C_int(ccx, 0) // Placeholder for when not using a switch
1716     };
1717
1718     let defaults = enter_default(else_cx, dm, m, col, val, chk);
1719     let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1720     let len = opts.len();
1721
1722     // Compile subtrees for each option
1723     for (i, opt) in opts.iter().enumerate() {
1724         // In some cases in vector pattern matching, we need to override
1725         // the failure case so that instead of failing, it proceeds to
1726         // try more matching. branch_chk, then, is the proper failure case
1727         // for the current conditional branch.
1728         let mut branch_chk = None;
1729         let mut opt_cx = else_cx;
1730         if !exhaustive || i+1 < len {
1731             opt_cx = bcx.fcx.new_temp_block("match_case");
1732             match kind {
1733               single => Br(bcx, opt_cx.llbb),
1734               switch => {
1735                   match trans_opt(bcx, opt) {
1736                       single_result(r) => {
1737                         unsafe {
1738                           llvm::LLVMAddCase(sw, r.val, opt_cx.llbb);
1739                           bcx = r.bcx;
1740                         }
1741                       }
1742                       _ => {
1743                           bcx.sess().bug(
1744                               "in compile_submatch, expected \
1745                                trans_opt to return a single_result")
1746                       }
1747                   }
1748               }
1749               compare => {
1750                   let t = node_id_type(bcx, pat_id);
1751                   let Result {bcx: after_cx, val: matches} = {
1752                       match trans_opt(bcx, opt) {
1753                           single_result(Result {bcx, val}) => {
1754                               compare_values(bcx, test_val, val, t)
1755                           }
1756                           lower_bound(Result {bcx, val}) => {
1757                               compare_scalar_types(
1758                                   bcx, test_val, val,
1759                                   t, ast::BiGe)
1760                           }
1761                           range_result(Result {val: vbegin, ..},
1762                                        Result {bcx, val: vend}) => {
1763                               let Result {bcx, val: llge} =
1764                                   compare_scalar_types(
1765                                   bcx, test_val,
1766                                   vbegin, t, ast::BiGe);
1767                               let Result {bcx, val: llle} =
1768                                   compare_scalar_types(
1769                                   bcx, test_val, vend,
1770                                   t, ast::BiLe);
1771                               rslt(bcx, And(bcx, llge, llle))
1772                           }
1773                       }
1774                   };
1775                   bcx = fcx.new_temp_block("compare_next");
1776                   CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1777               }
1778               compare_vec_len => {
1779                   let Result {bcx: after_cx, val: matches} = {
1780                       match trans_opt(bcx, opt) {
1781                           single_result(
1782                               Result {bcx, val}) => {
1783                               let value = compare_scalar_values(
1784                                   bcx, test_val, val,
1785                                   signed_int, ast::BiEq);
1786                               rslt(bcx, value)
1787                           }
1788                           lower_bound(
1789                               Result {bcx, val: val}) => {
1790                               let value = compare_scalar_values(
1791                                   bcx, test_val, val,
1792                                   signed_int, ast::BiGe);
1793                               rslt(bcx, value)
1794                           }
1795                           range_result(
1796                               Result {val: vbegin, ..},
1797                               Result {bcx, val: vend}) => {
1798                               let llge =
1799                                   compare_scalar_values(
1800                                   bcx, test_val,
1801                                   vbegin, signed_int, ast::BiGe);
1802                               let llle =
1803                                   compare_scalar_values(
1804                                   bcx, test_val, vend,
1805                                   signed_int, ast::BiLe);
1806                               rslt(bcx, And(bcx, llge, llle))
1807                           }
1808                       }
1809                   };
1810                   bcx = fcx.new_temp_block("compare_vec_len_next");
1811
1812                   // If none of these subcases match, move on to the
1813                   // next condition.
1814                   branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1815                   CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1816               }
1817               _ => ()
1818             }
1819         } else if kind == compare || kind == compare_vec_len {
1820             Br(bcx, else_cx.llbb);
1821         }
1822
1823         let mut size = 0u;
1824         let mut unpacked = Vec::new();
1825         match *opt {
1826             var(disr_val, repr) => {
1827                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1828                     extract_variant_args(opt_cx, repr, disr_val, val);
1829                 size = argvals.len();
1830                 unpacked = argvals;
1831                 opt_cx = new_bcx;
1832             }
1833             vec_len(n, vt, _) => {
1834                 let (n, slice) = match vt {
1835                     vec_len_ge(i) => (n + 1u, Some(i)),
1836                     vec_len_eq => (n, None)
1837                 };
1838                 let args = extract_vec_elems(opt_cx, pat_id, n,
1839                                              slice, val, test_val);
1840                 size = args.vals.len();
1841                 unpacked = args.vals.clone();
1842                 opt_cx = args.bcx;
1843             }
1844             lit(_) | range(_, _) => ()
1845         }
1846         let opt_ms = enter_opt(opt_cx, m, opt, col, size, val);
1847         let opt_vals = vec::append(unpacked, vals_left.as_slice());
1848
1849         match branch_chk {
1850             None => {
1851                 compile_submatch(opt_cx,
1852                                  opt_ms.as_slice(),
1853                                  opt_vals.as_slice(),
1854                                  chk)
1855             }
1856             Some(branch_chk) => {
1857                 compile_submatch(opt_cx,
1858                                  opt_ms.as_slice(),
1859                                  opt_vals.as_slice(),
1860                                  &branch_chk)
1861             }
1862         }
1863     }
1864
1865     // Compile the fall-through case, if any
1866     if !exhaustive {
1867         if kind == compare || kind == compare_vec_len {
1868             Br(bcx, else_cx.llbb);
1869         }
1870         if kind != single {
1871             compile_submatch(else_cx,
1872                              defaults.as_slice(),
1873                              vals_left.as_slice(),
1874                              chk);
1875         }
1876     }
1877 }
1878
1879 pub fn trans_match<'a>(
1880                    bcx: &'a Block<'a>,
1881                    match_expr: &ast::Expr,
1882                    discr_expr: &ast::Expr,
1883                    arms: &[ast::Arm],
1884                    dest: Dest)
1885                    -> &'a Block<'a> {
1886     let _icx = push_ctxt("match::trans_match");
1887     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1888 }
1889
1890 fn create_bindings_map(bcx: &Block, pat: @ast::Pat) -> BindingsMap {
1891     // Create the bindings map, which is a mapping from each binding name
1892     // to an alloca() that will be the value for that local variable.
1893     // Note that we use the names because each binding will have many ids
1894     // from the various alternatives.
1895     let ccx = bcx.ccx();
1896     let tcx = bcx.tcx();
1897     let mut bindings_map = HashMap::new();
1898     pat_bindings(tcx.def_map, pat, |bm, p_id, span, path| {
1899         let ident = path_to_ident(path);
1900         let variable_ty = node_id_type(bcx, p_id);
1901         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1902
1903         let llmatch;
1904         let trmode;
1905         match bm {
1906             ast::BindByValue(_) => {
1907                 // in this case, the final type of the variable will be T,
1908                 // but during matching we need to store a *T as explained
1909                 // above
1910                 llmatch = alloca(bcx, llvariable_ty.ptr_to(), "__llmatch");
1911                 trmode = TrByValue(alloca(bcx, llvariable_ty,
1912                                           bcx.ident(ident)));
1913             }
1914             ast::BindByRef(_) => {
1915                 llmatch = alloca(bcx, llvariable_ty, bcx.ident(ident));
1916                 trmode = TrByRef;
1917             }
1918         };
1919         bindings_map.insert(ident, BindingInfo {
1920             llmatch: llmatch,
1921             trmode: trmode,
1922             id: p_id,
1923             span: span,
1924             ty: variable_ty
1925         });
1926     });
1927     return bindings_map;
1928 }
1929
1930 fn trans_match_inner<'a>(scope_cx: &'a Block<'a>,
1931                          match_id: ast::NodeId,
1932                          discr_expr: &ast::Expr,
1933                          arms: &[ast::Arm],
1934                          dest: Dest) -> &'a Block<'a> {
1935     let _icx = push_ctxt("match::trans_match_inner");
1936     let fcx = scope_cx.fcx;
1937     let mut bcx = scope_cx;
1938     let tcx = bcx.tcx();
1939
1940     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1941                                                                "match"));
1942     if bcx.unreachable.get() {
1943         return bcx;
1944     }
1945
1946     let mut arm_datas = Vec::new();
1947     let mut matches = Vec::new();
1948     for arm in arms.iter() {
1949         let body = fcx.new_id_block("case_body", arm.body.id);
1950         let bindings_map = create_bindings_map(bcx, *arm.pats.get(0));
1951         let arm_data = ArmData {
1952             bodycx: body,
1953             arm: arm,
1954             bindings_map: @bindings_map
1955         };
1956         arm_datas.push(arm_data.clone());
1957         for p in arm.pats.iter() {
1958             matches.push(Match {
1959                 pats: vec!(*p),
1960                 data: arm_data.clone(),
1961                 bound_ptrs: Vec::new(),
1962             });
1963         }
1964     }
1965
1966     let t = node_id_type(bcx, discr_expr.id);
1967     let chk = {
1968         if ty::type_is_empty(tcx, t) {
1969             // Special case for empty types
1970             let fail_cx = Cell::new(None);
1971             let fail_handler = ~DynamicFailureHandler {
1972                 bcx: scope_cx,
1973                 sp: discr_expr.span,
1974                 msg: InternedString::new("scrutinizing value that can't \
1975                                           exist"),
1976                 finished: fail_cx,
1977             };
1978             DynamicFailureHandlerClass(fail_handler)
1979         } else {
1980             Infallible
1981         }
1982     };
1983     let lldiscr = discr_datum.val;
1984     compile_submatch(bcx, matches.as_slice(), [lldiscr], &chk);
1985
1986     let mut arm_cxs = Vec::new();
1987     for arm_data in arm_datas.iter() {
1988         let mut bcx = arm_data.bodycx;
1989
1990         // If this arm has a guard, then the various by-value bindings have
1991         // already been copied into their homes.  If not, we do it here.  This
1992         // is just to reduce code space.  See extensive comment at the start
1993         // of the file for more details.
1994         if arm_data.arm.guard.is_none() {
1995             bcx = store_non_ref_bindings(bcx, arm_data.bindings_map, None);
1996         }
1997
1998         // insert bindings into the lllocals map and add cleanups
1999         let cleanup_scope = fcx.push_custom_cleanup_scope();
2000         bcx = insert_lllocals(bcx, arm_data.bindings_map,
2001                               cleanup::CustomScope(cleanup_scope));
2002         bcx = expr::trans_into(bcx, arm_data.arm.body, dest);
2003         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope);
2004         arm_cxs.push(bcx);
2005     }
2006
2007     bcx = scope_cx.fcx.join_blocks(match_id, arm_cxs.as_slice());
2008     return bcx;
2009 }
2010
2011 enum IrrefutablePatternBindingMode {
2012     // Stores the association between node ID and LLVM value in `lllocals`.
2013     BindLocal,
2014     // Stores the association between node ID and LLVM value in `llargs`.
2015     BindArgument
2016 }
2017
2018 pub fn store_local<'a>(bcx: &'a Block<'a>,
2019                        local: &ast::Local)
2020                        -> &'a Block<'a> {
2021     /*!
2022      * Generates code for a local variable declaration like
2023      * `let <pat>;` or `let <pat> = <opt_init_expr>`.
2024      */
2025     let _icx = push_ctxt("match::store_local");
2026     let mut bcx = bcx;
2027     let tcx = bcx.tcx();
2028     let pat = local.pat;
2029     let opt_init_expr = local.init;
2030
2031     return match opt_init_expr {
2032         Some(init_expr) => {
2033             // Optimize the "let x = expr" case. This just writes
2034             // the result of evaluating `expr` directly into the alloca
2035             // for `x`. Often the general path results in similar or the
2036             // same code post-optimization, but not always. In particular,
2037             // in unsafe code, you can have expressions like
2038             //
2039             //    let x = intrinsics::uninit();
2040             //
2041             // In such cases, the more general path is unsafe, because
2042             // it assumes it is matching against a valid value.
2043             match simple_identifier(pat) {
2044                 Some(path) => {
2045                     let var_scope = cleanup::var_scope(tcx, local.id);
2046                     return mk_binding_alloca(
2047                         bcx, pat.id, path, BindLocal, var_scope, (),
2048                         |(), bcx, v, _| expr::trans_into(bcx, init_expr,
2049                                                          expr::SaveIn(v)));
2050                 }
2051
2052                 None => {}
2053             }
2054
2055             // General path.
2056             let init_datum =
2057                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, init_expr, "let"));
2058             if ty::type_is_bot(expr_ty(bcx, init_expr)) {
2059                 create_dummy_locals(bcx, pat)
2060             } else {
2061                 if bcx.sess().asm_comments() {
2062                     add_comment(bcx, "creating zeroable ref llval");
2063                 }
2064                 let var_scope = cleanup::var_scope(tcx, local.id);
2065                 bind_irrefutable_pat(bcx, pat, init_datum.val, BindLocal, var_scope)
2066             }
2067         }
2068         None => {
2069             create_dummy_locals(bcx, pat)
2070         }
2071     };
2072
2073     fn create_dummy_locals<'a>(mut bcx: &'a Block<'a>,
2074                                pat: @ast::Pat)
2075                                -> &'a Block<'a> {
2076         // create dummy memory for the variables if we have no
2077         // value to store into them immediately
2078         let tcx = bcx.tcx();
2079         pat_bindings(tcx.def_map, pat, |_, p_id, _, path| {
2080                 let scope = cleanup::var_scope(tcx, p_id);
2081                 bcx = mk_binding_alloca(
2082                     bcx, p_id, path, BindLocal, scope, (),
2083                     |(), bcx, llval, ty| { zero_mem(bcx, llval, ty); bcx });
2084             });
2085         bcx
2086     }
2087 }
2088
2089 pub fn store_arg<'a>(mut bcx: &'a Block<'a>,
2090                      pat: @ast::Pat,
2091                      arg: Datum<Rvalue>,
2092                      arg_scope: cleanup::ScopeId)
2093                      -> &'a Block<'a> {
2094     /*!
2095      * Generates code for argument patterns like `fn foo(<pat>: T)`.
2096      * Creates entries in the `llargs` map for each of the bindings
2097      * in `pat`.
2098      *
2099      * # Arguments
2100      *
2101      * - `pat` is the argument pattern
2102      * - `llval` is a pointer to the argument value (in other words,
2103      *   if the argument type is `T`, then `llval` is a `T*`). In some
2104      *   cases, this code may zero out the memory `llval` points at.
2105      */
2106
2107     let _icx = push_ctxt("match::store_arg");
2108
2109     match simple_identifier(pat) {
2110         Some(path) => {
2111             // Generate nicer LLVM for the common case of fn a pattern
2112             // like `x: T`
2113             let arg_ty = node_id_type(bcx, pat.id);
2114             if type_of::arg_is_indirect(bcx.ccx(), arg_ty)
2115                 && bcx.sess().opts.debuginfo != FullDebugInfo {
2116                 // Don't copy an indirect argument to an alloca, the caller
2117                 // already put it in a temporary alloca and gave it up, unless
2118                 // we emit extra-debug-info, which requires local allocas :(.
2119                 let arg_val = arg.add_clean(bcx.fcx, arg_scope);
2120                 bcx.fcx.llargs.borrow_mut()
2121                    .insert(pat.id, Datum(arg_val, arg_ty, Lvalue));
2122                 bcx
2123             } else {
2124                 mk_binding_alloca(
2125                     bcx, pat.id, path, BindArgument, arg_scope, arg,
2126                     |arg, bcx, llval, _| arg.store_to(bcx, llval))
2127             }
2128         }
2129
2130         None => {
2131             // General path. Copy out the values that are used in the
2132             // pattern.
2133             let arg = unpack_datum!(
2134                 bcx, arg.to_lvalue_datum_in_scope(bcx, "__arg", arg_scope));
2135             bind_irrefutable_pat(bcx, pat, arg.val,
2136                                  BindArgument, arg_scope)
2137         }
2138     }
2139 }
2140
2141 fn mk_binding_alloca<'a,A>(bcx: &'a Block<'a>,
2142                            p_id: ast::NodeId,
2143                            path: &ast::Path,
2144                            binding_mode: IrrefutablePatternBindingMode,
2145                            cleanup_scope: cleanup::ScopeId,
2146                            arg: A,
2147                            populate: |A, &'a Block<'a>, ValueRef, ty::t| -> &'a Block<'a>)
2148                          -> &'a Block<'a> {
2149     let var_ty = node_id_type(bcx, p_id);
2150     let ident = ast_util::path_to_ident(path);
2151
2152     // Allocate memory on stack for the binding.
2153     let llval = alloc_ty(bcx, var_ty, bcx.ident(ident));
2154
2155     // Subtle: be sure that we *populate* the memory *before*
2156     // we schedule the cleanup.
2157     let bcx = populate(arg, bcx, llval, var_ty);
2158     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
2159
2160     // Now that memory is initialized and has cleanup scheduled,
2161     // create the datum and insert into the local variable map.
2162     let datum = Datum(llval, var_ty, Lvalue);
2163     let mut llmap = match binding_mode {
2164         BindLocal => bcx.fcx.lllocals.borrow_mut(),
2165         BindArgument => bcx.fcx.llargs.borrow_mut()
2166     };
2167     llmap.insert(p_id, datum);
2168     bcx
2169 }
2170
2171 fn bind_irrefutable_pat<'a>(
2172                         bcx: &'a Block<'a>,
2173                         pat: @ast::Pat,
2174                         val: ValueRef,
2175                         binding_mode: IrrefutablePatternBindingMode,
2176                         cleanup_scope: cleanup::ScopeId)
2177                         -> &'a Block<'a> {
2178     /*!
2179      * A simple version of the pattern matching code that only handles
2180      * irrefutable patterns. This is used in let/argument patterns,
2181      * not in match statements. Unifying this code with the code above
2182      * sounds nice, but in practice it produces very inefficient code,
2183      * since the match code is so much more general. In most cases,
2184      * LLVM is able to optimize the code, but it causes longer compile
2185      * times and makes the generated code nigh impossible to read.
2186      *
2187      * # Arguments
2188      * - bcx: starting basic block context
2189      * - pat: the irrefutable pattern being matched.
2190      * - val: the value being matched -- must be an lvalue (by ref, with cleanup)
2191      * - binding_mode: is this for an argument or a local variable?
2192      */
2193
2194     debug!("bind_irrefutable_pat(bcx={}, pat={}, binding_mode={:?})",
2195            bcx.to_str(),
2196            pat.repr(bcx.tcx()),
2197            binding_mode);
2198
2199     if bcx.sess().asm_comments() {
2200         add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
2201                               pat.repr(bcx.tcx())));
2202     }
2203
2204     let _indenter = indenter();
2205
2206     let _icx = push_ctxt("match::bind_irrefutable_pat");
2207     let mut bcx = bcx;
2208     let tcx = bcx.tcx();
2209     let ccx = bcx.ccx();
2210     match pat.node {
2211         ast::PatIdent(pat_binding_mode, ref path, inner) => {
2212             if pat_is_binding(tcx.def_map, pat) {
2213                 // Allocate the stack slot where the value of this
2214                 // binding will live and place it into the appropriate
2215                 // map.
2216                 bcx = mk_binding_alloca(
2217                     bcx, pat.id, path, binding_mode, cleanup_scope, (),
2218                     |(), bcx, llval, ty| {
2219                         match pat_binding_mode {
2220                             ast::BindByValue(_) => {
2221                                 // By value binding: move the value that `val`
2222                                 // points at into the binding's stack slot.
2223                                 let d = Datum(val, ty, Lvalue);
2224                                 d.store_to(bcx, llval)
2225                             }
2226
2227                             ast::BindByRef(_) => {
2228                                 // By ref binding: the value of the variable
2229                                 // is the pointer `val` itself.
2230                                 Store(bcx, val, llval);
2231                                 bcx
2232                             }
2233                         }
2234                     });
2235             }
2236
2237             for &inner_pat in inner.iter() {
2238                 bcx = bind_irrefutable_pat(bcx, inner_pat, val,
2239                                            binding_mode, cleanup_scope);
2240             }
2241         }
2242         ast::PatEnum(_, ref sub_pats) => {
2243             let opt_def = bcx.tcx().def_map.borrow().find_copy(&pat.id);
2244             match opt_def {
2245                 Some(ast::DefVariant(enum_id, var_id, _)) => {
2246                     let repr = adt::represent_node(bcx, pat.id);
2247                     let vinfo = ty::enum_variant_with_id(ccx.tcx(),
2248                                                          enum_id,
2249                                                          var_id);
2250                     let args = extract_variant_args(bcx,
2251                                                     repr,
2252                                                     vinfo.disr_val,
2253                                                     val);
2254                     for sub_pat in sub_pats.iter() {
2255                         for (i, argval) in args.vals.iter().enumerate() {
2256                             bcx = bind_irrefutable_pat(bcx, *sub_pat.get(i),
2257                                                        *argval, binding_mode,
2258                                                        cleanup_scope);
2259                         }
2260                     }
2261                 }
2262                 Some(ast::DefFn(..)) |
2263                 Some(ast::DefStruct(..)) => {
2264                     match *sub_pats {
2265                         None => {
2266                             // This is a unit-like struct. Nothing to do here.
2267                         }
2268                         Some(ref elems) => {
2269                             // This is the tuple struct case.
2270                             let repr = adt::represent_node(bcx, pat.id);
2271                             for (i, elem) in elems.iter().enumerate() {
2272                                 let fldptr = adt::trans_field_ptr(bcx, repr,
2273                                                                   val, 0, i);
2274                                 bcx = bind_irrefutable_pat(bcx, *elem,
2275                                                            fldptr, binding_mode,
2276                                                            cleanup_scope);
2277                             }
2278                         }
2279                     }
2280                 }
2281                 Some(ast::DefStatic(_, false)) => {
2282                 }
2283                 _ => {
2284                     // Nothing to do here.
2285                 }
2286             }
2287         }
2288         ast::PatStruct(_, ref fields, _) => {
2289             let tcx = bcx.tcx();
2290             let pat_ty = node_id_type(bcx, pat.id);
2291             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
2292             expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
2293                 for f in fields.iter() {
2294                     let ix = ty::field_idx_strict(tcx, f.ident.name, field_tys);
2295                     let fldptr = adt::trans_field_ptr(bcx, pat_repr, val,
2296                                                       discr, ix);
2297                     bcx = bind_irrefutable_pat(bcx, f.pat, fldptr,
2298                                                binding_mode, cleanup_scope);
2299                 }
2300             })
2301         }
2302         ast::PatTup(ref elems) => {
2303             let repr = adt::represent_node(bcx, pat.id);
2304             for (i, elem) in elems.iter().enumerate() {
2305                 let fldptr = adt::trans_field_ptr(bcx, repr, val, 0, i);
2306                 bcx = bind_irrefutable_pat(bcx, *elem, fldptr,
2307                                            binding_mode, cleanup_scope);
2308             }
2309         }
2310         ast::PatUniq(inner) => {
2311             let llbox = Load(bcx, val);
2312             bcx = bind_irrefutable_pat(bcx, inner, llbox, binding_mode, cleanup_scope);
2313         }
2314         ast::PatRegion(inner) => {
2315             let loaded_val = Load(bcx, val);
2316             bcx = bind_irrefutable_pat(bcx, inner, loaded_val, binding_mode, cleanup_scope);
2317         }
2318         ast::PatVec(..) => {
2319             bcx.sess().span_bug(pat.span,
2320                 format!("vector patterns are never irrefutable!"));
2321         }
2322         ast::PatWild | ast::PatWildMulti | ast::PatLit(_) | ast::PatRange(_, _) => ()
2323     }
2324     return bcx;
2325 }