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;
28 use syntax::codemap::{self, Span};
29 use syntax::ast::{self, NodeId};
32 use rustc_front::visit::{self, Visitor, FnKind};
33 use rustc_front::hir::{Block, Item, FnDecl, Arm, Pat, Stmt, Expr, Local};
34 use rustc_front::util::stmt_id;
36 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
37 RustcDecodable, Debug, Copy)]
38 pub struct CodeExtent(u32);
40 /// The root of everything. I should be using NonZero or profiling
41 /// instead of this (probably).
42 pub const ROOT_CODE_EXTENT : CodeExtent = CodeExtent(0);
43 /// A placeholder used in trans to stand for real code extents
44 pub const DUMMY_CODE_EXTENT : CodeExtent = CodeExtent(1);
46 /// CodeExtent represents a statically-describable extent that can be
47 /// used to bound the lifetime/region for values.
49 /// `Misc(node_id)`: Any AST node that has any extent at all has the
50 /// `Misc(node_id)` extent. Other variants represent special cases not
51 /// immediately derivable from the abstract syntax tree structure.
53 /// `DestructionScope(node_id)` represents the extent of destructors
54 /// implicitly-attached to `node_id` that run immediately after the
55 /// expression for `node_id` itself. Not every AST node carries a
56 /// `DestructionScope`, but those that are `terminating_scopes` do;
57 /// see discussion with `RegionMaps`.
59 /// `Remainder(BlockRemainder { block, statement_index })` represents
60 /// the extent of user code running immediately after the initializer
61 /// expression for the indexed statement, until the end of the block.
63 /// So: the following code can be broken down into the extents beneath:
65 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
70 /// +---------+ (R10.)
72 /// +----------+ (M8.)
73 /// +----------------------+ (R7.)
75 /// +----------+ (M5.)
76 /// +-----------------------------------+ (M4.)
77 /// +--------------------------------------------------+ (M3.)
79 /// +-----------------------------------------------------------+ (M1.)
81 /// (M1.): Misc extent of the whole `let a = ...;` statement.
82 /// (M2.): Misc extent of the `f()` expression.
83 /// (M3.): Misc extent of the `f().g(..)` expression.
84 /// (M4.): Misc extent of the block labelled `'b:`.
85 /// (M5.): Misc extent of the `let x = d();` statement
86 /// (D6.): DestructionScope for temporaries created during M5.
87 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
88 /// (M8.): Misc Extent of the `let y = d();` statement.
89 /// (D9.): DestructionScope for temporaries created during M8.
90 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
91 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
92 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
94 /// Note that while the above picture shows the destruction scopes
95 /// as following their corresponding misc extents, in the internal
96 /// data structures of the compiler the destruction scopes are
97 /// represented as enclosing parents. This is sound because we use the
98 /// enclosing parent relationship just to ensure that referenced
99 /// values live long enough; phrased another way, the starting point
100 /// of each range is not really the important thing in the above
101 /// picture, but rather the ending point.
103 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
104 /// placate the same deriving in `ty::FreeRegion`, but we may want to
105 /// actually attach a more meaningful ordering to scopes than the one
106 /// generated via deriving here.
107 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy)]
108 pub enum CodeExtentData {
111 // extent of parameters passed to a function or closure (they
113 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
115 // extent of destructors for temporaries of node-id
116 DestructionScope(ast::NodeId),
118 // extent of code following a `let id = expr;` binding in a block
119 Remainder(BlockRemainder)
122 /// extent of destructors for temporaries of node-id
123 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
124 RustcDecodable, Debug, Copy)]
125 pub struct DestructionScopeData {
126 pub node_id: ast::NodeId
129 impl DestructionScopeData {
130 pub fn new(node_id: ast::NodeId) -> DestructionScopeData {
131 DestructionScopeData { node_id: node_id }
133 pub fn to_code_extent(&self, region_maps: &RegionMaps) -> CodeExtent {
134 region_maps.lookup_code_extent(
135 CodeExtentData::DestructionScope(self.node_id))
139 /// Represents a subscope of `block` for a binding that is introduced
140 /// by `block.stmts[first_statement_index]`. Such subscopes represent
141 /// a suffix of the block. Note that each subscope does not include
142 /// the initializer expression, if any, for the statement indexed by
143 /// `first_statement_index`.
145 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
147 /// * the subscope with `first_statement_index == 0` is scope of both
148 /// `a` and `b`; it does not include EXPR_1, but does include
149 /// everything after that first `let`. (If you want a scope that
150 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
151 /// but instead another `CodeExtent` that encompasses the whole block,
152 /// e.g. `CodeExtentData::Misc`.
154 /// * the subscope with `first_statement_index == 1` is scope of `c`,
155 /// and thus does not include EXPR_2, but covers the `...`.
156 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
157 RustcDecodable, Debug, Copy)]
158 pub struct BlockRemainder {
159 pub block: ast::NodeId,
160 pub first_statement_index: u32,
163 impl CodeExtentData {
164 /// Returns a node id associated with this scope.
166 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
167 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
168 pub fn node_id(&self) -> ast::NodeId {
170 CodeExtentData::Misc(node_id) => node_id,
172 // These cases all return rough approximations to the
173 // precise extent denoted by `self`.
174 CodeExtentData::Remainder(br) => br.block,
175 CodeExtentData::DestructionScope(node_id) => node_id,
176 CodeExtentData::ParameterScope { fn_id: _, body_id } => body_id,
183 fn into_option(self) -> Option<CodeExtent> {
184 if self == ROOT_CODE_EXTENT {
190 pub fn node_id(&self, region_maps: &RegionMaps) -> ast::NodeId {
191 region_maps.code_extent_data(*self).node_id()
194 /// Returns the span of this CodeExtent. Note that in general the
195 /// returned span may not correspond to the span of any node id in
197 pub fn span(&self, region_maps: &RegionMaps, ast_map: &ast_map::Map) -> Option<Span> {
198 match ast_map.find(self.node_id(region_maps)) {
199 Some(ast_map::NodeBlock(ref blk)) => {
200 match region_maps.code_extent_data(*self) {
201 CodeExtentData::ParameterScope { .. } |
202 CodeExtentData::Misc(_) |
203 CodeExtentData::DestructionScope(_) => Some(blk.span),
205 CodeExtentData::Remainder(r) => {
206 assert_eq!(r.block, blk.id);
207 // Want span for extent starting after the
208 // indexed statement and ending at end of
209 // `blk`; reuse span of `blk` and shift `lo`
210 // forward to end of indexed statement.
212 // (This is the special case aluded to in the
213 // doc-comment for this method)
214 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
215 Some(Span { lo: stmt_span.hi, ..blk.span })
219 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
220 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
221 Some(ast_map::NodeItem(ref item)) => Some(item.span),
222 Some(_) | None => None,
227 /// The region maps encode information about region relationships.
228 pub struct RegionMaps {
229 code_extents: RefCell<Vec<CodeExtentData>>,
230 code_extent_interner: RefCell<FnvHashMap<CodeExtentData, CodeExtent>>,
231 /// `scope_map` maps from a scope id to the enclosing scope id;
232 /// this is usually corresponding to the lexical nesting, though
233 /// in the case of closures the parent scope is the innermost
234 /// conditional expression or repeating block. (Note that the
235 /// enclosing scope id for the block associated with a closure is
236 /// the closure itself.)
237 scope_map: RefCell<Vec<CodeExtent>>,
239 /// `var_map` maps from a variable or binding id to the block in
240 /// which that variable is declared.
241 var_map: RefCell<NodeMap<CodeExtent>>,
243 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
244 /// larger than the default. The map goes from the expression id
245 /// to the cleanup scope id. For rvalues not present in this
246 /// table, the appropriate cleanup scope is the innermost
247 /// enclosing statement, conditional expression, or repeating
248 /// block (see `terminating_scopes`).
249 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
251 /// Encodes the hierarchy of fn bodies. Every fn body (including
252 /// closures) forms its own distinct region hierarchy, rooted in
253 /// the block that is the fn body. This map points from the id of
254 /// that root block to the id of the root block for the enclosing
255 /// fn, if any. Thus the map structures the fn bodies into a
256 /// hierarchy based on their lexical mapping. This is used to
257 /// handle the relationships between regions in a fn and in a
258 /// closure defined by that fn. See the "Modeling closures"
259 /// section of the README in middle::infer::region_inference for
261 fn_tree: RefCell<NodeMap<ast::NodeId>>,
264 #[derive(Debug, Copy, Clone)]
266 /// the root of the current region tree. This is typically the id
267 /// of the innermost fn body. Each fn forms its own disjoint tree
268 /// in the region hierarchy. These fn bodies are themselves
269 /// arranged into a tree. See the "Modeling closures" section of
270 /// the README in middle::infer::region_inference for more
272 root_id: Option<ast::NodeId>,
274 /// the scope that contains any new variables declared
275 var_parent: CodeExtent,
277 /// region parent of expressions etc
281 struct RegionResolutionVisitor<'a> {
285 region_maps: &'a RegionMaps,
289 /// `terminating_scopes` is a set containing the ids of each
290 /// statement, or conditional/repeating expression. These scopes
291 /// are calling "terminating scopes" because, when attempting to
292 /// find the scope of a temporary, by default we search up the
293 /// enclosing scopes until we encounter the terminating scope. A
294 /// conditional/repeating expression is one which is not
295 /// guaranteed to execute exactly once upon entering the parent
296 /// scope. This could be because the expression only executes
297 /// conditionally, such as the expression `b` in `a && b`, or
298 /// because the expression may execute many times, such as a loop
299 /// body. The reason that we distinguish such expressions is that,
300 /// upon exiting the parent scope, we cannot statically know how
301 /// many times the expression executed, and thus if the expression
302 /// creates temporaries we cannot know statically how many such
303 /// temporaries we would have to cleanup. Therefore we ensure that
304 /// the temporaries never outlast the conditional/repeating
305 /// expression, preventing the need for dynamic checks and/or
306 /// arbitrary amounts of stack space. Terminating scopes end
307 /// up being contained in a DestructionScope that contains the
308 /// destructor's execution.
309 terminating_scopes: NodeSet
314 /// create a bogus code extent for the regions in astencode types. Nobody
315 /// really cares about the contents of these.
316 pub fn bogus_code_extent(&self, e: CodeExtentData) -> CodeExtent {
317 self.intern_code_extent(e, DUMMY_CODE_EXTENT)
319 pub fn lookup_code_extent(&self, e: CodeExtentData) -> CodeExtent {
320 match self.code_extent_interner.borrow().get(&e) {
322 None => panic!("unknown code extent {:?}", e)
325 pub fn node_extent(&self, n: ast::NodeId) -> CodeExtent {
326 self.lookup_code_extent(CodeExtentData::Misc(n))
328 // Returns the code extent for an item - the destruction scope.
329 pub fn item_extent(&self, n: ast::NodeId) -> CodeExtent {
330 self.lookup_code_extent(CodeExtentData::DestructionScope(n))
332 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
333 self.code_extent_interner.borrow().get(&CodeExtentData::DestructionScope(n)).cloned()
335 pub fn intern_code_extent(&self,
337 parent: CodeExtent) -> CodeExtent {
338 match self.code_extent_interner.borrow_mut().entry(e) {
339 Entry::Occupied(o) => {
340 // this can happen when the bogus code extents from tydecode
341 // have (bogus) NodeId-s that overlap items created during
343 // We probably shouldn't be creating bogus code extents
346 if parent == DUMMY_CODE_EXTENT {
347 info!("CodeExtent({}) = {:?} [parent={}] BOGUS!",
350 assert_eq!(self.scope_map.borrow()[idx.0 as usize],
352 info!("CodeExtent({}) = {:?} [parent={}] RECLAIMED!",
354 self.scope_map.borrow_mut()[idx.0 as usize] = parent;
358 Entry::Vacant(v) => {
359 if self.code_extents.borrow().len() > 0xffffffffusize {
360 unreachable!() // should pass a sess,
361 // but this isn't the only place
363 let idx = CodeExtent(self.code_extents.borrow().len() as u32);
364 info!("CodeExtent({}) = {:?} [parent={}]", idx.0, e, parent.0);
365 self.code_extents.borrow_mut().push(e);
366 self.scope_map.borrow_mut().push(parent);
371 pub fn intern_node(&self,
373 parent: CodeExtent) -> CodeExtent {
374 self.intern_code_extent(CodeExtentData::Misc(n), parent)
376 pub fn code_extent_data(&self, e: CodeExtent) -> CodeExtentData {
377 self.code_extents.borrow()[e.0 as usize]
379 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
380 for child_id in 1..self.code_extents.borrow().len() {
381 let child = CodeExtent(child_id as u32);
382 if let Some(parent) = self.opt_encl_scope(child) {
387 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
388 for (child, parent) in self.var_map.borrow().iter() {
392 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
393 for (child, parent) in self.rvalue_scopes.borrow().iter() {
397 /// Records that `sub_fn` is defined within `sup_fn`. These ids
398 /// should be the id of the block that is the fn body, which is
399 /// also the root of the region hierarchy for that fn.
400 fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
401 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
402 assert!(sub_fn != sup_fn);
403 let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
404 assert!(previous.is_none());
407 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
408 let fn_tree = self.fn_tree.borrow();
410 if sub_fn == sup_fn { return true; }
411 match fn_tree.get(&sub_fn) {
412 Some(&s) => { sub_fn = s; }
413 None => { return false; }
418 fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
419 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
420 assert!(var != lifetime.node_id(self));
421 self.var_map.borrow_mut().insert(var, lifetime);
424 fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
425 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
426 assert!(var != lifetime.node_id(self));
427 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
430 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
431 //! Returns the narrowest scope that encloses `id`, if any.
432 self.scope_map.borrow()[id.0 as usize].into_option()
435 #[allow(dead_code)] // used in middle::cfg
436 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
437 //! Returns the narrowest scope that encloses `id`, if any.
438 self.opt_encl_scope(id).unwrap()
441 /// Returns the lifetime of the local variable `var_id`
442 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
443 match self.var_map.borrow().get(&var_id) {
445 None => { panic!("no enclosing scope for id {:?}", var_id); }
449 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
450 //! Returns the scope when temp created by expr_id will be cleaned up
452 // check for a designated rvalue scope
453 match self.rvalue_scopes.borrow().get(&expr_id) {
455 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
461 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
462 let code_extents: &[CodeExtentData] = &self.code_extents.borrow();
464 // else, locate the innermost terminating scope
465 // if there's one. Static items, for instance, won't
466 // have an enclosing scope, hence no scope will be
468 let expr_extent = self.node_extent(expr_id);
469 // For some reason, the expr's scope itself is skipped here.
470 let mut id = match scope_map[expr_extent.0 as usize].into_option() {
475 while let Some(p) = scope_map[id.0 as usize].into_option() {
476 match code_extents[p.0 as usize] {
477 CodeExtentData::DestructionScope(..) => {
478 debug!("temporary_scope({:?}) = {:?} [enclosing]",
486 debug!("temporary_scope({:?}) = None", expr_id);
490 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
491 //! Returns the lifetime of the variable `id`.
493 let scope = ty::ReScope(self.var_scope(id));
494 debug!("var_region({:?}) = {:?}", id, scope);
498 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
500 self.is_subscope_of(scope1, scope2) ||
501 self.is_subscope_of(scope2, scope1)
504 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
506 pub fn is_subscope_of(&self,
507 subscope: CodeExtent,
508 superscope: CodeExtent)
510 let mut s = subscope;
511 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
512 while superscope != s {
513 match self.opt_encl_scope(s) {
515 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
516 subscope, superscope, s);
519 Some(scope) => s = scope
523 debug!("is_subscope_of({:?}, {:?})=true",
524 subscope, superscope);
529 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
530 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
531 pub fn nearest_common_ancestor(&self,
535 if scope_a == scope_b { return scope_a; }
537 let mut a_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
538 let mut a_vec: Vec<CodeExtent> = vec![];
539 let mut b_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
540 let mut b_vec: Vec<CodeExtent> = vec![];
541 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
542 let a_ancestors = ancestors_of(scope_map,
543 scope_a, &mut a_buf, &mut a_vec);
544 let b_ancestors = ancestors_of(scope_map,
545 scope_b, &mut b_buf, &mut b_vec);
546 let mut a_index = a_ancestors.len() - 1;
547 let mut b_index = b_ancestors.len() - 1;
549 // Here, [ab]_ancestors is a vector going from narrow to broad.
550 // The end of each vector will be the item where the scope is
551 // defined; if there are any common ancestors, then the tails of
552 // the vector will be the same. So basically we want to walk
553 // backwards from the tail of each vector and find the first point
554 // where they diverge. If one vector is a suffix of the other,
555 // then the corresponding scope is a superscope of the other.
557 if a_ancestors[a_index] != b_ancestors[b_index] {
558 // In this case, the two regions belong to completely
559 // different functions. Compare those fn for lexical
560 // nesting. The reasoning behind this is subtle. See the
561 // "Modeling closures" section of the README in
562 // middle::infer::region_inference for more details.
563 let a_root_scope = self.code_extent_data(a_ancestors[a_index]);
564 let b_root_scope = self.code_extent_data(a_ancestors[a_index]);
565 return match (a_root_scope, b_root_scope) {
566 (CodeExtentData::DestructionScope(a_root_id),
567 CodeExtentData::DestructionScope(b_root_id)) => {
568 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
569 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
571 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
572 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
575 // neither fn encloses the other
580 // root ids are always Misc right now
587 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
588 // for all indices between a_index and the end of the array
589 if a_index == 0 { return scope_a; }
590 if b_index == 0 { return scope_b; }
593 if a_ancestors[a_index] != b_ancestors[b_index] {
594 return a_ancestors[a_index + 1];
598 fn ancestors_of<'a>(scope_map: &[CodeExtent],
600 buf: &'a mut [CodeExtent; 32],
601 vec: &'a mut Vec<CodeExtent>) -> &'a [CodeExtent] {
602 // debug!("ancestors_of(scope={:?})", scope);
603 let mut scope = scope;
608 match scope_map[scope.0 as usize].into_option() {
609 Some(superscope) => scope = superscope,
610 _ => return &buf[..i+1]
615 *vec = Vec::with_capacity(64);
619 match scope_map[scope.0 as usize].into_option() {
620 Some(superscope) => scope = superscope,
628 /// Records the lifetime of a local variable as `cx.var_parent`
629 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
632 match visitor.cx.var_parent {
633 ROOT_CODE_EXTENT => {
634 // this can happen in extern fn declarations like
636 // extern fn isalnum(c: c_int) -> c_int
639 visitor.region_maps.record_var_scope(var_id, parent_scope),
643 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &hir::Block) {
644 debug!("resolve_block(blk.id={:?})", blk.id);
646 let prev_cx = visitor.cx;
647 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
649 // We treat the tail expression in the block (if any) somewhat
650 // differently from the statements. The issue has to do with
651 // temporary lifetimes. Consider the following:
654 // let inner = ... (&bar()) ...;
656 // (... (&foo()) ...) // (the tail expression)
657 // }, other_argument());
659 // Each of the statements within the block is a terminating
660 // scope, and thus a temporary (e.g. the result of calling
661 // `bar()` in the initalizer expression for `let inner = ...;`)
662 // will be cleaned up immediately after its corresponding
663 // statement (i.e. `let inner = ...;`) executes.
665 // On the other hand, temporaries associated with evaluating the
666 // tail expression for the block are assigned lifetimes so that
667 // they will be cleaned up as part of the terminating scope
668 // *surrounding* the block expression. Here, the terminating
669 // scope for the block expression is the `quux(..)` call; so
670 // those temporaries will only be cleaned up *after* both
671 // `other_argument()` has run and also the call to `quux(..)`
672 // itself has returned.
674 visitor.cx = Context {
675 root_id: prev_cx.root_id,
676 var_parent: block_extent,
677 parent: block_extent,
681 // This block should be kept approximately in sync with
682 // `visit::walk_block`. (We manually walk the block, rather
683 // than call `walk_block`, in order to maintain precise
684 // index information.)
686 for (i, statement) in blk.stmts.iter().enumerate() {
687 if let hir::StmtDecl(..) = statement.node {
688 // Each StmtDecl introduces a subscope for bindings
689 // introduced by the declaration; this subscope covers
690 // a suffix of the block . Each subscope in a block
691 // has the previous subscope in the block as a parent,
692 // except for the first such subscope, which has the
693 // block itself as a parent.
694 let stmt_extent = visitor.new_code_extent(
695 CodeExtentData::Remainder(BlockRemainder {
697 first_statement_index: i as u32
700 visitor.cx = Context {
701 root_id: prev_cx.root_id,
702 var_parent: stmt_extent,
706 visitor.visit_stmt(&**statement)
708 walk_list!(visitor, visit_expr, &blk.expr);
711 visitor.cx = prev_cx;
714 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &hir::Arm) {
715 visitor.terminating_scopes.insert(arm.body.id);
717 if let Some(ref expr) = arm.guard {
718 visitor.terminating_scopes.insert(expr.id);
721 visit::walk_arm(visitor, arm);
724 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &hir::Pat) {
725 visitor.new_node_extent(pat.id);
727 // If this is a binding (or maybe a binding, I'm too lazy to check
728 // the def map) then record the lifetime of that binding.
730 hir::PatIdent(..) => {
731 record_var_lifetime(visitor, pat.id, pat.span);
736 visit::walk_pat(visitor, pat);
739 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &hir::Stmt) {
740 let stmt_id = stmt_id(stmt);
741 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
743 // Every statement will clean up the temporaries created during
744 // execution of that statement. Therefore each statement has an
745 // associated destruction scope that represents the extent of the
746 // statement plus its destructors, and thus the extent for which
747 // regions referenced by the destructors need to survive.
748 visitor.terminating_scopes.insert(stmt_id);
749 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
751 let prev_parent = visitor.cx.parent;
752 visitor.cx.parent = stmt_extent;
753 visit::walk_stmt(visitor, stmt);
754 visitor.cx.parent = prev_parent;
757 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &hir::Expr) {
758 debug!("resolve_expr(expr.id={:?})", expr.id);
760 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
761 let prev_cx = visitor.cx;
762 visitor.cx.parent = expr_extent;
765 let terminating_scopes = &mut visitor.terminating_scopes;
766 let mut terminating = |id: ast::NodeId| {
767 terminating_scopes.insert(id);
770 // Conditional or repeating scopes are always terminating
771 // scopes, meaning that temporaries cannot outlive them.
772 // This ensures fixed size stacks.
774 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
775 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
776 // For shortcircuiting operators, mark the RHS as a terminating
777 // scope since it only executes conditionally.
781 hir::ExprIf(_, ref then, Some(ref otherwise)) => {
782 terminating(then.id);
783 terminating(otherwise.id);
786 hir::ExprIf(ref expr, ref then, None) => {
787 terminating(expr.id);
788 terminating(then.id);
791 hir::ExprLoop(ref body, _) => {
792 terminating(body.id);
795 hir::ExprWhile(ref expr, ref body, _) => {
796 terminating(expr.id);
797 terminating(body.id);
800 hir::ExprMatch(..) => {
801 visitor.cx.var_parent = expr_extent;
804 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
805 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
806 // FIXME(#6268) Nested method calls
808 // The lifetimes for a call or method call look as follows:
816 // The idea is that call.callee_id represents *the time when
817 // the invoked function is actually running* and call.id
818 // represents *the time to prepare the arguments and make the
819 // call*. See the section "Borrows in Calls" borrowck/README.md
820 // for an extended explanation of why this distinction is
823 // record_superlifetime(new_cx, expr.callee_id);
830 visit::walk_expr(visitor, expr);
831 visitor.cx = prev_cx;
834 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &hir::Local) {
835 debug!("resolve_local(local.id={:?},local.init={:?})",
836 local.id,local.init.is_some());
838 // For convenience in trans, associate with the local-id the var
839 // scope that will be used for any bindings declared in this
841 let blk_scope = visitor.cx.var_parent;
842 assert!(blk_scope != ROOT_CODE_EXTENT); // locals must be within a block
843 visitor.region_maps.record_var_scope(local.id, blk_scope);
845 // As an exception to the normal rules governing temporary
846 // lifetimes, initializers in a let have a temporary lifetime
847 // of the enclosing block. This means that e.g. a program
848 // like the following is legal:
850 // let ref x = HashMap::new();
852 // Because the hash map will be freed in the enclosing block.
854 // We express the rules more formally based on 3 grammars (defined
855 // fully in the helpers below that implement them):
857 // 1. `E&`, which matches expressions like `&<rvalue>` that
858 // own a pointer into the stack.
860 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
861 // y)` that produce ref bindings into the value they are
862 // matched against or something (at least partially) owned by
863 // the value they are matched against. (By partially owned,
864 // I mean that creating a binding into a ref-counted or managed value
865 // would still count.)
867 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
868 // based on rvalues like `foo().x[2].y`.
870 // A subexpression `<rvalue>` that appears in a let initializer
871 // `let pat [: ty] = expr` has an extended temporary lifetime if
872 // any of the following conditions are met:
874 // A. `pat` matches `P&` and `expr` matches `ET`
875 // (covers cases where `pat` creates ref bindings into an rvalue
876 // produced by `expr`)
877 // B. `ty` is a borrowed pointer and `expr` matches `ET`
878 // (covers cases where coercion creates a borrow)
879 // C. `expr` matches `E&`
880 // (covers cases `expr` borrows an rvalue that is then assigned
881 // to memory (at least partially) owned by the binding)
883 // Here are some examples hopefully giving an intuition where each
884 // rule comes into play and why:
886 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
887 // would have an extended lifetime, but not `foo()`.
889 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
890 // would have an extended lifetime, but not `foo()`.
892 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
895 // In some cases, multiple rules may apply (though not to the same
896 // rvalue). For example:
898 // let ref x = [&a(), &b()];
900 // Here, the expression `[...]` has an extended lifetime due to rule
901 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
904 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
908 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
911 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
913 if is_binding_pat(&*local.pat) || is_borrow {
914 record_rvalue_scope(visitor, &**expr, blk_scope);
921 visit::walk_local(visitor, local);
923 /// True if `pat` match the `P&` nonterminal:
926 /// | StructName { ..., P&, ... }
927 /// | VariantName(..., P&, ...)
928 /// | [ ..., P&, ... ]
929 /// | ( ..., P&, ... )
931 fn is_binding_pat(pat: &hir::Pat) -> bool {
933 hir::PatIdent(hir::BindByRef(_), _, _) => true,
935 hir::PatStruct(_, ref field_pats, _) => {
936 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
939 hir::PatVec(ref pats1, ref pats2, ref pats3) => {
940 pats1.iter().any(|p| is_binding_pat(&**p)) ||
941 pats2.iter().any(|p| is_binding_pat(&**p)) ||
942 pats3.iter().any(|p| is_binding_pat(&**p))
945 hir::PatEnum(_, Some(ref subpats)) |
946 hir::PatTup(ref subpats) => {
947 subpats.iter().any(|p| is_binding_pat(&**p))
950 hir::PatBox(ref subpat) => {
951 is_binding_pat(&**subpat)
958 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
959 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
961 hir::TyRptr(..) => true,
966 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
969 /// | StructName { ..., f: E&, ... }
970 /// | [ ..., E&, ... ]
971 /// | ( ..., E&, ... )
976 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
978 blk_id: CodeExtent) {
980 hir::ExprAddrOf(_, ref subexpr) => {
981 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
982 record_rvalue_scope(visitor, &**subexpr, blk_id);
984 hir::ExprStruct(_, ref fields, _) => {
985 for field in fields {
986 record_rvalue_scope_if_borrow_expr(
987 visitor, &*field.expr, blk_id);
990 hir::ExprVec(ref subexprs) |
991 hir::ExprTup(ref subexprs) => {
992 for subexpr in subexprs {
993 record_rvalue_scope_if_borrow_expr(
994 visitor, &**subexpr, blk_id);
997 hir::ExprCast(ref subexpr, _) => {
998 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1000 hir::ExprBlock(ref block) => {
1002 Some(ref subexpr) => {
1003 record_rvalue_scope_if_borrow_expr(
1004 visitor, &**subexpr, blk_id);
1014 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1015 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1016 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1019 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1020 /// `<rvalue>` as `blk_id`:
1028 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1029 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1030 expr: &'a hir::Expr,
1031 blk_scope: CodeExtent) {
1032 let mut expr = expr;
1034 // Note: give all the expressions matching `ET` with the
1035 // extended temporary lifetime, not just the innermost rvalue,
1036 // because in trans if we must compile e.g. `*rvalue()`
1037 // into a temporary, we request the temporary scope of the
1038 // outer expression.
1039 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1042 hir::ExprAddrOf(_, ref subexpr) |
1043 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1044 hir::ExprField(ref subexpr, _) |
1045 hir::ExprTupField(ref subexpr, _) |
1046 hir::ExprIndex(ref subexpr, _) => {
1057 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &hir::Item) {
1058 // Items create a new outer block scope as far as we're concerned.
1059 let prev_cx = visitor.cx;
1060 let prev_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1061 visitor.cx = Context {
1063 var_parent: ROOT_CODE_EXTENT,
1064 parent: ROOT_CODE_EXTENT
1066 visit::walk_item(visitor, item);
1067 visitor.create_item_scope_if_needed(item.id);
1068 visitor.cx = prev_cx;
1069 visitor.terminating_scopes = prev_ts;
1072 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1078 debug!("region::resolve_fn(id={:?}, \
1083 visitor.sess.codemap().span_to_string(sp),
1087 let fn_decl_scope = visitor.new_code_extent(
1088 CodeExtentData::ParameterScope { fn_id: id, body_id: body.id });
1090 if let Some(root_id) = visitor.cx.root_id {
1091 visitor.region_maps.record_fn_parent(body.id, root_id);
1094 let outer_cx = visitor.cx;
1095 let outer_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1096 visitor.terminating_scopes.insert(body.id);
1098 // The arguments and `self` are parented to the fn.
1099 visitor.cx = Context {
1100 root_id: Some(body.id),
1101 parent: ROOT_CODE_EXTENT,
1102 var_parent: fn_decl_scope,
1105 visit::walk_fn_decl(visitor, decl);
1106 visit::walk_fn_kind(visitor, kind);
1108 // The body of the every fn is a root scope.
1109 visitor.cx = Context {
1110 root_id: Some(body.id),
1111 parent: fn_decl_scope,
1112 var_parent: fn_decl_scope
1114 visitor.visit_block(body);
1116 // Restore context we had at the start.
1117 visitor.cx = outer_cx;
1118 visitor.terminating_scopes = outer_ts;
1121 impl<'a> RegionResolutionVisitor<'a> {
1122 /// Records the current parent (if any) as the parent of `child_scope`.
1123 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent {
1124 self.region_maps.intern_code_extent(child_scope, self.cx.parent)
1127 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent {
1128 self.new_code_extent(CodeExtentData::Misc(child_scope))
1131 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent {
1132 // If node was previously marked as a terminating scope during the
1133 // recursive visit of its parent node in the AST, then we need to
1134 // account for the destruction scope representing the extent of
1135 // the destructors that run immediately after it completes.
1136 if self.terminating_scopes.contains(&id) {
1137 let ds = self.new_code_extent(
1138 CodeExtentData::DestructionScope(id));
1139 self.region_maps.intern_node(id, ds)
1141 self.new_node_extent(id)
1145 fn create_item_scope_if_needed(&mut self, id: ast::NodeId) {
1146 // create a region for the destruction scope - this is needed
1147 // for constructing parameter environments based on the item.
1148 // functions put their destruction scopes *inside* their parameter
1150 let scope = CodeExtentData::DestructionScope(id);
1151 if !self.region_maps.code_extent_interner.borrow().contains_key(&scope) {
1152 self.region_maps.intern_code_extent(scope, ROOT_CODE_EXTENT);
1157 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1158 fn visit_block(&mut self, b: &Block) {
1159 resolve_block(self, b);
1162 fn visit_item(&mut self, i: &Item) {
1163 resolve_item(self, i);
1166 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
1167 visit::walk_impl_item(self, ii);
1168 self.create_item_scope_if_needed(ii.id);
1171 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
1172 visit::walk_trait_item(self, ti);
1173 self.create_item_scope_if_needed(ti.id);
1176 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1177 b: &'v Block, s: Span, n: NodeId) {
1178 resolve_fn(self, fk, fd, b, s, n);
1180 fn visit_arm(&mut self, a: &Arm) {
1181 resolve_arm(self, a);
1183 fn visit_pat(&mut self, p: &Pat) {
1184 resolve_pat(self, p);
1186 fn visit_stmt(&mut self, s: &Stmt) {
1187 resolve_stmt(self, s);
1189 fn visit_expr(&mut self, ex: &Expr) {
1190 resolve_expr(self, ex);
1192 fn visit_local(&mut self, l: &Local) {
1193 resolve_local(self, l);
1197 pub fn resolve_crate(sess: &Session, krate: &hir::Crate) -> RegionMaps {
1198 let maps = RegionMaps {
1199 code_extents: RefCell::new(vec![]),
1200 code_extent_interner: RefCell::new(FnvHashMap()),
1201 scope_map: RefCell::new(vec![]),
1202 var_map: RefCell::new(NodeMap()),
1203 rvalue_scopes: RefCell::new(NodeMap()),
1204 fn_tree: RefCell::new(NodeMap()),
1206 let root_extent = maps.bogus_code_extent(
1207 CodeExtentData::DestructionScope(ast::DUMMY_NODE_ID));
1208 assert_eq!(root_extent, ROOT_CODE_EXTENT);
1209 let bogus_extent = maps.bogus_code_extent(
1210 CodeExtentData::Misc(ast::DUMMY_NODE_ID));
1211 assert_eq!(bogus_extent, DUMMY_CODE_EXTENT);
1213 let mut visitor = RegionResolutionVisitor {
1218 parent: ROOT_CODE_EXTENT,
1219 var_parent: ROOT_CODE_EXTENT
1221 terminating_scopes: NodeSet()
1223 visit::walk_crate(&mut visitor, krate);
1228 pub fn resolve_inlined_item(sess: &Session,
1229 region_maps: &RegionMaps,
1230 item: &InlinedItem) {
1231 let mut visitor = RegionResolutionVisitor {
1233 region_maps: region_maps,
1236 parent: ROOT_CODE_EXTENT,
1237 var_parent: ROOT_CODE_EXTENT
1239 terminating_scopes: NodeSet()
1241 item.visit(&mut visitor);