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 hir::map as hir_map;
21 use util::nodemap::{FxHashMap, NodeMap, NodeSet};
24 use std::collections::hash_map::Entry;
29 use syntax::ast::{self, NodeId};
32 use ty::maps::Providers;
35 use hir::def_id::{CrateNum, LOCAL_CRATE};
36 use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
37 use hir::{Block, Item, FnDecl, Arm, Pat, PatKind, Stmt, Expr, Local};
39 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
40 RustcDecodable, Copy)]
41 pub struct CodeExtent(u32);
43 impl fmt::Debug for CodeExtent {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 write!(f, "CodeExtent({:?}", self.0)?;
47 ty::tls::with_opt(|opt_tcx| {
48 if let Some(tcx) = opt_tcx {
49 let region_maps = tcx.region_maps();
51 let code_extents = ®ion_maps.code_extents;
52 if let Some(data) = code_extents.get(self.0 as usize) {
53 write!(f, "/{:?}", data)?;
55 mem::drop(code_extents); // FIXME why is this necessary?
65 /// The root of everything. I should be using NonZero or profiling
66 /// instead of this (probably).
67 pub const ROOT_CODE_EXTENT : CodeExtent = CodeExtent(0);
68 /// A placeholder used in trans to stand for real code extents
69 pub const DUMMY_CODE_EXTENT : CodeExtent = CodeExtent(1);
71 /// CodeExtent represents a statically-describable extent that can be
72 /// used to bound the lifetime/region for values.
74 /// `Misc(node_id)`: Any AST node that has any extent at all has the
75 /// `Misc(node_id)` extent. Other variants represent special cases not
76 /// immediately derivable from the abstract syntax tree structure.
78 /// `DestructionScope(node_id)` represents the extent of destructors
79 /// implicitly-attached to `node_id` that run immediately after the
80 /// expression for `node_id` itself. Not every AST node carries a
81 /// `DestructionScope`, but those that are `terminating_scopes` do;
82 /// see discussion with `RegionMaps`.
84 /// `Remainder(BlockRemainder { block, statement_index })` represents
85 /// the extent of user code running immediately after the initializer
86 /// expression for the indexed statement, until the end of the block.
88 /// So: the following code can be broken down into the extents beneath:
90 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
95 /// +---------+ (R10.)
97 /// +----------+ (M8.)
98 /// +----------------------+ (R7.)
100 /// +----------+ (M5.)
101 /// +-----------------------------------+ (M4.)
102 /// +--------------------------------------------------+ (M3.)
104 /// +-----------------------------------------------------------+ (M1.)
106 /// (M1.): Misc extent of the whole `let a = ...;` statement.
107 /// (M2.): Misc extent of the `f()` expression.
108 /// (M3.): Misc extent of the `f().g(..)` expression.
109 /// (M4.): Misc extent of the block labelled `'b:`.
110 /// (M5.): Misc extent of the `let x = d();` statement
111 /// (D6.): DestructionScope for temporaries created during M5.
112 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
113 /// (M8.): Misc Extent of the `let y = d();` statement.
114 /// (D9.): DestructionScope for temporaries created during M8.
115 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
116 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
117 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
119 /// Note that while the above picture shows the destruction scopes
120 /// as following their corresponding misc extents, in the internal
121 /// data structures of the compiler the destruction scopes are
122 /// represented as enclosing parents. This is sound because we use the
123 /// enclosing parent relationship just to ensure that referenced
124 /// values live long enough; phrased another way, the starting point
125 /// of each range is not really the important thing in the above
126 /// picture, but rather the ending point.
128 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
129 /// placate the same deriving in `ty::FreeRegion`, but we may want to
130 /// actually attach a more meaningful ordering to scopes than the one
131 /// generated via deriving here.
132 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy)]
133 pub enum CodeExtentData {
136 // extent of the call-site for a function or closure (outlives
137 // the parameters as well as the body).
138 CallSiteScope { fn_id: ast::NodeId, body_id: ast::NodeId },
140 // extent of parameters passed to a function or closure (they
142 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
144 // extent of destructors for temporaries of node-id
145 DestructionScope(ast::NodeId),
147 // extent of code following a `let id = expr;` binding in a block
148 Remainder(BlockRemainder)
151 /// extent of call-site for a function/method.
152 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
153 RustcDecodable, Debug, Copy)]
154 pub struct CallSiteScopeData {
155 pub fn_id: ast::NodeId, pub body_id: ast::NodeId,
158 impl CallSiteScopeData {
159 pub fn to_code_extent(&self, region_maps: &RegionMaps) -> CodeExtent {
160 region_maps.lookup_code_extent(
162 CallSiteScopeData { fn_id, body_id } =>
163 CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id },
168 /// Represents a subscope of `block` for a binding that is introduced
169 /// by `block.stmts[first_statement_index]`. Such subscopes represent
170 /// a suffix of the block. Note that each subscope does not include
171 /// the initializer expression, if any, for the statement indexed by
172 /// `first_statement_index`.
174 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
176 /// * the subscope with `first_statement_index == 0` is scope of both
177 /// `a` and `b`; it does not include EXPR_1, but does include
178 /// everything after that first `let`. (If you want a scope that
179 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
180 /// but instead another `CodeExtent` that encompasses the whole block,
181 /// e.g. `CodeExtentData::Misc`.
183 /// * the subscope with `first_statement_index == 1` is scope of `c`,
184 /// and thus does not include EXPR_2, but covers the `...`.
185 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
186 RustcDecodable, Debug, Copy)]
187 pub struct BlockRemainder {
188 pub block: ast::NodeId,
189 pub first_statement_index: u32,
192 impl CodeExtentData {
193 /// Returns a node id associated with this scope.
195 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
196 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
197 pub fn node_id(&self) -> ast::NodeId {
199 CodeExtentData::Misc(node_id) => node_id,
201 // These cases all return rough approximations to the
202 // precise extent denoted by `self`.
203 CodeExtentData::Remainder(br) => br.block,
204 CodeExtentData::DestructionScope(node_id) => node_id,
205 CodeExtentData::CallSiteScope { fn_id: _, body_id } |
206 CodeExtentData::ParameterScope { fn_id: _, body_id } => body_id,
213 fn into_option(self) -> Option<CodeExtent> {
214 if self == ROOT_CODE_EXTENT {
220 pub fn node_id(&self, region_maps: &RegionMaps) -> ast::NodeId {
221 region_maps.code_extent_data(*self).node_id()
224 /// Returns the span of this CodeExtent. Note that in general the
225 /// returned span may not correspond to the span of any node id in
227 pub fn span(&self, region_maps: &RegionMaps, hir_map: &hir_map::Map) -> Option<Span> {
228 match hir_map.find(self.node_id(region_maps)) {
229 Some(hir_map::NodeBlock(ref blk)) => {
230 match region_maps.code_extent_data(*self) {
231 CodeExtentData::CallSiteScope { .. } |
232 CodeExtentData::ParameterScope { .. } |
233 CodeExtentData::Misc(_) |
234 CodeExtentData::DestructionScope(_) => Some(blk.span),
236 CodeExtentData::Remainder(r) => {
237 assert_eq!(r.block, blk.id);
238 // Want span for extent starting after the
239 // indexed statement and ending at end of
240 // `blk`; reuse span of `blk` and shift `lo`
241 // forward to end of indexed statement.
243 // (This is the special case aluded to in the
244 // doc-comment for this method)
245 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
246 Some(Span { lo: stmt_span.hi, hi: blk.span.hi, ctxt: stmt_span.ctxt })
250 Some(hir_map::NodeExpr(ref expr)) => Some(expr.span),
251 Some(hir_map::NodeStmt(ref stmt)) => Some(stmt.span),
252 Some(hir_map::NodeItem(ref item)) => Some(item.span),
253 Some(_) | None => None,
258 /// The region maps encode information about region relationships.
259 pub struct RegionMaps {
260 code_extents: Vec<CodeExtentData>,
261 code_extent_interner: FxHashMap<CodeExtentData, CodeExtent>,
262 /// `scope_map` maps from a scope id to the enclosing scope id;
263 /// this is usually corresponding to the lexical nesting, though
264 /// in the case of closures the parent scope is the innermost
265 /// conditional expression or repeating block. (Note that the
266 /// enclosing scope id for the block associated with a closure is
267 /// the closure itself.)
268 scope_map: Vec<CodeExtent>,
270 /// `var_map` maps from a variable or binding id to the block in
271 /// which that variable is declared.
272 var_map: NodeMap<CodeExtent>,
274 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
275 /// larger than the default. The map goes from the expression id
276 /// to the cleanup scope id. For rvalues not present in this
277 /// table, the appropriate cleanup scope is the innermost
278 /// enclosing statement, conditional expression, or repeating
279 /// block (see `terminating_scopes`).
280 rvalue_scopes: NodeMap<CodeExtent>,
282 /// Records the value of rvalue scopes before they were shrunk by
283 /// #36082, for error reporting.
285 /// FIXME: this should be temporary. Remove this by 1.18.0 or
287 shrunk_rvalue_scopes: NodeMap<CodeExtent>,
289 /// Encodes the hierarchy of fn bodies. Every fn body (including
290 /// closures) forms its own distinct region hierarchy, rooted in
291 /// the block that is the fn body. This map points from the id of
292 /// that root block to the id of the root block for the enclosing
293 /// fn, if any. Thus the map structures the fn bodies into a
294 /// hierarchy based on their lexical mapping. This is used to
295 /// handle the relationships between regions in a fn and in a
296 /// closure defined by that fn. See the "Modeling closures"
297 /// section of the README in infer::region_inference for
299 fn_tree: NodeMap<ast::NodeId>,
302 #[derive(Debug, Copy, Clone)]
304 /// the root of the current region tree. This is typically the id
305 /// of the innermost fn body. Each fn forms its own disjoint tree
306 /// in the region hierarchy. These fn bodies are themselves
307 /// arranged into a tree. See the "Modeling closures" section of
308 /// the README in infer::region_inference for more
310 root_id: Option<ast::NodeId>,
312 /// the scope that contains any new variables declared
313 var_parent: CodeExtent,
315 /// region parent of expressions etc
319 struct RegionResolutionVisitor<'hir: 'a, 'a> {
323 region_maps: &'a mut RegionMaps,
327 map: &'a hir_map::Map<'hir>,
329 /// `terminating_scopes` is a set containing the ids of each
330 /// statement, or conditional/repeating expression. These scopes
331 /// are calling "terminating scopes" because, when attempting to
332 /// find the scope of a temporary, by default we search up the
333 /// enclosing scopes until we encounter the terminating scope. A
334 /// conditional/repeating expression is one which is not
335 /// guaranteed to execute exactly once upon entering the parent
336 /// scope. This could be because the expression only executes
337 /// conditionally, such as the expression `b` in `a && b`, or
338 /// because the expression may execute many times, such as a loop
339 /// body. The reason that we distinguish such expressions is that,
340 /// upon exiting the parent scope, we cannot statically know how
341 /// many times the expression executed, and thus if the expression
342 /// creates temporaries we cannot know statically how many such
343 /// temporaries we would have to cleanup. Therefore we ensure that
344 /// the temporaries never outlast the conditional/repeating
345 /// expression, preventing the need for dynamic checks and/or
346 /// arbitrary amounts of stack space. Terminating scopes end
347 /// up being contained in a DestructionScope that contains the
348 /// destructor's execution.
349 terminating_scopes: NodeSet
354 /// create a bogus code extent for the regions in astencode types. Nobody
355 /// really cares about the contents of these.
356 pub fn bogus_code_extent(&mut self, e: CodeExtentData) -> CodeExtent {
357 self.intern_code_extent(e, DUMMY_CODE_EXTENT)
359 pub fn lookup_code_extent(&self, e: CodeExtentData) -> CodeExtent {
360 match self.code_extent_interner.get(&e) {
362 None => bug!("unknown code extent {:?}", e)
365 pub fn node_extent(&self, n: ast::NodeId) -> CodeExtent {
366 self.lookup_code_extent(CodeExtentData::Misc(n))
368 // Returns the code extent for an item - the destruction scope.
369 pub fn item_extent(&self, n: ast::NodeId) -> CodeExtent {
370 self.lookup_code_extent(CodeExtentData::DestructionScope(n))
372 pub fn call_site_extent(&self, fn_id: ast::NodeId, body_id: ast::NodeId) -> CodeExtent {
373 assert!(fn_id != body_id);
374 self.lookup_code_extent(CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id })
376 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
377 self.code_extent_interner.get(&CodeExtentData::DestructionScope(n)).cloned()
379 pub fn intern_code_extent(&mut self,
381 parent: CodeExtent) -> CodeExtent {
382 match self.code_extent_interner.entry(e) {
383 Entry::Occupied(o) => {
384 // this can happen when the bogus code extents from tydecode
385 // have (bogus) NodeId-s that overlap items created during
387 // We probably shouldn't be creating bogus code extents
390 if parent == DUMMY_CODE_EXTENT {
391 info!("CodeExtent({}) = {:?} [parent={}] BOGUS!",
394 assert_eq!(self.scope_map[idx.0 as usize],
396 info!("CodeExtent({}) = {:?} [parent={}] RECLAIMED!",
398 self.scope_map[idx.0 as usize] = parent;
402 Entry::Vacant(v) => {
403 if self.code_extents.len() > 0xffffffffusize {
404 bug!() // should pass a sess,
405 // but this isn't the only place
407 let idx = CodeExtent(self.code_extents.len() as u32);
408 debug!("CodeExtent({}) = {:?} [parent={}]", idx.0, e, parent.0);
409 self.code_extents.push(e);
410 self.scope_map.push(parent);
415 pub fn intern_node(&mut self,
417 parent: CodeExtent) -> CodeExtent {
418 self.intern_code_extent(CodeExtentData::Misc(n), parent)
420 pub fn code_extent_data(&self, e: CodeExtent) -> CodeExtentData {
421 self.code_extents[e.0 as usize]
423 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
424 for child_id in 1..self.code_extents.len() {
425 let child = CodeExtent(child_id as u32);
426 if let Some(parent) = self.opt_encl_scope(child) {
431 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
432 for (child, parent) in self.var_map.iter() {
437 /// Records that `sub_fn` is defined within `sup_fn`. These ids
438 /// should be the id of the block that is the fn body, which is
439 /// also the root of the region hierarchy for that fn.
440 fn record_fn_parent(&mut self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
441 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
442 assert!(sub_fn != sup_fn);
443 let previous = self.fn_tree.insert(sub_fn, sup_fn);
444 assert!(previous.is_none());
447 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
449 if sub_fn == sup_fn { return true; }
450 match self.fn_tree.get(&sub_fn) {
451 Some(&s) => { sub_fn = s; }
452 None => { return false; }
457 fn record_var_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
458 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
459 assert!(var != lifetime.node_id(self));
460 self.var_map.insert(var, lifetime);
463 fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
464 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
465 assert!(var != lifetime.node_id(self));
466 self.rvalue_scopes.insert(var, lifetime);
469 fn record_shrunk_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
470 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
471 assert!(var != lifetime.node_id(self));
472 self.shrunk_rvalue_scopes.insert(var, lifetime);
475 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
476 //! Returns the narrowest scope that encloses `id`, if any.
477 self.scope_map[id.0 as usize].into_option()
480 #[allow(dead_code)] // used in cfg
481 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
482 //! Returns the narrowest scope that encloses `id`, if any.
483 self.opt_encl_scope(id).unwrap()
486 /// Returns the lifetime of the local variable `var_id`
487 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
488 match self.var_map.get(&var_id) {
490 None => { bug!("no enclosing scope for id {:?}", var_id); }
494 pub fn temporary_scope2(&self, expr_id: ast::NodeId) -> (Option<CodeExtent>, bool) {
495 let temporary_scope = self.temporary_scope(expr_id);
496 let was_shrunk = match self.shrunk_rvalue_scopes.get(&expr_id) {
498 info!("temporary_scope2({:?}, scope={:?}, shrunk={:?})",
499 expr_id, temporary_scope, s);
500 temporary_scope != Some(s)
504 info!("temporary_scope2({:?}) - was_shrunk={:?}", expr_id, was_shrunk);
505 (temporary_scope, was_shrunk)
508 pub fn old_and_new_temporary_scope(&self, expr_id: ast::NodeId) ->
509 (Option<CodeExtent>, Option<CodeExtent>)
511 let temporary_scope = self.temporary_scope(expr_id);
513 self.shrunk_rvalue_scopes
514 .get(&expr_id).cloned()
515 .or(temporary_scope))
518 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
519 //! Returns the scope when temp created by expr_id will be cleaned up
521 // check for a designated rvalue scope
522 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
523 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
527 let scope_map : &[CodeExtent] = &self.scope_map;
528 let code_extents: &[CodeExtentData] = &self.code_extents;
530 // else, locate the innermost terminating scope
531 // if there's one. Static items, for instance, won't
532 // have an enclosing scope, hence no scope will be
534 let mut id = self.node_extent(expr_id);
536 while let Some(p) = scope_map[id.0 as usize].into_option() {
537 match code_extents[p.0 as usize] {
538 CodeExtentData::DestructionScope(..) => {
539 debug!("temporary_scope({:?}) = {:?} [enclosing]",
547 debug!("temporary_scope({:?}) = None", expr_id);
551 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
552 //! Returns the lifetime of the variable `id`.
554 let scope = ty::ReScope(self.var_scope(id));
555 debug!("var_region({:?}) = {:?}", id, scope);
559 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
561 self.is_subscope_of(scope1, scope2) ||
562 self.is_subscope_of(scope2, scope1)
565 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
567 pub fn is_subscope_of(&self,
568 subscope: CodeExtent,
569 superscope: CodeExtent)
571 let mut s = subscope;
572 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
573 while superscope != s {
574 match self.opt_encl_scope(s) {
576 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
577 subscope, superscope, s);
580 Some(scope) => s = scope
584 debug!("is_subscope_of({:?}, {:?})=true",
585 subscope, superscope);
590 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
591 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
592 pub fn nearest_common_ancestor(&self,
596 if scope_a == scope_b { return scope_a; }
598 let mut a_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
599 let mut a_vec: Vec<CodeExtent> = vec![];
600 let mut b_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
601 let mut b_vec: Vec<CodeExtent> = vec![];
602 let scope_map : &[CodeExtent] = &self.scope_map;
603 let a_ancestors = ancestors_of(scope_map,
604 scope_a, &mut a_buf, &mut a_vec);
605 let b_ancestors = ancestors_of(scope_map,
606 scope_b, &mut b_buf, &mut b_vec);
607 let mut a_index = a_ancestors.len() - 1;
608 let mut b_index = b_ancestors.len() - 1;
610 // Here, [ab]_ancestors is a vector going from narrow to broad.
611 // The end of each vector will be the item where the scope is
612 // defined; if there are any common ancestors, then the tails of
613 // the vector will be the same. So basically we want to walk
614 // backwards from the tail of each vector and find the first point
615 // where they diverge. If one vector is a suffix of the other,
616 // then the corresponding scope is a superscope of the other.
618 if a_ancestors[a_index] != b_ancestors[b_index] {
619 // In this case, the two regions belong to completely
620 // different functions. Compare those fn for lexical
621 // nesting. The reasoning behind this is subtle. See the
622 // "Modeling closures" section of the README in
623 // infer::region_inference for more details.
624 let a_root_scope = self.code_extent_data(a_ancestors[a_index]);
625 let b_root_scope = self.code_extent_data(a_ancestors[a_index]);
626 return match (a_root_scope, b_root_scope) {
627 (CodeExtentData::DestructionScope(a_root_id),
628 CodeExtentData::DestructionScope(b_root_id)) => {
629 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
630 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
632 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
633 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
636 // neither fn encloses the other
641 // root ids are always Misc right now
648 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
649 // for all indices between a_index and the end of the array
650 if a_index == 0 { return scope_a; }
651 if b_index == 0 { return scope_b; }
654 if a_ancestors[a_index] != b_ancestors[b_index] {
655 return a_ancestors[a_index + 1];
659 fn ancestors_of<'a>(scope_map: &[CodeExtent],
661 buf: &'a mut [CodeExtent; 32],
662 vec: &'a mut Vec<CodeExtent>) -> &'a [CodeExtent] {
663 // debug!("ancestors_of(scope={:?})", scope);
664 let mut scope = scope;
669 match scope_map[scope.0 as usize].into_option() {
670 Some(superscope) => scope = superscope,
671 _ => return &buf[..i+1]
676 *vec = Vec::with_capacity(64);
677 vec.extend_from_slice(buf);
680 match scope_map[scope.0 as usize].into_option() {
681 Some(superscope) => scope = superscope,
689 /// Records the lifetime of a local variable as `cx.var_parent`
690 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
693 match visitor.cx.var_parent {
694 ROOT_CODE_EXTENT => {
695 // this can happen in extern fn declarations like
697 // extern fn isalnum(c: c_int) -> c_int
700 visitor.region_maps.record_var_scope(var_id, parent_scope),
704 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>, blk: &'tcx hir::Block) {
705 debug!("resolve_block(blk.id={:?})", blk.id);
707 let prev_cx = visitor.cx;
708 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
710 // We treat the tail expression in the block (if any) somewhat
711 // differently from the statements. The issue has to do with
712 // temporary lifetimes. Consider the following:
715 // let inner = ... (&bar()) ...;
717 // (... (&foo()) ...) // (the tail expression)
718 // }, other_argument());
720 // Each of the statements within the block is a terminating
721 // scope, and thus a temporary (e.g. the result of calling
722 // `bar()` in the initalizer expression for `let inner = ...;`)
723 // will be cleaned up immediately after its corresponding
724 // statement (i.e. `let inner = ...;`) executes.
726 // On the other hand, temporaries associated with evaluating the
727 // tail expression for the block are assigned lifetimes so that
728 // they will be cleaned up as part of the terminating scope
729 // *surrounding* the block expression. Here, the terminating
730 // scope for the block expression is the `quux(..)` call; so
731 // those temporaries will only be cleaned up *after* both
732 // `other_argument()` has run and also the call to `quux(..)`
733 // itself has returned.
735 visitor.cx = Context {
736 root_id: prev_cx.root_id,
737 var_parent: block_extent,
738 parent: block_extent,
742 // This block should be kept approximately in sync with
743 // `intravisit::walk_block`. (We manually walk the block, rather
744 // than call `walk_block`, in order to maintain precise
745 // index information.)
747 for (i, statement) in blk.stmts.iter().enumerate() {
748 if let hir::StmtDecl(..) = statement.node {
749 // Each StmtDecl introduces a subscope for bindings
750 // introduced by the declaration; this subscope covers
751 // a suffix of the block . Each subscope in a block
752 // has the previous subscope in the block as a parent,
753 // except for the first such subscope, which has the
754 // block itself as a parent.
755 let stmt_extent = visitor.new_code_extent(
756 CodeExtentData::Remainder(BlockRemainder {
758 first_statement_index: i as u32
761 visitor.cx = Context {
762 root_id: prev_cx.root_id,
763 var_parent: stmt_extent,
767 visitor.visit_stmt(statement)
769 walk_list!(visitor, visit_expr, &blk.expr);
772 visitor.cx = prev_cx;
775 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>, arm: &'tcx hir::Arm) {
776 visitor.terminating_scopes.insert(arm.body.id);
778 if let Some(ref expr) = arm.guard {
779 visitor.terminating_scopes.insert(expr.id);
782 intravisit::walk_arm(visitor, arm);
785 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>, pat: &'tcx hir::Pat) {
786 visitor.new_node_extent(pat.id);
788 // If this is a binding then record the lifetime of that binding.
789 if let PatKind::Binding(..) = pat.node {
790 record_var_lifetime(visitor, pat.id, pat.span);
793 intravisit::walk_pat(visitor, pat);
796 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>, stmt: &'tcx hir::Stmt) {
797 let stmt_id = stmt.node.id();
798 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
800 // Every statement will clean up the temporaries created during
801 // execution of that statement. Therefore each statement has an
802 // associated destruction scope that represents the extent of the
803 // statement plus its destructors, and thus the extent for which
804 // regions referenced by the destructors need to survive.
805 visitor.terminating_scopes.insert(stmt_id);
806 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
808 let prev_parent = visitor.cx.parent;
809 visitor.cx.parent = stmt_extent;
810 intravisit::walk_stmt(visitor, stmt);
811 visitor.cx.parent = prev_parent;
814 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>, expr: &'tcx hir::Expr) {
815 debug!("resolve_expr(expr.id={:?})", expr.id);
817 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
818 let prev_cx = visitor.cx;
819 visitor.cx.parent = expr_extent;
822 let terminating_scopes = &mut visitor.terminating_scopes;
823 let mut terminating = |id: ast::NodeId| {
824 terminating_scopes.insert(id);
827 // Conditional or repeating scopes are always terminating
828 // scopes, meaning that temporaries cannot outlive them.
829 // This ensures fixed size stacks.
831 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
832 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
833 // For shortcircuiting operators, mark the RHS as a terminating
834 // scope since it only executes conditionally.
838 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
839 terminating(expr.id);
840 terminating(then.id);
841 terminating(otherwise.id);
844 hir::ExprIf(ref expr, ref then, None) => {
845 terminating(expr.id);
846 terminating(then.id);
849 hir::ExprLoop(ref body, _, _) => {
850 terminating(body.id);
853 hir::ExprWhile(ref expr, ref body, _) => {
854 terminating(expr.id);
855 terminating(body.id);
858 hir::ExprMatch(..) => {
859 visitor.cx.var_parent = expr_extent;
862 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
863 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
864 // FIXME(#6268) Nested method calls
866 // The lifetimes for a call or method call look as follows:
874 // The idea is that call.callee_id represents *the time when
875 // the invoked function is actually running* and call.id
876 // represents *the time to prepare the arguments and make the
877 // call*. See the section "Borrows in Calls" borrowck/README.md
878 // for an extended explanation of why this distinction is
881 // record_superlifetime(new_cx, expr.callee_id);
888 intravisit::walk_expr(visitor, expr);
889 visitor.cx = prev_cx;
892 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>,
893 local: &'tcx hir::Local) {
894 debug!("resolve_local(local.id={:?},local.init={:?})",
895 local.id,local.init.is_some());
897 // For convenience in trans, associate with the local-id the var
898 // scope that will be used for any bindings declared in this
900 let blk_scope = visitor.cx.var_parent;
901 assert!(blk_scope != ROOT_CODE_EXTENT); // locals must be within a block
902 visitor.region_maps.record_var_scope(local.id, blk_scope);
904 // As an exception to the normal rules governing temporary
905 // lifetimes, initializers in a let have a temporary lifetime
906 // of the enclosing block. This means that e.g. a program
907 // like the following is legal:
909 // let ref x = HashMap::new();
911 // Because the hash map will be freed in the enclosing block.
913 // We express the rules more formally based on 3 grammars (defined
914 // fully in the helpers below that implement them):
916 // 1. `E&`, which matches expressions like `&<rvalue>` that
917 // own a pointer into the stack.
919 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
920 // y)` that produce ref bindings into the value they are
921 // matched against or something (at least partially) owned by
922 // the value they are matched against. (By partially owned,
923 // I mean that creating a binding into a ref-counted or managed value
924 // would still count.)
926 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
927 // based on rvalues like `foo().x[2].y`.
929 // A subexpression `<rvalue>` that appears in a let initializer
930 // `let pat [: ty] = expr` has an extended temporary lifetime if
931 // any of the following conditions are met:
933 // A. `pat` matches `P&` and `expr` matches `ET`
934 // (covers cases where `pat` creates ref bindings into an rvalue
935 // produced by `expr`)
936 // B. `ty` is a borrowed pointer and `expr` matches `ET`
937 // (covers cases where coercion creates a borrow)
938 // C. `expr` matches `E&`
939 // (covers cases `expr` borrows an rvalue that is then assigned
940 // to memory (at least partially) owned by the binding)
942 // Here are some examples hopefully giving an intuition where each
943 // rule comes into play and why:
945 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
946 // would have an extended lifetime, but not `foo()`.
948 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
949 // would have an extended lifetime, but not `foo()`.
951 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
954 // In some cases, multiple rules may apply (though not to the same
955 // rvalue). For example:
957 // let ref x = [&a(), &b()];
959 // Here, the expression `[...]` has an extended lifetime due to rule
960 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
963 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
965 if let Some(ref expr) = local.init {
966 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
969 if let Some(ref ty) = local.ty { is_borrowed_ty(&ty) } else { false };
971 if is_binding_pat(&local.pat) {
972 record_rvalue_scope(visitor, &expr, blk_scope, false);
973 } else if is_borrow {
974 record_rvalue_scope(visitor, &expr, blk_scope, true);
978 intravisit::walk_local(visitor, local);
980 /// True if `pat` match the `P&` nonterminal:
983 /// | StructName { ..., P&, ... }
984 /// | VariantName(..., P&, ...)
985 /// | [ ..., P&, ... ]
986 /// | ( ..., P&, ... )
988 fn is_binding_pat(pat: &hir::Pat) -> bool {
990 PatKind::Binding(hir::BindByRef(_), ..) => true,
992 PatKind::Struct(_, ref field_pats, _) => {
993 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
996 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
997 pats1.iter().any(|p| is_binding_pat(&p)) ||
998 pats2.iter().any(|p| is_binding_pat(&p)) ||
999 pats3.iter().any(|p| is_binding_pat(&p))
1002 PatKind::TupleStruct(_, ref subpats, _) |
1003 PatKind::Tuple(ref subpats, _) => {
1004 subpats.iter().any(|p| is_binding_pat(&p))
1007 PatKind::Box(ref subpat) => {
1008 is_binding_pat(&subpat)
1015 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
1016 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
1018 hir::TyRptr(..) => true,
1023 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1026 /// | StructName { ..., f: E&, ... }
1027 /// | [ ..., E&, ... ]
1028 /// | ( ..., E&, ... )
1033 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1035 blk_id: CodeExtent) {
1037 hir::ExprAddrOf(_, ref subexpr) => {
1038 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1039 record_rvalue_scope(visitor, &subexpr, blk_id, false);
1041 hir::ExprStruct(_, ref fields, _) => {
1042 for field in fields {
1043 record_rvalue_scope_if_borrow_expr(
1044 visitor, &field.expr, blk_id);
1047 hir::ExprArray(ref subexprs) |
1048 hir::ExprTup(ref subexprs) => {
1049 for subexpr in subexprs {
1050 record_rvalue_scope_if_borrow_expr(
1051 visitor, &subexpr, blk_id);
1054 hir::ExprCast(ref subexpr, _) => {
1055 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1057 hir::ExprBlock(ref block) => {
1058 if let Some(ref subexpr) = block.expr {
1059 record_rvalue_scope_if_borrow_expr(
1060 visitor, &subexpr, blk_id);
1067 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1068 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1069 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1072 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1073 /// `<rvalue>` as `blk_id`:
1081 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1082 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1083 expr: &'a hir::Expr,
1084 blk_scope: CodeExtent,
1086 let mut expr = expr;
1088 // Note: give all the expressions matching `ET` with the
1089 // extended temporary lifetime, not just the innermost rvalue,
1090 // because in trans if we must compile e.g. `*rvalue()`
1091 // into a temporary, we request the temporary scope of the
1092 // outer expression.
1094 // this changed because of #36082
1095 visitor.region_maps.record_shrunk_rvalue_scope(expr.id, blk_scope);
1097 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1101 hir::ExprAddrOf(_, ref subexpr) |
1102 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1103 hir::ExprField(ref subexpr, _) |
1104 hir::ExprTupField(ref subexpr, _) |
1105 hir::ExprIndex(ref subexpr, _) => {
1116 fn resolve_item_like<'a, 'tcx, F>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>,
1119 where F: FnOnce(&mut RegionResolutionVisitor<'tcx, 'a>)
1121 // Items create a new outer block scope as far as we're concerned.
1122 let prev_cx = visitor.cx;
1123 let prev_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1124 visitor.cx = Context {
1126 var_parent: ROOT_CODE_EXTENT,
1127 parent: ROOT_CODE_EXTENT
1130 visitor.create_item_scope_if_needed(id);
1131 visitor.cx = prev_cx;
1132 visitor.terminating_scopes = prev_ts;
1135 fn resolve_fn<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'tcx, 'a>,
1137 decl: &'tcx hir::FnDecl,
1138 body_id: hir::BodyId,
1141 debug!("region::resolve_fn(id={:?}, \
1146 visitor.sess.codemap().span_to_string(sp),
1150 visitor.cx.parent = visitor.new_code_extent(
1151 CodeExtentData::CallSiteScope { fn_id: id, body_id: body_id.node_id });
1153 let fn_decl_scope = visitor.new_code_extent(
1154 CodeExtentData::ParameterScope { fn_id: id, body_id: body_id.node_id });
1156 if let Some(root_id) = visitor.cx.root_id {
1157 visitor.region_maps.record_fn_parent(body_id.node_id, root_id);
1160 let outer_cx = visitor.cx;
1161 let outer_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1162 visitor.terminating_scopes.insert(body_id.node_id);
1164 // The arguments and `self` are parented to the fn.
1165 visitor.cx = Context {
1166 root_id: Some(body_id.node_id),
1167 parent: ROOT_CODE_EXTENT,
1168 var_parent: fn_decl_scope,
1171 intravisit::walk_fn_decl(visitor, decl);
1172 intravisit::walk_fn_kind(visitor, kind);
1174 // The body of the every fn is a root scope.
1175 visitor.cx = Context {
1176 root_id: Some(body_id.node_id),
1177 parent: fn_decl_scope,
1178 var_parent: fn_decl_scope
1180 visitor.visit_nested_body(body_id);
1182 // Restore context we had at the start.
1183 visitor.cx = outer_cx;
1184 visitor.terminating_scopes = outer_ts;
1187 impl<'hir, 'a> RegionResolutionVisitor<'hir, 'a> {
1188 /// Records the current parent (if any) as the parent of `child_scope`.
1189 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent {
1190 self.region_maps.intern_code_extent(child_scope, self.cx.parent)
1193 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent {
1194 self.new_code_extent(CodeExtentData::Misc(child_scope))
1197 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent {
1198 // If node was previously marked as a terminating scope during the
1199 // recursive visit of its parent node in the AST, then we need to
1200 // account for the destruction scope representing the extent of
1201 // the destructors that run immediately after it completes.
1202 if self.terminating_scopes.contains(&id) {
1203 let ds = self.new_code_extent(
1204 CodeExtentData::DestructionScope(id));
1205 self.region_maps.intern_node(id, ds)
1207 self.new_node_extent(id)
1211 fn create_item_scope_if_needed(&mut self, id: ast::NodeId) {
1212 // create a region for the destruction scope - this is needed
1213 // for constructing parameter environments based on the item.
1214 // functions put their destruction scopes *inside* their parameter
1216 let scope = CodeExtentData::DestructionScope(id);
1217 if !self.region_maps.code_extent_interner.contains_key(&scope) {
1218 self.region_maps.intern_code_extent(scope, ROOT_CODE_EXTENT);
1223 impl<'hir, 'a> Visitor<'hir> for RegionResolutionVisitor<'hir, 'a> {
1224 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
1225 NestedVisitorMap::OnlyBodies(&self.map)
1228 fn visit_block(&mut self, b: &'hir Block) {
1229 resolve_block(self, b);
1232 fn visit_item(&mut self, i: &'hir Item) {
1233 resolve_item_like(self, i.id, |this| intravisit::walk_item(this, i));
1236 fn visit_impl_item(&mut self, ii: &'hir hir::ImplItem) {
1237 resolve_item_like(self, ii.id, |this| intravisit::walk_impl_item(this, ii));
1240 fn visit_trait_item(&mut self, ti: &'hir hir::TraitItem) {
1241 resolve_item_like(self, ti.id, |this| intravisit::walk_trait_item(this, ti));
1244 fn visit_fn(&mut self, fk: FnKind<'hir>, fd: &'hir FnDecl,
1245 b: hir::BodyId, s: Span, n: NodeId) {
1246 resolve_fn(self, fk, fd, b, s, n);
1248 fn visit_arm(&mut self, a: &'hir Arm) {
1249 resolve_arm(self, a);
1251 fn visit_pat(&mut self, p: &'hir Pat) {
1252 resolve_pat(self, p);
1254 fn visit_stmt(&mut self, s: &'hir Stmt) {
1255 resolve_stmt(self, s);
1257 fn visit_expr(&mut self, ex: &'hir Expr) {
1258 resolve_expr(self, ex);
1260 fn visit_local(&mut self, l: &'hir Local) {
1261 resolve_local(self, l);
1265 pub fn resolve_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<RegionMaps> {
1266 tcx.region_resolve_crate(LOCAL_CRATE)
1269 fn region_resolve_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum)
1272 debug_assert!(crate_num == LOCAL_CRATE);
1274 let sess = &tcx.sess;
1275 let hir_map = &tcx.hir;
1277 let krate = hir_map.krate();
1279 let mut maps = RegionMaps {
1280 code_extents: vec![],
1281 code_extent_interner: FxHashMap(),
1284 rvalue_scopes: NodeMap(),
1285 shrunk_rvalue_scopes: NodeMap(),
1288 let root_extent = maps.bogus_code_extent(
1289 CodeExtentData::DestructionScope(ast::DUMMY_NODE_ID));
1290 assert_eq!(root_extent, ROOT_CODE_EXTENT);
1291 let bogus_extent = maps.bogus_code_extent(
1292 CodeExtentData::Misc(ast::DUMMY_NODE_ID));
1293 assert_eq!(bogus_extent, DUMMY_CODE_EXTENT);
1295 let mut visitor = RegionResolutionVisitor {
1297 region_maps: &mut maps,
1301 parent: ROOT_CODE_EXTENT,
1302 var_parent: ROOT_CODE_EXTENT
1304 terminating_scopes: NodeSet()
1306 krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
1311 pub fn provide(providers: &mut Providers) {
1312 *providers = Providers {
1313 region_resolve_crate,