1 // Copyright 2012 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.
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.
13 * # Compilation of match statements
15 * I will endeavor to explain the code as best I can. I have only a loose
16 * understanding of some parts of it.
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.
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:
33 * enum Foo { A, B(int), C(uint, uint) }
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`.
50 * Here is a quick guide to the various functions:
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.
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.
64 * We store information about the bound variables for each arm as part of the
65 * per-arm `ArmData` struct. There is a mapping from identifiers to
66 * `BindingInfo` structs. These structs contain the mode/id/type of the
67 * binding, but they also contain up to two LLVM values, called `llmatch` and
68 * `llbinding` respectively (the `llbinding`, as will be described shortly, is
69 * optional and only present for by-value bindings---therefore it is bundled
70 * up as part of the `TransBindingMode` type). Both point at allocas.
72 * The `llmatch` binding always stores a pointer into the value being matched
73 * which points at the data for the binding. If the value being matched has
74 * type `T`, then, `llmatch` will point at an alloca of type `T*` (and hence
75 * `llmatch` has type `T**`). So, if you have a pattern like:
79 * match (a, b) { (ref c, d) => { ... } }
81 * For `c` and `d`, we would generate allocas of type `C*` and `D*`
82 * respectively. These are called the `llmatch`. As we match, when we come
83 * up against an identifier, we store the current pointer into the
84 * corresponding alloca.
86 * In addition, for each by-value binding (copy or move), we will create a
87 * second alloca (`llbinding`) that will hold the final value. In this
88 * example, that means that `d` would have this second alloca of type `D` (and
89 * hence `llbinding` has type `D*`).
91 * Once a pattern is completely matched, and assuming that there is no guard
92 * pattern, we will branch to a block that leads to the body itself. For any
93 * by-value bindings, this block will first load the ptr from `llmatch` (the
94 * one of type `D*`) and copy/move the value into `llbinding` (the one of type
95 * `D`). The second alloca then becomes the value of the local variable. For
96 * by ref bindings, the value of the local variable is simply the first
99 * So, for the example above, we would generate a setup kind of like this:
105 * +-------------------------------------------+
106 * | llmatch_c = (addr of first half of tuple) |
107 * | llmatch_d = (addr of first half of tuple) |
108 * +-------------------------------------------+
110 * +--------------------------------------+
111 * | *llbinding_d = **llmatch_dlbinding_d |
112 * +--------------------------------------+
114 * If there is a guard, the situation is slightly different, because we must
115 * execute the guard code. Moreover, we need to do so once for each of the
116 * alternatives that lead to the arm, because if the guard fails, they may
117 * have different points from which to continue the search. Therefore, in that
118 * case, we generate code that looks more like:
124 * +-------------------------------------------+
125 * | llmatch_c = (addr of first half of tuple) |
126 * | llmatch_d = (addr of first half of tuple) |
127 * +-------------------------------------------+
129 * +-------------------------------------------------+
130 * | *llbinding_d = **llmatch_dlbinding_d |
131 * | check condition |
132 * | if false { free *llbinding_d, goto next case } |
133 * | if true { goto body } |
134 * +-------------------------------------------------+
136 * The handling for the cleanups is a bit... sensitive. Basically, the body
137 * is the one that invokes `add_clean()` for each binding. During the guard
138 * evaluation, we add temporary cleanups and revoke them after the guard is
139 * evaluated (it could fail, after all). Presuming the guard fails, we drop
140 * the various values we copied explicitly. Note that guards and moves are
141 * just plain incompatible.
143 * Some relevant helper functions that manage bindings:
144 * - `create_bindings_map()`
145 * - `store_non_ref_bindings()`
146 * - `insert_lllocals()`
149 * ## Notes on vector pattern matching.
151 * Vector pattern matching is surprisingly tricky. The problem is that
152 * the structure of the vector isn't fully known, and slice matches
153 * can be done on subparts of it.
155 * The way that vector pattern matches are dealt with, then, is as
156 * follows. First, we make the actual condition associated with a
157 * vector pattern simply a vector length comparison. So the pattern
158 * [1, .. x] gets the condition "vec len >= 1", and the pattern
159 * [.. x] gets the condition "vec len >= 0". The problem here is that
160 * having the condition "vec len >= 1" hold clearly does not mean that
161 * only a pattern that has exactly that condition will match. This
162 * means that it may well be the case that a condition holds, but none
163 * of the patterns matching that condition match; to deal with this,
164 * when doing vector length matches, we have match failures proceed to
165 * the next condition to check.
167 * There are a couple more subtleties to deal with. While the "actual"
168 * condition associated with vector length tests is simply a test on
169 * the vector length, the actual vec_len Opt entry contains more
170 * information used to restrict which matches are associated with it.
171 * So that all matches in a submatch are matching against the same
172 * values from inside the vector, they are split up by how many
173 * elements they match at the front and at the back of the vector. In
174 * order to make sure that arms are properly checked in order, even
175 * with the overmatching conditions, each vec_len Opt entry is
176 * associated with a range of matches.
177 * Consider the following:
181 * [1, 2, 2, .. _] => 1,
182 * [1, 2, 3, .. _] => 2,
186 * The proper arm to match is arm 2, but arms 0 and 3 both have the
187 * condition "len >= 2". If arm 3 was lumped in with arm 0, then the
188 * wrong branch would be taken. Instead, vec_len Opts are associated
189 * with a contiguous range of matches that have the same "shape".
190 * This is sort of ugly and requires a bunch of special handling of
197 use lib::llvm::{llvm, ValueRef, BasicBlockRef};
198 use middle::const_eval;
199 use middle::borrowck::root_map_key;
200 use middle::lang_items::{UniqStrEqFnLangItem, StrEqFnLangItem};
201 use middle::pat_util::*;
202 use middle::resolve::DefMap;
203 use middle::trans::adt;
204 use middle::trans::base::*;
205 use middle::trans::build::*;
206 use middle::trans::callee;
207 use middle::trans::common::*;
208 use middle::trans::consts;
209 use middle::trans::controlflow;
210 use middle::trans::datum;
211 use middle::trans::datum::*;
212 use middle::trans::expr::Dest;
213 use middle::trans::expr;
214 use middle::trans::glue;
215 use middle::trans::tvec;
216 use middle::trans::type_of;
217 use middle::trans::debuginfo;
219 use util::common::indenter;
220 use util::ppaux::{Repr, vec_map_to_str};
222 use std::hashmap::HashMap;
225 use syntax::ast::Ident;
226 use syntax::ast_util::path_to_ident;
227 use syntax::ast_util;
228 use syntax::codemap::{Span, dummy_sp};
230 // An option identifying a literal: either a unit-like struct or an
233 UnitLikeStructLit(ast::NodeId), // the node ID of the pattern
235 ConstLit(ast::DefId), // the def ID of the constant
241 vec_len_ge(/* length of prefix */uint)
244 // An option identifying a branch (either a literal, a enum variant or a
248 var(ty::Disr, @adt::Repr),
249 range(@ast::Expr, @ast::Expr),
250 vec_len(/* length */ uint, VecLenOpt, /*range of matches*/(uint, uint))
253 fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool {
255 (&lit(a), &lit(b)) => {
257 (UnitLikeStructLit(a), UnitLikeStructLit(b)) => a == b,
261 ExprLit(existing_a_expr) => a_expr = existing_a_expr,
262 ConstLit(a_const) => {
263 let e = const_eval::lookup_const_by_id(tcx, a_const);
266 UnitLikeStructLit(_) => {
267 fail2!("UnitLikeStructLit should have been handled \
274 ExprLit(existing_b_expr) => b_expr = existing_b_expr,
275 ConstLit(b_const) => {
276 let e = const_eval::lookup_const_by_id(tcx, b_const);
279 UnitLikeStructLit(_) => {
280 fail2!("UnitLikeStructLit should have been handled \
285 match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) {
286 Some(val1) => val1 == 0,
287 None => fail2!("compare_list_exprs: type mismatch"),
292 (&range(a1, a2), &range(b1, b2)) => {
293 let m1 = const_eval::compare_lit_exprs(tcx, a1, b1);
294 let m2 = const_eval::compare_lit_exprs(tcx, a2, b2);
296 (Some(val1), Some(val2)) => (val1 == 0 && val2 == 0),
297 _ => fail2!("compare_list_exprs: type mismatch"),
300 (&var(a, _), &var(b, _)) => a == b,
301 (&vec_len(a1, a2, _), &vec_len(b1, b2, _)) =>
302 a1 == b1 && a2 == b2,
307 pub enum opt_result {
308 single_result(Result),
310 range_result(Result, Result),
312 fn trans_opt(bcx: @mut Block, o: &Opt) -> opt_result {
313 let _icx = push_ctxt("match::trans_opt");
317 lit(ExprLit(lit_expr)) => {
318 let datumblock = expr::trans_to_datum(bcx, lit_expr);
319 return single_result(datumblock.to_result());
321 lit(UnitLikeStructLit(pat_id)) => {
322 let struct_ty = ty::node_id_to_type(bcx.tcx(), pat_id);
323 let datumblock = datum::scratch_datum(bcx, struct_ty, "", true);
324 return single_result(datumblock.to_result(bcx));
326 lit(ConstLit(lit_id)) => {
327 let (llval, _) = consts::get_const_val(bcx.ccx(), lit_id);
328 return single_result(rslt(bcx, llval));
330 var(disr_val, repr) => {
331 return adt::trans_case(bcx, repr, disr_val);
334 let (l1, _) = consts::const_expr(ccx, l1);
335 let (l2, _) = consts::const_expr(ccx, l2);
336 return range_result(rslt(bcx, l1), rslt(bcx, l2));
338 vec_len(n, vec_len_eq, _) => {
339 return single_result(rslt(bcx, C_int(ccx, n as int)));
341 vec_len(n, vec_len_ge(_), _) => {
342 return lower_bound(rslt(bcx, C_int(ccx, n as int)));
347 fn variant_opt(bcx: @mut Block, pat_id: ast::NodeId)
350 match ccx.tcx.def_map.get_copy(&pat_id) {
351 ast::DefVariant(enum_id, var_id, _) => {
352 let variants = ty::enum_variants(ccx.tcx, enum_id);
353 for v in (*variants).iter() {
355 return var(v.disr_val,
356 adt::represent_node(bcx, pat_id))
362 ast::DefStruct(_) => {
363 return lit(UnitLikeStructLit(pat_id));
366 ccx.sess.bug("non-variant or struct in variant_opt()");
372 enum TransBindingMode {
373 TrByValue(/*llbinding:*/ ValueRef),
378 * Information about a pattern binding:
379 * - `llmatch` is a pointer to a stack slot. The stack slot contains a
380 * pointer into the value being matched. Hence, llmatch has type `T**`
381 * where `T` is the value being matched.
382 * - `trmode` is the trans binding mode
383 * - `id` is the node id of the binding
384 * - `ty` is the Rust type of the binding */
388 trmode: TransBindingMode,
394 type BindingsMap = HashMap<Ident, BindingInfo>;
397 struct ArmData<'self> {
399 arm: &'self ast::Arm,
400 bindings_map: @BindingsMap
405 * If all `pats` are matched then arm `data` will be executed.
406 * As we proceed `bound_ptrs` are filled with pointers to values to be bound,
407 * these pointers are stored in llmatch variables just before executing `data` arm.
410 struct Match<'self> {
412 data: ArmData<'self>,
413 bound_ptrs: ~[(Ident, ValueRef)]
416 impl<'self> Repr for Match<'self> {
417 fn repr(&self, tcx: ty::ctxt) -> ~str {
418 if tcx.sess.verbose() {
419 // for many programs, this just take too long to serialize
422 format!("{} pats", self.pats.len())
427 fn has_nested_bindings(m: &[Match], col: uint) -> bool {
429 match br.pats[col].node {
430 ast::PatIdent(_, _, Some(_)) => return true,
437 fn expand_nested_bindings<'r>(bcx: @mut Block,
442 debug2!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
446 bcx.val_to_str(val));
447 let _indenter = indenter();
450 match br.pats[col].node {
451 ast::PatIdent(_, ref path, Some(inner)) => {
452 let pats = vec::append(
453 br.pats.slice(0u, col).to_owned(),
454 vec::append(~[inner],
455 br.pats.slice(col + 1u,
458 let mut res = Match {
460 data: br.data.clone(),
461 bound_ptrs: br.bound_ptrs.clone()
463 res.bound_ptrs.push((path_to_ident(path), val));
471 fn assert_is_binding_or_wild(bcx: @mut Block, p: @ast::Pat) {
472 if !pat_is_binding_or_wild(bcx.tcx().def_map, p) {
475 format!("Expected an identifier pattern but found p: {}",
480 type enter_pat<'self> = &'self fn(@ast::Pat) -> Option<~[@ast::Pat]>;
482 fn enter_match<'r>(bcx: @mut Block,
489 debug2!("enter_match(bcx={}, m={}, col={}, val={})",
493 bcx.val_to_str(val));
494 let _indenter = indenter();
496 let mut result = ~[];
498 match e(br.pats[col]) {
502 vec::append(sub, br.pats.slice(0u, col)),
503 br.pats.slice(col + 1u, br.pats.len()));
505 let this = br.pats[col];
506 let mut bound_ptrs = br.bound_ptrs.clone();
508 ast::PatIdent(_, ref path, None) => {
509 if pat_is_binding(dm, this) {
510 bound_ptrs.push((path_to_ident(path), val));
518 data: br.data.clone(),
519 bound_ptrs: bound_ptrs
526 debug2!("result={}", result.repr(bcx.tcx()));
531 fn enter_default<'r>(bcx: @mut Block,
538 debug2!("enter_default(bcx={}, m={}, col={}, val={})",
542 bcx.val_to_str(val));
543 let _indenter = indenter();
545 // Collect all of the matches that can match against anything.
546 let matches = do enter_match(bcx, dm, m, col, val) |p| {
548 ast::PatWild | ast::PatTup(_) => Some(~[]),
549 ast::PatIdent(_, _, None) if pat_is_binding(dm, p) => Some(~[]),
554 // Ok, now, this is pretty subtle. A "default" match is a match
555 // that needs to be considered if none of the actual checks on the
556 // value being considered succeed. The subtlety lies in that sometimes
557 // identifier/wildcard matches are *not* default matches. Consider:
558 // "match x { _ if something => foo, true => bar, false => baz }".
559 // There is a wildcard match, but it is *not* a default case. The boolean
560 // case on the value being considered is exhaustive. If the case is
561 // exhaustive, then there are no defaults.
563 // We detect whether the case is exhaustive in the following
564 // somewhat kludgy way: if the last wildcard/binding match has a
565 // guard, then by non-redundancy, we know that there aren't any
566 // non guarded matches, and thus by exhaustiveness, we know that
567 // we don't need any default cases. If the check *isn't* nonexhaustive
568 // (because chk is Some), then we need the defaults anyways.
569 let is_exhaustive = match matches.last_opt() {
570 Some(m) if m.data.arm.guard.is_some() && chk.is_infallible() => true,
574 if is_exhaustive { ~[] } else { matches }
577 // <pcwalton> nmatsakis: what does enter_opt do?
578 // <pcwalton> in trans/match
579 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
580 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
581 // patterns as needed
582 // <nmatsakis> yeah, at some point I kind of achieved some level of
584 // <nmatsakis> anyhow, they adjust the patterns given that something of that
585 // kind has been found
586 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
588 // <nmatsakis> enter_match() kind of embodies the generic code
589 // <nmatsakis> it is provided with a function that tests each pattern to see
590 // if it might possibly apply and so forth
591 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
592 // <nmatsakis> then _ would be expanded to (_, _)
593 // <nmatsakis> one spot for each of the sub-patterns
594 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
596 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
597 // are infallible patterns
598 // <nmatsakis> so all patterns must either be records (resp. tuples) or
601 fn enter_opt<'r>(bcx: @mut Block,
608 debug2!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})",
613 bcx.val_to_str(val));
614 let _indenter = indenter();
617 let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
619 do enter_match(bcx, tcx.def_map, m, col, val) |p| {
620 let answer = match p.node {
622 ast::PatIdent(_, _, None) if pat_is_const(tcx.def_map, p) => {
623 let const_def = tcx.def_map.get_copy(&p.id);
624 let const_def_id = ast_util::def_id_of_def(const_def);
625 if opt_eq(tcx, &lit(ConstLit(const_def_id)), opt) {
631 ast::PatEnum(_, ref subpats) => {
632 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
633 // XXX: Must we clone?
635 None => Some(vec::from_elem(variant_size, dummy)),
636 _ => (*subpats).clone(),
642 ast::PatIdent(_, _, None)
643 if pat_is_variant_or_struct(tcx.def_map, p) => {
644 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
651 if opt_eq(tcx, &lit(ExprLit(l)), opt) {Some(~[])} else {None}
653 ast::PatRange(l1, l2) => {
654 if opt_eq(tcx, &range(l1, l2), opt) {Some(~[])} else {None}
656 ast::PatStruct(_, ref field_pats, _) => {
657 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
658 // Look up the struct variant ID.
660 match tcx.def_map.get_copy(&p.id) {
661 ast::DefVariant(_, found_struct_id, _) => {
662 struct_id = found_struct_id;
665 tcx.sess.span_bug(p.span, "expected enum variant def");
669 // Reorder the patterns into the same order they were
670 // specified in the struct definition. Also fill in
671 // unspecified fields with dummy.
672 let mut reordered_patterns = ~[];
673 let r = ty::lookup_struct_fields(tcx, struct_id);
674 for field in r.iter() {
675 match field_pats.iter().find(|p| p.ident.name
677 None => reordered_patterns.push(dummy),
678 Some(fp) => reordered_patterns.push(fp.pat)
681 Some(reordered_patterns)
686 ast::PatVec(ref before, slice, ref after) => {
687 let (lo, hi) = match *opt {
688 vec_len(_, _, (lo, hi)) => (lo, hi),
689 _ => tcx.sess.span_bug(p.span,
690 "vec pattern but not vec opt")
694 Some(slice) if i >= lo && i <= hi => {
695 let n = before.len() + after.len();
696 let this_opt = vec_len(n, vec_len_ge(before.len()),
698 if opt_eq(tcx, &this_opt, opt) {
699 Some(vec::append_one((*before).clone(), slice) +
705 None if i >= lo && i <= hi => {
706 let n = before.len();
707 if opt_eq(tcx, &vec_len(n, vec_len_eq, (lo,hi)), opt) {
708 Some((*before).clone())
717 assert_is_binding_or_wild(bcx, p);
718 // In most cases, a binding/wildcard match be
719 // considered to match against any Opt. However, when
720 // doing vector pattern matching, submatches are
721 // considered even if the eventual match might be from
722 // a different submatch. Thus, when a submatch fails
723 // when doing a vector match, we proceed to the next
724 // submatch. Thus, including a default match would
725 // cause the default match to fire spuriously.
728 _ => Some(vec::from_elem(variant_size, dummy))
737 fn enter_rec_or_struct<'r>(bcx: @mut Block,
741 fields: &[ast::Ident],
744 debug2!("enter_rec_or_struct(bcx={}, m={}, col={}, val={})",
748 bcx.val_to_str(val));
749 let _indenter = indenter();
751 let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
752 do enter_match(bcx, dm, m, col, val) |p| {
754 ast::PatStruct(_, ref fpats, _) => {
756 for fname in fields.iter() {
757 match fpats.iter().find(|p| p.ident.name == fname.name) {
758 None => pats.push(dummy),
759 Some(pat) => pats.push(pat.pat)
765 assert_is_binding_or_wild(bcx, p);
766 Some(vec::from_elem(fields.len(), dummy))
772 fn enter_tup<'r>(bcx: @mut Block,
779 debug2!("enter_tup(bcx={}, m={}, col={}, val={})",
783 bcx.val_to_str(val));
784 let _indenter = indenter();
786 let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
787 do enter_match(bcx, dm, m, col, val) |p| {
789 ast::PatTup(ref elts) => Some((*elts).clone()),
791 assert_is_binding_or_wild(bcx, p);
792 Some(vec::from_elem(n_elts, dummy))
798 fn enter_tuple_struct<'r>(bcx: @mut Block,
805 debug2!("enter_tuple_struct(bcx={}, m={}, col={}, val={})",
809 bcx.val_to_str(val));
810 let _indenter = indenter();
812 let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
813 do enter_match(bcx, dm, m, col, val) |p| {
815 ast::PatEnum(_, Some(ref elts)) => Some((*elts).clone()),
817 assert_is_binding_or_wild(bcx, p);
818 Some(vec::from_elem(n_elts, dummy))
824 fn enter_box<'r>(bcx: @mut Block,
830 debug2!("enter_box(bcx={}, m={}, col={}, val={})",
834 bcx.val_to_str(val));
835 let _indenter = indenter();
837 let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
838 do enter_match(bcx, dm, m, col, val) |p| {
840 ast::PatBox(sub) => {
844 assert_is_binding_or_wild(bcx, p);
851 fn enter_uniq<'r>(bcx: @mut Block,
857 debug2!("enter_uniq(bcx={}, m={}, col={}, val={})",
861 bcx.val_to_str(val));
862 let _indenter = indenter();
864 let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
865 do enter_match(bcx, dm, m, col, val) |p| {
867 ast::PatUniq(sub) => {
871 assert_is_binding_or_wild(bcx, p);
878 fn enter_region<'r>(bcx: @mut Block,
884 debug2!("enter_region(bcx={}, m={}, col={}, val={})",
888 bcx.val_to_str(val));
889 let _indenter = indenter();
891 let dummy = @ast::Pat { id: 0, node: ast::PatWild, span: dummy_sp() };
892 do enter_match(bcx, dm, m, col, val) |p| {
894 ast::PatRegion(sub) => {
898 assert_is_binding_or_wild(bcx, p);
905 // Returns the options in one column of matches. An option is something that
906 // needs to be conditionally matched at runtime; for example, the discriminant
907 // on a set of enum variants or a literal.
908 fn get_options(bcx: @mut Block, m: &[Match], col: uint) -> ~[Opt] {
910 fn add_to_set(tcx: ty::ctxt, set: &mut ~[Opt], val: Opt) {
911 if set.iter().any(|l| opt_eq(tcx, l, &val)) {return;}
914 // Vector comparisions are special in that since the actual
915 // conditions over-match, we need to be careful about them. This
916 // means that in order to properly handle things in order, we need
917 // to not always merge conditions.
918 fn add_veclen_to_set(set: &mut ~[Opt], i: uint,
919 len: uint, vlo: VecLenOpt) {
920 match set.last_opt() {
921 // If the last condition in the list matches the one we want
922 // to add, then extend its range. Otherwise, make a new
923 // vec_len with a range just covering the new entry.
924 Some(&vec_len(len2, vlo2, (start, end)))
925 if len == len2 && vlo == vlo2 =>
926 set[set.len() - 1] = vec_len(len, vlo, (start, end+1)),
927 _ => set.push(vec_len(len, vlo, (i, i)))
932 for (i, br) in m.iter().enumerate() {
933 let cur = br.pats[col];
936 add_to_set(ccx.tcx, &mut found, lit(ExprLit(l)));
938 ast::PatIdent(*) => {
939 // This is one of: an enum variant, a unit-like struct, or a
941 match ccx.tcx.def_map.find(&cur.id) {
942 Some(&ast::DefVariant(*)) => {
943 add_to_set(ccx.tcx, &mut found,
944 variant_opt(bcx, cur.id));
946 Some(&ast::DefStruct(*)) => {
947 add_to_set(ccx.tcx, &mut found,
948 lit(UnitLikeStructLit(cur.id)));
950 Some(&ast::DefStatic(const_did, false)) => {
951 add_to_set(ccx.tcx, &mut found,
952 lit(ConstLit(const_did)));
957 ast::PatEnum(*) | ast::PatStruct(*) => {
958 // This could be one of: a tuple-like enum variant, a
959 // struct-like enum variant, or a struct.
960 match ccx.tcx.def_map.find(&cur.id) {
961 Some(&ast::DefFn(*)) |
962 Some(&ast::DefVariant(*)) => {
963 add_to_set(ccx.tcx, &mut found,
964 variant_opt(bcx, cur.id));
966 Some(&ast::DefStatic(const_did, false)) => {
967 add_to_set(ccx.tcx, &mut found,
968 lit(ConstLit(const_did)));
973 ast::PatRange(l1, l2) => {
974 add_to_set(ccx.tcx, &mut found, range(l1, l2));
976 ast::PatVec(ref before, slice, ref after) => {
977 let (len, vec_opt) = match slice {
978 None => (before.len(), vec_len_eq),
979 Some(_) => (before.len() + after.len(),
980 vec_len_ge(before.len()))
982 add_veclen_to_set(&mut found, i, len, vec_opt);
990 struct ExtractedBlock {
995 fn extract_variant_args(bcx: @mut Block,
1000 let _icx = push_ctxt("match::extract_variant_args");
1001 let args = do vec::from_fn(adt::num_args(repr, disr_val)) |i| {
1002 adt::trans_field_ptr(bcx, repr, val, disr_val, i)
1005 ExtractedBlock { vals: args, bcx: bcx }
1008 fn match_datum(bcx: @mut Block, val: ValueRef, pat_id: ast::NodeId) -> Datum {
1009 //! Helper for converting from the ValueRef that we pass around in
1010 //! the match code, which is always by ref, into a Datum. Eventually
1011 //! we should just pass around a Datum and be done with it.
1013 let ty = node_id_type(bcx, pat_id);
1014 Datum {val: val, ty: ty, mode: datum::ByRef(RevokeClean)}
1018 fn extract_vec_elems(bcx: @mut Block,
1020 pat_id: ast::NodeId,
1022 slice: Option<uint>,
1026 let _icx = push_ctxt("match::extract_vec_elems");
1027 let vec_datum = match_datum(bcx, val, pat_id);
1028 let (bcx, base, len) = vec_datum.get_vec_base_and_len(bcx, pat_span, pat_id, 0);
1029 let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id));
1031 let mut elems = do vec::from_fn(elem_count) |i| {
1033 None => GEPi(bcx, base, [i]),
1034 Some(n) if i < n => GEPi(bcx, base, [i]),
1035 Some(n) if i > n => {
1036 InBoundsGEP(bcx, base, [
1038 C_int(bcx.ccx(), (elem_count - i) as int))])
1040 _ => unsafe { llvm::LLVMGetUndef(vt.llunit_ty.to_ref()) }
1043 if slice.is_some() {
1044 let n = slice.unwrap();
1045 let slice_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), n));
1046 let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset);
1047 let slice_len_offset = C_uint(bcx.ccx(), elem_count - 1u);
1048 let slice_len = Sub(bcx, len, slice_len_offset);
1049 let slice_ty = ty::mk_evec(bcx.tcx(),
1050 ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable},
1051 ty::vstore_slice(ty::re_static)
1053 let scratch = scratch_datum(bcx, slice_ty, "", false);
1054 Store(bcx, slice_begin,
1055 GEPi(bcx, scratch.val, [0u, abi::slice_elt_base])
1057 Store(bcx, slice_len, GEPi(bcx, scratch.val, [0u, abi::slice_elt_len]));
1058 elems[n] = scratch.val;
1059 scratch.add_clean(bcx);
1062 ExtractedBlock { vals: elems, bcx: bcx }
1065 /// Checks every pattern in `m` at `col` column.
1066 /// If there are a struct pattern among them function
1067 /// returns list of all fields that are matched in these patterns.
1068 /// Function returns None if there is no struct pattern.
1069 /// Function doesn't collect fields from struct-like enum variants.
1070 /// Function can return empty list if there is only wildcard struct pattern.
1071 fn collect_record_or_struct_fields(bcx: @mut Block,
1074 -> Option<~[ast::Ident]> {
1075 let mut fields: ~[ast::Ident] = ~[];
1076 let mut found = false;
1077 for br in m.iter() {
1078 match br.pats[col].node {
1079 ast::PatStruct(_, ref fs, _) => {
1080 match ty::get(node_id_type(bcx, br.pats[col].id)).sty {
1081 ty::ty_struct(*) => {
1082 extend(&mut fields, *fs);
1092 return Some(fields);
1097 fn extend(idents: &mut ~[ast::Ident], field_pats: &[ast::FieldPat]) {
1098 for field_pat in field_pats.iter() {
1099 let field_ident = field_pat.ident;
1100 if !idents.iter().any(|x| x.name == field_ident.name) {
1101 idents.push(field_ident);
1107 fn pats_require_rooting(bcx: @mut Block,
1111 do m.iter().any |br| {
1112 let pat_id = br.pats[col].id;
1113 let key = root_map_key {id: pat_id, derefs: 0u };
1114 bcx.ccx().maps.root_map.contains_key(&key)
1118 fn root_pats_as_necessary(mut bcx: @mut Block,
1123 for br in m.iter() {
1124 let pat_id = br.pats[col].id;
1126 let datum = Datum {val: val, ty: node_id_type(bcx, pat_id),
1127 mode: ByRef(ZeroMem)};
1128 bcx = datum.root_and_write_guard(bcx, br.pats[col].span, pat_id, 0);
1134 // Macro for deciding whether any of the remaining matches fit a given kind of
1135 // pattern. Note that, because the macro is well-typed, either ALL of the
1136 // matches should fit that sort of pattern or NONE (however, some of the
1137 // matches may be wildcards like _ or identifiers).
1138 macro_rules! any_pat (
1139 ($m:expr, $pattern:pat) => (
1140 do ($m).iter().any |br| {
1141 match br.pats[col].node {
1149 fn any_box_pat(m: &[Match], col: uint) -> bool {
1150 any_pat!(m, ast::PatBox(_))
1153 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
1154 any_pat!(m, ast::PatUniq(_))
1157 fn any_region_pat(m: &[Match], col: uint) -> bool {
1158 any_pat!(m, ast::PatRegion(_))
1161 fn any_tup_pat(m: &[Match], col: uint) -> bool {
1162 any_pat!(m, ast::PatTup(_))
1165 fn any_tuple_struct_pat(bcx: @mut Block, m: &[Match], col: uint) -> bool {
1166 do m.iter().any |br| {
1167 let pat = br.pats[col];
1169 ast::PatEnum(_, Some(_)) => {
1170 match bcx.tcx().def_map.find(&pat.id) {
1171 Some(&ast::DefFn(*)) |
1172 Some(&ast::DefStruct(*)) => true,
1181 trait CustomFailureHandler {
1182 fn handle_fail(&self) -> BasicBlockRef;
1185 struct DynamicFailureHandler {
1189 finished: @mut Option<BasicBlockRef>,
1192 impl CustomFailureHandler for DynamicFailureHandler {
1193 fn handle_fail(&self) -> BasicBlockRef {
1194 match *self.finished {
1195 Some(bb) => return bb,
1199 let fail_cx = sub_block(self.bcx, "case_fallthrough");
1200 controlflow::trans_fail(fail_cx, Some(self.sp), self.msg);
1201 *self.finished = Some(fail_cx.llbb);
1206 /// What to do when the pattern match fails.
1207 enum FailureHandler {
1209 JumpToBasicBlock(BasicBlockRef),
1210 CustomFailureHandlerClass(@CustomFailureHandler),
1213 impl FailureHandler {
1214 fn is_infallible(&self) -> bool {
1221 fn is_fallible(&self) -> bool {
1222 !self.is_infallible()
1225 fn handle_fail(&self) -> BasicBlockRef {
1228 fail2!("attempted to fail in infallible failure handler!")
1230 JumpToBasicBlock(basic_block) => basic_block,
1231 CustomFailureHandlerClass(custom_failure_handler) => {
1232 custom_failure_handler.handle_fail()
1238 fn pick_col(m: &[Match]) -> uint {
1239 fn score(p: &ast::Pat) -> uint {
1241 ast::PatLit(_) | ast::PatEnum(_, _) | ast::PatRange(_, _) => 1u,
1242 ast::PatIdent(_, _, Some(p)) => score(p),
1246 let mut scores = vec::from_elem(m[0].pats.len(), 0u);
1247 for br in m.iter() {
1248 for (i, p) in br.pats.iter().enumerate() {
1249 scores[i] += score(*p);
1252 let mut max_score = 0u;
1253 let mut best_col = 0u;
1254 for (i, score) in scores.iter().enumerate() {
1257 // Irrefutable columns always go first, they'd only be duplicated in
1259 if score == 0u { return i; }
1260 // If no irrefutable ones are found, we pick the one with the biggest
1261 // branching factor.
1262 if score > max_score { max_score = score; best_col = i; }
1268 pub enum branch_kind { no_branch, single, switch, compare, compare_vec_len, }
1270 // Compiles a comparison between two things.
1272 // NB: This must produce an i1, not a Rust bool (i8).
1273 fn compare_values(cx: @mut Block,
1278 let _icx = push_ctxt("compare_values");
1279 if ty::type_is_scalar(rhs_t) {
1280 let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
1281 return rslt(rs.bcx, rs.val);
1284 match ty::get(rhs_t).sty {
1285 ty::ty_estr(ty::vstore_uniq) => {
1286 let scratch_lhs = alloca(cx, val_ty(lhs), "__lhs");
1287 Store(cx, lhs, scratch_lhs);
1288 let scratch_rhs = alloca(cx, val_ty(rhs), "__rhs");
1289 Store(cx, rhs, scratch_rhs);
1290 let did = langcall(cx, None,
1291 format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
1292 UniqStrEqFnLangItem);
1293 let result = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], None);
1296 val: bool_to_i1(result.bcx, result.val)
1300 let did = langcall(cx, None,
1301 format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
1303 let result = callee::trans_lang_call(cx, did, [lhs, rhs], None);
1306 val: bool_to_i1(result.bcx, result.val)
1310 cx.tcx().sess.bug("only scalars and strings supported in \
1316 fn store_non_ref_bindings(bcx: @mut Block,
1317 bindings_map: &BindingsMap,
1318 mut opt_temp_cleanups: Option<&mut ~[ValueRef]>)
1323 * For each copy/move binding, copy the value from the value
1324 * being matched into its final home. This code executes once
1325 * one of the patterns for a given arm has completely matched.
1326 * It adds temporary cleanups to the `temp_cleanups` array,
1327 * if one is provided.
1331 for (_, &binding_info) in bindings_map.iter() {
1332 match binding_info.trmode {
1333 TrByValue(lldest) => {
1334 let llval = Load(bcx, binding_info.llmatch); // get a T*
1335 let datum = Datum {val: llval, ty: binding_info.ty,
1336 mode: ByRef(ZeroMem)};
1337 bcx = datum.store_to(bcx, INIT, lldest);
1338 do opt_temp_cleanups.mutate |temp_cleanups| {
1339 add_clean_temp_mem(bcx, lldest, binding_info.ty);
1340 temp_cleanups.push(lldest);
1350 fn insert_lllocals(bcx: @mut Block,
1351 bindings_map: &BindingsMap,
1352 add_cleans: bool) -> @mut Block {
1354 * For each binding in `data.bindings_map`, adds an appropriate entry into
1355 * the `fcx.lllocals` map. If add_cleans is true, then adds cleanups for
1359 let llmap = bcx.fcx.lllocals;
1361 for (&ident, &binding_info) in bindings_map.iter() {
1362 let llval = match binding_info.trmode {
1363 // By value bindings: use the stack slot that we
1364 // copied/moved the value into
1365 TrByValue(lldest) => {
1367 add_clean(bcx, lldest, binding_info.ty);
1373 // By ref binding: use the ptr into the matched value
1375 binding_info.llmatch
1379 debug2!("binding {:?} to {}", binding_info.id, bcx.val_to_str(llval));
1380 llmap.insert(binding_info.id, llval);
1382 if bcx.sess().opts.extra_debuginfo {
1383 debuginfo::create_match_binding_metadata(bcx,
1393 fn compile_guard(bcx: @mut Block,
1394 guard_expr: &ast::Expr,
1398 chk: FailureHandler)
1400 debug2!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
1402 bcx.expr_to_str(guard_expr),
1404 vec_map_to_str(vals, |v| bcx.val_to_str(*v)));
1405 let _indenter = indenter();
1408 let mut temp_cleanups = ~[];
1409 bcx = store_non_ref_bindings(bcx,
1411 Some(&mut temp_cleanups));
1412 bcx = insert_lllocals(bcx, data.bindings_map, false);
1414 let val = unpack_result!(bcx, {
1415 do with_scope_result(bcx, guard_expr.info(),
1417 expr::trans_to_datum(bcx, guard_expr).to_result()
1420 let val = bool_to_i1(bcx, val);
1422 // Revoke the temp cleanups now that the guard successfully executed.
1423 for llval in temp_cleanups.iter() {
1424 revoke_clean(bcx, *llval);
1427 return do with_cond(bcx, Not(bcx, val)) |bcx| {
1428 // Guard does not match: free the values we copied,
1429 // and remove all bindings from the lllocals table
1430 let bcx = drop_bindings(bcx, data);
1431 compile_submatch(bcx, m, vals, chk);
1435 fn drop_bindings(bcx: @mut Block, data: &ArmData) -> @mut Block {
1437 for (_, &binding_info) in data.bindings_map.iter() {
1438 match binding_info.trmode {
1439 TrByValue(llval) => {
1440 bcx = glue::drop_ty(bcx, llval, binding_info.ty);
1444 bcx.fcx.lllocals.remove(&binding_info.id);
1450 fn compile_submatch(bcx: @mut Block,
1453 chk: FailureHandler) {
1454 debug2!("compile_submatch(bcx={}, m={}, vals={})",
1457 vec_map_to_str(vals, |v| bcx.val_to_str(*v)));
1458 let _indenter = indenter();
1461 For an empty match, a fall-through case must exist
1463 assert!((m.len() > 0u || chk.is_fallible()));
1464 let _icx = push_ctxt("match::compile_submatch");
1467 Br(bcx, chk.handle_fail());
1470 if m[0].pats.len() == 0u {
1471 let data = &m[0].data;
1472 for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
1473 let llmatch = data.bindings_map.get(ident).llmatch;
1474 Store(bcx, *value_ptr, llmatch);
1476 match data.arm.guard {
1477 Some(guard_expr) => {
1478 bcx = compile_guard(bcx,
1481 m.slice(1, m.len()),
1487 Br(bcx, data.bodycx.llbb);
1491 let col = pick_col(m);
1492 let val = vals[col];
1494 if has_nested_bindings(m, col) {
1495 let expanded = expand_nested_bindings(bcx, m, col, val);
1496 compile_submatch_continue(bcx, expanded, vals, chk, col, val)
1498 compile_submatch_continue(bcx, m, vals, chk, col, val)
1502 fn compile_submatch_continue(mut bcx: @mut Block,
1505 chk: FailureHandler,
1508 let tcx = bcx.tcx();
1509 let dm = tcx.def_map;
1511 let vals_left = vec::append(vals.slice(0u, col).to_owned(),
1512 vals.slice(col + 1u, vals.len()));
1513 let ccx = bcx.fcx.ccx;
1515 let mut pat_span = dummy_sp();
1516 for br in m.iter() {
1517 // Find a real id (we're adding placeholder wildcard patterns, but
1518 // each column is guaranteed to have at least one real pattern)
1520 pat_id = br.pats[col].id;
1521 pat_span = br.pats[col].span;
1525 // If we are not matching against an `@T`, we should not be
1526 // required to root any values.
1527 assert!(any_box_pat(m, col) || !pats_require_rooting(bcx, m, col));
1529 match collect_record_or_struct_fields(bcx, m, col) {
1530 Some(ref rec_fields) => {
1531 let pat_ty = node_id_type(bcx, pat_id);
1532 let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1533 do expr::with_field_tys(tcx, pat_ty, None) |discr, field_tys| {
1534 let rec_vals = rec_fields.map(|field_name| {
1535 let ix = ty::field_idx_strict(tcx, field_name.name, field_tys);
1536 adt::trans_field_ptr(bcx, pat_repr, val, discr, ix)
1540 enter_rec_or_struct(bcx, dm, m, col, *rec_fields, val),
1541 vec::append(rec_vals, vals_left),
1549 if any_tup_pat(m, col) {
1550 let tup_ty = node_id_type(bcx, pat_id);
1551 let tup_repr = adt::represent_type(bcx.ccx(), tup_ty);
1552 let n_tup_elts = match ty::get(tup_ty).sty {
1553 ty::ty_tup(ref elts) => elts.len(),
1554 _ => ccx.sess.bug("non-tuple type in tuple pattern")
1556 let tup_vals = do vec::from_fn(n_tup_elts) |i| {
1557 adt::trans_field_ptr(bcx, tup_repr, val, 0, i)
1559 compile_submatch(bcx, enter_tup(bcx, dm, m, col, val, n_tup_elts),
1560 vec::append(tup_vals, vals_left), chk);
1564 if any_tuple_struct_pat(bcx, m, col) {
1565 let struct_ty = node_id_type(bcx, pat_id);
1566 let struct_element_count;
1567 match ty::get(struct_ty).sty {
1568 ty::ty_struct(struct_id, _) => {
1569 struct_element_count =
1570 ty::lookup_struct_fields(tcx, struct_id).len();
1573 ccx.sess.bug("non-struct type in tuple struct pattern");
1577 let struct_repr = adt::represent_type(bcx.ccx(), struct_ty);
1578 let llstructvals = do vec::from_fn(struct_element_count) |i| {
1579 adt::trans_field_ptr(bcx, struct_repr, val, 0, i)
1581 compile_submatch(bcx,
1582 enter_tuple_struct(bcx, dm, m, col, val,
1583 struct_element_count),
1584 vec::append(llstructvals, vals_left),
1589 // Unbox in case of a box field
1590 if any_box_pat(m, col) {
1591 bcx = root_pats_as_necessary(bcx, m, col, val);
1592 let llbox = Load(bcx, val);
1593 let unboxed = GEPi(bcx, llbox, [0u, abi::box_field_body]);
1594 compile_submatch(bcx, enter_box(bcx, dm, m, col, val),
1595 vec::append(~[unboxed], vals_left), chk);
1599 if any_uniq_pat(m, col) {
1600 let pat_ty = node_id_type(bcx, pat_id);
1601 let llbox = Load(bcx, val);
1602 let unboxed = match ty::get(pat_ty).sty {
1603 ty::ty_uniq(*) if !ty::type_contents(bcx.tcx(), pat_ty).contains_managed() => llbox,
1604 _ => GEPi(bcx, llbox, [0u, abi::box_field_body])
1606 compile_submatch(bcx, enter_uniq(bcx, dm, m, col, val),
1607 vec::append(~[unboxed], vals_left), chk);
1611 if any_region_pat(m, col) {
1612 let loaded_val = Load(bcx, val);
1613 compile_submatch(bcx, enter_region(bcx, dm, m, col, val),
1614 vec::append(~[loaded_val], vals_left), chk);
1618 // Decide what kind of branch we need
1619 let opts = get_options(bcx, m, col);
1620 debug2!("options={:?}", opts);
1621 let mut kind = no_branch;
1622 let mut test_val = val;
1623 if opts.len() > 0u {
1626 let (the_kind, val_opt) = adt::trans_switch(bcx, repr, val);
1628 for &tval in val_opt.iter() { test_val = tval; }
1631 let pty = node_id_type(bcx, pat_id);
1632 test_val = load_if_immediate(bcx, val, pty);
1633 kind = if ty::type_is_integral(pty) { switch }
1637 test_val = Load(bcx, val);
1641 let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id));
1642 let unboxed = load_if_immediate(bcx, val, vt.vec_ty);
1643 let (_, len) = tvec::get_base_and_len(bcx, unboxed, vt.vec_ty);
1645 kind = compare_vec_len;
1649 for o in opts.iter() {
1651 range(_, _) => { kind = compare; break }
1655 let else_cx = match kind {
1656 no_branch | single => bcx,
1657 _ => sub_block(bcx, "match_else")
1659 let sw = if kind == switch {
1660 Switch(bcx, test_val, else_cx.llbb, opts.len())
1662 C_int(ccx, 0) // Placeholder for when not using a switch
1665 let defaults = enter_default(else_cx, dm, m, col, val, chk);
1666 let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1667 let len = opts.len();
1669 // Compile subtrees for each option
1670 for (i, opt) in opts.iter().enumerate() {
1671 // In some cases in vector pattern matching, we need to override
1672 // the failure case so that instead of failing, it proceeds to
1673 // try more matching. branch_chk, then, is the proper failure case
1674 // for the current conditional branch.
1675 let mut branch_chk = chk;
1676 let mut opt_cx = else_cx;
1677 if !exhaustive || i+1 < len {
1678 opt_cx = sub_block(bcx, "match_case");
1680 single => Br(bcx, opt_cx.llbb),
1682 match trans_opt(bcx, opt) {
1683 single_result(r) => {
1685 llvm::LLVMAddCase(sw, r.val, opt_cx.llbb);
1691 "in compile_submatch, expected \
1692 trans_opt to return a single_result")
1697 let t = node_id_type(bcx, pat_id);
1698 let Result {bcx: after_cx, val: matches} = {
1699 do with_scope_result(bcx, None,
1700 "compare_scope") |bcx| {
1701 match trans_opt(bcx, opt) {
1703 Result {bcx, val}) => {
1704 compare_values(bcx, test_val, val, t)
1707 Result {bcx, val}) => {
1708 compare_scalar_types(
1713 Result {val: vbegin, _},
1714 Result {bcx, val: vend}) => {
1715 let Result {bcx, val: llge} =
1716 compare_scalar_types(
1718 vbegin, t, ast::BiGe);
1719 let Result {bcx, val: llle} =
1720 compare_scalar_types(
1721 bcx, test_val, vend,
1723 rslt(bcx, And(bcx, llge, llle))
1728 bcx = sub_block(after_cx, "compare_next");
1729 CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1731 compare_vec_len => {
1732 let Result {bcx: after_cx, val: matches} = {
1733 do with_scope_result(bcx, None,
1734 "compare_vec_len_scope") |bcx| {
1735 match trans_opt(bcx, opt) {
1737 Result {bcx, val}) => {
1738 let value = compare_scalar_values(
1740 signed_int, ast::BiEq);
1744 Result {bcx, val: val}) => {
1745 let value = compare_scalar_values(
1747 signed_int, ast::BiGe);
1751 Result {val: vbegin, _},
1752 Result {bcx, val: vend}) => {
1754 compare_scalar_values(
1756 vbegin, signed_int, ast::BiGe);
1758 compare_scalar_values(
1759 bcx, test_val, vend,
1760 signed_int, ast::BiLe);
1761 rslt(bcx, And(bcx, llge, llle))
1766 bcx = sub_block(after_cx, "compare_vec_len_next");
1768 // If none of these subcases match, move on to the
1770 branch_chk = JumpToBasicBlock(bcx.llbb);
1771 CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1775 } else if kind == compare || kind == compare_vec_len {
1776 Br(bcx, else_cx.llbb);
1780 let mut unpacked = ~[];
1782 var(disr_val, repr) => {
1783 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1784 extract_variant_args(opt_cx, repr, disr_val, val);
1785 size = argvals.len();
1789 vec_len(n, vt, _) => {
1790 let (n, slice) = match vt {
1791 vec_len_ge(i) => (n + 1u, Some(i)),
1792 vec_len_eq => (n, None)
1794 let args = extract_vec_elems(opt_cx, pat_span, pat_id, n,
1795 slice, val, test_val);
1796 size = args.vals.len();
1797 unpacked = args.vals.clone();
1800 lit(_) | range(_, _) => ()
1802 let opt_ms = enter_opt(opt_cx, m, opt, col, size, val);
1803 let opt_vals = vec::append(unpacked, vals_left);
1804 compile_submatch(opt_cx, opt_ms, opt_vals, branch_chk);
1807 // Compile the fall-through case, if any
1809 if kind == compare || kind == compare_vec_len {
1810 Br(bcx, else_cx.llbb);
1813 compile_submatch(else_cx, defaults, vals_left, chk);
1818 pub fn trans_match(bcx: @mut Block,
1819 match_expr: &ast::Expr,
1820 discr_expr: &ast::Expr,
1822 dest: Dest) -> @mut Block {
1823 let _icx = push_ctxt("match::trans_match");
1824 do with_scope(bcx, match_expr.info(), "match") |bcx| {
1825 trans_match_inner(bcx, discr_expr, arms, dest)
1829 fn create_bindings_map(bcx: @mut Block, pat: @ast::Pat) -> BindingsMap {
1830 // Create the bindings map, which is a mapping from each binding name
1831 // to an alloca() that will be the value for that local variable.
1832 // Note that we use the names because each binding will have many ids
1833 // from the various alternatives.
1834 let ccx = bcx.ccx();
1835 let tcx = bcx.tcx();
1836 let mut bindings_map = HashMap::new();
1837 do pat_bindings(tcx.def_map, pat) |bm, p_id, span, path| {
1838 let ident = path_to_ident(path);
1839 let variable_ty = node_id_type(bcx, p_id);
1840 let llvariable_ty = type_of::type_of(ccx, variable_ty);
1846 // in this case, the final type of the variable will be T,
1847 // but during matching we need to store a *T as explained
1849 llmatch = alloca(bcx, llvariable_ty.ptr_to(), "__llmatch");
1850 trmode = TrByValue(alloca(bcx, llvariable_ty,
1853 ast::BindByRef(_) => {
1854 llmatch = alloca(bcx, llvariable_ty, bcx.ident(ident));
1858 bindings_map.insert(ident, BindingInfo {
1866 return bindings_map;
1869 fn trans_match_inner(scope_cx: @mut Block,
1870 discr_expr: &ast::Expr,
1872 dest: Dest) -> @mut Block {
1873 let _icx = push_ctxt("match::trans_match_inner");
1874 let mut bcx = scope_cx;
1875 let tcx = bcx.tcx();
1877 let discr_datum = unpack_datum!(bcx, {
1878 expr::trans_to_datum(bcx, discr_expr)
1880 if bcx.unreachable {
1884 let mut arm_datas = ~[];
1885 let mut matches = ~[];
1886 for arm in arms.iter() {
1887 let body = scope_block(bcx, arm.body.info(), "case_body");
1888 let bindings_map = create_bindings_map(bcx, arm.pats[0]);
1889 let arm_data = ArmData {
1892 bindings_map: @bindings_map
1894 arm_datas.push(arm_data.clone());
1895 for p in arm.pats.iter() {
1896 matches.push(Match {
1898 data: arm_data.clone(),
1904 let t = node_id_type(bcx, discr_expr.id);
1906 if ty::type_is_empty(tcx, t) {
1907 // Special case for empty types
1908 let fail_cx = @mut None;
1909 let fail_handler = @DynamicFailureHandler {
1911 sp: discr_expr.span,
1912 msg: @"scrutinizing value that can't exist",
1914 } as @CustomFailureHandler;
1915 CustomFailureHandlerClass(fail_handler)
1920 let lldiscr = discr_datum.to_zeroable_ref_llval(bcx);
1921 compile_submatch(bcx, matches, [lldiscr], chk);
1923 let mut arm_cxs = ~[];
1924 for arm_data in arm_datas.iter() {
1925 let mut bcx = arm_data.bodycx;
1927 // If this arm has a guard, then the various by-value bindings have
1928 // already been copied into their homes. If not, we do it here. This
1929 // is just to reduce code space. See extensive comment at the start
1930 // of the file for more details.
1931 if arm_data.arm.guard.is_none() {
1932 bcx = store_non_ref_bindings(bcx, arm_data.bindings_map, None);
1935 // insert bindings into the lllocals map and add cleanups
1936 bcx = insert_lllocals(bcx, arm_data.bindings_map, true);
1938 bcx = controlflow::trans_block(bcx, &arm_data.arm.body, dest);
1939 bcx = trans_block_cleanups(bcx, block_cleanups(arm_data.bodycx));
1943 bcx = controlflow::join_blocks(scope_cx, arm_cxs);
1947 enum IrrefutablePatternBindingMode {
1948 // Stores the association between node ID and LLVM value in `lllocals`.
1950 // Stores the association between node ID and LLVM value in `llargs`.
1954 pub fn store_local(bcx: @mut Block,
1956 opt_init_expr: Option<@ast::Expr>)
1959 * Generates code for a local variable declaration like
1960 * `let <pat>;` or `let <pat> = <opt_init_expr>`.
1962 let _icx = push_ctxt("match::store_local");
1965 return match opt_init_expr {
1966 Some(init_expr) => {
1967 // Optimize the "let x = expr" case. This just writes
1968 // the result of evaluating `expr` directly into the alloca
1969 // for `x`. Often the general path results in similar or the
1970 // same code post-optimization, but not always. In particular,
1971 // in unsafe code, you can have expressions like
1973 // let x = intrinsics::uninit();
1975 // In such cases, the more general path is unsafe, because
1976 // it assumes it is matching against a valid value.
1977 match simple_identifier(pat) {
1979 return mk_binding_alloca(
1980 bcx, pat.id, path, BindLocal,
1981 |bcx, _, llval| expr::trans_into(bcx, init_expr,
1982 expr::SaveIn(llval)));
1992 expr::trans_to_datum(bcx, init_expr));
1993 if ty::type_is_bot(expr_ty(bcx, init_expr)) {
1994 create_dummy_locals(bcx, pat)
1996 if bcx.sess().asm_comments() {
1997 add_comment(bcx, "creating zeroable ref llval");
1999 let llptr = init_datum.to_zeroable_ref_llval(bcx);
2000 return bind_irrefutable_pat(bcx, pat, llptr, BindLocal);
2004 create_dummy_locals(bcx, pat)
2008 fn create_dummy_locals(mut bcx: @mut Block, pat: @ast::Pat) -> @mut Block {
2009 // create dummy memory for the variables if we have no
2010 // value to store into them immediately
2011 let tcx = bcx.tcx();
2012 do pat_bindings(tcx.def_map, pat) |_, p_id, _, path| {
2013 bcx = mk_binding_alloca(
2014 bcx, p_id, path, BindLocal,
2015 |bcx, var_ty, llval| { zero_mem(bcx, llval, var_ty); bcx });
2021 pub fn store_arg(mut bcx: @mut Block,
2026 * Generates code for argument patterns like `fn foo(<pat>: T)`.
2027 * Creates entries in the `llargs` map for each of the bindings
2032 * - `pat` is the argument pattern
2033 * - `llval` is a pointer to the argument value (in other words,
2034 * if the argument type is `T`, then `llval` is a `T*`). In some
2035 * cases, this code may zero out the memory `llval` points at.
2037 let _icx = push_ctxt("match::store_arg");
2039 // We always need to cleanup the argument as we exit the fn scope.
2040 // Note that we cannot do it before for fear of a fn like
2041 // fn getaddr(~ref x: ~uint) -> *uint {....}
2042 // (From test `run-pass/func-arg-ref-pattern.rs`)
2043 let arg_ty = node_id_type(bcx, pat.id);
2044 add_clean(bcx, llval, arg_ty);
2046 // Debug information (the llvm.dbg.declare intrinsic to be precise) always expects to get an
2047 // alloca, which only is the case on the general path, so lets disable the optimized path when
2048 // debug info is enabled.
2049 let fast_path = !bcx.ccx().sess.opts.extra_debuginfo && simple_identifier(pat).is_some();
2052 // Optimized path for `x: T` case. This just adopts
2053 // `llval` wholesale as the pointer for `x`, avoiding the
2054 // general logic which may copy out of `llval`.
2055 bcx.fcx.llargs.insert(pat.id, llval);
2057 // General path. Copy out the values that are used in the
2059 bcx = bind_irrefutable_pat(bcx, pat, llval, BindArgument);
2065 fn mk_binding_alloca(mut bcx: @mut Block,
2068 binding_mode: IrrefutablePatternBindingMode,
2069 populate: &fn(@mut Block, ty::t, ValueRef) -> @mut Block) -> @mut Block {
2070 let var_ty = node_id_type(bcx, p_id);
2071 let ident = ast_util::path_to_ident(path);
2072 let llval = alloc_ty(bcx, var_ty, bcx.ident(ident));
2073 bcx = populate(bcx, var_ty, llval);
2074 let llmap = match binding_mode {
2075 BindLocal => bcx.fcx.lllocals,
2076 BindArgument => bcx.fcx.llargs
2078 llmap.insert(p_id, llval);
2079 add_clean(bcx, llval, var_ty);
2083 fn bind_irrefutable_pat(bcx: @mut Block,
2086 binding_mode: IrrefutablePatternBindingMode)
2089 * A simple version of the pattern matching code that only handles
2090 * irrefutable patterns. This is used in let/argument patterns,
2091 * not in match statements. Unifying this code with the code above
2092 * sounds nice, but in practice it produces very inefficient code,
2093 * since the match code is so much more general. In most cases,
2094 * LLVM is able to optimize the code, but it causes longer compile
2095 * times and makes the generated code nigh impossible to read.
2098 * - bcx: starting basic block context
2099 * - pat: the irrefutable pattern being matched.
2100 * - val: a pointer to the value being matched. If pat matches a value
2101 * of type T, then this is a T*. If the value is moved from `pat`,
2102 * then `*pat` will be zeroed; otherwise, it's existing cleanup
2104 * - binding_mode: is this for an argument or a local variable?
2107 debug2!("bind_irrefutable_pat(bcx={}, pat={}, binding_mode={:?})",
2109 pat.repr(bcx.tcx()),
2112 if bcx.sess().asm_comments() {
2113 add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
2114 pat.repr(bcx.tcx())));
2117 let _indenter = indenter();
2119 let _icx = push_ctxt("alt::bind_irrefutable_pat");
2121 let tcx = bcx.tcx();
2122 let ccx = bcx.ccx();
2124 ast::PatIdent(pat_binding_mode, ref path, inner) => {
2125 if pat_is_binding(tcx.def_map, pat) {
2126 // Allocate the stack slot where the value of this
2127 // binding will live and place it into the appropriate
2129 bcx = mk_binding_alloca(
2130 bcx, pat.id, path, binding_mode,
2131 |bcx, variable_ty, llvariable_val| {
2132 match pat_binding_mode {
2134 // By value binding: move the value that `val`
2135 // points at into the binding's stack slot.
2136 let datum = Datum {val: val,
2138 mode: ByRef(ZeroMem)};
2139 datum.store_to(bcx, INIT, llvariable_val)
2142 ast::BindByRef(_) => {
2143 // By ref binding: the value of the variable
2144 // is the pointer `val` itself.
2145 Store(bcx, val, llvariable_val);
2152 for &inner_pat in inner.iter() {
2153 bcx = bind_irrefutable_pat(bcx, inner_pat, val, binding_mode);
2156 ast::PatEnum(_, ref sub_pats) => {
2157 match bcx.tcx().def_map.find(&pat.id) {
2158 Some(&ast::DefVariant(enum_id, var_id, _)) => {
2159 let repr = adt::represent_node(bcx, pat.id);
2160 let vinfo = ty::enum_variant_with_id(ccx.tcx,
2163 let args = extract_variant_args(bcx,
2167 for sub_pat in sub_pats.iter() {
2168 for (i, argval) in args.vals.iter().enumerate() {
2169 bcx = bind_irrefutable_pat(bcx, sub_pat[i],
2170 *argval, binding_mode);
2174 Some(&ast::DefFn(*)) |
2175 Some(&ast::DefStruct(*)) => {
2178 // This is a unit-like struct. Nothing to do here.
2180 Some(ref elems) => {
2181 // This is the tuple struct case.
2182 let repr = adt::represent_node(bcx, pat.id);
2183 for (i, elem) in elems.iter().enumerate() {
2184 let fldptr = adt::trans_field_ptr(bcx, repr,
2186 bcx = bind_irrefutable_pat(bcx, *elem,
2187 fldptr, binding_mode);
2192 Some(&ast::DefStatic(_, false)) => {
2195 // Nothing to do here.
2199 ast::PatStruct(_, ref fields, _) => {
2200 let tcx = bcx.tcx();
2201 let pat_ty = node_id_type(bcx, pat.id);
2202 let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
2203 do expr::with_field_tys(tcx, pat_ty, None) |discr, field_tys| {
2204 for f in fields.iter() {
2205 let ix = ty::field_idx_strict(tcx, f.ident.name, field_tys);
2206 let fldptr = adt::trans_field_ptr(bcx, pat_repr, val,
2208 bcx = bind_irrefutable_pat(bcx, f.pat, fldptr, binding_mode);
2212 ast::PatTup(ref elems) => {
2213 let repr = adt::represent_node(bcx, pat.id);
2214 for (i, elem) in elems.iter().enumerate() {
2215 let fldptr = adt::trans_field_ptr(bcx, repr, val, 0, i);
2216 bcx = bind_irrefutable_pat(bcx, *elem, fldptr, binding_mode);
2219 ast::PatBox(inner) | ast::PatUniq(inner) => {
2220 let pat_ty = node_id_type(bcx, pat.id);
2221 let llbox = Load(bcx, val);
2222 let unboxed = match ty::get(pat_ty).sty {
2223 ty::ty_uniq(*) if !ty::type_contents(bcx.tcx(), pat_ty).contains_managed() => llbox,
2224 _ => GEPi(bcx, llbox, [0u, abi::box_field_body])
2226 bcx = bind_irrefutable_pat(bcx, inner, unboxed, binding_mode);
2228 ast::PatRegion(inner) => {
2229 let loaded_val = Load(bcx, val);
2230 bcx = bind_irrefutable_pat(bcx, inner, loaded_val, binding_mode);
2233 bcx.tcx().sess.span_bug(
2235 format!("vector patterns are never irrefutable!"));
2237 ast::PatWild | ast::PatLit(_) | ast::PatRange(_, _) => ()
2242 fn simple_identifier<'a>(pat: &'a ast::Pat) -> Option<&'a ast::Path> {
2244 ast::PatIdent(ast::BindInfer, ref path, None) => {