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 builds up the `ScopeTree`, which describes
12 //! the parent links in the region hierarchy.
14 //! Most of the documentation on regions can be found in
15 //! `middle/infer/region_inference/README.md`
17 use util::nodemap::{FxHashMap, FxHashSet};
20 use std::collections::hash_map::Entry;
25 use syntax_pos::{Span, DUMMY_SP};
27 use ty::maps::Providers;
30 use hir::def_id::DefId;
31 use hir::intravisit::{self, Visitor, NestedVisitorMap};
32 use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
33 use mir::transform::MirSource;
35 /// Scope represents a statically-describable scope that can be
36 /// used to bound the lifetime/region for values.
38 /// `Node(node_id)`: Any AST node that has any scope at all has the
39 /// `Node(node_id)` scope. Other variants represent special cases not
40 /// immediately derivable from the abstract syntax tree structure.
42 /// `DestructionScope(node_id)` represents the scope of destructors
43 /// implicitly-attached to `node_id` that run immediately after the
44 /// expression for `node_id` itself. Not every AST node carries a
45 /// `DestructionScope`, but those that are `terminating_scopes` do;
46 /// see discussion with `ScopeTree`.
48 /// `Remainder(BlockRemainder { block, statement_index })` represents
49 /// the scope of user code running immediately after the initializer
50 /// expression for the indexed statement, until the end of the block.
52 /// So: the following code can be broken down into the scopes beneath:
54 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
59 /// +---------+ (R10.)
61 /// +----------+ (M8.)
62 /// +----------------------+ (R7.)
64 /// +----------+ (M5.)
65 /// +-----------------------------------+ (M4.)
66 /// +--------------------------------------------------+ (M3.)
68 /// +-----------------------------------------------------------+ (M1.)
70 /// (M1.): Node scope of the whole `let a = ...;` statement.
71 /// (M2.): Node scope of the `f()` expression.
72 /// (M3.): Node scope of the `f().g(..)` expression.
73 /// (M4.): Node scope of the block labeled `'b:`.
74 /// (M5.): Node scope of the `let x = d();` statement
75 /// (D6.): DestructionScope for temporaries created during M5.
76 /// (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
77 /// (M8.): Node scope of the `let y = d();` statement.
78 /// (D9.): DestructionScope for temporaries created during M8.
79 /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
80 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
81 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
83 /// Note that while the above picture shows the destruction scopes
84 /// as following their corresponding node scopes, in the internal
85 /// data structures of the compiler the destruction scopes are
86 /// represented as enclosing parents. This is sound because we use the
87 /// enclosing parent relationship just to ensure that referenced
88 /// values live long enough; phrased another way, the starting point
89 /// of each range is not really the important thing in the above
90 /// picture, but rather the ending point.
92 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
93 /// placate the same deriving in `ty::FreeRegion`, but we may want to
94 /// actually attach a more meaningful ordering to scopes than the one
95 /// generated via deriving here.
96 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
98 Node(hir::ItemLocalId),
100 // Scope of the call-site for a function or closure
101 // (outlives the arguments as well as the body).
102 CallSite(hir::ItemLocalId),
104 // Scope of arguments passed to a function or closure
105 // (they outlive its body).
106 Arguments(hir::ItemLocalId),
108 // Scope of destructors for temporaries of node-id.
109 Destruction(hir::ItemLocalId),
111 // Scope following a `let id = expr;` binding in a block.
112 Remainder(BlockRemainder)
115 /// Represents a subscope of `block` for a binding that is introduced
116 /// by `block.stmts[first_statement_index]`. Such subscopes represent
117 /// a suffix of the block. Note that each subscope does not include
118 /// the initializer expression, if any, for the statement indexed by
119 /// `first_statement_index`.
121 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
123 /// * the subscope with `first_statement_index == 0` is scope of both
124 /// `a` and `b`; it does not include EXPR_1, but does include
125 /// everything after that first `let`. (If you want a scope that
126 /// includes EXPR_1 as well, then do not use `Scope::Remainder`,
127 /// but instead another `Scope` that encompasses the whole block,
128 /// e.g. `Scope::Node`.
130 /// * the subscope with `first_statement_index == 1` is scope of `c`,
131 /// and thus does not include EXPR_2, but covers the `...`.
132 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
133 RustcDecodable, Debug, Copy)]
134 pub struct BlockRemainder {
135 pub block: hir::ItemLocalId,
136 pub first_statement_index: u32,
140 /// Returns a item-local id associated with this scope.
142 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
143 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
144 pub fn item_local_id(&self) -> hir::ItemLocalId {
146 Scope::Node(id) => id,
148 // These cases all return rough approximations to the
149 // precise scope denoted by `self`.
150 Scope::Remainder(br) => br.block,
151 Scope::Destruction(id) |
152 Scope::CallSite(id) |
153 Scope::Arguments(id) => id,
157 pub fn node_id(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> ast::NodeId {
158 match scope_tree.root_body {
160 tcx.hir.hir_to_node_id(hir::HirId {
162 local_id: self.item_local_id()
165 None => ast::DUMMY_NODE_ID
169 /// Returns the span of this Scope. Note that in general the
170 /// returned span may not correspond to the span of any node id in
172 pub fn span(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> Span {
173 let node_id = self.node_id(tcx, scope_tree);
174 if node_id == ast::DUMMY_NODE_ID {
177 let span = tcx.hir.span(node_id);
178 if let Scope::Remainder(r) = *self {
179 if let hir::map::NodeBlock(ref blk) = tcx.hir.get(node_id) {
180 // Want span for scope starting after the
181 // indexed statement and ending at end of
182 // `blk`; reuse span of `blk` and shift `lo`
183 // forward to end of indexed statement.
185 // (This is the special case aluded to in the
186 // doc-comment for this method)
188 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
190 // To avoid issues with macro-generated spans, the span
191 // of the statement must be nested in that of the block.
192 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
193 return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
201 /// The region scope tree encodes information about region relationships.
203 pub struct ScopeTree {
204 /// If not empty, this body is the root of this region hierarchy.
205 root_body: Option<hir::HirId>,
207 /// The parent of the root body owner, if the latter is an
208 /// an associated const or method, as impls/traits can also
209 /// have lifetime parameters free in this body.
210 root_parent: Option<ast::NodeId>,
212 /// `parent_map` maps from a scope id to the enclosing scope id;
213 /// this is usually corresponding to the lexical nesting, though
214 /// in the case of closures the parent scope is the innermost
215 /// conditional expression or repeating block. (Note that the
216 /// enclosing scope id for the block associated with a closure is
217 /// the closure itself.)
218 parent_map: FxHashMap<Scope, Scope>,
220 /// `var_map` maps from a variable or binding id to the block in
221 /// which that variable is declared.
222 var_map: FxHashMap<hir::ItemLocalId, Scope>,
224 /// maps from a node-id to the associated destruction scope (if any)
225 destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
227 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
228 /// larger than the default. The map goes from the expression id
229 /// to the cleanup scope id. For rvalues not present in this
230 /// table, the appropriate cleanup scope is the innermost
231 /// enclosing statement, conditional expression, or repeating
232 /// block (see `terminating_scopes`).
233 /// In constants, None is used to indicate that certain expressions
234 /// escape into 'static and should have no local cleanup scope.
235 rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
237 /// Encodes the hierarchy of fn bodies. Every fn body (including
238 /// closures) forms its own distinct region hierarchy, rooted in
239 /// the block that is the fn body. This map points from the id of
240 /// that root block to the id of the root block for the enclosing
241 /// fn, if any. Thus the map structures the fn bodies into a
242 /// hierarchy based on their lexical mapping. This is used to
243 /// handle the relationships between regions in a fn and in a
244 /// closure defined by that fn. See the "Modeling closures"
245 /// section of the README in infer::region_inference for
247 closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
249 /// If there are any `yield` nested within a scope, this map
250 /// stores the `Span` of the first one.
251 yield_in_scope: FxHashMap<Scope, Span>,
254 #[derive(Debug, Copy, Clone)]
256 /// the root of the current region tree. This is typically the id
257 /// of the innermost fn body. Each fn forms its own disjoint tree
258 /// in the region hierarchy. These fn bodies are themselves
259 /// arranged into a tree. See the "Modeling closures" section of
260 /// the README in infer::region_inference for more
262 root_id: Option<hir::ItemLocalId>,
264 /// the scope that contains any new variables declared
265 var_parent: Option<Scope>,
267 /// region parent of expressions etc
268 parent: Option<Scope>,
271 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
272 tcx: TyCtxt<'a, 'tcx, 'tcx>,
274 // Generated scope tree:
275 scope_tree: ScopeTree,
279 /// `terminating_scopes` is a set containing the ids of each
280 /// statement, or conditional/repeating expression. These scopes
281 /// are calling "terminating scopes" because, when attempting to
282 /// find the scope of a temporary, by default we search up the
283 /// enclosing scopes until we encounter the terminating scope. A
284 /// conditional/repeating expression is one which is not
285 /// guaranteed to execute exactly once upon entering the parent
286 /// scope. This could be because the expression only executes
287 /// conditionally, such as the expression `b` in `a && b`, or
288 /// because the expression may execute many times, such as a loop
289 /// body. The reason that we distinguish such expressions is that,
290 /// upon exiting the parent scope, we cannot statically know how
291 /// many times the expression executed, and thus if the expression
292 /// creates temporaries we cannot know statically how many such
293 /// temporaries we would have to cleanup. Therefore we ensure that
294 /// the temporaries never outlast the conditional/repeating
295 /// expression, preventing the need for dynamic checks and/or
296 /// arbitrary amounts of stack space. Terminating scopes end
297 /// up being contained in a DestructionScope that contains the
298 /// destructor's execution.
299 terminating_scopes: FxHashSet<hir::ItemLocalId>,
303 impl<'tcx> ScopeTree {
304 pub fn record_scope_parent(&mut self, child: Scope, parent: Option<Scope>) {
305 debug!("{:?}.parent = {:?}", child, parent);
307 if let Some(p) = parent {
308 let prev = self.parent_map.insert(child, p);
309 assert!(prev.is_none());
312 // record the destruction scopes for later so we can query them
313 if let Scope::Destruction(n) = child {
314 self.destruction_scopes.insert(n, child);
318 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) {
319 for (&child, &parent) in &self.parent_map {
324 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) {
325 for (child, &parent) in self.var_map.iter() {
330 pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
331 self.destruction_scopes.get(&n).cloned()
334 /// Records that `sub_closure` is defined within `sup_closure`. These ids
335 /// should be the id of the block that is the fn body, which is
336 /// also the root of the region hierarchy for that fn.
337 fn record_closure_parent(&mut self,
338 sub_closure: hir::ItemLocalId,
339 sup_closure: hir::ItemLocalId) {
340 debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
341 sub_closure, sup_closure);
342 assert!(sub_closure != sup_closure);
343 let previous = self.closure_tree.insert(sub_closure, sup_closure);
344 assert!(previous.is_none());
347 fn closure_is_enclosed_by(&self,
348 mut sub_closure: hir::ItemLocalId,
349 sup_closure: hir::ItemLocalId) -> bool {
351 if sub_closure == sup_closure { return true; }
352 match self.closure_tree.get(&sub_closure) {
353 Some(&s) => { sub_closure = s; }
354 None => { return false; }
359 fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
360 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
361 assert!(var != lifetime.item_local_id());
362 self.var_map.insert(var, lifetime);
365 fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
366 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
367 if let Some(lifetime) = lifetime {
368 assert!(var != lifetime.item_local_id());
370 self.rvalue_scopes.insert(var, lifetime);
373 pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
374 //! Returns the narrowest scope that encloses `id`, if any.
375 self.parent_map.get(&id).cloned()
378 #[allow(dead_code)] // used in cfg
379 pub fn encl_scope(&self, id: Scope) -> Scope {
380 //! Returns the narrowest scope that encloses `id`, if any.
381 self.opt_encl_scope(id).unwrap()
384 /// Returns the lifetime of the local variable `var_id`
385 pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
386 match self.var_map.get(&var_id) {
388 None => { bug!("no enclosing scope for id {:?}", var_id); }
392 pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
393 //! Returns the scope when temp created by expr_id will be cleaned up
395 // check for a designated rvalue scope
396 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
397 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
401 // else, locate the innermost terminating scope
402 // if there's one. Static items, for instance, won't
403 // have an enclosing scope, hence no scope will be
405 let mut id = Scope::Node(expr_id);
407 while let Some(&p) = self.parent_map.get(&id) {
409 Scope::Destruction(..) => {
410 debug!("temporary_scope({:?}) = {:?} [enclosing]",
418 debug!("temporary_scope({:?}) = None", expr_id);
422 pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
423 //! Returns the lifetime of the variable `id`.
425 let scope = ty::ReScope(self.var_scope(id));
426 debug!("var_region({:?}) = {:?}", id, scope);
430 pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope)
432 self.is_subscope_of(scope1, scope2) ||
433 self.is_subscope_of(scope2, scope1)
436 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
438 pub fn is_subscope_of(&self,
442 let mut s = subscope;
443 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
444 while superscope != s {
445 match self.opt_encl_scope(s) {
447 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
448 subscope, superscope, s);
451 Some(scope) => s = scope
455 debug!("is_subscope_of({:?}, {:?})=true",
456 subscope, superscope);
461 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
462 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
463 pub fn nearest_common_ancestor(&self,
467 if scope_a == scope_b { return scope_a; }
469 // [1] The initial values for `a_buf` and `b_buf` are not used.
470 // The `ancestors_of` function will return some prefix that
471 // is re-initialized with new values (or else fallback to a
472 // heap-allocated vector).
473 let mut a_buf: [Scope; 32] = [scope_a /* [1] */; 32];
474 let mut a_vec: Vec<Scope> = vec![];
475 let mut b_buf: [Scope; 32] = [scope_b /* [1] */; 32];
476 let mut b_vec: Vec<Scope> = vec![];
477 let parent_map = &self.parent_map;
478 let a_ancestors = ancestors_of(parent_map, scope_a, &mut a_buf, &mut a_vec);
479 let b_ancestors = ancestors_of(parent_map, scope_b, &mut b_buf, &mut b_vec);
480 let mut a_index = a_ancestors.len() - 1;
481 let mut b_index = b_ancestors.len() - 1;
483 // Here, [ab]_ancestors is a vector going from narrow to broad.
484 // The end of each vector will be the item where the scope is
485 // defined; if there are any common ancestors, then the tails of
486 // the vector will be the same. So basically we want to walk
487 // backwards from the tail of each vector and find the first point
488 // where they diverge. If one vector is a suffix of the other,
489 // then the corresponding scope is a superscope of the other.
491 if a_ancestors[a_index] != b_ancestors[b_index] {
492 // In this case, the two regions belong to completely
493 // different functions. Compare those fn for lexical
494 // nesting. The reasoning behind this is subtle. See the
495 // "Modeling closures" section of the README in
496 // infer::region_inference for more details.
497 let a_root_scope = a_ancestors[a_index];
498 let b_root_scope = a_ancestors[a_index];
499 return match (a_root_scope, b_root_scope) {
500 (Scope::Destruction(a_root_id),
501 Scope::Destruction(b_root_id)) => {
502 if self.closure_is_enclosed_by(a_root_id, b_root_id) {
503 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
505 } else if self.closure_is_enclosed_by(b_root_id, a_root_id) {
506 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
509 // neither fn encloses the other
514 // root ids are always Node right now
521 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
522 // for all indices between a_index and the end of the array
523 if a_index == 0 { return scope_a; }
524 if b_index == 0 { return scope_b; }
527 if a_ancestors[a_index] != b_ancestors[b_index] {
528 return a_ancestors[a_index + 1];
532 fn ancestors_of<'a, 'tcx>(parent_map: &FxHashMap<Scope, Scope>,
534 buf: &'a mut [Scope; 32],
535 vec: &'a mut Vec<Scope>)
537 // debug!("ancestors_of(scope={:?})", scope);
538 let mut scope = scope;
543 match parent_map.get(&scope) {
544 Some(&superscope) => scope = superscope,
545 _ => return &buf[..i+1]
550 *vec = Vec::with_capacity(64);
551 vec.extend_from_slice(buf);
554 match parent_map.get(&scope) {
555 Some(&superscope) => scope = superscope,
562 /// Assuming that the provided region was defined within this `ScopeTree`,
563 /// returns the outermost `Scope` that the region outlives.
564 pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
565 br: &ty::EarlyBoundRegion)
567 let param_owner = tcx.parent_def_id(br.def_id).unwrap();
569 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
570 let scope = tcx.hir.maybe_body_owned_by(param_owner_id).map(|body_id| {
571 tcx.hir.body(body_id).value.hir_id.local_id
572 }).unwrap_or_else(|| {
573 // The lifetime was defined on node that doesn't own a body,
574 // which in practice can only mean a trait or an impl, that
575 // is the parent of a method, and that is enforced below.
576 assert_eq!(Some(param_owner_id), self.root_parent,
577 "free_scope: {:?} not recognized by the \
578 region scope tree for {:?} / {:?}",
580 self.root_parent.map(|id| tcx.hir.local_def_id(id)),
581 self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
583 // The trait/impl lifetime is in scope for the method's body.
584 self.root_body.unwrap().local_id
587 Scope::CallSite(scope)
590 /// Assuming that the provided region was defined within this `ScopeTree`,
591 /// returns the outermost `Scope` that the region outlives.
592 pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
594 let param_owner = match fr.bound_region {
595 ty::BoundRegion::BrNamed(def_id, _) => {
596 tcx.parent_def_id(def_id).unwrap()
601 // Ensure that the named late-bound lifetimes were defined
602 // on the same function that they ended up being freed in.
603 assert_eq!(param_owner, fr.scope);
605 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
606 let body_id = tcx.hir.body_owned_by(param_owner_id);
607 Scope::CallSite(tcx.hir.body(body_id).value.hir_id.local_id)
610 /// Checks whether the given scope contains a `yield`. If so,
611 /// returns `Some(span)` with the span of a yield we found.
612 pub fn yield_in_scope(&self, scope: Scope) -> Option<Span> {
613 self.yield_in_scope.get(&scope).cloned()
617 /// Records the lifetime of a local variable as `cx.var_parent`
618 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
619 var_id: hir::ItemLocalId,
621 match visitor.cx.var_parent {
623 // this can happen in extern fn declarations like
625 // extern fn isalnum(c: c_int) -> c_int
627 Some(parent_scope) =>
628 visitor.scope_tree.record_var_scope(var_id, parent_scope),
632 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
633 debug!("resolve_block(blk.id={:?})", blk.id);
635 let prev_cx = visitor.cx;
637 // We treat the tail expression in the block (if any) somewhat
638 // differently from the statements. The issue has to do with
639 // temporary lifetimes. Consider the following:
642 // let inner = ... (&bar()) ...;
644 // (... (&foo()) ...) // (the tail expression)
645 // }, other_argument());
647 // Each of the statements within the block is a terminating
648 // scope, and thus a temporary (e.g. the result of calling
649 // `bar()` in the initalizer expression for `let inner = ...;`)
650 // will be cleaned up immediately after its corresponding
651 // statement (i.e. `let inner = ...;`) executes.
653 // On the other hand, temporaries associated with evaluating the
654 // tail expression for the block are assigned lifetimes so that
655 // they will be cleaned up as part of the terminating scope
656 // *surrounding* the block expression. Here, the terminating
657 // scope for the block expression is the `quux(..)` call; so
658 // those temporaries will only be cleaned up *after* both
659 // `other_argument()` has run and also the call to `quux(..)`
660 // itself has returned.
662 visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
663 visitor.cx.var_parent = visitor.cx.parent;
666 // This block should be kept approximately in sync with
667 // `intravisit::walk_block`. (We manually walk the block, rather
668 // than call `walk_block`, in order to maintain precise
669 // index information.)
671 for (i, statement) in blk.stmts.iter().enumerate() {
672 if let hir::StmtDecl(..) = statement.node {
673 // Each StmtDecl introduces a subscope for bindings
674 // introduced by the declaration; this subscope covers
675 // a suffix of the block . Each subscope in a block
676 // has the previous subscope in the block as a parent,
677 // except for the first such subscope, which has the
678 // block itself as a parent.
680 Scope::Remainder(BlockRemainder {
681 block: blk.hir_id.local_id,
682 first_statement_index: i as u32
685 visitor.cx.var_parent = visitor.cx.parent;
687 visitor.visit_stmt(statement)
689 walk_list!(visitor, visit_expr, &blk.expr);
692 visitor.cx = prev_cx;
695 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
696 visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
698 if let Some(ref expr) = arm.guard {
699 visitor.terminating_scopes.insert(expr.hir_id.local_id);
702 intravisit::walk_arm(visitor, arm);
705 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
706 visitor.record_child_scope(Scope::Node(pat.hir_id.local_id));
708 // If this is a binding then record the lifetime of that binding.
709 if let PatKind::Binding(..) = pat.node {
710 record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
713 intravisit::walk_pat(visitor, pat);
716 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
717 let stmt_id = visitor.tcx.hir.node_to_hir_id(stmt.node.id()).local_id;
718 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
720 // Every statement will clean up the temporaries created during
721 // execution of that statement. Therefore each statement has an
722 // associated destruction scope that represents the scope of the
723 // statement plus its destructors, and thus the scope for which
724 // regions referenced by the destructors need to survive.
725 visitor.terminating_scopes.insert(stmt_id);
727 let prev_parent = visitor.cx.parent;
728 visitor.enter_node_scope_with_dtor(stmt_id);
730 intravisit::walk_stmt(visitor, stmt);
732 visitor.cx.parent = prev_parent;
735 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
736 debug!("resolve_expr(expr.id={:?})", expr.id);
738 let prev_cx = visitor.cx;
739 visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
742 let terminating_scopes = &mut visitor.terminating_scopes;
743 let mut terminating = |id: hir::ItemLocalId| {
744 terminating_scopes.insert(id);
747 // Conditional or repeating scopes are always terminating
748 // scopes, meaning that temporaries cannot outlive them.
749 // This ensures fixed size stacks.
751 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
752 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
753 // For shortcircuiting operators, mark the RHS as a terminating
754 // scope since it only executes conditionally.
755 terminating(r.hir_id.local_id);
758 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
759 terminating(expr.hir_id.local_id);
760 terminating(then.hir_id.local_id);
761 terminating(otherwise.hir_id.local_id);
764 hir::ExprIf(ref expr, ref then, None) => {
765 terminating(expr.hir_id.local_id);
766 terminating(then.hir_id.local_id);
769 hir::ExprLoop(ref body, _, _) => {
770 terminating(body.hir_id.local_id);
773 hir::ExprWhile(ref expr, ref body, _) => {
774 terminating(expr.hir_id.local_id);
775 terminating(body.hir_id.local_id);
778 hir::ExprMatch(..) => {
779 visitor.cx.var_parent = visitor.cx.parent;
782 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
783 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
784 // FIXME(#6268) Nested method calls
786 // The lifetimes for a call or method call look as follows:
794 // The idea is that call.callee_id represents *the time when
795 // the invoked function is actually running* and call.id
796 // represents *the time to prepare the arguments and make the
797 // call*. See the section "Borrows in Calls" borrowck/README.md
798 // for an extended explanation of why this distinction is
801 // record_superlifetime(new_cx, expr.callee_id);
804 hir::ExprYield(..) => {
805 // Mark this expr's scope and all parent scopes as containing `yield`.
806 let mut scope = Scope::Node(expr.hir_id.local_id);
808 match visitor.scope_tree.yield_in_scope.entry(scope) {
809 // Another `yield` has already been found.
810 Entry::Occupied(_) => break,
812 Entry::Vacant(entry) => {
813 entry.insert(expr.span);
817 // Keep traversing up while we can.
818 match visitor.scope_tree.parent_map.get(&scope) {
819 // Don't cross from closure bodies to their parent.
820 Some(&Scope::CallSite(_)) => break,
821 Some(&superscope) => scope = superscope,
832 // Manually recurse over closures, because they are the only
833 // case of nested bodies that share the parent environment.
834 hir::ExprClosure(.., body, _, _) => {
835 let body = visitor.tcx.hir.body(body);
836 visitor.visit_body(body);
839 _ => intravisit::walk_expr(visitor, expr)
842 visitor.cx = prev_cx;
845 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
846 pat: Option<&'tcx hir::Pat>,
847 init: Option<&'tcx hir::Expr>) {
848 debug!("resolve_local(pat={:?}, init={:?})", pat, init);
850 let blk_scope = visitor.cx.var_parent;
852 // As an exception to the normal rules governing temporary
853 // lifetimes, initializers in a let have a temporary lifetime
854 // of the enclosing block. This means that e.g. a program
855 // like the following is legal:
857 // let ref x = HashMap::new();
859 // Because the hash map will be freed in the enclosing block.
861 // We express the rules more formally based on 3 grammars (defined
862 // fully in the helpers below that implement them):
864 // 1. `E&`, which matches expressions like `&<rvalue>` that
865 // own a pointer into the stack.
867 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
868 // y)` that produce ref bindings into the value they are
869 // matched against or something (at least partially) owned by
870 // the value they are matched against. (By partially owned,
871 // I mean that creating a binding into a ref-counted or managed value
872 // would still count.)
874 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
875 // based on rvalues like `foo().x[2].y`.
877 // A subexpression `<rvalue>` that appears in a let initializer
878 // `let pat [: ty] = expr` has an extended temporary lifetime if
879 // any of the following conditions are met:
881 // A. `pat` matches `P&` and `expr` matches `ET`
882 // (covers cases where `pat` creates ref bindings into an rvalue
883 // produced by `expr`)
884 // B. `ty` is a borrowed pointer and `expr` matches `ET`
885 // (covers cases where coercion creates a borrow)
886 // C. `expr` matches `E&`
887 // (covers cases `expr` borrows an rvalue that is then assigned
888 // to memory (at least partially) owned by the binding)
890 // Here are some examples hopefully giving an intuition where each
891 // rule comes into play and why:
893 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
894 // would have an extended lifetime, but not `foo()`.
896 // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
899 // In some cases, multiple rules may apply (though not to the same
900 // rvalue). For example:
902 // let ref x = [&a(), &b()];
904 // Here, the expression `[...]` has an extended lifetime due to rule
905 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
908 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
910 if let Some(expr) = init {
911 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
913 if let Some(pat) = pat {
914 if is_binding_pat(pat) {
915 record_rvalue_scope(visitor, &expr, blk_scope);
920 if let Some(pat) = pat {
921 visitor.visit_pat(pat);
923 if let Some(expr) = init {
924 visitor.visit_expr(expr);
927 /// True if `pat` match the `P&` nonterminal:
930 /// | StructName { ..., P&, ... }
931 /// | VariantName(..., P&, ...)
932 /// | [ ..., P&, ... ]
933 /// | ( ..., P&, ... )
935 fn is_binding_pat(pat: &hir::Pat) -> bool {
936 // Note that the code below looks for *explicit* refs only, that is, it won't
937 // know about *implicit* refs as introduced in #42640.
939 // This is not a problem. For example, consider
941 // let (ref x, ref y) = (Foo { .. }, Bar { .. });
943 // Due to the explicit refs on the left hand side, the below code would signal
944 // that the temporary value on the right hand side should live until the end of
945 // the enclosing block (as opposed to being dropped after the let is complete).
947 // To create an implicit ref, however, you must have a borrowed value on the RHS
948 // already, as in this example (which won't compile before #42640):
950 // let Foo { x, .. } = &Foo { x: ..., ... };
954 // let Foo { ref x, .. } = Foo { ... };
956 // In the former case (the implicit ref version), the temporary is created by the
957 // & expression, and its lifetime would be extended to the end of the block (due
958 // to a different rule, not the below code).
960 PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
961 PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
963 PatKind::Struct(_, ref field_pats, _) => {
964 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
967 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
968 pats1.iter().any(|p| is_binding_pat(&p)) ||
969 pats2.iter().any(|p| is_binding_pat(&p)) ||
970 pats3.iter().any(|p| is_binding_pat(&p))
973 PatKind::TupleStruct(_, ref subpats, _) |
974 PatKind::Tuple(ref subpats, _) => {
975 subpats.iter().any(|p| is_binding_pat(&p))
978 PatKind::Box(ref subpat) => {
979 is_binding_pat(&subpat)
986 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
989 /// | StructName { ..., f: E&, ... }
990 /// | [ ..., E&, ... ]
991 /// | ( ..., E&, ... )
996 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
997 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
999 blk_id: Option<Scope>)
1002 hir::ExprAddrOf(_, ref subexpr) => {
1003 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1004 record_rvalue_scope(visitor, &subexpr, blk_id);
1006 hir::ExprStruct(_, ref fields, _) => {
1007 for field in fields {
1008 record_rvalue_scope_if_borrow_expr(
1009 visitor, &field.expr, blk_id);
1012 hir::ExprArray(ref subexprs) |
1013 hir::ExprTup(ref subexprs) => {
1014 for subexpr in subexprs {
1015 record_rvalue_scope_if_borrow_expr(
1016 visitor, &subexpr, blk_id);
1019 hir::ExprCast(ref subexpr, _) => {
1020 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1022 hir::ExprBlock(ref block) => {
1023 if let Some(ref subexpr) = block.expr {
1024 record_rvalue_scope_if_borrow_expr(
1025 visitor, &subexpr, blk_id);
1032 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1033 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1034 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1037 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1038 /// `<rvalue>` as `blk_id`:
1046 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1047 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1049 blk_scope: Option<Scope>) {
1050 let mut expr = expr;
1052 // Note: give all the expressions matching `ET` with the
1053 // extended temporary lifetime, not just the innermost rvalue,
1054 // because in trans if we must compile e.g. `*rvalue()`
1055 // into a temporary, we request the temporary scope of the
1056 // outer expression.
1057 visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1060 hir::ExprAddrOf(_, ref subexpr) |
1061 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1062 hir::ExprField(ref subexpr, _) |
1063 hir::ExprTupField(ref subexpr, _) |
1064 hir::ExprIndex(ref subexpr, _) => {
1075 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1076 /// Records the current parent (if any) as the parent of `child_scope`.
1077 fn record_child_scope(&mut self, child_scope: Scope) {
1078 let parent = self.cx.parent;
1079 self.scope_tree.record_scope_parent(child_scope, parent);
1082 /// Records the current parent (if any) as the parent of `child_scope`,
1083 /// and sets `child_scope` as the new current parent.
1084 fn enter_scope(&mut self, child_scope: Scope) {
1085 self.record_child_scope(child_scope);
1086 self.cx.parent = Some(child_scope);
1089 fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1090 // If node was previously marked as a terminating scope during the
1091 // recursive visit of its parent node in the AST, then we need to
1092 // account for the destruction scope representing the scope of
1093 // the destructors that run immediately after it completes.
1094 if self.terminating_scopes.contains(&id) {
1095 self.enter_scope(Scope::Destruction(id));
1097 self.enter_scope(Scope::Node(id));
1101 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1102 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1103 NestedVisitorMap::None
1106 fn visit_block(&mut self, b: &'tcx Block) {
1107 resolve_block(self, b);
1110 fn visit_body(&mut self, body: &'tcx hir::Body) {
1111 let body_id = body.id();
1112 let owner_id = self.tcx.hir.body_owner(body_id);
1114 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1116 self.tcx.sess.codemap().span_to_string(body.value.span),
1120 let outer_cx = self.cx;
1121 let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet());
1122 self.terminating_scopes.insert(body.value.hir_id.local_id);
1124 if let Some(root_id) = self.cx.root_id {
1125 self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1127 self.cx.root_id = Some(body.value.hir_id.local_id);
1129 self.enter_scope(Scope::CallSite(body.value.hir_id.local_id));
1130 self.enter_scope(Scope::Arguments(body.value.hir_id.local_id));
1132 // The arguments and `self` are parented to the fn.
1133 self.cx.var_parent = self.cx.parent.take();
1134 for argument in &body.arguments {
1135 self.visit_pat(&argument.pat);
1138 // The body of the every fn is a root scope.
1139 self.cx.parent = self.cx.var_parent;
1140 if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1141 self.visit_expr(&body.value);
1143 // Only functions have an outer terminating (drop) scope, while
1144 // temporaries in constant initializers may be 'static, but only
1145 // according to rvalue lifetime semantics, using the same
1146 // syntactical rules used for let initializers.
1148 // E.g. in `let x = &f();`, the temporary holding the result from
1149 // the `f()` call lives for the entirety of the surrounding block.
1151 // Similarly, `const X: ... = &f();` would have the result of `f()`
1152 // live for `'static`, implying (if Drop restrictions on constants
1153 // ever get lifted) that the value *could* have a destructor, but
1154 // it'd get leaked instead of the destructor running during the
1155 // evaluation of `X` (if at all allowed by CTFE).
1157 // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1158 // would *not* let the `f()` temporary escape into an outer scope
1159 // (i.e. `'static`), which means that after `g` returns, it drops,
1160 // and all the associated destruction scope rules apply.
1161 self.cx.var_parent = None;
1162 resolve_local(self, None, Some(&body.value));
1165 // Restore context we had at the start.
1167 self.terminating_scopes = outer_ts;
1170 fn visit_arm(&mut self, a: &'tcx Arm) {
1171 resolve_arm(self, a);
1173 fn visit_pat(&mut self, p: &'tcx Pat) {
1174 resolve_pat(self, p);
1176 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1177 resolve_stmt(self, s);
1179 fn visit_expr(&mut self, ex: &'tcx Expr) {
1180 resolve_expr(self, ex);
1182 fn visit_local(&mut self, l: &'tcx Local) {
1183 resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1187 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1190 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1191 if closure_base_def_id != def_id {
1192 return tcx.region_scope_tree(closure_base_def_id);
1195 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1196 let scope_tree = if let Some(body_id) = tcx.hir.maybe_body_owned_by(id) {
1197 let mut visitor = RegionResolutionVisitor {
1199 scope_tree: ScopeTree::default(),
1205 terminating_scopes: FxHashSet(),
1208 let body = tcx.hir.body(body_id);
1209 visitor.scope_tree.root_body = Some(body.value.hir_id);
1211 // If the item is an associated const or a method,
1212 // record its impl/trait parent, as it can also have
1213 // lifetime parameters free in this body.
1214 match tcx.hir.get(id) {
1215 hir::map::NodeImplItem(_) |
1216 hir::map::NodeTraitItem(_) => {
1217 visitor.scope_tree.root_parent = Some(tcx.hir.get_parent(id));
1222 visitor.visit_body(body);
1226 ScopeTree::default()
1232 pub fn provide(providers: &mut Providers) {
1233 *providers = Providers {