1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This file actually contains two passes related to regions. The first
12 //! pass builds up the `scope_map`, which describes the parent links in
13 //! the region hierarchy. The second pass infers which types must be
14 //! region parameterized.
16 //! Most of the documentation on regions can be found in
17 //! `middle/typeck/infer/region_inference.rs`
20 use middle::ty::{self, Ty, FreeRegion};
21 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
22 use util::common::can_reach;
24 use std::cell::RefCell;
25 use syntax::codemap::{self, Span};
26 use syntax::{ast, visit};
27 use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local};
28 use syntax::ast_util::{stmt_id};
31 use syntax::visit::{Visitor, FnKind};
33 /// CodeExtent represents a statically-describable extent that can be
34 /// used to bound the lifetime/region for values.
36 /// `Misc(node_id)`: Any AST node that has any extent at all has the
37 /// `Misc(node_id)` extent. Other variants represent special cases not
38 /// immediately derivable from the abstract syntax tree structure.
40 /// `DestructionScope(node_id)` represents the extent of destructors
41 /// implicitly-attached to `node_id` that run immediately after the
42 /// expression for `node_id` itself. Not every AST node carries a
43 /// `DestructionScope`, but those that are `terminating_scopes` do;
44 /// see discussion with `RegionMaps`.
46 /// `Remainder(BlockRemainder { block, statement_index })` represents
47 /// the extent of user code running immediately after the initializer
48 /// expression for the indexed statement, until the end of the block.
50 /// So: the following code can be broken down into the extents beneath:
52 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
57 /// +---------+ (R10.)
59 /// +----------+ (M8.)
60 /// +----------------------+ (R7.)
62 /// +----------+ (M5.)
63 /// +-----------------------------------+ (M4.)
64 /// +--------------------------------------------------+ (M3.)
66 /// +-----------------------------------------------------------+ (M1.)
68 /// (M1.): Misc extent of the whole `let a = ...;` statement.
69 /// (M2.): Misc extent of the `f()` expression.
70 /// (M3.): Misc extent of the `f().g(..)` expression.
71 /// (M4.): Misc extent of the block labelled `'b:`.
72 /// (M5.): Misc extent of the `let x = d();` statement
73 /// (D6.): DestructionScope for temporaries created during M5.
74 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
75 /// (M8.): Misc Extent of the `let y = d();` statement.
76 /// (D9.): DestructionScope for temporaries created during M8.
77 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
78 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
79 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
81 /// Note that while the above picture shows the destruction scopes
82 /// as following their corresponding misc extents, in the internal
83 /// data structures of the compiler the destruction scopes are
84 /// represented as enclosing parents. This is sound because we use the
85 /// enclosing parent relationship just to ensure that referenced
86 /// values live long enough; phrased another way, the starting point
87 /// of each range is not really the important thing in the above
88 /// picture, but rather the ending point.
90 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
91 /// placate the same deriving in `ty::FreeRegion`, but we may want to
92 /// actually attach a more meaningful ordering to scopes than the one
93 /// generated via deriving here.
94 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
95 RustcDecodable, Debug, Copy)]
98 DestructionScope(ast::NodeId), // extent of destructors for temporaries of node-id
99 Remainder(BlockRemainder)
102 /// extent of destructors for temporaries of node-id
103 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
104 RustcDecodable, Debug, Copy)]
105 pub struct DestructionScopeData {
106 pub node_id: ast::NodeId
109 impl DestructionScopeData {
110 pub fn new(node_id: ast::NodeId) -> DestructionScopeData {
111 DestructionScopeData { node_id: node_id }
113 pub fn to_code_extent(&self) -> CodeExtent {
114 CodeExtent::DestructionScope(self.node_id)
118 /// Represents a subscope of `block` for a binding that is introduced
119 /// by `block.stmts[first_statement_index]`. Such subscopes represent
120 /// a suffix of the block. Note that each subscope does not include
121 /// the initializer expression, if any, for the statement indexed by
122 /// `first_statement_index`.
124 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
126 /// * the subscope with `first_statement_index == 0` is scope of both
127 /// `a` and `b`; it does not include EXPR_1, but does include
128 /// everything after that first `let`. (If you want a scope that
129 /// includes EXPR_1 as well, then do not use `CodeExtent::Remainder`,
130 /// but instead another `CodeExtent` that encompasses the whole block,
131 /// e.g. `CodeExtent::Misc`.
133 /// * the subscope with `first_statement_index == 1` is scope of `c`,
134 /// and thus does not include EXPR_2, but covers the `...`.
135 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
136 RustcDecodable, Debug, Copy)]
137 pub struct BlockRemainder {
138 pub block: ast::NodeId,
139 pub first_statement_index: uint,
143 /// Creates a scope that represents the dynamic extent associated
145 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
146 CodeExtent::Misc(node_id)
149 /// Returns a node id associated with this scope.
151 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
152 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
153 pub fn node_id(&self) -> ast::NodeId {
155 CodeExtent::Misc(node_id) => node_id,
156 CodeExtent::Remainder(br) => br.block,
157 CodeExtent::DestructionScope(node_id) => node_id,
161 /// Maps this scope to a potentially new one according to the
162 /// NodeId transformer `f_id`.
163 pub fn map_id<F>(&self, f_id: F) -> CodeExtent where
164 F: FnOnce(ast::NodeId) -> ast::NodeId,
167 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
168 CodeExtent::Remainder(br) =>
169 CodeExtent::Remainder(BlockRemainder {
170 block: f_id(br.block), first_statement_index: br.first_statement_index }),
171 CodeExtent::DestructionScope(node_id) =>
172 CodeExtent::DestructionScope(f_id(node_id)),
176 /// Returns the span of this CodeExtent. Note that in general the
177 /// returned span may not correspond to the span of any node id in
179 pub fn span(&self, ast_map: &ast_map::Map) -> Option<Span> {
180 match ast_map.find(self.node_id()) {
181 Some(ast_map::NodeBlock(ref blk)) => {
183 CodeExtent::Misc(_) |
184 CodeExtent::DestructionScope(_) => Some(blk.span),
186 CodeExtent::Remainder(r) => {
187 assert_eq!(r.block, blk.id);
188 // Want span for extent starting after the
189 // indexed statement and ending at end of
190 // `blk`; reuse span of `blk` and shift `lo`
191 // forward to end of indexed statement.
193 // (This is the special case aluded to in the
194 // doc-comment for this method)
195 let stmt_span = blk.stmts[r.first_statement_index].span;
196 Some(Span { lo: stmt_span.hi, ..blk.span })
200 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
201 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
202 Some(ast_map::NodeItem(ref item)) => Some(item.span),
203 Some(_) | None => None,
208 /// The region maps encode information about region relationships.
210 /// - `scope_map` maps from a scope id to the enclosing scope id; this is
211 /// usually corresponding to the lexical nesting, though in the case of
212 /// closures the parent scope is the innermost conditional expression or repeating
213 /// block. (Note that the enclosing scope id for the block
214 /// associated with a closure is the closure itself.)
216 /// - `var_map` maps from a variable or binding id to the block in which
217 /// that variable is declared.
219 /// - `free_region_map` maps from a free region `a` to a list of free
220 /// regions `bs` such that `a <= b for all b in bs`
221 /// - the free region map is populated during type check as we check
222 /// each function. See the function `relate_free_regions` for
223 /// more information.
225 /// - `rvalue_scopes` includes entries for those expressions whose cleanup
226 /// scope is larger than the default. The map goes from the expression
227 /// id to the cleanup scope id. For rvalues not present in this table,
228 /// the appropriate cleanup scope is the innermost enclosing statement,
229 /// conditional expression, or repeating block (see `terminating_scopes`).
231 /// - `terminating_scopes` is a set containing the ids of each statement,
232 /// or conditional/repeating expression. These scopes are calling "terminating
233 /// scopes" because, when attempting to find the scope of a temporary, by
234 /// default we search up the enclosing scopes until we encounter the
235 /// terminating scope. A conditional/repeating
236 /// expression is one which is not guaranteed to execute exactly once
237 /// upon entering the parent scope. This could be because the expression
238 /// only executes conditionally, such as the expression `b` in `a && b`,
239 /// or because the expression may execute many times, such as a loop
240 /// body. The reason that we distinguish such expressions is that, upon
241 /// exiting the parent scope, we cannot statically know how many times
242 /// the expression executed, and thus if the expression creates
243 /// temporaries we cannot know statically how many such temporaries we
244 /// would have to cleanup. Therefore we ensure that the temporaries never
245 /// outlast the conditional/repeating expression, preventing the need
246 /// for dynamic checks and/or arbitrary amounts of stack space.
247 pub struct RegionMaps {
248 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
249 var_map: RefCell<NodeMap<CodeExtent>>,
250 free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
251 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
252 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
255 /// Carries the node id for the innermost block or match expression,
256 /// for building up the `var_map` which maps ids to the blocks in
257 /// which they were declared.
258 #[derive(PartialEq, Eq, Debug, Copy)]
259 enum InnermostDeclaringBlock {
262 Statement(DeclaringStatementContext),
266 impl InnermostDeclaringBlock {
267 fn to_code_extent(&self) -> Option<CodeExtent> {
268 let extent = match *self {
269 InnermostDeclaringBlock::None => {
272 InnermostDeclaringBlock::Block(id) |
273 InnermostDeclaringBlock::Match(id) => CodeExtent::from_node_id(id),
274 InnermostDeclaringBlock::Statement(s) => s.to_code_extent(),
280 /// Contextual information for declarations introduced by a statement
281 /// (i.e. `let`). It carries node-id's for statement and enclosing
282 /// block both, as well as the statement's index within the block.
283 #[derive(PartialEq, Eq, Debug, Copy)]
284 struct DeclaringStatementContext {
285 stmt_id: ast::NodeId,
286 block_id: ast::NodeId,
290 impl DeclaringStatementContext {
291 fn to_code_extent(&self) -> CodeExtent {
292 CodeExtent::Remainder(BlockRemainder {
293 block: self.block_id,
294 first_statement_index: self.stmt_index,
299 #[derive(PartialEq, Eq, Debug, Copy)]
300 enum InnermostEnclosingExpr {
303 Statement(DeclaringStatementContext),
306 impl InnermostEnclosingExpr {
307 fn to_code_extent(&self) -> Option<CodeExtent> {
308 let extent = match *self {
309 InnermostEnclosingExpr::None => {
312 InnermostEnclosingExpr::Statement(s) =>
314 InnermostEnclosingExpr::Some(parent_id) =>
315 CodeExtent::from_node_id(parent_id),
321 #[derive(Debug, Copy)]
323 /// the scope that contains any new variables declared
324 var_parent: InnermostDeclaringBlock,
326 /// region parent of expressions etc
327 parent: InnermostEnclosingExpr,
330 struct RegionResolutionVisitor<'a> {
334 region_maps: &'a RegionMaps,
341 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
342 for (child, parent) in self.scope_map.borrow().iter() {
346 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
347 for (child, parent) in self.var_map.borrow().iter() {
351 pub fn each_encl_free_region<E>(&self, mut e:E) where E: FnMut(&FreeRegion, &FreeRegion) {
352 for (child, parents) in self.free_region_map.borrow().iter() {
353 for parent in parents.iter() {
358 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
359 for (child, parent) in self.rvalue_scopes.borrow().iter() {
363 pub fn each_terminating_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent) {
364 for scope in self.terminating_scopes.borrow().iter() {
369 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
370 match self.free_region_map.borrow_mut().get_mut(&sub) {
372 if !sups.iter().any(|x| x == &sup) {
380 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
381 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
384 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
385 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
387 self.scope_map.borrow_mut().insert(sub, sup);
390 pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
391 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
392 assert!(var != lifetime.node_id());
393 self.var_map.borrow_mut().insert(var, lifetime);
396 pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
397 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
398 assert!(var != lifetime.node_id());
399 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
402 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
403 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
405 pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
406 debug!("record_terminating_scope(scope_id={:?})", scope_id);
407 self.terminating_scopes.borrow_mut().insert(scope_id);
410 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
411 //! Returns the narrowest scope that encloses `id`, if any.
412 self.scope_map.borrow().get(&id).cloned()
415 #[allow(dead_code)] // used in middle::cfg
416 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
417 //! Returns the narrowest scope that encloses `id`, if any.
418 match self.scope_map.borrow().get(&id) {
420 None => { panic!("no enclosing scope for id {:?}", id); }
424 /// Returns the lifetime of the local variable `var_id`
425 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
426 match self.var_map.borrow().get(&var_id) {
428 None => { panic!("no enclosing scope for id {:?}", var_id); }
432 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
433 //! Returns the scope when temp created by expr_id will be cleaned up
435 // check for a designated rvalue scope
436 match self.rvalue_scopes.borrow().get(&expr_id) {
438 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
444 // else, locate the innermost terminating scope
445 // if there's one. Static items, for instance, won't
446 // have an enclosing scope, hence no scope will be
448 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
450 None => { return None; }
453 while !self.terminating_scopes.borrow().contains(&id) {
454 match self.opt_encl_scope(id) {
459 debug!("temporary_scope({:?}) = None", expr_id);
464 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
468 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
469 //! Returns the lifetime of the variable `id`.
471 let scope = ty::ReScope(self.var_scope(id));
472 debug!("var_region({:?}) = {:?}", id, scope);
476 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
478 self.is_subscope_of(scope1, scope2) ||
479 self.is_subscope_of(scope2, scope1)
482 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
484 pub fn is_subscope_of(&self,
485 subscope: CodeExtent,
486 superscope: CodeExtent)
488 let mut s = subscope;
489 while superscope != s {
490 match self.scope_map.borrow().get(&s) {
492 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
493 subscope, superscope, s);
497 Some(&scope) => s = scope
501 debug!("is_subscope_of({:?}, {:?})=true",
502 subscope, superscope);
507 /// Determines whether two free regions have a subregion relationship
508 /// by walking the graph encoded in `free_region_map`. Note that
509 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
510 /// (that is, the user can give two different names to the same lifetime).
511 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
512 can_reach(&*self.free_region_map.borrow(), sub, sup)
515 /// Determines whether one region is a subregion of another. This is intended to run *after
516 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
517 pub fn is_subregion_of(&self,
518 sub_region: ty::Region,
519 super_region: ty::Region)
521 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
522 sub_region, super_region);
524 sub_region == super_region || {
525 match (sub_region, super_region) {
527 (_, ty::ReStatic) => {
531 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
532 self.is_subscope_of(sub_scope, super_scope)
535 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
536 self.is_subscope_of(sub_scope, fr.scope.to_code_extent())
539 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
540 self.sub_free_region(sub_fr, super_fr)
543 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
544 ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
545 // This case is used only to make sure that explicitly-
546 // specified `Self` types match the real self type in
548 param_id_a == param_id_b &&
549 param_space_a == param_space_b &&
560 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
561 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
562 pub fn nearest_common_ancestor(&self,
565 -> Option<CodeExtent> {
566 if scope_a == scope_b { return Some(scope_a); }
568 let a_ancestors = ancestors_of(self, scope_a);
569 let b_ancestors = ancestors_of(self, scope_b);
570 let mut a_index = a_ancestors.len() - 1;
571 let mut b_index = b_ancestors.len() - 1;
573 // Here, ~[ab]_ancestors is a vector going from narrow to broad.
574 // The end of each vector will be the item where the scope is
575 // defined; if there are any common ancestors, then the tails of
576 // the vector will be the same. So basically we want to walk
577 // backwards from the tail of each vector and find the first point
578 // where they diverge. If one vector is a suffix of the other,
579 // then the corresponding scope is a superscope of the other.
581 if a_ancestors[a_index] != b_ancestors[b_index] {
586 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
587 // for all indices between a_index and the end of the array
588 if a_index == 0 { return Some(scope_a); }
589 if b_index == 0 { return Some(scope_b); }
592 if a_ancestors[a_index] != b_ancestors[b_index] {
593 return Some(a_ancestors[a_index + 1]);
597 fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
599 // debug!("ancestors_of(scope={:?})", scope);
600 let mut result = vec!(scope);
601 let mut scope = scope;
603 match this.scope_map.borrow().get(&scope) {
604 None => return result,
605 Some(&superscope) => {
606 result.push(superscope);
610 // debug!("ancestors_of_loop(scope={:?})", scope);
616 /// Records the current parent (if any) as the parent of `child_scope`.
617 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
618 child_scope: CodeExtent,
620 match visitor.cx.parent.to_code_extent() {
621 Some(parent_scope) =>
622 visitor.region_maps.record_encl_scope(child_scope, parent_scope),
627 /// Records the lifetime of a local variable as `cx.var_parent`
628 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
631 match visitor.cx.var_parent.to_code_extent() {
632 Some(parent_scope) =>
633 visitor.region_maps.record_var_scope(var_id, parent_scope),
635 // this can happen in extern fn declarations like
637 // extern fn isalnum(c: c_int) -> c_int
642 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
643 debug!("resolve_block(blk.id={:?})", blk.id);
645 let prev_cx = visitor.cx;
647 let blk_scope = CodeExtent::Misc(blk.id);
648 // If block was previously marked as a terminating scope during
649 // the recursive visit of its parent node in the AST, then we need
650 // to account for the destruction scope representing the extent of
651 // the destructors that run immediately after the the block itself
653 if visitor.region_maps.terminating_scopes.borrow().contains(&blk_scope) {
654 let dtor_scope = CodeExtent::DestructionScope(blk.id);
655 record_superlifetime(visitor, dtor_scope, blk.span);
656 visitor.region_maps.record_encl_scope(blk_scope, dtor_scope);
658 record_superlifetime(visitor, blk_scope, blk.span);
661 // We treat the tail expression in the block (if any) somewhat
662 // differently from the statements. The issue has to do with
663 // temporary lifetimes. Consider the following:
666 // let inner = ... (&bar()) ...;
668 // (... (&foo()) ...) // (the tail expression)
669 // }, other_argument());
671 // Each of the statements within the block is a terminating
672 // scope, and thus a temporary (e.g. the result of calling
673 // `bar()` in the initalizer expression for `let inner = ...;`)
674 // will be cleaned up immediately after its corresponding
675 // statement (i.e. `let inner = ...;`) executes.
677 // On the other hand, temporaries associated with evaluating the
678 // tail expression for the block are assigned lifetimes so that
679 // they will be cleaned up as part of the terminating scope
680 // *surrounding* the block expression. Here, the terminating
681 // scope for the block expression is the `quux(..)` call; so
682 // those temporaries will only be cleaned up *after* both
683 // `other_argument()` has run and also the call to `quux(..)`
684 // itself has returned.
686 visitor.cx = Context {
687 var_parent: InnermostDeclaringBlock::Block(blk.id),
688 parent: InnermostEnclosingExpr::Some(blk.id),
692 // This block should be kept approximately in sync with
693 // `visit::walk_block`. (We manually walk the block, rather
694 // than call `walk_block`, in order to maintain precise
695 // `InnermostDeclaringBlock` information.)
697 for (i, statement) in blk.stmts.iter().enumerate() {
698 if let ast::StmtDecl(_, stmt_id) = statement.node {
699 // Each StmtDecl introduces a subscope for bindings
700 // introduced by the declaration; this subscope covers
701 // a suffix of the block . Each subscope in a block
702 // has the previous subscope in the block as a parent,
703 // except for the first such subscope, which has the
704 // block itself as a parent.
705 let declaring = DeclaringStatementContext {
710 record_superlifetime(
711 visitor, declaring.to_code_extent(), statement.span);
712 visitor.cx = Context {
713 var_parent: InnermostDeclaringBlock::Statement(declaring),
714 parent: InnermostEnclosingExpr::Statement(declaring),
717 visitor.visit_stmt(&**statement)
719 visit::walk_expr_opt(visitor, &blk.expr)
722 visitor.cx = prev_cx;
725 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
726 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
727 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
731 let guard_scope = CodeExtent::from_node_id(expr.id);
732 visitor.region_maps.mark_as_terminating_scope(guard_scope);
737 visit::walk_arm(visitor, arm);
740 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
741 record_superlifetime(visitor, CodeExtent::from_node_id(pat.id), pat.span);
743 // If this is a binding (or maybe a binding, I'm too lazy to check
744 // the def map) then record the lifetime of that binding.
746 ast::PatIdent(..) => {
747 record_var_lifetime(visitor, pat.id, pat.span);
752 visit::walk_pat(visitor, pat);
755 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
756 let stmt_id = stmt_id(stmt);
757 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
759 let stmt_scope = CodeExtent::from_node_id(stmt_id);
761 // Every statement will clean up the temporaries created during
762 // execution of that statement. Therefore each statement has an
763 // associated destruction scope that represents the extent of the
764 // statement plus its destructors, and thus the extent for which
765 // regions referenced by the destructors need to survive.
766 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
767 let dtor_scope = CodeExtent::DestructionScope(stmt_id);
768 visitor.region_maps.record_encl_scope(stmt_scope, dtor_scope);
769 record_superlifetime(visitor, dtor_scope, stmt.span);
771 let prev_parent = visitor.cx.parent;
772 visitor.cx.parent = InnermostEnclosingExpr::Some(stmt_id);
773 visit::walk_stmt(visitor, stmt);
774 visitor.cx.parent = prev_parent;
777 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
778 debug!("resolve_expr(expr.id={:?})", expr.id);
780 let expr_scope = CodeExtent::Misc(expr.id);
781 // If expr was previously marked as a terminating scope during the
782 // recursive visit of its parent node in the AST, then we need to
783 // account for the destruction scope representing the extent of
784 // the destructors that run immediately after the the expression
786 if visitor.region_maps.terminating_scopes.borrow().contains(&expr_scope) {
787 let dtor_scope = CodeExtent::DestructionScope(expr.id);
788 record_superlifetime(visitor, dtor_scope, expr.span);
789 visitor.region_maps.record_encl_scope(expr_scope, dtor_scope);
791 record_superlifetime(visitor, expr_scope, expr.span);
794 let prev_cx = visitor.cx;
795 visitor.cx.parent = InnermostEnclosingExpr::Some(expr.id);
798 let region_maps = &mut visitor.region_maps;
799 let terminating = |e: &P<ast::Expr>| {
800 let scope = CodeExtent::from_node_id(e.id);
801 region_maps.mark_as_terminating_scope(scope)
803 let terminating_block = |b: &P<ast::Block>| {
804 let scope = CodeExtent::from_node_id(b.id);
805 region_maps.mark_as_terminating_scope(scope)
808 // Conditional or repeating scopes are always terminating
809 // scopes, meaning that temporaries cannot outlive them.
810 // This ensures fixed size stacks.
812 ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
813 ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
814 // For shortcircuiting operators, mark the RHS as a terminating
815 // scope since it only executes conditionally.
819 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
820 terminating_block(then);
821 terminating(otherwise);
824 ast::ExprIf(ref expr, ref then, None) => {
826 terminating_block(then);
829 ast::ExprLoop(ref body, _) => {
830 terminating_block(body);
833 ast::ExprWhile(ref expr, ref body, _) => {
835 terminating_block(body);
838 ast::ExprMatch(..) => {
839 visitor.cx.var_parent = InnermostDeclaringBlock::Match(expr.id);
842 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
843 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
844 // FIXME(#6268) Nested method calls
846 // The lifetimes for a call or method call look as follows:
854 // The idea is that call.callee_id represents *the time when
855 // the invoked function is actually running* and call.id
856 // represents *the time to prepare the arguments and make the
857 // call*. See the section "Borrows in Calls" borrowck/README.md
858 // for an extended explanation of why this distinction is
861 // record_superlifetime(new_cx, expr.callee_id);
868 visit::walk_expr(visitor, expr);
869 visitor.cx = prev_cx;
872 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
873 debug!("resolve_local(local.id={:?},local.init={:?})",
874 local.id,local.init.is_some());
876 // For convenience in trans, associate with the local-id the var
877 // scope that will be used for any bindings declared in this
879 let blk_scope = visitor.cx.var_parent.to_code_extent()
880 .unwrap_or_else(|| visitor.sess.span_bug(
881 local.span, "local without enclosing block"));
883 visitor.region_maps.record_var_scope(local.id, blk_scope);
885 // As an exception to the normal rules governing temporary
886 // lifetimes, initializers in a let have a temporary lifetime
887 // of the enclosing block. This means that e.g. a program
888 // like the following is legal:
890 // let ref x = HashMap::new();
892 // Because the hash map will be freed in the enclosing block.
894 // We express the rules more formally based on 3 grammars (defined
895 // fully in the helpers below that implement them):
897 // 1. `E&`, which matches expressions like `&<rvalue>` that
898 // own a pointer into the stack.
900 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
901 // y)` that produce ref bindings into the value they are
902 // matched against or something (at least partially) owned by
903 // the value they are matched against. (By partially owned,
904 // I mean that creating a binding into a ref-counted or managed value
905 // would still count.)
907 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
908 // based on rvalues like `foo().x[2].y`.
910 // A subexpression `<rvalue>` that appears in a let initializer
911 // `let pat [: ty] = expr` has an extended temporary lifetime if
912 // any of the following conditions are met:
914 // A. `pat` matches `P&` and `expr` matches `ET`
915 // (covers cases where `pat` creates ref bindings into an rvalue
916 // produced by `expr`)
917 // B. `ty` is a borrowed pointer and `expr` matches `ET`
918 // (covers cases where coercion creates a borrow)
919 // C. `expr` matches `E&`
920 // (covers cases `expr` borrows an rvalue that is then assigned
921 // to memory (at least partially) owned by the binding)
923 // Here are some examples hopefully giving an intuition where each
924 // rule comes into play and why:
926 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
927 // would have an extended lifetime, but not `foo()`.
929 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
930 // would have an extended lifetime, but not `foo()`.
932 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
935 // In some cases, multiple rules may apply (though not to the same
936 // rvalue). For example:
938 // let ref x = [&a(), &b()];
940 // Here, the expression `[...]` has an extended lifetime due to rule
941 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
944 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
948 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
951 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
953 if is_binding_pat(&*local.pat) || is_borrow {
954 record_rvalue_scope(visitor, &**expr, blk_scope);
961 visit::walk_local(visitor, local);
963 /// True if `pat` match the `P&` nonterminal:
966 /// | StructName { ..., P&, ... }
967 /// | VariantName(..., P&, ...)
968 /// | [ ..., P&, ... ]
969 /// | ( ..., P&, ... )
971 fn is_binding_pat(pat: &ast::Pat) -> bool {
973 ast::PatIdent(ast::BindByRef(_), _, _) => true,
975 ast::PatStruct(_, ref field_pats, _) => {
976 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
979 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
980 pats1.iter().any(|p| is_binding_pat(&**p)) ||
981 pats2.iter().any(|p| is_binding_pat(&**p)) ||
982 pats3.iter().any(|p| is_binding_pat(&**p))
985 ast::PatEnum(_, Some(ref subpats)) |
986 ast::PatTup(ref subpats) => {
987 subpats.iter().any(|p| is_binding_pat(&**p))
990 ast::PatBox(ref subpat) => {
991 is_binding_pat(&**subpat)
998 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
999 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
1001 ast::TyRptr(..) => true,
1006 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1009 /// | StructName { ..., f: E&, ... }
1010 /// | [ ..., E&, ... ]
1011 /// | ( ..., E&, ... )
1016 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1018 blk_id: CodeExtent) {
1020 ast::ExprAddrOf(_, ref subexpr) => {
1021 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1022 record_rvalue_scope(visitor, &**subexpr, blk_id);
1024 ast::ExprStruct(_, ref fields, _) => {
1025 for field in fields {
1026 record_rvalue_scope_if_borrow_expr(
1027 visitor, &*field.expr, blk_id);
1030 ast::ExprVec(ref subexprs) |
1031 ast::ExprTup(ref subexprs) => {
1032 for subexpr in subexprs {
1033 record_rvalue_scope_if_borrow_expr(
1034 visitor, &**subexpr, blk_id);
1037 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
1038 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1040 ast::ExprCast(ref subexpr, _) |
1041 ast::ExprParen(ref subexpr) => {
1042 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1044 ast::ExprBlock(ref block) => {
1046 Some(ref subexpr) => {
1047 record_rvalue_scope_if_borrow_expr(
1048 visitor, &**subexpr, blk_id);
1058 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1059 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1060 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1063 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1064 /// `<rvalue>` as `blk_id`:
1072 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1073 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1074 expr: &'a ast::Expr,
1075 blk_scope: CodeExtent) {
1076 let mut expr = expr;
1078 // Note: give all the expressions matching `ET` with the
1079 // extended temporary lifetime, not just the innermost rvalue,
1080 // because in trans if we must compile e.g. `*rvalue()`
1081 // into a temporary, we request the temporary scope of the
1082 // outer expression.
1083 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1086 ast::ExprAddrOf(_, ref subexpr) |
1087 ast::ExprUnary(ast::UnDeref, ref subexpr) |
1088 ast::ExprField(ref subexpr, _) |
1089 ast::ExprTupField(ref subexpr, _) |
1090 ast::ExprIndex(ref subexpr, _) |
1091 ast::ExprParen(ref subexpr) => {
1102 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
1103 // Items create a new outer block scope as far as we're concerned.
1104 let prev_cx = visitor.cx;
1105 visitor.cx = Context {
1106 var_parent: InnermostDeclaringBlock::None,
1107 parent: InnermostEnclosingExpr::None
1109 visit::walk_item(visitor, item);
1110 visitor.cx = prev_cx;
1113 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1119 debug!("region::resolve_fn(id={:?}, \
1124 visitor.sess.codemap().span_to_string(sp),
1128 let body_scope = CodeExtent::from_node_id(body.id);
1129 visitor.region_maps.mark_as_terminating_scope(body_scope);
1130 let dtor_scope = CodeExtent::DestructionScope(body.id);
1131 visitor.region_maps.record_encl_scope(body_scope, dtor_scope);
1132 record_superlifetime(visitor, dtor_scope, body.span);
1134 let outer_cx = visitor.cx;
1136 // The arguments and `self` are parented to the body of the fn.
1137 visitor.cx = Context {
1138 parent: InnermostEnclosingExpr::Some(body.id),
1139 var_parent: InnermostDeclaringBlock::Block(body.id)
1141 visit::walk_fn_decl(visitor, decl);
1143 // The body of the fn itself is either a root scope (top-level fn)
1144 // or it continues with the inherited scope (closures).
1146 visit::FkItemFn(..) | visit::FkMethod(..) => {
1147 visitor.cx = Context {
1148 parent: InnermostEnclosingExpr::None,
1149 var_parent: InnermostDeclaringBlock::None
1151 visitor.visit_block(body);
1152 visitor.cx = outer_cx;
1154 visit::FkFnBlock(..) => {
1155 // FIXME(#3696) -- at present we are place the closure body
1156 // within the region hierarchy exactly where it appears lexically.
1157 // This is wrong because the closure may live longer
1158 // than the enclosing expression. We should probably fix this,
1159 // but the correct fix is a bit subtle, and I am also not sure
1160 // that the present approach is unsound -- it may not permit
1161 // any illegal programs. See issue for more details.
1162 visitor.cx = outer_cx;
1163 visitor.visit_block(body);
1168 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1170 fn visit_block(&mut self, b: &Block) {
1171 resolve_block(self, b);
1174 fn visit_item(&mut self, i: &Item) {
1175 resolve_item(self, i);
1178 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1179 b: &'v Block, s: Span, n: NodeId) {
1180 resolve_fn(self, fk, fd, b, s, n);
1182 fn visit_arm(&mut self, a: &Arm) {
1183 resolve_arm(self, a);
1185 fn visit_pat(&mut self, p: &Pat) {
1186 resolve_pat(self, p);
1188 fn visit_stmt(&mut self, s: &Stmt) {
1189 resolve_stmt(self, s);
1191 fn visit_expr(&mut self, ex: &Expr) {
1192 resolve_expr(self, ex);
1194 fn visit_local(&mut self, l: &Local) {
1195 resolve_local(self, l);
1199 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
1200 let maps = RegionMaps {
1201 scope_map: RefCell::new(FnvHashMap()),
1202 var_map: RefCell::new(NodeMap()),
1203 free_region_map: RefCell::new(FnvHashMap()),
1204 rvalue_scopes: RefCell::new(NodeMap()),
1205 terminating_scopes: RefCell::new(FnvHashSet()),
1208 let mut visitor = RegionResolutionVisitor {
1212 parent: InnermostEnclosingExpr::None,
1213 var_parent: InnermostDeclaringBlock::None,
1216 visit::walk_crate(&mut visitor, krate);
1221 pub fn resolve_inlined_item(sess: &Session,
1222 region_maps: &RegionMaps,
1223 item: &ast::InlinedItem) {
1224 let mut visitor = RegionResolutionVisitor {
1226 region_maps: region_maps,
1228 parent: InnermostEnclosingExpr::None,
1229 var_parent: InnermostDeclaringBlock::None
1232 visit::walk_inlined_item(&mut visitor, item);