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`
19 use metadata::inline::InlinedItem;
20 use front::map as ast_map;
22 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
23 use middle::ty::{self, Ty};
25 use std::cell::RefCell;
26 use std::collections::hash_map::Entry;
29 use syntax::codemap::{self, Span};
30 use syntax::ast::{self, NodeId};
33 use rustc_front::visit::{self, Visitor, FnKind};
34 use rustc_front::hir::{Block, Item, FnDecl, Arm, Pat, Stmt, Expr, Local};
35 use rustc_front::util::stmt_id;
37 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
38 RustcDecodable, Copy)]
39 pub struct CodeExtent(u32);
41 impl fmt::Debug for CodeExtent {
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 try!(write!(f, "CodeExtent({:?}", self.0));
45 try!(ty::tls::with_opt(|opt_tcx| {
46 if let Some(tcx) = opt_tcx {
47 let data = tcx.region_maps.code_extents.borrow()[self.0 as usize];
48 try!(write!(f, "/{:?}", data));
57 /// The root of everything. I should be using NonZero or profiling
58 /// instead of this (probably).
59 pub const ROOT_CODE_EXTENT : CodeExtent = CodeExtent(0);
60 /// A placeholder used in trans to stand for real code extents
61 pub const DUMMY_CODE_EXTENT : CodeExtent = CodeExtent(1);
63 /// CodeExtent represents a statically-describable extent that can be
64 /// used to bound the lifetime/region for values.
66 /// `Misc(node_id)`: Any AST node that has any extent at all has the
67 /// `Misc(node_id)` extent. Other variants represent special cases not
68 /// immediately derivable from the abstract syntax tree structure.
70 /// `DestructionScope(node_id)` represents the extent of destructors
71 /// implicitly-attached to `node_id` that run immediately after the
72 /// expression for `node_id` itself. Not every AST node carries a
73 /// `DestructionScope`, but those that are `terminating_scopes` do;
74 /// see discussion with `RegionMaps`.
76 /// `Remainder(BlockRemainder { block, statement_index })` represents
77 /// the extent of user code running immediately after the initializer
78 /// expression for the indexed statement, until the end of the block.
80 /// So: the following code can be broken down into the extents beneath:
82 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
87 /// +---------+ (R10.)
89 /// +----------+ (M8.)
90 /// +----------------------+ (R7.)
92 /// +----------+ (M5.)
93 /// +-----------------------------------+ (M4.)
94 /// +--------------------------------------------------+ (M3.)
96 /// +-----------------------------------------------------------+ (M1.)
98 /// (M1.): Misc extent of the whole `let a = ...;` statement.
99 /// (M2.): Misc extent of the `f()` expression.
100 /// (M3.): Misc extent of the `f().g(..)` expression.
101 /// (M4.): Misc extent of the block labelled `'b:`.
102 /// (M5.): Misc extent of the `let x = d();` statement
103 /// (D6.): DestructionScope for temporaries created during M5.
104 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
105 /// (M8.): Misc Extent of the `let y = d();` statement.
106 /// (D9.): DestructionScope for temporaries created during M8.
107 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
108 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
109 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
111 /// Note that while the above picture shows the destruction scopes
112 /// as following their corresponding misc extents, in the internal
113 /// data structures of the compiler the destruction scopes are
114 /// represented as enclosing parents. This is sound because we use the
115 /// enclosing parent relationship just to ensure that referenced
116 /// values live long enough; phrased another way, the starting point
117 /// of each range is not really the important thing in the above
118 /// picture, but rather the ending point.
120 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
121 /// placate the same deriving in `ty::FreeRegion`, but we may want to
122 /// actually attach a more meaningful ordering to scopes than the one
123 /// generated via deriving here.
124 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy)]
125 pub enum CodeExtentData {
128 // extent of parameters passed to a function or closure (they
130 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
132 // extent of destructors for temporaries of node-id
133 DestructionScope(ast::NodeId),
135 // extent of code following a `let id = expr;` binding in a block
136 Remainder(BlockRemainder)
139 /// extent of destructors for temporaries of node-id
140 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
141 RustcDecodable, Debug, Copy)]
142 pub struct DestructionScopeData {
143 pub node_id: ast::NodeId
146 impl DestructionScopeData {
147 pub fn new(node_id: ast::NodeId) -> DestructionScopeData {
148 DestructionScopeData { node_id: node_id }
150 pub fn to_code_extent(&self, region_maps: &RegionMaps) -> CodeExtent {
151 region_maps.lookup_code_extent(
152 CodeExtentData::DestructionScope(self.node_id))
156 /// Represents a subscope of `block` for a binding that is introduced
157 /// by `block.stmts[first_statement_index]`. Such subscopes represent
158 /// a suffix of the block. Note that each subscope does not include
159 /// the initializer expression, if any, for the statement indexed by
160 /// `first_statement_index`.
162 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
164 /// * the subscope with `first_statement_index == 0` is scope of both
165 /// `a` and `b`; it does not include EXPR_1, but does include
166 /// everything after that first `let`. (If you want a scope that
167 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
168 /// but instead another `CodeExtent` that encompasses the whole block,
169 /// e.g. `CodeExtentData::Misc`.
171 /// * the subscope with `first_statement_index == 1` is scope of `c`,
172 /// and thus does not include EXPR_2, but covers the `...`.
173 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
174 RustcDecodable, Debug, Copy)]
175 pub struct BlockRemainder {
176 pub block: ast::NodeId,
177 pub first_statement_index: u32,
180 impl CodeExtentData {
181 /// Returns a node id associated with this scope.
183 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
184 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
185 pub fn node_id(&self) -> ast::NodeId {
187 CodeExtentData::Misc(node_id) => node_id,
189 // These cases all return rough approximations to the
190 // precise extent denoted by `self`.
191 CodeExtentData::Remainder(br) => br.block,
192 CodeExtentData::DestructionScope(node_id) => node_id,
193 CodeExtentData::ParameterScope { fn_id: _, body_id } => body_id,
200 fn into_option(self) -> Option<CodeExtent> {
201 if self == ROOT_CODE_EXTENT {
207 pub fn node_id(&self, region_maps: &RegionMaps) -> ast::NodeId {
208 region_maps.code_extent_data(*self).node_id()
211 /// Returns the span of this CodeExtent. Note that in general the
212 /// returned span may not correspond to the span of any node id in
214 pub fn span(&self, region_maps: &RegionMaps, ast_map: &ast_map::Map) -> Option<Span> {
215 match ast_map.find(self.node_id(region_maps)) {
216 Some(ast_map::NodeBlock(ref blk)) => {
217 match region_maps.code_extent_data(*self) {
218 CodeExtentData::ParameterScope { .. } |
219 CodeExtentData::Misc(_) |
220 CodeExtentData::DestructionScope(_) => Some(blk.span),
222 CodeExtentData::Remainder(r) => {
223 assert_eq!(r.block, blk.id);
224 // Want span for extent starting after the
225 // indexed statement and ending at end of
226 // `blk`; reuse span of `blk` and shift `lo`
227 // forward to end of indexed statement.
229 // (This is the special case aluded to in the
230 // doc-comment for this method)
231 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
232 Some(Span { lo: stmt_span.hi, ..blk.span })
236 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
237 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
238 Some(ast_map::NodeItem(ref item)) => Some(item.span),
239 Some(_) | None => None,
244 /// The region maps encode information about region relationships.
245 pub struct RegionMaps {
246 code_extents: RefCell<Vec<CodeExtentData>>,
247 code_extent_interner: RefCell<FnvHashMap<CodeExtentData, CodeExtent>>,
248 /// `scope_map` maps from a scope id to the enclosing scope id;
249 /// this is usually corresponding to the lexical nesting, though
250 /// in the case of closures the parent scope is the innermost
251 /// conditional expression or repeating block. (Note that the
252 /// enclosing scope id for the block associated with a closure is
253 /// the closure itself.)
254 scope_map: RefCell<Vec<CodeExtent>>,
256 /// `var_map` maps from a variable or binding id to the block in
257 /// which that variable is declared.
258 var_map: RefCell<NodeMap<CodeExtent>>,
260 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
261 /// larger than the default. The map goes from the expression id
262 /// to the cleanup scope id. For rvalues not present in this
263 /// table, the appropriate cleanup scope is the innermost
264 /// enclosing statement, conditional expression, or repeating
265 /// block (see `terminating_scopes`).
266 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
268 /// Encodes the hierarchy of fn bodies. Every fn body (including
269 /// closures) forms its own distinct region hierarchy, rooted in
270 /// the block that is the fn body. This map points from the id of
271 /// that root block to the id of the root block for the enclosing
272 /// fn, if any. Thus the map structures the fn bodies into a
273 /// hierarchy based on their lexical mapping. This is used to
274 /// handle the relationships between regions in a fn and in a
275 /// closure defined by that fn. See the "Modeling closures"
276 /// section of the README in middle::infer::region_inference for
278 fn_tree: RefCell<NodeMap<ast::NodeId>>,
281 #[derive(Debug, Copy, Clone)]
283 /// the root of the current region tree. This is typically the id
284 /// of the innermost fn body. Each fn forms its own disjoint tree
285 /// in the region hierarchy. These fn bodies are themselves
286 /// arranged into a tree. See the "Modeling closures" section of
287 /// the README in middle::infer::region_inference for more
289 root_id: Option<ast::NodeId>,
291 /// the scope that contains any new variables declared
292 var_parent: CodeExtent,
294 /// region parent of expressions etc
298 struct RegionResolutionVisitor<'a> {
302 region_maps: &'a RegionMaps,
306 /// `terminating_scopes` is a set containing the ids of each
307 /// statement, or conditional/repeating expression. These scopes
308 /// are calling "terminating scopes" because, when attempting to
309 /// find the scope of a temporary, by default we search up the
310 /// enclosing scopes until we encounter the terminating scope. A
311 /// conditional/repeating expression is one which is not
312 /// guaranteed to execute exactly once upon entering the parent
313 /// scope. This could be because the expression only executes
314 /// conditionally, such as the expression `b` in `a && b`, or
315 /// because the expression may execute many times, such as a loop
316 /// body. The reason that we distinguish such expressions is that,
317 /// upon exiting the parent scope, we cannot statically know how
318 /// many times the expression executed, and thus if the expression
319 /// creates temporaries we cannot know statically how many such
320 /// temporaries we would have to cleanup. Therefore we ensure that
321 /// the temporaries never outlast the conditional/repeating
322 /// expression, preventing the need for dynamic checks and/or
323 /// arbitrary amounts of stack space. Terminating scopes end
324 /// up being contained in a DestructionScope that contains the
325 /// destructor's execution.
326 terminating_scopes: NodeSet
331 /// create a bogus code extent for the regions in astencode types. Nobody
332 /// really cares about the contents of these.
333 pub fn bogus_code_extent(&self, e: CodeExtentData) -> CodeExtent {
334 self.intern_code_extent(e, DUMMY_CODE_EXTENT)
336 pub fn lookup_code_extent(&self, e: CodeExtentData) -> CodeExtent {
337 match self.code_extent_interner.borrow().get(&e) {
339 None => panic!("unknown code extent {:?}", e)
342 pub fn node_extent(&self, n: ast::NodeId) -> CodeExtent {
343 self.lookup_code_extent(CodeExtentData::Misc(n))
345 // Returns the code extent for an item - the destruction scope.
346 pub fn item_extent(&self, n: ast::NodeId) -> CodeExtent {
347 self.lookup_code_extent(CodeExtentData::DestructionScope(n))
349 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
350 self.code_extent_interner.borrow().get(&CodeExtentData::DestructionScope(n)).cloned()
352 pub fn intern_code_extent(&self,
354 parent: CodeExtent) -> CodeExtent {
355 match self.code_extent_interner.borrow_mut().entry(e) {
356 Entry::Occupied(o) => {
357 // this can happen when the bogus code extents from tydecode
358 // have (bogus) NodeId-s that overlap items created during
360 // We probably shouldn't be creating bogus code extents
363 if parent == DUMMY_CODE_EXTENT {
364 info!("CodeExtent({}) = {:?} [parent={}] BOGUS!",
367 assert_eq!(self.scope_map.borrow()[idx.0 as usize],
369 info!("CodeExtent({}) = {:?} [parent={}] RECLAIMED!",
371 self.scope_map.borrow_mut()[idx.0 as usize] = parent;
375 Entry::Vacant(v) => {
376 if self.code_extents.borrow().len() > 0xffffffffusize {
377 unreachable!() // should pass a sess,
378 // but this isn't the only place
380 let idx = CodeExtent(self.code_extents.borrow().len() as u32);
381 info!("CodeExtent({}) = {:?} [parent={}]", idx.0, e, parent.0);
382 self.code_extents.borrow_mut().push(e);
383 self.scope_map.borrow_mut().push(parent);
388 pub fn intern_node(&self,
390 parent: CodeExtent) -> CodeExtent {
391 self.intern_code_extent(CodeExtentData::Misc(n), parent)
393 pub fn code_extent_data(&self, e: CodeExtent) -> CodeExtentData {
394 self.code_extents.borrow()[e.0 as usize]
396 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
397 for child_id in 1..self.code_extents.borrow().len() {
398 let child = CodeExtent(child_id as u32);
399 if let Some(parent) = self.opt_encl_scope(child) {
404 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
405 for (child, parent) in self.var_map.borrow().iter() {
409 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
410 for (child, parent) in self.rvalue_scopes.borrow().iter() {
414 /// Records that `sub_fn` is defined within `sup_fn`. These ids
415 /// should be the id of the block that is the fn body, which is
416 /// also the root of the region hierarchy for that fn.
417 fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
418 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
419 assert!(sub_fn != sup_fn);
420 let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
421 assert!(previous.is_none());
424 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
425 let fn_tree = self.fn_tree.borrow();
427 if sub_fn == sup_fn { return true; }
428 match fn_tree.get(&sub_fn) {
429 Some(&s) => { sub_fn = s; }
430 None => { return false; }
435 fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
436 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
437 assert!(var != lifetime.node_id(self));
438 self.var_map.borrow_mut().insert(var, lifetime);
441 fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
442 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
443 assert!(var != lifetime.node_id(self));
444 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
447 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
448 //! Returns the narrowest scope that encloses `id`, if any.
449 self.scope_map.borrow()[id.0 as usize].into_option()
452 #[allow(dead_code)] // used in middle::cfg
453 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
454 //! Returns the narrowest scope that encloses `id`, if any.
455 self.opt_encl_scope(id).unwrap()
458 /// Returns the lifetime of the local variable `var_id`
459 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
460 match self.var_map.borrow().get(&var_id) {
462 None => { panic!("no enclosing scope for id {:?}", var_id); }
466 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
467 //! Returns the scope when temp created by expr_id will be cleaned up
469 // check for a designated rvalue scope
470 match self.rvalue_scopes.borrow().get(&expr_id) {
472 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
478 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
479 let code_extents: &[CodeExtentData] = &self.code_extents.borrow();
481 // else, locate the innermost terminating scope
482 // if there's one. Static items, for instance, won't
483 // have an enclosing scope, hence no scope will be
485 let expr_extent = self.node_extent(expr_id);
486 // For some reason, the expr's scope itself is skipped here.
487 let mut id = match scope_map[expr_extent.0 as usize].into_option() {
492 while let Some(p) = scope_map[id.0 as usize].into_option() {
493 match code_extents[p.0 as usize] {
494 CodeExtentData::DestructionScope(..) => {
495 debug!("temporary_scope({:?}) = {:?} [enclosing]",
503 debug!("temporary_scope({:?}) = None", expr_id);
507 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
508 //! Returns the lifetime of the variable `id`.
510 let scope = ty::ReScope(self.var_scope(id));
511 debug!("var_region({:?}) = {:?}", id, scope);
515 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
517 self.is_subscope_of(scope1, scope2) ||
518 self.is_subscope_of(scope2, scope1)
521 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
523 pub fn is_subscope_of(&self,
524 subscope: CodeExtent,
525 superscope: CodeExtent)
527 let mut s = subscope;
528 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
529 while superscope != s {
530 match self.opt_encl_scope(s) {
532 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
533 subscope, superscope, s);
536 Some(scope) => s = scope
540 debug!("is_subscope_of({:?}, {:?})=true",
541 subscope, superscope);
546 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
547 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
548 pub fn nearest_common_ancestor(&self,
552 if scope_a == scope_b { return scope_a; }
554 let mut a_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
555 let mut a_vec: Vec<CodeExtent> = vec![];
556 let mut b_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
557 let mut b_vec: Vec<CodeExtent> = vec![];
558 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
559 let a_ancestors = ancestors_of(scope_map,
560 scope_a, &mut a_buf, &mut a_vec);
561 let b_ancestors = ancestors_of(scope_map,
562 scope_b, &mut b_buf, &mut b_vec);
563 let mut a_index = a_ancestors.len() - 1;
564 let mut b_index = b_ancestors.len() - 1;
566 // Here, [ab]_ancestors is a vector going from narrow to broad.
567 // The end of each vector will be the item where the scope is
568 // defined; if there are any common ancestors, then the tails of
569 // the vector will be the same. So basically we want to walk
570 // backwards from the tail of each vector and find the first point
571 // where they diverge. If one vector is a suffix of the other,
572 // then the corresponding scope is a superscope of the other.
574 if a_ancestors[a_index] != b_ancestors[b_index] {
575 // In this case, the two regions belong to completely
576 // different functions. Compare those fn for lexical
577 // nesting. The reasoning behind this is subtle. See the
578 // "Modeling closures" section of the README in
579 // middle::infer::region_inference for more details.
580 let a_root_scope = self.code_extent_data(a_ancestors[a_index]);
581 let b_root_scope = self.code_extent_data(a_ancestors[a_index]);
582 return match (a_root_scope, b_root_scope) {
583 (CodeExtentData::DestructionScope(a_root_id),
584 CodeExtentData::DestructionScope(b_root_id)) => {
585 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
586 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
588 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
589 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
592 // neither fn encloses the other
597 // root ids are always Misc right now
604 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
605 // for all indices between a_index and the end of the array
606 if a_index == 0 { return scope_a; }
607 if b_index == 0 { return scope_b; }
610 if a_ancestors[a_index] != b_ancestors[b_index] {
611 return a_ancestors[a_index + 1];
615 fn ancestors_of<'a>(scope_map: &[CodeExtent],
617 buf: &'a mut [CodeExtent; 32],
618 vec: &'a mut Vec<CodeExtent>) -> &'a [CodeExtent] {
619 // debug!("ancestors_of(scope={:?})", scope);
620 let mut scope = scope;
625 match scope_map[scope.0 as usize].into_option() {
626 Some(superscope) => scope = superscope,
627 _ => return &buf[..i+1]
632 *vec = Vec::with_capacity(64);
636 match scope_map[scope.0 as usize].into_option() {
637 Some(superscope) => scope = superscope,
645 /// Records the lifetime of a local variable as `cx.var_parent`
646 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
649 match visitor.cx.var_parent {
650 ROOT_CODE_EXTENT => {
651 // this can happen in extern fn declarations like
653 // extern fn isalnum(c: c_int) -> c_int
656 visitor.region_maps.record_var_scope(var_id, parent_scope),
660 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &hir::Block) {
661 debug!("resolve_block(blk.id={:?})", blk.id);
663 let prev_cx = visitor.cx;
664 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
666 // We treat the tail expression in the block (if any) somewhat
667 // differently from the statements. The issue has to do with
668 // temporary lifetimes. Consider the following:
671 // let inner = ... (&bar()) ...;
673 // (... (&foo()) ...) // (the tail expression)
674 // }, other_argument());
676 // Each of the statements within the block is a terminating
677 // scope, and thus a temporary (e.g. the result of calling
678 // `bar()` in the initalizer expression for `let inner = ...;`)
679 // will be cleaned up immediately after its corresponding
680 // statement (i.e. `let inner = ...;`) executes.
682 // On the other hand, temporaries associated with evaluating the
683 // tail expression for the block are assigned lifetimes so that
684 // they will be cleaned up as part of the terminating scope
685 // *surrounding* the block expression. Here, the terminating
686 // scope for the block expression is the `quux(..)` call; so
687 // those temporaries will only be cleaned up *after* both
688 // `other_argument()` has run and also the call to `quux(..)`
689 // itself has returned.
691 visitor.cx = Context {
692 root_id: prev_cx.root_id,
693 var_parent: block_extent,
694 parent: block_extent,
698 // This block should be kept approximately in sync with
699 // `visit::walk_block`. (We manually walk the block, rather
700 // than call `walk_block`, in order to maintain precise
701 // index information.)
703 for (i, statement) in blk.stmts.iter().enumerate() {
704 if let hir::StmtDecl(..) = statement.node {
705 // Each StmtDecl introduces a subscope for bindings
706 // introduced by the declaration; this subscope covers
707 // a suffix of the block . Each subscope in a block
708 // has the previous subscope in the block as a parent,
709 // except for the first such subscope, which has the
710 // block itself as a parent.
711 let stmt_extent = visitor.new_code_extent(
712 CodeExtentData::Remainder(BlockRemainder {
714 first_statement_index: i as u32
717 visitor.cx = Context {
718 root_id: prev_cx.root_id,
719 var_parent: stmt_extent,
723 visitor.visit_stmt(&**statement)
725 walk_list!(visitor, visit_expr, &blk.expr);
728 visitor.cx = prev_cx;
731 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &hir::Arm) {
732 visitor.terminating_scopes.insert(arm.body.id);
734 if let Some(ref expr) = arm.guard {
735 visitor.terminating_scopes.insert(expr.id);
738 visit::walk_arm(visitor, arm);
741 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &hir::Pat) {
742 visitor.new_node_extent(pat.id);
744 // If this is a binding (or maybe a binding, I'm too lazy to check
745 // the def map) then record the lifetime of that binding.
747 hir::PatIdent(..) => {
748 record_var_lifetime(visitor, pat.id, pat.span);
753 visit::walk_pat(visitor, pat);
756 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &hir::Stmt) {
757 let stmt_id = stmt_id(stmt);
758 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
760 // Every statement will clean up the temporaries created during
761 // execution of that statement. Therefore each statement has an
762 // associated destruction scope that represents the extent of the
763 // statement plus its destructors, and thus the extent for which
764 // regions referenced by the destructors need to survive.
765 visitor.terminating_scopes.insert(stmt_id);
766 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
768 let prev_parent = visitor.cx.parent;
769 visitor.cx.parent = stmt_extent;
770 visit::walk_stmt(visitor, stmt);
771 visitor.cx.parent = prev_parent;
774 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &hir::Expr) {
775 debug!("resolve_expr(expr.id={:?})", expr.id);
777 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
778 let prev_cx = visitor.cx;
779 visitor.cx.parent = expr_extent;
782 let terminating_scopes = &mut visitor.terminating_scopes;
783 let mut terminating = |id: ast::NodeId| {
784 terminating_scopes.insert(id);
787 // Conditional or repeating scopes are always terminating
788 // scopes, meaning that temporaries cannot outlive them.
789 // This ensures fixed size stacks.
791 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
792 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
793 // For shortcircuiting operators, mark the RHS as a terminating
794 // scope since it only executes conditionally.
798 hir::ExprIf(_, ref then, Some(ref otherwise)) => {
799 terminating(then.id);
800 terminating(otherwise.id);
803 hir::ExprIf(ref expr, ref then, None) => {
804 terminating(expr.id);
805 terminating(then.id);
808 hir::ExprLoop(ref body, _) => {
809 terminating(body.id);
812 hir::ExprWhile(ref expr, ref body, _) => {
813 terminating(expr.id);
814 terminating(body.id);
817 hir::ExprMatch(..) => {
818 visitor.cx.var_parent = expr_extent;
821 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
822 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
823 // FIXME(#6268) Nested method calls
825 // The lifetimes for a call or method call look as follows:
833 // The idea is that call.callee_id represents *the time when
834 // the invoked function is actually running* and call.id
835 // represents *the time to prepare the arguments and make the
836 // call*. See the section "Borrows in Calls" borrowck/README.md
837 // for an extended explanation of why this distinction is
840 // record_superlifetime(new_cx, expr.callee_id);
847 visit::walk_expr(visitor, expr);
848 visitor.cx = prev_cx;
851 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &hir::Local) {
852 debug!("resolve_local(local.id={:?},local.init={:?})",
853 local.id,local.init.is_some());
855 // For convenience in trans, associate with the local-id the var
856 // scope that will be used for any bindings declared in this
858 let blk_scope = visitor.cx.var_parent;
859 assert!(blk_scope != ROOT_CODE_EXTENT); // locals must be within a block
860 visitor.region_maps.record_var_scope(local.id, blk_scope);
862 // As an exception to the normal rules governing temporary
863 // lifetimes, initializers in a let have a temporary lifetime
864 // of the enclosing block. This means that e.g. a program
865 // like the following is legal:
867 // let ref x = HashMap::new();
869 // Because the hash map will be freed in the enclosing block.
871 // We express the rules more formally based on 3 grammars (defined
872 // fully in the helpers below that implement them):
874 // 1. `E&`, which matches expressions like `&<rvalue>` that
875 // own a pointer into the stack.
877 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
878 // y)` that produce ref bindings into the value they are
879 // matched against or something (at least partially) owned by
880 // the value they are matched against. (By partially owned,
881 // I mean that creating a binding into a ref-counted or managed value
882 // would still count.)
884 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
885 // based on rvalues like `foo().x[2].y`.
887 // A subexpression `<rvalue>` that appears in a let initializer
888 // `let pat [: ty] = expr` has an extended temporary lifetime if
889 // any of the following conditions are met:
891 // A. `pat` matches `P&` and `expr` matches `ET`
892 // (covers cases where `pat` creates ref bindings into an rvalue
893 // produced by `expr`)
894 // B. `ty` is a borrowed pointer and `expr` matches `ET`
895 // (covers cases where coercion creates a borrow)
896 // C. `expr` matches `E&`
897 // (covers cases `expr` borrows an rvalue that is then assigned
898 // to memory (at least partially) owned by the binding)
900 // Here are some examples hopefully giving an intuition where each
901 // rule comes into play and why:
903 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
904 // would have an extended lifetime, but not `foo()`.
906 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
907 // would have an extended lifetime, but not `foo()`.
909 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
912 // In some cases, multiple rules may apply (though not to the same
913 // rvalue). For example:
915 // let ref x = [&a(), &b()];
917 // Here, the expression `[...]` has an extended lifetime due to rule
918 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
921 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
925 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
928 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
930 if is_binding_pat(&*local.pat) || is_borrow {
931 record_rvalue_scope(visitor, &**expr, blk_scope);
938 visit::walk_local(visitor, local);
940 /// True if `pat` match the `P&` nonterminal:
943 /// | StructName { ..., P&, ... }
944 /// | VariantName(..., P&, ...)
945 /// | [ ..., P&, ... ]
946 /// | ( ..., P&, ... )
948 fn is_binding_pat(pat: &hir::Pat) -> bool {
950 hir::PatIdent(hir::BindByRef(_), _, _) => true,
952 hir::PatStruct(_, ref field_pats, _) => {
953 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
956 hir::PatVec(ref pats1, ref pats2, ref pats3) => {
957 pats1.iter().any(|p| is_binding_pat(&**p)) ||
958 pats2.iter().any(|p| is_binding_pat(&**p)) ||
959 pats3.iter().any(|p| is_binding_pat(&**p))
962 hir::PatEnum(_, Some(ref subpats)) |
963 hir::PatTup(ref subpats) => {
964 subpats.iter().any(|p| is_binding_pat(&**p))
967 hir::PatBox(ref subpat) => {
968 is_binding_pat(&**subpat)
975 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
976 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
978 hir::TyRptr(..) => true,
983 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
986 /// | StructName { ..., f: E&, ... }
987 /// | [ ..., E&, ... ]
988 /// | ( ..., E&, ... )
993 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
995 blk_id: CodeExtent) {
997 hir::ExprAddrOf(_, ref subexpr) => {
998 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
999 record_rvalue_scope(visitor, &**subexpr, blk_id);
1001 hir::ExprStruct(_, ref fields, _) => {
1002 for field in fields {
1003 record_rvalue_scope_if_borrow_expr(
1004 visitor, &*field.expr, blk_id);
1007 hir::ExprVec(ref subexprs) |
1008 hir::ExprTup(ref subexprs) => {
1009 for subexpr in subexprs {
1010 record_rvalue_scope_if_borrow_expr(
1011 visitor, &**subexpr, blk_id);
1014 hir::ExprCast(ref subexpr, _) => {
1015 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1017 hir::ExprBlock(ref block) => {
1019 Some(ref subexpr) => {
1020 record_rvalue_scope_if_borrow_expr(
1021 visitor, &**subexpr, blk_id);
1031 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1032 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1033 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1036 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1037 /// `<rvalue>` as `blk_id`:
1045 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1046 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1047 expr: &'a hir::Expr,
1048 blk_scope: CodeExtent) {
1049 let mut expr = expr;
1051 // Note: give all the expressions matching `ET` with the
1052 // extended temporary lifetime, not just the innermost rvalue,
1053 // because in trans if we must compile e.g. `*rvalue()`
1054 // into a temporary, we request the temporary scope of the
1055 // outer expression.
1056 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1059 hir::ExprAddrOf(_, ref subexpr) |
1060 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1061 hir::ExprField(ref subexpr, _) |
1062 hir::ExprTupField(ref subexpr, _) |
1063 hir::ExprIndex(ref subexpr, _) => {
1074 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &hir::Item) {
1075 // Items create a new outer block scope as far as we're concerned.
1076 let prev_cx = visitor.cx;
1077 let prev_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1078 visitor.cx = Context {
1080 var_parent: ROOT_CODE_EXTENT,
1081 parent: ROOT_CODE_EXTENT
1083 visit::walk_item(visitor, item);
1084 visitor.create_item_scope_if_needed(item.id);
1085 visitor.cx = prev_cx;
1086 visitor.terminating_scopes = prev_ts;
1089 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1095 debug!("region::resolve_fn(id={:?}, \
1100 visitor.sess.codemap().span_to_string(sp),
1104 let fn_decl_scope = visitor.new_code_extent(
1105 CodeExtentData::ParameterScope { fn_id: id, body_id: body.id });
1107 if let Some(root_id) = visitor.cx.root_id {
1108 visitor.region_maps.record_fn_parent(body.id, root_id);
1111 let outer_cx = visitor.cx;
1112 let outer_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1113 visitor.terminating_scopes.insert(body.id);
1115 // The arguments and `self` are parented to the fn.
1116 visitor.cx = Context {
1117 root_id: Some(body.id),
1118 parent: ROOT_CODE_EXTENT,
1119 var_parent: fn_decl_scope,
1122 visit::walk_fn_decl(visitor, decl);
1123 visit::walk_fn_kind(visitor, kind);
1125 // The body of the every fn is a root scope.
1126 visitor.cx = Context {
1127 root_id: Some(body.id),
1128 parent: fn_decl_scope,
1129 var_parent: fn_decl_scope
1131 visitor.visit_block(body);
1133 // Restore context we had at the start.
1134 visitor.cx = outer_cx;
1135 visitor.terminating_scopes = outer_ts;
1138 impl<'a> RegionResolutionVisitor<'a> {
1139 /// Records the current parent (if any) as the parent of `child_scope`.
1140 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent {
1141 self.region_maps.intern_code_extent(child_scope, self.cx.parent)
1144 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent {
1145 self.new_code_extent(CodeExtentData::Misc(child_scope))
1148 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent {
1149 // If node was previously marked as a terminating scope during the
1150 // recursive visit of its parent node in the AST, then we need to
1151 // account for the destruction scope representing the extent of
1152 // the destructors that run immediately after it completes.
1153 if self.terminating_scopes.contains(&id) {
1154 let ds = self.new_code_extent(
1155 CodeExtentData::DestructionScope(id));
1156 self.region_maps.intern_node(id, ds)
1158 self.new_node_extent(id)
1162 fn create_item_scope_if_needed(&mut self, id: ast::NodeId) {
1163 // create a region for the destruction scope - this is needed
1164 // for constructing parameter environments based on the item.
1165 // functions put their destruction scopes *inside* their parameter
1167 let scope = CodeExtentData::DestructionScope(id);
1168 if !self.region_maps.code_extent_interner.borrow().contains_key(&scope) {
1169 self.region_maps.intern_code_extent(scope, ROOT_CODE_EXTENT);
1174 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1175 fn visit_block(&mut self, b: &Block) {
1176 resolve_block(self, b);
1179 fn visit_item(&mut self, i: &Item) {
1180 resolve_item(self, i);
1183 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
1184 visit::walk_impl_item(self, ii);
1185 self.create_item_scope_if_needed(ii.id);
1188 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
1189 visit::walk_trait_item(self, ti);
1190 self.create_item_scope_if_needed(ti.id);
1193 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1194 b: &'v Block, s: Span, n: NodeId) {
1195 resolve_fn(self, fk, fd, b, s, n);
1197 fn visit_arm(&mut self, a: &Arm) {
1198 resolve_arm(self, a);
1200 fn visit_pat(&mut self, p: &Pat) {
1201 resolve_pat(self, p);
1203 fn visit_stmt(&mut self, s: &Stmt) {
1204 resolve_stmt(self, s);
1206 fn visit_expr(&mut self, ex: &Expr) {
1207 resolve_expr(self, ex);
1209 fn visit_local(&mut self, l: &Local) {
1210 resolve_local(self, l);
1214 pub fn resolve_crate(sess: &Session, krate: &hir::Crate) -> RegionMaps {
1215 let maps = RegionMaps {
1216 code_extents: RefCell::new(vec![]),
1217 code_extent_interner: RefCell::new(FnvHashMap()),
1218 scope_map: RefCell::new(vec![]),
1219 var_map: RefCell::new(NodeMap()),
1220 rvalue_scopes: RefCell::new(NodeMap()),
1221 fn_tree: RefCell::new(NodeMap()),
1223 let root_extent = maps.bogus_code_extent(
1224 CodeExtentData::DestructionScope(ast::DUMMY_NODE_ID));
1225 assert_eq!(root_extent, ROOT_CODE_EXTENT);
1226 let bogus_extent = maps.bogus_code_extent(
1227 CodeExtentData::Misc(ast::DUMMY_NODE_ID));
1228 assert_eq!(bogus_extent, DUMMY_CODE_EXTENT);
1230 let mut visitor = RegionResolutionVisitor {
1235 parent: ROOT_CODE_EXTENT,
1236 var_parent: ROOT_CODE_EXTENT
1238 terminating_scopes: NodeSet()
1240 visit::walk_crate(&mut visitor, krate);
1245 pub fn resolve_inlined_item(sess: &Session,
1246 region_maps: &RegionMaps,
1247 item: &InlinedItem) {
1248 let mut visitor = RegionResolutionVisitor {
1250 region_maps: region_maps,
1253 parent: ROOT_CODE_EXTENT,
1254 var_parent: ROOT_CODE_EXTENT
1256 terminating_scopes: NodeSet()
1258 item.visit(&mut visitor);