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 // NOTE(stage0) remove import after a snapshot
27 use std::hash::{Hash};
28 use syntax::codemap::Span;
29 use syntax::{ast, visit};
30 use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local};
31 use syntax::ast_util::{stmt_id};
32 use syntax::visit::{Visitor, FnKind};
34 /// CodeExtent represents a statically-describable extent that can be
35 /// used to bound the lifetime/region for values.
37 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
38 /// placate the same deriving in `ty::FreeRegion`, but we may want to
39 /// actually attach a more meaningful ordering to scopes than the one
40 /// generated via deriving here.
41 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
42 RustcDecodable, Show, Copy)]
48 /// Creates a scope that represents the dynamic extent associated
50 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
51 CodeExtent::Misc(node_id)
54 /// Returns a node id associated with this scope.
56 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
57 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
58 pub fn node_id(&self) -> ast::NodeId {
60 CodeExtent::Misc(node_id) => node_id,
64 /// Maps this scope to a potentially new one according to the
65 /// NodeId transformer `f_id`.
66 pub fn map_id<F>(&self, f_id: F) -> CodeExtent where
67 F: FnOnce(ast::NodeId) -> ast::NodeId,
70 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
75 /// The region maps encode information about region relationships.
77 /// - `scope_map` maps from a scope id to the enclosing scope id; this is
78 /// usually corresponding to the lexical nesting, though in the case of
79 /// closures the parent scope is the innermost conditional expression or repeating
82 /// - `var_map` maps from a variable or binding id to the block in which
83 /// that variable is declared.
85 /// - `free_region_map` maps from a free region `a` to a list of free
86 /// regions `bs` such that `a <= b for all b in bs`
87 /// - the free region map is populated during type check as we check
88 /// each function. See the function `relate_free_regions` for
91 /// - `rvalue_scopes` includes entries for those expressions whose cleanup
92 /// scope is larger than the default. The map goes from the expression
93 /// id to the cleanup scope id. For rvalues not present in this table,
94 /// the appropriate cleanup scope is the innermost enclosing statement,
95 /// conditional expression, or repeating block (see `terminating_scopes`).
97 /// - `terminating_scopes` is a set containing the ids of each statement,
98 /// or conditional/repeating expression. These scopes are calling "terminating
99 /// scopes" because, when attempting to find the scope of a temporary, by
100 /// default we search up the enclosing scopes until we encounter the
101 /// terminating scope. A conditional/repeating
102 /// expression is one which is not guaranteed to execute exactly once
103 /// upon entering the parent scope. This could be because the expression
104 /// only executes conditionally, such as the expression `b` in `a && b`,
105 /// or because the expression may execute many times, such as a loop
106 /// body. The reason that we distinguish such expressions is that, upon
107 /// exiting the parent scope, we cannot statically know how many times
108 /// the expression executed, and thus if the expression creates
109 /// temporaries we cannot know statically how many such temporaries we
110 /// would have to cleanup. Therefore we ensure that the temporaries never
111 /// outlast the conditional/repeating expression, preventing the need
112 /// for dynamic checks and/or arbitrary amounts of stack space.
113 pub struct RegionMaps {
114 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
115 var_map: RefCell<NodeMap<CodeExtent>>,
116 free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
117 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
118 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
123 var_parent: Option<ast::NodeId>,
125 // Innermost enclosing expression
126 parent: Option<ast::NodeId>,
129 struct RegionResolutionVisitor<'a> {
133 region_maps: &'a RegionMaps,
140 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
141 match self.free_region_map.borrow_mut().get_mut(&sub) {
143 if !sups.iter().any(|x| x == &sup) {
151 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
152 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
155 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
156 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
158 self.scope_map.borrow_mut().insert(sub, sup);
161 pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
162 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
163 assert!(var != lifetime.node_id());
164 self.var_map.borrow_mut().insert(var, lifetime);
167 pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
168 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
169 assert!(var != lifetime.node_id());
170 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
173 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
174 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
176 pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
177 debug!("record_terminating_scope(scope_id={:?})", scope_id);
178 self.terminating_scopes.borrow_mut().insert(scope_id);
181 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
182 //! Returns the narrowest scope that encloses `id`, if any.
183 self.scope_map.borrow().get(&id).map(|x| *x)
186 #[allow(dead_code)] // used in middle::cfg
187 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
188 //! Returns the narrowest scope that encloses `id`, if any.
189 match self.scope_map.borrow().get(&id) {
191 None => { panic!("no enclosing scope for id {:?}", id); }
195 /// Returns the lifetime of the local variable `var_id`
196 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
197 match self.var_map.borrow().get(&var_id) {
199 None => { panic!("no enclosing scope for id {:?}", var_id); }
203 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
204 //! Returns the scope when temp created by expr_id will be cleaned up
206 // check for a designated rvalue scope
207 match self.rvalue_scopes.borrow().get(&expr_id) {
209 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
215 // else, locate the innermost terminating scope
216 // if there's one. Static items, for instance, won't
217 // have an enclosing scope, hence no scope will be
219 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
221 None => { return None; }
224 while !self.terminating_scopes.borrow().contains(&id) {
225 match self.opt_encl_scope(id) {
230 debug!("temporary_scope({:?}) = None", expr_id);
235 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
239 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
240 //! Returns the lifetime of the variable `id`.
242 let scope = ty::ReScope(self.var_scope(id));
243 debug!("var_region({:?}) = {:?}", id, scope);
247 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
249 self.is_subscope_of(scope1, scope2) ||
250 self.is_subscope_of(scope2, scope1)
253 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
255 pub fn is_subscope_of(&self,
256 subscope: CodeExtent,
257 superscope: CodeExtent)
259 let mut s = subscope;
260 while superscope != s {
261 match self.scope_map.borrow().get(&s) {
263 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
264 subscope, superscope, s);
268 Some(&scope) => s = scope
272 debug!("is_subscope_of({:?}, {:?})=true",
273 subscope, superscope);
278 /// Determines whether two free regions have a subregion relationship
279 /// by walking the graph encoded in `free_region_map`. Note that
280 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
281 /// (that is, the user can give two different names to the same lifetime).
282 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
283 can_reach(&*self.free_region_map.borrow(), sub, sup)
286 /// Determines whether one region is a subregion of another. This is intended to run *after
287 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
288 pub fn is_subregion_of(&self,
289 sub_region: ty::Region,
290 super_region: ty::Region)
292 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
293 sub_region, super_region);
295 sub_region == super_region || {
296 match (sub_region, super_region) {
298 (_, ty::ReStatic) => {
302 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
303 self.is_subscope_of(sub_scope, super_scope)
306 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
307 self.is_subscope_of(sub_scope, fr.scope)
310 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
311 self.sub_free_region(sub_fr, super_fr)
314 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
315 ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
316 // This case is used only to make sure that explicitly-
317 // specified `Self` types match the real self type in
319 param_id_a == param_id_b &&
320 param_space_a == param_space_b &&
331 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
332 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
333 pub fn nearest_common_ancestor(&self,
336 -> Option<CodeExtent> {
337 if scope_a == scope_b { return Some(scope_a); }
339 let a_ancestors = ancestors_of(self, scope_a);
340 let b_ancestors = ancestors_of(self, scope_b);
341 let mut a_index = a_ancestors.len() - 1u;
342 let mut b_index = b_ancestors.len() - 1u;
344 // Here, ~[ab]_ancestors is a vector going from narrow to broad.
345 // The end of each vector will be the item where the scope is
346 // defined; if there are any common ancestors, then the tails of
347 // the vector will be the same. So basically we want to walk
348 // backwards from the tail of each vector and find the first point
349 // where they diverge. If one vector is a suffix of the other,
350 // then the corresponding scope is a superscope of the other.
352 if a_ancestors[a_index] != b_ancestors[b_index] {
357 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
358 // for all indices between a_index and the end of the array
359 if a_index == 0u { return Some(scope_a); }
360 if b_index == 0u { return Some(scope_b); }
363 if a_ancestors[a_index] != b_ancestors[b_index] {
364 return Some(a_ancestors[a_index + 1]);
368 fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
370 // debug!("ancestors_of(scope={:?})", scope);
371 let mut result = vec!(scope);
372 let mut scope = scope;
374 match this.scope_map.borrow().get(&scope) {
375 None => return result,
376 Some(&superscope) => {
377 result.push(superscope);
381 // debug!("ancestors_of_loop(scope={:?})", scope);
387 /// Records the current parent (if any) as the parent of `child_id`.
388 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
389 child_id: ast::NodeId,
391 match visitor.cx.parent {
393 let child_scope = CodeExtent::from_node_id(child_id);
394 let parent_scope = CodeExtent::from_node_id(parent_id);
395 visitor.region_maps.record_encl_scope(child_scope, parent_scope);
401 /// Records the lifetime of a local variable as `cx.var_parent`
402 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
405 match visitor.cx.var_parent {
407 let parent_scope = CodeExtent::from_node_id(parent_id);
408 visitor.region_maps.record_var_scope(var_id, parent_scope);
411 // this can happen in extern fn declarations like
413 // extern fn isalnum(c: c_int) -> c_int
418 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
419 debug!("resolve_block(blk.id={:?})", blk.id);
421 // Record the parent of this block.
422 record_superlifetime(visitor, blk.id, blk.span);
424 // We treat the tail expression in the block (if any) somewhat
425 // differently from the statements. The issue has to do with
426 // temporary lifetimes. If the user writes:
433 let prev_cx = visitor.cx;
434 visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)};
435 visit::walk_block(visitor, blk);
436 visitor.cx = prev_cx;
439 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
440 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
441 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
445 let guard_scope = CodeExtent::from_node_id(expr.id);
446 visitor.region_maps.mark_as_terminating_scope(guard_scope);
451 visit::walk_arm(visitor, arm);
454 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
455 record_superlifetime(visitor, pat.id, pat.span);
457 // If this is a binding (or maybe a binding, I'm too lazy to check
458 // the def map) then record the lifetime of that binding.
460 ast::PatIdent(..) => {
461 record_var_lifetime(visitor, pat.id, pat.span);
466 visit::walk_pat(visitor, pat);
469 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
470 let stmt_id = stmt_id(stmt);
471 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
473 let stmt_scope = CodeExtent::from_node_id(stmt_id);
474 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
475 record_superlifetime(visitor, stmt_id, stmt.span);
477 let prev_parent = visitor.cx.parent;
478 visitor.cx.parent = Some(stmt_id);
479 visit::walk_stmt(visitor, stmt);
480 visitor.cx.parent = prev_parent;
483 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
484 debug!("resolve_expr(expr.id={:?})", expr.id);
486 record_superlifetime(visitor, expr.id, expr.span);
488 let prev_cx = visitor.cx;
489 visitor.cx.parent = Some(expr.id);
492 let region_maps = &mut visitor.region_maps;
493 let terminating = |&: id| {
494 let scope = CodeExtent::from_node_id(id);
495 region_maps.mark_as_terminating_scope(scope)
498 // Conditional or repeating scopes are always terminating
499 // scopes, meaning that temporaries cannot outlive them.
500 // This ensures fixed size stacks.
502 ast::ExprBinary(ast::BiAnd, _, ref r) |
503 ast::ExprBinary(ast::BiOr, _, ref r) => {
504 // For shortcircuiting operators, mark the RHS as a terminating
505 // scope since it only executes conditionally.
509 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
510 terminating(then.id);
511 terminating(otherwise.id);
514 ast::ExprIf(ref expr, ref then, None) => {
515 terminating(expr.id);
516 terminating(then.id);
519 ast::ExprLoop(ref body, _) => {
520 terminating(body.id);
523 ast::ExprWhile(ref expr, ref body, _) => {
524 terminating(expr.id);
525 terminating(body.id);
528 ast::ExprForLoop(ref _pat, ref _head, ref body, _) => {
529 terminating(body.id);
531 // The variable parent of everything inside (most importantly, the
532 // pattern) is the body.
533 visitor.cx.var_parent = Some(body.id);
536 ast::ExprMatch(..) => {
537 visitor.cx.var_parent = Some(expr.id);
540 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
541 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
542 // FIXME(#6268) Nested method calls
544 // The lifetimes for a call or method call look as follows:
552 // The idea is that call.callee_id represents *the time when
553 // the invoked function is actually running* and call.id
554 // represents *the time to prepare the arguments and make the
555 // call*. See the section "Borrows in Calls" borrowck/doc.rs
556 // for an extended explanation of why this distinction is
559 // record_superlifetime(new_cx, expr.callee_id);
566 visit::walk_expr(visitor, expr);
567 visitor.cx = prev_cx;
570 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
571 debug!("resolve_local(local.id={:?},local.init={:?})",
572 local.id,local.init.is_some());
574 let blk_id = match visitor.cx.var_parent {
577 visitor.sess.span_bug(
579 "local without enclosing block");
583 // For convenience in trans, associate with the local-id the var
584 // scope that will be used for any bindings declared in this
586 let blk_scope = CodeExtent::from_node_id(blk_id);
587 visitor.region_maps.record_var_scope(local.id, blk_scope);
589 // As an exception to the normal rules governing temporary
590 // lifetimes, initializers in a let have a temporary lifetime
591 // of the enclosing block. This means that e.g. a program
592 // like the following is legal:
594 // let ref x = HashMap::new();
596 // Because the hash map will be freed in the enclosing block.
598 // We express the rules more formally based on 3 grammars (defined
599 // fully in the helpers below that implement them):
601 // 1. `E&`, which matches expressions like `&<rvalue>` that
602 // own a pointer into the stack.
604 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
605 // y)` that produce ref bindings into the value they are
606 // matched against or something (at least partially) owned by
607 // the value they are matched against. (By partially owned,
608 // I mean that creating a binding into a ref-counted or managed value
609 // would still count.)
611 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
612 // based on rvalues like `foo().x[2].y`.
614 // A subexpression `<rvalue>` that appears in a let initializer
615 // `let pat [: ty] = expr` has an extended temporary lifetime if
616 // any of the following conditions are met:
618 // A. `pat` matches `P&` and `expr` matches `ET`
619 // (covers cases where `pat` creates ref bindings into an rvalue
620 // produced by `expr`)
621 // B. `ty` is a borrowed pointer and `expr` matches `ET`
622 // (covers cases where coercion creates a borrow)
623 // C. `expr` matches `E&`
624 // (covers cases `expr` borrows an rvalue that is then assigned
625 // to memory (at least partially) owned by the binding)
627 // Here are some examples hopefully giving an intuition where each
628 // rule comes into play and why:
630 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
631 // would have an extended lifetime, but not `foo()`.
633 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
634 // would have an extended lifetime, but not `foo()`.
636 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
639 // In some cases, multiple rules may apply (though not to the same
640 // rvalue). For example:
642 // let ref x = [&a(), &b()];
644 // Here, the expression `[...]` has an extended lifetime due to rule
645 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
648 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
652 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
655 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
657 if is_binding_pat(&*local.pat) || is_borrow {
658 record_rvalue_scope(visitor, &**expr, blk_scope);
665 visit::walk_local(visitor, local);
667 /// True if `pat` match the `P&` nonterminal:
670 /// | StructName { ..., P&, ... }
671 /// | VariantName(..., P&, ...)
672 /// | [ ..., P&, ... ]
673 /// | ( ..., P&, ... )
675 fn is_binding_pat(pat: &ast::Pat) -> bool {
677 ast::PatIdent(ast::BindByRef(_), _, _) => true,
679 ast::PatStruct(_, ref field_pats, _) => {
680 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
683 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
684 pats1.iter().any(|p| is_binding_pat(&**p)) ||
685 pats2.iter().any(|p| is_binding_pat(&**p)) ||
686 pats3.iter().any(|p| is_binding_pat(&**p))
689 ast::PatEnum(_, Some(ref subpats)) |
690 ast::PatTup(ref subpats) => {
691 subpats.iter().any(|p| is_binding_pat(&**p))
694 ast::PatBox(ref subpat) => {
695 is_binding_pat(&**subpat)
702 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
703 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
705 ast::TyRptr(..) => true,
710 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
713 /// | StructName { ..., f: E&, ... }
714 /// | [ ..., E&, ... ]
715 /// | ( ..., E&, ... )
720 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
722 blk_id: CodeExtent) {
724 ast::ExprAddrOf(_, ref subexpr) => {
725 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
726 record_rvalue_scope(visitor, &**subexpr, blk_id);
728 ast::ExprStruct(_, ref fields, _) => {
729 for field in fields.iter() {
730 record_rvalue_scope_if_borrow_expr(
731 visitor, &*field.expr, blk_id);
734 ast::ExprVec(ref subexprs) |
735 ast::ExprTup(ref subexprs) => {
736 for subexpr in subexprs.iter() {
737 record_rvalue_scope_if_borrow_expr(
738 visitor, &**subexpr, blk_id);
741 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
742 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
744 ast::ExprCast(ref subexpr, _) |
745 ast::ExprParen(ref subexpr) => {
746 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
748 ast::ExprBlock(ref block) => {
750 Some(ref subexpr) => {
751 record_rvalue_scope_if_borrow_expr(
752 visitor, &**subexpr, blk_id);
762 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
763 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
764 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
767 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
768 /// `<rvalue>` as `blk_id`:
776 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
777 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
779 blk_scope: CodeExtent) {
782 // Note: give all the expressions matching `ET` with the
783 // extended temporary lifetime, not just the innermost rvalue,
784 // because in trans if we must compile e.g. `*rvalue()`
785 // into a temporary, we request the temporary scope of the
787 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
790 ast::ExprAddrOf(_, ref subexpr) |
791 ast::ExprUnary(ast::UnDeref, ref subexpr) |
792 ast::ExprField(ref subexpr, _) |
793 ast::ExprTupField(ref subexpr, _) |
794 ast::ExprIndex(ref subexpr, _) |
795 ast::ExprParen(ref subexpr) => {
806 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
807 // Items create a new outer block scope as far as we're concerned.
808 let prev_cx = visitor.cx;
809 visitor.cx = Context {var_parent: None, parent: None};
810 visit::walk_item(visitor, item);
811 visitor.cx = prev_cx;
814 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
820 debug!("region::resolve_fn(id={:?}, \
825 visitor.sess.codemap().span_to_string(sp),
829 let body_scope = CodeExtent::from_node_id(body.id);
830 visitor.region_maps.mark_as_terminating_scope(body_scope);
832 let outer_cx = visitor.cx;
834 // The arguments and `self` are parented to the body of the fn.
835 visitor.cx = Context { parent: Some(body.id),
836 var_parent: Some(body.id) };
837 visit::walk_fn_decl(visitor, decl);
839 // The body of the fn itself is either a root scope (top-level fn)
840 // or it continues with the inherited scope (closures).
842 visit::FkItemFn(..) | visit::FkMethod(..) => {
843 visitor.cx = Context { parent: None, var_parent: None };
844 visitor.visit_block(body);
845 visitor.cx = outer_cx;
847 visit::FkFnBlock(..) => {
848 // FIXME(#3696) -- at present we are place the closure body
849 // within the region hierarchy exactly where it appears lexically.
850 // This is wrong because the closure may live longer
851 // than the enclosing expression. We should probably fix this,
852 // but the correct fix is a bit subtle, and I am also not sure
853 // that the present approach is unsound -- it may not permit
854 // any illegal programs. See issue for more details.
855 visitor.cx = outer_cx;
856 visitor.visit_block(body);
861 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
863 fn visit_block(&mut self, b: &Block) {
864 resolve_block(self, b);
867 fn visit_item(&mut self, i: &Item) {
868 resolve_item(self, i);
871 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
872 b: &'v Block, s: Span, n: NodeId) {
873 resolve_fn(self, fk, fd, b, s, n);
875 fn visit_arm(&mut self, a: &Arm) {
876 resolve_arm(self, a);
878 fn visit_pat(&mut self, p: &Pat) {
879 resolve_pat(self, p);
881 fn visit_stmt(&mut self, s: &Stmt) {
882 resolve_stmt(self, s);
884 fn visit_expr(&mut self, ex: &Expr) {
885 resolve_expr(self, ex);
887 fn visit_local(&mut self, l: &Local) {
888 resolve_local(self, l);
892 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
893 let maps = RegionMaps {
894 scope_map: RefCell::new(FnvHashMap()),
895 var_map: RefCell::new(NodeMap()),
896 free_region_map: RefCell::new(FnvHashMap()),
897 rvalue_scopes: RefCell::new(NodeMap()),
898 terminating_scopes: RefCell::new(FnvHashSet()),
901 let mut visitor = RegionResolutionVisitor {
904 cx: Context { parent: None, var_parent: None }
906 visit::walk_crate(&mut visitor, krate);
911 pub fn resolve_inlined_item(sess: &Session,
912 region_maps: &RegionMaps,
913 item: &ast::InlinedItem) {
914 let mut visitor = RegionResolutionVisitor {
916 region_maps: region_maps,
917 cx: Context { parent: None, var_parent: None }
919 visit::walk_inlined_item(&mut visitor, item);