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 var_parent: InnermostDeclaringBlock,
325 parent: InnermostEnclosingExpr,
328 struct RegionResolutionVisitor<'a> {
332 region_maps: &'a RegionMaps,
339 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
340 for (child, parent) in self.scope_map.borrow().iter() {
344 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
345 for (child, parent) in self.var_map.borrow().iter() {
349 pub fn each_encl_free_region<E>(&self, mut e:E) where E: FnMut(&FreeRegion, &FreeRegion) {
350 for (child, parents) in self.free_region_map.borrow().iter() {
351 for parent in parents.iter() {
356 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
357 for (child, parent) in self.rvalue_scopes.borrow().iter() {
361 pub fn each_terminating_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent) {
362 for scope in self.terminating_scopes.borrow().iter() {
367 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
368 match self.free_region_map.borrow_mut().get_mut(&sub) {
370 if !sups.iter().any(|x| x == &sup) {
378 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
379 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
382 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
383 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
385 self.scope_map.borrow_mut().insert(sub, sup);
388 pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
389 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
390 assert!(var != lifetime.node_id());
391 self.var_map.borrow_mut().insert(var, lifetime);
394 pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
395 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
396 assert!(var != lifetime.node_id());
397 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
400 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
401 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
403 pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
404 debug!("record_terminating_scope(scope_id={:?})", scope_id);
405 self.terminating_scopes.borrow_mut().insert(scope_id);
408 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
409 //! Returns the narrowest scope that encloses `id`, if any.
410 self.scope_map.borrow().get(&id).map(|x| *x)
413 #[allow(dead_code)] // used in middle::cfg
414 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
415 //! Returns the narrowest scope that encloses `id`, if any.
416 match self.scope_map.borrow().get(&id) {
418 None => { panic!("no enclosing scope for id {:?}", id); }
422 /// Returns the lifetime of the local variable `var_id`
423 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
424 match self.var_map.borrow().get(&var_id) {
426 None => { panic!("no enclosing scope for id {:?}", var_id); }
430 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
431 //! Returns the scope when temp created by expr_id will be cleaned up
433 // check for a designated rvalue scope
434 match self.rvalue_scopes.borrow().get(&expr_id) {
436 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
442 // else, locate the innermost terminating scope
443 // if there's one. Static items, for instance, won't
444 // have an enclosing scope, hence no scope will be
446 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
448 None => { return None; }
451 while !self.terminating_scopes.borrow().contains(&id) {
452 match self.opt_encl_scope(id) {
457 debug!("temporary_scope({:?}) = None", expr_id);
462 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
466 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
467 //! Returns the lifetime of the variable `id`.
469 let scope = ty::ReScope(self.var_scope(id));
470 debug!("var_region({:?}) = {:?}", id, scope);
474 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
476 self.is_subscope_of(scope1, scope2) ||
477 self.is_subscope_of(scope2, scope1)
480 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
482 pub fn is_subscope_of(&self,
483 subscope: CodeExtent,
484 superscope: CodeExtent)
486 let mut s = subscope;
487 while superscope != s {
488 match self.scope_map.borrow().get(&s) {
490 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
491 subscope, superscope, s);
495 Some(&scope) => s = scope
499 debug!("is_subscope_of({:?}, {:?})=true",
500 subscope, superscope);
505 /// Determines whether two free regions have a subregion relationship
506 /// by walking the graph encoded in `free_region_map`. Note that
507 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
508 /// (that is, the user can give two different names to the same lifetime).
509 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
510 can_reach(&*self.free_region_map.borrow(), sub, sup)
513 /// Determines whether one region is a subregion of another. This is intended to run *after
514 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
515 pub fn is_subregion_of(&self,
516 sub_region: ty::Region,
517 super_region: ty::Region)
519 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
520 sub_region, super_region);
522 sub_region == super_region || {
523 match (sub_region, super_region) {
525 (_, ty::ReStatic) => {
529 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
530 self.is_subscope_of(sub_scope, super_scope)
533 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
534 self.is_subscope_of(sub_scope, fr.scope.to_code_extent())
537 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
538 self.sub_free_region(sub_fr, super_fr)
541 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
542 ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
543 // This case is used only to make sure that explicitly-
544 // specified `Self` types match the real self type in
546 param_id_a == param_id_b &&
547 param_space_a == param_space_b &&
558 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
559 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
560 pub fn nearest_common_ancestor(&self,
563 -> Option<CodeExtent> {
564 if scope_a == scope_b { return Some(scope_a); }
566 let a_ancestors = ancestors_of(self, scope_a);
567 let b_ancestors = ancestors_of(self, scope_b);
568 let mut a_index = a_ancestors.len() - 1;
569 let mut b_index = b_ancestors.len() - 1;
571 // Here, ~[ab]_ancestors is a vector going from narrow to broad.
572 // The end of each vector will be the item where the scope is
573 // defined; if there are any common ancestors, then the tails of
574 // the vector will be the same. So basically we want to walk
575 // backwards from the tail of each vector and find the first point
576 // where they diverge. If one vector is a suffix of the other,
577 // then the corresponding scope is a superscope of the other.
579 if a_ancestors[a_index] != b_ancestors[b_index] {
584 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
585 // for all indices between a_index and the end of the array
586 if a_index == 0 { return Some(scope_a); }
587 if b_index == 0 { return Some(scope_b); }
590 if a_ancestors[a_index] != b_ancestors[b_index] {
591 return Some(a_ancestors[a_index + 1]);
595 fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
597 // debug!("ancestors_of(scope={:?})", scope);
598 let mut result = vec!(scope);
599 let mut scope = scope;
601 match this.scope_map.borrow().get(&scope) {
602 None => return result,
603 Some(&superscope) => {
604 result.push(superscope);
608 // debug!("ancestors_of_loop(scope={:?})", scope);
614 /// Records the current parent (if any) as the parent of `child_scope`.
615 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
616 child_scope: CodeExtent,
618 match visitor.cx.parent.to_code_extent() {
619 Some(parent_scope) =>
620 visitor.region_maps.record_encl_scope(child_scope, parent_scope),
625 /// Records the lifetime of a local variable as `cx.var_parent`
626 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
629 match visitor.cx.var_parent.to_code_extent() {
630 Some(parent_scope) =>
631 visitor.region_maps.record_var_scope(var_id, parent_scope),
633 // this can happen in extern fn declarations like
635 // extern fn isalnum(c: c_int) -> c_int
640 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
641 debug!("resolve_block(blk.id={:?})", blk.id);
643 let prev_cx = visitor.cx;
645 let blk_scope = CodeExtent::Misc(blk.id);
646 // If block was previously marked as a terminating scope during
647 // the recursive visit of its parent node in the AST, then we need
648 // to account for the destruction scope representing the extent of
649 // the destructors that run immediately after the the block itself
651 if visitor.region_maps.terminating_scopes.borrow().contains(&blk_scope) {
652 let dtor_scope = CodeExtent::DestructionScope(blk.id);
653 record_superlifetime(visitor, dtor_scope, blk.span);
654 visitor.region_maps.record_encl_scope(blk_scope, dtor_scope);
656 record_superlifetime(visitor, blk_scope, blk.span);
659 // We treat the tail expression in the block (if any) somewhat
660 // differently from the statements. The issue has to do with
661 // temporary lifetimes. Consider the following:
664 // let inner = ... (&bar()) ...;
666 // (... (&foo()) ...) // (the tail expression)
667 // }, other_argument());
669 // Each of the statements within the block is a terminating
670 // scope, and thus a temporary (e.g. the result of calling
671 // `bar()` in the initalizer expression for `let inner = ...;`)
672 // will be cleaned up immediately after its corresponding
673 // statement (i.e. `let inner = ...;`) executes.
675 // On the other hand, temporaries associated with evaluating the
676 // tail expression for the block are assigned lifetimes so that
677 // they will be cleaned up as part of the terminating scope
678 // *surrounding* the block expression. Here, the terminating
679 // scope for the block expression is the `quux(..)` call; so
680 // those temporaries will only be cleaned up *after* both
681 // `other_argument()` has run and also the call to `quux(..)`
682 // itself has returned.
684 visitor.cx = Context {
685 var_parent: InnermostDeclaringBlock::Block(blk.id),
686 parent: InnermostEnclosingExpr::Some(blk.id),
690 // This block should be kept approximately in sync with
691 // `visit::walk_block`. (We manually walk the block, rather
692 // than call `walk_block`, in order to maintain precise
693 // `InnermostDeclaringBlock` information.)
695 for (i, statement) in blk.stmts.iter().enumerate() {
696 if let ast::StmtDecl(_, stmt_id) = statement.node {
697 // Each StmtDecl introduces a subscope for bindings
698 // introduced by the declaration; this subscope covers
699 // a suffix of the block . Each subscope in a block
700 // has the previous subscope in the block as a parent,
701 // except for the first such subscope, which has the
702 // block itself as a parent.
703 let declaring = DeclaringStatementContext {
708 record_superlifetime(
709 visitor, declaring.to_code_extent(), statement.span);
710 visitor.cx = Context {
711 var_parent: InnermostDeclaringBlock::Statement(declaring),
712 parent: InnermostEnclosingExpr::Statement(declaring),
715 visitor.visit_stmt(&**statement)
717 visit::walk_expr_opt(visitor, &blk.expr)
720 visitor.cx = prev_cx;
723 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
724 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
725 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
729 let guard_scope = CodeExtent::from_node_id(expr.id);
730 visitor.region_maps.mark_as_terminating_scope(guard_scope);
735 visit::walk_arm(visitor, arm);
738 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
739 record_superlifetime(visitor, CodeExtent::from_node_id(pat.id), pat.span);
741 // If this is a binding (or maybe a binding, I'm too lazy to check
742 // the def map) then record the lifetime of that binding.
744 ast::PatIdent(..) => {
745 record_var_lifetime(visitor, pat.id, pat.span);
750 visit::walk_pat(visitor, pat);
753 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
754 let stmt_id = stmt_id(stmt);
755 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
757 let stmt_scope = CodeExtent::from_node_id(stmt_id);
759 // Every statement will clean up the temporaries created during
760 // execution of that statement. Therefore each statement has an
761 // associated destruction scope that represents the extent of the
762 // statement plus its destructors, and thus the extent for which
763 // regions referenced by the destructors need to survive.
764 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
765 let dtor_scope = CodeExtent::DestructionScope(stmt_id);
766 visitor.region_maps.record_encl_scope(stmt_scope, dtor_scope);
767 record_superlifetime(visitor, dtor_scope, stmt.span);
769 let prev_parent = visitor.cx.parent;
770 visitor.cx.parent = InnermostEnclosingExpr::Some(stmt_id);
771 visit::walk_stmt(visitor, stmt);
772 visitor.cx.parent = prev_parent;
775 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
776 debug!("resolve_expr(expr.id={:?})", expr.id);
778 let expr_scope = CodeExtent::Misc(expr.id);
779 // If expr was previously marked as a terminating scope during the
780 // recursive visit of its parent node in the AST, then we need to
781 // account for the destruction scope representing the extent of
782 // the destructors that run immediately after the the expression
784 if visitor.region_maps.terminating_scopes.borrow().contains(&expr_scope) {
785 let dtor_scope = CodeExtent::DestructionScope(expr.id);
786 record_superlifetime(visitor, dtor_scope, expr.span);
787 visitor.region_maps.record_encl_scope(expr_scope, dtor_scope);
789 record_superlifetime(visitor, expr_scope, expr.span);
792 let prev_cx = visitor.cx;
793 visitor.cx.parent = InnermostEnclosingExpr::Some(expr.id);
796 let region_maps = &mut visitor.region_maps;
797 let terminating = |e: &P<ast::Expr>| {
798 let scope = CodeExtent::from_node_id(e.id);
799 region_maps.mark_as_terminating_scope(scope)
801 let terminating_block = |b: &P<ast::Block>| {
802 let scope = CodeExtent::from_node_id(b.id);
803 region_maps.mark_as_terminating_scope(scope)
806 // Conditional or repeating scopes are always terminating
807 // scopes, meaning that temporaries cannot outlive them.
808 // This ensures fixed size stacks.
810 ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
811 ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
812 // For shortcircuiting operators, mark the RHS as a terminating
813 // scope since it only executes conditionally.
817 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
818 terminating_block(then);
819 terminating(otherwise);
822 ast::ExprIf(ref expr, ref then, None) => {
824 terminating_block(then);
827 ast::ExprLoop(ref body, _) => {
828 terminating_block(body);
831 ast::ExprWhile(ref expr, ref body, _) => {
833 terminating_block(body);
836 ast::ExprMatch(..) => {
837 visitor.cx.var_parent = InnermostDeclaringBlock::Match(expr.id);
840 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
841 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
842 // FIXME(#6268) Nested method calls
844 // The lifetimes for a call or method call look as follows:
852 // The idea is that call.callee_id represents *the time when
853 // the invoked function is actually running* and call.id
854 // represents *the time to prepare the arguments and make the
855 // call*. See the section "Borrows in Calls" borrowck/doc.rs
856 // for an extended explanation of why this distinction is
859 // record_superlifetime(new_cx, expr.callee_id);
866 visit::walk_expr(visitor, expr);
867 visitor.cx = prev_cx;
870 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
871 debug!("resolve_local(local.id={:?},local.init={:?})",
872 local.id,local.init.is_some());
874 // For convenience in trans, associate with the local-id the var
875 // scope that will be used for any bindings declared in this
877 let blk_scope = visitor.cx.var_parent.to_code_extent()
878 .unwrap_or_else(|| visitor.sess.span_bug(
879 local.span, "local without enclosing block"));
881 visitor.region_maps.record_var_scope(local.id, blk_scope);
883 // As an exception to the normal rules governing temporary
884 // lifetimes, initializers in a let have a temporary lifetime
885 // of the enclosing block. This means that e.g. a program
886 // like the following is legal:
888 // let ref x = HashMap::new();
890 // Because the hash map will be freed in the enclosing block.
892 // We express the rules more formally based on 3 grammars (defined
893 // fully in the helpers below that implement them):
895 // 1. `E&`, which matches expressions like `&<rvalue>` that
896 // own a pointer into the stack.
898 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
899 // y)` that produce ref bindings into the value they are
900 // matched against or something (at least partially) owned by
901 // the value they are matched against. (By partially owned,
902 // I mean that creating a binding into a ref-counted or managed value
903 // would still count.)
905 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
906 // based on rvalues like `foo().x[2].y`.
908 // A subexpression `<rvalue>` that appears in a let initializer
909 // `let pat [: ty] = expr` has an extended temporary lifetime if
910 // any of the following conditions are met:
912 // A. `pat` matches `P&` and `expr` matches `ET`
913 // (covers cases where `pat` creates ref bindings into an rvalue
914 // produced by `expr`)
915 // B. `ty` is a borrowed pointer and `expr` matches `ET`
916 // (covers cases where coercion creates a borrow)
917 // C. `expr` matches `E&`
918 // (covers cases `expr` borrows an rvalue that is then assigned
919 // to memory (at least partially) owned by the binding)
921 // Here are some examples hopefully giving an intuition where each
922 // rule comes into play and why:
924 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
925 // would have an extended lifetime, but not `foo()`.
927 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
928 // would have an extended lifetime, but not `foo()`.
930 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
933 // In some cases, multiple rules may apply (though not to the same
934 // rvalue). For example:
936 // let ref x = [&a(), &b()];
938 // Here, the expression `[...]` has an extended lifetime due to rule
939 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
942 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
946 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
949 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
951 if is_binding_pat(&*local.pat) || is_borrow {
952 record_rvalue_scope(visitor, &**expr, blk_scope);
959 visit::walk_local(visitor, local);
961 /// True if `pat` match the `P&` nonterminal:
964 /// | StructName { ..., P&, ... }
965 /// | VariantName(..., P&, ...)
966 /// | [ ..., P&, ... ]
967 /// | ( ..., P&, ... )
969 fn is_binding_pat(pat: &ast::Pat) -> bool {
971 ast::PatIdent(ast::BindByRef(_), _, _) => true,
973 ast::PatStruct(_, ref field_pats, _) => {
974 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
977 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
978 pats1.iter().any(|p| is_binding_pat(&**p)) ||
979 pats2.iter().any(|p| is_binding_pat(&**p)) ||
980 pats3.iter().any(|p| is_binding_pat(&**p))
983 ast::PatEnum(_, Some(ref subpats)) |
984 ast::PatTup(ref subpats) => {
985 subpats.iter().any(|p| is_binding_pat(&**p))
988 ast::PatBox(ref subpat) => {
989 is_binding_pat(&**subpat)
996 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
997 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
999 ast::TyRptr(..) => true,
1004 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1007 /// | StructName { ..., f: E&, ... }
1008 /// | [ ..., E&, ... ]
1009 /// | ( ..., E&, ... )
1014 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1016 blk_id: CodeExtent) {
1018 ast::ExprAddrOf(_, ref subexpr) => {
1019 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1020 record_rvalue_scope(visitor, &**subexpr, blk_id);
1022 ast::ExprStruct(_, ref fields, _) => {
1023 for field in fields {
1024 record_rvalue_scope_if_borrow_expr(
1025 visitor, &*field.expr, blk_id);
1028 ast::ExprVec(ref subexprs) |
1029 ast::ExprTup(ref subexprs) => {
1030 for subexpr in subexprs {
1031 record_rvalue_scope_if_borrow_expr(
1032 visitor, &**subexpr, blk_id);
1035 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
1036 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1038 ast::ExprCast(ref subexpr, _) |
1039 ast::ExprParen(ref subexpr) => {
1040 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1042 ast::ExprBlock(ref block) => {
1044 Some(ref subexpr) => {
1045 record_rvalue_scope_if_borrow_expr(
1046 visitor, &**subexpr, blk_id);
1056 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1057 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1058 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1061 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1062 /// `<rvalue>` as `blk_id`:
1070 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1071 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1072 expr: &'a ast::Expr,
1073 blk_scope: CodeExtent) {
1074 let mut expr = expr;
1076 // Note: give all the expressions matching `ET` with the
1077 // extended temporary lifetime, not just the innermost rvalue,
1078 // because in trans if we must compile e.g. `*rvalue()`
1079 // into a temporary, we request the temporary scope of the
1080 // outer expression.
1081 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1084 ast::ExprAddrOf(_, ref subexpr) |
1085 ast::ExprUnary(ast::UnDeref, ref subexpr) |
1086 ast::ExprField(ref subexpr, _) |
1087 ast::ExprTupField(ref subexpr, _) |
1088 ast::ExprIndex(ref subexpr, _) |
1089 ast::ExprParen(ref subexpr) => {
1100 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
1101 // Items create a new outer block scope as far as we're concerned.
1102 let prev_cx = visitor.cx;
1103 visitor.cx = Context {
1104 var_parent: InnermostDeclaringBlock::None,
1105 parent: InnermostEnclosingExpr::None
1107 visit::walk_item(visitor, item);
1108 visitor.cx = prev_cx;
1111 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1117 debug!("region::resolve_fn(id={:?}, \
1122 visitor.sess.codemap().span_to_string(sp),
1126 let body_scope = CodeExtent::from_node_id(body.id);
1127 visitor.region_maps.mark_as_terminating_scope(body_scope);
1128 let dtor_scope = CodeExtent::DestructionScope(body.id);
1129 visitor.region_maps.record_encl_scope(body_scope, dtor_scope);
1130 record_superlifetime(visitor, dtor_scope, body.span);
1132 let outer_cx = visitor.cx;
1134 // The arguments and `self` are parented to the body of the fn.
1135 visitor.cx = Context {
1136 parent: InnermostEnclosingExpr::Some(body.id),
1137 var_parent: InnermostDeclaringBlock::Block(body.id)
1139 visit::walk_fn_decl(visitor, decl);
1141 // The body of the fn itself is either a root scope (top-level fn)
1142 // or it continues with the inherited scope (closures).
1144 visit::FkItemFn(..) | visit::FkMethod(..) => {
1145 visitor.cx = Context {
1146 parent: InnermostEnclosingExpr::None,
1147 var_parent: InnermostDeclaringBlock::None
1149 visitor.visit_block(body);
1150 visitor.cx = outer_cx;
1152 visit::FkFnBlock(..) => {
1153 // FIXME(#3696) -- at present we are place the closure body
1154 // within the region hierarchy exactly where it appears lexically.
1155 // This is wrong because the closure may live longer
1156 // than the enclosing expression. We should probably fix this,
1157 // but the correct fix is a bit subtle, and I am also not sure
1158 // that the present approach is unsound -- it may not permit
1159 // any illegal programs. See issue for more details.
1160 visitor.cx = outer_cx;
1161 visitor.visit_block(body);
1166 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1168 fn visit_block(&mut self, b: &Block) {
1169 resolve_block(self, b);
1172 fn visit_item(&mut self, i: &Item) {
1173 resolve_item(self, i);
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: &ast::Crate) -> RegionMaps {
1198 let maps = RegionMaps {
1199 scope_map: RefCell::new(FnvHashMap()),
1200 var_map: RefCell::new(NodeMap()),
1201 free_region_map: RefCell::new(FnvHashMap()),
1202 rvalue_scopes: RefCell::new(NodeMap()),
1203 terminating_scopes: RefCell::new(FnvHashSet()),
1206 let mut visitor = RegionResolutionVisitor {
1210 parent: InnermostEnclosingExpr::None,
1211 var_parent: InnermostDeclaringBlock::None,
1214 visit::walk_crate(&mut visitor, krate);
1219 pub fn resolve_inlined_item(sess: &Session,
1220 region_maps: &RegionMaps,
1221 item: &ast::InlinedItem) {
1222 let mut visitor = RegionResolutionVisitor {
1224 region_maps: region_maps,
1226 parent: InnermostEnclosingExpr::None,
1227 var_parent: InnermostDeclaringBlock::None
1230 visit::walk_inlined_item(&mut visitor, item);