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 //! For more information about how MIR-based region-checking works,
15 //! see the [rustc guide].
17 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir-borrowck.html
19 use ich::{StableHashingContext, NodeIdHashingMode};
20 use util::nodemap::{FxHashMap, FxHashSet};
25 use rustc_data_structures::small_vec::SmallVec;
26 use rustc_data_structures::sync::Lrc;
29 use syntax_pos::{Span, DUMMY_SP};
31 use ty::maps::Providers;
34 use hir::def_id::DefId;
35 use hir::intravisit::{self, Visitor, NestedVisitorMap};
36 use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
37 use rustc_data_structures::indexed_vec::Idx;
38 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
41 /// Scope represents a statically-describable scope that can be
42 /// used to bound the lifetime/region for values.
44 /// `Node(node_id)`: Any AST node that has any scope at all has the
45 /// `Node(node_id)` scope. Other variants represent special cases not
46 /// immediately derivable from the abstract syntax tree structure.
48 /// `DestructionScope(node_id)` represents the scope of destructors
49 /// implicitly-attached to `node_id` that run immediately after the
50 /// expression for `node_id` itself. Not every AST node carries a
51 /// `DestructionScope`, but those that are `terminating_scopes` do;
52 /// see discussion with `ScopeTree`.
54 /// `Remainder(BlockRemainder { block, statement_index })` represents
55 /// the scope of user code running immediately after the initializer
56 /// expression for the indexed statement, until the end of the block.
58 /// So: the following code can be broken down into the scopes beneath:
61 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
65 /// +---------+ (R10.)
67 /// +----------+ (M8.)
68 /// +----------------------+ (R7.)
70 /// +----------+ (M5.)
71 /// +-----------------------------------+ (M4.)
72 /// +--------------------------------------------------+ (M3.)
74 /// +-----------------------------------------------------------+ (M1.)
76 /// (M1.): Node scope of the whole `let a = ...;` statement.
77 /// (M2.): Node scope of the `f()` expression.
78 /// (M3.): Node scope of the `f().g(..)` expression.
79 /// (M4.): Node scope of the block labeled `'b:`.
80 /// (M5.): Node scope of the `let x = d();` statement
81 /// (D6.): DestructionScope for temporaries created during M5.
82 /// (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
83 /// (M8.): Node scope of the `let y = d();` statement.
84 /// (D9.): DestructionScope for temporaries created during M8.
85 /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
86 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
87 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
90 /// Note that while the above picture shows the destruction scopes
91 /// as following their corresponding node scopes, in the internal
92 /// data structures of the compiler the destruction scopes are
93 /// represented as enclosing parents. This is sound because we use the
94 /// enclosing parent relationship just to ensure that referenced
95 /// values live long enough; phrased another way, the starting point
96 /// of each range is not really the important thing in the above
97 /// picture, but rather the ending point.
99 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
100 /// placate the same deriving in `ty::FreeRegion`, but we may want to
101 /// actually attach a more meaningful ordering to scopes than the one
102 /// generated via deriving here.
104 /// Scope is a bit-packed to save space - if `code` is SCOPE_DATA_REMAINDER_MAX
105 /// or less, it is a `ScopeData::Remainder`, otherwise it is a type specified
106 /// by the bitpacking.
107 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, RustcEncodable, RustcDecodable)]
109 pub(crate) id: hir::ItemLocalId,
113 const SCOPE_DATA_NODE: u32 = !0;
114 const SCOPE_DATA_CALLSITE: u32 = !1;
115 const SCOPE_DATA_ARGUMENTS: u32 = !2;
116 const SCOPE_DATA_DESTRUCTION: u32 = !3;
117 const SCOPE_DATA_REMAINDER_MAX: u32 = !4;
119 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
121 Node(hir::ItemLocalId),
123 // Scope of the call-site for a function or closure
124 // (outlives the arguments as well as the body).
125 CallSite(hir::ItemLocalId),
127 // Scope of arguments passed to a function or closure
128 // (they outlive its body).
129 Arguments(hir::ItemLocalId),
131 // Scope of destructors for temporaries of node-id.
132 Destruction(hir::ItemLocalId),
134 // Scope following a `let id = expr;` binding in a block.
135 Remainder(BlockRemainder)
138 /// Represents a subscope of `block` for a binding that is introduced
139 /// by `block.stmts[first_statement_index]`. Such subscopes represent
140 /// a suffix of the block. Note that each subscope does not include
141 /// the initializer expression, if any, for the statement indexed by
142 /// `first_statement_index`.
144 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
146 /// * the subscope with `first_statement_index == 0` is scope of both
147 /// `a` and `b`; it does not include EXPR_1, but does include
148 /// everything after that first `let`. (If you want a scope that
149 /// includes EXPR_1 as well, then do not use `Scope::Remainder`,
150 /// but instead another `Scope` that encompasses the whole block,
151 /// e.g. `Scope::Node`.
153 /// * the subscope with `first_statement_index == 1` is scope of `c`,
154 /// and thus does not include EXPR_2, but covers the `...`.
155 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
156 RustcDecodable, Debug, Copy)]
157 pub struct BlockRemainder {
158 pub block: hir::ItemLocalId,
159 pub first_statement_index: FirstStatementIndex,
162 newtype_index!(FirstStatementIndex
165 MAX = SCOPE_DATA_REMAINDER_MAX
168 impl From<ScopeData> for Scope {
170 fn from(scope_data: ScopeData) -> Self {
171 let (id, code) = match scope_data {
172 ScopeData::Node(id) => (id, SCOPE_DATA_NODE),
173 ScopeData::CallSite(id) => (id, SCOPE_DATA_CALLSITE),
174 ScopeData::Arguments(id) => (id, SCOPE_DATA_ARGUMENTS),
175 ScopeData::Destruction(id) => (id, SCOPE_DATA_DESTRUCTION),
176 ScopeData::Remainder(r) => (r.block, r.first_statement_index.index() as u32)
182 impl fmt::Debug for Scope {
183 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
184 fmt::Debug::fmt(&self.data(), formatter)
188 #[allow(non_snake_case)]
191 pub fn data(self) -> ScopeData {
193 SCOPE_DATA_NODE => ScopeData::Node(self.id),
194 SCOPE_DATA_CALLSITE => ScopeData::CallSite(self.id),
195 SCOPE_DATA_ARGUMENTS => ScopeData::Arguments(self.id),
196 SCOPE_DATA_DESTRUCTION => ScopeData::Destruction(self.id),
197 idx => ScopeData::Remainder(BlockRemainder {
199 first_statement_index: FirstStatementIndex::new(idx as usize)
205 pub fn Node(id: hir::ItemLocalId) -> Self {
206 Self::from(ScopeData::Node(id))
210 pub fn CallSite(id: hir::ItemLocalId) -> Self {
211 Self::from(ScopeData::CallSite(id))
215 pub fn Arguments(id: hir::ItemLocalId) -> Self {
216 Self::from(ScopeData::Arguments(id))
220 pub fn Destruction(id: hir::ItemLocalId) -> Self {
221 Self::from(ScopeData::Destruction(id))
225 pub fn Remainder(r: BlockRemainder) -> Self {
226 Self::from(ScopeData::Remainder(r))
231 /// Returns a item-local id associated with this scope.
233 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
234 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
235 pub fn item_local_id(&self) -> hir::ItemLocalId {
239 pub fn node_id(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> ast::NodeId {
240 match scope_tree.root_body {
242 tcx.hir.hir_to_node_id(hir::HirId {
244 local_id: self.item_local_id()
247 None => ast::DUMMY_NODE_ID
251 /// Returns the span of this Scope. Note that in general the
252 /// returned span may not correspond to the span of any node id in
254 pub fn span(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> Span {
255 let node_id = self.node_id(tcx, scope_tree);
256 if node_id == ast::DUMMY_NODE_ID {
259 let span = tcx.hir.span(node_id);
260 if let ScopeData::Remainder(r) = self.data() {
261 if let hir::map::NodeBlock(ref blk) = tcx.hir.get(node_id) {
262 // Want span for scope starting after the
263 // indexed statement and ending at end of
264 // `blk`; reuse span of `blk` and shift `lo`
265 // forward to end of indexed statement.
267 // (This is the special case aluded to in the
268 // doc-comment for this method)
270 let stmt_span = blk.stmts[r.first_statement_index.index()].span;
272 // To avoid issues with macro-generated spans, the span
273 // of the statement must be nested in that of the block.
274 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
275 return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
283 /// The region scope tree encodes information about region relationships.
284 #[derive(Default, Debug)]
285 pub struct ScopeTree {
286 /// If not empty, this body is the root of this region hierarchy.
287 root_body: Option<hir::HirId>,
289 /// The parent of the root body owner, if the latter is an
290 /// an associated const or method, as impls/traits can also
291 /// have lifetime parameters free in this body.
292 root_parent: Option<ast::NodeId>,
294 /// `parent_map` maps from a scope id to the enclosing scope id;
295 /// this is usually corresponding to the lexical nesting, though
296 /// in the case of closures the parent scope is the innermost
297 /// conditional expression or repeating block. (Note that the
298 /// enclosing scope id for the block associated with a closure is
299 /// the closure itself.)
300 parent_map: FxHashMap<Scope, Scope>,
302 /// `var_map` maps from a variable or binding id to the block in
303 /// which that variable is declared.
304 var_map: FxHashMap<hir::ItemLocalId, Scope>,
306 /// maps from a node-id to the associated destruction scope (if any)
307 destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
309 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
310 /// larger than the default. The map goes from the expression id
311 /// to the cleanup scope id. For rvalues not present in this
312 /// table, the appropriate cleanup scope is the innermost
313 /// enclosing statement, conditional expression, or repeating
314 /// block (see `terminating_scopes`).
315 /// In constants, None is used to indicate that certain expressions
316 /// escape into 'static and should have no local cleanup scope.
317 rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
319 /// Encodes the hierarchy of fn bodies. Every fn body (including
320 /// closures) forms its own distinct region hierarchy, rooted in
321 /// the block that is the fn body. This map points from the id of
322 /// that root block to the id of the root block for the enclosing
323 /// fn, if any. Thus the map structures the fn bodies into a
324 /// hierarchy based on their lexical mapping. This is used to
325 /// handle the relationships between regions in a fn and in a
326 /// closure defined by that fn. See the "Modeling closures"
327 /// section of the README in infer::region_constraints for
329 closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
331 /// If there are any `yield` nested within a scope, this map
332 /// stores the `Span` of the last one and its index in the
333 /// postorder of the Visitor traversal on the HIR.
335 /// HIR Visitor postorder indexes might seem like a peculiar
336 /// thing to care about. but it turns out that HIR bindings
337 /// and the temporary results of HIR expressions are never
338 /// storage-live at the end of HIR nodes with postorder indexes
339 /// lower than theirs, and therefore don't need to be suspended
340 /// at yield-points at these indexes.
342 /// For an example, suppose we have some code such as:
343 /// ```rust,ignore (example)
344 /// foo(f(), yield y, bar(g()))
347 /// With the HIR tree (calls numbered for expository purposes)
349 /// Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
352 /// Obviously, the result of `f()` was created before the yield
353 /// (and therefore needs to be kept valid over the yield) while
354 /// the result of `g()` occurs after the yield (and therefore
355 /// doesn't). If we want to infer that, we can look at the
356 /// postorder traversal:
358 /// `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
361 /// In which we can easily see that `Call#1` occurs before the yield,
362 /// and `Call#3` after it.
364 /// To see that this method works, consider:
366 /// Let `D` be our binding/temporary and `U` be our other HIR node, with
367 /// `HIR-postorder(U) < HIR-postorder(D)` (in our example, U would be
368 /// the yield and D would be one of the calls). Let's show that
369 /// `D` is storage-dead at `U`.
371 /// Remember that storage-live/storage-dead refers to the state of
372 /// the *storage*, and does not consider moves/drop flags.
375 /// 1. From the ordering guarantee of HIR visitors (see
376 /// `rustc::hir::intravisit`), `D` does not dominate `U`.
377 /// 2. Therefore, `D` is *potentially* storage-dead at `U` (because
378 /// we might visit `U` without ever getting to `D`).
379 /// 3. However, we guarantee that at each HIR point, each
380 /// binding/temporary is always either always storage-live
381 /// or always storage-dead. This is what is being guaranteed
382 /// by `terminating_scopes` including all blocks where the
383 /// count of executions is not guaranteed.
384 /// 4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
387 /// I don't think this property relies on `3.` in an essential way - it
388 /// is probably still correct even if we have "unrestricted" terminating
389 /// scopes. However, why use the complicated proof when a simple one
392 /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
393 /// might seem that a `box` expression creates a `Box<T>` temporary
394 /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
395 /// be true in the MIR desugaring, but it is not important in the semantics.
397 /// The reason is that semantically, until the `box` expression returns,
398 /// the values are still owned by their containing expressions. So
399 /// we'll see that `&x`.
400 yield_in_scope: FxHashMap<Scope, (Span, usize)>,
402 /// The number of visit_expr and visit_pat calls done in the body.
403 /// Used to sanity check visit_expr/visit_pat call count when
404 /// calculating generator interiors.
405 body_expr_count: FxHashMap<hir::BodyId, usize>,
408 #[derive(Debug, Copy, Clone)]
410 /// the root of the current region tree. This is typically the id
411 /// of the innermost fn body. Each fn forms its own disjoint tree
412 /// in the region hierarchy. These fn bodies are themselves
413 /// arranged into a tree. See the "Modeling closures" section of
414 /// the README in infer::region_constraints for more
416 root_id: Option<hir::ItemLocalId>,
418 /// the scope that contains any new variables declared
419 var_parent: Option<Scope>,
421 /// region parent of expressions etc
422 parent: Option<Scope>,
425 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
426 tcx: TyCtxt<'a, 'tcx, 'tcx>,
428 // The number of expressions and patterns visited in the current body
429 expr_and_pat_count: usize,
431 // Generated scope tree:
432 scope_tree: ScopeTree,
436 /// `terminating_scopes` is a set containing the ids of each
437 /// statement, or conditional/repeating expression. These scopes
438 /// are calling "terminating scopes" because, when attempting to
439 /// find the scope of a temporary, by default we search up the
440 /// enclosing scopes until we encounter the terminating scope. A
441 /// conditional/repeating expression is one which is not
442 /// guaranteed to execute exactly once upon entering the parent
443 /// scope. This could be because the expression only executes
444 /// conditionally, such as the expression `b` in `a && b`, or
445 /// because the expression may execute many times, such as a loop
446 /// body. The reason that we distinguish such expressions is that,
447 /// upon exiting the parent scope, we cannot statically know how
448 /// many times the expression executed, and thus if the expression
449 /// creates temporaries we cannot know statically how many such
450 /// temporaries we would have to cleanup. Therefore we ensure that
451 /// the temporaries never outlast the conditional/repeating
452 /// expression, preventing the need for dynamic checks and/or
453 /// arbitrary amounts of stack space. Terminating scopes end
454 /// up being contained in a DestructionScope that contains the
455 /// destructor's execution.
456 terminating_scopes: FxHashSet<hir::ItemLocalId>,
459 struct ExprLocatorVisitor {
461 result: Option<usize>,
462 expr_and_pat_count: usize,
465 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor
466 // since `expr_count` is compared against the results there.
467 impl<'tcx> Visitor<'tcx> for ExprLocatorVisitor {
468 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
469 NestedVisitorMap::None
472 fn visit_pat(&mut self, pat: &'tcx Pat) {
473 intravisit::walk_pat(self, pat);
475 self.expr_and_pat_count += 1;
477 if pat.id == self.id {
478 self.result = Some(self.expr_and_pat_count);
482 fn visit_expr(&mut self, expr: &'tcx Expr) {
483 debug!("ExprLocatorVisitor - pre-increment {} expr = {:?}",
484 self.expr_and_pat_count,
487 intravisit::walk_expr(self, expr);
489 self.expr_and_pat_count += 1;
491 debug!("ExprLocatorVisitor - post-increment {} expr = {:?}",
492 self.expr_and_pat_count,
495 if expr.id == self.id {
496 self.result = Some(self.expr_and_pat_count);
501 impl<'tcx> ScopeTree {
502 pub fn record_scope_parent(&mut self, child: Scope, parent: Option<Scope>) {
503 debug!("{:?}.parent = {:?}", child, parent);
505 if let Some(p) = parent {
506 let prev = self.parent_map.insert(child, p);
507 assert!(prev.is_none());
510 // record the destruction scopes for later so we can query them
511 if let ScopeData::Destruction(n) = child.data() {
512 self.destruction_scopes.insert(n, child);
516 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) {
517 for (&child, &parent) in &self.parent_map {
522 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) {
523 for (child, &parent) in self.var_map.iter() {
528 pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
529 self.destruction_scopes.get(&n).cloned()
532 /// Records that `sub_closure` is defined within `sup_closure`. These ids
533 /// should be the id of the block that is the fn body, which is
534 /// also the root of the region hierarchy for that fn.
535 fn record_closure_parent(&mut self,
536 sub_closure: hir::ItemLocalId,
537 sup_closure: hir::ItemLocalId) {
538 debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
539 sub_closure, sup_closure);
540 assert!(sub_closure != sup_closure);
541 let previous = self.closure_tree.insert(sub_closure, sup_closure);
542 assert!(previous.is_none());
545 fn closure_is_enclosed_by(&self,
546 mut sub_closure: hir::ItemLocalId,
547 sup_closure: hir::ItemLocalId) -> bool {
549 if sub_closure == sup_closure { return true; }
550 match self.closure_tree.get(&sub_closure) {
551 Some(&s) => { sub_closure = s; }
552 None => { return false; }
557 fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
558 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
559 assert!(var != lifetime.item_local_id());
560 self.var_map.insert(var, lifetime);
563 fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
564 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
565 if let Some(lifetime) = lifetime {
566 assert!(var != lifetime.item_local_id());
568 self.rvalue_scopes.insert(var, lifetime);
571 pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
572 //! Returns the narrowest scope that encloses `id`, if any.
573 self.parent_map.get(&id).cloned()
576 #[allow(dead_code)] // used in cfg
577 pub fn encl_scope(&self, id: Scope) -> Scope {
578 //! Returns the narrowest scope that encloses `id`, if any.
579 self.opt_encl_scope(id).unwrap()
582 /// Returns the lifetime of the local variable `var_id`
583 pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
584 match self.var_map.get(&var_id) {
586 None => { bug!("no enclosing scope for id {:?}", var_id); }
590 pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
591 //! Returns the scope when temp created by expr_id will be cleaned up
593 // check for a designated rvalue scope
594 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
595 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
599 // else, locate the innermost terminating scope
600 // if there's one. Static items, for instance, won't
601 // have an enclosing scope, hence no scope will be
603 let mut id = Scope::Node(expr_id);
605 while let Some(&p) = self.parent_map.get(&id) {
607 ScopeData::Destruction(..) => {
608 debug!("temporary_scope({:?}) = {:?} [enclosing]",
616 debug!("temporary_scope({:?}) = None", expr_id);
620 pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
621 //! Returns the lifetime of the variable `id`.
623 let scope = ty::ReScope(self.var_scope(id));
624 debug!("var_region({:?}) = {:?}", id, scope);
628 pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope)
630 self.is_subscope_of(scope1, scope2) ||
631 self.is_subscope_of(scope2, scope1)
634 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
636 pub fn is_subscope_of(&self,
640 let mut s = subscope;
641 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
642 while superscope != s {
643 match self.opt_encl_scope(s) {
645 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
646 subscope, superscope, s);
649 Some(scope) => s = scope
653 debug!("is_subscope_of({:?}, {:?})=true",
654 subscope, superscope);
659 /// Returns the id of the innermost containing body
660 pub fn containing_body(&self, mut scope: Scope)-> Option<hir::ItemLocalId> {
662 if let ScopeData::CallSite(id) = scope.data() {
666 match self.opt_encl_scope(scope) {
668 Some(parent) => scope = parent,
673 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
674 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
675 pub fn nearest_common_ancestor(&self,
679 if scope_a == scope_b { return scope_a; }
681 // Process the lists in tandem from the innermost scope, recording the
682 // scopes seen so far. The first scope that comes up for a second time
683 // is the nearest common ancestor.
685 // Note: another way to compute the nearest common ancestor is to get
686 // the full scope chain for both scopes and then compare the chains to
687 // find the first scope in a common tail. But getting a parent scope
688 // requires a hash table lookup, and we often have very long scope
689 // chains (10s or 100s of scopes) that only differ by a few elements at
690 // the start. So this algorithm is faster.
691 let mut ma = Some(scope_a);
692 let mut mb = Some(scope_b);
693 let mut seen_a: SmallVec<[Scope; 32]> = SmallVec::new();
694 let mut seen_b: SmallVec<[Scope; 32]> = SmallVec::new();
696 if let Some(a) = ma {
697 if seen_b.iter().position(|s| *s == a).is_some() {
701 ma = self.parent_map.get(&a).map(|s| *s);
704 if let Some(b) = mb {
705 if seen_a.iter().position(|s| *s == b).is_some() {
709 mb = self.parent_map.get(&b).map(|s| *s);
712 if ma.is_none() && mb.is_none() {
717 fn outermost_scope(parent_map: &FxHashMap<Scope, Scope>, scope: Scope) -> Scope {
718 let mut scope = scope;
720 match parent_map.get(&scope) {
721 Some(&superscope) => scope = superscope,
727 // In this (rare) case, the two regions belong to completely different
728 // functions. Compare those fn for lexical nesting. The reasoning
729 // behind this is subtle. See the "Modeling closures" section of the
730 // README in infer::region_constraints for more details.
731 let a_root_scope = outermost_scope(&self.parent_map, scope_a);
732 let b_root_scope = outermost_scope(&self.parent_map, scope_b);
733 match (a_root_scope.data(), b_root_scope.data()) {
734 (ScopeData::Destruction(a_root_id),
735 ScopeData::Destruction(b_root_id)) => {
736 if self.closure_is_enclosed_by(a_root_id, b_root_id) {
737 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
739 } else if self.closure_is_enclosed_by(b_root_id, a_root_id) {
740 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
743 // neither fn encloses the other
748 // root ids are always Node right now
754 /// Assuming that the provided region was defined within this `ScopeTree`,
755 /// returns the outermost `Scope` that the region outlives.
756 pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
757 br: &ty::EarlyBoundRegion)
759 let param_owner = tcx.parent_def_id(br.def_id).unwrap();
761 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
762 let scope = tcx.hir.maybe_body_owned_by(param_owner_id).map(|body_id| {
763 tcx.hir.body(body_id).value.hir_id.local_id
764 }).unwrap_or_else(|| {
765 // The lifetime was defined on node that doesn't own a body,
766 // which in practice can only mean a trait or an impl, that
767 // is the parent of a method, and that is enforced below.
768 assert_eq!(Some(param_owner_id), self.root_parent,
769 "free_scope: {:?} not recognized by the \
770 region scope tree for {:?} / {:?}",
772 self.root_parent.map(|id| tcx.hir.local_def_id(id)),
773 self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
775 // The trait/impl lifetime is in scope for the method's body.
776 self.root_body.unwrap().local_id
779 Scope::CallSite(scope)
782 /// Assuming that the provided region was defined within this `ScopeTree`,
783 /// returns the outermost `Scope` that the region outlives.
784 pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
786 let param_owner = match fr.bound_region {
787 ty::BoundRegion::BrNamed(def_id, _) => {
788 tcx.parent_def_id(def_id).unwrap()
793 // Ensure that the named late-bound lifetimes were defined
794 // on the same function that they ended up being freed in.
795 assert_eq!(param_owner, fr.scope);
797 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
798 let body_id = tcx.hir.body_owned_by(param_owner_id);
799 Scope::CallSite(tcx.hir.body(body_id).value.hir_id.local_id)
802 /// Checks whether the given scope contains a `yield`. If so,
803 /// returns `Some((span, expr_count))` with the span of a yield we found and
804 /// the number of expressions and patterns appearing before the `yield` in the body + 1.
805 /// If there a are multiple yields in a scope, the one with the highest number is returned.
806 pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
807 self.yield_in_scope.get(&scope).cloned()
810 /// Checks whether the given scope contains a `yield` and if that yield could execute
811 /// after `expr`. If so, it returns the span of that `yield`.
812 /// `scope` must be inside the body.
813 pub fn yield_in_scope_for_expr(&self,
816 body: &'tcx hir::Body) -> Option<Span> {
817 self.yield_in_scope(scope).and_then(|(span, count)| {
818 let mut visitor = ExprLocatorVisitor {
821 expr_and_pat_count: 0,
823 visitor.visit_body(body);
824 if count >= visitor.result.unwrap() {
832 /// Gives the number of expressions visited in a body.
833 /// Used to sanity check visit_expr call count when
834 /// calculating generator interiors.
835 pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
836 self.body_expr_count.get(&body_id).map(|r| *r)
840 /// Records the lifetime of a local variable as `cx.var_parent`
841 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
842 var_id: hir::ItemLocalId,
844 match visitor.cx.var_parent {
846 // this can happen in extern fn declarations like
848 // extern fn isalnum(c: c_int) -> c_int
850 Some(parent_scope) =>
851 visitor.scope_tree.record_var_scope(var_id, parent_scope),
855 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
856 debug!("resolve_block(blk.id={:?})", blk.id);
858 let prev_cx = visitor.cx;
860 // We treat the tail expression in the block (if any) somewhat
861 // differently from the statements. The issue has to do with
862 // temporary lifetimes. Consider the following:
865 // let inner = ... (&bar()) ...;
867 // (... (&foo()) ...) // (the tail expression)
868 // }, other_argument());
870 // Each of the statements within the block is a terminating
871 // scope, and thus a temporary (e.g. the result of calling
872 // `bar()` in the initializer expression for `let inner = ...;`)
873 // will be cleaned up immediately after its corresponding
874 // statement (i.e. `let inner = ...;`) executes.
876 // On the other hand, temporaries associated with evaluating the
877 // tail expression for the block are assigned lifetimes so that
878 // they will be cleaned up as part of the terminating scope
879 // *surrounding* the block expression. Here, the terminating
880 // scope for the block expression is the `quux(..)` call; so
881 // those temporaries will only be cleaned up *after* both
882 // `other_argument()` has run and also the call to `quux(..)`
883 // itself has returned.
885 visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
886 visitor.cx.var_parent = visitor.cx.parent;
889 // This block should be kept approximately in sync with
890 // `intravisit::walk_block`. (We manually walk the block, rather
891 // than call `walk_block`, in order to maintain precise
892 // index information.)
894 for (i, statement) in blk.stmts.iter().enumerate() {
895 if let hir::StmtDecl(..) = statement.node {
896 // Each StmtDecl introduces a subscope for bindings
897 // introduced by the declaration; this subscope covers
898 // a suffix of the block . Each subscope in a block
899 // has the previous subscope in the block as a parent,
900 // except for the first such subscope, which has the
901 // block itself as a parent.
903 Scope::Remainder(BlockRemainder {
904 block: blk.hir_id.local_id,
905 first_statement_index: FirstStatementIndex::new(i)
908 visitor.cx.var_parent = visitor.cx.parent;
910 visitor.visit_stmt(statement)
912 walk_list!(visitor, visit_expr, &blk.expr);
915 visitor.cx = prev_cx;
918 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
919 visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
921 if let Some(ref expr) = arm.guard {
922 visitor.terminating_scopes.insert(expr.hir_id.local_id);
925 intravisit::walk_arm(visitor, arm);
928 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
929 visitor.record_child_scope(Scope::Node(pat.hir_id.local_id));
931 // If this is a binding then record the lifetime of that binding.
932 if let PatKind::Binding(..) = pat.node {
933 record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
936 debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
938 intravisit::walk_pat(visitor, pat);
940 visitor.expr_and_pat_count += 1;
942 debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
945 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
946 let stmt_id = visitor.tcx.hir.node_to_hir_id(stmt.node.id()).local_id;
947 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
949 // Every statement will clean up the temporaries created during
950 // execution of that statement. Therefore each statement has an
951 // associated destruction scope that represents the scope of the
952 // statement plus its destructors, and thus the scope for which
953 // regions referenced by the destructors need to survive.
954 visitor.terminating_scopes.insert(stmt_id);
956 let prev_parent = visitor.cx.parent;
957 visitor.enter_node_scope_with_dtor(stmt_id);
959 intravisit::walk_stmt(visitor, stmt);
961 visitor.cx.parent = prev_parent;
964 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
965 debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr);
967 let prev_cx = visitor.cx;
968 visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
971 let terminating_scopes = &mut visitor.terminating_scopes;
972 let mut terminating = |id: hir::ItemLocalId| {
973 terminating_scopes.insert(id);
976 // Conditional or repeating scopes are always terminating
977 // scopes, meaning that temporaries cannot outlive them.
978 // This ensures fixed size stacks.
980 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
981 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
982 // For shortcircuiting operators, mark the RHS as a terminating
983 // scope since it only executes conditionally.
984 terminating(r.hir_id.local_id);
987 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
988 terminating(expr.hir_id.local_id);
989 terminating(then.hir_id.local_id);
990 terminating(otherwise.hir_id.local_id);
993 hir::ExprIf(ref expr, ref then, None) => {
994 terminating(expr.hir_id.local_id);
995 terminating(then.hir_id.local_id);
998 hir::ExprLoop(ref body, _, _) => {
999 terminating(body.hir_id.local_id);
1002 hir::ExprWhile(ref expr, ref body, _) => {
1003 terminating(expr.hir_id.local_id);
1004 terminating(body.hir_id.local_id);
1007 hir::ExprMatch(..) => {
1008 visitor.cx.var_parent = visitor.cx.parent;
1011 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
1012 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
1013 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
1015 // The lifetimes for a call or method call look as follows:
1023 // The idea is that call.callee_id represents *the time when
1024 // the invoked function is actually running* and call.id
1025 // represents *the time to prepare the arguments and make the
1026 // call*. See the section "Borrows in Calls" borrowck/README.md
1027 // for an extended explanation of why this distinction is
1030 // record_superlifetime(new_cx, expr.callee_id);
1038 // Manually recurse over closures, because they are the only
1039 // case of nested bodies that share the parent environment.
1040 hir::ExprClosure(.., body, _, _) => {
1041 let body = visitor.tcx.hir.body(body);
1042 visitor.visit_body(body);
1045 _ => intravisit::walk_expr(visitor, expr)
1048 visitor.expr_and_pat_count += 1;
1050 debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
1052 if let hir::ExprYield(..) = expr.node {
1053 // Mark this expr's scope and all parent scopes as containing `yield`.
1054 let mut scope = Scope::Node(expr.hir_id.local_id);
1056 visitor.scope_tree.yield_in_scope.insert(scope,
1057 (expr.span, visitor.expr_and_pat_count));
1059 // Keep traversing up while we can.
1060 match visitor.scope_tree.parent_map.get(&scope) {
1061 // Don't cross from closure bodies to their parent.
1062 Some(&superscope) => match superscope.data() {
1063 ScopeData::CallSite(_) => break,
1064 _ => scope = superscope
1071 visitor.cx = prev_cx;
1074 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1075 pat: Option<&'tcx hir::Pat>,
1076 init: Option<&'tcx hir::Expr>) {
1077 debug!("resolve_local(pat={:?}, init={:?})", pat, init);
1079 let blk_scope = visitor.cx.var_parent;
1081 // As an exception to the normal rules governing temporary
1082 // lifetimes, initializers in a let have a temporary lifetime
1083 // of the enclosing block. This means that e.g. a program
1084 // like the following is legal:
1086 // let ref x = HashMap::new();
1088 // Because the hash map will be freed in the enclosing block.
1090 // We express the rules more formally based on 3 grammars (defined
1091 // fully in the helpers below that implement them):
1093 // 1. `E&`, which matches expressions like `&<rvalue>` that
1094 // own a pointer into the stack.
1096 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
1097 // y)` that produce ref bindings into the value they are
1098 // matched against or something (at least partially) owned by
1099 // the value they are matched against. (By partially owned,
1100 // I mean that creating a binding into a ref-counted or managed value
1101 // would still count.)
1103 // 3. `ET`, which matches both rvalues like `foo()` as well as places
1104 // based on rvalues like `foo().x[2].y`.
1106 // A subexpression `<rvalue>` that appears in a let initializer
1107 // `let pat [: ty] = expr` has an extended temporary lifetime if
1108 // any of the following conditions are met:
1110 // A. `pat` matches `P&` and `expr` matches `ET`
1111 // (covers cases where `pat` creates ref bindings into an rvalue
1112 // produced by `expr`)
1113 // B. `ty` is a borrowed pointer and `expr` matches `ET`
1114 // (covers cases where coercion creates a borrow)
1115 // C. `expr` matches `E&`
1116 // (covers cases `expr` borrows an rvalue that is then assigned
1117 // to memory (at least partially) owned by the binding)
1119 // Here are some examples hopefully giving an intuition where each
1120 // rule comes into play and why:
1122 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1123 // would have an extended lifetime, but not `foo()`.
1125 // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1128 // In some cases, multiple rules may apply (though not to the same
1129 // rvalue). For example:
1131 // let ref x = [&a(), &b()];
1133 // Here, the expression `[...]` has an extended lifetime due to rule
1134 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1137 if let Some(expr) = init {
1138 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1140 if let Some(pat) = pat {
1141 if is_binding_pat(pat) {
1142 record_rvalue_scope(visitor, &expr, blk_scope);
1147 // Make sure we visit the initializer first, so expr_and_pat_count remains correct
1148 if let Some(expr) = init {
1149 visitor.visit_expr(expr);
1151 if let Some(pat) = pat {
1152 visitor.visit_pat(pat);
1155 /// True if `pat` match the `P&` nonterminal:
1158 /// | StructName { ..., P&, ... }
1159 /// | VariantName(..., P&, ...)
1160 /// | [ ..., P&, ... ]
1161 /// | ( ..., P&, ... )
1163 fn is_binding_pat(pat: &hir::Pat) -> bool {
1164 // Note that the code below looks for *explicit* refs only, that is, it won't
1165 // know about *implicit* refs as introduced in #42640.
1167 // This is not a problem. For example, consider
1169 // let (ref x, ref y) = (Foo { .. }, Bar { .. });
1171 // Due to the explicit refs on the left hand side, the below code would signal
1172 // that the temporary value on the right hand side should live until the end of
1173 // the enclosing block (as opposed to being dropped after the let is complete).
1175 // To create an implicit ref, however, you must have a borrowed value on the RHS
1176 // already, as in this example (which won't compile before #42640):
1178 // let Foo { x, .. } = &Foo { x: ..., ... };
1182 // let Foo { ref x, .. } = Foo { ... };
1184 // In the former case (the implicit ref version), the temporary is created by the
1185 // & expression, and its lifetime would be extended to the end of the block (due
1186 // to a different rule, not the below code).
1188 PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1189 PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1191 PatKind::Struct(_, ref field_pats, _) => {
1192 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1195 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
1196 pats1.iter().any(|p| is_binding_pat(&p)) ||
1197 pats2.iter().any(|p| is_binding_pat(&p)) ||
1198 pats3.iter().any(|p| is_binding_pat(&p))
1201 PatKind::TupleStruct(_, ref subpats, _) |
1202 PatKind::Tuple(ref subpats, _) => {
1203 subpats.iter().any(|p| is_binding_pat(&p))
1206 PatKind::Box(ref subpat) => {
1207 is_binding_pat(&subpat)
1214 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1217 /// | StructName { ..., f: E&, ... }
1218 /// | [ ..., E&, ... ]
1219 /// | ( ..., E&, ... )
1224 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1225 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1227 blk_id: Option<Scope>)
1230 hir::ExprAddrOf(_, ref subexpr) => {
1231 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1232 record_rvalue_scope(visitor, &subexpr, blk_id);
1234 hir::ExprStruct(_, ref fields, _) => {
1235 for field in fields {
1236 record_rvalue_scope_if_borrow_expr(
1237 visitor, &field.expr, blk_id);
1240 hir::ExprArray(ref subexprs) |
1241 hir::ExprTup(ref subexprs) => {
1242 for subexpr in subexprs {
1243 record_rvalue_scope_if_borrow_expr(
1244 visitor, &subexpr, blk_id);
1247 hir::ExprCast(ref subexpr, _) => {
1248 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1250 hir::ExprBlock(ref block) => {
1251 if let Some(ref subexpr) = block.expr {
1252 record_rvalue_scope_if_borrow_expr(
1253 visitor, &subexpr, blk_id);
1260 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1261 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1262 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1265 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1266 /// `<rvalue>` as `blk_id`:
1274 /// Note: ET is intended to match "rvalues or places based on rvalues".
1275 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1277 blk_scope: Option<Scope>) {
1278 let mut expr = expr;
1280 // Note: give all the expressions matching `ET` with the
1281 // extended temporary lifetime, not just the innermost rvalue,
1282 // because in trans if we must compile e.g. `*rvalue()`
1283 // into a temporary, we request the temporary scope of the
1284 // outer expression.
1285 visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1288 hir::ExprAddrOf(_, ref subexpr) |
1289 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1290 hir::ExprField(ref subexpr, _) |
1291 hir::ExprIndex(ref subexpr, _) => {
1302 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1303 /// Records the current parent (if any) as the parent of `child_scope`.
1304 fn record_child_scope(&mut self, child_scope: Scope) {
1305 let parent = self.cx.parent;
1306 self.scope_tree.record_scope_parent(child_scope, parent);
1309 /// Records the current parent (if any) as the parent of `child_scope`,
1310 /// and sets `child_scope` as the new current parent.
1311 fn enter_scope(&mut self, child_scope: Scope) {
1312 self.record_child_scope(child_scope);
1313 self.cx.parent = Some(child_scope);
1316 fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1317 // If node was previously marked as a terminating scope during the
1318 // recursive visit of its parent node in the AST, then we need to
1319 // account for the destruction scope representing the scope of
1320 // the destructors that run immediately after it completes.
1321 if self.terminating_scopes.contains(&id) {
1322 self.enter_scope(Scope::Destruction(id));
1324 self.enter_scope(Scope::Node(id));
1328 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1329 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1330 NestedVisitorMap::None
1333 fn visit_block(&mut self, b: &'tcx Block) {
1334 resolve_block(self, b);
1337 fn visit_body(&mut self, body: &'tcx hir::Body) {
1338 let body_id = body.id();
1339 let owner_id = self.tcx.hir.body_owner(body_id);
1341 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1343 self.tcx.sess.codemap().span_to_string(body.value.span),
1347 let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
1348 let outer_cx = self.cx;
1349 let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet());
1350 self.terminating_scopes.insert(body.value.hir_id.local_id);
1352 if let Some(root_id) = self.cx.root_id {
1353 self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1355 self.cx.root_id = Some(body.value.hir_id.local_id);
1357 self.enter_scope(Scope::CallSite(body.value.hir_id.local_id));
1358 self.enter_scope(Scope::Arguments(body.value.hir_id.local_id));
1360 // The arguments and `self` are parented to the fn.
1361 self.cx.var_parent = self.cx.parent.take();
1362 for argument in &body.arguments {
1363 self.visit_pat(&argument.pat);
1366 // The body of the every fn is a root scope.
1367 self.cx.parent = self.cx.var_parent;
1368 if let hir::BodyOwnerKind::Fn = self.tcx.hir.body_owner_kind(owner_id) {
1369 self.visit_expr(&body.value);
1371 // Only functions have an outer terminating (drop) scope, while
1372 // temporaries in constant initializers may be 'static, but only
1373 // according to rvalue lifetime semantics, using the same
1374 // syntactical rules used for let initializers.
1376 // E.g. in `let x = &f();`, the temporary holding the result from
1377 // the `f()` call lives for the entirety of the surrounding block.
1379 // Similarly, `const X: ... = &f();` would have the result of `f()`
1380 // live for `'static`, implying (if Drop restrictions on constants
1381 // ever get lifted) that the value *could* have a destructor, but
1382 // it'd get leaked instead of the destructor running during the
1383 // evaluation of `X` (if at all allowed by CTFE).
1385 // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1386 // would *not* let the `f()` temporary escape into an outer scope
1387 // (i.e. `'static`), which means that after `g` returns, it drops,
1388 // and all the associated destruction scope rules apply.
1389 self.cx.var_parent = None;
1390 resolve_local(self, None, Some(&body.value));
1393 if body.is_generator {
1394 self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1397 // Restore context we had at the start.
1398 self.expr_and_pat_count = outer_ec;
1400 self.terminating_scopes = outer_ts;
1403 fn visit_arm(&mut self, a: &'tcx Arm) {
1404 resolve_arm(self, a);
1406 fn visit_pat(&mut self, p: &'tcx Pat) {
1407 resolve_pat(self, p);
1409 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1410 resolve_stmt(self, s);
1412 fn visit_expr(&mut self, ex: &'tcx Expr) {
1413 resolve_expr(self, ex);
1415 fn visit_local(&mut self, l: &'tcx Local) {
1416 resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1420 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1423 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1424 if closure_base_def_id != def_id {
1425 return tcx.region_scope_tree(closure_base_def_id);
1428 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1429 let scope_tree = if let Some(body_id) = tcx.hir.maybe_body_owned_by(id) {
1430 let mut visitor = RegionResolutionVisitor {
1432 scope_tree: ScopeTree::default(),
1433 expr_and_pat_count: 0,
1439 terminating_scopes: FxHashSet(),
1442 let body = tcx.hir.body(body_id);
1443 visitor.scope_tree.root_body = Some(body.value.hir_id);
1445 // If the item is an associated const or a method,
1446 // record its impl/trait parent, as it can also have
1447 // lifetime parameters free in this body.
1448 match tcx.hir.get(id) {
1449 hir::map::NodeImplItem(_) |
1450 hir::map::NodeTraitItem(_) => {
1451 visitor.scope_tree.root_parent = Some(tcx.hir.get_parent(id));
1456 visitor.visit_body(body);
1460 ScopeTree::default()
1463 Lrc::new(scope_tree)
1466 pub fn provide(providers: &mut Providers) {
1467 *providers = Providers {
1473 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
1474 fn hash_stable<W: StableHasherResult>(&self,
1475 hcx: &mut StableHashingContext<'a>,
1476 hasher: &mut StableHasher<W>) {
1480 ref body_expr_count,
1483 ref destruction_scopes,
1489 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1490 root_body.hash_stable(hcx, hasher);
1491 root_parent.hash_stable(hcx, hasher);
1494 body_expr_count.hash_stable(hcx, hasher);
1495 parent_map.hash_stable(hcx, hasher);
1496 var_map.hash_stable(hcx, hasher);
1497 destruction_scopes.hash_stable(hcx, hasher);
1498 rvalue_scopes.hash_stable(hcx, hasher);
1499 closure_tree.hash_stable(hcx, hasher);
1500 yield_in_scope.hash_stable(hcx, hasher);