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;
31 use syntax::visit::{Visitor, FnKind};
33 /// CodeExtent represents a statically-describable extent that can be
34 /// used to bound the lifetime/region for values.
36 /// `Misc(node_id)`: Any AST node that has any extent at all has the
37 /// `Misc(node_id)` extent. Other variants represent special cases not
38 /// immediately derivable from the abstract syntax tree structure.
40 /// `DestructionScope(node_id)` represents the extent of destructors
41 /// implicitly-attached to `node_id` that run immediately after the
42 /// expression for `node_id` itself. Not every AST node carries a
43 /// `DestructionScope`, but those that are `terminating_scopes` do;
44 /// see discussion with `RegionMaps`.
46 /// `Remainder(BlockRemainder { block, statement_index })` represents
47 /// the extent of user code running immediately after the initializer
48 /// expression for the indexed statement, until the end of the block.
50 /// So: the following code can be broken down into the extents beneath:
52 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
57 /// +---------+ (R10.)
59 /// +----------+ (M8.)
60 /// +----------------------+ (R7.)
62 /// +----------+ (M5.)
63 /// +-----------------------------------+ (M4.)
64 /// +--------------------------------------------------+ (M3.)
66 /// +-----------------------------------------------------------+ (M1.)
68 /// (M1.): Misc extent of the whole `let a = ...;` statement.
69 /// (M2.): Misc extent of the `f()` expression.
70 /// (M3.): Misc extent of the `f().g(..)` expression.
71 /// (M4.): Misc extent of the block labelled `'b:`.
72 /// (M5.): Misc extent of the `let x = d();` statement
73 /// (D6.): DestructionScope for temporaries created during M5.
74 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
75 /// (M8.): Misc Extent of the `let y = d();` statement.
76 /// (D9.): DestructionScope for temporaries created during M8.
77 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
78 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
79 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
81 /// Note that while the above picture shows the destruction scopes
82 /// as following their corresponding misc extents, in the internal
83 /// data structures of the compiler the destruction scopes are
84 /// represented as enclosing parents. This is sound because we use the
85 /// enclosing parent relationship just to ensure that referenced
86 /// values live long enough; phrased another way, the starting point
87 /// of each range is not really the important thing in the above
88 /// picture, but rather the ending point.
90 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
91 /// placate the same deriving in `ty::FreeRegion`, but we may want to
92 /// actually attach a more meaningful ordering to scopes than the one
93 /// generated via deriving here.
94 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
95 RustcDecodable, Debug, Copy)]
99 // extent of parameters passed to a function or closure (they
101 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
103 // extent of destructors for temporaries of node-id
104 DestructionScope(ast::NodeId),
106 // extent of code following a `let id = expr;` binding in a block
107 Remainder(BlockRemainder)
110 /// extent of destructors for temporaries of node-id
111 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
112 RustcDecodable, Debug, Copy)]
113 pub struct DestructionScopeData {
114 pub node_id: ast::NodeId
117 impl DestructionScopeData {
118 pub fn new(node_id: ast::NodeId) -> DestructionScopeData {
119 DestructionScopeData { node_id: node_id }
121 pub fn to_code_extent(&self) -> CodeExtent {
122 CodeExtent::DestructionScope(self.node_id)
126 /// Represents a subscope of `block` for a binding that is introduced
127 /// by `block.stmts[first_statement_index]`. Such subscopes represent
128 /// a suffix of the block. Note that each subscope does not include
129 /// the initializer expression, if any, for the statement indexed by
130 /// `first_statement_index`.
132 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
134 /// * the subscope with `first_statement_index == 0` is scope of both
135 /// `a` and `b`; it does not include EXPR_1, but does include
136 /// everything after that first `let`. (If you want a scope that
137 /// includes EXPR_1 as well, then do not use `CodeExtent::Remainder`,
138 /// but instead another `CodeExtent` that encompasses the whole block,
139 /// e.g. `CodeExtent::Misc`.
141 /// * the subscope with `first_statement_index == 1` is scope of `c`,
142 /// and thus does not include EXPR_2, but covers the `...`.
143 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
144 RustcDecodable, Debug, Copy)]
145 pub struct BlockRemainder {
146 pub block: ast::NodeId,
147 pub first_statement_index: usize,
151 /// Creates a scope that represents the dynamic extent associated
153 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
154 CodeExtent::Misc(node_id)
157 /// Returns a node id associated with this scope.
159 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
160 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
161 pub fn node_id(&self) -> ast::NodeId {
163 CodeExtent::Misc(node_id) => node_id,
165 // These cases all return rough approximations to the
166 // precise extent denoted by `self`.
167 CodeExtent::Remainder(br) => br.block,
168 CodeExtent::DestructionScope(node_id) => node_id,
169 CodeExtent::ParameterScope { fn_id: _, body_id } => body_id,
173 /// Maps this scope to a potentially new one according to the
174 /// NodeId transformer `f_id`.
175 pub fn map_id<F>(&self, mut f_id: F) -> CodeExtent where
176 F: FnMut(ast::NodeId) -> ast::NodeId,
179 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
180 CodeExtent::Remainder(br) =>
181 CodeExtent::Remainder(BlockRemainder {
182 block: f_id(br.block), first_statement_index: br.first_statement_index }),
183 CodeExtent::DestructionScope(node_id) =>
184 CodeExtent::DestructionScope(f_id(node_id)),
185 CodeExtent::ParameterScope { fn_id, body_id } =>
186 CodeExtent::ParameterScope { fn_id: f_id(fn_id), body_id: f_id(body_id) },
190 /// Returns the span of this CodeExtent. Note that in general the
191 /// returned span may not correspond to the span of any node id in
193 pub fn span(&self, ast_map: &ast_map::Map) -> Option<Span> {
194 match ast_map.find(self.node_id()) {
195 Some(ast_map::NodeBlock(ref blk)) => {
197 CodeExtent::ParameterScope { .. } |
198 CodeExtent::Misc(_) |
199 CodeExtent::DestructionScope(_) => Some(blk.span),
201 CodeExtent::Remainder(r) => {
202 assert_eq!(r.block, blk.id);
203 // Want span for extent starting after the
204 // indexed statement and ending at end of
205 // `blk`; reuse span of `blk` and shift `lo`
206 // forward to end of indexed statement.
208 // (This is the special case aluded to in the
209 // doc-comment for this method)
210 let stmt_span = blk.stmts[r.first_statement_index].span;
211 Some(Span { lo: stmt_span.hi, ..blk.span })
215 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
216 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
217 Some(ast_map::NodeItem(ref item)) => Some(item.span),
218 Some(_) | None => None,
223 /// The region maps encode information about region relationships.
224 pub struct RegionMaps {
225 /// `scope_map` maps from a scope id to the enclosing scope id;
226 /// this is usually corresponding to the lexical nesting, though
227 /// in the case of closures the parent scope is the innermost
228 /// conditional expression or repeating block. (Note that the
229 /// enclosing scope id for the block associated with a closure is
230 /// the closure itself.)
231 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
233 /// `var_map` maps from a variable or binding id to the block in
234 /// which that variable is declared.
235 var_map: RefCell<NodeMap<CodeExtent>>,
237 /// `free_region_map` maps from a free region `a` to a list of
238 /// free regions `bs` such that `a <= b for all b in bs`
240 /// NB. the free region map is populated during type check as we
241 /// check each function. See the function `relate_free_regions`
242 /// for more information.
243 free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
245 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
246 /// larger than the default. The map goes from the expression id
247 /// to the cleanup scope id. For rvalues not present in this
248 /// table, the appropriate cleanup scope is the innermost
249 /// enclosing statement, conditional expression, or repeating
250 /// block (see `terminating_scopes`).
251 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
253 /// `terminating_scopes` is a set containing the ids of each
254 /// statement, or conditional/repeating expression. These scopes
255 /// are calling "terminating scopes" because, when attempting to
256 /// find the scope of a temporary, by default we search up the
257 /// enclosing scopes until we encounter the terminating scope. A
258 /// conditional/repeating expression is one which is not
259 /// guaranteed to execute exactly once upon entering the parent
260 /// scope. This could be because the expression only executes
261 /// conditionally, such as the expression `b` in `a && b`, or
262 /// because the expression may execute many times, such as a loop
263 /// body. The reason that we distinguish such expressions is that,
264 /// upon exiting the parent scope, we cannot statically know how
265 /// many times the expression executed, and thus if the expression
266 /// creates temporaries we cannot know statically how many such
267 /// temporaries we would have to cleanup. Therefore we ensure that
268 /// the temporaries never outlast the conditional/repeating
269 /// expression, preventing the need for dynamic checks and/or
270 /// arbitrary amounts of stack space.
271 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
273 /// Encodes the hierarchy of fn bodies. Every fn body (including
274 /// closures) forms its own distinct region hierarchy, rooted in
275 /// the block that is the fn body. This map points from the id of
276 /// that root block to the id of the root block for the enclosing
277 /// fn, if any. Thus the map structures the fn bodies into a
278 /// hierarchy based on their lexical mapping. This is used to
279 /// handle the relationships between regions in a fn and in a
280 /// closure defined by that fn. See the "Modeling closures"
281 /// section of the README in middle::infer::region_inference for
283 fn_tree: RefCell<NodeMap<ast::NodeId>>,
286 /// Carries the node id for the innermost block or match expression,
287 /// for building up the `var_map` which maps ids to the blocks in
288 /// which they were declared.
289 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
290 enum InnermostDeclaringBlock {
293 Statement(DeclaringStatementContext),
295 FnDecl { fn_id: ast::NodeId, body_id: ast::NodeId },
298 impl InnermostDeclaringBlock {
299 fn to_code_extent(&self) -> Option<CodeExtent> {
300 let extent = match *self {
301 InnermostDeclaringBlock::None => {
304 InnermostDeclaringBlock::FnDecl { fn_id, body_id } =>
305 CodeExtent::ParameterScope { fn_id: fn_id, body_id: body_id },
306 InnermostDeclaringBlock::Block(id) |
307 InnermostDeclaringBlock::Match(id) => CodeExtent::from_node_id(id),
308 InnermostDeclaringBlock::Statement(s) => s.to_code_extent(),
314 /// Contextual information for declarations introduced by a statement
315 /// (i.e. `let`). It carries node-id's for statement and enclosing
316 /// block both, as well as the statement's index within the block.
317 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
318 struct DeclaringStatementContext {
319 stmt_id: ast::NodeId,
320 block_id: ast::NodeId,
324 impl DeclaringStatementContext {
325 fn to_code_extent(&self) -> CodeExtent {
326 CodeExtent::Remainder(BlockRemainder {
327 block: self.block_id,
328 first_statement_index: self.stmt_index,
333 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
334 enum InnermostEnclosingExpr {
337 Statement(DeclaringStatementContext),
340 impl InnermostEnclosingExpr {
341 fn to_code_extent(&self) -> Option<CodeExtent> {
342 let extent = match *self {
343 InnermostEnclosingExpr::None => {
346 InnermostEnclosingExpr::Statement(s) =>
348 InnermostEnclosingExpr::Some(parent_id) =>
349 CodeExtent::from_node_id(parent_id),
355 #[derive(Debug, Copy, Clone)]
357 /// the root of the current region tree. This is typically the id
358 /// of the innermost fn body. Each fn forms its own disjoint tree
359 /// in the region hierarchy. These fn bodies are themselves
360 /// arranged into a tree. See the "Modeling closures" section of
361 /// the README in middle::infer::region_inference for more
363 root_id: Option<ast::NodeId>,
365 /// the scope that contains any new variables declared
366 var_parent: InnermostDeclaringBlock,
368 /// region parent of expressions etc
369 parent: InnermostEnclosingExpr,
372 struct RegionResolutionVisitor<'a> {
376 region_maps: &'a RegionMaps,
383 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
384 for (child, parent) in self.scope_map.borrow().iter() {
388 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
389 for (child, parent) in self.var_map.borrow().iter() {
393 pub fn each_encl_free_region<E>(&self, mut e:E) where E: FnMut(&FreeRegion, &FreeRegion) {
394 for (child, parents) in self.free_region_map.borrow().iter() {
395 for parent in parents.iter() {
400 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
401 for (child, parent) in self.rvalue_scopes.borrow().iter() {
405 pub fn each_terminating_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent) {
406 for scope in self.terminating_scopes.borrow().iter() {
411 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
412 match self.free_region_map.borrow_mut().get_mut(&sub) {
414 if !sups.iter().any(|x| x == &sup) {
422 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
423 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
426 /// Records that `sub_fn` is defined within `sup_fn`. These ids
427 /// should be the id of the block that is the fn body, which is
428 /// also the root of the region hierarchy for that fn.
429 fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
430 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
431 assert!(sub_fn != sup_fn);
432 let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
433 assert!(previous.is_none());
436 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
437 let fn_tree = self.fn_tree.borrow();
439 if sub_fn == sup_fn { return true; }
440 match fn_tree.get(&sub_fn) {
441 Some(&s) => { sub_fn = s; }
442 None => { return false; }
447 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
448 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
450 self.scope_map.borrow_mut().insert(sub, sup);
453 fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
454 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
455 assert!(var != lifetime.node_id());
456 self.var_map.borrow_mut().insert(var, lifetime);
459 fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
460 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
461 assert!(var != lifetime.node_id());
462 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
465 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
466 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
468 fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
469 debug!("record_terminating_scope(scope_id={:?})", scope_id);
470 self.terminating_scopes.borrow_mut().insert(scope_id);
473 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
474 //! Returns the narrowest scope that encloses `id`, if any.
475 self.scope_map.borrow().get(&id).cloned()
478 #[allow(dead_code)] // used in middle::cfg
479 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
480 //! Returns the narrowest scope that encloses `id`, if any.
481 match self.scope_map.borrow().get(&id) {
483 None => { panic!("no enclosing scope for id {:?}", id); }
487 /// Returns the lifetime of the local variable `var_id`
488 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
489 match self.var_map.borrow().get(&var_id) {
491 None => { panic!("no enclosing scope for id {:?}", var_id); }
495 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
496 //! Returns the scope when temp created by expr_id will be cleaned up
498 // check for a designated rvalue scope
499 match self.rvalue_scopes.borrow().get(&expr_id) {
501 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
507 // else, locate the innermost terminating scope
508 // if there's one. Static items, for instance, won't
509 // have an enclosing scope, hence no scope will be
511 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
513 None => { return None; }
516 while !self.terminating_scopes.borrow().contains(&id) {
517 match self.opt_encl_scope(id) {
522 debug!("temporary_scope({:?}) = None", expr_id);
527 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
531 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
532 //! Returns the lifetime of the variable `id`.
534 let scope = ty::ReScope(self.var_scope(id));
535 debug!("var_region({:?}) = {:?}", id, scope);
539 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
541 self.is_subscope_of(scope1, scope2) ||
542 self.is_subscope_of(scope2, scope1)
545 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
547 pub fn is_subscope_of(&self,
548 subscope: CodeExtent,
549 superscope: CodeExtent)
551 let mut s = subscope;
552 while superscope != s {
553 match self.scope_map.borrow().get(&s) {
555 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
556 subscope, superscope, s);
560 Some(&scope) => s = scope
564 debug!("is_subscope_of({:?}, {:?})=true",
565 subscope, superscope);
570 /// Determines whether two free regions have a subregion relationship
571 /// by walking the graph encoded in `free_region_map`. Note that
572 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
573 /// (that is, the user can give two different names to the same lifetime).
574 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
575 can_reach(&*self.free_region_map.borrow(), sub, sup)
578 /// Determines whether one region is a subregion of another. This is intended to run *after
579 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
580 pub fn is_subregion_of(&self,
581 sub_region: ty::Region,
582 super_region: ty::Region)
584 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
585 sub_region, super_region);
587 sub_region == super_region || {
588 match (sub_region, super_region) {
590 (_, ty::ReStatic) => {
594 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
595 self.is_subscope_of(sub_scope, super_scope)
598 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
599 self.is_subscope_of(sub_scope, fr.scope.to_code_extent())
602 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
603 self.sub_free_region(sub_fr, super_fr)
606 (ty::ReEarlyBound(data_a), ty::ReEarlyBound(data_b)) => {
607 // This case is used only to make sure that explicitly-
608 // specified `Self` types match the real self type in
609 // implementations. Yuck.
620 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
621 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
622 pub fn nearest_common_ancestor(&self,
626 if scope_a == scope_b { return scope_a; }
628 let a_ancestors = ancestors_of(self, scope_a);
629 let b_ancestors = ancestors_of(self, scope_b);
630 let mut a_index = a_ancestors.len() - 1;
631 let mut b_index = b_ancestors.len() - 1;
633 // Here, [ab]_ancestors is a vector going from narrow to broad.
634 // The end of each vector will be the item where the scope is
635 // defined; if there are any common ancestors, then the tails of
636 // the vector will be the same. So basically we want to walk
637 // backwards from the tail of each vector and find the first point
638 // where they diverge. If one vector is a suffix of the other,
639 // then the corresponding scope is a superscope of the other.
641 if a_ancestors[a_index] != b_ancestors[b_index] {
642 // In this case, the two regions belong to completely
643 // different functions. Compare those fn for lexical
644 // nesting. The reasoning behind this is subtle. See the
645 // "Modeling closures" section of the README in
646 // middle::infer::region_inference for more details.
647 let a_root_scope = a_ancestors[a_index];
648 let b_root_scope = a_ancestors[a_index];
649 return match (a_root_scope, b_root_scope) {
650 (CodeExtent::DestructionScope(a_root_id),
651 CodeExtent::DestructionScope(b_root_id)) => {
652 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
653 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
655 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
656 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
659 // neither fn encloses the other
664 // root ids are always Misc right now
671 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
672 // for all indices between a_index and the end of the array
673 if a_index == 0 { return scope_a; }
674 if b_index == 0 { return scope_b; }
677 if a_ancestors[a_index] != b_ancestors[b_index] {
678 return a_ancestors[a_index + 1];
682 fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec<CodeExtent> {
683 // debug!("ancestors_of(scope={:?})", scope);
684 let mut result = vec!(scope);
685 let mut scope = scope;
687 match this.scope_map.borrow().get(&scope) {
688 None => return result,
689 Some(&superscope) => {
690 result.push(superscope);
694 // debug!("ancestors_of_loop(scope={:?})", scope);
700 /// Records the current parent (if any) as the parent of `child_scope`.
701 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
702 child_scope: CodeExtent,
704 match visitor.cx.parent.to_code_extent() {
705 Some(parent_scope) =>
706 visitor.region_maps.record_encl_scope(child_scope, parent_scope),
711 /// Records the lifetime of a local variable as `cx.var_parent`
712 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
715 match visitor.cx.var_parent.to_code_extent() {
716 Some(parent_scope) =>
717 visitor.region_maps.record_var_scope(var_id, parent_scope),
719 // this can happen in extern fn declarations like
721 // extern fn isalnum(c: c_int) -> c_int
726 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
727 debug!("resolve_block(blk.id={:?})", blk.id);
729 let prev_cx = visitor.cx;
731 let blk_scope = CodeExtent::Misc(blk.id);
733 // If block was previously marked as a terminating scope during
734 // the recursive visit of its parent node in the AST, then we need
735 // to account for the destruction scope representing the extent of
736 // the destructors that run immediately after the the block itself
738 if visitor.region_maps.terminating_scopes.borrow().contains(&blk_scope) {
739 let dtor_scope = CodeExtent::DestructionScope(blk.id);
740 record_superlifetime(visitor, dtor_scope, blk.span);
741 visitor.region_maps.record_encl_scope(blk_scope, dtor_scope);
743 record_superlifetime(visitor, blk_scope, blk.span);
746 // We treat the tail expression in the block (if any) somewhat
747 // differently from the statements. The issue has to do with
748 // temporary lifetimes. Consider the following:
751 // let inner = ... (&bar()) ...;
753 // (... (&foo()) ...) // (the tail expression)
754 // }, other_argument());
756 // Each of the statements within the block is a terminating
757 // scope, and thus a temporary (e.g. the result of calling
758 // `bar()` in the initalizer expression for `let inner = ...;`)
759 // will be cleaned up immediately after its corresponding
760 // statement (i.e. `let inner = ...;`) executes.
762 // On the other hand, temporaries associated with evaluating the
763 // tail expression for the block are assigned lifetimes so that
764 // they will be cleaned up as part of the terminating scope
765 // *surrounding* the block expression. Here, the terminating
766 // scope for the block expression is the `quux(..)` call; so
767 // those temporaries will only be cleaned up *after* both
768 // `other_argument()` has run and also the call to `quux(..)`
769 // itself has returned.
771 visitor.cx = Context {
772 root_id: prev_cx.root_id,
773 var_parent: InnermostDeclaringBlock::Block(blk.id),
774 parent: InnermostEnclosingExpr::Some(blk.id),
778 // This block should be kept approximately in sync with
779 // `visit::walk_block`. (We manually walk the block, rather
780 // than call `walk_block`, in order to maintain precise
781 // `InnermostDeclaringBlock` information.)
783 for (i, statement) in blk.stmts.iter().enumerate() {
784 if let ast::StmtDecl(_, stmt_id) = statement.node {
785 // Each StmtDecl introduces a subscope for bindings
786 // introduced by the declaration; this subscope covers
787 // a suffix of the block . Each subscope in a block
788 // has the previous subscope in the block as a parent,
789 // except for the first such subscope, which has the
790 // block itself as a parent.
791 let declaring = DeclaringStatementContext {
796 record_superlifetime(
797 visitor, declaring.to_code_extent(), statement.span);
798 visitor.cx = Context {
799 root_id: prev_cx.root_id,
800 var_parent: InnermostDeclaringBlock::Statement(declaring),
801 parent: InnermostEnclosingExpr::Statement(declaring),
804 visitor.visit_stmt(&**statement)
806 visit::walk_expr_opt(visitor, &blk.expr)
809 visitor.cx = prev_cx;
812 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
813 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
814 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
818 let guard_scope = CodeExtent::from_node_id(expr.id);
819 visitor.region_maps.mark_as_terminating_scope(guard_scope);
824 visit::walk_arm(visitor, arm);
827 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
828 record_superlifetime(visitor, CodeExtent::from_node_id(pat.id), pat.span);
830 // If this is a binding (or maybe a binding, I'm too lazy to check
831 // the def map) then record the lifetime of that binding.
833 ast::PatIdent(..) => {
834 record_var_lifetime(visitor, pat.id, pat.span);
839 visit::walk_pat(visitor, pat);
842 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
843 let stmt_id = stmt_id(stmt);
844 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
846 let stmt_scope = CodeExtent::from_node_id(stmt_id);
848 // Every statement will clean up the temporaries created during
849 // execution of that statement. Therefore each statement has an
850 // associated destruction scope that represents the extent of the
851 // statement plus its destructors, and thus the extent for which
852 // regions referenced by the destructors need to survive.
853 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
854 let dtor_scope = CodeExtent::DestructionScope(stmt_id);
855 visitor.region_maps.record_encl_scope(stmt_scope, dtor_scope);
856 record_superlifetime(visitor, dtor_scope, stmt.span);
858 let prev_parent = visitor.cx.parent;
859 visitor.cx.parent = InnermostEnclosingExpr::Some(stmt_id);
860 visit::walk_stmt(visitor, stmt);
861 visitor.cx.parent = prev_parent;
864 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
865 debug!("resolve_expr(expr.id={:?})", expr.id);
867 let expr_scope = CodeExtent::Misc(expr.id);
868 // If expr was previously marked as a terminating scope during the
869 // recursive visit of its parent node in the AST, then we need to
870 // account for the destruction scope representing the extent of
871 // the destructors that run immediately after the the expression
873 if visitor.region_maps.terminating_scopes.borrow().contains(&expr_scope) {
874 let dtor_scope = CodeExtent::DestructionScope(expr.id);
875 record_superlifetime(visitor, dtor_scope, expr.span);
876 visitor.region_maps.record_encl_scope(expr_scope, dtor_scope);
878 record_superlifetime(visitor, expr_scope, expr.span);
881 let prev_cx = visitor.cx;
882 visitor.cx.parent = InnermostEnclosingExpr::Some(expr.id);
885 let region_maps = &mut visitor.region_maps;
886 let terminating = |e: &P<ast::Expr>| {
887 let scope = CodeExtent::from_node_id(e.id);
888 region_maps.mark_as_terminating_scope(scope)
890 let terminating_block = |b: &P<ast::Block>| {
891 let scope = CodeExtent::from_node_id(b.id);
892 region_maps.mark_as_terminating_scope(scope)
895 // Conditional or repeating scopes are always terminating
896 // scopes, meaning that temporaries cannot outlive them.
897 // This ensures fixed size stacks.
899 ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
900 ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
901 // For shortcircuiting operators, mark the RHS as a terminating
902 // scope since it only executes conditionally.
906 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
907 terminating_block(then);
908 terminating(otherwise);
911 ast::ExprIf(ref expr, ref then, None) => {
913 terminating_block(then);
916 ast::ExprLoop(ref body, _) => {
917 terminating_block(body);
920 ast::ExprWhile(ref expr, ref body, _) => {
922 terminating_block(body);
925 ast::ExprMatch(..) => {
926 visitor.cx.var_parent = InnermostDeclaringBlock::Match(expr.id);
929 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
930 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
931 // FIXME(#6268) Nested method calls
933 // The lifetimes for a call or method call look as follows:
941 // The idea is that call.callee_id represents *the time when
942 // the invoked function is actually running* and call.id
943 // represents *the time to prepare the arguments and make the
944 // call*. See the section "Borrows in Calls" borrowck/README.md
945 // for an extended explanation of why this distinction is
948 // record_superlifetime(new_cx, expr.callee_id);
955 visit::walk_expr(visitor, expr);
956 visitor.cx = prev_cx;
959 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
960 debug!("resolve_local(local.id={:?},local.init={:?})",
961 local.id,local.init.is_some());
963 // For convenience in trans, associate with the local-id the var
964 // scope that will be used for any bindings declared in this
966 let blk_scope = visitor.cx.var_parent.to_code_extent()
967 .unwrap_or_else(|| visitor.sess.span_bug(
968 local.span, "local without enclosing block"));
970 visitor.region_maps.record_var_scope(local.id, blk_scope);
972 // As an exception to the normal rules governing temporary
973 // lifetimes, initializers in a let have a temporary lifetime
974 // of the enclosing block. This means that e.g. a program
975 // like the following is legal:
977 // let ref x = HashMap::new();
979 // Because the hash map will be freed in the enclosing block.
981 // We express the rules more formally based on 3 grammars (defined
982 // fully in the helpers below that implement them):
984 // 1. `E&`, which matches expressions like `&<rvalue>` that
985 // own a pointer into the stack.
987 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
988 // y)` that produce ref bindings into the value they are
989 // matched against or something (at least partially) owned by
990 // the value they are matched against. (By partially owned,
991 // I mean that creating a binding into a ref-counted or managed value
992 // would still count.)
994 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
995 // based on rvalues like `foo().x[2].y`.
997 // A subexpression `<rvalue>` that appears in a let initializer
998 // `let pat [: ty] = expr` has an extended temporary lifetime if
999 // any of the following conditions are met:
1001 // A. `pat` matches `P&` and `expr` matches `ET`
1002 // (covers cases where `pat` creates ref bindings into an rvalue
1003 // produced by `expr`)
1004 // B. `ty` is a borrowed pointer and `expr` matches `ET`
1005 // (covers cases where coercion creates a borrow)
1006 // C. `expr` matches `E&`
1007 // (covers cases `expr` borrows an rvalue that is then assigned
1008 // to memory (at least partially) owned by the binding)
1010 // Here are some examples hopefully giving an intuition where each
1011 // rule comes into play and why:
1013 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1014 // would have an extended lifetime, but not `foo()`.
1016 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
1017 // would have an extended lifetime, but not `foo()`.
1019 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
1022 // In some cases, multiple rules may apply (though not to the same
1023 // rvalue). For example:
1025 // let ref x = [&a(), &b()];
1027 // Here, the expression `[...]` has an extended lifetime due to rule
1028 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1031 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
1035 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
1038 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
1040 if is_binding_pat(&*local.pat) || is_borrow {
1041 record_rvalue_scope(visitor, &**expr, blk_scope);
1048 visit::walk_local(visitor, local);
1050 /// True if `pat` match the `P&` nonterminal:
1053 /// | StructName { ..., P&, ... }
1054 /// | VariantName(..., P&, ...)
1055 /// | [ ..., P&, ... ]
1056 /// | ( ..., P&, ... )
1058 fn is_binding_pat(pat: &ast::Pat) -> bool {
1060 ast::PatIdent(ast::BindByRef(_), _, _) => true,
1062 ast::PatStruct(_, ref field_pats, _) => {
1063 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
1066 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
1067 pats1.iter().any(|p| is_binding_pat(&**p)) ||
1068 pats2.iter().any(|p| is_binding_pat(&**p)) ||
1069 pats3.iter().any(|p| is_binding_pat(&**p))
1072 ast::PatEnum(_, Some(ref subpats)) |
1073 ast::PatTup(ref subpats) => {
1074 subpats.iter().any(|p| is_binding_pat(&**p))
1077 ast::PatBox(ref subpat) => {
1078 is_binding_pat(&**subpat)
1085 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
1086 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
1088 ast::TyRptr(..) => true,
1093 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1096 /// | StructName { ..., f: E&, ... }
1097 /// | [ ..., E&, ... ]
1098 /// | ( ..., E&, ... )
1103 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1105 blk_id: CodeExtent) {
1107 ast::ExprAddrOf(_, ref subexpr) => {
1108 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1109 record_rvalue_scope(visitor, &**subexpr, blk_id);
1111 ast::ExprStruct(_, ref fields, _) => {
1112 for field in fields {
1113 record_rvalue_scope_if_borrow_expr(
1114 visitor, &*field.expr, blk_id);
1117 ast::ExprVec(ref subexprs) |
1118 ast::ExprTup(ref subexprs) => {
1119 for subexpr in subexprs {
1120 record_rvalue_scope_if_borrow_expr(
1121 visitor, &**subexpr, blk_id);
1124 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
1125 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1127 ast::ExprCast(ref subexpr, _) |
1128 ast::ExprParen(ref subexpr) => {
1129 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1131 ast::ExprBlock(ref block) => {
1133 Some(ref subexpr) => {
1134 record_rvalue_scope_if_borrow_expr(
1135 visitor, &**subexpr, blk_id);
1145 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1146 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1147 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1150 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1151 /// `<rvalue>` as `blk_id`:
1159 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1160 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1161 expr: &'a ast::Expr,
1162 blk_scope: CodeExtent) {
1163 let mut expr = expr;
1165 // Note: give all the expressions matching `ET` with the
1166 // extended temporary lifetime, not just the innermost rvalue,
1167 // because in trans if we must compile e.g. `*rvalue()`
1168 // into a temporary, we request the temporary scope of the
1169 // outer expression.
1170 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1173 ast::ExprAddrOf(_, ref subexpr) |
1174 ast::ExprUnary(ast::UnDeref, ref subexpr) |
1175 ast::ExprField(ref subexpr, _) |
1176 ast::ExprTupField(ref subexpr, _) |
1177 ast::ExprIndex(ref subexpr, _) |
1178 ast::ExprParen(ref subexpr) => {
1189 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
1190 // Items create a new outer block scope as far as we're concerned.
1191 let prev_cx = visitor.cx;
1192 visitor.cx = Context {
1194 var_parent: InnermostDeclaringBlock::None,
1195 parent: InnermostEnclosingExpr::None
1197 visit::walk_item(visitor, item);
1198 visitor.cx = prev_cx;
1201 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1207 debug!("region::resolve_fn(id={:?}, \
1212 visitor.sess.codemap().span_to_string(sp),
1216 // This scope covers the function body, which includes the
1217 // bindings introduced by let statements as well as temporaries
1218 // created by the fn's tail expression (if any). It does *not*
1219 // include the fn parameters (see below).
1220 let body_scope = CodeExtent::from_node_id(body.id);
1221 visitor.region_maps.mark_as_terminating_scope(body_scope);
1223 let dtor_scope = CodeExtent::DestructionScope(body.id);
1224 visitor.region_maps.record_encl_scope(body_scope, dtor_scope);
1226 let fn_decl_scope = CodeExtent::ParameterScope { fn_id: id, body_id: body.id };
1227 visitor.region_maps.record_encl_scope(dtor_scope, fn_decl_scope);
1229 record_superlifetime(visitor, fn_decl_scope, body.span);
1231 if let Some(root_id) = visitor.cx.root_id {
1232 visitor.region_maps.record_fn_parent(body.id, root_id);
1235 let outer_cx = visitor.cx;
1237 // The arguments and `self` are parented to the fn.
1238 visitor.cx = Context {
1239 root_id: Some(body.id),
1240 parent: InnermostEnclosingExpr::None,
1241 var_parent: InnermostDeclaringBlock::FnDecl {
1242 fn_id: id, body_id: body.id
1245 visit::walk_fn_decl(visitor, decl);
1247 // The body of the every fn is a root scope.
1248 visitor.cx = Context {
1249 root_id: Some(body.id),
1250 parent: InnermostEnclosingExpr::None,
1251 var_parent: InnermostDeclaringBlock::None
1253 visitor.visit_block(body);
1255 // Restore context we had at the start.
1256 visitor.cx = outer_cx;
1259 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1261 fn visit_block(&mut self, b: &Block) {
1262 resolve_block(self, b);
1265 fn visit_item(&mut self, i: &Item) {
1266 resolve_item(self, i);
1269 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1270 b: &'v Block, s: Span, n: NodeId) {
1271 resolve_fn(self, fk, fd, b, s, n);
1273 fn visit_arm(&mut self, a: &Arm) {
1274 resolve_arm(self, a);
1276 fn visit_pat(&mut self, p: &Pat) {
1277 resolve_pat(self, p);
1279 fn visit_stmt(&mut self, s: &Stmt) {
1280 resolve_stmt(self, s);
1282 fn visit_expr(&mut self, ex: &Expr) {
1283 resolve_expr(self, ex);
1285 fn visit_local(&mut self, l: &Local) {
1286 resolve_local(self, l);
1290 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
1291 let maps = RegionMaps {
1292 scope_map: RefCell::new(FnvHashMap()),
1293 var_map: RefCell::new(NodeMap()),
1294 free_region_map: RefCell::new(FnvHashMap()),
1295 rvalue_scopes: RefCell::new(NodeMap()),
1296 terminating_scopes: RefCell::new(FnvHashSet()),
1297 fn_tree: RefCell::new(NodeMap()),
1300 let mut visitor = RegionResolutionVisitor {
1305 parent: InnermostEnclosingExpr::None,
1306 var_parent: InnermostDeclaringBlock::None,
1309 visit::walk_crate(&mut visitor, krate);
1314 pub fn resolve_inlined_item(sess: &Session,
1315 region_maps: &RegionMaps,
1316 item: &ast::InlinedItem) {
1317 let mut visitor = RegionResolutionVisitor {
1319 region_maps: region_maps,
1322 parent: InnermostEnclosingExpr::None,
1323 var_parent: InnermostDeclaringBlock::None
1326 visit::walk_inlined_item(&mut visitor, item);