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