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/infer/region_inference/README.md`
19 use front::map as ast_map;
21 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
22 use middle::cstore::InlinedItem;
23 use middle::ty::{self, Ty};
25 use std::cell::RefCell;
26 use std::collections::hash_map::Entry;
29 use syntax::codemap::{self, Span};
30 use syntax::ast::{self, NodeId};
33 use rustc_front::intravisit::{self, Visitor, FnKind};
34 use rustc_front::hir::{Block, Item, FnDecl, Arm, Pat, Stmt, Expr, Local};
35 use rustc_front::util::stmt_id;
37 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
38 RustcDecodable, Copy)]
39 pub struct CodeExtent(u32);
41 impl fmt::Debug for CodeExtent {
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 try!(write!(f, "CodeExtent({:?}", self.0));
45 try!(ty::tls::with_opt(|opt_tcx| {
46 if let Some(tcx) = opt_tcx {
47 let data = tcx.region_maps.code_extents.borrow()[self.0 as usize];
48 try!(write!(f, "/{:?}", data));
57 /// The root of everything. I should be using NonZero or profiling
58 /// instead of this (probably).
59 pub const ROOT_CODE_EXTENT : CodeExtent = CodeExtent(0);
60 /// A placeholder used in trans to stand for real code extents
61 pub const DUMMY_CODE_EXTENT : CodeExtent = CodeExtent(1);
63 /// CodeExtent represents a statically-describable extent that can be
64 /// used to bound the lifetime/region for values.
66 /// `Misc(node_id)`: Any AST node that has any extent at all has the
67 /// `Misc(node_id)` extent. Other variants represent special cases not
68 /// immediately derivable from the abstract syntax tree structure.
70 /// `DestructionScope(node_id)` represents the extent of destructors
71 /// implicitly-attached to `node_id` that run immediately after the
72 /// expression for `node_id` itself. Not every AST node carries a
73 /// `DestructionScope`, but those that are `terminating_scopes` do;
74 /// see discussion with `RegionMaps`.
76 /// `Remainder(BlockRemainder { block, statement_index })` represents
77 /// the extent of user code running immediately after the initializer
78 /// expression for the indexed statement, until the end of the block.
80 /// So: the following code can be broken down into the extents beneath:
82 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
87 /// +---------+ (R10.)
89 /// +----------+ (M8.)
90 /// +----------------------+ (R7.)
92 /// +----------+ (M5.)
93 /// +-----------------------------------+ (M4.)
94 /// +--------------------------------------------------+ (M3.)
96 /// +-----------------------------------------------------------+ (M1.)
98 /// (M1.): Misc extent of the whole `let a = ...;` statement.
99 /// (M2.): Misc extent of the `f()` expression.
100 /// (M3.): Misc extent of the `f().g(..)` expression.
101 /// (M4.): Misc extent of the block labelled `'b:`.
102 /// (M5.): Misc extent of the `let x = d();` statement
103 /// (D6.): DestructionScope for temporaries created during M5.
104 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
105 /// (M8.): Misc Extent of the `let y = d();` statement.
106 /// (D9.): DestructionScope for temporaries created during M8.
107 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
108 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
109 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
111 /// Note that while the above picture shows the destruction scopes
112 /// as following their corresponding misc extents, in the internal
113 /// data structures of the compiler the destruction scopes are
114 /// represented as enclosing parents. This is sound because we use the
115 /// enclosing parent relationship just to ensure that referenced
116 /// values live long enough; phrased another way, the starting point
117 /// of each range is not really the important thing in the above
118 /// picture, but rather the ending point.
120 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
121 /// placate the same deriving in `ty::FreeRegion`, but we may want to
122 /// actually attach a more meaningful ordering to scopes than the one
123 /// generated via deriving here.
124 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy)]
125 pub enum CodeExtentData {
128 // extent of the call-site for a function or closure (outlives
129 // the parameters as well as the body).
130 CallSiteScope { fn_id: ast::NodeId, body_id: ast::NodeId },
132 // extent of parameters passed to a function or closure (they
134 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
136 // extent of destructors for temporaries of node-id
137 DestructionScope(ast::NodeId),
139 // extent of code following a `let id = expr;` binding in a block
140 Remainder(BlockRemainder)
143 /// extent of call-site for a function/method.
144 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
145 RustcDecodable, Debug, Copy)]
146 pub struct CallSiteScopeData {
147 pub fn_id: ast::NodeId, pub body_id: ast::NodeId,
150 impl CallSiteScopeData {
151 pub fn to_code_extent(&self, region_maps: &RegionMaps) -> CodeExtent {
152 region_maps.lookup_code_extent(
154 CallSiteScopeData { fn_id, body_id } =>
155 CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id },
160 /// Represents a subscope of `block` for a binding that is introduced
161 /// by `block.stmts[first_statement_index]`. Such subscopes represent
162 /// a suffix of the block. Note that each subscope does not include
163 /// the initializer expression, if any, for the statement indexed by
164 /// `first_statement_index`.
166 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
168 /// * the subscope with `first_statement_index == 0` is scope of both
169 /// `a` and `b`; it does not include EXPR_1, but does include
170 /// everything after that first `let`. (If you want a scope that
171 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
172 /// but instead another `CodeExtent` that encompasses the whole block,
173 /// e.g. `CodeExtentData::Misc`.
175 /// * the subscope with `first_statement_index == 1` is scope of `c`,
176 /// and thus does not include EXPR_2, but covers the `...`.
177 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
178 RustcDecodable, Debug, Copy)]
179 pub struct BlockRemainder {
180 pub block: ast::NodeId,
181 pub first_statement_index: u32,
184 impl CodeExtentData {
185 /// Returns a node id associated with this scope.
187 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
188 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
189 pub fn node_id(&self) -> ast::NodeId {
191 CodeExtentData::Misc(node_id) => node_id,
193 // These cases all return rough approximations to the
194 // precise extent denoted by `self`.
195 CodeExtentData::Remainder(br) => br.block,
196 CodeExtentData::DestructionScope(node_id) => node_id,
197 CodeExtentData::CallSiteScope { fn_id: _, body_id } |
198 CodeExtentData::ParameterScope { fn_id: _, body_id } => body_id,
205 fn into_option(self) -> Option<CodeExtent> {
206 if self == ROOT_CODE_EXTENT {
212 pub fn node_id(&self, region_maps: &RegionMaps) -> ast::NodeId {
213 region_maps.code_extent_data(*self).node_id()
216 /// Returns the span of this CodeExtent. Note that in general the
217 /// returned span may not correspond to the span of any node id in
219 pub fn span(&self, region_maps: &RegionMaps, ast_map: &ast_map::Map) -> Option<Span> {
220 match ast_map.find(self.node_id(region_maps)) {
221 Some(ast_map::NodeBlock(ref blk)) => {
222 match region_maps.code_extent_data(*self) {
223 CodeExtentData::CallSiteScope { .. } |
224 CodeExtentData::ParameterScope { .. } |
225 CodeExtentData::Misc(_) |
226 CodeExtentData::DestructionScope(_) => Some(blk.span),
228 CodeExtentData::Remainder(r) => {
229 assert_eq!(r.block, blk.id);
230 // Want span for extent starting after the
231 // indexed statement and ending at end of
232 // `blk`; reuse span of `blk` and shift `lo`
233 // forward to end of indexed statement.
235 // (This is the special case aluded to in the
236 // doc-comment for this method)
237 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
238 Some(Span { lo: stmt_span.hi, ..blk.span })
242 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
243 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
244 Some(ast_map::NodeItem(ref item)) => Some(item.span),
245 Some(_) | None => None,
250 /// The region maps encode information about region relationships.
251 pub struct RegionMaps {
252 code_extents: RefCell<Vec<CodeExtentData>>,
253 code_extent_interner: RefCell<FnvHashMap<CodeExtentData, CodeExtent>>,
254 /// `scope_map` maps from a scope id to the enclosing scope id;
255 /// this is usually corresponding to the lexical nesting, though
256 /// in the case of closures the parent scope is the innermost
257 /// conditional expression or repeating block. (Note that the
258 /// enclosing scope id for the block associated with a closure is
259 /// the closure itself.)
260 scope_map: RefCell<Vec<CodeExtent>>,
262 /// `var_map` maps from a variable or binding id to the block in
263 /// which that variable is declared.
264 var_map: RefCell<NodeMap<CodeExtent>>,
266 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
267 /// larger than the default. The map goes from the expression id
268 /// to the cleanup scope id. For rvalues not present in this
269 /// table, the appropriate cleanup scope is the innermost
270 /// enclosing statement, conditional expression, or repeating
271 /// block (see `terminating_scopes`).
272 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
274 /// Encodes the hierarchy of fn bodies. Every fn body (including
275 /// closures) forms its own distinct region hierarchy, rooted in
276 /// the block that is the fn body. This map points from the id of
277 /// that root block to the id of the root block for the enclosing
278 /// fn, if any. Thus the map structures the fn bodies into a
279 /// hierarchy based on their lexical mapping. This is used to
280 /// handle the relationships between regions in a fn and in a
281 /// closure defined by that fn. See the "Modeling closures"
282 /// section of the README in middle::infer::region_inference for
284 fn_tree: RefCell<NodeMap<ast::NodeId>>,
287 #[derive(Debug, Copy, Clone)]
289 /// the root of the current region tree. This is typically the id
290 /// of the innermost fn body. Each fn forms its own disjoint tree
291 /// in the region hierarchy. These fn bodies are themselves
292 /// arranged into a tree. See the "Modeling closures" section of
293 /// the README in middle::infer::region_inference for more
295 root_id: Option<ast::NodeId>,
297 /// the scope that contains any new variables declared
298 var_parent: CodeExtent,
300 /// region parent of expressions etc
304 struct RegionResolutionVisitor<'a> {
308 region_maps: &'a RegionMaps,
312 /// `terminating_scopes` is a set containing the ids of each
313 /// statement, or conditional/repeating expression. These scopes
314 /// are calling "terminating scopes" because, when attempting to
315 /// find the scope of a temporary, by default we search up the
316 /// enclosing scopes until we encounter the terminating scope. A
317 /// conditional/repeating expression is one which is not
318 /// guaranteed to execute exactly once upon entering the parent
319 /// scope. This could be because the expression only executes
320 /// conditionally, such as the expression `b` in `a && b`, or
321 /// because the expression may execute many times, such as a loop
322 /// body. The reason that we distinguish such expressions is that,
323 /// upon exiting the parent scope, we cannot statically know how
324 /// many times the expression executed, and thus if the expression
325 /// creates temporaries we cannot know statically how many such
326 /// temporaries we would have to cleanup. Therefore we ensure that
327 /// the temporaries never outlast the conditional/repeating
328 /// expression, preventing the need for dynamic checks and/or
329 /// arbitrary amounts of stack space. Terminating scopes end
330 /// up being contained in a DestructionScope that contains the
331 /// destructor's execution.
332 terminating_scopes: NodeSet
337 /// create a bogus code extent for the regions in astencode types. Nobody
338 /// really cares about the contents of these.
339 pub fn bogus_code_extent(&self, e: CodeExtentData) -> CodeExtent {
340 self.intern_code_extent(e, DUMMY_CODE_EXTENT)
342 pub fn lookup_code_extent(&self, e: CodeExtentData) -> CodeExtent {
343 match self.code_extent_interner.borrow().get(&e) {
345 None => panic!("unknown code extent {:?}", e)
348 pub fn node_extent(&self, n: ast::NodeId) -> CodeExtent {
349 self.lookup_code_extent(CodeExtentData::Misc(n))
351 // Returns the code extent for an item - the destruction scope.
352 pub fn item_extent(&self, n: ast::NodeId) -> CodeExtent {
353 self.lookup_code_extent(CodeExtentData::DestructionScope(n))
355 pub fn call_site_extent(&self, fn_id: ast::NodeId, body_id: ast::NodeId) -> CodeExtent {
356 assert!(fn_id != body_id);
357 self.lookup_code_extent(CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id })
359 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
360 self.code_extent_interner.borrow().get(&CodeExtentData::DestructionScope(n)).cloned()
362 pub fn intern_code_extent(&self,
364 parent: CodeExtent) -> CodeExtent {
365 match self.code_extent_interner.borrow_mut().entry(e) {
366 Entry::Occupied(o) => {
367 // this can happen when the bogus code extents from tydecode
368 // have (bogus) NodeId-s that overlap items created during
370 // We probably shouldn't be creating bogus code extents
373 if parent == DUMMY_CODE_EXTENT {
374 info!("CodeExtent({}) = {:?} [parent={}] BOGUS!",
377 assert_eq!(self.scope_map.borrow()[idx.0 as usize],
379 info!("CodeExtent({}) = {:?} [parent={}] RECLAIMED!",
381 self.scope_map.borrow_mut()[idx.0 as usize] = parent;
385 Entry::Vacant(v) => {
386 if self.code_extents.borrow().len() > 0xffffffffusize {
387 unreachable!() // should pass a sess,
388 // but this isn't the only place
390 let idx = CodeExtent(self.code_extents.borrow().len() as u32);
391 info!("CodeExtent({}) = {:?} [parent={}]", idx.0, e, parent.0);
392 self.code_extents.borrow_mut().push(e);
393 self.scope_map.borrow_mut().push(parent);
398 pub fn intern_node(&self,
400 parent: CodeExtent) -> CodeExtent {
401 self.intern_code_extent(CodeExtentData::Misc(n), parent)
403 pub fn code_extent_data(&self, e: CodeExtent) -> CodeExtentData {
404 self.code_extents.borrow()[e.0 as usize]
406 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
407 for child_id in 1..self.code_extents.borrow().len() {
408 let child = CodeExtent(child_id as u32);
409 if let Some(parent) = self.opt_encl_scope(child) {
414 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
415 for (child, parent) in self.var_map.borrow().iter() {
419 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
420 for (child, parent) in self.rvalue_scopes.borrow().iter() {
424 /// Records that `sub_fn` is defined within `sup_fn`. These ids
425 /// should be the id of the block that is the fn body, which is
426 /// also the root of the region hierarchy for that fn.
427 fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
428 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
429 assert!(sub_fn != sup_fn);
430 let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
431 assert!(previous.is_none());
434 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
435 let fn_tree = self.fn_tree.borrow();
437 if sub_fn == sup_fn { return true; }
438 match fn_tree.get(&sub_fn) {
439 Some(&s) => { sub_fn = s; }
440 None => { return false; }
445 fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
446 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
447 assert!(var != lifetime.node_id(self));
448 self.var_map.borrow_mut().insert(var, lifetime);
451 fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
452 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
453 assert!(var != lifetime.node_id(self));
454 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
457 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
458 //! Returns the narrowest scope that encloses `id`, if any.
459 self.scope_map.borrow()[id.0 as usize].into_option()
462 #[allow(dead_code)] // used in middle::cfg
463 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
464 //! Returns the narrowest scope that encloses `id`, if any.
465 self.opt_encl_scope(id).unwrap()
468 /// Returns the lifetime of the local variable `var_id`
469 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
470 match self.var_map.borrow().get(&var_id) {
472 None => { panic!("no enclosing scope for id {:?}", var_id); }
476 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
477 //! Returns the scope when temp created by expr_id will be cleaned up
479 // check for a designated rvalue scope
480 match self.rvalue_scopes.borrow().get(&expr_id) {
482 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
488 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
489 let code_extents: &[CodeExtentData] = &self.code_extents.borrow();
491 // else, locate the innermost terminating scope
492 // if there's one. Static items, for instance, won't
493 // have an enclosing scope, hence no scope will be
495 let expr_extent = self.node_extent(expr_id);
496 // For some reason, the expr's scope itself is skipped here.
497 let mut id = match scope_map[expr_extent.0 as usize].into_option() {
502 while let Some(p) = scope_map[id.0 as usize].into_option() {
503 match code_extents[p.0 as usize] {
504 CodeExtentData::DestructionScope(..) => {
505 debug!("temporary_scope({:?}) = {:?} [enclosing]",
513 debug!("temporary_scope({:?}) = None", expr_id);
517 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
518 //! Returns the lifetime of the variable `id`.
520 let scope = ty::ReScope(self.var_scope(id));
521 debug!("var_region({:?}) = {:?}", id, scope);
525 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
527 self.is_subscope_of(scope1, scope2) ||
528 self.is_subscope_of(scope2, scope1)
531 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
533 pub fn is_subscope_of(&self,
534 subscope: CodeExtent,
535 superscope: CodeExtent)
537 let mut s = subscope;
538 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
539 while superscope != s {
540 match self.opt_encl_scope(s) {
542 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
543 subscope, superscope, s);
546 Some(scope) => s = scope
550 debug!("is_subscope_of({:?}, {:?})=true",
551 subscope, superscope);
556 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
557 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
558 pub fn nearest_common_ancestor(&self,
562 if scope_a == scope_b { return scope_a; }
564 let mut a_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
565 let mut a_vec: Vec<CodeExtent> = vec![];
566 let mut b_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
567 let mut b_vec: Vec<CodeExtent> = vec![];
568 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
569 let a_ancestors = ancestors_of(scope_map,
570 scope_a, &mut a_buf, &mut a_vec);
571 let b_ancestors = ancestors_of(scope_map,
572 scope_b, &mut b_buf, &mut b_vec);
573 let mut a_index = a_ancestors.len() - 1;
574 let mut b_index = b_ancestors.len() - 1;
576 // Here, [ab]_ancestors is a vector going from narrow to broad.
577 // The end of each vector will be the item where the scope is
578 // defined; if there are any common ancestors, then the tails of
579 // the vector will be the same. So basically we want to walk
580 // backwards from the tail of each vector and find the first point
581 // where they diverge. If one vector is a suffix of the other,
582 // then the corresponding scope is a superscope of the other.
584 if a_ancestors[a_index] != b_ancestors[b_index] {
585 // In this case, the two regions belong to completely
586 // different functions. Compare those fn for lexical
587 // nesting. The reasoning behind this is subtle. See the
588 // "Modeling closures" section of the README in
589 // middle::infer::region_inference for more details.
590 let a_root_scope = self.code_extent_data(a_ancestors[a_index]);
591 let b_root_scope = self.code_extent_data(a_ancestors[a_index]);
592 return match (a_root_scope, b_root_scope) {
593 (CodeExtentData::DestructionScope(a_root_id),
594 CodeExtentData::DestructionScope(b_root_id)) => {
595 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
596 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
598 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
599 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
602 // neither fn encloses the other
607 // root ids are always Misc right now
614 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
615 // for all indices between a_index and the end of the array
616 if a_index == 0 { return scope_a; }
617 if b_index == 0 { return scope_b; }
620 if a_ancestors[a_index] != b_ancestors[b_index] {
621 return a_ancestors[a_index + 1];
625 fn ancestors_of<'a>(scope_map: &[CodeExtent],
627 buf: &'a mut [CodeExtent; 32],
628 vec: &'a mut Vec<CodeExtent>) -> &'a [CodeExtent] {
629 // debug!("ancestors_of(scope={:?})", scope);
630 let mut scope = scope;
635 match scope_map[scope.0 as usize].into_option() {
636 Some(superscope) => scope = superscope,
637 _ => return &buf[..i+1]
642 *vec = Vec::with_capacity(64);
643 vec.extend_from_slice(buf);
646 match scope_map[scope.0 as usize].into_option() {
647 Some(superscope) => scope = superscope,
655 /// Records the lifetime of a local variable as `cx.var_parent`
656 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
659 match visitor.cx.var_parent {
660 ROOT_CODE_EXTENT => {
661 // this can happen in extern fn declarations like
663 // extern fn isalnum(c: c_int) -> c_int
666 visitor.region_maps.record_var_scope(var_id, parent_scope),
670 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &hir::Block) {
671 debug!("resolve_block(blk.id={:?})", blk.id);
673 let prev_cx = visitor.cx;
674 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
676 // We treat the tail expression in the block (if any) somewhat
677 // differently from the statements. The issue has to do with
678 // temporary lifetimes. Consider the following:
681 // let inner = ... (&bar()) ...;
683 // (... (&foo()) ...) // (the tail expression)
684 // }, other_argument());
686 // Each of the statements within the block is a terminating
687 // scope, and thus a temporary (e.g. the result of calling
688 // `bar()` in the initalizer expression for `let inner = ...;`)
689 // will be cleaned up immediately after its corresponding
690 // statement (i.e. `let inner = ...;`) executes.
692 // On the other hand, temporaries associated with evaluating the
693 // tail expression for the block are assigned lifetimes so that
694 // they will be cleaned up as part of the terminating scope
695 // *surrounding* the block expression. Here, the terminating
696 // scope for the block expression is the `quux(..)` call; so
697 // those temporaries will only be cleaned up *after* both
698 // `other_argument()` has run and also the call to `quux(..)`
699 // itself has returned.
701 visitor.cx = Context {
702 root_id: prev_cx.root_id,
703 var_parent: block_extent,
704 parent: block_extent,
708 // This block should be kept approximately in sync with
709 // `intravisit::walk_block`. (We manually walk the block, rather
710 // than call `walk_block`, in order to maintain precise
711 // index information.)
713 for (i, statement) in blk.stmts.iter().enumerate() {
714 if let hir::StmtDecl(..) = statement.node {
715 // Each StmtDecl introduces a subscope for bindings
716 // introduced by the declaration; this subscope covers
717 // a suffix of the block . Each subscope in a block
718 // has the previous subscope in the block as a parent,
719 // except for the first such subscope, which has the
720 // block itself as a parent.
721 let stmt_extent = visitor.new_code_extent(
722 CodeExtentData::Remainder(BlockRemainder {
724 first_statement_index: i as u32
727 visitor.cx = Context {
728 root_id: prev_cx.root_id,
729 var_parent: stmt_extent,
733 visitor.visit_stmt(statement)
735 walk_list!(visitor, visit_expr, &blk.expr);
738 visitor.cx = prev_cx;
741 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &hir::Arm) {
742 visitor.terminating_scopes.insert(arm.body.id);
744 if let Some(ref expr) = arm.guard {
745 visitor.terminating_scopes.insert(expr.id);
748 intravisit::walk_arm(visitor, arm);
751 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &hir::Pat) {
752 visitor.new_node_extent(pat.id);
754 // If this is a binding (or maybe a binding, I'm too lazy to check
755 // the def map) then record the lifetime of that binding.
757 hir::PatIdent(..) => {
758 record_var_lifetime(visitor, pat.id, pat.span);
763 intravisit::walk_pat(visitor, pat);
766 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &hir::Stmt) {
767 let stmt_id = stmt_id(stmt);
768 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
770 // Every statement will clean up the temporaries created during
771 // execution of that statement. Therefore each statement has an
772 // associated destruction scope that represents the extent of the
773 // statement plus its destructors, and thus the extent for which
774 // regions referenced by the destructors need to survive.
775 visitor.terminating_scopes.insert(stmt_id);
776 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
778 let prev_parent = visitor.cx.parent;
779 visitor.cx.parent = stmt_extent;
780 intravisit::walk_stmt(visitor, stmt);
781 visitor.cx.parent = prev_parent;
784 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &hir::Expr) {
785 debug!("resolve_expr(expr.id={:?})", expr.id);
787 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
788 let prev_cx = visitor.cx;
789 visitor.cx.parent = expr_extent;
792 let terminating_scopes = &mut visitor.terminating_scopes;
793 let mut terminating = |id: ast::NodeId| {
794 terminating_scopes.insert(id);
797 // Conditional or repeating scopes are always terminating
798 // scopes, meaning that temporaries cannot outlive them.
799 // This ensures fixed size stacks.
801 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
802 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
803 // For shortcircuiting operators, mark the RHS as a terminating
804 // scope since it only executes conditionally.
808 hir::ExprIf(_, ref then, Some(ref otherwise)) => {
809 terminating(then.id);
810 terminating(otherwise.id);
813 hir::ExprIf(ref expr, ref then, None) => {
814 terminating(expr.id);
815 terminating(then.id);
818 hir::ExprLoop(ref body, _) => {
819 terminating(body.id);
822 hir::ExprWhile(ref expr, ref body, _) => {
823 terminating(expr.id);
824 terminating(body.id);
827 hir::ExprMatch(..) => {
828 visitor.cx.var_parent = expr_extent;
831 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
832 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
833 // FIXME(#6268) Nested method calls
835 // The lifetimes for a call or method call look as follows:
843 // The idea is that call.callee_id represents *the time when
844 // the invoked function is actually running* and call.id
845 // represents *the time to prepare the arguments and make the
846 // call*. See the section "Borrows in Calls" borrowck/README.md
847 // for an extended explanation of why this distinction is
850 // record_superlifetime(new_cx, expr.callee_id);
857 intravisit::walk_expr(visitor, expr);
858 visitor.cx = prev_cx;
861 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &hir::Local) {
862 debug!("resolve_local(local.id={:?},local.init={:?})",
863 local.id,local.init.is_some());
865 // For convenience in trans, associate with the local-id the var
866 // scope that will be used for any bindings declared in this
868 let blk_scope = visitor.cx.var_parent;
869 assert!(blk_scope != ROOT_CODE_EXTENT); // locals must be within a block
870 visitor.region_maps.record_var_scope(local.id, blk_scope);
872 // As an exception to the normal rules governing temporary
873 // lifetimes, initializers in a let have a temporary lifetime
874 // of the enclosing block. This means that e.g. a program
875 // like the following is legal:
877 // let ref x = HashMap::new();
879 // Because the hash map will be freed in the enclosing block.
881 // We express the rules more formally based on 3 grammars (defined
882 // fully in the helpers below that implement them):
884 // 1. `E&`, which matches expressions like `&<rvalue>` that
885 // own a pointer into the stack.
887 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
888 // y)` that produce ref bindings into the value they are
889 // matched against or something (at least partially) owned by
890 // the value they are matched against. (By partially owned,
891 // I mean that creating a binding into a ref-counted or managed value
892 // would still count.)
894 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
895 // based on rvalues like `foo().x[2].y`.
897 // A subexpression `<rvalue>` that appears in a let initializer
898 // `let pat [: ty] = expr` has an extended temporary lifetime if
899 // any of the following conditions are met:
901 // A. `pat` matches `P&` and `expr` matches `ET`
902 // (covers cases where `pat` creates ref bindings into an rvalue
903 // produced by `expr`)
904 // B. `ty` is a borrowed pointer and `expr` matches `ET`
905 // (covers cases where coercion creates a borrow)
906 // C. `expr` matches `E&`
907 // (covers cases `expr` borrows an rvalue that is then assigned
908 // to memory (at least partially) owned by the binding)
910 // Here are some examples hopefully giving an intuition where each
911 // rule comes into play and why:
913 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
914 // would have an extended lifetime, but not `foo()`.
916 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
917 // would have an extended lifetime, but not `foo()`.
919 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
922 // In some cases, multiple rules may apply (though not to the same
923 // rvalue). For example:
925 // let ref x = [&a(), &b()];
927 // Here, the expression `[...]` has an extended lifetime due to rule
928 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
931 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
935 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
938 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
940 if is_binding_pat(&*local.pat) || is_borrow {
941 record_rvalue_scope(visitor, &**expr, blk_scope);
948 intravisit::walk_local(visitor, local);
950 /// True if `pat` match the `P&` nonterminal:
953 /// | StructName { ..., P&, ... }
954 /// | VariantName(..., P&, ...)
955 /// | [ ..., P&, ... ]
956 /// | ( ..., P&, ... )
958 fn is_binding_pat(pat: &hir::Pat) -> bool {
960 hir::PatIdent(hir::BindByRef(_), _, _) => true,
962 hir::PatStruct(_, ref field_pats, _) => {
963 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
966 hir::PatVec(ref pats1, ref pats2, ref pats3) => {
967 pats1.iter().any(|p| is_binding_pat(&**p)) ||
968 pats2.iter().any(|p| is_binding_pat(&**p)) ||
969 pats3.iter().any(|p| is_binding_pat(&**p))
972 hir::PatEnum(_, Some(ref subpats)) |
973 hir::PatTup(ref subpats) => {
974 subpats.iter().any(|p| is_binding_pat(&**p))
977 hir::PatBox(ref subpat) => {
978 is_binding_pat(&**subpat)
985 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
986 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
988 hir::TyRptr(..) => true,
993 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
996 /// | StructName { ..., f: E&, ... }
997 /// | [ ..., E&, ... ]
998 /// | ( ..., E&, ... )
1003 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1005 blk_id: CodeExtent) {
1007 hir::ExprAddrOf(_, ref subexpr) => {
1008 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
1009 record_rvalue_scope(visitor, &**subexpr, blk_id);
1011 hir::ExprStruct(_, ref fields, _) => {
1012 for field in fields {
1013 record_rvalue_scope_if_borrow_expr(
1014 visitor, &*field.expr, blk_id);
1017 hir::ExprVec(ref subexprs) |
1018 hir::ExprTup(ref subexprs) => {
1019 for subexpr in subexprs {
1020 record_rvalue_scope_if_borrow_expr(
1021 visitor, &**subexpr, blk_id);
1024 hir::ExprCast(ref subexpr, _) => {
1025 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
1027 hir::ExprBlock(ref block) => {
1029 Some(ref subexpr) => {
1030 record_rvalue_scope_if_borrow_expr(
1031 visitor, &**subexpr, blk_id);
1041 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1042 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1043 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1046 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1047 /// `<rvalue>` as `blk_id`:
1055 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1056 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1057 expr: &'a hir::Expr,
1058 blk_scope: CodeExtent) {
1059 let mut expr = expr;
1061 // Note: give all the expressions matching `ET` with the
1062 // extended temporary lifetime, not just the innermost rvalue,
1063 // because in trans if we must compile e.g. `*rvalue()`
1064 // into a temporary, we request the temporary scope of the
1065 // outer expression.
1066 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1069 hir::ExprAddrOf(_, ref subexpr) |
1070 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1071 hir::ExprField(ref subexpr, _) |
1072 hir::ExprTupField(ref subexpr, _) |
1073 hir::ExprIndex(ref subexpr, _) => {
1084 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &hir::Item) {
1085 // Items create a new outer block scope as far as we're concerned.
1086 let prev_cx = visitor.cx;
1087 let prev_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1088 visitor.cx = Context {
1090 var_parent: ROOT_CODE_EXTENT,
1091 parent: ROOT_CODE_EXTENT
1093 intravisit::walk_item(visitor, item);
1094 visitor.create_item_scope_if_needed(item.id);
1095 visitor.cx = prev_cx;
1096 visitor.terminating_scopes = prev_ts;
1099 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1105 debug!("region::resolve_fn(id={:?}, \
1110 visitor.sess.codemap().span_to_string(sp),
1114 visitor.cx.parent = visitor.new_code_extent(
1115 CodeExtentData::CallSiteScope { fn_id: id, body_id: body.id });
1117 let fn_decl_scope = visitor.new_code_extent(
1118 CodeExtentData::ParameterScope { fn_id: id, body_id: body.id });
1120 if let Some(root_id) = visitor.cx.root_id {
1121 visitor.region_maps.record_fn_parent(body.id, root_id);
1124 let outer_cx = visitor.cx;
1125 let outer_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1126 visitor.terminating_scopes.insert(body.id);
1128 // The arguments and `self` are parented to the fn.
1129 visitor.cx = Context {
1130 root_id: Some(body.id),
1131 parent: ROOT_CODE_EXTENT,
1132 var_parent: fn_decl_scope,
1135 intravisit::walk_fn_decl(visitor, decl);
1136 intravisit::walk_fn_kind(visitor, kind);
1138 // The body of the every fn is a root scope.
1139 visitor.cx = Context {
1140 root_id: Some(body.id),
1141 parent: fn_decl_scope,
1142 var_parent: fn_decl_scope
1144 visitor.visit_block(body);
1146 // Restore context we had at the start.
1147 visitor.cx = outer_cx;
1148 visitor.terminating_scopes = outer_ts;
1151 impl<'a> RegionResolutionVisitor<'a> {
1152 /// Records the current parent (if any) as the parent of `child_scope`.
1153 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent {
1154 self.region_maps.intern_code_extent(child_scope, self.cx.parent)
1157 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent {
1158 self.new_code_extent(CodeExtentData::Misc(child_scope))
1161 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent {
1162 // If node was previously marked as a terminating scope during the
1163 // recursive visit of its parent node in the AST, then we need to
1164 // account for the destruction scope representing the extent of
1165 // the destructors that run immediately after it completes.
1166 if self.terminating_scopes.contains(&id) {
1167 let ds = self.new_code_extent(
1168 CodeExtentData::DestructionScope(id));
1169 self.region_maps.intern_node(id, ds)
1171 self.new_node_extent(id)
1175 fn create_item_scope_if_needed(&mut self, id: ast::NodeId) {
1176 // create a region for the destruction scope - this is needed
1177 // for constructing parameter environments based on the item.
1178 // functions put their destruction scopes *inside* their parameter
1180 let scope = CodeExtentData::DestructionScope(id);
1181 if !self.region_maps.code_extent_interner.borrow().contains_key(&scope) {
1182 self.region_maps.intern_code_extent(scope, ROOT_CODE_EXTENT);
1187 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1188 fn visit_block(&mut self, b: &Block) {
1189 resolve_block(self, b);
1192 fn visit_item(&mut self, i: &Item) {
1193 resolve_item(self, i);
1196 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
1197 intravisit::walk_impl_item(self, ii);
1198 self.create_item_scope_if_needed(ii.id);
1201 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
1202 intravisit::walk_trait_item(self, ti);
1203 self.create_item_scope_if_needed(ti.id);
1206 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1207 b: &'v Block, s: Span, n: NodeId) {
1208 resolve_fn(self, fk, fd, b, s, n);
1210 fn visit_arm(&mut self, a: &Arm) {
1211 resolve_arm(self, a);
1213 fn visit_pat(&mut self, p: &Pat) {
1214 resolve_pat(self, p);
1216 fn visit_stmt(&mut self, s: &Stmt) {
1217 resolve_stmt(self, s);
1219 fn visit_expr(&mut self, ex: &Expr) {
1220 resolve_expr(self, ex);
1222 fn visit_local(&mut self, l: &Local) {
1223 resolve_local(self, l);
1227 pub fn resolve_crate(sess: &Session, krate: &hir::Crate) -> RegionMaps {
1228 let maps = RegionMaps {
1229 code_extents: RefCell::new(vec![]),
1230 code_extent_interner: RefCell::new(FnvHashMap()),
1231 scope_map: RefCell::new(vec![]),
1232 var_map: RefCell::new(NodeMap()),
1233 rvalue_scopes: RefCell::new(NodeMap()),
1234 fn_tree: RefCell::new(NodeMap()),
1236 let root_extent = maps.bogus_code_extent(
1237 CodeExtentData::DestructionScope(ast::DUMMY_NODE_ID));
1238 assert_eq!(root_extent, ROOT_CODE_EXTENT);
1239 let bogus_extent = maps.bogus_code_extent(
1240 CodeExtentData::Misc(ast::DUMMY_NODE_ID));
1241 assert_eq!(bogus_extent, DUMMY_CODE_EXTENT);
1243 let mut visitor = RegionResolutionVisitor {
1248 parent: ROOT_CODE_EXTENT,
1249 var_parent: ROOT_CODE_EXTENT
1251 terminating_scopes: NodeSet()
1253 krate.visit_all_items(&mut visitor);
1258 pub fn resolve_inlined_item(sess: &Session,
1259 region_maps: &RegionMaps,
1260 item: &InlinedItem) {
1261 let mut visitor = RegionResolutionVisitor {
1263 region_maps: region_maps,
1266 parent: ROOT_CODE_EXTENT,
1267 var_parent: ROOT_CODE_EXTENT
1269 terminating_scopes: NodeSet()
1271 item.visit(&mut visitor);