]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/region.rs
Update region_scope_tree
[rust.git] / src / librustc / middle / region.rs
1 //! This file builds up the `ScopeTree`, which describes
2 //! the parent links in the region hierarchy.
3 //!
4 //! For more information about how MIR-based region-checking works,
5 //! see the [rustc guide].
6 //!
7 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/borrowck.html
8
9 use crate::ich::{StableHashingContext, NodeIdHashingMode};
10 use crate::util::nodemap::{FxHashMap, FxHashSet};
11 use crate::ty;
12
13 use std::mem;
14 use std::fmt;
15 use rustc_macros::HashStable;
16 use syntax::source_map;
17 use syntax::ast;
18 use syntax_pos::{Span, DUMMY_SP};
19 use crate::ty::{DefIdTree, TyCtxt};
20 use crate::ty::query::Providers;
21
22 use crate::hir;
23 use crate::hir::Node;
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,
29                                            StableHasherResult};
30
31 /// Scope represents a statically-describable scope that can be
32 /// used to bound the lifetime/region for values.
33 ///
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.
37 ///
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`.
43 ///
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.
47 ///
48 /// So: the following code can be broken down into the scopes beneath:
49 ///
50 /// ```text
51 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y)  }   ) ;
52 ///
53 ///                                                              +-+ (D12.)
54 ///                                                        +-+       (D11.)
55 ///                                              +---------+         (R10.)
56 ///                                              +-+                  (D9.)
57 ///                                   +----------+                    (M8.)
58 ///                                 +----------------------+          (R7.)
59 ///                                 +-+                               (D6.)
60 ///                      +----------+                                 (M5.)
61 ///                    +-----------------------------------+          (M4.)
62 ///         +--------------------------------------------------+      (M3.)
63 ///         +--+                                                      (M2.)
64 /// +-----------------------------------------------------------+     (M1.)
65 ///
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()).
78 /// ```
79 ///
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.
88 //
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)]
95 pub struct Scope {
96     pub id: hir::ItemLocalId,
97     pub data: ScopeData,
98 }
99
100 impl fmt::Debug for Scope {
101     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
102         match self.data {
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!(
108                 fmt,
109                 "Remainder {{ block: {:?}, first_statement_index: {}}}",
110                 self.id,
111                 fsi.as_u32(),
112             ),
113         }
114     }
115 }
116
117 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy,
118          RustcEncodable, RustcDecodable, HashStable)]
119 pub enum ScopeData {
120     Node,
121
122     // Scope of the call-site for a function or closure
123     // (outlives the arguments as well as the body).
124     CallSite,
125
126     // Scope of arguments passed to a function or closure
127     // (they outlive its body).
128     Arguments,
129
130     // Scope of destructors for temporaries of node-id.
131     Destruction,
132
133     // Scope following a `let id = expr;` binding in a block.
134     Remainder(FirstStatementIndex)
135 }
136
137 newtype_index! {
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`.
143     ///
144     /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
145     ///
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`.
152     ///
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 { .. }
156 }
157
158 impl_stable_hash_for!(struct crate::middle::region::FirstStatementIndex { private });
159
160 // compilation error if size of `ScopeData` is not the same as a `u32`
161 static_assert!(ASSERT_SCOPE_DATA: mem::size_of::<ScopeData>() == 4);
162
163 impl Scope {
164     /// Returns a item-local ID associated with this scope.
165     ///
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 {
169         self.id
170     }
171
172     pub fn node_id(&self, tcx: TyCtxt<'_, '_, '_>, scope_tree: &ScopeTree) -> ast::NodeId {
173         match scope_tree.root_body {
174             Some(hir_id) => {
175                 tcx.hir().hir_to_node_id(hir::HirId {
176                     owner: hir_id.owner,
177                     local_id: self.item_local_id()
178                 })
179             }
180             None => ast::DUMMY_NODE_ID
181         }
182     }
183
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
186     /// the AST.
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 {
190             return DUMMY_SP;
191         }
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.
199                 //
200                 // (This is the special case aluded to in the
201                 // doc-comment for this method)
202
203                 let stmt_span = blk.stmts[first_statement_index.index()].span;
204
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());
209                 }
210             }
211          }
212          span
213     }
214 }
215
216 pub type ScopeDepth = u32;
217
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>,
223
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>,
228
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)>,
236
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>,
240
241     /// maps from a `NodeId` to the associated destruction scope (if any)
242     destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
243
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>>,
253
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
263     /// more details.
264     closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
265
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.
269     ///
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.
276     ///
277     /// For an example, suppose we have some code such as:
278     /// ```rust,ignore (example)
279     ///     foo(f(), yield y, bar(g()))
280     /// ```
281     ///
282     /// With the HIR tree (calls numbered for expository purposes)
283     /// ```
284     ///     Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
285     /// ```
286     ///
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:
292     /// ```plain,ignore
293     ///     `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
294     /// ```
295     ///
296     /// In which we can easily see that `Call#1` occurs before the yield,
297     /// and `Call#3` after it.
298     ///
299     /// To see that this method works, consider:
300     ///
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`.
305     ///
306     /// Remember that storage-live/storage-dead refers to the state of
307     /// the *storage*, and does not consider moves/drop flags.
308     ///
309     /// Then:
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`,
320     ///     QED.
321     ///
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
325     /// works?
326     ///
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.
331     ///
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)>,
336
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>,
341 }
342
343 #[derive(Debug, Copy, Clone)]
344 pub struct Context {
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
350     /// details.
351     root_id: Option<hir::ItemLocalId>,
352
353     /// The scope that contains any new variables declared, plus its depth in
354     /// the scope tree.
355     var_parent: Option<(Scope, ScopeDepth)>,
356
357     /// Region parent of expressions, etc., plus its depth in the scope tree.
358     parent: Option<(Scope, ScopeDepth)>,
359 }
360
361 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
362     tcx: TyCtxt<'a, 'tcx, 'tcx>,
363
364     // The number of expressions and patterns visited in the current body
365     expr_and_pat_count: usize,
366
367     // Generated scope tree:
368     scope_tree: ScopeTree,
369
370     cx: Context,
371
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>,
393 }
394
395 struct ExprLocatorVisitor {
396     hir_id: hir::HirId,
397     result: Option<usize>,
398     expr_and_pat_count: usize,
399 }
400
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
406     }
407
408     fn visit_pat(&mut self, pat: &'tcx Pat) {
409         intravisit::walk_pat(self, pat);
410
411         self.expr_and_pat_count += 1;
412
413         if pat.hir_id == self.hir_id {
414             self.result = Some(self.expr_and_pat_count);
415         }
416     }
417
418     fn visit_expr(&mut self, expr: &'tcx Expr) {
419         debug!("ExprLocatorVisitor - pre-increment {} expr = {:?}",
420                self.expr_and_pat_count,
421                expr);
422
423         intravisit::walk_expr(self, expr);
424
425         self.expr_and_pat_count += 1;
426
427         debug!("ExprLocatorVisitor - post-increment {} expr = {:?}",
428                self.expr_and_pat_count,
429                expr);
430
431         if expr.hir_id == self.hir_id {
432             self.result = Some(self.expr_and_pat_count);
433         }
434     }
435 }
436
437 impl<'tcx> ScopeTree {
438     pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) {
439         debug!("{:?}.parent = {:?}", child, parent);
440
441         if let Some(p) = parent {
442             let prev = self.parent_map.insert(child, p);
443             assert!(prev.is_none());
444         }
445
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);
449         }
450     }
451
452     pub fn each_encl_scope<E>(&self, mut e: E) where E: FnMut(Scope, Scope) {
453         for (&child, &parent) in &self.parent_map {
454             e(child, parent.0)
455         }
456     }
457
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() {
460             e(child, parent)
461         }
462     }
463
464     pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
465         self.destruction_scopes.get(&n).cloned()
466     }
467
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());
479     }
480
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);
485     }
486
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());
491         }
492         self.rvalue_scopes.insert(var, lifetime);
493     }
494
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)
498     }
499
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()
504     }
505
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))
510     }
511
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
514
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);
518             return s;
519         }
520
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
524         // returned.
525         let mut id = Scope { id: expr_id, data: ScopeData::Node };
526
527         while let Some(&(p, _)) = self.parent_map.get(&id) {
528             match p.data {
529                 ScopeData::Destruction => {
530                     debug!("temporary_scope({:?}) = {:?} [enclosing]",
531                            expr_id, id);
532                     return Some(id);
533                 }
534                 _ => id = p
535             }
536         }
537
538         debug!("temporary_scope({:?}) = None", expr_id);
539         return None;
540     }
541
542     pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
543         //! Returns the lifetime of the variable `id`.
544
545         let scope = ty::ReScope(self.var_scope(id));
546         debug!("var_region({:?}) = {:?}", id, scope);
547         scope
548     }
549
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)
553     }
554
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,
558                           subscope: Scope,
559                           superscope: Scope)
560                           -> bool {
561         let mut s = subscope;
562         debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
563         while superscope != s {
564             match self.opt_encl_scope(s) {
565                 None => {
566                     debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
567                            subscope, superscope, s);
568                     return false;
569                 }
570                 Some(scope) => s = scope
571             }
572         }
573
574         debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
575
576         return true;
577     }
578
579     /// Returns the ID of the innermost containing body
580     pub fn containing_body(&self, mut scope: Scope) -> Option<hir::ItemLocalId> {
581         loop {
582             if let ScopeData::CallSite = scope.data {
583                 return Some(scope.item_local_id());
584             }
585
586             scope = self.opt_encl_scope(scope)?;
587         }
588     }
589
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
592     /// `scope_b`.
593     pub fn nearest_common_ancestor(&self, scope_a: Scope, scope_b: Scope) -> Scope {
594         if scope_a == scope_b { return scope_a; }
595
596         let mut a = scope_a;
597         let mut b = scope_b;
598
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) {
604             Some(pd) => *pd,
605             None => return a,
606         };
607         let (parent_b, parent_b_depth) = match self.parent_map.get(&b) {
608             Some(pd) => *pd,
609             None => return b,
610         };
611
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.
616             a = parent_a;
617             for _ in 0..(parent_a_depth - parent_b_depth - 1) {
618                 a = self.parent_map.get(&a).unwrap().0;
619             }
620         } else if parent_b_depth > parent_a_depth {
621             // `b` is lower than `a`.
622             b = parent_b;
623             for _ in 0..(parent_b_depth - parent_a_depth - 1) {
624                 b = self.parent_map.get(&b).unwrap().0;
625             }
626         } else {
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);
631             a = parent_a;
632             b = parent_b;
633         }
634
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
638         // vice versa.
639         while a != b {
640             a = self.parent_map.get(&a).unwrap().0;
641             b = self.parent_map.get(&b).unwrap().0;
642         };
643
644         a
645     }
646
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)
651                                       -> Scope {
652         let param_owner = tcx.parent(br.def_id).unwrap();
653
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             assert_eq!(Some(param_owner_id), self.root_parent,
662                        "free_scope: {:?} not recognized by the \
663                         region scope tree for {:?} / {:?}",
664                        param_owner,
665                        self.root_parent.map(|id| tcx.hir().local_def_id_from_hir_id(id)),
666                        self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
667
668             // The trait/impl lifetime is in scope for the method's body.
669             self.root_body.unwrap().local_id
670         });
671
672         Scope { id: scope, data: ScopeData::CallSite }
673     }
674
675     /// Assuming that the provided region was defined within this `ScopeTree`,
676     /// returns the outermost `Scope` that the region outlives.
677     pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
678                                  -> Scope {
679         let param_owner = match fr.bound_region {
680             ty::BoundRegion::BrNamed(def_id, _) => {
681                 tcx.parent(def_id).unwrap()
682             }
683             _ => fr.scope
684         };
685
686         // Ensure that the named late-bound lifetimes were defined
687         // on the same function that they ended up being freed in.
688         assert_eq!(param_owner, fr.scope);
689
690         let param_owner_id = tcx.hir().as_local_hir_id(param_owner).unwrap();
691         let body_id = tcx.hir().body_owned_by(param_owner_id);
692         Scope { id: tcx.hir().body(body_id).value.hir_id.local_id, data: ScopeData::CallSite }
693     }
694
695     /// Checks whether the given scope contains a `yield`. If so,
696     /// returns `Some((span, expr_count))` with the span of a yield we found and
697     /// the number of expressions and patterns appearing before the `yield` in the body + 1.
698     /// If there a are multiple yields in a scope, the one with the highest number is returned.
699     pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
700         self.yield_in_scope.get(&scope).cloned()
701     }
702
703     /// Checks whether the given scope contains a `yield` and if that yield could execute
704     /// after `expr`. If so, it returns the span of that `yield`.
705     /// `scope` must be inside the body.
706     pub fn yield_in_scope_for_expr(&self,
707                                    scope: Scope,
708                                    expr_hir_id: hir::HirId,
709                                    body: &'tcx hir::Body) -> Option<Span> {
710         self.yield_in_scope(scope).and_then(|(span, count)| {
711             let mut visitor = ExprLocatorVisitor {
712                 hir_id: expr_hir_id,
713                 result: None,
714                 expr_and_pat_count: 0,
715             };
716             visitor.visit_body(body);
717             if count >= visitor.result.unwrap() {
718                 Some(span)
719             } else {
720                 None
721             }
722         })
723     }
724
725     /// Gives the number of expressions visited in a body.
726     /// Used to sanity check visit_expr call count when
727     /// calculating generator interiors.
728     pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
729         self.body_expr_count.get(&body_id).map(|r| *r)
730     }
731 }
732
733 /// Records the lifetime of a local variable as `cx.var_parent`
734 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor<'_, '_>,
735                        var_id: hir::ItemLocalId,
736                        _sp: Span) {
737     match visitor.cx.var_parent {
738         None => {
739             // this can happen in extern fn declarations like
740             //
741             // extern fn isalnum(c: c_int) -> c_int
742         }
743         Some((parent_scope, _)) =>
744             visitor.scope_tree.record_var_scope(var_id, parent_scope),
745     }
746 }
747
748 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
749     debug!("resolve_block(blk.hir_id={:?})", blk.hir_id);
750
751     let prev_cx = visitor.cx;
752
753     // We treat the tail expression in the block (if any) somewhat
754     // differently from the statements. The issue has to do with
755     // temporary lifetimes. Consider the following:
756     //
757     //    quux({
758     //        let inner = ... (&bar()) ...;
759     //
760     //        (... (&foo()) ...) // (the tail expression)
761     //    }, other_argument());
762     //
763     // Each of the statements within the block is a terminating
764     // scope, and thus a temporary (e.g., the result of calling
765     // `bar()` in the initializer expression for `let inner = ...;`)
766     // will be cleaned up immediately after its corresponding
767     // statement (i.e., `let inner = ...;`) executes.
768     //
769     // On the other hand, temporaries associated with evaluating the
770     // tail expression for the block are assigned lifetimes so that
771     // they will be cleaned up as part of the terminating scope
772     // *surrounding* the block expression. Here, the terminating
773     // scope for the block expression is the `quux(..)` call; so
774     // those temporaries will only be cleaned up *after* both
775     // `other_argument()` has run and also the call to `quux(..)`
776     // itself has returned.
777
778     visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
779     visitor.cx.var_parent = visitor.cx.parent;
780
781     {
782         // This block should be kept approximately in sync with
783         // `intravisit::walk_block`. (We manually walk the block, rather
784         // than call `walk_block`, in order to maintain precise
785         // index information.)
786
787         for (i, statement) in blk.stmts.iter().enumerate() {
788             match statement.node {
789                 hir::StmtKind::Local(..) |
790                 hir::StmtKind::Item(..) => {
791                     // Each declaration introduces a subscope for bindings
792                     // introduced by the declaration; this subscope covers a
793                     // suffix of the block. Each subscope in a block has the
794                     // previous subscope in the block as a parent, except for
795                     // the first such subscope, which has the block itself as a
796                     // parent.
797                     visitor.enter_scope(
798                         Scope {
799                             id: blk.hir_id.local_id,
800                             data: ScopeData::Remainder(FirstStatementIndex::new(i))
801                         }
802                     );
803                     visitor.cx.var_parent = visitor.cx.parent;
804                 }
805                 hir::StmtKind::Expr(..) |
806                 hir::StmtKind::Semi(..) => {}
807             }
808             visitor.visit_stmt(statement)
809         }
810         walk_list!(visitor, visit_expr, &blk.expr);
811     }
812
813     visitor.cx = prev_cx;
814 }
815
816 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
817     visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
818
819     if let Some(hir::Guard::If(ref expr)) = arm.guard {
820         visitor.terminating_scopes.insert(expr.hir_id.local_id);
821     }
822
823     intravisit::walk_arm(visitor, arm);
824 }
825
826 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
827     visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node });
828
829     // If this is a binding then record the lifetime of that binding.
830     if let PatKind::Binding(..) = pat.node {
831         record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
832     }
833
834     debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
835
836     intravisit::walk_pat(visitor, pat);
837
838     visitor.expr_and_pat_count += 1;
839
840     debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
841 }
842
843 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
844     let stmt_id = stmt.hir_id.local_id;
845     debug!("resolve_stmt(stmt.id={:?})", stmt_id);
846
847     // Every statement will clean up the temporaries created during
848     // execution of that statement. Therefore each statement has an
849     // associated destruction scope that represents the scope of the
850     // statement plus its destructors, and thus the scope for which
851     // regions referenced by the destructors need to survive.
852     visitor.terminating_scopes.insert(stmt_id);
853
854     let prev_parent = visitor.cx.parent;
855     visitor.enter_node_scope_with_dtor(stmt_id);
856
857     intravisit::walk_stmt(visitor, stmt);
858
859     visitor.cx.parent = prev_parent;
860 }
861
862 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
863     debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr);
864
865     let prev_cx = visitor.cx;
866     visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
867
868     {
869         let terminating_scopes = &mut visitor.terminating_scopes;
870         let mut terminating = |id: hir::ItemLocalId| {
871             terminating_scopes.insert(id);
872         };
873         match expr.node {
874             // Conditional or repeating scopes are always terminating
875             // scopes, meaning that temporaries cannot outlive them.
876             // This ensures fixed size stacks.
877
878             hir::ExprKind::Binary(
879                 source_map::Spanned { node: hir::BinOpKind::And, .. }, _, ref r) |
880             hir::ExprKind::Binary(
881                 source_map::Spanned { node: hir::BinOpKind::Or, .. }, _, ref r) => {
882                     // For shortcircuiting operators, mark the RHS as a terminating
883                     // scope since it only executes conditionally.
884                     terminating(r.hir_id.local_id);
885             }
886
887             hir::ExprKind::If(ref expr, ref then, Some(ref otherwise)) => {
888                 terminating(expr.hir_id.local_id);
889                 terminating(then.hir_id.local_id);
890                 terminating(otherwise.hir_id.local_id);
891             }
892
893             hir::ExprKind::If(ref expr, ref then, None) => {
894                 terminating(expr.hir_id.local_id);
895                 terminating(then.hir_id.local_id);
896             }
897
898             hir::ExprKind::Loop(ref body, _, _) => {
899                 terminating(body.hir_id.local_id);
900             }
901
902             hir::ExprKind::While(ref expr, ref body, _) => {
903                 terminating(expr.hir_id.local_id);
904                 terminating(body.hir_id.local_id);
905             }
906
907             hir::ExprKind::Match(..) => {
908                 visitor.cx.var_parent = visitor.cx.parent;
909             }
910
911             hir::ExprKind::AssignOp(..) | hir::ExprKind::Index(..) |
912             hir::ExprKind::Unary(..) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) => {
913                 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
914                 //
915                 // The lifetimes for a call or method call look as follows:
916                 //
917                 // call.id
918                 // - arg0.id
919                 // - ...
920                 // - argN.id
921                 // - call.callee_id
922                 //
923                 // The idea is that call.callee_id represents *the time when
924                 // the invoked function is actually running* and call.id
925                 // represents *the time to prepare the arguments and make the
926                 // call*.  See the section "Borrows in Calls" borrowck/README.md
927                 // for an extended explanation of why this distinction is
928                 // important.
929                 //
930                 // record_superlifetime(new_cx, expr.callee_id);
931             }
932
933             _ => {}
934         }
935     }
936
937     match expr.node {
938         // Manually recurse over closures, because they are the only
939         // case of nested bodies that share the parent environment.
940         hir::ExprKind::Closure(.., body, _, _) => {
941             let body = visitor.tcx.hir().body(body);
942             visitor.visit_body(body);
943         }
944
945         _ => intravisit::walk_expr(visitor, expr)
946     }
947
948     visitor.expr_and_pat_count += 1;
949
950     debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
951
952     if let hir::ExprKind::Yield(..) = expr.node {
953         // Mark this expr's scope and all parent scopes as containing `yield`.
954         let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node };
955         loop {
956             visitor.scope_tree.yield_in_scope.insert(scope,
957                 (expr.span, visitor.expr_and_pat_count));
958
959             // Keep traversing up while we can.
960             match visitor.scope_tree.parent_map.get(&scope) {
961                 // Don't cross from closure bodies to their parent.
962                 Some(&(superscope, _)) => match superscope.data {
963                     ScopeData::CallSite => break,
964                     _ => scope = superscope
965                 },
966                 None => break
967             }
968         }
969     }
970
971     visitor.cx = prev_cx;
972 }
973
974 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
975                            pat: Option<&'tcx hir::Pat>,
976                            init: Option<&'tcx hir::Expr>) {
977     debug!("resolve_local(pat={:?}, init={:?})", pat, init);
978
979     let blk_scope = visitor.cx.var_parent.map(|(p, _)| p);
980
981     // As an exception to the normal rules governing temporary
982     // lifetimes, initializers in a let have a temporary lifetime
983     // of the enclosing block. This means that e.g., a program
984     // like the following is legal:
985     //
986     //     let ref x = HashMap::new();
987     //
988     // Because the hash map will be freed in the enclosing block.
989     //
990     // We express the rules more formally based on 3 grammars (defined
991     // fully in the helpers below that implement them):
992     //
993     // 1. `E&`, which matches expressions like `&<rvalue>` that
994     //    own a pointer into the stack.
995     //
996     // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
997     //    y)` that produce ref bindings into the value they are
998     //    matched against or something (at least partially) owned by
999     //    the value they are matched against. (By partially owned,
1000     //    I mean that creating a binding into a ref-counted or managed value
1001     //    would still count.)
1002     //
1003     // 3. `ET`, which matches both rvalues like `foo()` as well as places
1004     //    based on rvalues like `foo().x[2].y`.
1005     //
1006     // A subexpression `<rvalue>` that appears in a let initializer
1007     // `let pat [: ty] = expr` has an extended temporary lifetime if
1008     // any of the following conditions are met:
1009     //
1010     // A. `pat` matches `P&` and `expr` matches `ET`
1011     //    (covers cases where `pat` creates ref bindings into an rvalue
1012     //     produced by `expr`)
1013     // B. `ty` is a borrowed pointer and `expr` matches `ET`
1014     //    (covers cases where coercion creates a borrow)
1015     // C. `expr` matches `E&`
1016     //    (covers cases `expr` borrows an rvalue that is then assigned
1017     //     to memory (at least partially) owned by the binding)
1018     //
1019     // Here are some examples hopefully giving an intuition where each
1020     // rule comes into play and why:
1021     //
1022     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1023     // would have an extended lifetime, but not `foo()`.
1024     //
1025     // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1026     // lifetime.
1027     //
1028     // In some cases, multiple rules may apply (though not to the same
1029     // rvalue). For example:
1030     //
1031     //     let ref x = [&a(), &b()];
1032     //
1033     // Here, the expression `[...]` has an extended lifetime due to rule
1034     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1035     // due to rule C.
1036
1037     if let Some(expr) = init {
1038         record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1039
1040         if let Some(pat) = pat {
1041             if is_binding_pat(pat) {
1042                 record_rvalue_scope(visitor, &expr, blk_scope);
1043             }
1044         }
1045     }
1046
1047     // Make sure we visit the initializer first, so expr_and_pat_count remains correct
1048     if let Some(expr) = init {
1049         visitor.visit_expr(expr);
1050     }
1051     if let Some(pat) = pat {
1052         visitor.visit_pat(pat);
1053     }
1054
1055     /// Returns `true` if `pat` match the `P&` non-terminal.
1056     ///
1057     ///     P& = ref X
1058     ///        | StructName { ..., P&, ... }
1059     ///        | VariantName(..., P&, ...)
1060     ///        | [ ..., P&, ... ]
1061     ///        | ( ..., P&, ... )
1062     ///        | box P&
1063     fn is_binding_pat(pat: &hir::Pat) -> bool {
1064         // Note that the code below looks for *explicit* refs only, that is, it won't
1065         // know about *implicit* refs as introduced in #42640.
1066         //
1067         // This is not a problem. For example, consider
1068         //
1069         //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
1070         //
1071         // Due to the explicit refs on the left hand side, the below code would signal
1072         // that the temporary value on the right hand side should live until the end of
1073         // the enclosing block (as opposed to being dropped after the let is complete).
1074         //
1075         // To create an implicit ref, however, you must have a borrowed value on the RHS
1076         // already, as in this example (which won't compile before #42640):
1077         //
1078         //      let Foo { x, .. } = &Foo { x: ..., ... };
1079         //
1080         // in place of
1081         //
1082         //      let Foo { ref x, .. } = Foo { ... };
1083         //
1084         // In the former case (the implicit ref version), the temporary is created by the
1085         // & expression, and its lifetime would be extended to the end of the block (due
1086         // to a different rule, not the below code).
1087         match pat.node {
1088             PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1089             PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1090
1091             PatKind::Struct(_, ref field_pats, _) => {
1092                 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1093             }
1094
1095             PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
1096                 pats1.iter().any(|p| is_binding_pat(&p)) ||
1097                 pats2.iter().any(|p| is_binding_pat(&p)) ||
1098                 pats3.iter().any(|p| is_binding_pat(&p))
1099             }
1100
1101             PatKind::TupleStruct(_, ref subpats, _) |
1102             PatKind::Tuple(ref subpats, _) => {
1103                 subpats.iter().any(|p| is_binding_pat(&p))
1104             }
1105
1106             PatKind::Box(ref subpat) => {
1107                 is_binding_pat(&subpat)
1108             }
1109
1110             _ => false,
1111         }
1112     }
1113
1114     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1115     ///
1116     ///     E& = & ET
1117     ///        | StructName { ..., f: E&, ... }
1118     ///        | [ ..., E&, ... ]
1119     ///        | ( ..., E&, ... )
1120     ///        | {...; E&}
1121     ///        | box E&
1122     ///        | E& as ...
1123     ///        | ( E& )
1124     fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1125         visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1126         expr: &hir::Expr,
1127         blk_id: Option<Scope>)
1128     {
1129         match expr.node {
1130             hir::ExprKind::AddrOf(_, ref subexpr) => {
1131                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1132                 record_rvalue_scope(visitor, &subexpr, blk_id);
1133             }
1134             hir::ExprKind::Struct(_, ref fields, _) => {
1135                 for field in fields {
1136                     record_rvalue_scope_if_borrow_expr(
1137                         visitor, &field.expr, blk_id);
1138                 }
1139             }
1140             hir::ExprKind::Array(ref subexprs) |
1141             hir::ExprKind::Tup(ref subexprs) => {
1142                 for subexpr in subexprs {
1143                     record_rvalue_scope_if_borrow_expr(
1144                         visitor, &subexpr, blk_id);
1145                 }
1146             }
1147             hir::ExprKind::Cast(ref subexpr, _) => {
1148                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1149             }
1150             hir::ExprKind::Block(ref block, _) => {
1151                 if let Some(ref subexpr) = block.expr {
1152                     record_rvalue_scope_if_borrow_expr(
1153                         visitor, &subexpr, blk_id);
1154                 }
1155             }
1156             _ => {}
1157         }
1158     }
1159
1160     /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1161     /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1162     /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1163     /// statement.
1164     ///
1165     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1166     /// `<rvalue>` as `blk_id`:
1167     ///
1168     ///     ET = *ET
1169     ///        | ET[...]
1170     ///        | ET.f
1171     ///        | (ET)
1172     ///        | <rvalue>
1173     ///
1174     /// Note: ET is intended to match "rvalues or places based on rvalues".
1175     fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1176                                      expr: &hir::Expr,
1177                                      blk_scope: Option<Scope>) {
1178         let mut expr = expr;
1179         loop {
1180             // Note: give all the expressions matching `ET` with the
1181             // extended temporary lifetime, not just the innermost rvalue,
1182             // because in codegen if we must compile e.g., `*rvalue()`
1183             // into a temporary, we request the temporary scope of the
1184             // outer expression.
1185             visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1186
1187             match expr.node {
1188                 hir::ExprKind::AddrOf(_, ref subexpr) |
1189                 hir::ExprKind::Unary(hir::UnDeref, ref subexpr) |
1190                 hir::ExprKind::Field(ref subexpr, _) |
1191                 hir::ExprKind::Index(ref subexpr, _) => {
1192                     expr = &subexpr;
1193                 }
1194                 _ => {
1195                     return;
1196                 }
1197             }
1198         }
1199     }
1200 }
1201
1202 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1203     /// Records the current parent (if any) as the parent of `child_scope`.
1204     /// Returns the depth of `child_scope`.
1205     fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth {
1206         let parent = self.cx.parent;
1207         self.scope_tree.record_scope_parent(child_scope, parent);
1208         // If `child_scope` has no parent, it must be the root node, and so has
1209         // a depth of 1. Otherwise, its depth is one more than its parent's.
1210         parent.map_or(1, |(_p, d)| d + 1)
1211     }
1212
1213     /// Records the current parent (if any) as the parent of `child_scope`,
1214     /// and sets `child_scope` as the new current parent.
1215     fn enter_scope(&mut self, child_scope: Scope) {
1216         let child_depth = self.record_child_scope(child_scope);
1217         self.cx.parent = Some((child_scope, child_depth));
1218     }
1219
1220     fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1221         // If node was previously marked as a terminating scope during the
1222         // recursive visit of its parent node in the AST, then we need to
1223         // account for the destruction scope representing the scope of
1224         // the destructors that run immediately after it completes.
1225         if self.terminating_scopes.contains(&id) {
1226             self.enter_scope(Scope { id, data: ScopeData::Destruction });
1227         }
1228         self.enter_scope(Scope { id, data: ScopeData::Node });
1229     }
1230 }
1231
1232 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1233     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1234         NestedVisitorMap::None
1235     }
1236
1237     fn visit_block(&mut self, b: &'tcx Block) {
1238         resolve_block(self, b);
1239     }
1240
1241     fn visit_body(&mut self, body: &'tcx hir::Body) {
1242         let body_id = body.id();
1243         let owner_id = self.tcx.hir().body_owner(body_id);
1244
1245         debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1246                owner_id,
1247                self.tcx.sess.source_map().span_to_string(body.value.span),
1248                body_id,
1249                self.cx.parent);
1250
1251         let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
1252         let outer_cx = self.cx;
1253         let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet::default());
1254         self.terminating_scopes.insert(body.value.hir_id.local_id);
1255
1256         if let Some(root_id) = self.cx.root_id {
1257             self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1258         }
1259         self.cx.root_id = Some(body.value.hir_id.local_id);
1260
1261         self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite });
1262         self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments });
1263
1264         // The arguments and `self` are parented to the fn.
1265         self.cx.var_parent = self.cx.parent.take();
1266         for argument in &body.arguments {
1267             self.visit_pat(&argument.pat);
1268         }
1269
1270         // The body of the every fn is a root scope.
1271         self.cx.parent = self.cx.var_parent;
1272         if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() {
1273             self.visit_expr(&body.value)
1274         } else {
1275             // Only functions have an outer terminating (drop) scope, while
1276             // temporaries in constant initializers may be 'static, but only
1277             // according to rvalue lifetime semantics, using the same
1278             // syntactical rules used for let initializers.
1279             //
1280             // e.g., in `let x = &f();`, the temporary holding the result from
1281             // the `f()` call lives for the entirety of the surrounding block.
1282             //
1283             // Similarly, `const X: ... = &f();` would have the result of `f()`
1284             // live for `'static`, implying (if Drop restrictions on constants
1285             // ever get lifted) that the value *could* have a destructor, but
1286             // it'd get leaked instead of the destructor running during the
1287             // evaluation of `X` (if at all allowed by CTFE).
1288             //
1289             // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1290             // would *not* let the `f()` temporary escape into an outer scope
1291             // (i.e., `'static`), which means that after `g` returns, it drops,
1292             // and all the associated destruction scope rules apply.
1293             self.cx.var_parent = None;
1294             resolve_local(self, None, Some(&body.value));
1295         }
1296
1297         if body.is_generator {
1298             self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1299         }
1300
1301         // Restore context we had at the start.
1302         self.expr_and_pat_count = outer_ec;
1303         self.cx = outer_cx;
1304         self.terminating_scopes = outer_ts;
1305     }
1306
1307     fn visit_arm(&mut self, a: &'tcx Arm) {
1308         resolve_arm(self, a);
1309     }
1310     fn visit_pat(&mut self, p: &'tcx Pat) {
1311         resolve_pat(self, p);
1312     }
1313     fn visit_stmt(&mut self, s: &'tcx Stmt) {
1314         resolve_stmt(self, s);
1315     }
1316     fn visit_expr(&mut self, ex: &'tcx Expr) {
1317         resolve_expr(self, ex);
1318     }
1319     fn visit_local(&mut self, l: &'tcx Local) {
1320         resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1321     }
1322 }
1323
1324 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1325     -> &'tcx ScopeTree
1326 {
1327     let closure_base_def_id = tcx.closure_base_def_id(def_id);
1328     if closure_base_def_id != def_id {
1329         return tcx.region_scope_tree(closure_base_def_id);
1330     }
1331
1332     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1333     let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by_by_hir_id(id) {
1334         let mut visitor = RegionResolutionVisitor {
1335             tcx,
1336             scope_tree: ScopeTree::default(),
1337             expr_and_pat_count: 0,
1338             cx: Context {
1339                 root_id: None,
1340                 parent: None,
1341                 var_parent: None,
1342             },
1343             terminating_scopes: Default::default(),
1344         };
1345
1346         let body = tcx.hir().body(body_id);
1347         visitor.scope_tree.root_body = Some(body.value.hir_id);
1348
1349         // If the item is an associated const or a method,
1350         // record its impl/trait parent, as it can also have
1351         // lifetime parameters free in this body.
1352         match tcx.hir().get_by_hir_id(id) {
1353             Node::ImplItem(_) |
1354             Node::TraitItem(_) => {
1355                 visitor.scope_tree.root_parent = Some(tcx.hir().get_parent_item(id));
1356             }
1357             _ => {}
1358         }
1359
1360         visitor.visit_body(body);
1361
1362         visitor.scope_tree
1363     } else {
1364         ScopeTree::default()
1365     };
1366
1367     tcx.arena.alloc(scope_tree)
1368 }
1369
1370 pub fn provide(providers: &mut Providers<'_>) {
1371     *providers = Providers {
1372         region_scope_tree,
1373         ..*providers
1374     };
1375 }
1376
1377 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
1378     fn hash_stable<W: StableHasherResult>(&self,
1379                                           hcx: &mut StableHashingContext<'a>,
1380                                           hasher: &mut StableHasher<W>) {
1381         let ScopeTree {
1382             root_body,
1383             root_parent,
1384             ref body_expr_count,
1385             ref parent_map,
1386             ref var_map,
1387             ref destruction_scopes,
1388             ref rvalue_scopes,
1389             ref closure_tree,
1390             ref yield_in_scope,
1391         } = *self;
1392
1393         hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1394             root_body.hash_stable(hcx, hasher);
1395             root_parent.hash_stable(hcx, hasher);
1396         });
1397
1398         body_expr_count.hash_stable(hcx, hasher);
1399         parent_map.hash_stable(hcx, hasher);
1400         var_map.hash_stable(hcx, hasher);
1401         destruction_scopes.hash_stable(hcx, hasher);
1402         rvalue_scopes.hash_stable(hcx, hasher);
1403         closure_tree.hash_stable(hcx, hasher);
1404         yield_in_scope.hash_stable(hcx, hasher);
1405     }
1406 }