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 //! This file actually contains two passes related to regions. The first
12 //! pass builds up the `scope_map`, which describes the parent links in
13 //! the region hierarchy. The second pass infers which types must be
14 //! region parameterized.
16 //! Most of the documentation on regions can be found in
17 //! `middle/typeck/infer/region_inference.rs`
20 use middle::ty::{self, Ty, FreeRegion};
21 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
22 use util::common::can_reach;
24 use std::cell::RefCell;
25 use syntax::codemap::{self, Span};
26 use syntax::{ast, visit};
27 use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local};
28 use syntax::ast_util::{stmt_id};
29 use syntax::visit::{Visitor, FnKind};
31 /// CodeExtent represents a statically-describable extent that can be
32 /// used to bound the lifetime/region for values.
34 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
35 /// placate the same deriving in `ty::FreeRegion`, but we may want to
36 /// actually attach a more meaningful ordering to scopes than the one
37 /// generated via deriving here.
38 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
39 RustcDecodable, Show, Copy)]
45 /// Creates a scope that represents the dynamic extent associated
47 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
48 CodeExtent::Misc(node_id)
51 /// Returns a node id associated with this scope.
53 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
54 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
55 pub fn node_id(&self) -> ast::NodeId {
57 CodeExtent::Misc(node_id) => node_id,
61 /// Maps this scope to a potentially new one according to the
62 /// NodeId transformer `f_id`.
63 pub fn map_id<F>(&self, f_id: F) -> CodeExtent where
64 F: FnOnce(ast::NodeId) -> ast::NodeId,
67 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
72 /// The region maps encode information about region relationships.
74 /// - `scope_map` maps from a scope id to the enclosing scope id; this is
75 /// usually corresponding to the lexical nesting, though in the case of
76 /// closures the parent scope is the innermost conditional expression or repeating
79 /// - `var_map` maps from a variable or binding id to the block in which
80 /// that variable is declared.
82 /// - `free_region_map` maps from a free region `a` to a list of free
83 /// regions `bs` such that `a <= b for all b in bs`
84 /// - the free region map is populated during type check as we check
85 /// each function. See the function `relate_free_regions` for
88 /// - `rvalue_scopes` includes entries for those expressions whose cleanup
89 /// scope is larger than the default. The map goes from the expression
90 /// id to the cleanup scope id. For rvalues not present in this table,
91 /// the appropriate cleanup scope is the innermost enclosing statement,
92 /// conditional expression, or repeating block (see `terminating_scopes`).
94 /// - `terminating_scopes` is a set containing the ids of each statement,
95 /// or conditional/repeating expression. These scopes are calling "terminating
96 /// scopes" because, when attempting to find the scope of a temporary, by
97 /// default we search up the enclosing scopes until we encounter the
98 /// terminating scope. A conditional/repeating
99 /// expression is one which is not guaranteed to execute exactly once
100 /// upon entering the parent scope. This could be because the expression
101 /// only executes conditionally, such as the expression `b` in `a && b`,
102 /// or because the expression may execute many times, such as a loop
103 /// body. The reason that we distinguish such expressions is that, upon
104 /// exiting the parent scope, we cannot statically know how many times
105 /// the expression executed, and thus if the expression creates
106 /// temporaries we cannot know statically how many such temporaries we
107 /// would have to cleanup. Therefore we ensure that the temporaries never
108 /// outlast the conditional/repeating expression, preventing the need
109 /// for dynamic checks and/or arbitrary amounts of stack space.
110 pub struct RegionMaps {
111 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
112 var_map: RefCell<NodeMap<CodeExtent>>,
113 free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
114 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
115 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
120 var_parent: Option<ast::NodeId>,
122 // Innermost enclosing expression
123 parent: Option<ast::NodeId>,
126 struct RegionResolutionVisitor<'a> {
130 region_maps: &'a RegionMaps,
137 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
138 match self.free_region_map.borrow_mut().get_mut(&sub) {
140 if !sups.iter().any(|x| x == &sup) {
148 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
149 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
152 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
153 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
155 self.scope_map.borrow_mut().insert(sub, sup);
158 pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
159 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
160 assert!(var != lifetime.node_id());
161 self.var_map.borrow_mut().insert(var, lifetime);
164 pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
165 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
166 assert!(var != lifetime.node_id());
167 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
170 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
171 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
173 pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
174 debug!("record_terminating_scope(scope_id={:?})", scope_id);
175 self.terminating_scopes.borrow_mut().insert(scope_id);
178 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
179 //! Returns the narrowest scope that encloses `id`, if any.
180 self.scope_map.borrow().get(&id).map(|x| *x)
183 #[allow(dead_code)] // used in middle::cfg
184 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
185 //! Returns the narrowest scope that encloses `id`, if any.
186 match self.scope_map.borrow().get(&id) {
188 None => { panic!("no enclosing scope for id {:?}", id); }
192 /// Returns the lifetime of the local variable `var_id`
193 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
194 match self.var_map.borrow().get(&var_id) {
196 None => { panic!("no enclosing scope for id {:?}", var_id); }
200 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
201 //! Returns the scope when temp created by expr_id will be cleaned up
203 // check for a designated rvalue scope
204 match self.rvalue_scopes.borrow().get(&expr_id) {
206 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
212 // else, locate the innermost terminating scope
213 // if there's one. Static items, for instance, won't
214 // have an enclosing scope, hence no scope will be
216 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
218 None => { return None; }
221 while !self.terminating_scopes.borrow().contains(&id) {
222 match self.opt_encl_scope(id) {
227 debug!("temporary_scope({:?}) = None", expr_id);
232 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
236 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
237 //! Returns the lifetime of the variable `id`.
239 let scope = ty::ReScope(self.var_scope(id));
240 debug!("var_region({:?}) = {:?}", id, scope);
244 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
246 self.is_subscope_of(scope1, scope2) ||
247 self.is_subscope_of(scope2, scope1)
250 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
252 pub fn is_subscope_of(&self,
253 subscope: CodeExtent,
254 superscope: CodeExtent)
256 let mut s = subscope;
257 while superscope != s {
258 match self.scope_map.borrow().get(&s) {
260 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
261 subscope, superscope, s);
265 Some(&scope) => s = scope
269 debug!("is_subscope_of({:?}, {:?})=true",
270 subscope, superscope);
275 /// Determines whether two free regions have a subregion relationship
276 /// by walking the graph encoded in `free_region_map`. Note that
277 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
278 /// (that is, the user can give two different names to the same lifetime).
279 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
280 can_reach(&*self.free_region_map.borrow(), sub, sup)
283 /// Determines whether one region is a subregion of another. This is intended to run *after
284 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
285 pub fn is_subregion_of(&self,
286 sub_region: ty::Region,
287 super_region: ty::Region)
289 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
290 sub_region, super_region);
292 sub_region == super_region || {
293 match (sub_region, super_region) {
295 (_, ty::ReStatic) => {
299 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
300 self.is_subscope_of(sub_scope, super_scope)
303 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
304 self.is_subscope_of(sub_scope, fr.scope)
307 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
308 self.sub_free_region(sub_fr, super_fr)
311 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
312 ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
313 // This case is used only to make sure that explicitly-
314 // specified `Self` types match the real self type in
316 param_id_a == param_id_b &&
317 param_space_a == param_space_b &&
328 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
329 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
330 pub fn nearest_common_ancestor(&self,
333 -> Option<CodeExtent> {
334 if scope_a == scope_b { return Some(scope_a); }
336 let a_ancestors = ancestors_of(self, scope_a);
337 let b_ancestors = ancestors_of(self, scope_b);
338 let mut a_index = a_ancestors.len() - 1u;
339 let mut b_index = b_ancestors.len() - 1u;
341 // Here, ~[ab]_ancestors is a vector going from narrow to broad.
342 // The end of each vector will be the item where the scope is
343 // defined; if there are any common ancestors, then the tails of
344 // the vector will be the same. So basically we want to walk
345 // backwards from the tail of each vector and find the first point
346 // where they diverge. If one vector is a suffix of the other,
347 // then the corresponding scope is a superscope of the other.
349 if a_ancestors[a_index] != b_ancestors[b_index] {
354 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
355 // for all indices between a_index and the end of the array
356 if a_index == 0u { return Some(scope_a); }
357 if b_index == 0u { return Some(scope_b); }
360 if a_ancestors[a_index] != b_ancestors[b_index] {
361 return Some(a_ancestors[a_index + 1]);
365 fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
367 // debug!("ancestors_of(scope={:?})", scope);
368 let mut result = vec!(scope);
369 let mut scope = scope;
371 match this.scope_map.borrow().get(&scope) {
372 None => return result,
373 Some(&superscope) => {
374 result.push(superscope);
378 // debug!("ancestors_of_loop(scope={:?})", scope);
384 /// Records the current parent (if any) as the parent of `child_id`.
385 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
386 child_id: ast::NodeId,
388 match visitor.cx.parent {
390 let child_scope = CodeExtent::from_node_id(child_id);
391 let parent_scope = CodeExtent::from_node_id(parent_id);
392 visitor.region_maps.record_encl_scope(child_scope, parent_scope);
398 /// Records the lifetime of a local variable as `cx.var_parent`
399 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
402 match visitor.cx.var_parent {
404 let parent_scope = CodeExtent::from_node_id(parent_id);
405 visitor.region_maps.record_var_scope(var_id, parent_scope);
408 // this can happen in extern fn declarations like
410 // extern fn isalnum(c: c_int) -> c_int
415 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
416 debug!("resolve_block(blk.id={:?})", blk.id);
418 // Record the parent of this block.
419 record_superlifetime(visitor, blk.id, blk.span);
421 // We treat the tail expression in the block (if any) somewhat
422 // differently from the statements. The issue has to do with
423 // temporary lifetimes. If the user writes:
430 let prev_cx = visitor.cx;
431 visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)};
432 visit::walk_block(visitor, blk);
433 visitor.cx = prev_cx;
436 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
437 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
438 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
442 let guard_scope = CodeExtent::from_node_id(expr.id);
443 visitor.region_maps.mark_as_terminating_scope(guard_scope);
448 visit::walk_arm(visitor, arm);
451 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
452 record_superlifetime(visitor, pat.id, pat.span);
454 // If this is a binding (or maybe a binding, I'm too lazy to check
455 // the def map) then record the lifetime of that binding.
457 ast::PatIdent(..) => {
458 record_var_lifetime(visitor, pat.id, pat.span);
463 visit::walk_pat(visitor, pat);
466 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
467 let stmt_id = stmt_id(stmt);
468 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
470 let stmt_scope = CodeExtent::from_node_id(stmt_id);
471 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
472 record_superlifetime(visitor, stmt_id, stmt.span);
474 let prev_parent = visitor.cx.parent;
475 visitor.cx.parent = Some(stmt_id);
476 visit::walk_stmt(visitor, stmt);
477 visitor.cx.parent = prev_parent;
480 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
481 debug!("resolve_expr(expr.id={:?})", expr.id);
483 record_superlifetime(visitor, expr.id, expr.span);
485 let prev_cx = visitor.cx;
486 visitor.cx.parent = Some(expr.id);
489 let region_maps = &mut visitor.region_maps;
490 let terminating = |&: id| {
491 let scope = CodeExtent::from_node_id(id);
492 region_maps.mark_as_terminating_scope(scope)
495 // Conditional or repeating scopes are always terminating
496 // scopes, meaning that temporaries cannot outlive them.
497 // This ensures fixed size stacks.
499 ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
500 ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
501 // For shortcircuiting operators, mark the RHS as a terminating
502 // scope since it only executes conditionally.
506 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
507 terminating(then.id);
508 terminating(otherwise.id);
511 ast::ExprIf(ref expr, ref then, None) => {
512 terminating(expr.id);
513 terminating(then.id);
516 ast::ExprLoop(ref body, _) => {
517 terminating(body.id);
520 ast::ExprWhile(ref expr, ref body, _) => {
521 terminating(expr.id);
522 terminating(body.id);
525 ast::ExprForLoop(ref _pat, ref _head, ref body, _) => {
526 terminating(body.id);
528 // The variable parent of everything inside (most importantly, the
529 // pattern) is the body.
530 visitor.cx.var_parent = Some(body.id);
533 ast::ExprMatch(..) => {
534 visitor.cx.var_parent = Some(expr.id);
537 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
538 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
539 // FIXME(#6268) Nested method calls
541 // The lifetimes for a call or method call look as follows:
549 // The idea is that call.callee_id represents *the time when
550 // the invoked function is actually running* and call.id
551 // represents *the time to prepare the arguments and make the
552 // call*. See the section "Borrows in Calls" borrowck/doc.rs
553 // for an extended explanation of why this distinction is
556 // record_superlifetime(new_cx, expr.callee_id);
563 visit::walk_expr(visitor, expr);
564 visitor.cx = prev_cx;
567 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
568 debug!("resolve_local(local.id={:?},local.init={:?})",
569 local.id,local.init.is_some());
571 let blk_id = match visitor.cx.var_parent {
574 visitor.sess.span_bug(
576 "local without enclosing block");
580 // For convenience in trans, associate with the local-id the var
581 // scope that will be used for any bindings declared in this
583 let blk_scope = CodeExtent::from_node_id(blk_id);
584 visitor.region_maps.record_var_scope(local.id, blk_scope);
586 // As an exception to the normal rules governing temporary
587 // lifetimes, initializers in a let have a temporary lifetime
588 // of the enclosing block. This means that e.g. a program
589 // like the following is legal:
591 // let ref x = HashMap::new();
593 // Because the hash map will be freed in the enclosing block.
595 // We express the rules more formally based on 3 grammars (defined
596 // fully in the helpers below that implement them):
598 // 1. `E&`, which matches expressions like `&<rvalue>` that
599 // own a pointer into the stack.
601 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
602 // y)` that produce ref bindings into the value they are
603 // matched against or something (at least partially) owned by
604 // the value they are matched against. (By partially owned,
605 // I mean that creating a binding into a ref-counted or managed value
606 // would still count.)
608 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
609 // based on rvalues like `foo().x[2].y`.
611 // A subexpression `<rvalue>` that appears in a let initializer
612 // `let pat [: ty] = expr` has an extended temporary lifetime if
613 // any of the following conditions are met:
615 // A. `pat` matches `P&` and `expr` matches `ET`
616 // (covers cases where `pat` creates ref bindings into an rvalue
617 // produced by `expr`)
618 // B. `ty` is a borrowed pointer and `expr` matches `ET`
619 // (covers cases where coercion creates a borrow)
620 // C. `expr` matches `E&`
621 // (covers cases `expr` borrows an rvalue that is then assigned
622 // to memory (at least partially) owned by the binding)
624 // Here are some examples hopefully giving an intuition where each
625 // rule comes into play and why:
627 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
628 // would have an extended lifetime, but not `foo()`.
630 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
631 // would have an extended lifetime, but not `foo()`.
633 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
636 // In some cases, multiple rules may apply (though not to the same
637 // rvalue). For example:
639 // let ref x = [&a(), &b()];
641 // Here, the expression `[...]` has an extended lifetime due to rule
642 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
645 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
649 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
652 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
654 if is_binding_pat(&*local.pat) || is_borrow {
655 record_rvalue_scope(visitor, &**expr, blk_scope);
662 visit::walk_local(visitor, local);
664 /// True if `pat` match the `P&` nonterminal:
667 /// | StructName { ..., P&, ... }
668 /// | VariantName(..., P&, ...)
669 /// | [ ..., P&, ... ]
670 /// | ( ..., P&, ... )
672 fn is_binding_pat(pat: &ast::Pat) -> bool {
674 ast::PatIdent(ast::BindByRef(_), _, _) => true,
676 ast::PatStruct(_, ref field_pats, _) => {
677 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
680 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
681 pats1.iter().any(|p| is_binding_pat(&**p)) ||
682 pats2.iter().any(|p| is_binding_pat(&**p)) ||
683 pats3.iter().any(|p| is_binding_pat(&**p))
686 ast::PatEnum(_, Some(ref subpats)) |
687 ast::PatTup(ref subpats) => {
688 subpats.iter().any(|p| is_binding_pat(&**p))
691 ast::PatBox(ref subpat) => {
692 is_binding_pat(&**subpat)
699 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
700 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
702 ast::TyRptr(..) => true,
707 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
710 /// | StructName { ..., f: E&, ... }
711 /// | [ ..., E&, ... ]
712 /// | ( ..., E&, ... )
717 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
719 blk_id: CodeExtent) {
721 ast::ExprAddrOf(_, ref subexpr) => {
722 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
723 record_rvalue_scope(visitor, &**subexpr, blk_id);
725 ast::ExprStruct(_, ref fields, _) => {
726 for field in fields.iter() {
727 record_rvalue_scope_if_borrow_expr(
728 visitor, &*field.expr, blk_id);
731 ast::ExprVec(ref subexprs) |
732 ast::ExprTup(ref subexprs) => {
733 for subexpr in subexprs.iter() {
734 record_rvalue_scope_if_borrow_expr(
735 visitor, &**subexpr, blk_id);
738 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
739 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
741 ast::ExprCast(ref subexpr, _) |
742 ast::ExprParen(ref subexpr) => {
743 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
745 ast::ExprBlock(ref block) => {
747 Some(ref subexpr) => {
748 record_rvalue_scope_if_borrow_expr(
749 visitor, &**subexpr, blk_id);
759 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
760 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
761 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
764 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
765 /// `<rvalue>` as `blk_id`:
773 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
774 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
776 blk_scope: CodeExtent) {
779 // Note: give all the expressions matching `ET` with the
780 // extended temporary lifetime, not just the innermost rvalue,
781 // because in trans if we must compile e.g. `*rvalue()`
782 // into a temporary, we request the temporary scope of the
784 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
787 ast::ExprAddrOf(_, ref subexpr) |
788 ast::ExprUnary(ast::UnDeref, ref subexpr) |
789 ast::ExprField(ref subexpr, _) |
790 ast::ExprTupField(ref subexpr, _) |
791 ast::ExprIndex(ref subexpr, _) |
792 ast::ExprParen(ref subexpr) => {
803 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
804 // Items create a new outer block scope as far as we're concerned.
805 let prev_cx = visitor.cx;
806 visitor.cx = Context {var_parent: None, parent: None};
807 visit::walk_item(visitor, item);
808 visitor.cx = prev_cx;
811 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
817 debug!("region::resolve_fn(id={:?}, \
822 visitor.sess.codemap().span_to_string(sp),
826 let body_scope = CodeExtent::from_node_id(body.id);
827 visitor.region_maps.mark_as_terminating_scope(body_scope);
829 let outer_cx = visitor.cx;
831 // The arguments and `self` are parented to the body of the fn.
832 visitor.cx = Context { parent: Some(body.id),
833 var_parent: Some(body.id) };
834 visit::walk_fn_decl(visitor, decl);
836 // The body of the fn itself is either a root scope (top-level fn)
837 // or it continues with the inherited scope (closures).
839 visit::FkItemFn(..) | visit::FkMethod(..) => {
840 visitor.cx = Context { parent: None, var_parent: None };
841 visitor.visit_block(body);
842 visitor.cx = outer_cx;
844 visit::FkFnBlock(..) => {
845 // FIXME(#3696) -- at present we are place the closure body
846 // within the region hierarchy exactly where it appears lexically.
847 // This is wrong because the closure may live longer
848 // than the enclosing expression. We should probably fix this,
849 // but the correct fix is a bit subtle, and I am also not sure
850 // that the present approach is unsound -- it may not permit
851 // any illegal programs. See issue for more details.
852 visitor.cx = outer_cx;
853 visitor.visit_block(body);
858 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
860 fn visit_block(&mut self, b: &Block) {
861 resolve_block(self, b);
864 fn visit_item(&mut self, i: &Item) {
865 resolve_item(self, i);
868 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
869 b: &'v Block, s: Span, n: NodeId) {
870 resolve_fn(self, fk, fd, b, s, n);
872 fn visit_arm(&mut self, a: &Arm) {
873 resolve_arm(self, a);
875 fn visit_pat(&mut self, p: &Pat) {
876 resolve_pat(self, p);
878 fn visit_stmt(&mut self, s: &Stmt) {
879 resolve_stmt(self, s);
881 fn visit_expr(&mut self, ex: &Expr) {
882 resolve_expr(self, ex);
884 fn visit_local(&mut self, l: &Local) {
885 resolve_local(self, l);
889 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
890 let maps = RegionMaps {
891 scope_map: RefCell::new(FnvHashMap()),
892 var_map: RefCell::new(NodeMap()),
893 free_region_map: RefCell::new(FnvHashMap()),
894 rvalue_scopes: RefCell::new(NodeMap()),
895 terminating_scopes: RefCell::new(FnvHashSet()),
898 let mut visitor = RegionResolutionVisitor {
901 cx: Context { parent: None, var_parent: None }
903 visit::walk_crate(&mut visitor, krate);
908 pub fn resolve_inlined_item(sess: &Session,
909 region_maps: &RegionMaps,
910 item: &ast::InlinedItem) {
911 let mut visitor = RegionResolutionVisitor {
913 region_maps: region_maps,
914 cx: Context { parent: None, var_parent: None }
916 visit::walk_inlined_item(&mut visitor, item);