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.github.io/rustc-guide/mir/borrowck.html
19 use ich::{StableHashingContext, NodeIdHashingMode};
20 use util::nodemap::{FxHashMap, FxHashSet};
25 use rustc_data_structures::sync::Lrc;
26 use syntax::source_map;
28 use syntax_pos::{Span, DUMMY_SP};
30 use ty::query::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 { 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.
103 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, RustcEncodable, RustcDecodable)]
105 pub id: hir::ItemLocalId,
109 impl fmt::Debug for Scope {
110 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
112 ScopeData::Node => write!(fmt, "Node({:?})", self.id),
113 ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id),
114 ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id),
115 ScopeData::Destruction => write!(fmt, "Destruction({:?})", self.id),
116 ScopeData::Remainder(fsi) => write!(
118 "Remainder {{ block: {:?}, first_statement_index: {}}}",
126 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
130 // Scope of the call-site for a function or closure
131 // (outlives the arguments as well as the body).
134 // Scope of arguments passed to a function or closure
135 // (they outlive its body).
138 // Scope of destructors for temporaries of node-id.
141 // Scope following a `let id = expr;` binding in a block.
142 Remainder(FirstStatementIndex)
145 /// Represents a subscope of `block` for a binding that is introduced
146 /// by `block.stmts[first_statement_index]`. Such subscopes represent
147 /// a suffix of the block. Note that each subscope does not include
148 /// the initializer expression, if any, for the statement indexed by
149 /// `first_statement_index`.
151 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
153 /// * the subscope with `first_statement_index == 0` is scope of both
154 /// `a` and `b`; it does not include EXPR_1, but does include
155 /// everything after that first `let`. (If you want a scope that
156 /// includes EXPR_1 as well, then do not use `Scope::Remainder`,
157 /// but instead another `Scope` that encompasses the whole block,
158 /// e.g., `Scope::Node`.
160 /// * the subscope with `first_statement_index == 1` is scope of `c`,
161 /// and thus does not include EXPR_2, but covers the `...`.
164 pub struct FirstStatementIndex { .. }
167 impl_stable_hash_for!(struct ::middle::region::FirstStatementIndex { private });
169 // compilation error if size of `ScopeData` is not the same as a `u32`
170 static_assert!(ASSERT_SCOPE_DATA: mem::size_of::<ScopeData>() == 4);
173 /// Returns a item-local id associated with this scope.
175 /// N.B., likely to be replaced as API is refined; e.g., pnkfelix
176 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
177 pub fn item_local_id(&self) -> hir::ItemLocalId {
181 pub fn node_id(&self, tcx: TyCtxt<'_, '_, '_>, scope_tree: &ScopeTree) -> ast::NodeId {
182 match scope_tree.root_body {
184 tcx.hir().hir_to_node_id(hir::HirId {
186 local_id: self.item_local_id()
189 None => ast::DUMMY_NODE_ID
193 /// Returns the span of this Scope. Note that in general the
194 /// returned span may not correspond to the span of any node id in
196 pub fn span(&self, tcx: TyCtxt<'_, '_, '_>, scope_tree: &ScopeTree) -> Span {
197 let node_id = self.node_id(tcx, scope_tree);
198 if node_id == ast::DUMMY_NODE_ID {
201 let span = tcx.hir().span(node_id);
202 if let ScopeData::Remainder(first_statement_index) = self.data {
203 if let Node::Block(ref blk) = tcx.hir().get(node_id) {
204 // Want span for scope starting after the
205 // indexed statement and ending at end of
206 // `blk`; reuse span of `blk` and shift `lo`
207 // forward to end of indexed statement.
209 // (This is the special case aluded to in the
210 // doc-comment for this method)
212 let stmt_span = blk.stmts[first_statement_index.index()].span;
214 // To avoid issues with macro-generated spans, the span
215 // of the statement must be nested in that of the block.
216 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
217 return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
225 pub type ScopeDepth = u32;
227 /// The region scope tree encodes information about region relationships.
228 #[derive(Default, Debug)]
229 pub struct ScopeTree {
230 /// If not empty, this body is the root of this region hierarchy.
231 root_body: Option<hir::HirId>,
233 /// The parent of the root body owner, if the latter is an
234 /// an associated const or method, as impls/traits can also
235 /// have lifetime parameters free in this body.
236 root_parent: Option<ast::NodeId>,
238 /// `parent_map` maps from a scope id to the enclosing scope id;
239 /// this is usually corresponding to the lexical nesting, though
240 /// in the case of closures the parent scope is the innermost
241 /// conditional expression or repeating block. (Note that the
242 /// enclosing scope id for the block associated with a closure is
243 /// the closure itself.)
244 parent_map: FxHashMap<Scope, (Scope, ScopeDepth)>,
246 /// `var_map` maps from a variable or binding id to the block in
247 /// which that variable is declared.
248 var_map: FxHashMap<hir::ItemLocalId, Scope>,
250 /// maps from a node-id to the associated destruction scope (if any)
251 destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
253 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
254 /// larger than the default. The map goes from the expression id
255 /// to the cleanup scope id. For rvalues not present in this
256 /// table, the appropriate cleanup scope is the innermost
257 /// enclosing statement, conditional expression, or repeating
258 /// block (see `terminating_scopes`).
259 /// In constants, None is used to indicate that certain expressions
260 /// escape into 'static and should have no local cleanup scope.
261 rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
263 /// Encodes the hierarchy of fn bodies. Every fn body (including
264 /// closures) forms its own distinct region hierarchy, rooted in
265 /// the block that is the fn body. This map points from the id of
266 /// that root block to the id of the root block for the enclosing
267 /// fn, if any. Thus the map structures the fn bodies into a
268 /// hierarchy based on their lexical mapping. This is used to
269 /// handle the relationships between regions in a fn and in a
270 /// closure defined by that fn. See the "Modeling closures"
271 /// section of the README in infer::region_constraints for
273 closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
275 /// If there are any `yield` nested within a scope, this map
276 /// stores the `Span` of the last one and its index in the
277 /// postorder of the Visitor traversal on the HIR.
279 /// HIR Visitor postorder indexes might seem like a peculiar
280 /// thing to care about. but it turns out that HIR bindings
281 /// and the temporary results of HIR expressions are never
282 /// storage-live at the end of HIR nodes with postorder indexes
283 /// lower than theirs, and therefore don't need to be suspended
284 /// at yield-points at these indexes.
286 /// For an example, suppose we have some code such as:
287 /// ```rust,ignore (example)
288 /// foo(f(), yield y, bar(g()))
291 /// With the HIR tree (calls numbered for expository purposes)
293 /// Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
296 /// Obviously, the result of `f()` was created before the yield
297 /// (and therefore needs to be kept valid over the yield) while
298 /// the result of `g()` occurs after the yield (and therefore
299 /// doesn't). If we want to infer that, we can look at the
300 /// postorder traversal:
302 /// `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
305 /// In which we can easily see that `Call#1` occurs before the yield,
306 /// and `Call#3` after it.
308 /// To see that this method works, consider:
310 /// Let `D` be our binding/temporary and `U` be our other HIR node, with
311 /// `HIR-postorder(U) < HIR-postorder(D)` (in our example, U would be
312 /// the yield and D would be one of the calls). Let's show that
313 /// `D` is storage-dead at `U`.
315 /// Remember that storage-live/storage-dead refers to the state of
316 /// the *storage*, and does not consider moves/drop flags.
319 /// 1. From the ordering guarantee of HIR visitors (see
320 /// `rustc::hir::intravisit`), `D` does not dominate `U`.
321 /// 2. Therefore, `D` is *potentially* storage-dead at `U` (because
322 /// we might visit `U` without ever getting to `D`).
323 /// 3. However, we guarantee that at each HIR point, each
324 /// binding/temporary is always either always storage-live
325 /// or always storage-dead. This is what is being guaranteed
326 /// by `terminating_scopes` including all blocks where the
327 /// count of executions is not guaranteed.
328 /// 4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
331 /// I don't think this property relies on `3.` in an essential way - it
332 /// is probably still correct even if we have "unrestricted" terminating
333 /// scopes. However, why use the complicated proof when a simple one
336 /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
337 /// might seem that a `box` expression creates a `Box<T>` temporary
338 /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
339 /// be true in the MIR desugaring, but it is not important in the semantics.
341 /// The reason is that semantically, until the `box` expression returns,
342 /// the values are still owned by their containing expressions. So
343 /// we'll see that `&x`.
344 yield_in_scope: FxHashMap<Scope, (Span, usize)>,
346 /// The number of visit_expr and visit_pat calls done in the body.
347 /// Used to sanity check visit_expr/visit_pat call count when
348 /// calculating generator interiors.
349 body_expr_count: FxHashMap<hir::BodyId, usize>,
352 #[derive(Debug, Copy, Clone)]
354 /// the root of the current region tree. This is typically the id
355 /// of the innermost fn body. Each fn forms its own disjoint tree
356 /// in the region hierarchy. These fn bodies are themselves
357 /// arranged into a tree. See the "Modeling closures" section of
358 /// the README in infer::region_constraints for more
360 root_id: Option<hir::ItemLocalId>,
362 /// The scope that contains any new variables declared, plus its depth in
364 var_parent: Option<(Scope, ScopeDepth)>,
366 /// Region parent of expressions, etc., plus its depth in the scope tree.
367 parent: Option<(Scope, ScopeDepth)>,
370 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
371 tcx: TyCtxt<'a, 'tcx, 'tcx>,
373 // The number of expressions and patterns visited in the current body
374 expr_and_pat_count: usize,
376 // Generated scope tree:
377 scope_tree: ScopeTree,
381 /// `terminating_scopes` is a set containing the ids of each
382 /// statement, or conditional/repeating expression. These scopes
383 /// are calling "terminating scopes" because, when attempting to
384 /// find the scope of a temporary, by default we search up the
385 /// enclosing scopes until we encounter the terminating scope. A
386 /// conditional/repeating expression is one which is not
387 /// guaranteed to execute exactly once upon entering the parent
388 /// scope. This could be because the expression only executes
389 /// conditionally, such as the expression `b` in `a && b`, or
390 /// because the expression may execute many times, such as a loop
391 /// body. The reason that we distinguish such expressions is that,
392 /// upon exiting the parent scope, we cannot statically know how
393 /// many times the expression executed, and thus if the expression
394 /// creates temporaries we cannot know statically how many such
395 /// temporaries we would have to cleanup. Therefore we ensure that
396 /// the temporaries never outlast the conditional/repeating
397 /// expression, preventing the need for dynamic checks and/or
398 /// arbitrary amounts of stack space. Terminating scopes end
399 /// up being contained in a DestructionScope that contains the
400 /// destructor's execution.
401 terminating_scopes: FxHashSet<hir::ItemLocalId>,
404 struct ExprLocatorVisitor {
406 result: Option<usize>,
407 expr_and_pat_count: usize,
410 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor
411 // since `expr_count` is compared against the results there.
412 impl<'tcx> Visitor<'tcx> for ExprLocatorVisitor {
413 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
414 NestedVisitorMap::None
417 fn visit_pat(&mut self, pat: &'tcx Pat) {
418 intravisit::walk_pat(self, pat);
420 self.expr_and_pat_count += 1;
422 if pat.hir_id == self.hir_id {
423 self.result = Some(self.expr_and_pat_count);
427 fn visit_expr(&mut self, expr: &'tcx Expr) {
428 debug!("ExprLocatorVisitor - pre-increment {} expr = {:?}",
429 self.expr_and_pat_count,
432 intravisit::walk_expr(self, expr);
434 self.expr_and_pat_count += 1;
436 debug!("ExprLocatorVisitor - post-increment {} expr = {:?}",
437 self.expr_and_pat_count,
440 if expr.hir_id == self.hir_id {
441 self.result = Some(self.expr_and_pat_count);
446 impl<'tcx> ScopeTree {
447 pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) {
448 debug!("{:?}.parent = {:?}", child, parent);
450 if let Some(p) = parent {
451 let prev = self.parent_map.insert(child, p);
452 assert!(prev.is_none());
455 // record the destruction scopes for later so we can query them
456 if let ScopeData::Destruction = child.data {
457 self.destruction_scopes.insert(child.item_local_id(), child);
461 pub fn each_encl_scope<E>(&self, mut e: E) where E: FnMut(Scope, Scope) {
462 for (&child, &parent) in &self.parent_map {
467 pub fn each_var_scope<E>(&self, mut e: E) where E: FnMut(&hir::ItemLocalId, Scope) {
468 for (child, &parent) in self.var_map.iter() {
473 pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
474 self.destruction_scopes.get(&n).cloned()
477 /// Records that `sub_closure` is defined within `sup_closure`. These ids
478 /// should be the id of the block that is the fn body, which is
479 /// also the root of the region hierarchy for that fn.
480 fn record_closure_parent(&mut self,
481 sub_closure: hir::ItemLocalId,
482 sup_closure: hir::ItemLocalId) {
483 debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
484 sub_closure, sup_closure);
485 assert!(sub_closure != sup_closure);
486 let previous = self.closure_tree.insert(sub_closure, sup_closure);
487 assert!(previous.is_none());
490 fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
491 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
492 assert!(var != lifetime.item_local_id());
493 self.var_map.insert(var, lifetime);
496 fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
497 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
498 if let Some(lifetime) = lifetime {
499 assert!(var != lifetime.item_local_id());
501 self.rvalue_scopes.insert(var, lifetime);
504 pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
505 //! Returns the narrowest scope that encloses `id`, if any.
506 self.parent_map.get(&id).cloned().map(|(p, _)| p)
509 #[allow(dead_code)] // used in cfg
510 pub fn encl_scope(&self, id: Scope) -> Scope {
511 //! Returns the narrowest scope that encloses `id`, if any.
512 self.opt_encl_scope(id).unwrap()
515 /// Returns the lifetime of the local variable `var_id`
516 pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
517 self.var_map.get(&var_id).cloned().unwrap_or_else(||
518 bug!("no enclosing scope for id {:?}", var_id))
521 pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
522 //! Returns the scope when temp created by expr_id will be cleaned up
524 // check for a designated rvalue scope
525 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
526 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
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 = Scope { id: expr_id, data: ScopeData::Node };
536 while let Some(&(p, _)) = self.parent_map.get(&id) {
538 ScopeData::Destruction => {
539 debug!("temporary_scope({:?}) = {:?} [enclosing]",
547 debug!("temporary_scope({:?}) = None", expr_id);
551 pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
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: Scope, scope2: Scope) -> bool {
560 self.is_subscope_of(scope1, scope2) ||
561 self.is_subscope_of(scope2, scope1)
564 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
566 pub fn is_subscope_of(&self,
570 let mut s = subscope;
571 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
572 while superscope != s {
573 match self.opt_encl_scope(s) {
575 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
576 subscope, superscope, s);
579 Some(scope) => s = scope
583 debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
588 /// Returns the id of the innermost containing body
589 pub fn containing_body(&self, mut scope: Scope) -> Option<hir::ItemLocalId> {
591 if let ScopeData::CallSite = scope.data {
592 return Some(scope.item_local_id());
595 scope = self.opt_encl_scope(scope)?;
599 /// Finds the nearest common ancestor of two scopes. That is, finds the
600 /// smallest scope which is greater than or equal to both `scope_a` and
602 pub fn nearest_common_ancestor(&self, scope_a: Scope, scope_b: Scope) -> Scope {
603 if scope_a == scope_b { return scope_a; }
608 // Get the depth of each scope's parent. If either scope has no parent,
609 // it must be the root, which means we can stop immediately because the
610 // root must be the nearest common ancestor. (In practice, this is
611 // moderately common.)
612 let (parent_a, parent_a_depth) = match self.parent_map.get(&a) {
616 let (parent_b, parent_b_depth) = match self.parent_map.get(&b) {
621 if parent_a_depth > parent_b_depth {
622 // `a` is lower than `b`. Move `a` up until it's at the same depth
623 // as `b`. The first move up is trivial because we already found
624 // `parent_a` above; the loop does the remaining N-1 moves.
626 for _ in 0..(parent_a_depth - parent_b_depth - 1) {
627 a = self.parent_map.get(&a).unwrap().0;
629 } else if parent_b_depth > parent_a_depth {
630 // `b` is lower than `a`.
632 for _ in 0..(parent_b_depth - parent_a_depth - 1) {
633 b = self.parent_map.get(&b).unwrap().0;
636 // Both scopes are at the same depth, and we know they're not equal
637 // because that case was tested for at the top of this function. So
638 // we can trivially move them both up one level now.
639 assert!(parent_a_depth != 0);
644 // Now both scopes are at the same level. We move upwards in lockstep
645 // until they match. In practice, this loop is almost always executed
646 // zero times because `a` is almost always a direct ancestor of `b` or
649 a = self.parent_map.get(&a).unwrap().0;
650 b = self.parent_map.get(&b).unwrap().0;
656 /// Assuming that the provided region was defined within this `ScopeTree`,
657 /// returns the outermost `Scope` that the region outlives.
658 pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
659 br: &ty::EarlyBoundRegion)
661 let param_owner = tcx.parent_def_id(br.def_id).unwrap();
663 let param_owner_id = tcx.hir().as_local_node_id(param_owner).unwrap();
664 let scope = tcx.hir().maybe_body_owned_by(param_owner_id).map(|body_id| {
665 tcx.hir().body(body_id).value.hir_id.local_id
666 }).unwrap_or_else(|| {
667 // The lifetime was defined on node that doesn't own a body,
668 // which in practice can only mean a trait or an impl, that
669 // is the parent of a method, and that is enforced below.
670 assert_eq!(Some(param_owner_id), self.root_parent,
671 "free_scope: {:?} not recognized by the \
672 region scope tree for {:?} / {:?}",
674 self.root_parent.map(|id| tcx.hir().local_def_id(id)),
675 self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
677 // The trait/impl lifetime is in scope for the method's body.
678 self.root_body.unwrap().local_id
681 Scope { id: scope, data: ScopeData::CallSite }
684 /// Assuming that the provided region was defined within this `ScopeTree`,
685 /// returns the outermost `Scope` that the region outlives.
686 pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
688 let param_owner = match fr.bound_region {
689 ty::BoundRegion::BrNamed(def_id, _) => {
690 tcx.parent_def_id(def_id).unwrap()
695 // Ensure that the named late-bound lifetimes were defined
696 // on the same function that they ended up being freed in.
697 assert_eq!(param_owner, fr.scope);
699 let param_owner_id = tcx.hir().as_local_node_id(param_owner).unwrap();
700 let body_id = tcx.hir().body_owned_by(param_owner_id);
701 Scope { id: tcx.hir().body(body_id).value.hir_id.local_id, data: ScopeData::CallSite }
704 /// Checks whether the given scope contains a `yield`. If so,
705 /// returns `Some((span, expr_count))` with the span of a yield we found and
706 /// the number of expressions and patterns appearing before the `yield` in the body + 1.
707 /// If there a are multiple yields in a scope, the one with the highest number is returned.
708 pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
709 self.yield_in_scope.get(&scope).cloned()
712 /// Checks whether the given scope contains a `yield` and if that yield could execute
713 /// after `expr`. If so, it returns the span of that `yield`.
714 /// `scope` must be inside the body.
715 pub fn yield_in_scope_for_expr(&self,
717 expr_hir_id: hir::HirId,
718 body: &'tcx hir::Body) -> Option<Span> {
719 self.yield_in_scope(scope).and_then(|(span, count)| {
720 let mut visitor = ExprLocatorVisitor {
723 expr_and_pat_count: 0,
725 visitor.visit_body(body);
726 if count >= visitor.result.unwrap() {
734 /// Gives the number of expressions visited in a body.
735 /// Used to sanity check visit_expr call count when
736 /// calculating generator interiors.
737 pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
738 self.body_expr_count.get(&body_id).map(|r| *r)
742 /// Records the lifetime of a local variable as `cx.var_parent`
743 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor<'_, '_>,
744 var_id: hir::ItemLocalId,
746 match visitor.cx.var_parent {
748 // this can happen in extern fn declarations like
750 // extern fn isalnum(c: c_int) -> c_int
752 Some((parent_scope, _)) =>
753 visitor.scope_tree.record_var_scope(var_id, parent_scope),
757 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
758 debug!("resolve_block(blk.id={:?})", blk.id);
760 let prev_cx = visitor.cx;
762 // We treat the tail expression in the block (if any) somewhat
763 // differently from the statements. The issue has to do with
764 // temporary lifetimes. Consider the following:
767 // let inner = ... (&bar()) ...;
769 // (... (&foo()) ...) // (the tail expression)
770 // }, other_argument());
772 // Each of the statements within the block is a terminating
773 // scope, and thus a temporary (e.g., the result of calling
774 // `bar()` in the initializer expression for `let inner = ...;`)
775 // will be cleaned up immediately after its corresponding
776 // statement (i.e., `let inner = ...;`) executes.
778 // On the other hand, temporaries associated with evaluating the
779 // tail expression for the block are assigned lifetimes so that
780 // they will be cleaned up as part of the terminating scope
781 // *surrounding* the block expression. Here, the terminating
782 // scope for the block expression is the `quux(..)` call; so
783 // those temporaries will only be cleaned up *after* both
784 // `other_argument()` has run and also the call to `quux(..)`
785 // itself has returned.
787 visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
788 visitor.cx.var_parent = visitor.cx.parent;
791 // This block should be kept approximately in sync with
792 // `intravisit::walk_block`. (We manually walk the block, rather
793 // than call `walk_block`, in order to maintain precise
794 // index information.)
796 for (i, statement) in blk.stmts.iter().enumerate() {
797 if let hir::StmtKind::Decl(..) = statement.node {
798 // Each StmtKind::Decl introduces a subscope for bindings
799 // introduced by the declaration; this subscope covers
800 // a suffix of the block . Each subscope in a block
801 // has the previous subscope in the block as a parent,
802 // except for the first such subscope, which has the
803 // block itself as a parent.
806 id: blk.hir_id.local_id,
807 data: ScopeData::Remainder(FirstStatementIndex::new(i))
810 visitor.cx.var_parent = visitor.cx.parent;
812 visitor.visit_stmt(statement)
814 walk_list!(visitor, visit_expr, &blk.expr);
817 visitor.cx = prev_cx;
820 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
821 visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
823 if let Some(hir::Guard::If(ref expr)) = arm.guard {
824 visitor.terminating_scopes.insert(expr.hir_id.local_id);
827 intravisit::walk_arm(visitor, arm);
830 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
831 visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node });
833 // If this is a binding then record the lifetime of that binding.
834 if let PatKind::Binding(..) = pat.node {
835 record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
838 debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
840 intravisit::walk_pat(visitor, pat);
842 visitor.expr_and_pat_count += 1;
844 debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
847 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
848 let stmt_id = visitor.tcx.hir().node_to_hir_id(stmt.node.id()).local_id;
849 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
851 // Every statement will clean up the temporaries created during
852 // execution of that statement. Therefore each statement has an
853 // associated destruction scope that represents the scope of the
854 // statement plus its destructors, and thus the scope for which
855 // regions referenced by the destructors need to survive.
856 visitor.terminating_scopes.insert(stmt_id);
858 let prev_parent = visitor.cx.parent;
859 visitor.enter_node_scope_with_dtor(stmt_id);
861 intravisit::walk_stmt(visitor, stmt);
863 visitor.cx.parent = prev_parent;
866 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
867 debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr);
869 let prev_cx = visitor.cx;
870 visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
873 let terminating_scopes = &mut visitor.terminating_scopes;
874 let mut terminating = |id: hir::ItemLocalId| {
875 terminating_scopes.insert(id);
878 // Conditional or repeating scopes are always terminating
879 // scopes, meaning that temporaries cannot outlive them.
880 // This ensures fixed size stacks.
882 hir::ExprKind::Binary(
883 source_map::Spanned { node: hir::BinOpKind::And, .. }, _, ref r) |
884 hir::ExprKind::Binary(
885 source_map::Spanned { node: hir::BinOpKind::Or, .. }, _, ref r) => {
886 // For shortcircuiting operators, mark the RHS as a terminating
887 // scope since it only executes conditionally.
888 terminating(r.hir_id.local_id);
891 hir::ExprKind::If(ref expr, ref then, Some(ref otherwise)) => {
892 terminating(expr.hir_id.local_id);
893 terminating(then.hir_id.local_id);
894 terminating(otherwise.hir_id.local_id);
897 hir::ExprKind::If(ref expr, ref then, None) => {
898 terminating(expr.hir_id.local_id);
899 terminating(then.hir_id.local_id);
902 hir::ExprKind::Loop(ref body, _, _) => {
903 terminating(body.hir_id.local_id);
906 hir::ExprKind::While(ref expr, ref body, _) => {
907 terminating(expr.hir_id.local_id);
908 terminating(body.hir_id.local_id);
911 hir::ExprKind::Match(..) => {
912 visitor.cx.var_parent = visitor.cx.parent;
915 hir::ExprKind::AssignOp(..) | hir::ExprKind::Index(..) |
916 hir::ExprKind::Unary(..) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) => {
917 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
919 // The lifetimes for a call or method call look as follows:
927 // The idea is that call.callee_id represents *the time when
928 // the invoked function is actually running* and call.id
929 // represents *the time to prepare the arguments and make the
930 // call*. See the section "Borrows in Calls" borrowck/README.md
931 // for an extended explanation of why this distinction is
934 // record_superlifetime(new_cx, expr.callee_id);
942 // Manually recurse over closures, because they are the only
943 // case of nested bodies that share the parent environment.
944 hir::ExprKind::Closure(.., body, _, _) => {
945 let body = visitor.tcx.hir().body(body);
946 visitor.visit_body(body);
949 _ => intravisit::walk_expr(visitor, expr)
952 visitor.expr_and_pat_count += 1;
954 debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
956 if let hir::ExprKind::Yield(..) = expr.node {
957 // Mark this expr's scope and all parent scopes as containing `yield`.
958 let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node };
960 visitor.scope_tree.yield_in_scope.insert(scope,
961 (expr.span, visitor.expr_and_pat_count));
963 // Keep traversing up while we can.
964 match visitor.scope_tree.parent_map.get(&scope) {
965 // Don't cross from closure bodies to their parent.
966 Some(&(superscope, _)) => match superscope.data {
967 ScopeData::CallSite => break,
968 _ => scope = superscope
975 visitor.cx = prev_cx;
978 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
979 pat: Option<&'tcx hir::Pat>,
980 init: Option<&'tcx hir::Expr>) {
981 debug!("resolve_local(pat={:?}, init={:?})", pat, init);
983 let blk_scope = visitor.cx.var_parent.map(|(p, _)| p);
985 // As an exception to the normal rules governing temporary
986 // lifetimes, initializers in a let have a temporary lifetime
987 // of the enclosing block. This means that e.g., a program
988 // like the following is legal:
990 // let ref x = HashMap::new();
992 // Because the hash map will be freed in the enclosing block.
994 // We express the rules more formally based on 3 grammars (defined
995 // fully in the helpers below that implement them):
997 // 1. `E&`, which matches expressions like `&<rvalue>` that
998 // own a pointer into the stack.
1000 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
1001 // y)` that produce ref bindings into the value they are
1002 // matched against or something (at least partially) owned by
1003 // the value they are matched against. (By partially owned,
1004 // I mean that creating a binding into a ref-counted or managed value
1005 // would still count.)
1007 // 3. `ET`, which matches both rvalues like `foo()` as well as places
1008 // based on rvalues like `foo().x[2].y`.
1010 // A subexpression `<rvalue>` that appears in a let initializer
1011 // `let pat [: ty] = expr` has an extended temporary lifetime if
1012 // any of the following conditions are met:
1014 // A. `pat` matches `P&` and `expr` matches `ET`
1015 // (covers cases where `pat` creates ref bindings into an rvalue
1016 // produced by `expr`)
1017 // B. `ty` is a borrowed pointer and `expr` matches `ET`
1018 // (covers cases where coercion creates a borrow)
1019 // C. `expr` matches `E&`
1020 // (covers cases `expr` borrows an rvalue that is then assigned
1021 // to memory (at least partially) owned by the binding)
1023 // Here are some examples hopefully giving an intuition where each
1024 // rule comes into play and why:
1026 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1027 // would have an extended lifetime, but not `foo()`.
1029 // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1032 // In some cases, multiple rules may apply (though not to the same
1033 // rvalue). For example:
1035 // let ref x = [&a(), &b()];
1037 // Here, the expression `[...]` has an extended lifetime due to rule
1038 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1041 if let Some(expr) = init {
1042 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1044 if let Some(pat) = pat {
1045 if is_binding_pat(pat) {
1046 record_rvalue_scope(visitor, &expr, blk_scope);
1051 // Make sure we visit the initializer first, so expr_and_pat_count remains correct
1052 if let Some(expr) = init {
1053 visitor.visit_expr(expr);
1055 if let Some(pat) = pat {
1056 visitor.visit_pat(pat);
1059 /// True if `pat` match the `P&` nonterminal:
1062 /// | StructName { ..., P&, ... }
1063 /// | VariantName(..., P&, ...)
1064 /// | [ ..., P&, ... ]
1065 /// | ( ..., P&, ... )
1067 fn is_binding_pat(pat: &hir::Pat) -> bool {
1068 // Note that the code below looks for *explicit* refs only, that is, it won't
1069 // know about *implicit* refs as introduced in #42640.
1071 // This is not a problem. For example, consider
1073 // let (ref x, ref y) = (Foo { .. }, Bar { .. });
1075 // Due to the explicit refs on the left hand side, the below code would signal
1076 // that the temporary value on the right hand side should live until the end of
1077 // the enclosing block (as opposed to being dropped after the let is complete).
1079 // To create an implicit ref, however, you must have a borrowed value on the RHS
1080 // already, as in this example (which won't compile before #42640):
1082 // let Foo { x, .. } = &Foo { x: ..., ... };
1086 // let Foo { ref x, .. } = Foo { ... };
1088 // In the former case (the implicit ref version), the temporary is created by the
1089 // & expression, and its lifetime would be extended to the end of the block (due
1090 // to a different rule, not the below code).
1092 PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1093 PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1095 PatKind::Struct(_, ref field_pats, _) => {
1096 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1099 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
1100 pats1.iter().any(|p| is_binding_pat(&p)) ||
1101 pats2.iter().any(|p| is_binding_pat(&p)) ||
1102 pats3.iter().any(|p| is_binding_pat(&p))
1105 PatKind::TupleStruct(_, ref subpats, _) |
1106 PatKind::Tuple(ref subpats, _) => {
1107 subpats.iter().any(|p| is_binding_pat(&p))
1110 PatKind::Box(ref subpat) => {
1111 is_binding_pat(&subpat)
1118 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1121 /// | StructName { ..., f: E&, ... }
1122 /// | [ ..., E&, ... ]
1123 /// | ( ..., E&, ... )
1128 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1129 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1131 blk_id: Option<Scope>)
1134 hir::ExprKind::AddrOf(_, ref subexpr) => {
1135 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1136 record_rvalue_scope(visitor, &subexpr, blk_id);
1138 hir::ExprKind::Struct(_, ref fields, _) => {
1139 for field in fields {
1140 record_rvalue_scope_if_borrow_expr(
1141 visitor, &field.expr, blk_id);
1144 hir::ExprKind::Array(ref subexprs) |
1145 hir::ExprKind::Tup(ref subexprs) => {
1146 for subexpr in subexprs {
1147 record_rvalue_scope_if_borrow_expr(
1148 visitor, &subexpr, blk_id);
1151 hir::ExprKind::Cast(ref subexpr, _) => {
1152 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1154 hir::ExprKind::Block(ref block, _) => {
1155 if let Some(ref subexpr) = block.expr {
1156 record_rvalue_scope_if_borrow_expr(
1157 visitor, &subexpr, blk_id);
1164 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1165 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1166 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1169 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1170 /// `<rvalue>` as `blk_id`:
1178 /// Note: ET is intended to match "rvalues or places based on rvalues".
1179 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1181 blk_scope: Option<Scope>) {
1182 let mut expr = expr;
1184 // Note: give all the expressions matching `ET` with the
1185 // extended temporary lifetime, not just the innermost rvalue,
1186 // because in codegen if we must compile e.g., `*rvalue()`
1187 // into a temporary, we request the temporary scope of the
1188 // outer expression.
1189 visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1192 hir::ExprKind::AddrOf(_, ref subexpr) |
1193 hir::ExprKind::Unary(hir::UnDeref, ref subexpr) |
1194 hir::ExprKind::Field(ref subexpr, _) |
1195 hir::ExprKind::Index(ref subexpr, _) => {
1206 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1207 /// Records the current parent (if any) as the parent of `child_scope`.
1208 /// Returns the depth of `child_scope`.
1209 fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth {
1210 let parent = self.cx.parent;
1211 self.scope_tree.record_scope_parent(child_scope, parent);
1212 // If `child_scope` has no parent, it must be the root node, and so has
1213 // a depth of 1. Otherwise, its depth is one more than its parent's.
1214 parent.map_or(1, |(_p, d)| d + 1)
1217 /// Records the current parent (if any) as the parent of `child_scope`,
1218 /// and sets `child_scope` as the new current parent.
1219 fn enter_scope(&mut self, child_scope: Scope) {
1220 let child_depth = self.record_child_scope(child_scope);
1221 self.cx.parent = Some((child_scope, child_depth));
1224 fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1225 // If node was previously marked as a terminating scope during the
1226 // recursive visit of its parent node in the AST, then we need to
1227 // account for the destruction scope representing the scope of
1228 // the destructors that run immediately after it completes.
1229 if self.terminating_scopes.contains(&id) {
1230 self.enter_scope(Scope { id, data: ScopeData::Destruction });
1232 self.enter_scope(Scope { id, data: ScopeData::Node });
1236 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1237 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1238 NestedVisitorMap::None
1241 fn visit_block(&mut self, b: &'tcx Block) {
1242 resolve_block(self, b);
1245 fn visit_body(&mut self, body: &'tcx hir::Body) {
1246 let body_id = body.id();
1247 let owner_id = self.tcx.hir().body_owner(body_id);
1249 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1251 self.tcx.sess.source_map().span_to_string(body.value.span),
1255 let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
1256 let outer_cx = self.cx;
1257 let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet::default());
1258 self.terminating_scopes.insert(body.value.hir_id.local_id);
1260 if let Some(root_id) = self.cx.root_id {
1261 self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1263 self.cx.root_id = Some(body.value.hir_id.local_id);
1265 self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite });
1266 self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments });
1268 // The arguments and `self` are parented to the fn.
1269 self.cx.var_parent = self.cx.parent.take();
1270 for argument in &body.arguments {
1271 self.visit_pat(&argument.pat);
1274 // The body of the every fn is a root scope.
1275 self.cx.parent = self.cx.var_parent;
1276 if let hir::BodyOwnerKind::Fn = self.tcx.hir().body_owner_kind(owner_id) {
1277 self.visit_expr(&body.value);
1279 // Only functions have an outer terminating (drop) scope, while
1280 // temporaries in constant initializers may be 'static, but only
1281 // according to rvalue lifetime semantics, using the same
1282 // syntactical rules used for let initializers.
1284 // e.g., in `let x = &f();`, the temporary holding the result from
1285 // the `f()` call lives for the entirety of the surrounding block.
1287 // Similarly, `const X: ... = &f();` would have the result of `f()`
1288 // live for `'static`, implying (if Drop restrictions on constants
1289 // ever get lifted) that the value *could* have a destructor, but
1290 // it'd get leaked instead of the destructor running during the
1291 // evaluation of `X` (if at all allowed by CTFE).
1293 // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1294 // would *not* let the `f()` temporary escape into an outer scope
1295 // (i.e., `'static`), which means that after `g` returns, it drops,
1296 // and all the associated destruction scope rules apply.
1297 self.cx.var_parent = None;
1298 resolve_local(self, None, Some(&body.value));
1301 if body.is_generator {
1302 self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1305 // Restore context we had at the start.
1306 self.expr_and_pat_count = outer_ec;
1308 self.terminating_scopes = outer_ts;
1311 fn visit_arm(&mut self, a: &'tcx Arm) {
1312 resolve_arm(self, a);
1314 fn visit_pat(&mut self, p: &'tcx Pat) {
1315 resolve_pat(self, p);
1317 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1318 resolve_stmt(self, s);
1320 fn visit_expr(&mut self, ex: &'tcx Expr) {
1321 resolve_expr(self, ex);
1323 fn visit_local(&mut self, l: &'tcx Local) {
1324 resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1328 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1331 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1332 if closure_base_def_id != def_id {
1333 return tcx.region_scope_tree(closure_base_def_id);
1336 let id = tcx.hir().as_local_node_id(def_id).unwrap();
1337 let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) {
1338 let mut visitor = RegionResolutionVisitor {
1340 scope_tree: ScopeTree::default(),
1341 expr_and_pat_count: 0,
1347 terminating_scopes: Default::default(),
1350 let body = tcx.hir().body(body_id);
1351 visitor.scope_tree.root_body = Some(body.value.hir_id);
1353 // If the item is an associated const or a method,
1354 // record its impl/trait parent, as it can also have
1355 // lifetime parameters free in this body.
1356 match tcx.hir().get(id) {
1358 Node::TraitItem(_) => {
1359 visitor.scope_tree.root_parent = Some(tcx.hir().get_parent(id));
1364 visitor.visit_body(body);
1368 ScopeTree::default()
1371 Lrc::new(scope_tree)
1374 pub fn provide(providers: &mut Providers<'_>) {
1375 *providers = Providers {
1381 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
1382 fn hash_stable<W: StableHasherResult>(&self,
1383 hcx: &mut StableHashingContext<'a>,
1384 hasher: &mut StableHasher<W>) {
1388 ref body_expr_count,
1391 ref destruction_scopes,
1397 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1398 root_body.hash_stable(hcx, hasher);
1399 root_parent.hash_stable(hcx, hasher);
1402 body_expr_count.hash_stable(hcx, hasher);
1403 parent_map.hash_stable(hcx, hasher);
1404 var_map.hash_stable(hcx, hasher);
1405 destruction_scopes.hash_stable(hcx, hasher);
1406 rvalue_scopes.hash_stable(hcx, hasher);
1407 closure_tree.hash_stable(hcx, hasher);
1408 yield_in_scope.hash_stable(hcx, hasher);