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};
21 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
23 use std::cell::RefCell;
24 use syntax::codemap::{self, Span};
25 use syntax::{ast, visit};
26 use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local};
27 use syntax::ast_util::stmt_id;
30 use syntax::visit::{Visitor, FnKind};
32 /// CodeExtent represents a statically-describable extent that can be
33 /// used to bound the lifetime/region for values.
35 /// `Misc(node_id)`: Any AST node that has any extent at all has the
36 /// `Misc(node_id)` extent. Other variants represent special cases not
37 /// immediately derivable from the abstract syntax tree structure.
39 /// `DestructionScope(node_id)` represents the extent of destructors
40 /// implicitly-attached to `node_id` that run immediately after the
41 /// expression for `node_id` itself. Not every AST node carries a
42 /// `DestructionScope`, but those that are `terminating_scopes` do;
43 /// see discussion with `RegionMaps`.
45 /// `Remainder(BlockRemainder { block, statement_index })` represents
46 /// the extent of user code running immediately after the initializer
47 /// expression for the indexed statement, until the end of the block.
49 /// So: the following code can be broken down into the extents beneath:
51 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
56 /// +---------+ (R10.)
58 /// +----------+ (M8.)
59 /// +----------------------+ (R7.)
61 /// +----------+ (M5.)
62 /// +-----------------------------------+ (M4.)
63 /// +--------------------------------------------------+ (M3.)
65 /// +-----------------------------------------------------------+ (M1.)
67 /// (M1.): Misc extent of the whole `let a = ...;` statement.
68 /// (M2.): Misc extent of the `f()` expression.
69 /// (M3.): Misc extent of the `f().g(..)` expression.
70 /// (M4.): Misc extent of the block labelled `'b:`.
71 /// (M5.): Misc extent of the `let x = d();` statement
72 /// (D6.): DestructionScope for temporaries created during M5.
73 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
74 /// (M8.): Misc Extent of the `let y = d();` statement.
75 /// (D9.): DestructionScope for temporaries created during M8.
76 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
77 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
78 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
80 /// Note that while the above picture shows the destruction scopes
81 /// as following their corresponding misc extents, in the internal
82 /// data structures of the compiler the destruction scopes are
83 /// represented as enclosing parents. This is sound because we use the
84 /// enclosing parent relationship just to ensure that referenced
85 /// values live long enough; phrased another way, the starting point
86 /// of each range is not really the important thing in the above
87 /// picture, but rather the ending point.
89 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
90 /// placate the same deriving in `ty::FreeRegion`, but we may want to
91 /// actually attach a more meaningful ordering to scopes than the one
92 /// generated via deriving here.
93 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
94 RustcDecodable, Debug, Copy)]
98 // extent of parameters passed to a function or closure (they
100 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
102 // extent of destructors for temporaries of node-id
103 DestructionScope(ast::NodeId),
105 // extent of code following a `let id = expr;` binding in a block
106 Remainder(BlockRemainder)
109 /// extent of destructors for temporaries of node-id
110 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
111 RustcDecodable, Debug, Copy)]
112 pub struct DestructionScopeData {
113 pub node_id: ast::NodeId
116 impl DestructionScopeData {
117 pub fn new(node_id: ast::NodeId) -> DestructionScopeData {
118 DestructionScopeData { node_id: node_id }
120 pub fn to_code_extent(&self) -> CodeExtent {
121 CodeExtent::DestructionScope(self.node_id)
125 /// Represents a subscope of `block` for a binding that is introduced
126 /// by `block.stmts[first_statement_index]`. Such subscopes represent
127 /// a suffix of the block. Note that each subscope does not include
128 /// the initializer expression, if any, for the statement indexed by
129 /// `first_statement_index`.
131 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
133 /// * the subscope with `first_statement_index == 0` is scope of both
134 /// `a` and `b`; it does not include EXPR_1, but does include
135 /// everything after that first `let`. (If you want a scope that
136 /// includes EXPR_1 as well, then do not use `CodeExtent::Remainder`,
137 /// but instead another `CodeExtent` that encompasses the whole block,
138 /// e.g. `CodeExtent::Misc`.
140 /// * the subscope with `first_statement_index == 1` is scope of `c`,
141 /// and thus does not include EXPR_2, but covers the `...`.
142 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
143 RustcDecodable, Debug, Copy)]
144 pub struct BlockRemainder {
145 pub block: ast::NodeId,
146 pub first_statement_index: usize,
150 /// Creates a scope that represents the dynamic extent associated
152 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
153 CodeExtent::Misc(node_id)
156 /// Returns a node id associated with this scope.
158 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
159 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
160 pub fn node_id(&self) -> ast::NodeId {
162 CodeExtent::Misc(node_id) => node_id,
164 // These cases all return rough approximations to the
165 // precise extent denoted by `self`.
166 CodeExtent::Remainder(br) => br.block,
167 CodeExtent::DestructionScope(node_id) => node_id,
168 CodeExtent::ParameterScope { fn_id: _, body_id } => body_id,
172 /// Maps this scope to a potentially new one according to the
173 /// NodeId transformer `f_id`.
174 pub fn map_id<F>(&self, mut f_id: F) -> CodeExtent where
175 F: FnMut(ast::NodeId) -> ast::NodeId,
178 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
179 CodeExtent::Remainder(br) =>
180 CodeExtent::Remainder(BlockRemainder {
181 block: f_id(br.block), first_statement_index: br.first_statement_index }),
182 CodeExtent::DestructionScope(node_id) =>
183 CodeExtent::DestructionScope(f_id(node_id)),
184 CodeExtent::ParameterScope { fn_id, body_id } =>
185 CodeExtent::ParameterScope { fn_id: f_id(fn_id), body_id: f_id(body_id) },
189 /// Returns the span of this CodeExtent. Note that in general the
190 /// returned span may not correspond to the span of any node id in
192 pub fn span(&self, ast_map: &ast_map::Map) -> Option<Span> {
193 match ast_map.find(self.node_id()) {
194 Some(ast_map::NodeBlock(ref blk)) => {
196 CodeExtent::ParameterScope { .. } |
197 CodeExtent::Misc(_) |
198 CodeExtent::DestructionScope(_) => Some(blk.span),
200 CodeExtent::Remainder(r) => {
201 assert_eq!(r.block, blk.id);
202 // Want span for extent starting after the
203 // indexed statement and ending at end of
204 // `blk`; reuse span of `blk` and shift `lo`
205 // forward to end of indexed statement.
207 // (This is the special case aluded to in the
208 // doc-comment for this method)
209 let stmt_span = blk.stmts[r.first_statement_index].span;
210 Some(Span { lo: stmt_span.hi, ..blk.span })
214 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
215 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
216 Some(ast_map::NodeItem(ref item)) => Some(item.span),
217 Some(_) | None => None,
222 /// The region maps encode information about region relationships.
223 pub struct RegionMaps {
224 /// `scope_map` maps from a scope id to the enclosing scope id;
225 /// this is usually corresponding to the lexical nesting, though
226 /// in the case of closures the parent scope is the innermost
227 /// conditional expression or repeating block. (Note that the
228 /// enclosing scope id for the block associated with a closure is
229 /// the closure itself.)
230 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
232 /// `var_map` maps from a variable or binding id to the block in
233 /// which that variable is declared.
234 var_map: RefCell<NodeMap<CodeExtent>>,
236 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
237 /// larger than the default. The map goes from the expression id
238 /// to the cleanup scope id. For rvalues not present in this
239 /// table, the appropriate cleanup scope is the innermost
240 /// enclosing statement, conditional expression, or repeating
241 /// block (see `terminating_scopes`).
242 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
244 /// `terminating_scopes` is a set containing the ids of each
245 /// statement, or conditional/repeating expression. These scopes
246 /// are calling "terminating scopes" because, when attempting to
247 /// find the scope of a temporary, by default we search up the
248 /// enclosing scopes until we encounter the terminating scope. A
249 /// conditional/repeating expression is one which is not
250 /// guaranteed to execute exactly once upon entering the parent
251 /// scope. This could be because the expression only executes
252 /// conditionally, such as the expression `b` in `a && b`, or
253 /// because the expression may execute many times, such as a loop
254 /// body. The reason that we distinguish such expressions is that,
255 /// upon exiting the parent scope, we cannot statically know how
256 /// many times the expression executed, and thus if the expression
257 /// creates temporaries we cannot know statically how many such
258 /// temporaries we would have to cleanup. Therefore we ensure that
259 /// the temporaries never outlast the conditional/repeating
260 /// expression, preventing the need for dynamic checks and/or
261 /// arbitrary amounts of stack space.
262 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
264 /// Encodes the hierarchy of fn bodies. Every fn body (including
265 /// closures) forms its own distinct region hierarchy, rooted in
266 /// the block that is the fn body. This map points from the id of
267 /// that root block to the id of the root block for the enclosing
268 /// fn, if any. Thus the map structures the fn bodies into a
269 /// hierarchy based on their lexical mapping. This is used to
270 /// handle the relationships between regions in a fn and in a
271 /// closure defined by that fn. See the "Modeling closures"
272 /// section of the README in middle::infer::region_inference for
274 fn_tree: RefCell<NodeMap<ast::NodeId>>,
277 /// Carries the node id for the innermost block or match expression,
278 /// for building up the `var_map` which maps ids to the blocks in
279 /// which they were declared.
280 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
281 enum InnermostDeclaringBlock {
284 Statement(DeclaringStatementContext),
286 FnDecl { fn_id: ast::NodeId, body_id: ast::NodeId },
289 impl InnermostDeclaringBlock {
290 fn to_code_extent(&self) -> Option<CodeExtent> {
291 let extent = match *self {
292 InnermostDeclaringBlock::None => {
295 InnermostDeclaringBlock::FnDecl { fn_id, body_id } =>
296 CodeExtent::ParameterScope { fn_id: fn_id, body_id: body_id },
297 InnermostDeclaringBlock::Block(id) |
298 InnermostDeclaringBlock::Match(id) => CodeExtent::from_node_id(id),
299 InnermostDeclaringBlock::Statement(s) => s.to_code_extent(),
305 /// Contextual information for declarations introduced by a statement
306 /// (i.e. `let`). It carries node-id's for statement and enclosing
307 /// block both, as well as the statement's index within the block.
308 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
309 struct DeclaringStatementContext {
310 stmt_id: ast::NodeId,
311 block_id: ast::NodeId,
315 impl DeclaringStatementContext {
316 fn to_code_extent(&self) -> CodeExtent {
317 CodeExtent::Remainder(BlockRemainder {
318 block: self.block_id,
319 first_statement_index: self.stmt_index,
324 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
325 enum InnermostEnclosingExpr {
328 Statement(DeclaringStatementContext),
331 impl InnermostEnclosingExpr {
332 fn to_code_extent(&self) -> Option<CodeExtent> {
333 let extent = match *self {
334 InnermostEnclosingExpr::None => {
337 InnermostEnclosingExpr::Statement(s) =>
339 InnermostEnclosingExpr::Some(parent_id) =>
340 CodeExtent::from_node_id(parent_id),
346 #[derive(Debug, Copy, Clone)]
348 /// the root of the current region tree. This is typically the id
349 /// of the innermost fn body. Each fn forms its own disjoint tree
350 /// in the region hierarchy. These fn bodies are themselves
351 /// arranged into a tree. See the "Modeling closures" section of
352 /// the README in middle::infer::region_inference for more
354 root_id: Option<ast::NodeId>,
356 /// the scope that contains any new variables declared
357 var_parent: InnermostDeclaringBlock,
359 /// region parent of expressions etc
360 parent: InnermostEnclosingExpr,
363 struct RegionResolutionVisitor<'a> {
367 region_maps: &'a RegionMaps,
374 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
375 for (child, parent) in self.scope_map.borrow().iter() {
379 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
380 for (child, parent) in self.var_map.borrow().iter() {
384 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
385 for (child, parent) in self.rvalue_scopes.borrow().iter() {
389 pub fn each_terminating_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent) {
390 for scope in self.terminating_scopes.borrow().iter() {
395 /// Records that `sub_fn` is defined within `sup_fn`. These ids
396 /// should be the id of the block that is the fn body, which is
397 /// also the root of the region hierarchy for that fn.
398 fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
399 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
400 assert!(sub_fn != sup_fn);
401 let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
402 assert!(previous.is_none());
405 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
406 let fn_tree = self.fn_tree.borrow();
408 if sub_fn == sup_fn { return true; }
409 match fn_tree.get(&sub_fn) {
410 Some(&s) => { sub_fn = s; }
411 None => { return false; }
416 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
417 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
419 self.scope_map.borrow_mut().insert(sub, sup);
422 fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
423 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
424 assert!(var != lifetime.node_id());
425 self.var_map.borrow_mut().insert(var, lifetime);
428 fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
429 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
430 assert!(var != lifetime.node_id());
431 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
434 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
435 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
437 fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
438 debug!("record_terminating_scope(scope_id={:?})", scope_id);
439 self.terminating_scopes.borrow_mut().insert(scope_id);
442 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
443 //! Returns the narrowest scope that encloses `id`, if any.
444 self.scope_map.borrow().get(&id).cloned()
447 #[allow(dead_code)] // used in middle::cfg
448 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
449 //! Returns the narrowest scope that encloses `id`, if any.
450 match self.scope_map.borrow().get(&id) {
452 None => { panic!("no enclosing scope for id {:?}", id); }
456 /// Returns the lifetime of the local variable `var_id`
457 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
458 match self.var_map.borrow().get(&var_id) {
460 None => { panic!("no enclosing scope for id {:?}", var_id); }
464 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
465 //! Returns the scope when temp created by expr_id will be cleaned up
467 // check for a designated rvalue scope
468 match self.rvalue_scopes.borrow().get(&expr_id) {
470 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
476 // else, locate the innermost terminating scope
477 // if there's one. Static items, for instance, won't
478 // have an enclosing scope, hence no scope will be
480 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
482 None => { return None; }
485 while !self.terminating_scopes.borrow().contains(&id) {
486 match self.opt_encl_scope(id) {
491 debug!("temporary_scope({:?}) = None", expr_id);
496 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
500 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
501 //! Returns the lifetime of the variable `id`.
503 let scope = ty::ReScope(self.var_scope(id));
504 debug!("var_region({:?}) = {:?}", id, scope);
508 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
510 self.is_subscope_of(scope1, scope2) ||
511 self.is_subscope_of(scope2, scope1)
514 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
516 pub fn is_subscope_of(&self,
517 subscope: CodeExtent,
518 superscope: CodeExtent)
520 let mut s = subscope;
521 while superscope != s {
522 match self.scope_map.borrow().get(&s) {
524 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
525 subscope, superscope, s);
529 Some(&scope) => s = scope
533 debug!("is_subscope_of({:?}, {:?})=true",
534 subscope, superscope);
539 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
540 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
541 pub fn nearest_common_ancestor(&self,
545 if scope_a == scope_b { return scope_a; }
547 let a_ancestors = ancestors_of(self, scope_a);
548 let b_ancestors = ancestors_of(self, scope_b);
549 let mut a_index = a_ancestors.len() - 1;
550 let mut b_index = b_ancestors.len() - 1;
552 // Here, [ab]_ancestors is a vector going from narrow to broad.
553 // The end of each vector will be the item where the scope is
554 // defined; if there are any common ancestors, then the tails of
555 // the vector will be the same. So basically we want to walk
556 // backwards from the tail of each vector and find the first point
557 // where they diverge. If one vector is a suffix of the other,
558 // then the corresponding scope is a superscope of the other.
560 if a_ancestors[a_index] != b_ancestors[b_index] {
561 // In this case, the two regions belong to completely
562 // different functions. Compare those fn for lexical
563 // nesting. The reasoning behind this is subtle. See the
564 // "Modeling closures" section of the README in
565 // middle::infer::region_inference for more details.
566 let a_root_scope = a_ancestors[a_index];
567 let b_root_scope = a_ancestors[a_index];
568 return match (a_root_scope, b_root_scope) {
569 (CodeExtent::DestructionScope(a_root_id),
570 CodeExtent::DestructionScope(b_root_id)) => {
571 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
572 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
574 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
575 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
578 // neither fn encloses the other
583 // root ids are always Misc right now
590 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
591 // for all indices between a_index and the end of the array
592 if a_index == 0 { return scope_a; }
593 if b_index == 0 { return scope_b; }
596 if a_ancestors[a_index] != b_ancestors[b_index] {
597 return a_ancestors[a_index + 1];
601 fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec<CodeExtent> {
602 // debug!("ancestors_of(scope={:?})", scope);
603 let mut result = vec!(scope);
604 let mut scope = scope;
606 match this.scope_map.borrow().get(&scope) {
607 None => return result,
608 Some(&superscope) => {
609 result.push(superscope);
613 // debug!("ancestors_of_loop(scope={:?})", scope);
619 /// Records the current parent (if any) as the parent of `child_scope`.
620 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
621 child_scope: CodeExtent,
623 match visitor.cx.parent.to_code_extent() {
624 Some(parent_scope) =>
625 visitor.region_maps.record_encl_scope(child_scope, parent_scope),
630 /// Records the lifetime of a local variable as `cx.var_parent`
631 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
634 match visitor.cx.var_parent.to_code_extent() {
635 Some(parent_scope) =>
636 visitor.region_maps.record_var_scope(var_id, parent_scope),
638 // this can happen in extern fn declarations like
640 // extern fn isalnum(c: c_int) -> c_int
645 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
646 debug!("resolve_block(blk.id={:?})", blk.id);
648 let prev_cx = visitor.cx;
650 let blk_scope = CodeExtent::Misc(blk.id);
652 // If block was previously marked as a terminating scope during
653 // the recursive visit of its parent node in the AST, then we need
654 // to account for the destruction scope representing the extent of
655 // the destructors that run immediately after the the block itself
657 if visitor.region_maps.terminating_scopes.borrow().contains(&blk_scope) {
658 let dtor_scope = CodeExtent::DestructionScope(blk.id);
659 record_superlifetime(visitor, dtor_scope, blk.span);
660 visitor.region_maps.record_encl_scope(blk_scope, dtor_scope);
662 record_superlifetime(visitor, blk_scope, blk.span);
665 // We treat the tail expression in the block (if any) somewhat
666 // differently from the statements. The issue has to do with
667 // temporary lifetimes. Consider the following:
670 // let inner = ... (&bar()) ...;
672 // (... (&foo()) ...) // (the tail expression)
673 // }, other_argument());
675 // Each of the statements within the block is a terminating
676 // scope, and thus a temporary (e.g. the result of calling
677 // `bar()` in the initalizer expression for `let inner = ...;`)
678 // will be cleaned up immediately after its corresponding
679 // statement (i.e. `let inner = ...;`) executes.
681 // On the other hand, temporaries associated with evaluating the
682 // tail expression for the block are assigned lifetimes so that
683 // they will be cleaned up as part of the terminating scope
684 // *surrounding* the block expression. Here, the terminating
685 // scope for the block expression is the `quux(..)` call; so
686 // those temporaries will only be cleaned up *after* both
687 // `other_argument()` has run and also the call to `quux(..)`
688 // itself has returned.
690 visitor.cx = Context {
691 root_id: prev_cx.root_id,
692 var_parent: InnermostDeclaringBlock::Block(blk.id),
693 parent: InnermostEnclosingExpr::Some(blk.id),
697 // This block should be kept approximately in sync with
698 // `visit::walk_block`. (We manually walk the block, rather
699 // than call `walk_block`, in order to maintain precise
700 // `InnermostDeclaringBlock` information.)
702 for (i, statement) in blk.stmts.iter().enumerate() {
703 if let ast::StmtDecl(_, stmt_id) = statement.node {
704 // Each StmtDecl introduces a subscope for bindings
705 // introduced by the declaration; this subscope covers
706 // a suffix of the block . Each subscope in a block
707 // has the previous subscope in the block as a parent,
708 // except for the first such subscope, which has the
709 // block itself as a parent.
710 let declaring = DeclaringStatementContext {
715 record_superlifetime(
716 visitor, declaring.to_code_extent(), statement.span);
717 visitor.cx = Context {
718 root_id: prev_cx.root_id,
719 var_parent: InnermostDeclaringBlock::Statement(declaring),
720 parent: InnermostEnclosingExpr::Statement(declaring),
723 visitor.visit_stmt(&**statement)
725 visit::walk_expr_opt(visitor, &blk.expr)
728 visitor.cx = prev_cx;
731 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
732 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
733 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
737 let guard_scope = CodeExtent::from_node_id(expr.id);
738 visitor.region_maps.mark_as_terminating_scope(guard_scope);
743 visit::walk_arm(visitor, arm);
746 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
747 record_superlifetime(visitor, CodeExtent::from_node_id(pat.id), pat.span);
749 // If this is a binding (or maybe a binding, I'm too lazy to check
750 // the def map) then record the lifetime of that binding.
752 ast::PatIdent(..) => {
753 record_var_lifetime(visitor, pat.id, pat.span);
758 visit::walk_pat(visitor, pat);
761 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
762 let stmt_id = stmt_id(stmt);
763 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
765 let stmt_scope = CodeExtent::from_node_id(stmt_id);
767 // Every statement will clean up the temporaries created during
768 // execution of that statement. Therefore each statement has an
769 // associated destruction scope that represents the extent of the
770 // statement plus its destructors, and thus the extent for which
771 // regions referenced by the destructors need to survive.
772 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
773 let dtor_scope = CodeExtent::DestructionScope(stmt_id);
774 visitor.region_maps.record_encl_scope(stmt_scope, dtor_scope);
775 record_superlifetime(visitor, dtor_scope, stmt.span);
777 let prev_parent = visitor.cx.parent;
778 visitor.cx.parent = InnermostEnclosingExpr::Some(stmt_id);
779 visit::walk_stmt(visitor, stmt);
780 visitor.cx.parent = prev_parent;
783 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
784 debug!("resolve_expr(expr.id={:?})", expr.id);
786 let expr_scope = CodeExtent::Misc(expr.id);
787 // If expr was previously marked as a terminating scope during the
788 // recursive visit of its parent node in the AST, then we need to
789 // account for the destruction scope representing the extent of
790 // the destructors that run immediately after the the expression
792 if visitor.region_maps.terminating_scopes.borrow().contains(&expr_scope) {
793 let dtor_scope = CodeExtent::DestructionScope(expr.id);
794 record_superlifetime(visitor, dtor_scope, expr.span);
795 visitor.region_maps.record_encl_scope(expr_scope, dtor_scope);
797 record_superlifetime(visitor, expr_scope, expr.span);
800 let prev_cx = visitor.cx;
801 visitor.cx.parent = InnermostEnclosingExpr::Some(expr.id);
804 let region_maps = &mut visitor.region_maps;
805 let terminating = |e: &P<ast::Expr>| {
806 let scope = CodeExtent::from_node_id(e.id);
807 region_maps.mark_as_terminating_scope(scope)
809 let terminating_block = |b: &P<ast::Block>| {
810 let scope = CodeExtent::from_node_id(b.id);
811 region_maps.mark_as_terminating_scope(scope)
814 // Conditional or repeating scopes are always terminating
815 // scopes, meaning that temporaries cannot outlive them.
816 // This ensures fixed size stacks.
818 ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
819 ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
820 // For shortcircuiting operators, mark the RHS as a terminating
821 // scope since it only executes conditionally.
825 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
826 terminating_block(then);
827 terminating(otherwise);
830 ast::ExprIf(ref expr, ref then, None) => {
832 terminating_block(then);
835 ast::ExprLoop(ref body, _) => {
836 terminating_block(body);
839 ast::ExprWhile(ref expr, ref body, _) => {
841 terminating_block(body);
844 ast::ExprMatch(..) => {
845 visitor.cx.var_parent = InnermostDeclaringBlock::Match(expr.id);
848 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
849 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
850 // FIXME(#6268) Nested method calls
852 // The lifetimes for a call or method call look as follows:
860 // The idea is that call.callee_id represents *the time when
861 // the invoked function is actually running* and call.id
862 // represents *the time to prepare the arguments and make the
863 // call*. See the section "Borrows in Calls" borrowck/README.md
864 // for an extended explanation of why this distinction is
867 // record_superlifetime(new_cx, expr.callee_id);
874 visit::walk_expr(visitor, expr);
875 visitor.cx = prev_cx;
878 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
879 debug!("resolve_local(local.id={:?},local.init={:?})",
880 local.id,local.init.is_some());
882 // For convenience in trans, associate with the local-id the var
883 // scope that will be used for any bindings declared in this
885 let blk_scope = visitor.cx.var_parent.to_code_extent()
886 .unwrap_or_else(|| visitor.sess.span_bug(
887 local.span, "local without enclosing block"));
889 visitor.region_maps.record_var_scope(local.id, blk_scope);
891 // As an exception to the normal rules governing temporary
892 // lifetimes, initializers in a let have a temporary lifetime
893 // of the enclosing block. This means that e.g. a program
894 // like the following is legal:
896 // let ref x = HashMap::new();
898 // Because the hash map will be freed in the enclosing block.
900 // We express the rules more formally based on 3 grammars (defined
901 // fully in the helpers below that implement them):
903 // 1. `E&`, which matches expressions like `&<rvalue>` that
904 // own a pointer into the stack.
906 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
907 // y)` that produce ref bindings into the value they are
908 // matched against or something (at least partially) owned by
909 // the value they are matched against. (By partially owned,
910 // I mean that creating a binding into a ref-counted or managed value
911 // would still count.)
913 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
914 // based on rvalues like `foo().x[2].y`.
916 // A subexpression `<rvalue>` that appears in a let initializer
917 // `let pat [: ty] = expr` has an extended temporary lifetime if
918 // any of the following conditions are met:
920 // A. `pat` matches `P&` and `expr` matches `ET`
921 // (covers cases where `pat` creates ref bindings into an rvalue
922 // produced by `expr`)
923 // B. `ty` is a borrowed pointer and `expr` matches `ET`
924 // (covers cases where coercion creates a borrow)
925 // C. `expr` matches `E&`
926 // (covers cases `expr` borrows an rvalue that is then assigned
927 // to memory (at least partially) owned by the binding)
929 // Here are some examples hopefully giving an intuition where each
930 // rule comes into play and why:
932 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
933 // would have an extended lifetime, but not `foo()`.
935 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
936 // would have an extended lifetime, but not `foo()`.
938 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
941 // In some cases, multiple rules may apply (though not to the same
942 // rvalue). For example:
944 // let ref x = [&a(), &b()];
946 // Here, the expression `[...]` has an extended lifetime due to rule
947 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
950 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
954 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
957 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
959 if is_binding_pat(&*local.pat) || is_borrow {
960 record_rvalue_scope(visitor, &**expr, blk_scope);
967 visit::walk_local(visitor, local);
969 /// True if `pat` match the `P&` nonterminal:
972 /// | StructName { ..., P&, ... }
973 /// | VariantName(..., P&, ...)
974 /// | [ ..., P&, ... ]
975 /// | ( ..., P&, ... )
977 fn is_binding_pat(pat: &ast::Pat) -> bool {
979 ast::PatIdent(ast::BindByRef(_), _, _) => true,
981 ast::PatStruct(_, ref field_pats, _) => {
982 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
985 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
986 pats1.iter().any(|p| is_binding_pat(&**p)) ||
987 pats2.iter().any(|p| is_binding_pat(&**p)) ||
988 pats3.iter().any(|p| is_binding_pat(&**p))
991 ast::PatEnum(_, Some(ref subpats)) |
992 ast::PatTup(ref subpats) => {
993 subpats.iter().any(|p| is_binding_pat(&**p))
996 ast::PatBox(ref subpat) => {
997 is_binding_pat(&**subpat)
1004 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
1005 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
1007 ast::TyRptr(..) => true,
1012 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1015 /// | StructName { ..., f: E&, ... }
1016 /// | [ ..., E&, ... ]
1017 /// | ( ..., E&, ... )
1022 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1024 blk_id: CodeExtent) {
1026 ast::ExprAddrOf(_, ref subexpr) => {
1027 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1028 record_rvalue_scope(visitor, &**subexpr, blk_id);
1030 ast::ExprStruct(_, ref fields, _) => {
1031 for field in fields {
1032 record_rvalue_scope_if_borrow_expr(
1033 visitor, &*field.expr, blk_id);
1036 ast::ExprVec(ref subexprs) |
1037 ast::ExprTup(ref subexprs) => {
1038 for subexpr in subexprs {
1039 record_rvalue_scope_if_borrow_expr(
1040 visitor, &**subexpr, blk_id);
1043 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
1044 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1046 ast::ExprCast(ref subexpr, _) |
1047 ast::ExprParen(ref subexpr) => {
1048 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1050 ast::ExprBlock(ref block) => {
1052 Some(ref subexpr) => {
1053 record_rvalue_scope_if_borrow_expr(
1054 visitor, &**subexpr, blk_id);
1064 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1065 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1066 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1069 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1070 /// `<rvalue>` as `blk_id`:
1078 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1079 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1080 expr: &'a ast::Expr,
1081 blk_scope: CodeExtent) {
1082 let mut expr = expr;
1084 // Note: give all the expressions matching `ET` with the
1085 // extended temporary lifetime, not just the innermost rvalue,
1086 // because in trans if we must compile e.g. `*rvalue()`
1087 // into a temporary, we request the temporary scope of the
1088 // outer expression.
1089 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1092 ast::ExprAddrOf(_, ref subexpr) |
1093 ast::ExprUnary(ast::UnDeref, ref subexpr) |
1094 ast::ExprField(ref subexpr, _) |
1095 ast::ExprTupField(ref subexpr, _) |
1096 ast::ExprIndex(ref subexpr, _) |
1097 ast::ExprParen(ref subexpr) => {
1108 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
1109 // Items create a new outer block scope as far as we're concerned.
1110 let prev_cx = visitor.cx;
1111 visitor.cx = Context {
1113 var_parent: InnermostDeclaringBlock::None,
1114 parent: InnermostEnclosingExpr::None
1116 visit::walk_item(visitor, item);
1117 visitor.cx = prev_cx;
1120 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1126 debug!("region::resolve_fn(id={:?}, \
1131 visitor.sess.codemap().span_to_string(sp),
1135 // This scope covers the function body, which includes the
1136 // bindings introduced by let statements as well as temporaries
1137 // created by the fn's tail expression (if any). It does *not*
1138 // include the fn parameters (see below).
1139 let body_scope = CodeExtent::from_node_id(body.id);
1140 visitor.region_maps.mark_as_terminating_scope(body_scope);
1142 let dtor_scope = CodeExtent::DestructionScope(body.id);
1143 visitor.region_maps.record_encl_scope(body_scope, dtor_scope);
1145 let fn_decl_scope = CodeExtent::ParameterScope { fn_id: id, body_id: body.id };
1146 visitor.region_maps.record_encl_scope(dtor_scope, fn_decl_scope);
1148 record_superlifetime(visitor, fn_decl_scope, body.span);
1150 if let Some(root_id) = visitor.cx.root_id {
1151 visitor.region_maps.record_fn_parent(body.id, root_id);
1154 let outer_cx = visitor.cx;
1156 // The arguments and `self` are parented to the fn.
1157 visitor.cx = Context {
1158 root_id: Some(body.id),
1159 parent: InnermostEnclosingExpr::None,
1160 var_parent: InnermostDeclaringBlock::FnDecl {
1161 fn_id: id, body_id: body.id
1164 visit::walk_fn_decl(visitor, decl);
1166 // The body of the every fn is a root scope.
1167 visitor.cx = Context {
1168 root_id: Some(body.id),
1169 parent: InnermostEnclosingExpr::None,
1170 var_parent: InnermostDeclaringBlock::None
1172 visitor.visit_block(body);
1174 // Restore context we had at the start.
1175 visitor.cx = outer_cx;
1178 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1180 fn visit_block(&mut self, b: &Block) {
1181 resolve_block(self, b);
1184 fn visit_item(&mut self, i: &Item) {
1185 resolve_item(self, i);
1188 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1189 b: &'v Block, s: Span, n: NodeId) {
1190 resolve_fn(self, fk, fd, b, s, n);
1192 fn visit_arm(&mut self, a: &Arm) {
1193 resolve_arm(self, a);
1195 fn visit_pat(&mut self, p: &Pat) {
1196 resolve_pat(self, p);
1198 fn visit_stmt(&mut self, s: &Stmt) {
1199 resolve_stmt(self, s);
1201 fn visit_expr(&mut self, ex: &Expr) {
1202 resolve_expr(self, ex);
1204 fn visit_local(&mut self, l: &Local) {
1205 resolve_local(self, l);
1209 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
1210 let maps = RegionMaps {
1211 scope_map: RefCell::new(FnvHashMap()),
1212 var_map: RefCell::new(NodeMap()),
1213 rvalue_scopes: RefCell::new(NodeMap()),
1214 terminating_scopes: RefCell::new(FnvHashSet()),
1215 fn_tree: RefCell::new(NodeMap()),
1218 let mut visitor = RegionResolutionVisitor {
1223 parent: InnermostEnclosingExpr::None,
1224 var_parent: InnermostDeclaringBlock::None,
1227 visit::walk_crate(&mut visitor, krate);
1232 pub fn resolve_inlined_item(sess: &Session,
1233 region_maps: &RegionMaps,
1234 item: &ast::InlinedItem) {
1235 let mut visitor = RegionResolutionVisitor {
1237 region_maps: region_maps,
1240 parent: InnermostEnclosingExpr::None,
1241 var_parent: InnermostDeclaringBlock::None
1244 visit::walk_inlined_item(&mut visitor, item);