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 std::hash::{Hash};
26 use syntax::codemap::Span;
27 use syntax::{ast, visit};
28 use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local};
29 use syntax::ast_util::{stmt_id};
30 use syntax::visit::{Visitor, FnKind};
32 /// CodeExtent represents a statically-describable extent that can be
33 /// used to bound the lifetime/region for values.
35 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
36 /// placate the same deriving in `ty::FreeRegion`, but we may want to
37 /// actually attach a more meaningful ordering to scopes than the one
38 /// generated via deriving here.
39 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
40 RustcDecodable, Show, Copy)]
46 /// Creates a scope that represents the dynamic extent associated
48 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
49 CodeExtent::Misc(node_id)
52 /// Returns a node id associated with this scope.
54 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
55 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
56 pub fn node_id(&self) -> ast::NodeId {
58 CodeExtent::Misc(node_id) => node_id,
62 /// Maps this scope to a potentially new one according to the
63 /// NodeId transformer `f_id`.
64 pub fn map_id<F>(&self, f_id: F) -> CodeExtent where
65 F: FnOnce(ast::NodeId) -> ast::NodeId,
68 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
73 /// The region maps encode information about region relationships.
75 /// - `scope_map` maps from a scope id to the enclosing scope id; this is
76 /// usually corresponding to the lexical nesting, though in the case of
77 /// closures the parent scope is the innermost conditional expression or repeating
80 /// - `var_map` maps from a variable or binding id to the block in which
81 /// that variable is declared.
83 /// - `free_region_map` maps from a free region `a` to a list of free
84 /// regions `bs` such that `a <= b for all b in bs`
85 /// - the free region map is populated during type check as we check
86 /// each function. See the function `relate_free_regions` for
89 /// - `rvalue_scopes` includes entries for those expressions whose cleanup
90 /// scope is larger than the default. The map goes from the expression
91 /// id to the cleanup scope id. For rvalues not present in this table,
92 /// the appropriate cleanup scope is the innermost enclosing statement,
93 /// conditional expression, or repeating block (see `terminating_scopes`).
95 /// - `terminating_scopes` is a set containing the ids of each statement,
96 /// or conditional/repeating expression. These scopes are calling "terminating
97 /// scopes" because, when attempting to find the scope of a temporary, by
98 /// default we search up the enclosing scopes until we encounter the
99 /// terminating scope. A conditional/repeating
100 /// expression is one which is not guaranteed to execute exactly once
101 /// upon entering the parent scope. This could be because the expression
102 /// only executes conditionally, such as the expression `b` in `a && b`,
103 /// or because the expression may execute many times, such as a loop
104 /// body. The reason that we distinguish such expressions is that, upon
105 /// exiting the parent scope, we cannot statically know how many times
106 /// the expression executed, and thus if the expression creates
107 /// temporaries we cannot know statically how many such temporaries we
108 /// would have to cleanup. Therefore we ensure that the temporaries never
109 /// outlast the conditional/repeating expression, preventing the need
110 /// for dynamic checks and/or arbitrary amounts of stack space.
111 pub struct RegionMaps {
112 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
113 var_map: RefCell<NodeMap<CodeExtent>>,
114 free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
115 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
116 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
121 var_parent: Option<ast::NodeId>,
123 // Innermost enclosing expression
124 parent: Option<ast::NodeId>,
127 struct RegionResolutionVisitor<'a> {
131 region_maps: &'a RegionMaps,
138 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
139 match self.free_region_map.borrow_mut().get_mut(&sub) {
141 if !sups.iter().any(|x| x == &sup) {
149 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
150 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
153 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
154 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
156 self.scope_map.borrow_mut().insert(sub, sup);
159 pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
160 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
161 assert!(var != lifetime.node_id());
162 self.var_map.borrow_mut().insert(var, lifetime);
165 pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
166 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
167 assert!(var != lifetime.node_id());
168 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
171 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
172 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
174 pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
175 debug!("record_terminating_scope(scope_id={:?})", scope_id);
176 self.terminating_scopes.borrow_mut().insert(scope_id);
179 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
180 //! Returns the narrowest scope that encloses `id`, if any.
181 self.scope_map.borrow().get(&id).map(|x| *x)
184 #[allow(dead_code)] // used in middle::cfg
185 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
186 //! Returns the narrowest scope that encloses `id`, if any.
187 match self.scope_map.borrow().get(&id) {
189 None => { panic!("no enclosing scope for id {:?}", id); }
193 /// Returns the lifetime of the local variable `var_id`
194 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
195 match self.var_map.borrow().get(&var_id) {
197 None => { panic!("no enclosing scope for id {:?}", var_id); }
201 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
202 //! Returns the scope when temp created by expr_id will be cleaned up
204 // check for a designated rvalue scope
205 match self.rvalue_scopes.borrow().get(&expr_id) {
207 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
213 // else, locate the innermost terminating scope
214 // if there's one. Static items, for instance, won't
215 // have an enclosing scope, hence no scope will be
217 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
219 None => { return None; }
222 while !self.terminating_scopes.borrow().contains(&id) {
223 match self.opt_encl_scope(id) {
228 debug!("temporary_scope({:?}) = None", expr_id);
233 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
237 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
238 //! Returns the lifetime of the variable `id`.
240 let scope = ty::ReScope(self.var_scope(id));
241 debug!("var_region({:?}) = {:?}", id, scope);
245 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
247 self.is_subscope_of(scope1, scope2) ||
248 self.is_subscope_of(scope2, scope1)
251 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
253 pub fn is_subscope_of(&self,
254 subscope: CodeExtent,
255 superscope: CodeExtent)
257 let mut s = subscope;
258 while superscope != s {
259 match self.scope_map.borrow().get(&s) {
261 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
262 subscope, superscope, s);
266 Some(&scope) => s = scope
270 debug!("is_subscope_of({:?}, {:?})=true",
271 subscope, superscope);
276 /// Determines whether two free regions have a subregion relationship
277 /// by walking the graph encoded in `free_region_map`. Note that
278 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
279 /// (that is, the user can give two different names to the same lifetime).
280 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
281 can_reach(&*self.free_region_map.borrow(), sub, sup)
284 /// Determines whether one region is a subregion of another. This is intended to run *after
285 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
286 pub fn is_subregion_of(&self,
287 sub_region: ty::Region,
288 super_region: ty::Region)
290 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
291 sub_region, super_region);
293 sub_region == super_region || {
294 match (sub_region, super_region) {
296 (_, ty::ReStatic) => {
300 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
301 self.is_subscope_of(sub_scope, super_scope)
304 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
305 self.is_subscope_of(sub_scope, fr.scope)
308 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
309 self.sub_free_region(sub_fr, super_fr)
312 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
313 ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
314 // This case is used only to make sure that explicitly-
315 // specified `Self` types match the real self type in
317 param_id_a == param_id_b &&
318 param_space_a == param_space_b &&
329 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
330 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
331 pub fn nearest_common_ancestor(&self,
334 -> Option<CodeExtent> {
335 if scope_a == scope_b { return Some(scope_a); }
337 let a_ancestors = ancestors_of(self, scope_a);
338 let b_ancestors = ancestors_of(self, scope_b);
339 let mut a_index = a_ancestors.len() - 1u;
340 let mut b_index = b_ancestors.len() - 1u;
342 // Here, ~[ab]_ancestors is a vector going from narrow to broad.
343 // The end of each vector will be the item where the scope is
344 // defined; if there are any common ancestors, then the tails of
345 // the vector will be the same. So basically we want to walk
346 // backwards from the tail of each vector and find the first point
347 // where they diverge. If one vector is a suffix of the other,
348 // then the corresponding scope is a superscope of the other.
350 if a_ancestors[a_index] != b_ancestors[b_index] {
355 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
356 // for all indices between a_index and the end of the array
357 if a_index == 0u { return Some(scope_a); }
358 if b_index == 0u { return Some(scope_b); }
361 if a_ancestors[a_index] != b_ancestors[b_index] {
362 return Some(a_ancestors[a_index + 1]);
366 fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
368 // debug!("ancestors_of(scope={:?})", scope);
369 let mut result = vec!(scope);
370 let mut scope = scope;
372 match this.scope_map.borrow().get(&scope) {
373 None => return result,
374 Some(&superscope) => {
375 result.push(superscope);
379 // debug!("ancestors_of_loop(scope={:?})", scope);
385 /// Records the current parent (if any) as the parent of `child_id`.
386 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
387 child_id: ast::NodeId,
389 match visitor.cx.parent {
391 let child_scope = CodeExtent::from_node_id(child_id);
392 let parent_scope = CodeExtent::from_node_id(parent_id);
393 visitor.region_maps.record_encl_scope(child_scope, parent_scope);
399 /// Records the lifetime of a local variable as `cx.var_parent`
400 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
403 match visitor.cx.var_parent {
405 let parent_scope = CodeExtent::from_node_id(parent_id);
406 visitor.region_maps.record_var_scope(var_id, parent_scope);
409 // this can happen in extern fn declarations like
411 // extern fn isalnum(c: c_int) -> c_int
416 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
417 debug!("resolve_block(blk.id={:?})", blk.id);
419 // Record the parent of this block.
420 record_superlifetime(visitor, blk.id, blk.span);
422 // We treat the tail expression in the block (if any) somewhat
423 // differently from the statements. The issue has to do with
424 // temporary lifetimes. If the user writes:
431 let prev_cx = visitor.cx;
432 visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)};
433 visit::walk_block(visitor, blk);
434 visitor.cx = prev_cx;
437 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
438 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
439 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
443 let guard_scope = CodeExtent::from_node_id(expr.id);
444 visitor.region_maps.mark_as_terminating_scope(guard_scope);
449 visit::walk_arm(visitor, arm);
452 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
453 record_superlifetime(visitor, pat.id, pat.span);
455 // If this is a binding (or maybe a binding, I'm too lazy to check
456 // the def map) then record the lifetime of that binding.
458 ast::PatIdent(..) => {
459 record_var_lifetime(visitor, pat.id, pat.span);
464 visit::walk_pat(visitor, pat);
467 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
468 let stmt_id = stmt_id(stmt);
469 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
471 let stmt_scope = CodeExtent::from_node_id(stmt_id);
472 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
473 record_superlifetime(visitor, stmt_id, stmt.span);
475 let prev_parent = visitor.cx.parent;
476 visitor.cx.parent = Some(stmt_id);
477 visit::walk_stmt(visitor, stmt);
478 visitor.cx.parent = prev_parent;
481 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
482 debug!("resolve_expr(expr.id={:?})", expr.id);
484 record_superlifetime(visitor, expr.id, expr.span);
486 let prev_cx = visitor.cx;
487 visitor.cx.parent = Some(expr.id);
490 let region_maps = &mut visitor.region_maps;
491 let terminating = |&: id| {
492 let scope = CodeExtent::from_node_id(id);
493 region_maps.mark_as_terminating_scope(scope)
496 // Conditional or repeating scopes are always terminating
497 // scopes, meaning that temporaries cannot outlive them.
498 // This ensures fixed size stacks.
500 ast::ExprBinary(ast::BiAnd, _, ref r) |
501 ast::ExprBinary(ast::BiOr, _, ref r) => {
502 // For shortcircuiting operators, mark the RHS as a terminating
503 // scope since it only executes conditionally.
507 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
508 terminating(then.id);
509 terminating(otherwise.id);
512 ast::ExprIf(ref expr, ref then, None) => {
513 terminating(expr.id);
514 terminating(then.id);
517 ast::ExprLoop(ref body, _) => {
518 terminating(body.id);
521 ast::ExprWhile(ref expr, ref body, _) => {
522 terminating(expr.id);
523 terminating(body.id);
526 ast::ExprForLoop(ref _pat, ref _head, ref body, _) => {
527 terminating(body.id);
529 // The variable parent of everything inside (most importantly, the
530 // pattern) is the body.
531 visitor.cx.var_parent = Some(body.id);
534 ast::ExprMatch(..) => {
535 visitor.cx.var_parent = Some(expr.id);
538 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
539 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
540 // FIXME(#6268) Nested method calls
542 // The lifetimes for a call or method call look as follows:
550 // The idea is that call.callee_id represents *the time when
551 // the invoked function is actually running* and call.id
552 // represents *the time to prepare the arguments and make the
553 // call*. See the section "Borrows in Calls" borrowck/doc.rs
554 // for an extended explanation of why this distinction is
557 // record_superlifetime(new_cx, expr.callee_id);
564 visit::walk_expr(visitor, expr);
565 visitor.cx = prev_cx;
568 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
569 debug!("resolve_local(local.id={:?},local.init={:?})",
570 local.id,local.init.is_some());
572 let blk_id = match visitor.cx.var_parent {
575 visitor.sess.span_bug(
577 "local without enclosing block");
581 // For convenience in trans, associate with the local-id the var
582 // scope that will be used for any bindings declared in this
584 let blk_scope = CodeExtent::from_node_id(blk_id);
585 visitor.region_maps.record_var_scope(local.id, blk_scope);
587 // As an exception to the normal rules governing temporary
588 // lifetimes, initializers in a let have a temporary lifetime
589 // of the enclosing block. This means that e.g. a program
590 // like the following is legal:
592 // let ref x = HashMap::new();
594 // Because the hash map will be freed in the enclosing block.
596 // We express the rules more formally based on 3 grammars (defined
597 // fully in the helpers below that implement them):
599 // 1. `E&`, which matches expressions like `&<rvalue>` that
600 // own a pointer into the stack.
602 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
603 // y)` that produce ref bindings into the value they are
604 // matched against or something (at least partially) owned by
605 // the value they are matched against. (By partially owned,
606 // I mean that creating a binding into a ref-counted or managed value
607 // would still count.)
609 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
610 // based on rvalues like `foo().x[2].y`.
612 // A subexpression `<rvalue>` that appears in a let initializer
613 // `let pat [: ty] = expr` has an extended temporary lifetime if
614 // any of the following conditions are met:
616 // A. `pat` matches `P&` and `expr` matches `ET`
617 // (covers cases where `pat` creates ref bindings into an rvalue
618 // produced by `expr`)
619 // B. `ty` is a borrowed pointer and `expr` matches `ET`
620 // (covers cases where coercion creates a borrow)
621 // C. `expr` matches `E&`
622 // (covers cases `expr` borrows an rvalue that is then assigned
623 // to memory (at least partially) owned by the binding)
625 // Here are some examples hopefully giving an intuition where each
626 // rule comes into play and why:
628 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
629 // would have an extended lifetime, but not `foo()`.
631 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
632 // would have an extended lifetime, but not `foo()`.
634 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
637 // In some cases, multiple rules may apply (though not to the same
638 // rvalue). For example:
640 // let ref x = [&a(), &b()];
642 // Here, the expression `[...]` has an extended lifetime due to rule
643 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
646 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
650 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
653 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
655 if is_binding_pat(&*local.pat) || is_borrow {
656 record_rvalue_scope(visitor, &**expr, blk_scope);
663 visit::walk_local(visitor, local);
665 /// True if `pat` match the `P&` nonterminal:
668 /// | StructName { ..., P&, ... }
669 /// | VariantName(..., P&, ...)
670 /// | [ ..., P&, ... ]
671 /// | ( ..., P&, ... )
673 fn is_binding_pat(pat: &ast::Pat) -> bool {
675 ast::PatIdent(ast::BindByRef(_), _, _) => true,
677 ast::PatStruct(_, ref field_pats, _) => {
678 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
681 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
682 pats1.iter().any(|p| is_binding_pat(&**p)) ||
683 pats2.iter().any(|p| is_binding_pat(&**p)) ||
684 pats3.iter().any(|p| is_binding_pat(&**p))
687 ast::PatEnum(_, Some(ref subpats)) |
688 ast::PatTup(ref subpats) => {
689 subpats.iter().any(|p| is_binding_pat(&**p))
692 ast::PatBox(ref subpat) => {
693 is_binding_pat(&**subpat)
700 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
701 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
703 ast::TyRptr(..) => true,
708 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
711 /// | StructName { ..., f: E&, ... }
712 /// | [ ..., E&, ... ]
713 /// | ( ..., E&, ... )
718 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
720 blk_id: CodeExtent) {
722 ast::ExprAddrOf(_, ref subexpr) => {
723 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
724 record_rvalue_scope(visitor, &**subexpr, blk_id);
726 ast::ExprStruct(_, ref fields, _) => {
727 for field in fields.iter() {
728 record_rvalue_scope_if_borrow_expr(
729 visitor, &*field.expr, blk_id);
732 ast::ExprVec(ref subexprs) |
733 ast::ExprTup(ref subexprs) => {
734 for subexpr in subexprs.iter() {
735 record_rvalue_scope_if_borrow_expr(
736 visitor, &**subexpr, blk_id);
739 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
740 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
742 ast::ExprCast(ref subexpr, _) |
743 ast::ExprParen(ref subexpr) => {
744 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
746 ast::ExprBlock(ref block) => {
748 Some(ref subexpr) => {
749 record_rvalue_scope_if_borrow_expr(
750 visitor, &**subexpr, blk_id);
760 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
761 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
762 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
765 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
766 /// `<rvalue>` as `blk_id`:
774 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
775 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
777 blk_scope: CodeExtent) {
780 // Note: give all the expressions matching `ET` with the
781 // extended temporary lifetime, not just the innermost rvalue,
782 // because in trans if we must compile e.g. `*rvalue()`
783 // into a temporary, we request the temporary scope of the
785 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
788 ast::ExprAddrOf(_, ref subexpr) |
789 ast::ExprUnary(ast::UnDeref, ref subexpr) |
790 ast::ExprField(ref subexpr, _) |
791 ast::ExprTupField(ref subexpr, _) |
792 ast::ExprIndex(ref subexpr, _) |
793 ast::ExprParen(ref subexpr) => {
804 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
805 // Items create a new outer block scope as far as we're concerned.
806 let prev_cx = visitor.cx;
807 visitor.cx = Context {var_parent: None, parent: None};
808 visit::walk_item(visitor, item);
809 visitor.cx = prev_cx;
812 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
818 debug!("region::resolve_fn(id={:?}, \
823 visitor.sess.codemap().span_to_string(sp),
827 let body_scope = CodeExtent::from_node_id(body.id);
828 visitor.region_maps.mark_as_terminating_scope(body_scope);
830 let outer_cx = visitor.cx;
832 // The arguments and `self` are parented to the body of the fn.
833 visitor.cx = Context { parent: Some(body.id),
834 var_parent: Some(body.id) };
835 visit::walk_fn_decl(visitor, decl);
837 // The body of the fn itself is either a root scope (top-level fn)
838 // or it continues with the inherited scope (closures).
840 visit::FkItemFn(..) | visit::FkMethod(..) => {
841 visitor.cx = Context { parent: None, var_parent: None };
842 visitor.visit_block(body);
843 visitor.cx = outer_cx;
845 visit::FkFnBlock(..) => {
846 // FIXME(#3696) -- at present we are place the closure body
847 // within the region hierarchy exactly where it appears lexically.
848 // This is wrong because the closure may live longer
849 // than the enclosing expression. We should probably fix this,
850 // but the correct fix is a bit subtle, and I am also not sure
851 // that the present approach is unsound -- it may not permit
852 // any illegal programs. See issue for more details.
853 visitor.cx = outer_cx;
854 visitor.visit_block(body);
859 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
861 fn visit_block(&mut self, b: &Block) {
862 resolve_block(self, b);
865 fn visit_item(&mut self, i: &Item) {
866 resolve_item(self, i);
869 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
870 b: &'v Block, s: Span, n: NodeId) {
871 resolve_fn(self, fk, fd, b, s, n);
873 fn visit_arm(&mut self, a: &Arm) {
874 resolve_arm(self, a);
876 fn visit_pat(&mut self, p: &Pat) {
877 resolve_pat(self, p);
879 fn visit_stmt(&mut self, s: &Stmt) {
880 resolve_stmt(self, s);
882 fn visit_expr(&mut self, ex: &Expr) {
883 resolve_expr(self, ex);
885 fn visit_local(&mut self, l: &Local) {
886 resolve_local(self, l);
890 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
891 let maps = RegionMaps {
892 scope_map: RefCell::new(FnvHashMap::new()),
893 var_map: RefCell::new(NodeMap::new()),
894 free_region_map: RefCell::new(FnvHashMap::new()),
895 rvalue_scopes: RefCell::new(NodeMap::new()),
896 terminating_scopes: RefCell::new(FnvHashSet::new()),
899 let mut visitor = RegionResolutionVisitor {
902 cx: Context { parent: None, var_parent: None }
904 visit::walk_crate(&mut visitor, krate);
909 pub fn resolve_inlined_item(sess: &Session,
910 region_maps: &RegionMaps,
911 item: &ast::InlinedItem) {
912 let mut visitor = RegionResolutionVisitor {
914 region_maps: region_maps,
915 cx: Context { parent: None, var_parent: None }
917 visit::walk_inlined_item(&mut visitor, item);