1 //! This file builds up the `ScopeTree`, which describes
2 //! the parent links in the region hierarchy.
4 //! For more information about how MIR-based region-checking works,
5 //! see the [rustc guide].
7 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/borrowck.html
9 use crate::ich::{StableHashingContext, NodeIdHashingMode};
10 use crate::util::nodemap::{FxHashMap, FxHashSet};
15 use rustc_macros::HashStable;
16 use syntax::source_map;
18 use syntax_pos::{Span, DUMMY_SP};
19 use crate::ty::{DefIdTree, TyCtxt};
20 use crate::ty::query::Providers;
24 use crate::hir::def_id::DefId;
25 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
26 use crate::hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
27 use rustc_data_structures::indexed_vec::Idx;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
31 /// Scope represents a statically-describable scope that can be
32 /// used to bound the lifetime/region for values.
34 /// `Node(node_id)`: Any AST node that has any scope at all has the
35 /// `Node(node_id)` scope. Other variants represent special cases not
36 /// immediately derivable from the abstract syntax tree structure.
38 /// `DestructionScope(node_id)` represents the scope of destructors
39 /// implicitly-attached to `node_id` that run immediately after the
40 /// expression for `node_id` itself. Not every AST node carries a
41 /// `DestructionScope`, but those that are `terminating_scopes` do;
42 /// see discussion with `ScopeTree`.
44 /// `Remainder { block, statement_index }` represents
45 /// the scope of user code running immediately after the initializer
46 /// expression for the indexed statement, until the end of the block.
48 /// So: the following code can be broken down into the scopes beneath:
51 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
55 /// +---------+ (R10.)
57 /// +----------+ (M8.)
58 /// +----------------------+ (R7.)
60 /// +----------+ (M5.)
61 /// +-----------------------------------+ (M4.)
62 /// +--------------------------------------------------+ (M3.)
64 /// +-----------------------------------------------------------+ (M1.)
66 /// (M1.): Node scope of the whole `let a = ...;` statement.
67 /// (M2.): Node scope of the `f()` expression.
68 /// (M3.): Node scope of the `f().g(..)` expression.
69 /// (M4.): Node scope of the block labeled `'b:`.
70 /// (M5.): Node scope of the `let x = d();` statement
71 /// (D6.): DestructionScope for temporaries created during M5.
72 /// (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
73 /// (M8.): Node scope of the `let y = d();` statement.
74 /// (D9.): DestructionScope for temporaries created during M8.
75 /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
76 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
77 /// (D12.): DestructionScope for temporaries created during M1 (e.g., f()).
80 /// Note that while the above picture shows the destruction scopes
81 /// as following their corresponding node scopes, in the internal
82 /// data structures of the compiler the destruction scopes are
83 /// represented as enclosing parents. This is sound because we use the
84 /// enclosing parent relationship just to ensure that referenced
85 /// values live long enough; phrased another way, the starting point
86 /// of each range is not really the important thing in the above
87 /// picture, but rather the ending point.
89 // FIXME(pnkfelix): this currently derives `PartialOrd` and `Ord` to
90 // placate the same deriving in `ty::FreeRegion`, but we may want to
91 // actually attach a more meaningful ordering to scopes than the one
92 // generated via deriving here.
93 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy,
94 RustcEncodable, RustcDecodable, HashStable)]
96 pub id: hir::ItemLocalId,
100 impl fmt::Debug for Scope {
101 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
103 ScopeData::Node => write!(fmt, "Node({:?})", self.id),
104 ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id),
105 ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id),
106 ScopeData::Destruction => write!(fmt, "Destruction({:?})", self.id),
107 ScopeData::Remainder(fsi) => write!(
109 "Remainder {{ block: {:?}, first_statement_index: {}}}",
117 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy,
118 RustcEncodable, RustcDecodable, HashStable)]
122 /// Scope of the call-site for a function or closure
123 /// (outlives the arguments as well as the body).
126 /// Scope of arguments passed to a function or closure
127 /// (they outlive its body).
130 /// Scope of destructors for temporaries of node-id.
133 /// Scope following a `let id = expr;` binding in a block.
134 Remainder(FirstStatementIndex)
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 pub struct FirstStatementIndex {
160 // compilation error if size of `ScopeData` is not the same as a `u32`
161 static_assert_size!(ScopeData, 4);
164 /// Returns a item-local ID associated with this scope.
166 /// N.B., likely to be replaced as API is refined; e.g., pnkfelix
167 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
168 pub fn item_local_id(&self) -> hir::ItemLocalId {
172 pub fn node_id(&self, tcx: TyCtxt<'_, '_, '_>, scope_tree: &ScopeTree) -> ast::NodeId {
173 match scope_tree.root_body {
175 tcx.hir().hir_to_node_id(hir::HirId {
177 local_id: self.item_local_id()
180 None => ast::DUMMY_NODE_ID
184 /// Returns the span of this `Scope`. Note that in general the
185 /// returned span may not correspond to the span of any `NodeId` in
187 pub fn span(&self, tcx: TyCtxt<'_, '_, '_>, scope_tree: &ScopeTree) -> Span {
188 let node_id = self.node_id(tcx, scope_tree);
189 if node_id == ast::DUMMY_NODE_ID {
192 let span = tcx.hir().span(node_id);
193 if let ScopeData::Remainder(first_statement_index) = self.data {
194 if let Node::Block(ref blk) = tcx.hir().get(node_id) {
195 // Want span for scope starting after the
196 // indexed statement and ending at end of
197 // `blk`; reuse span of `blk` and shift `lo`
198 // forward to end of indexed statement.
200 // (This is the special case aluded to in the
201 // doc-comment for this method)
203 let stmt_span = blk.stmts[first_statement_index.index()].span;
205 // To avoid issues with macro-generated spans, the span
206 // of the statement must be nested in that of the block.
207 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
208 return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
216 pub type ScopeDepth = u32;
218 /// The region scope tree encodes information about region relationships.
219 #[derive(Default, Debug)]
220 pub struct ScopeTree {
221 /// If not empty, this body is the root of this region hierarchy.
222 root_body: Option<hir::HirId>,
224 /// The parent of the root body owner, if the latter is an
225 /// an associated const or method, as impls/traits can also
226 /// have lifetime parameters free in this body.
227 root_parent: Option<hir::HirId>,
229 /// `parent_map` maps from a scope ID to the enclosing scope id;
230 /// this is usually corresponding to the lexical nesting, though
231 /// in the case of closures the parent scope is the innermost
232 /// conditional expression or repeating block. (Note that the
233 /// enclosing scope ID for the block associated with a closure is
234 /// the closure itself.)
235 parent_map: FxHashMap<Scope, (Scope, ScopeDepth)>,
237 /// `var_map` maps from a variable or binding ID to the block in
238 /// which that variable is declared.
239 var_map: FxHashMap<hir::ItemLocalId, Scope>,
241 /// maps from a `NodeId` to the associated destruction scope (if any)
242 destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
244 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
245 /// larger than the default. The map goes from the expression id
246 /// to the cleanup scope id. For rvalues not present in this
247 /// table, the appropriate cleanup scope is the innermost
248 /// enclosing statement, conditional expression, or repeating
249 /// block (see `terminating_scopes`).
250 /// In constants, None is used to indicate that certain expressions
251 /// escape into 'static and should have no local cleanup scope.
252 rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
254 /// Encodes the hierarchy of fn bodies. Every fn body (including
255 /// closures) forms its own distinct region hierarchy, rooted in
256 /// the block that is the fn body. This map points from the ID of
257 /// that root block to the ID of the root block for the enclosing
258 /// fn, if any. Thus the map structures the fn bodies into a
259 /// hierarchy based on their lexical mapping. This is used to
260 /// handle the relationships between regions in a fn and in a
261 /// closure defined by that fn. See the "Modeling closures"
262 /// section of the README in infer::region_constraints for
264 closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
266 /// If there are any `yield` nested within a scope, this map
267 /// stores the `Span` of the last one and its index in the
268 /// postorder of the Visitor traversal on the HIR.
270 /// HIR Visitor postorder indexes might seem like a peculiar
271 /// thing to care about. but it turns out that HIR bindings
272 /// and the temporary results of HIR expressions are never
273 /// storage-live at the end of HIR nodes with postorder indexes
274 /// lower than theirs, and therefore don't need to be suspended
275 /// at yield-points at these indexes.
277 /// For an example, suppose we have some code such as:
278 /// ```rust,ignore (example)
279 /// foo(f(), yield y, bar(g()))
282 /// With the HIR tree (calls numbered for expository purposes)
284 /// Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
287 /// Obviously, the result of `f()` was created before the yield
288 /// (and therefore needs to be kept valid over the yield) while
289 /// the result of `g()` occurs after the yield (and therefore
290 /// doesn't). If we want to infer that, we can look at the
291 /// postorder traversal:
293 /// `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
296 /// In which we can easily see that `Call#1` occurs before the yield,
297 /// and `Call#3` after it.
299 /// To see that this method works, consider:
301 /// Let `D` be our binding/temporary and `U` be our other HIR node, with
302 /// `HIR-postorder(U) < HIR-postorder(D)` (in our example, U would be
303 /// the yield and D would be one of the calls). Let's show that
304 /// `D` is storage-dead at `U`.
306 /// Remember that storage-live/storage-dead refers to the state of
307 /// the *storage*, and does not consider moves/drop flags.
310 /// 1. From the ordering guarantee of HIR visitors (see
311 /// `rustc::hir::intravisit`), `D` does not dominate `U`.
312 /// 2. Therefore, `D` is *potentially* storage-dead at `U` (because
313 /// we might visit `U` without ever getting to `D`).
314 /// 3. However, we guarantee that at each HIR point, each
315 /// binding/temporary is always either always storage-live
316 /// or always storage-dead. This is what is being guaranteed
317 /// by `terminating_scopes` including all blocks where the
318 /// count of executions is not guaranteed.
319 /// 4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
322 /// I don't think this property relies on `3.` in an essential way - it
323 /// is probably still correct even if we have "unrestricted" terminating
324 /// scopes. However, why use the complicated proof when a simple one
327 /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
328 /// might seem that a `box` expression creates a `Box<T>` temporary
329 /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
330 /// be true in the MIR desugaring, but it is not important in the semantics.
332 /// The reason is that semantically, until the `box` expression returns,
333 /// the values are still owned by their containing expressions. So
334 /// we'll see that `&x`.
335 yield_in_scope: FxHashMap<Scope, (Span, usize)>,
337 /// The number of visit_expr and visit_pat calls done in the body.
338 /// Used to sanity check visit_expr/visit_pat call count when
339 /// calculating generator interiors.
340 body_expr_count: FxHashMap<hir::BodyId, usize>,
343 #[derive(Debug, Copy, Clone)]
345 /// the root of the current region tree. This is typically the id
346 /// of the innermost fn body. Each fn forms its own disjoint tree
347 /// in the region hierarchy. These fn bodies are themselves
348 /// arranged into a tree. See the "Modeling closures" section of
349 /// the README in infer::region_constraints for more
351 root_id: Option<hir::ItemLocalId>,
353 /// The scope that contains any new variables declared, plus its depth in
355 var_parent: Option<(Scope, ScopeDepth)>,
357 /// Region parent of expressions, etc., plus its depth in the scope tree.
358 parent: Option<(Scope, ScopeDepth)>,
361 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
362 tcx: TyCtxt<'a, 'tcx, 'tcx>,
364 // The number of expressions and patterns visited in the current body
365 expr_and_pat_count: usize,
367 // Generated scope tree:
368 scope_tree: ScopeTree,
372 /// `terminating_scopes` is a set containing the ids of each
373 /// statement, or conditional/repeating expression. These scopes
374 /// are calling "terminating scopes" because, when attempting to
375 /// find the scope of a temporary, by default we search up the
376 /// enclosing scopes until we encounter the terminating scope. A
377 /// conditional/repeating expression is one which is not
378 /// guaranteed to execute exactly once upon entering the parent
379 /// scope. This could be because the expression only executes
380 /// conditionally, such as the expression `b` in `a && b`, or
381 /// because the expression may execute many times, such as a loop
382 /// body. The reason that we distinguish such expressions is that,
383 /// upon exiting the parent scope, we cannot statically know how
384 /// many times the expression executed, and thus if the expression
385 /// creates temporaries we cannot know statically how many such
386 /// temporaries we would have to cleanup. Therefore, we ensure that
387 /// the temporaries never outlast the conditional/repeating
388 /// expression, preventing the need for dynamic checks and/or
389 /// arbitrary amounts of stack space. Terminating scopes end
390 /// up being contained in a DestructionScope that contains the
391 /// destructor's execution.
392 terminating_scopes: FxHashSet<hir::ItemLocalId>,
395 struct ExprLocatorVisitor {
397 result: Option<usize>,
398 expr_and_pat_count: usize,
401 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor
402 // since `expr_count` is compared against the results there.
403 impl<'tcx> Visitor<'tcx> for ExprLocatorVisitor {
404 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
405 NestedVisitorMap::None
408 fn visit_pat(&mut self, pat: &'tcx Pat) {
409 intravisit::walk_pat(self, pat);
411 self.expr_and_pat_count += 1;
413 if pat.hir_id == self.hir_id {
414 self.result = Some(self.expr_and_pat_count);
418 fn visit_expr(&mut self, expr: &'tcx Expr) {
419 debug!("ExprLocatorVisitor - pre-increment {} expr = {:?}",
420 self.expr_and_pat_count,
423 intravisit::walk_expr(self, expr);
425 self.expr_and_pat_count += 1;
427 debug!("ExprLocatorVisitor - post-increment {} expr = {:?}",
428 self.expr_and_pat_count,
431 if expr.hir_id == self.hir_id {
432 self.result = Some(self.expr_and_pat_count);
437 impl<'tcx> ScopeTree {
438 pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) {
439 debug!("{:?}.parent = {:?}", child, parent);
441 if let Some(p) = parent {
442 let prev = self.parent_map.insert(child, p);
443 assert!(prev.is_none());
446 // record the destruction scopes for later so we can query them
447 if let ScopeData::Destruction = child.data {
448 self.destruction_scopes.insert(child.item_local_id(), child);
452 pub fn each_encl_scope<E>(&self, mut e: E) where E: FnMut(Scope, Scope) {
453 for (&child, &parent) in &self.parent_map {
458 pub fn each_var_scope<E>(&self, mut e: E) where E: FnMut(&hir::ItemLocalId, Scope) {
459 for (child, &parent) in self.var_map.iter() {
464 pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
465 self.destruction_scopes.get(&n).cloned()
468 /// Records that `sub_closure` is defined within `sup_closure`. These ids
469 /// should be the ID of the block that is the fn body, which is
470 /// also the root of the region hierarchy for that fn.
471 fn record_closure_parent(&mut self,
472 sub_closure: hir::ItemLocalId,
473 sup_closure: hir::ItemLocalId) {
474 debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
475 sub_closure, sup_closure);
476 assert!(sub_closure != sup_closure);
477 let previous = self.closure_tree.insert(sub_closure, sup_closure);
478 assert!(previous.is_none());
481 fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
482 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
483 assert!(var != lifetime.item_local_id());
484 self.var_map.insert(var, lifetime);
487 fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
488 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
489 if let Some(lifetime) = lifetime {
490 assert!(var != lifetime.item_local_id());
492 self.rvalue_scopes.insert(var, lifetime);
495 pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
496 //! Returns the narrowest scope that encloses `id`, if any.
497 self.parent_map.get(&id).cloned().map(|(p, _)| p)
500 #[allow(dead_code)] // used in cfg
501 pub fn encl_scope(&self, id: Scope) -> Scope {
502 //! Returns the narrowest scope that encloses `id`, if any.
503 self.opt_encl_scope(id).unwrap()
506 /// Returns the lifetime of the local variable `var_id`
507 pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
508 self.var_map.get(&var_id).cloned().unwrap_or_else(||
509 bug!("no enclosing scope for id {:?}", var_id))
512 pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
513 //! Returns the scope when temp created by expr_id will be cleaned up
515 // check for a designated rvalue scope
516 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
517 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
521 // else, locate the innermost terminating scope
522 // if there's one. Static items, for instance, won't
523 // have an enclosing scope, hence no scope will be
525 let mut id = Scope { id: expr_id, data: ScopeData::Node };
527 while let Some(&(p, _)) = self.parent_map.get(&id) {
529 ScopeData::Destruction => {
530 debug!("temporary_scope({:?}) = {:?} [enclosing]",
538 debug!("temporary_scope({:?}) = None", expr_id);
542 pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
543 //! Returns the lifetime of the variable `id`.
545 let scope = ty::ReScope(self.var_scope(id));
546 debug!("var_region({:?}) = {:?}", id, scope);
550 pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope) -> bool {
551 self.is_subscope_of(scope1, scope2) ||
552 self.is_subscope_of(scope2, scope1)
555 /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and
556 /// `false` otherwise.
557 pub fn is_subscope_of(&self,
561 let mut s = subscope;
562 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
563 while superscope != s {
564 match self.opt_encl_scope(s) {
566 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
567 subscope, superscope, s);
570 Some(scope) => s = scope
574 debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
579 /// Returns the ID of the innermost containing body
580 pub fn containing_body(&self, mut scope: Scope) -> Option<hir::ItemLocalId> {
582 if let ScopeData::CallSite = scope.data {
583 return Some(scope.item_local_id());
586 scope = self.opt_encl_scope(scope)?;
590 /// Finds the nearest common ancestor of two scopes. That is, finds the
591 /// smallest scope which is greater than or equal to both `scope_a` and
593 pub fn nearest_common_ancestor(&self, scope_a: Scope, scope_b: Scope) -> Scope {
594 if scope_a == scope_b { return scope_a; }
599 // Get the depth of each scope's parent. If either scope has no parent,
600 // it must be the root, which means we can stop immediately because the
601 // root must be the nearest common ancestor. (In practice, this is
602 // moderately common.)
603 let (parent_a, parent_a_depth) = match self.parent_map.get(&a) {
607 let (parent_b, parent_b_depth) = match self.parent_map.get(&b) {
612 if parent_a_depth > parent_b_depth {
613 // `a` is lower than `b`. Move `a` up until it's at the same depth
614 // as `b`. The first move up is trivial because we already found
615 // `parent_a` above; the loop does the remaining N-1 moves.
617 for _ in 0..(parent_a_depth - parent_b_depth - 1) {
618 a = self.parent_map.get(&a).unwrap().0;
620 } else if parent_b_depth > parent_a_depth {
621 // `b` is lower than `a`.
623 for _ in 0..(parent_b_depth - parent_a_depth - 1) {
624 b = self.parent_map.get(&b).unwrap().0;
627 // Both scopes are at the same depth, and we know they're not equal
628 // because that case was tested for at the top of this function. So
629 // we can trivially move them both up one level now.
630 assert!(parent_a_depth != 0);
635 // Now both scopes are at the same level. We move upwards in lockstep
636 // until they match. In practice, this loop is almost always executed
637 // zero times because `a` is almost always a direct ancestor of `b` or
640 a = self.parent_map.get(&a).unwrap().0;
641 b = self.parent_map.get(&b).unwrap().0;
647 /// Assuming that the provided region was defined within this `ScopeTree`,
648 /// returns the outermost `Scope` that the region outlives.
649 pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
650 br: &ty::EarlyBoundRegion)
652 let param_owner = tcx.parent(br.def_id).unwrap();
654 let param_owner_id = tcx.hir().as_local_hir_id(param_owner).unwrap();
655 let scope = tcx.hir().maybe_body_owned_by_by_hir_id(param_owner_id).map(|body_id| {
656 tcx.hir().body(body_id).value.hir_id.local_id
657 }).unwrap_or_else(|| {
658 // The lifetime was defined on node that doesn't own a body,
659 // which in practice can only mean a trait or an impl, that
660 // is the parent of a method, and that is enforced below.
661 if Some(param_owner_id) != self.root_parent {
662 tcx.sess.delay_span_bug(
664 &format!("free_scope: {:?} not recognized by the \
665 region scope tree for {:?} / {:?}",
667 self.root_parent.map(|id| tcx.hir().local_def_id_from_hir_id(id)),
668 self.root_body.map(|hir_id| DefId::local(hir_id.owner))));
671 // The trait/impl lifetime is in scope for the method's body.
672 self.root_body.unwrap().local_id
675 Scope { id: scope, data: ScopeData::CallSite }
678 /// Assuming that the provided region was defined within this `ScopeTree`,
679 /// returns the outermost `Scope` that the region outlives.
680 pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
682 let param_owner = match fr.bound_region {
683 ty::BoundRegion::BrNamed(def_id, _) => {
684 tcx.parent(def_id).unwrap()
689 // Ensure that the named late-bound lifetimes were defined
690 // on the same function that they ended up being freed in.
691 assert_eq!(param_owner, fr.scope);
693 let param_owner_id = tcx.hir().as_local_hir_id(param_owner).unwrap();
694 let body_id = tcx.hir().body_owned_by(param_owner_id);
695 Scope { id: tcx.hir().body(body_id).value.hir_id.local_id, data: ScopeData::CallSite }
698 /// Checks whether the given scope contains a `yield`. If so,
699 /// returns `Some((span, expr_count))` with the span of a yield we found and
700 /// the number of expressions and patterns appearing before the `yield` in the body + 1.
701 /// If there a are multiple yields in a scope, the one with the highest number is returned.
702 pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
703 self.yield_in_scope.get(&scope).cloned()
706 /// Checks whether the given scope contains a `yield` and if that yield could execute
707 /// after `expr`. If so, it returns the span of that `yield`.
708 /// `scope` must be inside the body.
709 pub fn yield_in_scope_for_expr(&self,
711 expr_hir_id: hir::HirId,
712 body: &'tcx hir::Body) -> Option<Span> {
713 self.yield_in_scope(scope).and_then(|(span, count)| {
714 let mut visitor = ExprLocatorVisitor {
717 expr_and_pat_count: 0,
719 visitor.visit_body(body);
720 if count >= visitor.result.unwrap() {
728 /// Gives the number of expressions visited in a body.
729 /// Used to sanity check visit_expr call count when
730 /// calculating generator interiors.
731 pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
732 self.body_expr_count.get(&body_id).map(|r| *r)
736 /// Records the lifetime of a local variable as `cx.var_parent`
737 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor<'_, '_>,
738 var_id: hir::ItemLocalId,
740 match visitor.cx.var_parent {
742 // this can happen in extern fn declarations like
744 // extern fn isalnum(c: c_int) -> c_int
746 Some((parent_scope, _)) =>
747 visitor.scope_tree.record_var_scope(var_id, parent_scope),
751 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
752 debug!("resolve_block(blk.hir_id={:?})", blk.hir_id);
754 let prev_cx = visitor.cx;
756 // We treat the tail expression in the block (if any) somewhat
757 // differently from the statements. The issue has to do with
758 // temporary lifetimes. Consider the following:
761 // let inner = ... (&bar()) ...;
763 // (... (&foo()) ...) // (the tail expression)
764 // }, other_argument());
766 // Each of the statements within the block is a terminating
767 // scope, and thus a temporary (e.g., the result of calling
768 // `bar()` in the initializer expression for `let inner = ...;`)
769 // will be cleaned up immediately after its corresponding
770 // statement (i.e., `let inner = ...;`) executes.
772 // On the other hand, temporaries associated with evaluating the
773 // tail expression for the block are assigned lifetimes so that
774 // they will be cleaned up as part of the terminating scope
775 // *surrounding* the block expression. Here, the terminating
776 // scope for the block expression is the `quux(..)` call; so
777 // those temporaries will only be cleaned up *after* both
778 // `other_argument()` has run and also the call to `quux(..)`
779 // itself has returned.
781 visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
782 visitor.cx.var_parent = visitor.cx.parent;
785 // This block should be kept approximately in sync with
786 // `intravisit::walk_block`. (We manually walk the block, rather
787 // than call `walk_block`, in order to maintain precise
788 // index information.)
790 for (i, statement) in blk.stmts.iter().enumerate() {
791 match statement.node {
792 hir::StmtKind::Local(..) |
793 hir::StmtKind::Item(..) => {
794 // Each declaration introduces a subscope for bindings
795 // introduced by the declaration; this subscope covers a
796 // suffix of the block. Each subscope in a block has the
797 // previous subscope in the block as a parent, except for
798 // the first such subscope, which has the block itself as a
802 id: blk.hir_id.local_id,
803 data: ScopeData::Remainder(FirstStatementIndex::new(i))
806 visitor.cx.var_parent = visitor.cx.parent;
808 hir::StmtKind::Expr(..) |
809 hir::StmtKind::Semi(..) => {}
811 visitor.visit_stmt(statement)
813 walk_list!(visitor, visit_expr, &blk.expr);
816 visitor.cx = prev_cx;
819 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
820 let prev_cx = visitor.cx;
824 id: arm.hir_id.local_id,
825 data: ScopeData::Node,
828 visitor.cx.var_parent = visitor.cx.parent;
830 visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
832 if let Some(hir::Guard::If(ref expr)) = arm.guard {
833 visitor.terminating_scopes.insert(expr.hir_id.local_id);
836 intravisit::walk_arm(visitor, arm);
838 visitor.cx = prev_cx;
841 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
842 visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node });
844 // If this is a binding then record the lifetime of that binding.
845 if let PatKind::Binding(..) = pat.node {
846 record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
849 debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
851 intravisit::walk_pat(visitor, pat);
853 visitor.expr_and_pat_count += 1;
855 debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
858 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
859 let stmt_id = stmt.hir_id.local_id;
860 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
862 // Every statement will clean up the temporaries created during
863 // execution of that statement. Therefore each statement has an
864 // associated destruction scope that represents the scope of the
865 // statement plus its destructors, and thus the scope for which
866 // regions referenced by the destructors need to survive.
867 visitor.terminating_scopes.insert(stmt_id);
869 let prev_parent = visitor.cx.parent;
870 visitor.enter_node_scope_with_dtor(stmt_id);
872 intravisit::walk_stmt(visitor, stmt);
874 visitor.cx.parent = prev_parent;
877 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
878 debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr);
880 let prev_cx = visitor.cx;
881 visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
884 let terminating_scopes = &mut visitor.terminating_scopes;
885 let mut terminating = |id: hir::ItemLocalId| {
886 terminating_scopes.insert(id);
889 // Conditional or repeating scopes are always terminating
890 // scopes, meaning that temporaries cannot outlive them.
891 // This ensures fixed size stacks.
893 hir::ExprKind::Binary(
894 source_map::Spanned { node: hir::BinOpKind::And, .. }, _, ref r) |
895 hir::ExprKind::Binary(
896 source_map::Spanned { node: hir::BinOpKind::Or, .. }, _, ref r) => {
897 // For shortcircuiting operators, mark the RHS as a terminating
898 // scope since it only executes conditionally.
899 terminating(r.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::DropTemps(ref expr) => {
912 // `DropTemps(expr)` does not denote a conditional scope.
913 // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`.
914 terminating(expr.hir_id.local_id);
917 hir::ExprKind::AssignOp(..) | hir::ExprKind::Index(..) |
918 hir::ExprKind::Unary(..) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) => {
919 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
921 // The lifetimes for a call or method call look as follows:
929 // The idea is that call.callee_id represents *the time when
930 // the invoked function is actually running* and call.id
931 // represents *the time to prepare the arguments and make the
932 // call*. See the section "Borrows in Calls" borrowck/README.md
933 // for an extended explanation of why this distinction is
936 // record_superlifetime(new_cx, expr.callee_id);
944 // Manually recurse over closures, because they are the only
945 // case of nested bodies that share the parent environment.
946 hir::ExprKind::Closure(.., body, _, _) => {
947 let body = visitor.tcx.hir().body(body);
948 visitor.visit_body(body);
951 _ => intravisit::walk_expr(visitor, expr)
954 visitor.expr_and_pat_count += 1;
956 debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
958 if let hir::ExprKind::Yield(..) = expr.node {
959 // Mark this expr's scope and all parent scopes as containing `yield`.
960 let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node };
962 visitor.scope_tree.yield_in_scope.insert(scope,
963 (expr.span, visitor.expr_and_pat_count));
965 // Keep traversing up while we can.
966 match visitor.scope_tree.parent_map.get(&scope) {
967 // Don't cross from closure bodies to their parent.
968 Some(&(superscope, _)) => match superscope.data {
969 ScopeData::CallSite => break,
970 _ => scope = superscope
977 visitor.cx = prev_cx;
980 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
981 pat: Option<&'tcx hir::Pat>,
982 init: Option<&'tcx hir::Expr>) {
983 debug!("resolve_local(pat={:?}, init={:?})", pat, init);
985 let blk_scope = visitor.cx.var_parent.map(|(p, _)| p);
987 // As an exception to the normal rules governing temporary
988 // lifetimes, initializers in a let have a temporary lifetime
989 // of the enclosing block. This means that e.g., a program
990 // like the following is legal:
992 // let ref x = HashMap::new();
994 // Because the hash map will be freed in the enclosing block.
996 // We express the rules more formally based on 3 grammars (defined
997 // fully in the helpers below that implement them):
999 // 1. `E&`, which matches expressions like `&<rvalue>` that
1000 // own a pointer into the stack.
1002 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
1003 // y)` that produce ref bindings into the value they are
1004 // matched against or something (at least partially) owned by
1005 // the value they are matched against. (By partially owned,
1006 // I mean that creating a binding into a ref-counted or managed value
1007 // would still count.)
1009 // 3. `ET`, which matches both rvalues like `foo()` as well as places
1010 // based on rvalues like `foo().x[2].y`.
1012 // A subexpression `<rvalue>` that appears in a let initializer
1013 // `let pat [: ty] = expr` has an extended temporary lifetime if
1014 // any of the following conditions are met:
1016 // A. `pat` matches `P&` and `expr` matches `ET`
1017 // (covers cases where `pat` creates ref bindings into an rvalue
1018 // produced by `expr`)
1019 // B. `ty` is a borrowed pointer and `expr` matches `ET`
1020 // (covers cases where coercion creates a borrow)
1021 // C. `expr` matches `E&`
1022 // (covers cases `expr` borrows an rvalue that is then assigned
1023 // to memory (at least partially) owned by the binding)
1025 // Here are some examples hopefully giving an intuition where each
1026 // rule comes into play and why:
1028 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1029 // would have an extended lifetime, but not `foo()`.
1031 // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1034 // In some cases, multiple rules may apply (though not to the same
1035 // rvalue). For example:
1037 // let ref x = [&a(), &b()];
1039 // Here, the expression `[...]` has an extended lifetime due to rule
1040 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1043 if let Some(expr) = init {
1044 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1046 if let Some(pat) = pat {
1047 if is_binding_pat(pat) {
1048 record_rvalue_scope(visitor, &expr, blk_scope);
1053 // Make sure we visit the initializer first, so expr_and_pat_count remains correct
1054 if let Some(expr) = init {
1055 visitor.visit_expr(expr);
1057 if let Some(pat) = pat {
1058 visitor.visit_pat(pat);
1061 /// Returns `true` if `pat` match the `P&` non-terminal.
1064 /// | StructName { ..., P&, ... }
1065 /// | VariantName(..., P&, ...)
1066 /// | [ ..., P&, ... ]
1067 /// | ( ..., P&, ... )
1069 fn is_binding_pat(pat: &hir::Pat) -> bool {
1070 // Note that the code below looks for *explicit* refs only, that is, it won't
1071 // know about *implicit* refs as introduced in #42640.
1073 // This is not a problem. For example, consider
1075 // let (ref x, ref y) = (Foo { .. }, Bar { .. });
1077 // Due to the explicit refs on the left hand side, the below code would signal
1078 // that the temporary value on the right hand side should live until the end of
1079 // the enclosing block (as opposed to being dropped after the let is complete).
1081 // To create an implicit ref, however, you must have a borrowed value on the RHS
1082 // already, as in this example (which won't compile before #42640):
1084 // let Foo { x, .. } = &Foo { x: ..., ... };
1088 // let Foo { ref x, .. } = Foo { ... };
1090 // In the former case (the implicit ref version), the temporary is created by the
1091 // & expression, and its lifetime would be extended to the end of the block (due
1092 // to a different rule, not the below code).
1094 PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1095 PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1097 PatKind::Struct(_, ref field_pats, _) => {
1098 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1101 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
1102 pats1.iter().any(|p| is_binding_pat(&p)) ||
1103 pats2.iter().any(|p| is_binding_pat(&p)) ||
1104 pats3.iter().any(|p| is_binding_pat(&p))
1107 PatKind::TupleStruct(_, ref subpats, _) |
1108 PatKind::Tuple(ref subpats, _) => {
1109 subpats.iter().any(|p| is_binding_pat(&p))
1112 PatKind::Box(ref subpat) => {
1113 is_binding_pat(&subpat)
1120 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1123 /// | StructName { ..., f: E&, ... }
1124 /// | [ ..., E&, ... ]
1125 /// | ( ..., E&, ... )
1130 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1131 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1133 blk_id: Option<Scope>)
1136 hir::ExprKind::AddrOf(_, ref subexpr) => {
1137 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1138 record_rvalue_scope(visitor, &subexpr, blk_id);
1140 hir::ExprKind::Struct(_, ref fields, _) => {
1141 for field in fields {
1142 record_rvalue_scope_if_borrow_expr(
1143 visitor, &field.expr, blk_id);
1146 hir::ExprKind::Array(ref subexprs) |
1147 hir::ExprKind::Tup(ref subexprs) => {
1148 for subexpr in subexprs {
1149 record_rvalue_scope_if_borrow_expr(
1150 visitor, &subexpr, blk_id);
1153 hir::ExprKind::Cast(ref subexpr, _) => {
1154 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1156 hir::ExprKind::Block(ref block, _) => {
1157 if let Some(ref subexpr) = block.expr {
1158 record_rvalue_scope_if_borrow_expr(
1159 visitor, &subexpr, blk_id);
1166 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1167 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1168 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1171 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1172 /// `<rvalue>` as `blk_id`:
1180 /// Note: ET is intended to match "rvalues or places based on rvalues".
1181 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1183 blk_scope: Option<Scope>) {
1184 let mut expr = expr;
1186 // Note: give all the expressions matching `ET` with the
1187 // extended temporary lifetime, not just the innermost rvalue,
1188 // because in codegen if we must compile e.g., `*rvalue()`
1189 // into a temporary, we request the temporary scope of the
1190 // outer expression.
1191 visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1194 hir::ExprKind::AddrOf(_, ref subexpr) |
1195 hir::ExprKind::Unary(hir::UnDeref, ref subexpr) |
1196 hir::ExprKind::Field(ref subexpr, _) |
1197 hir::ExprKind::Index(ref subexpr, _) => {
1208 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1209 /// Records the current parent (if any) as the parent of `child_scope`.
1210 /// Returns the depth of `child_scope`.
1211 fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth {
1212 let parent = self.cx.parent;
1213 self.scope_tree.record_scope_parent(child_scope, parent);
1214 // If `child_scope` has no parent, it must be the root node, and so has
1215 // a depth of 1. Otherwise, its depth is one more than its parent's.
1216 parent.map_or(1, |(_p, d)| d + 1)
1219 /// Records the current parent (if any) as the parent of `child_scope`,
1220 /// and sets `child_scope` as the new current parent.
1221 fn enter_scope(&mut self, child_scope: Scope) {
1222 let child_depth = self.record_child_scope(child_scope);
1223 self.cx.parent = Some((child_scope, child_depth));
1226 fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1227 // If node was previously marked as a terminating scope during the
1228 // recursive visit of its parent node in the AST, then we need to
1229 // account for the destruction scope representing the scope of
1230 // the destructors that run immediately after it completes.
1231 if self.terminating_scopes.contains(&id) {
1232 self.enter_scope(Scope { id, data: ScopeData::Destruction });
1234 self.enter_scope(Scope { id, data: ScopeData::Node });
1238 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1239 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1240 NestedVisitorMap::None
1243 fn visit_block(&mut self, b: &'tcx Block) {
1244 resolve_block(self, b);
1247 fn visit_body(&mut self, body: &'tcx hir::Body) {
1248 let body_id = body.id();
1249 let owner_id = self.tcx.hir().body_owner(body_id);
1251 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1253 self.tcx.sess.source_map().span_to_string(body.value.span),
1257 let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
1258 let outer_cx = self.cx;
1259 let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet::default());
1260 self.terminating_scopes.insert(body.value.hir_id.local_id);
1262 if let Some(root_id) = self.cx.root_id {
1263 self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1265 self.cx.root_id = Some(body.value.hir_id.local_id);
1267 self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite });
1268 self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments });
1270 // The arguments and `self` are parented to the fn.
1271 self.cx.var_parent = self.cx.parent.take();
1272 for argument in &body.arguments {
1273 self.visit_pat(&argument.pat);
1276 // The body of the every fn is a root scope.
1277 self.cx.parent = self.cx.var_parent;
1278 if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() {
1279 self.visit_expr(&body.value)
1281 // Only functions have an outer terminating (drop) scope, while
1282 // temporaries in constant initializers may be 'static, but only
1283 // according to rvalue lifetime semantics, using the same
1284 // syntactical rules used for let initializers.
1286 // e.g., in `let x = &f();`, the temporary holding the result from
1287 // the `f()` call lives for the entirety of the surrounding block.
1289 // Similarly, `const X: ... = &f();` would have the result of `f()`
1290 // live for `'static`, implying (if Drop restrictions on constants
1291 // ever get lifted) that the value *could* have a destructor, but
1292 // it'd get leaked instead of the destructor running during the
1293 // evaluation of `X` (if at all allowed by CTFE).
1295 // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1296 // would *not* let the `f()` temporary escape into an outer scope
1297 // (i.e., `'static`), which means that after `g` returns, it drops,
1298 // and all the associated destruction scope rules apply.
1299 self.cx.var_parent = None;
1300 resolve_local(self, None, Some(&body.value));
1303 if body.is_generator {
1304 self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1307 // Restore context we had at the start.
1308 self.expr_and_pat_count = outer_ec;
1310 self.terminating_scopes = outer_ts;
1313 fn visit_arm(&mut self, a: &'tcx Arm) {
1314 resolve_arm(self, a);
1316 fn visit_pat(&mut self, p: &'tcx Pat) {
1317 resolve_pat(self, p);
1319 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1320 resolve_stmt(self, s);
1322 fn visit_expr(&mut self, ex: &'tcx Expr) {
1323 resolve_expr(self, ex);
1325 fn visit_local(&mut self, l: &'tcx Local) {
1326 resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1330 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1333 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1334 if closure_base_def_id != def_id {
1335 return tcx.region_scope_tree(closure_base_def_id);
1338 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1339 let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by_by_hir_id(id) {
1340 let mut visitor = RegionResolutionVisitor {
1342 scope_tree: ScopeTree::default(),
1343 expr_and_pat_count: 0,
1349 terminating_scopes: Default::default(),
1352 let body = tcx.hir().body(body_id);
1353 visitor.scope_tree.root_body = Some(body.value.hir_id);
1355 // If the item is an associated const or a method,
1356 // record its impl/trait parent, as it can also have
1357 // lifetime parameters free in this body.
1358 match tcx.hir().get_by_hir_id(id) {
1360 Node::TraitItem(_) => {
1361 visitor.scope_tree.root_parent = Some(tcx.hir().get_parent_item(id));
1366 visitor.visit_body(body);
1370 ScopeTree::default()
1373 tcx.arena.alloc(scope_tree)
1376 pub fn provide(providers: &mut Providers<'_>) {
1377 *providers = Providers {
1383 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
1384 fn hash_stable<W: StableHasherResult>(&self,
1385 hcx: &mut StableHashingContext<'a>,
1386 hasher: &mut StableHasher<W>) {
1390 ref body_expr_count,
1393 ref destruction_scopes,
1399 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1400 root_body.hash_stable(hcx, hasher);
1401 root_parent.hash_stable(hcx, hasher);
1404 body_expr_count.hash_stable(hcx, hasher);
1405 parent_map.hash_stable(hcx, hasher);
1406 var_map.hash_stable(hcx, hasher);
1407 destruction_scopes.hash_stable(hcx, hasher);
1408 rvalue_scopes.hash_stable(hcx, hasher);
1409 closure_tree.hash_stable(hcx, hasher);
1410 yield_in_scope.hash_stable(hcx, hasher);