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.
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.
11 //! # Compilation of match statements
13 //! I will endeavor to explain the code as best I can. I have only a loose
14 //! understanding of some parts of it.
18 //! The basic state of the code is maintained in an array `m` of `Match`
19 //! objects. Each `Match` describes some list of patterns, all of which must
20 //! match against the current list of values. If those patterns match, then
21 //! the arm listed in the match is the correct arm. A given arm may have
22 //! multiple corresponding match entries, one for each alternative that
23 //! remains. As we proceed these sets of matches are adjusted by the various
24 //! `enter_XXX()` functions, each of which adjusts the set of options given
25 //! some information about the value which has been matched.
27 //! So, initially, there is one value and N matches, each of which have one
28 //! constituent pattern. N here is usually the number of arms but may be
29 //! greater, if some arms have multiple alternatives. For example, here:
31 //! enum Foo { A, B(int), C(uint, uint) }
39 //! The value would be `foo`. There would be four matches, each of which
40 //! contains one pattern (and, in one case, a guard). We could collect the
41 //! various options and then compile the code for the case where `foo` is an
42 //! `A`, a `B`, and a `C`. When we generate the code for `C`, we would (1)
43 //! drop the two matches that do not match a `C` and (2) expand the other two
44 //! into two patterns each. In the first case, the two patterns would be `1u`
45 //! and `2`, and the in the second case the _ pattern would be expanded into
46 //! `_` and `_`. The two values are of course the arguments to `C`.
48 //! Here is a quick guide to the various functions:
50 //! - `compile_submatch()`: The main workhouse. It takes a list of values and
51 //! a list of matches and finds the various possibilities that could occur.
53 //! - `enter_XXX()`: modifies the list of matches based on some information
54 //! about the value that has been matched. For example,
55 //! `enter_rec_or_struct()` adjusts the values given that a record or struct
56 //! has been matched. This is an infallible pattern, so *all* of the matches
57 //! must be either wildcards or record/struct patterns. `enter_opt()`
58 //! handles the fallible cases, and it is correspondingly more complex.
62 //! We store information about the bound variables for each arm as part of the
63 //! per-arm `ArmData` struct. There is a mapping from identifiers to
64 //! `BindingInfo` structs. These structs contain the mode/id/type of the
65 //! binding, but they also contain an LLVM value which points at an alloca
66 //! called `llmatch`. For by value bindings that are Copy, we also create
67 //! an extra alloca that we copy the matched value to so that any changes
68 //! we do to our copy is not reflected in the original and vice-versa.
69 //! We don't do this if it's a move since the original value can't be used
70 //! and thus allowing us to cheat in not creating an extra alloca.
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 //! Once a pattern is completely matched, and assuming that there is no guard
87 //! pattern, we will branch to a block that leads to the body itself. For any
88 //! by-value bindings, this block will first load the ptr from `llmatch` (the
89 //! one of type `D*`) and then load a second time to get the actual value (the
90 //! one of type `D`). For by ref bindings, the value of the local variable is
91 //! simply the first alloca.
93 //! So, for the example above, we would generate a setup kind of like this:
99 //! +--------------------------------------------+
100 //! | llmatch_c = (addr of first half of tuple) |
101 //! | llmatch_d = (addr of second half of tuple) |
102 //! +--------------------------------------------+
104 //! +--------------------------------------+
105 //! | *llbinding_d = **llmatch_d |
106 //! +--------------------------------------+
108 //! If there is a guard, the situation is slightly different, because we must
109 //! execute the guard code. Moreover, we need to do so once for each of the
110 //! alternatives that lead to the arm, because if the guard fails, they may
111 //! have different points from which to continue the search. Therefore, in that
112 //! case, we generate code that looks more like:
118 //! +-------------------------------------------+
119 //! | llmatch_c = (addr of first half of tuple) |
120 //! | llmatch_d = (addr of first half of tuple) |
121 //! +-------------------------------------------+
123 //! +-------------------------------------------------+
124 //! | *llbinding_d = **llmatch_d |
125 //! | check condition |
126 //! | if false { goto next case } |
127 //! | if true { goto body } |
128 //! +-------------------------------------------------+
130 //! The handling for the cleanups is a bit... sensitive. Basically, the body
131 //! is the one that invokes `add_clean()` for each binding. During the guard
132 //! evaluation, we add temporary cleanups and revoke them after the guard is
133 //! evaluated (it could fail, after all). Note that guards and moves are
134 //! just plain incompatible.
136 //! Some relevant helper functions that manage bindings:
137 //! - `create_bindings_map()`
138 //! - `insert_lllocals()`
141 //! ## Notes on vector pattern matching.
143 //! Vector pattern matching is surprisingly tricky. The problem is that
144 //! the structure of the vector isn't fully known, and slice matches
145 //! can be done on subparts of it.
147 //! The way that vector pattern matches are dealt with, then, is as
148 //! follows. First, we make the actual condition associated with a
149 //! vector pattern simply a vector length comparison. So the pattern
150 //! [1, .. x] gets the condition "vec len >= 1", and the pattern
151 //! [.. x] gets the condition "vec len >= 0". The problem here is that
152 //! having the condition "vec len >= 1" hold clearly does not mean that
153 //! only a pattern that has exactly that condition will match. This
154 //! means that it may well be the case that a condition holds, but none
155 //! of the patterns matching that condition match; to deal with this,
156 //! when doing vector length matches, we have match failures proceed to
157 //! the next condition to check.
159 //! There are a couple more subtleties to deal with. While the "actual"
160 //! condition associated with vector length tests is simply a test on
161 //! the vector length, the actual vec_len Opt entry contains more
162 //! information used to restrict which matches are associated with it.
163 //! So that all matches in a submatch are matching against the same
164 //! values from inside the vector, they are split up by how many
165 //! elements they match at the front and at the back of the vector. In
166 //! order to make sure that arms are properly checked in order, even
167 //! with the overmatching conditions, each vec_len Opt entry is
168 //! associated with a range of matches.
169 //! Consider the following:
171 //! match &[1, 2, 3] {
172 //! [1, 1, .. _] => 0,
173 //! [1, 2, 2, .. _] => 1,
174 //! [1, 2, 3, .. _] => 2,
175 //! [1, 2, .. _] => 3,
178 //! The proper arm to match is arm 2, but arms 0 and 3 both have the
179 //! condition "len >= 2". If arm 3 was lumped in with arm 0, then the
180 //! wrong branch would be taken. Instead, vec_len Opts are associated
181 //! with a contiguous range of matches that have the same "shape".
182 //! This is sort of ugly and requires a bunch of special handling of
185 pub use self::BranchKind::*;
186 pub use self::OptResult::*;
187 pub use self::TransBindingMode::*;
189 use self::FailureHandler::*;
192 use llvm::{ValueRef, BasicBlockRef};
193 use middle::check_match::StaticInliner;
194 use middle::check_match;
195 use middle::const_eval;
197 use middle::expr_use_visitor as euv;
198 use middle::lang_items::StrEqFnLangItem;
199 use middle::mem_categorization as mc;
200 use middle::pat_util::*;
201 use middle::resolve::DefMap;
204 use trans::build::{AddCase, And, BitCast, Br, CondBr, GEPi, InBoundsGEP, Load};
205 use trans::build::{Mul, Not, Store, Sub, add_comment};
208 use trans::cleanup::{mod, CleanupMethods};
209 use trans::common::*;
212 use trans::expr::{mod, Dest};
215 use trans::debuginfo;
216 use middle::ty::{mod, Ty};
217 use session::config::FullDebugInfo;
218 use util::common::indenter;
219 use util::nodemap::FnvHashMap;
220 use util::ppaux::{Repr, vec_map_to_string};
223 use std::iter::AdditiveIterator;
226 use syntax::ast::{DUMMY_NODE_ID, Ident};
227 use syntax::codemap::Span;
228 use syntax::fold::Folder;
232 struct ConstantExpr<'a>(&'a ast::Expr);
234 impl<'a> Copy for ConstantExpr<'a> {}
236 impl<'a> ConstantExpr<'a> {
237 fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
238 let ConstantExpr(expr) = self;
239 let ConstantExpr(other_expr) = other;
240 match const_eval::compare_lit_exprs(tcx, expr, other_expr) {
241 Some(val1) => val1 == 0,
242 None => panic!("compare_list_exprs: type mismatch"),
247 // An option identifying a branch (either a literal, an enum variant or a range)
250 ConstantValue(ConstantExpr<'a>),
251 ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>),
252 Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId),
253 SliceLengthEqual(uint),
254 SliceLengthGreaterOrEqual(/* prefix length */ uint, /* suffix length */ uint),
257 impl<'a, 'tcx> Opt<'a, 'tcx> {
258 fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
259 match (self, other) {
260 (&ConstantValue(a), &ConstantValue(b)) => a.eq(b, tcx),
261 (&ConstantRange(a1, a2), &ConstantRange(b1, b2)) => {
262 a1.eq(b1, tcx) && a2.eq(b2, tcx)
264 (&Variant(a_disr, ref a_repr, a_def), &Variant(b_disr, ref b_repr, b_def)) => {
265 a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
267 (&SliceLengthEqual(a), &SliceLengthEqual(b)) => a == b,
268 (&SliceLengthGreaterOrEqual(a1, a2), &SliceLengthGreaterOrEqual(b1, b2)) => {
275 fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
276 let _icx = push_ctxt("match::trans_opt");
279 ConstantValue(ConstantExpr(lit_expr)) => {
280 let lit_ty = ty::node_id_to_type(bcx.tcx(), lit_expr.id);
281 let (llval, _) = consts::const_expr(ccx, &*lit_expr);
282 let lit_datum = immediate_rvalue(llval, lit_ty);
283 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
284 SingleResult(Result::new(bcx, lit_datum.val))
286 ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2)) => {
287 let (l1, _) = consts::const_expr(ccx, &**l1);
288 let (l2, _) = consts::const_expr(ccx, &**l2);
289 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
291 Variant(disr_val, ref repr, _) => {
292 adt::trans_case(bcx, &**repr, disr_val)
294 SliceLengthEqual(length) => {
295 SingleResult(Result::new(bcx, C_uint(ccx, length)))
297 SliceLengthGreaterOrEqual(prefix, suffix) => {
298 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
304 #[deriving(PartialEq)]
305 pub enum BranchKind {
313 impl Copy for BranchKind {}
315 pub enum OptResult<'blk, 'tcx: 'blk> {
316 SingleResult(Result<'blk, 'tcx>),
317 RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
318 LowerBound(Result<'blk, 'tcx>)
322 pub enum TransBindingMode {
323 TrByCopy(/* llbinding */ ValueRef),
328 impl Copy for TransBindingMode {}
330 /// Information about a pattern binding:
331 /// - `llmatch` is a pointer to a stack slot. The stack slot contains a
332 /// pointer into the value being matched. Hence, llmatch has type `T**`
333 /// where `T` is the value being matched.
334 /// - `trmode` is the trans binding mode
335 /// - `id` is the node id of the binding
336 /// - `ty` is the Rust type of the binding
338 pub struct BindingInfo<'tcx> {
339 pub llmatch: ValueRef,
340 pub trmode: TransBindingMode,
346 impl<'tcx> Copy for BindingInfo<'tcx> {}
348 type BindingsMap<'tcx> = FnvHashMap<Ident, BindingInfo<'tcx>>;
350 struct ArmData<'p, 'blk, 'tcx: 'blk> {
351 bodycx: Block<'blk, 'tcx>,
353 bindings_map: BindingsMap<'tcx>
356 /// Info about Match.
357 /// If all `pats` are matched then arm `data` will be executed.
358 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
359 /// these pointers are stored in llmatch variables just before executing `data` arm.
360 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
361 pats: Vec<&'p ast::Pat>,
362 data: &'a ArmData<'p, 'blk, 'tcx>,
363 bound_ptrs: Vec<(Ident, ValueRef)>,
366 impl<'a, 'p, 'blk, 'tcx> Repr<'tcx> for Match<'a, 'p, 'blk, 'tcx> {
367 fn repr(&self, tcx: &ty::ctxt) -> String {
368 if tcx.sess.verbose() {
369 // for many programs, this just take too long to serialize
372 format!("{} pats", self.pats.len())
377 fn has_nested_bindings(m: &[Match], col: uint) -> bool {
379 match br.pats[col].node {
380 ast::PatIdent(_, _, Some(_)) => return true,
387 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
388 m: &[Match<'a, 'p, 'blk, 'tcx>],
391 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
392 debug!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
396 bcx.val_to_string(val));
397 let _indenter = indenter();
400 let mut bound_ptrs = br.bound_ptrs.clone();
401 let mut pat = br.pats[col];
403 pat = match pat.node {
404 ast::PatIdent(_, ref path, Some(ref inner)) => {
405 bound_ptrs.push((path.node, val));
412 let mut pats = br.pats.clone();
417 bound_ptrs: bound_ptrs
422 type EnterPatterns<'a, 'p> = |&[&'p ast::Pat]|: 'a -> Option<Vec<&'p ast::Pat>>;
424 fn enter_match<'a, 'b, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
426 m: &[Match<'a, 'p, 'blk, 'tcx>],
429 e: EnterPatterns<'b, 'p>)
430 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
431 debug!("enter_match(bcx={}, m={}, col={}, val={})",
435 bcx.val_to_string(val));
436 let _indenter = indenter();
438 m.iter().filter_map(|br| {
439 e(br.pats.as_slice()).map(|pats| {
440 let this = br.pats[col];
441 let mut bound_ptrs = br.bound_ptrs.clone();
443 ast::PatIdent(_, ref path, None) => {
444 if pat_is_binding(dm, &*this) {
445 bound_ptrs.push((path.node, val));
448 ast::PatVec(ref before, Some(ref slice), ref after) => {
449 if let ast::PatIdent(_, ref path, None) = slice.node {
450 let subslice_val = bind_subslice_pat(
452 before.len(), after.len());
453 bound_ptrs.push((path.node, subslice_val));
461 bound_ptrs: bound_ptrs
467 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
469 m: &[Match<'a, 'p, 'blk, 'tcx>],
472 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
473 debug!("enter_default(bcx={}, m={}, col={}, val={})",
477 bcx.val_to_string(val));
478 let _indenter = indenter();
480 // Collect all of the matches that can match against anything.
481 enter_match(bcx, dm, m, col, val, |pats| {
482 if pat_is_binding_or_wild(dm, &*pats[col]) {
483 let mut r = pats[..col].to_vec();
484 r.push_all(pats[col + 1..]);
492 // <pcwalton> nmatsakis: what does enter_opt do?
493 // <pcwalton> in trans/match
494 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
495 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
496 // patterns as needed
497 // <nmatsakis> yeah, at some point I kind of achieved some level of
499 // <nmatsakis> anyhow, they adjust the patterns given that something of that
500 // kind has been found
501 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
503 // <nmatsakis> enter_match() kind of embodies the generic code
504 // <nmatsakis> it is provided with a function that tests each pattern to see
505 // if it might possibly apply and so forth
506 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
507 // <nmatsakis> then _ would be expanded to (_, _)
508 // <nmatsakis> one spot for each of the sub-patterns
509 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
511 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
512 // are infallible patterns
513 // <nmatsakis> so all patterns must either be records (resp. tuples) or
516 /// The above is now outdated in that enter_match() now takes a function that
517 /// takes the complete row of patterns rather than just the first one.
518 /// Also, most of the enter_() family functions have been unified with
519 /// the check_match specialization step.
520 fn enter_opt<'a, 'p, 'blk, 'tcx>(
521 bcx: Block<'blk, 'tcx>,
524 m: &[Match<'a, 'p, 'blk, 'tcx>],
529 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
530 debug!("enter_opt(bcx={}, m={}, opt={}, col={}, val={})",
535 bcx.val_to_string(val));
536 let _indenter = indenter();
538 let ctor = match opt {
539 &ConstantValue(ConstantExpr(expr)) => check_match::ConstantValue(
540 const_eval::eval_const_expr(bcx.tcx(), &*expr)
542 &ConstantRange(ConstantExpr(lo), ConstantExpr(hi)) => check_match::ConstantRange(
543 const_eval::eval_const_expr(bcx.tcx(), &*lo),
544 const_eval::eval_const_expr(bcx.tcx(), &*hi)
546 &SliceLengthEqual(n) =>
547 check_match::Slice(n),
548 &SliceLengthGreaterOrEqual(before, after) =>
549 check_match::SliceWithSubslice(before, after),
550 &Variant(_, _, def_id) =>
551 check_match::Constructor::Variant(def_id)
554 let param_env = ty::empty_parameter_environment();
555 let mcx = check_match::MatchCheckCtxt {
557 param_env: param_env,
559 enter_match(bcx, dm, m, col, val, |pats|
560 check_match::specialize(&mcx, pats.as_slice(), &ctor, col, variant_size)
564 // Returns the options in one column of matches. An option is something that
565 // needs to be conditionally matched at runtime; for example, the discriminant
566 // on a set of enum variants or a literal.
567 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
568 m: &[Match<'a, 'p, 'blk, 'tcx>], col: uint)
569 -> Vec<Opt<'p, 'tcx>> {
572 let mut found: Vec<Opt> = vec![];
574 let cur = br.pats[col];
575 let opt = match cur.node {
576 ast::PatLit(ref l) => ConstantValue(ConstantExpr(&**l)),
577 ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
578 // This is either an enum variant or a variable binding.
579 let opt_def = tcx.def_map.borrow().get(&cur.id).cloned();
581 Some(def::DefVariant(enum_id, var_id, _)) => {
582 let variant = ty::enum_variant_with_id(tcx, enum_id, var_id);
583 Variant(variant.disr_val, adt::represent_node(bcx, cur.id), var_id)
588 ast::PatRange(ref l1, ref l2) => {
589 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2))
591 ast::PatVec(ref before, None, ref after) => {
592 SliceLengthEqual(before.len() + after.len())
594 ast::PatVec(ref before, Some(_), ref after) => {
595 SliceLengthGreaterOrEqual(before.len(), after.len())
600 if !found.iter().any(|x| x.eq(&opt, tcx)) {
607 struct ExtractedBlock<'blk, 'tcx: 'blk> {
609 bcx: Block<'blk, 'tcx>,
612 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
613 repr: &adt::Repr<'tcx>,
616 -> ExtractedBlock<'blk, 'tcx> {
617 let _icx = push_ctxt("match::extract_variant_args");
618 let args = Vec::from_fn(adt::num_args(repr, disr_val), |i| {
619 adt::trans_field_ptr(bcx, repr, val, disr_val, i)
622 ExtractedBlock { vals: args, bcx: bcx }
625 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
626 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
627 fn match_datum<'tcx>(val: ValueRef, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
628 Datum::new(val, left_ty, Lvalue)
631 fn bind_subslice_pat(bcx: Block,
635 offset_right: uint) -> ValueRef {
636 let _icx = push_ctxt("match::bind_subslice_pat");
637 let vec_ty = node_id_type(bcx, pat_id);
638 let vt = tvec::vec_types(bcx, ty::sequence_element_type(bcx.tcx(), ty::type_content(vec_ty)));
639 let vec_datum = match_datum(val, vec_ty);
640 let (base, len) = vec_datum.get_vec_base_and_len(bcx);
642 let slice_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), offset_left));
643 let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset);
644 let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
645 let slice_len = Sub(bcx, len, slice_len_offset);
646 let slice_ty = ty::mk_slice(bcx.tcx(),
648 ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable});
649 let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
650 Store(bcx, slice_begin,
651 GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_ADDR]));
652 Store(bcx, slice_len, GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_EXTRA]));
656 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
661 -> ExtractedBlock<'blk, 'tcx> {
662 let _icx = push_ctxt("match::extract_vec_elems");
663 let vec_datum = match_datum(val, left_ty);
664 let (base, len) = vec_datum.get_vec_base_and_len(bcx);
665 let mut elems = vec![];
666 elems.extend(range(0, before).map(|i| GEPi(bcx, base, &[i])));
667 elems.extend(range(0, after).rev().map(|i| {
668 InBoundsGEP(bcx, base, &[
669 Sub(bcx, len, C_uint(bcx.ccx(), i + 1))
672 ExtractedBlock { vals: elems, bcx: bcx }
675 // Macro for deciding whether any of the remaining matches fit a given kind of
676 // pattern. Note that, because the macro is well-typed, either ALL of the
677 // matches should fit that sort of pattern or NONE (however, some of the
678 // matches may be wildcards like _ or identifiers).
679 macro_rules! any_pat (
680 ($m:expr, $col:expr, $pattern:pat) => (
681 ($m).iter().any(|br| {
682 match br.pats[$col].node {
690 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
691 any_pat!(m, col, ast::PatBox(_))
694 fn any_region_pat(m: &[Match], col: uint) -> bool {
695 any_pat!(m, col, ast::PatRegion(_))
698 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: uint) -> bool {
700 let pat = br.pats[col];
702 ast::PatTup(_) => true,
703 ast::PatStruct(..) => {
704 match tcx.def_map.borrow().get(&pat.id) {
705 Some(&def::DefVariant(..)) => false,
709 ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
710 match tcx.def_map.borrow().get(&pat.id) {
711 Some(&def::DefStruct(..)) => true,
720 /// What to do when the pattern match fails.
721 enum FailureHandler {
723 JumpToBasicBlock(BasicBlockRef),
727 impl FailureHandler {
728 fn is_fallible(&self) -> bool {
735 fn is_infallible(&self) -> bool {
739 fn handle_fail(&self, bcx: Block) {
742 panic!("attempted to panic in a non-panicking panic handler!"),
743 JumpToBasicBlock(basic_block) =>
744 Br(bcx, basic_block),
746 build::Unreachable(bcx)
751 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<uint> {
752 fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
754 ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
755 _ if pat_is_refutable(def_map, pat) => 1u,
760 let column_score: |&[Match], uint| -> uint = |m, col| {
761 let total_score = m.iter()
762 .map(|row| row.pats[col])
763 .map(|pat| pat_score(def_map, pat))
766 // Irrefutable columns always go first, they'd only be duplicated in the branches.
767 if total_score == 0 {
774 let column_contains_any_nonwild_patterns: |&uint| -> bool = |&col| {
775 m.iter().any(|row| match row.pats[col].node {
776 ast::PatWild(_) => false,
781 range(0, m[0].pats.len())
782 .filter(column_contains_any_nonwild_patterns)
783 .map(|col| (col, column_score(m, col)))
784 .max_by(|&(_, score)| score)
788 // Compiles a comparison between two things.
789 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
793 -> Result<'blk, 'tcx> {
794 fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
798 -> Result<'blk, 'tcx> {
799 let did = langcall(cx,
801 format!("comparison of `{}`",
802 cx.ty_to_string(rhs_t)).as_slice(),
804 callee::trans_lang_call(cx, did, &[lhs, rhs], None)
807 let _icx = push_ctxt("compare_values");
808 if ty::type_is_scalar(rhs_t) {
809 let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
810 return Result::new(rs.bcx, rs.val);
814 ty::ty_rptr(_, mt) => match mt.ty.sty {
815 ty::ty_str => compare_str(cx, lhs, rhs, rhs_t),
816 ty::ty_vec(ty, _) => match ty.sty {
817 ty::ty_uint(ast::TyU8) => {
818 // NOTE: cast &[u8] to &str and abuse the str_eq lang item,
819 // which calls memcmp().
820 let t = ty::mk_str_slice(cx.tcx(), ty::ReStatic, ast::MutImmutable);
821 let lhs = BitCast(cx, lhs, type_of::type_of(cx.ccx(), t).ptr_to());
822 let rhs = BitCast(cx, rhs, type_of::type_of(cx.ccx(), t).ptr_to());
823 compare_str(cx, lhs, rhs, rhs_t)
825 _ => cx.sess().bug("only byte strings supported in compare_values"),
827 _ => cx.sess().bug("only string and byte strings supported in compare_values"),
829 _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
833 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
834 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
835 bindings_map: &BindingsMap<'tcx>,
836 cs: Option<cleanup::ScopeId>)
837 -> Block<'blk, 'tcx> {
838 for (&ident, &binding_info) in bindings_map.iter() {
839 let llval = match binding_info.trmode {
840 // By value mut binding for a copy type: load from the ptr
841 // into the matched value and copy to our alloca
842 TrByCopy(llbinding) => {
843 let llval = Load(bcx, binding_info.llmatch);
844 let datum = Datum::new(llval, binding_info.ty, Lvalue);
845 call_lifetime_start(bcx, llbinding);
846 bcx = datum.store_to(bcx, llbinding);
847 if let Some(cs) = cs {
848 bcx.fcx.schedule_lifetime_end(cs, llbinding);
854 // By value move bindings: load from the ptr into the matched value
855 TrByMove => Load(bcx, binding_info.llmatch),
857 // By ref binding: use the ptr into the matched value
858 TrByRef => binding_info.llmatch
861 let datum = Datum::new(llval, binding_info.ty, Lvalue);
862 if let Some(cs) = cs {
863 bcx.fcx.schedule_drop_and_zero_mem(cs, llval, binding_info.ty);
864 bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
867 debug!("binding {} to {}",
869 bcx.val_to_string(llval));
870 bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
872 if bcx.sess().opts.debuginfo == FullDebugInfo {
873 debuginfo::create_match_binding_metadata(bcx,
881 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
882 guard_expr: &ast::Expr,
883 data: &ArmData<'p, 'blk, 'tcx>,
884 m: &[Match<'a, 'p, 'blk, 'tcx>],
886 chk: &FailureHandler,
887 has_genuine_default: bool)
888 -> Block<'blk, 'tcx> {
889 debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
891 bcx.expr_to_string(guard_expr),
893 vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
894 let _indenter = indenter();
896 let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
898 let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
899 let val = val.to_llbool(bcx);
901 for (_, &binding_info) in data.bindings_map.iter() {
902 if let TrByCopy(llbinding) = binding_info.trmode {
903 call_lifetime_end(bcx, llbinding);
907 with_cond(bcx, Not(bcx, val), |bcx| {
908 // Guard does not match: remove all bindings from the lllocals table
909 for (_, &binding_info) in data.bindings_map.iter() {
910 call_lifetime_end(bcx, binding_info.llmatch);
911 bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
914 // If the default arm is the only one left, move on to the next
915 // condition explicitly rather than (possibly) falling back to
917 &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
918 chk.handle_fail(bcx);
921 compile_submatch(bcx, m, vals, chk, has_genuine_default);
928 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
929 m: &[Match<'a, 'p, 'blk, 'tcx>],
931 chk: &FailureHandler,
932 has_genuine_default: bool) {
933 debug!("compile_submatch(bcx={}, m={}, vals={})",
936 vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
937 let _indenter = indenter();
938 let _icx = push_ctxt("match::compile_submatch");
941 if chk.is_fallible() {
942 chk.handle_fail(bcx);
948 let def_map = &tcx.def_map;
949 match pick_column_to_specialize(def_map, m) {
952 if has_nested_bindings(m, col) {
953 let expanded = expand_nested_bindings(bcx, m, col, val);
954 compile_submatch_continue(bcx,
962 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
966 let data = &m[0].data;
967 for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
968 let llmatch = data.bindings_map[*ident].llmatch;
969 call_lifetime_start(bcx, llmatch);
970 Store(bcx, *value_ptr, llmatch);
972 match data.arm.guard {
973 Some(ref guard_expr) => {
974 bcx = compile_guard(bcx,
980 has_genuine_default);
984 Br(bcx, data.bodycx.llbb);
989 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
990 m: &[Match<'a, 'p, 'blk, 'tcx>],
992 chk: &FailureHandler,
995 has_genuine_default: bool) {
998 let dm = &tcx.def_map;
1000 let mut vals_left = vals[0u..col].to_vec();
1001 vals_left.push_all(vals[col + 1u..]);
1002 let ccx = bcx.fcx.ccx;
1004 // Find a real id (we're adding placeholder wildcard patterns, but
1005 // each column is guaranteed to have at least one real pattern)
1006 let pat_id = m.iter().map(|br| br.pats[col].id)
1007 .find(|&id| id != DUMMY_NODE_ID)
1008 .unwrap_or(DUMMY_NODE_ID);
1010 let left_ty = if pat_id == DUMMY_NODE_ID {
1013 node_id_type(bcx, pat_id)
1016 let mcx = check_match::MatchCheckCtxt {
1018 param_env: ty::empty_parameter_environment(),
1020 let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1021 let repr = adt::represent_type(bcx.ccx(), left_ty);
1022 let arg_count = adt::num_args(&*repr, 0);
1023 let field_vals: Vec<ValueRef> = std::iter::range(0, arg_count).map(|ix|
1024 adt::trans_field_ptr(bcx, &*repr, val, 0, ix)
1027 } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1028 Some(vec!(Load(bcx, val)))
1031 ty::ty_vec(_, Some(n)) => {
1032 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1040 Some(field_vals) => {
1041 let pats = enter_match(bcx, dm, m, col, val, |pats|
1042 check_match::specialize(&mcx, pats,
1043 &check_match::Single, col,
1046 let mut vals = field_vals;
1047 vals.push_all(vals_left.as_slice());
1048 compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
1054 // Decide what kind of branch we need
1055 let opts = get_branches(bcx, m, col);
1056 debug!("options={}", opts);
1057 let mut kind = NoBranch;
1058 let mut test_val = val;
1059 debug!("test_val={}", bcx.val_to_string(test_val));
1060 if opts.len() > 0u {
1062 ConstantValue(_) | ConstantRange(_, _) => {
1063 test_val = load_if_immediate(bcx, val, left_ty);
1064 kind = if ty::type_is_integral(left_ty) {
1070 Variant(_, ref repr, _) => {
1071 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
1073 for &tval in val_opt.iter() { test_val = tval; }
1075 SliceLengthEqual(_) | SliceLengthGreaterOrEqual(_, _) => {
1076 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
1082 for o in opts.iter() {
1084 ConstantRange(_, _) => { kind = Compare; break },
1085 SliceLengthGreaterOrEqual(_, _) => { kind = CompareSliceLength; break },
1089 let else_cx = match kind {
1090 NoBranch | Single => bcx,
1091 _ => bcx.fcx.new_temp_block("match_else")
1093 let sw = if kind == Switch {
1094 build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1096 C_int(ccx, 0i) // Placeholder for when not using a switch
1099 let defaults = enter_default(else_cx, dm, m, col, val);
1100 let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1101 let len = opts.len();
1103 // Compile subtrees for each option
1104 for (i, opt) in opts.iter().enumerate() {
1105 // In some cases of range and vector pattern matching, we need to
1106 // override the failure case so that instead of failing, it proceeds
1107 // to try more matching. branch_chk, then, is the proper failure case
1108 // for the current conditional branch.
1109 let mut branch_chk = None;
1110 let mut opt_cx = else_cx;
1111 if !exhaustive || i + 1 < len {
1112 opt_cx = bcx.fcx.new_temp_block("match_case");
1114 Single => Br(bcx, opt_cx.llbb),
1116 match opt.trans(bcx) {
1117 SingleResult(r) => {
1118 AddCase(sw, r.val, opt_cx.llbb);
1123 "in compile_submatch, expected \
1124 opt.trans() to return a SingleResult")
1128 Compare | CompareSliceLength => {
1129 let t = if kind == Compare {
1132 ty::mk_uint() // vector length
1134 let Result { bcx: after_cx, val: matches } = {
1135 match opt.trans(bcx) {
1136 SingleResult(Result { bcx, val }) => {
1137 compare_values(bcx, test_val, val, t)
1139 RangeResult(Result { val: vbegin, .. },
1140 Result { bcx, val: vend }) => {
1141 let Result { bcx, val: llge } =
1142 compare_scalar_types(
1144 vbegin, t, ast::BiGe);
1145 let Result { bcx, val: llle } =
1146 compare_scalar_types(
1147 bcx, test_val, vend,
1149 Result::new(bcx, And(bcx, llge, llle))
1151 LowerBound(Result { bcx, val }) => {
1152 compare_scalar_types(bcx, test_val, val, t, ast::BiGe)
1156 bcx = fcx.new_temp_block("compare_next");
1158 // If none of the sub-cases match, and the current condition
1159 // is guarded or has multiple patterns, move on to the next
1160 // condition, if there is any, rather than falling back to
1162 let guarded = m[i].data.arm.guard.is_some();
1163 let multi_pats = m[i].pats.len() > 1;
1164 if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1165 branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1167 CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1171 } else if kind == Compare || kind == CompareSliceLength {
1172 Br(bcx, else_cx.llbb);
1176 let mut unpacked = Vec::new();
1178 Variant(disr_val, ref repr, _) => {
1179 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1180 extract_variant_args(opt_cx, &**repr, disr_val, val);
1181 size = argvals.len();
1185 SliceLengthEqual(len) => {
1186 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1187 size = args.vals.len();
1188 unpacked = args.vals.clone();
1191 SliceLengthGreaterOrEqual(before, after) => {
1192 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1193 size = args.vals.len();
1194 unpacked = args.vals.clone();
1197 ConstantValue(_) | ConstantRange(_, _) => ()
1199 let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1200 let mut opt_vals = unpacked;
1201 opt_vals.push_all(vals_left.as_slice());
1202 compile_submatch(opt_cx,
1204 opt_vals.as_slice(),
1205 branch_chk.as_ref().unwrap_or(chk),
1206 has_genuine_default);
1209 // Compile the fall-through case, if any
1210 if !exhaustive && kind != Single {
1211 if kind == Compare || kind == CompareSliceLength {
1212 Br(bcx, else_cx.llbb);
1215 // If there is only one default arm left, move on to the next
1216 // condition explicitly rather than (eventually) falling back to
1217 // the last default arm.
1218 &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1219 chk.handle_fail(else_cx);
1222 compile_submatch(else_cx,
1223 defaults.as_slice(),
1224 vals_left.as_slice(),
1226 has_genuine_default);
1232 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1233 match_expr: &ast::Expr,
1234 discr_expr: &ast::Expr,
1237 -> Block<'blk, 'tcx> {
1238 let _icx = push_ctxt("match::trans_match");
1239 trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1242 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1243 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1244 let (vid, field) = match discr.node {
1245 ast::ExprPath(..) => match bcx.def(discr.id) {
1246 def::DefLocal(vid) | def::DefUpvar(vid, _, _) => (vid, None),
1249 ast::ExprField(ref base, field) => {
1250 let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1251 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1254 (vid, Some(mc::NamedField(field.node.name)))
1256 ast::ExprTupField(ref base, field) => {
1257 let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1258 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1261 (vid, Some(mc::PositionalField(field.node)))
1266 let mut rc = ReassignmentChecker {
1272 let param_env = ty::empty_parameter_environment();
1273 let mut visitor = euv::ExprUseVisitor::new(&mut rc, bcx, param_env);
1274 visitor.walk_expr(body);
1279 struct ReassignmentChecker {
1281 field: Option<mc::FieldName>,
1285 // Determine if the expression we're matching on is reassigned to within
1286 // the body of the match's arm.
1287 // We only care for the `mutate` callback since this check only matters
1288 // for cases where the matched value is moved.
1289 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1290 fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1291 fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1292 fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1293 fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1294 _: ty::BorrowKind, _: euv::LoanCause) {}
1295 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1297 fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1299 mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1300 mc::cat_local(vid) => self.reassigned = self.node == vid,
1301 mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1302 match base_cmt.cat {
1303 mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1304 mc::cat_local(vid) => {
1305 self.reassigned = self.node == vid && Some(field) == self.field
1315 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1316 discr: &ast::Expr, body: &ast::Expr)
1317 -> BindingsMap<'tcx> {
1318 // Create the bindings map, which is a mapping from each binding name
1319 // to an alloca() that will be the value for that local variable.
1320 // Note that we use the names because each binding will have many ids
1321 // from the various alternatives.
1322 let ccx = bcx.ccx();
1323 let tcx = bcx.tcx();
1324 let reassigned = is_discr_reassigned(bcx, discr, body);
1325 let mut bindings_map = FnvHashMap::new();
1326 pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1327 let ident = path1.node;
1328 let variable_ty = node_id_type(bcx, p_id);
1329 let llvariable_ty = type_of::type_of(ccx, variable_ty);
1330 let tcx = bcx.tcx();
1331 let param_env = ty::empty_parameter_environment();
1337 if !ty::type_moves_by_default(tcx,
1339 ¶m_env) || reassigned => {
1340 llmatch = alloca_no_lifetime(bcx,
1341 llvariable_ty.ptr_to(),
1343 trmode = TrByCopy(alloca_no_lifetime(bcx,
1345 bcx.ident(ident).as_slice()));
1347 ast::BindByValue(_) => {
1348 // in this case, the final type of the variable will be T,
1349 // but during matching we need to store a *T as explained
1351 llmatch = alloca_no_lifetime(bcx,
1352 llvariable_ty.ptr_to(),
1353 bcx.ident(ident).as_slice());
1356 ast::BindByRef(_) => {
1357 llmatch = alloca_no_lifetime(bcx,
1359 bcx.ident(ident).as_slice());
1363 bindings_map.insert(ident, BindingInfo {
1371 return bindings_map;
1374 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1375 match_id: ast::NodeId,
1376 discr_expr: &ast::Expr,
1378 dest: Dest) -> Block<'blk, 'tcx> {
1379 let _icx = push_ctxt("match::trans_match_inner");
1380 let fcx = scope_cx.fcx;
1381 let mut bcx = scope_cx;
1382 let tcx = bcx.tcx();
1384 let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1386 if bcx.unreachable.get() {
1390 let t = node_id_type(bcx, discr_expr.id);
1391 let chk = if ty::type_is_empty(tcx, t) {
1397 let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1398 bodycx: fcx.new_id_block("case_body", arm.body.id),
1400 bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1403 let mut static_inliner = StaticInliner::new(scope_cx.tcx());
1404 let arm_pats: Vec<Vec<P<ast::Pat>>> = arm_datas.iter().map(|arm_data| {
1405 arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1407 let mut matches = Vec::new();
1408 for (arm_data, pats) in arm_datas.iter().zip(arm_pats.iter()) {
1409 matches.extend(pats.iter().map(|p| Match {
1412 bound_ptrs: Vec::new(),
1416 // `compile_submatch` works one column of arm patterns a time and
1417 // then peels that column off. So as we progress, it may become
1418 // impossible to tell whether we have a genuine default arm, i.e.
1419 // `_ => foo` or not. Sometimes it is important to know that in order
1420 // to decide whether moving on to the next condition or falling back
1421 // to the default arm.
1422 let has_default = arms.last().map_or(false, |arm| {
1424 && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1427 compile_submatch(bcx, matches.as_slice(), &[discr_datum.val], &chk, has_default);
1429 let mut arm_cxs = Vec::new();
1430 for arm_data in arm_datas.iter() {
1431 let mut bcx = arm_data.bodycx;
1433 // insert bindings into the lllocals map and add cleanups
1434 let cs = fcx.push_custom_cleanup_scope();
1435 bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1436 bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1437 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1441 bcx = scope_cx.fcx.join_blocks(match_id, arm_cxs.as_slice());
1445 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1446 /// <opt_init_expr>`.
1447 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1449 -> Block<'blk, 'tcx> {
1450 let _icx = push_ctxt("match::store_local");
1452 let tcx = bcx.tcx();
1453 let pat = &*local.pat;
1455 fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1457 -> Block<'blk, 'tcx> {
1458 // create dummy memory for the variables if we have no
1459 // value to store into them immediately
1460 let tcx = bcx.tcx();
1461 pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1462 let scope = cleanup::var_scope(tcx, p_id);
1463 bcx = mk_binding_alloca(
1464 bcx, p_id, &path1.node, scope, (),
1465 |(), bcx, llval, ty| { zero_mem(bcx, llval, ty); bcx });
1471 Some(ref init_expr) => {
1472 // Optimize the "let x = expr" case. This just writes
1473 // the result of evaluating `expr` directly into the alloca
1474 // for `x`. Often the general path results in similar or the
1475 // same code post-optimization, but not always. In particular,
1476 // in unsafe code, you can have expressions like
1478 // let x = intrinsics::uninit();
1480 // In such cases, the more general path is unsafe, because
1481 // it assumes it is matching against a valid value.
1482 match simple_identifier(&*pat) {
1484 let var_scope = cleanup::var_scope(tcx, local.id);
1485 return mk_binding_alloca(
1486 bcx, pat.id, ident, var_scope, (),
1487 |(), bcx, v, _| expr::trans_into(bcx, &**init_expr,
1496 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1497 if bcx.sess().asm_comments() {
1498 add_comment(bcx, "creating zeroable ref llval");
1500 let var_scope = cleanup::var_scope(tcx, local.id);
1501 bind_irrefutable_pat(bcx, pat, init_datum.val, var_scope)
1504 create_dummy_locals(bcx, pat)
1509 /// Generates code for argument patterns like `fn foo(<pat>: T)`.
1510 /// Creates entries in the `lllocals` map for each of the bindings
1515 /// - `pat` is the argument pattern
1516 /// - `llval` is a pointer to the argument value (in other words,
1517 /// if the argument type is `T`, then `llval` is a `T*`). In some
1518 /// cases, this code may zero out the memory `llval` points at.
1519 pub fn store_arg<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1521 arg: Datum<'tcx, Rvalue>,
1522 arg_scope: cleanup::ScopeId)
1523 -> Block<'blk, 'tcx> {
1524 let _icx = push_ctxt("match::store_arg");
1526 match simple_identifier(&*pat) {
1528 // Generate nicer LLVM for the common case of fn a pattern
1530 let arg_ty = node_id_type(bcx, pat.id);
1531 if type_of::arg_is_indirect(bcx.ccx(), arg_ty)
1532 && bcx.sess().opts.debuginfo != FullDebugInfo {
1533 // Don't copy an indirect argument to an alloca, the caller
1534 // already put it in a temporary alloca and gave it up, unless
1535 // we emit extra-debug-info, which requires local allocas :(.
1536 let arg_val = arg.add_clean(bcx.fcx, arg_scope);
1537 bcx.fcx.lllocals.borrow_mut()
1538 .insert(pat.id, Datum::new(arg_val, arg_ty, Lvalue));
1542 bcx, pat.id, ident, arg_scope, arg,
1543 |arg, bcx, llval, _| arg.store_to(bcx, llval))
1548 // General path. Copy out the values that are used in the
1550 let arg = unpack_datum!(
1551 bcx, arg.to_lvalue_datum_in_scope(bcx, "__arg", arg_scope));
1552 bind_irrefutable_pat(bcx, pat, arg.val, arg_scope)
1557 /// Generates code for the pattern binding in a `for` loop like
1558 /// `for <pat> in <expr> { ... }`.
1559 pub fn store_for_loop_binding<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1562 body_scope: cleanup::ScopeId)
1563 -> Block<'blk, 'tcx> {
1564 let _icx = push_ctxt("match::store_for_loop_binding");
1566 if simple_identifier(&*pat).is_some() {
1567 // Generate nicer LLVM for the common case of a `for` loop pattern
1568 // like `for x in blahblah { ... }`.
1569 let binding_type = node_id_type(bcx, pat.id);
1570 bcx.fcx.lllocals.borrow_mut().insert(pat.id,
1577 // General path. Copy out the values that are used in the pattern.
1578 bind_irrefutable_pat(bcx, pat, llvalue, body_scope)
1581 fn mk_binding_alloca<'blk, 'tcx, A>(bcx: Block<'blk, 'tcx>,
1584 cleanup_scope: cleanup::ScopeId,
1586 populate: |A, Block<'blk, 'tcx>, ValueRef, Ty<'tcx>|
1587 -> Block<'blk, 'tcx>)
1588 -> Block<'blk, 'tcx> {
1589 let var_ty = node_id_type(bcx, p_id);
1591 // Allocate memory on stack for the binding.
1592 let llval = alloc_ty(bcx, var_ty, bcx.ident(*ident).as_slice());
1594 // Subtle: be sure that we *populate* the memory *before*
1595 // we schedule the cleanup.
1596 let bcx = populate(arg, bcx, llval, var_ty);
1597 bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1598 bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
1600 // Now that memory is initialized and has cleanup scheduled,
1601 // create the datum and insert into the local variable map.
1602 let datum = Datum::new(llval, var_ty, Lvalue);
1603 bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1607 /// A simple version of the pattern matching code that only handles
1608 /// irrefutable patterns. This is used in let/argument patterns,
1609 /// not in match statements. Unifying this code with the code above
1610 /// sounds nice, but in practice it produces very inefficient code,
1611 /// since the match code is so much more general. In most cases,
1612 /// LLVM is able to optimize the code, but it causes longer compile
1613 /// times and makes the generated code nigh impossible to read.
1616 /// - bcx: starting basic block context
1617 /// - pat: the irrefutable pattern being matched.
1618 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1619 fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1622 cleanup_scope: cleanup::ScopeId)
1623 -> Block<'blk, 'tcx> {
1624 debug!("bind_irrefutable_pat(bcx={}, pat={})",
1626 pat.repr(bcx.tcx()));
1628 if bcx.sess().asm_comments() {
1629 add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
1630 pat.repr(bcx.tcx())).as_slice());
1633 let _indenter = indenter();
1635 let _icx = push_ctxt("match::bind_irrefutable_pat");
1637 let tcx = bcx.tcx();
1638 let ccx = bcx.ccx();
1640 ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1641 if pat_is_binding(&tcx.def_map, &*pat) {
1642 // Allocate the stack slot where the value of this
1643 // binding will live and place it into the appropriate
1645 bcx = mk_binding_alloca(
1646 bcx, pat.id, &path1.node, cleanup_scope, (),
1647 |(), bcx, llval, ty| {
1648 match pat_binding_mode {
1649 ast::BindByValue(_) => {
1650 // By value binding: move the value that `val`
1651 // points at into the binding's stack slot.
1652 let d = Datum::new(val, ty, Lvalue);
1653 d.store_to(bcx, llval)
1656 ast::BindByRef(_) => {
1657 // By ref binding: the value of the variable
1658 // is the pointer `val` itself.
1659 Store(bcx, val, llval);
1666 for inner_pat in inner.iter() {
1667 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1670 ast::PatEnum(_, ref sub_pats) => {
1671 let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).cloned();
1673 Some(def::DefVariant(enum_id, var_id, _)) => {
1674 let repr = adt::represent_node(bcx, pat.id);
1675 let vinfo = ty::enum_variant_with_id(ccx.tcx(),
1678 let args = extract_variant_args(bcx,
1682 for sub_pat in sub_pats.iter() {
1683 for (i, &argval) in args.vals.iter().enumerate() {
1684 bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
1685 argval, cleanup_scope);
1689 Some(def::DefStruct(..)) => {
1692 // This is a unit-like struct. Nothing to do here.
1694 Some(ref elems) => {
1695 // This is the tuple struct case.
1696 let repr = adt::represent_node(bcx, pat.id);
1697 for (i, elem) in elems.iter().enumerate() {
1698 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1700 bcx = bind_irrefutable_pat(bcx, &**elem,
1701 fldptr, cleanup_scope);
1707 // Nothing to do here.
1711 ast::PatStruct(_, ref fields, _) => {
1712 let tcx = bcx.tcx();
1713 let pat_ty = node_id_type(bcx, pat.id);
1714 let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1715 expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
1716 for f in fields.iter() {
1717 let ix = ty::field_idx_strict(tcx, f.node.ident.name, field_tys);
1718 let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val,
1720 bcx = bind_irrefutable_pat(bcx, &*f.node.pat, fldptr, cleanup_scope);
1724 ast::PatTup(ref elems) => {
1725 let repr = adt::represent_node(bcx, pat.id);
1726 for (i, elem) in elems.iter().enumerate() {
1727 let fldptr = adt::trans_field_ptr(bcx, &*repr, val, 0, i);
1728 bcx = bind_irrefutable_pat(bcx, &**elem, fldptr, cleanup_scope);
1731 ast::PatBox(ref inner) => {
1732 let llbox = Load(bcx, val);
1733 bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
1735 ast::PatRegion(ref inner) => {
1736 let loaded_val = Load(bcx, val);
1737 bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
1739 ast::PatVec(ref before, ref slice, ref after) => {
1740 let pat_ty = node_id_type(bcx, pat.id);
1741 let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1744 extracted.vals.insert(
1746 bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1753 .chain(slice.iter())
1754 .chain(after.iter())
1755 .zip(extracted.vals.into_iter())
1756 .fold(bcx, |bcx, (inner, elem)|
1757 bind_irrefutable_pat(bcx, &**inner, elem, cleanup_scope)
1760 ast::PatMac(..) => {
1761 bcx.sess().span_bug(pat.span, "unexpanded macro");
1763 ast::PatWild(_) | ast::PatLit(_) | ast::PatRange(_, _) => ()