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(usize, usize) }
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 `1`
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;
196 use middle::def::{self, DefMap};
197 use middle::expr_use_visitor as euv;
199 use middle::lang_items::StrEqFnLangItem;
200 use middle::mem_categorization as mc;
201 use middle::pat_util::*;
204 use trans::build::{AddCase, And, Br, CondBr, GEPi, InBoundsGEP, Load, PointerCast};
205 use trans::build::{Not, Store, Sub, add_comment};
208 use trans::cleanup::{self, CleanupMethods};
209 use trans::common::*;
212 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
213 use trans::expr::{self, Dest};
214 use trans::monomorphize;
217 use middle::ty::{self, Ty};
218 use session::config::NoDebugInfo;
219 use util::common::indenter;
220 use util::nodemap::FnvHashMap;
224 use std::cmp::Ordering;
228 use syntax::ast::{DUMMY_NODE_ID, NodeId};
229 use syntax::codemap::Span;
230 use syntax::fold::Folder;
233 #[derive(Copy, Clone, Debug)]
234 struct ConstantExpr<'a>(&'a ast::Expr);
236 impl<'a> ConstantExpr<'a> {
237 fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
238 match const_eval::compare_lit_exprs(tcx, self.0, other.0, None,
239 |id| {tcx.node_id_item_substs(id).substs}) {
240 Some(result) => result == Ordering::Equal,
241 None => panic!("compare_list_exprs: type mismatch"),
246 // An option identifying a branch (either a literal, an enum variant or a range)
249 ConstantValue(ConstantExpr<'a>, DebugLoc),
250 ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>, DebugLoc),
251 Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId, DebugLoc),
252 SliceLengthEqual(usize, DebugLoc),
253 SliceLengthGreaterOrEqual(/* prefix length */ usize,
254 /* suffix length */ usize,
258 impl<'a, 'tcx> Opt<'a, 'tcx> {
259 fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
260 match (self, other) {
261 (&ConstantValue(a, _), &ConstantValue(b, _)) => a.eq(b, tcx),
262 (&ConstantRange(a1, a2, _), &ConstantRange(b1, b2, _)) => {
263 a1.eq(b1, tcx) && a2.eq(b2, tcx)
265 (&Variant(a_disr, ref a_repr, a_def, _),
266 &Variant(b_disr, ref b_repr, b_def, _)) => {
267 a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
269 (&SliceLengthEqual(a, _), &SliceLengthEqual(b, _)) => a == b,
270 (&SliceLengthGreaterOrEqual(a1, a2, _),
271 &SliceLengthGreaterOrEqual(b1, b2, _)) => {
278 fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
279 let _icx = push_ctxt("match::trans_opt");
282 ConstantValue(ConstantExpr(lit_expr), _) => {
283 let lit_ty = bcx.tcx().node_id_to_type(lit_expr.id);
284 let (llval, _) = consts::const_expr(ccx, &*lit_expr, bcx.fcx.param_substs, None);
285 let lit_datum = immediate_rvalue(llval, lit_ty);
286 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
287 SingleResult(Result::new(bcx, lit_datum.val))
289 ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2), _) => {
290 let (l1, _) = consts::const_expr(ccx, &**l1, bcx.fcx.param_substs, None);
291 let (l2, _) = consts::const_expr(ccx, &**l2, bcx.fcx.param_substs, None);
292 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
294 Variant(disr_val, ref repr, _, _) => {
295 adt::trans_case(bcx, &**repr, disr_val)
297 SliceLengthEqual(length, _) => {
298 SingleResult(Result::new(bcx, C_uint(ccx, length)))
300 SliceLengthGreaterOrEqual(prefix, suffix, _) => {
301 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
306 fn debug_loc(&self) -> DebugLoc {
308 ConstantValue(_,debug_loc) |
309 ConstantRange(_, _, debug_loc) |
310 Variant(_, _, _, debug_loc) |
311 SliceLengthEqual(_, debug_loc) |
312 SliceLengthGreaterOrEqual(_, _, debug_loc) => debug_loc
317 #[derive(Copy, Clone, PartialEq)]
318 pub enum BranchKind {
326 pub enum OptResult<'blk, 'tcx: 'blk> {
327 SingleResult(Result<'blk, 'tcx>),
328 RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
329 LowerBound(Result<'blk, 'tcx>)
332 #[derive(Clone, Copy, PartialEq)]
333 pub enum TransBindingMode {
334 TrByCopy(/* llbinding */ ValueRef),
339 /// Information about a pattern binding:
340 /// - `llmatch` is a pointer to a stack slot. The stack slot contains a
341 /// pointer into the value being matched. Hence, llmatch has type `T**`
342 /// where `T` is the value being matched.
343 /// - `trmode` is the trans binding mode
344 /// - `id` is the node id of the binding
345 /// - `ty` is the Rust type of the binding
346 #[derive(Clone, Copy)]
347 pub struct BindingInfo<'tcx> {
348 pub llmatch: ValueRef,
349 pub trmode: TransBindingMode,
355 type BindingsMap<'tcx> = FnvHashMap<ast::Ident, BindingInfo<'tcx>>;
357 struct ArmData<'p, 'blk, 'tcx: 'blk> {
358 bodycx: Block<'blk, 'tcx>,
360 bindings_map: BindingsMap<'tcx>
363 /// Info about Match.
364 /// If all `pats` are matched then arm `data` will be executed.
365 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
366 /// these pointers are stored in llmatch variables just before executing `data` arm.
367 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
368 pats: Vec<&'p ast::Pat>,
369 data: &'a ArmData<'p, 'blk, 'tcx>,
370 bound_ptrs: Vec<(ast::Ident, ValueRef)>,
371 // Thread along renamings done by the check_match::StaticInliner, so we can
372 // map back to original NodeIds
373 pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>>
376 impl<'a, 'p, 'blk, 'tcx> fmt::Debug for Match<'a, 'p, 'blk, 'tcx> {
377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378 if ppaux::verbose() {
379 // for many programs, this just take too long to serialize
380 write!(f, "{:?}", self.pats)
382 write!(f, "{} pats", self.pats.len())
387 fn has_nested_bindings(m: &[Match], col: usize) -> bool {
389 match br.pats[col].node {
390 ast::PatIdent(_, _, Some(_)) => return true,
397 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
398 m: &[Match<'a, 'p, 'blk, 'tcx>],
401 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
402 debug!("expand_nested_bindings(bcx={}, m={:?}, col={}, val={})",
406 bcx.val_to_string(val));
407 let _indenter = indenter();
410 let mut bound_ptrs = br.bound_ptrs.clone();
411 let mut pat = br.pats[col];
413 pat = match pat.node {
414 ast::PatIdent(_, ref path, Some(ref inner)) => {
415 bound_ptrs.push((path.node, val));
422 let mut pats = br.pats.clone();
427 bound_ptrs: bound_ptrs,
428 pat_renaming_map: br.pat_renaming_map,
433 fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
435 m: &[Match<'a, 'p, 'blk, 'tcx>],
439 -> Vec<Match<'a, 'p, 'blk, 'tcx>> where
440 F: FnMut(&[&'p ast::Pat]) -> Option<Vec<&'p ast::Pat>>,
442 debug!("enter_match(bcx={}, m={:?}, col={}, val={})",
446 bcx.val_to_string(val));
447 let _indenter = indenter();
449 m.iter().filter_map(|br| {
450 e(&br.pats).map(|pats| {
451 let this = br.pats[col];
452 let mut bound_ptrs = br.bound_ptrs.clone();
454 ast::PatIdent(_, ref path, None) => {
455 if pat_is_binding(dm, &*this) {
456 bound_ptrs.push((path.node, val));
459 ast::PatVec(ref before, Some(ref slice), ref after) => {
460 if let ast::PatIdent(_, ref path, None) = slice.node {
461 let subslice_val = bind_subslice_pat(
463 before.len(), after.len());
464 bound_ptrs.push((path.node, subslice_val));
472 bound_ptrs: bound_ptrs,
473 pat_renaming_map: br.pat_renaming_map,
479 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
481 m: &[Match<'a, 'p, 'blk, 'tcx>],
484 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
485 debug!("enter_default(bcx={}, m={:?}, col={}, val={})",
489 bcx.val_to_string(val));
490 let _indenter = indenter();
492 // Collect all of the matches that can match against anything.
493 enter_match(bcx, dm, m, col, val, |pats| {
494 if pat_is_binding_or_wild(dm, &*pats[col]) {
495 let mut r = pats[..col].to_vec();
496 r.push_all(&pats[col + 1..]);
504 // <pcwalton> nmatsakis: what does enter_opt do?
505 // <pcwalton> in trans/match
506 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
507 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
508 // patterns as needed
509 // <nmatsakis> yeah, at some point I kind of achieved some level of
511 // <nmatsakis> anyhow, they adjust the patterns given that something of that
512 // kind has been found
513 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
515 // <nmatsakis> enter_match() kind of embodies the generic code
516 // <nmatsakis> it is provided with a function that tests each pattern to see
517 // if it might possibly apply and so forth
518 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
519 // <nmatsakis> then _ would be expanded to (_, _)
520 // <nmatsakis> one spot for each of the sub-patterns
521 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
523 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
524 // are infallible patterns
525 // <nmatsakis> so all patterns must either be records (resp. tuples) or
528 /// The above is now outdated in that enter_match() now takes a function that
529 /// takes the complete row of patterns rather than just the first one.
530 /// Also, most of the enter_() family functions have been unified with
531 /// the check_match specialization step.
532 fn enter_opt<'a, 'p, 'blk, 'tcx>(
533 bcx: Block<'blk, 'tcx>,
536 m: &[Match<'a, 'p, 'blk, 'tcx>],
541 -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
542 debug!("enter_opt(bcx={}, m={:?}, opt={:?}, col={}, val={})",
547 bcx.val_to_string(val));
548 let _indenter = indenter();
550 let ctor = match opt {
551 &ConstantValue(ConstantExpr(expr), _) => check_match::ConstantValue(
552 const_eval::eval_const_expr(bcx.tcx(), &*expr)
554 &ConstantRange(ConstantExpr(lo), ConstantExpr(hi), _) => check_match::ConstantRange(
555 const_eval::eval_const_expr(bcx.tcx(), &*lo),
556 const_eval::eval_const_expr(bcx.tcx(), &*hi)
558 &SliceLengthEqual(n, _) =>
559 check_match::Slice(n),
560 &SliceLengthGreaterOrEqual(before, after, _) =>
561 check_match::SliceWithSubslice(before, after),
562 &Variant(_, _, def_id, _) =>
563 check_match::Constructor::Variant(def_id)
566 let param_env = bcx.tcx().empty_parameter_environment();
567 let mcx = check_match::MatchCheckCtxt {
569 param_env: param_env,
571 enter_match(bcx, dm, m, col, val, |pats|
572 check_match::specialize(&mcx, &pats[..], &ctor, col, variant_size)
576 // Returns the options in one column of matches. An option is something that
577 // needs to be conditionally matched at runtime; for example, the discriminant
578 // on a set of enum variants or a literal.
579 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
580 m: &[Match<'a, 'p, 'blk, 'tcx>],
582 -> Vec<Opt<'p, 'tcx>> {
585 let mut found: Vec<Opt> = vec![];
587 let cur = br.pats[col];
588 let debug_loc = match br.pat_renaming_map {
589 Some(pat_renaming_map) => {
590 match pat_renaming_map.get(&(cur.id, cur.span)) {
591 Some(&id) => DebugLoc::At(id, cur.span),
592 None => DebugLoc::At(cur.id, cur.span),
595 None => DebugLoc::None
598 let opt = match cur.node {
599 ast::PatLit(ref l) => {
600 ConstantValue(ConstantExpr(&**l), debug_loc)
602 ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
603 // This is either an enum variant or a variable binding.
604 let opt_def = tcx.def_map.borrow().get(&cur.id).map(|d| d.full_def());
606 Some(def::DefVariant(enum_id, var_id, _)) => {
607 let variant = tcx.enum_variant_with_id(enum_id, var_id);
608 Variant(variant.disr_val,
609 adt::represent_node(bcx, cur.id),
616 ast::PatRange(ref l1, ref l2) => {
617 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2), debug_loc)
619 ast::PatVec(ref before, None, ref after) => {
620 SliceLengthEqual(before.len() + after.len(), debug_loc)
622 ast::PatVec(ref before, Some(_), ref after) => {
623 SliceLengthGreaterOrEqual(before.len(), after.len(), debug_loc)
628 if !found.iter().any(|x| x.eq(&opt, tcx)) {
635 struct ExtractedBlock<'blk, 'tcx: 'blk> {
637 bcx: Block<'blk, 'tcx>,
640 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
641 repr: &adt::Repr<'tcx>,
644 -> ExtractedBlock<'blk, 'tcx> {
645 let _icx = push_ctxt("match::extract_variant_args");
646 let args = (0..adt::num_args(repr, disr_val)).map(|i| {
647 adt::trans_field_ptr(bcx, repr, val, disr_val, i)
650 ExtractedBlock { vals: args, bcx: bcx }
653 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
654 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
655 fn match_datum<'tcx>(val: ValueRef, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
656 Datum::new(val, left_ty, Lvalue)
659 fn bind_subslice_pat(bcx: Block,
663 offset_right: usize) -> ValueRef {
664 let _icx = push_ctxt("match::bind_subslice_pat");
665 let vec_ty = node_id_type(bcx, pat_id);
666 let vec_ty_contents = match vec_ty.sty {
668 ty::TyRef(_, mt) | ty::TyRawPtr(mt) => mt.ty,
671 let unit_ty = vec_ty_contents.sequence_element_type(bcx.tcx());
672 let vec_datum = match_datum(val, vec_ty);
673 let (base, len) = vec_datum.get_vec_base_and_len(bcx);
675 let slice_begin = InBoundsGEP(bcx, base, &[C_uint(bcx.ccx(), offset_left)]);
676 let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
677 let slice_len = Sub(bcx, len, slice_len_offset, DebugLoc::None);
678 let slice_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic),
679 bcx.tcx().mk_slice(unit_ty));
680 let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
681 Store(bcx, slice_begin,
682 GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
683 Store(bcx, slice_len, GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
687 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
692 -> ExtractedBlock<'blk, 'tcx> {
693 let _icx = push_ctxt("match::extract_vec_elems");
694 let vec_datum = match_datum(val, left_ty);
695 let (base, len) = vec_datum.get_vec_base_and_len(bcx);
696 let mut elems = vec![];
697 elems.extend((0..before).map(|i| GEPi(bcx, base, &[i])));
698 elems.extend((0..after).rev().map(|i| {
699 InBoundsGEP(bcx, base, &[
700 Sub(bcx, len, C_uint(bcx.ccx(), i + 1), DebugLoc::None)
703 ExtractedBlock { vals: elems, bcx: bcx }
706 // Macro for deciding whether any of the remaining matches fit a given kind of
707 // pattern. Note that, because the macro is well-typed, either ALL of the
708 // matches should fit that sort of pattern or NONE (however, some of the
709 // matches may be wildcards like _ or identifiers).
710 macro_rules! any_pat {
711 ($m:expr, $col:expr, $pattern:pat) => (
712 ($m).iter().any(|br| {
713 match br.pats[$col].node {
721 fn any_uniq_pat(m: &[Match], col: usize) -> bool {
722 any_pat!(m, col, ast::PatBox(_))
725 fn any_region_pat(m: &[Match], col: usize) -> bool {
726 any_pat!(m, col, ast::PatRegion(..))
729 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: usize) -> bool {
731 let pat = br.pats[col];
733 ast::PatTup(_) => true,
734 ast::PatStruct(..) => {
735 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
736 Some(def::DefVariant(..)) => false,
740 ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
741 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
742 Some(def::DefStruct(..)) => true,
751 /// What to do when the pattern match fails.
752 enum FailureHandler {
754 JumpToBasicBlock(BasicBlockRef),
758 impl FailureHandler {
759 fn is_fallible(&self) -> bool {
766 fn is_infallible(&self) -> bool {
770 fn handle_fail(&self, bcx: Block) {
773 panic!("attempted to panic in a non-panicking panic handler!"),
774 JumpToBasicBlock(basic_block) =>
775 Br(bcx, basic_block, DebugLoc::None),
777 build::Unreachable(bcx)
782 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<usize> {
783 fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> usize {
785 ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
786 _ if pat_is_refutable(def_map, pat) => 1,
791 let column_score = |m: &[Match], col: usize| -> usize {
792 let total_score = m.iter()
793 .map(|row| row.pats[col])
794 .map(|pat| pat_score(def_map, pat))
797 // Irrefutable columns always go first, they'd only be duplicated in the branches.
798 if total_score == 0 {
805 let column_contains_any_nonwild_patterns = |&col: &usize| -> bool {
806 m.iter().any(|row| match row.pats[col].node {
807 ast::PatWild(_) => false,
813 .filter(column_contains_any_nonwild_patterns)
814 .map(|col| (col, column_score(m, col)))
815 .max_by(|&(_, score)| score)
819 // Compiles a comparison between two things.
820 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
825 -> Result<'blk, 'tcx> {
826 fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
831 -> Result<'blk, 'tcx> {
832 let did = langcall(cx,
834 &format!("comparison of `{}`", rhs_t),
836 let lhs_data = Load(cx, expr::get_dataptr(cx, lhs));
837 let lhs_len = Load(cx, expr::get_len(cx, lhs));
838 let rhs_data = Load(cx, expr::get_dataptr(cx, rhs));
839 let rhs_len = Load(cx, expr::get_len(cx, rhs));
840 callee::trans_lang_call(cx, did, &[lhs_data, lhs_len, rhs_data, rhs_len], None, debug_loc)
843 let _icx = push_ctxt("compare_values");
844 if rhs_t.is_scalar() {
845 let cmp = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq, debug_loc);
846 return Result::new(cx, cmp);
850 ty::TyRef(_, mt) => match mt.ty.sty {
851 ty::TyStr => compare_str(cx, lhs, rhs, rhs_t, debug_loc),
852 ty::TyArray(ty, _) | ty::TySlice(ty) => match ty.sty {
853 ty::TyUint(ast::TyU8) => {
854 // NOTE: cast &[u8] and &[u8; N] to &str and abuse the str_eq lang item,
855 // which calls memcmp().
856 let pat_len = val_ty(rhs).element_type().array_length();
857 let ty_str_slice = cx.tcx().mk_static_str();
859 let rhs_str = alloc_ty(cx, ty_str_slice, "rhs_str");
860 Store(cx, GEPi(cx, rhs, &[0, 0]), expr::get_dataptr(cx, rhs_str));
861 Store(cx, C_uint(cx.ccx(), pat_len), expr::get_len(cx, rhs_str));
864 if val_ty(lhs) == val_ty(rhs) {
865 // Both the discriminant and the pattern are thin pointers
866 lhs_str = alloc_ty(cx, ty_str_slice, "lhs_str");
867 Store(cx, GEPi(cx, lhs, &[0, 0]), expr::get_dataptr(cx, lhs_str));
868 Store(cx, C_uint(cx.ccx(), pat_len), expr::get_len(cx, lhs_str));
871 // The discriminant is a fat pointer
872 let llty_str_slice = type_of::type_of(cx.ccx(), ty_str_slice).ptr_to();
873 lhs_str = PointerCast(cx, lhs, llty_str_slice);
876 compare_str(cx, lhs_str, rhs_str, rhs_t, debug_loc)
878 _ => cx.sess().bug("only byte strings supported in compare_values"),
880 _ => cx.sess().bug("only string and byte strings supported in compare_values"),
882 _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
886 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
887 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
888 bindings_map: &BindingsMap<'tcx>,
889 cs: Option<cleanup::ScopeId>)
890 -> Block<'blk, 'tcx> {
891 for (&ident, &binding_info) in bindings_map {
892 let llval = match binding_info.trmode {
893 // By value mut binding for a copy type: load from the ptr
894 // into the matched value and copy to our alloca
895 TrByCopy(llbinding) => {
896 let llval = Load(bcx, binding_info.llmatch);
897 let datum = Datum::new(llval, binding_info.ty, Lvalue);
898 call_lifetime_start(bcx, llbinding);
899 bcx = datum.store_to(bcx, llbinding);
900 if let Some(cs) = cs {
901 bcx.fcx.schedule_lifetime_end(cs, llbinding);
907 // By value move bindings: load from the ptr into the matched value
908 TrByMove => Load(bcx, binding_info.llmatch),
910 // By ref binding: use the ptr into the matched value
911 TrByRef => binding_info.llmatch
914 let datum = Datum::new(llval, binding_info.ty, Lvalue);
915 if let Some(cs) = cs {
916 bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
917 bcx.fcx.schedule_drop_and_fill_mem(cs, llval, binding_info.ty);
920 debug!("binding {} to {}", binding_info.id, bcx.val_to_string(llval));
921 bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
922 debuginfo::create_match_binding_metadata(bcx, ident.name, binding_info);
927 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
928 guard_expr: &ast::Expr,
929 data: &ArmData<'p, 'blk, 'tcx>,
930 m: &[Match<'a, 'p, 'blk, 'tcx>],
932 chk: &FailureHandler,
933 has_genuine_default: bool)
934 -> Block<'blk, 'tcx> {
935 debug!("compile_guard(bcx={}, guard_expr={:?}, m={:?}, vals=[{}])",
939 vals.iter().map(|v| bcx.val_to_string(*v)).collect::<Vec<_>>().join(", "));
940 let _indenter = indenter();
942 let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
944 let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
945 let val = val.to_llbool(bcx);
947 for (_, &binding_info) in &data.bindings_map {
948 if let TrByCopy(llbinding) = binding_info.trmode {
949 call_lifetime_end(bcx, llbinding);
953 for (_, &binding_info) in &data.bindings_map {
954 bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
957 with_cond(bcx, Not(bcx, val, guard_expr.debug_loc()), |bcx| {
958 for (_, &binding_info) in &data.bindings_map {
959 call_lifetime_end(bcx, binding_info.llmatch);
962 // If the default arm is the only one left, move on to the next
963 // condition explicitly rather than (possibly) falling back to
965 &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
966 chk.handle_fail(bcx);
969 compile_submatch(bcx, m, vals, chk, has_genuine_default);
976 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
977 m: &[Match<'a, 'p, 'blk, 'tcx>],
979 chk: &FailureHandler,
980 has_genuine_default: bool) {
981 debug!("compile_submatch(bcx={}, m={:?}, vals=[{}])",
984 vals.iter().map(|v| bcx.val_to_string(*v)).collect::<Vec<_>>().join(", "));
985 let _indenter = indenter();
986 let _icx = push_ctxt("match::compile_submatch");
989 if chk.is_fallible() {
990 chk.handle_fail(bcx);
996 let def_map = &tcx.def_map;
997 match pick_column_to_specialize(def_map, m) {
1000 if has_nested_bindings(m, col) {
1001 let expanded = expand_nested_bindings(bcx, m, col, val);
1002 compile_submatch_continue(bcx,
1008 has_genuine_default)
1010 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
1014 let data = &m[0].data;
1015 for &(ref ident, ref value_ptr) in &m[0].bound_ptrs {
1016 let binfo = *data.bindings_map.get(ident).unwrap();
1017 call_lifetime_start(bcx, binfo.llmatch);
1018 if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) {
1019 expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch);
1022 Store(bcx, *value_ptr, binfo.llmatch);
1025 match data.arm.guard {
1026 Some(ref guard_expr) => {
1027 bcx = compile_guard(bcx,
1033 has_genuine_default);
1037 Br(bcx, data.bodycx.llbb, DebugLoc::None);
1042 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1043 m: &[Match<'a, 'p, 'blk, 'tcx>],
1045 chk: &FailureHandler,
1048 has_genuine_default: bool) {
1050 let tcx = bcx.tcx();
1051 let dm = &tcx.def_map;
1053 let mut vals_left = vals[0..col].to_vec();
1054 vals_left.push_all(&vals[col + 1..]);
1055 let ccx = bcx.fcx.ccx;
1057 // Find a real id (we're adding placeholder wildcard patterns, but
1058 // each column is guaranteed to have at least one real pattern)
1059 let pat_id = m.iter().map(|br| br.pats[col].id)
1060 .find(|&id| id != DUMMY_NODE_ID)
1061 .unwrap_or(DUMMY_NODE_ID);
1063 let left_ty = if pat_id == DUMMY_NODE_ID {
1066 node_id_type(bcx, pat_id)
1069 let mcx = check_match::MatchCheckCtxt {
1071 param_env: bcx.tcx().empty_parameter_environment(),
1073 let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1074 let repr = adt::represent_type(bcx.ccx(), left_ty);
1075 let arg_count = adt::num_args(&*repr, 0);
1076 let (arg_count, struct_val) = if type_is_sized(bcx.tcx(), left_ty) {
1079 // For an unsized ADT (i.e. DST struct), we need to treat
1080 // the last field specially: instead of simply passing a
1081 // ValueRef pointing to that field, as with all the others,
1082 // we skip it and instead construct a 'fat ptr' below.
1083 (arg_count - 1, Load(bcx, expr::get_dataptr(bcx, val)))
1085 let mut field_vals: Vec<ValueRef> = (0..arg_count).map(|ix|
1086 adt::trans_field_ptr(bcx, &*repr, struct_val, 0, ix)
1090 ty::TyStruct(def_id, substs) if !type_is_sized(bcx.tcx(), left_ty) => {
1091 // The last field is technically unsized but
1092 // since we can only ever match that field behind
1093 // a reference we construct a fat ptr here.
1094 let fields = bcx.tcx().lookup_struct_fields(def_id);
1095 let unsized_ty = fields.iter().last().map(|field| {
1096 let fty = bcx.tcx().lookup_field_type(def_id, field.id, substs);
1097 monomorphize::normalize_associated_type(bcx.tcx(), &fty)
1099 let llty = type_of::type_of(bcx.ccx(), unsized_ty);
1100 let scratch = alloca_no_lifetime(bcx, llty, "__struct_field_fat_ptr");
1101 let data = adt::trans_field_ptr(bcx, &*repr, struct_val, 0, arg_count);
1102 let len = Load(bcx, expr::get_len(bcx, val));
1103 Store(bcx, data, expr::get_dataptr(bcx, scratch));
1104 Store(bcx, len, expr::get_len(bcx, scratch));
1105 field_vals.push(scratch);
1110 } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1111 Some(vec!(Load(bcx, val)))
1114 ty::TyArray(_, n) => {
1115 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1122 Some(field_vals) => {
1123 let pats = enter_match(bcx, dm, m, col, val, |pats|
1124 check_match::specialize(&mcx, pats,
1125 &check_match::Single, col,
1128 let mut vals = field_vals;
1129 vals.push_all(&vals_left);
1130 compile_submatch(bcx, &pats, &vals, chk, has_genuine_default);
1136 // Decide what kind of branch we need
1137 let opts = get_branches(bcx, m, col);
1138 debug!("options={:?}", opts);
1139 let mut kind = NoBranch;
1140 let mut test_val = val;
1141 debug!("test_val={}", bcx.val_to_string(test_val));
1142 if !opts.is_empty() {
1144 ConstantValue(..) | ConstantRange(..) => {
1145 test_val = load_if_immediate(bcx, val, left_ty);
1146 kind = if left_ty.is_integral() {
1152 Variant(_, ref repr, _, _) => {
1153 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
1155 if let Some(tval) = val_opt { test_val = tval; }
1157 SliceLengthEqual(..) | SliceLengthGreaterOrEqual(..) => {
1158 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
1166 ConstantRange(..) => { kind = Compare; break },
1167 SliceLengthGreaterOrEqual(..) => { kind = CompareSliceLength; break },
1171 let else_cx = match kind {
1172 NoBranch | Single => bcx,
1173 _ => bcx.fcx.new_temp_block("match_else")
1175 let sw = if kind == Switch {
1176 build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1178 C_int(ccx, 0) // Placeholder for when not using a switch
1181 let defaults = enter_default(else_cx, dm, m, col, val);
1182 let exhaustive = chk.is_infallible() && defaults.is_empty();
1183 let len = opts.len();
1185 // Compile subtrees for each option
1186 for (i, opt) in opts.iter().enumerate() {
1187 // In some cases of range and vector pattern matching, we need to
1188 // override the failure case so that instead of failing, it proceeds
1189 // to try more matching. branch_chk, then, is the proper failure case
1190 // for the current conditional branch.
1191 let mut branch_chk = None;
1192 let mut opt_cx = else_cx;
1193 let debug_loc = opt.debug_loc();
1195 if !exhaustive || i + 1 < len {
1196 opt_cx = bcx.fcx.new_temp_block("match_case");
1198 Single => Br(bcx, opt_cx.llbb, debug_loc),
1200 match opt.trans(bcx) {
1201 SingleResult(r) => {
1202 AddCase(sw, r.val, opt_cx.llbb);
1207 "in compile_submatch, expected \
1208 opt.trans() to return a SingleResult")
1212 Compare | CompareSliceLength => {
1213 let t = if kind == Compare {
1216 tcx.types.usize // vector length
1218 let Result { bcx: after_cx, val: matches } = {
1219 match opt.trans(bcx) {
1220 SingleResult(Result { bcx, val }) => {
1221 compare_values(bcx, test_val, val, t, debug_loc)
1223 RangeResult(Result { val: vbegin, .. },
1224 Result { bcx, val: vend }) => {
1225 let llge = compare_scalar_types(bcx, test_val, vbegin,
1226 t, ast::BiGe, debug_loc);
1227 let llle = compare_scalar_types(bcx, test_val, vend,
1228 t, ast::BiLe, debug_loc);
1229 Result::new(bcx, And(bcx, llge, llle, DebugLoc::None))
1231 LowerBound(Result { bcx, val }) => {
1232 Result::new(bcx, compare_scalar_types(bcx, test_val,
1238 bcx = fcx.new_temp_block("compare_next");
1240 // If none of the sub-cases match, and the current condition
1241 // is guarded or has multiple patterns, move on to the next
1242 // condition, if there is any, rather than falling back to
1244 let guarded = m[i].data.arm.guard.is_some();
1245 let multi_pats = m[i].pats.len() > 1;
1246 if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1247 branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1249 CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb, debug_loc);
1253 } else if kind == Compare || kind == CompareSliceLength {
1254 Br(bcx, else_cx.llbb, debug_loc);
1258 let mut unpacked = Vec::new();
1260 Variant(disr_val, ref repr, _, _) => {
1261 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1262 extract_variant_args(opt_cx, &**repr, disr_val, val);
1263 size = argvals.len();
1267 SliceLengthEqual(len, _) => {
1268 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1269 size = args.vals.len();
1270 unpacked = args.vals.clone();
1273 SliceLengthGreaterOrEqual(before, after, _) => {
1274 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1275 size = args.vals.len();
1276 unpacked = args.vals.clone();
1279 ConstantValue(..) | ConstantRange(..) => ()
1281 let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1282 let mut opt_vals = unpacked;
1283 opt_vals.push_all(&vals_left[..]);
1284 compile_submatch(opt_cx,
1287 branch_chk.as_ref().unwrap_or(chk),
1288 has_genuine_default);
1291 // Compile the fall-through case, if any
1292 if !exhaustive && kind != Single {
1293 if kind == Compare || kind == CompareSliceLength {
1294 Br(bcx, else_cx.llbb, DebugLoc::None);
1297 // If there is only one default arm left, move on to the next
1298 // condition explicitly rather than (eventually) falling back to
1299 // the last default arm.
1300 &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1301 chk.handle_fail(else_cx);
1304 compile_submatch(else_cx,
1308 has_genuine_default);
1314 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1315 match_expr: &ast::Expr,
1316 discr_expr: &ast::Expr,
1319 -> Block<'blk, 'tcx> {
1320 let _icx = push_ctxt("match::trans_match");
1321 trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1324 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1325 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1326 let (vid, field) = match discr.node {
1327 ast::ExprPath(..) => match bcx.def(discr.id) {
1328 def::DefLocal(vid) | def::DefUpvar(vid, _) => (vid, None),
1331 ast::ExprField(ref base, field) => {
1332 let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1333 Some(def::DefLocal(vid)) | Some(def::DefUpvar(vid, _)) => vid,
1336 (vid, Some(mc::NamedField(field.node.name)))
1338 ast::ExprTupField(ref base, field) => {
1339 let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1340 Some(def::DefLocal(vid)) | Some(def::DefUpvar(vid, _)) => vid,
1343 (vid, Some(mc::PositionalField(field.node)))
1348 let mut rc = ReassignmentChecker {
1354 let infcx = infer::normalizing_infer_ctxt(bcx.tcx(), &bcx.tcx().tables);
1355 let mut visitor = euv::ExprUseVisitor::new(&mut rc, &infcx);
1356 visitor.walk_expr(body);
1361 struct ReassignmentChecker {
1363 field: Option<mc::FieldName>,
1367 // Determine if the expression we're matching on is reassigned to within
1368 // the body of the match's arm.
1369 // We only care for the `mutate` callback since this check only matters
1370 // for cases where the matched value is moved.
1371 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1372 fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1373 fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1374 fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1375 fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1376 _: ty::BorrowKind, _: euv::LoanCause) {}
1377 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1379 fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1381 mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1382 mc::cat_local(vid) => self.reassigned |= self.node == vid,
1383 mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1384 match base_cmt.cat {
1385 mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1386 mc::cat_local(vid) => {
1387 self.reassigned |= self.node == vid && Some(field) == self.field
1397 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1398 discr: &ast::Expr, body: &ast::Expr)
1399 -> BindingsMap<'tcx> {
1400 // Create the bindings map, which is a mapping from each binding name
1401 // to an alloca() that will be the value for that local variable.
1402 // Note that we use the names because each binding will have many ids
1403 // from the various alternatives.
1404 let ccx = bcx.ccx();
1405 let tcx = bcx.tcx();
1406 let reassigned = is_discr_reassigned(bcx, discr, body);
1407 let mut bindings_map = FnvHashMap();
1408 pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1409 let ident = path1.node;
1410 let name = ident.name;
1411 let variable_ty = node_id_type(bcx, p_id);
1412 let llvariable_ty = type_of::type_of(ccx, variable_ty);
1413 let tcx = bcx.tcx();
1414 let param_env = tcx.empty_parameter_environment();
1420 if !variable_ty.moves_by_default(¶m_env, span) || reassigned =>
1422 llmatch = alloca_no_lifetime(bcx,
1423 llvariable_ty.ptr_to(),
1425 trmode = TrByCopy(alloca_no_lifetime(bcx,
1429 ast::BindByValue(_) => {
1430 // in this case, the final type of the variable will be T,
1431 // but during matching we need to store a *T as explained
1433 llmatch = alloca_no_lifetime(bcx,
1434 llvariable_ty.ptr_to(),
1438 ast::BindByRef(_) => {
1439 llmatch = alloca_no_lifetime(bcx,
1445 bindings_map.insert(ident, BindingInfo {
1453 return bindings_map;
1456 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1457 match_id: ast::NodeId,
1458 discr_expr: &ast::Expr,
1460 dest: Dest) -> Block<'blk, 'tcx> {
1461 let _icx = push_ctxt("match::trans_match_inner");
1462 let fcx = scope_cx.fcx;
1463 let mut bcx = scope_cx;
1464 let tcx = bcx.tcx();
1466 let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1468 if bcx.unreachable.get() {
1472 let t = node_id_type(bcx, discr_expr.id);
1473 let chk = if t.is_empty(tcx) {
1479 let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1480 bodycx: fcx.new_id_block("case_body", arm.body.id),
1482 bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1485 let mut pat_renaming_map = if scope_cx.sess().opts.debuginfo != NoDebugInfo {
1491 let arm_pats: Vec<Vec<P<ast::Pat>>> = {
1492 let mut static_inliner = StaticInliner::new(scope_cx.tcx(),
1493 pat_renaming_map.as_mut());
1494 arm_datas.iter().map(|arm_data| {
1495 arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1499 let mut matches = Vec::new();
1500 for (arm_data, pats) in arm_datas.iter().zip(&arm_pats) {
1501 matches.extend(pats.iter().map(|p| Match {
1504 bound_ptrs: Vec::new(),
1505 pat_renaming_map: pat_renaming_map.as_ref()
1509 // `compile_submatch` works one column of arm patterns a time and
1510 // then peels that column off. So as we progress, it may become
1511 // impossible to tell whether we have a genuine default arm, i.e.
1512 // `_ => foo` or not. Sometimes it is important to know that in order
1513 // to decide whether moving on to the next condition or falling back
1514 // to the default arm.
1515 let has_default = arms.last().map_or(false, |arm| {
1517 && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1520 compile_submatch(bcx, &matches[..], &[discr_datum.val], &chk, has_default);
1522 let mut arm_cxs = Vec::new();
1523 for arm_data in &arm_datas {
1524 let mut bcx = arm_data.bodycx;
1526 // insert bindings into the lllocals map and add cleanups
1527 let cs = fcx.push_custom_cleanup_scope();
1528 bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1529 bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1530 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1534 bcx = scope_cx.fcx.join_blocks(match_id, &arm_cxs[..]);
1538 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1539 /// <opt_init_expr>`.
1540 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1542 -> Block<'blk, 'tcx> {
1543 let _icx = push_ctxt("match::store_local");
1545 let tcx = bcx.tcx();
1546 let pat = &*local.pat;
1548 fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1550 -> Block<'blk, 'tcx> {
1551 let _icx = push_ctxt("create_dummy_locals");
1552 // create dummy memory for the variables if we have no
1553 // value to store into them immediately
1554 let tcx = bcx.tcx();
1555 pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1556 let scope = cleanup::var_scope(tcx, p_id);
1557 bcx = mk_binding_alloca(
1558 bcx, p_id, path1.node.name, scope, (),
1559 |(), bcx, llval, ty| { drop_done_fill_mem(bcx, llval, ty); bcx });
1565 Some(ref init_expr) => {
1566 // Optimize the "let x = expr" case. This just writes
1567 // the result of evaluating `expr` directly into the alloca
1568 // for `x`. Often the general path results in similar or the
1569 // same code post-optimization, but not always. In particular,
1570 // in unsafe code, you can have expressions like
1572 // let x = intrinsics::uninit();
1574 // In such cases, the more general path is unsafe, because
1575 // it assumes it is matching against a valid value.
1576 match simple_identifier(&*pat) {
1578 let var_scope = cleanup::var_scope(tcx, local.id);
1579 return mk_binding_alloca(
1580 bcx, pat.id, ident.name, var_scope, (),
1581 |(), bcx, v, _| expr::trans_into(bcx, &**init_expr,
1590 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1591 if bcx.sess().asm_comments() {
1592 add_comment(bcx, "creating zeroable ref llval");
1594 let var_scope = cleanup::var_scope(tcx, local.id);
1595 bind_irrefutable_pat(bcx, pat, init_datum.val, var_scope)
1598 create_dummy_locals(bcx, pat)
1603 fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
1606 cleanup_scope: cleanup::ScopeId,
1609 -> Block<'blk, 'tcx> where
1610 F: FnOnce(A, Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
1612 let var_ty = node_id_type(bcx, p_id);
1614 // Allocate memory on stack for the binding.
1615 let llval = alloc_ty(bcx, var_ty, &bcx.name(name));
1617 // Subtle: be sure that we *populate* the memory *before*
1618 // we schedule the cleanup.
1619 let bcx = populate(arg, bcx, llval, var_ty);
1620 bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1621 bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
1623 // Now that memory is initialized and has cleanup scheduled,
1624 // create the datum and insert into the local variable map.
1625 let datum = Datum::new(llval, var_ty, Lvalue);
1626 bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1630 /// A simple version of the pattern matching code that only handles
1631 /// irrefutable patterns. This is used in let/argument patterns,
1632 /// not in match statements. Unifying this code with the code above
1633 /// sounds nice, but in practice it produces very inefficient code,
1634 /// since the match code is so much more general. In most cases,
1635 /// LLVM is able to optimize the code, but it causes longer compile
1636 /// times and makes the generated code nigh impossible to read.
1639 /// - bcx: starting basic block context
1640 /// - pat: the irrefutable pattern being matched.
1641 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1642 pub fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1645 cleanup_scope: cleanup::ScopeId)
1646 -> Block<'blk, 'tcx> {
1647 debug!("bind_irrefutable_pat(bcx={}, pat={:?})",
1651 if bcx.sess().asm_comments() {
1652 add_comment(bcx, &format!("bind_irrefutable_pat(pat={:?})",
1656 let _indenter = indenter();
1658 let _icx = push_ctxt("match::bind_irrefutable_pat");
1660 let tcx = bcx.tcx();
1661 let ccx = bcx.ccx();
1663 ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1664 if pat_is_binding(&tcx.def_map, &*pat) {
1665 // Allocate the stack slot where the value of this
1666 // binding will live and place it into the appropriate
1668 bcx = mk_binding_alloca(
1669 bcx, pat.id, path1.node.name, cleanup_scope, (),
1670 |(), bcx, llval, ty| {
1671 match pat_binding_mode {
1672 ast::BindByValue(_) => {
1673 // By value binding: move the value that `val`
1674 // points at into the binding's stack slot.
1675 let d = Datum::new(val, ty, Lvalue);
1676 d.store_to(bcx, llval)
1679 ast::BindByRef(_) => {
1680 // By ref binding: the value of the variable
1681 // is the pointer `val` itself or fat pointer referenced by `val`
1682 if type_is_fat_ptr(bcx.tcx(), ty) {
1683 expr::copy_fat_ptr(bcx, val, llval);
1686 Store(bcx, val, llval);
1695 if let Some(ref inner_pat) = *inner {
1696 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1699 ast::PatEnum(_, ref sub_pats) => {
1700 let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).map(|d| d.full_def());
1702 Some(def::DefVariant(enum_id, var_id, _)) => {
1703 let repr = adt::represent_node(bcx, pat.id);
1704 let vinfo = ccx.tcx().enum_variant_with_id(enum_id, var_id);
1705 let args = extract_variant_args(bcx,
1709 if let Some(ref sub_pat) = *sub_pats {
1710 for (i, &argval) in args.vals.iter().enumerate() {
1711 bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
1712 argval, cleanup_scope);
1716 Some(def::DefStruct(..)) => {
1719 // This is a unit-like struct. Nothing to do here.
1721 Some(ref elems) => {
1722 // This is the tuple struct case.
1723 let repr = adt::represent_node(bcx, pat.id);
1724 for (i, elem) in elems.iter().enumerate() {
1725 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1727 bcx = bind_irrefutable_pat(bcx, &**elem,
1728 fldptr, cleanup_scope);
1734 // Nothing to do here.
1738 ast::PatStruct(_, ref fields, _) => {
1739 let tcx = bcx.tcx();
1740 let pat_ty = node_id_type(bcx, pat.id);
1741 let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1742 expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
1744 let ix = tcx.field_idx_strict(f.node.ident.name, field_tys);
1745 let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val,
1747 bcx = bind_irrefutable_pat(bcx, &*f.node.pat, fldptr, cleanup_scope);
1751 ast::PatTup(ref elems) => {
1752 let repr = adt::represent_node(bcx, pat.id);
1753 for (i, elem) in elems.iter().enumerate() {
1754 let fldptr = adt::trans_field_ptr(bcx, &*repr, val, 0, i);
1755 bcx = bind_irrefutable_pat(bcx, &**elem, fldptr, cleanup_scope);
1758 ast::PatBox(ref inner) => {
1759 let llbox = Load(bcx, val);
1760 bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
1762 ast::PatRegion(ref inner, _) => {
1763 let loaded_val = Load(bcx, val);
1764 bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
1766 ast::PatVec(ref before, ref slice, ref after) => {
1767 let pat_ty = node_id_type(bcx, pat.id);
1768 let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1771 extracted.vals.insert(
1773 bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1780 .chain(slice.iter())
1781 .chain(after.iter())
1782 .zip(extracted.vals)
1783 .fold(bcx, |bcx, (inner, elem)|
1784 bind_irrefutable_pat(bcx, &**inner, elem, cleanup_scope)
1787 ast::PatMac(..) => {
1788 bcx.sess().span_bug(pat.span, "unexpanded macro");
1790 ast::PatQPath(..) | ast::PatWild(_) | ast::PatLit(_) |
1791 ast::PatRange(_, _) => ()