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