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