]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/region.rs
Auto merge of #61203 - memoryruins:bare_trait_objects, r=Centril
[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         derive [HashStable]
157     }
158 }
159
160 // compilation error if size of `ScopeData` is not the same as a `u32`
161 static_assert_size!(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             if Some(param_owner_id) != self.root_parent {
662                 tcx.sess.delay_span_bug(
663                     DUMMY_SP,
664                     &format!("free_scope: {:?} not recognized by the \
665                               region scope tree for {:?} / {:?}",
666                              param_owner,
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))));
669             }
670
671             // The trait/impl lifetime is in scope for the method's body.
672             self.root_body.unwrap().local_id
673         });
674
675         Scope { id: scope, data: ScopeData::CallSite }
676     }
677
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)
681                                  -> Scope {
682         let param_owner = match fr.bound_region {
683             ty::BoundRegion::BrNamed(def_id, _) => {
684                 tcx.parent(def_id).unwrap()
685             }
686             _ => fr.scope
687         };
688
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);
692
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 }
696     }
697
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()
704     }
705
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,
710                                    scope: Scope,
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 {
715                 hir_id: expr_hir_id,
716                 result: None,
717                 expr_and_pat_count: 0,
718             };
719             visitor.visit_body(body);
720             if count >= visitor.result.unwrap() {
721                 Some(span)
722             } else {
723                 None
724             }
725         })
726     }
727
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)
733     }
734 }
735
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,
739                        _sp: Span) {
740     match visitor.cx.var_parent {
741         None => {
742             // this can happen in extern fn declarations like
743             //
744             // extern fn isalnum(c: c_int) -> c_int
745         }
746         Some((parent_scope, _)) =>
747             visitor.scope_tree.record_var_scope(var_id, parent_scope),
748     }
749 }
750
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);
753
754     let prev_cx = visitor.cx;
755
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:
759     //
760     //    quux({
761     //        let inner = ... (&bar()) ...;
762     //
763     //        (... (&foo()) ...) // (the tail expression)
764     //    }, other_argument());
765     //
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.
771     //
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.
780
781     visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
782     visitor.cx.var_parent = visitor.cx.parent;
783
784     {
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.)
789
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
799                     // parent.
800                     visitor.enter_scope(
801                         Scope {
802                             id: blk.hir_id.local_id,
803                             data: ScopeData::Remainder(FirstStatementIndex::new(i))
804                         }
805                     );
806                     visitor.cx.var_parent = visitor.cx.parent;
807                 }
808                 hir::StmtKind::Expr(..) |
809                 hir::StmtKind::Semi(..) => {}
810             }
811             visitor.visit_stmt(statement)
812         }
813         walk_list!(visitor, visit_expr, &blk.expr);
814     }
815
816     visitor.cx = prev_cx;
817 }
818
819 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
820     let prev_cx = visitor.cx;
821
822     visitor.enter_scope(
823         Scope {
824             id: arm.hir_id.local_id,
825             data: ScopeData::Node,
826         }
827     );
828     visitor.cx.var_parent = visitor.cx.parent;
829
830     visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
831
832     if let Some(hir::Guard::If(ref expr)) = arm.guard {
833         visitor.terminating_scopes.insert(expr.hir_id.local_id);
834     }
835
836     intravisit::walk_arm(visitor, arm);
837
838     visitor.cx = prev_cx;
839 }
840
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 });
843
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);
847     }
848
849     debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
850
851     intravisit::walk_pat(visitor, pat);
852
853     visitor.expr_and_pat_count += 1;
854
855     debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
856 }
857
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);
861
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);
868
869     let prev_parent = visitor.cx.parent;
870     visitor.enter_node_scope_with_dtor(stmt_id);
871
872     intravisit::walk_stmt(visitor, stmt);
873
874     visitor.cx.parent = prev_parent;
875 }
876
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);
879
880     let prev_cx = visitor.cx;
881     visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
882
883     {
884         let terminating_scopes = &mut visitor.terminating_scopes;
885         let mut terminating = |id: hir::ItemLocalId| {
886             terminating_scopes.insert(id);
887         };
888         match expr.node {
889             // Conditional or repeating scopes are always terminating
890             // scopes, meaning that temporaries cannot outlive them.
891             // This ensures fixed size stacks.
892
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);
900             }
901
902             hir::ExprKind::Loop(ref body, _, _) => {
903                 terminating(body.hir_id.local_id);
904             }
905
906             hir::ExprKind::While(ref expr, ref body, _) => {
907                 terminating(expr.hir_id.local_id);
908                 terminating(body.hir_id.local_id);
909             }
910
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);
915             }
916
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
920                 //
921                 // The lifetimes for a call or method call look as follows:
922                 //
923                 // call.id
924                 // - arg0.id
925                 // - ...
926                 // - argN.id
927                 // - call.callee_id
928                 //
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
934                 // important.
935                 //
936                 // record_superlifetime(new_cx, expr.callee_id);
937             }
938
939             _ => {}
940         }
941     }
942
943     match expr.node {
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);
949         }
950
951         _ => intravisit::walk_expr(visitor, expr)
952     }
953
954     visitor.expr_and_pat_count += 1;
955
956     debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
957
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 };
961         loop {
962             visitor.scope_tree.yield_in_scope.insert(scope,
963                 (expr.span, visitor.expr_and_pat_count));
964
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
971                 },
972                 None => break
973             }
974         }
975     }
976
977     visitor.cx = prev_cx;
978 }
979
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);
984
985     let blk_scope = visitor.cx.var_parent.map(|(p, _)| p);
986
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:
991     //
992     //     let ref x = HashMap::new();
993     //
994     // Because the hash map will be freed in the enclosing block.
995     //
996     // We express the rules more formally based on 3 grammars (defined
997     // fully in the helpers below that implement them):
998     //
999     // 1. `E&`, which matches expressions like `&<rvalue>` that
1000     //    own a pointer into the stack.
1001     //
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.)
1008     //
1009     // 3. `ET`, which matches both rvalues like `foo()` as well as places
1010     //    based on rvalues like `foo().x[2].y`.
1011     //
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:
1015     //
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)
1024     //
1025     // Here are some examples hopefully giving an intuition where each
1026     // rule comes into play and why:
1027     //
1028     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1029     // would have an extended lifetime, but not `foo()`.
1030     //
1031     // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1032     // lifetime.
1033     //
1034     // In some cases, multiple rules may apply (though not to the same
1035     // rvalue). For example:
1036     //
1037     //     let ref x = [&a(), &b()];
1038     //
1039     // Here, the expression `[...]` has an extended lifetime due to rule
1040     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1041     // due to rule C.
1042
1043     if let Some(expr) = init {
1044         record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1045
1046         if let Some(pat) = pat {
1047             if is_binding_pat(pat) {
1048                 record_rvalue_scope(visitor, &expr, blk_scope);
1049             }
1050         }
1051     }
1052
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);
1056     }
1057     if let Some(pat) = pat {
1058         visitor.visit_pat(pat);
1059     }
1060
1061     /// Returns `true` if `pat` match the `P&` non-terminal.
1062     ///
1063     ///     P& = ref X
1064     ///        | StructName { ..., P&, ... }
1065     ///        | VariantName(..., P&, ...)
1066     ///        | [ ..., P&, ... ]
1067     ///        | ( ..., P&, ... )
1068     ///        | box 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.
1072         //
1073         // This is not a problem. For example, consider
1074         //
1075         //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
1076         //
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).
1080         //
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):
1083         //
1084         //      let Foo { x, .. } = &Foo { x: ..., ... };
1085         //
1086         // in place of
1087         //
1088         //      let Foo { ref x, .. } = Foo { ... };
1089         //
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).
1093         match pat.node {
1094             PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1095             PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1096
1097             PatKind::Struct(_, ref field_pats, _) => {
1098                 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1099             }
1100
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))
1105             }
1106
1107             PatKind::TupleStruct(_, ref subpats, _) |
1108             PatKind::Tuple(ref subpats, _) => {
1109                 subpats.iter().any(|p| is_binding_pat(&p))
1110             }
1111
1112             PatKind::Box(ref subpat) => {
1113                 is_binding_pat(&subpat)
1114             }
1115
1116             _ => false,
1117         }
1118     }
1119
1120     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1121     ///
1122     ///     E& = & ET
1123     ///        | StructName { ..., f: E&, ... }
1124     ///        | [ ..., E&, ... ]
1125     ///        | ( ..., E&, ... )
1126     ///        | {...; E&}
1127     ///        | box E&
1128     ///        | E& as ...
1129     ///        | ( E& )
1130     fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1131         visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1132         expr: &hir::Expr,
1133         blk_id: Option<Scope>)
1134     {
1135         match expr.node {
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);
1139             }
1140             hir::ExprKind::Struct(_, ref fields, _) => {
1141                 for field in fields {
1142                     record_rvalue_scope_if_borrow_expr(
1143                         visitor, &field.expr, blk_id);
1144                 }
1145             }
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);
1151                 }
1152             }
1153             hir::ExprKind::Cast(ref subexpr, _) => {
1154                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1155             }
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);
1160                 }
1161             }
1162             _ => {}
1163         }
1164     }
1165
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`
1169     /// statement.
1170     ///
1171     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1172     /// `<rvalue>` as `blk_id`:
1173     ///
1174     ///     ET = *ET
1175     ///        | ET[...]
1176     ///        | ET.f
1177     ///        | (ET)
1178     ///        | <rvalue>
1179     ///
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>,
1182                                      expr: &hir::Expr,
1183                                      blk_scope: Option<Scope>) {
1184         let mut expr = expr;
1185         loop {
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);
1192
1193             match expr.node {
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, _) => {
1198                     expr = &subexpr;
1199                 }
1200                 _ => {
1201                     return;
1202                 }
1203             }
1204         }
1205     }
1206 }
1207
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)
1217     }
1218
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));
1224     }
1225
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 });
1233         }
1234         self.enter_scope(Scope { id, data: ScopeData::Node });
1235     }
1236 }
1237
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
1241     }
1242
1243     fn visit_block(&mut self, b: &'tcx Block) {
1244         resolve_block(self, b);
1245     }
1246
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);
1250
1251         debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1252                owner_id,
1253                self.tcx.sess.source_map().span_to_string(body.value.span),
1254                body_id,
1255                self.cx.parent);
1256
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);
1261
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);
1264         }
1265         self.cx.root_id = Some(body.value.hir_id.local_id);
1266
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 });
1269
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);
1274         }
1275
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)
1280         } else {
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.
1285             //
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.
1288             //
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).
1294             //
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));
1301         }
1302
1303         if body.is_generator {
1304             self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1305         }
1306
1307         // Restore context we had at the start.
1308         self.expr_and_pat_count = outer_ec;
1309         self.cx = outer_cx;
1310         self.terminating_scopes = outer_ts;
1311     }
1312
1313     fn visit_arm(&mut self, a: &'tcx Arm) {
1314         resolve_arm(self, a);
1315     }
1316     fn visit_pat(&mut self, p: &'tcx Pat) {
1317         resolve_pat(self, p);
1318     }
1319     fn visit_stmt(&mut self, s: &'tcx Stmt) {
1320         resolve_stmt(self, s);
1321     }
1322     fn visit_expr(&mut self, ex: &'tcx Expr) {
1323         resolve_expr(self, ex);
1324     }
1325     fn visit_local(&mut self, l: &'tcx Local) {
1326         resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1327     }
1328 }
1329
1330 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1331     -> &'tcx ScopeTree
1332 {
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);
1336     }
1337
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 {
1341             tcx,
1342             scope_tree: ScopeTree::default(),
1343             expr_and_pat_count: 0,
1344             cx: Context {
1345                 root_id: None,
1346                 parent: None,
1347                 var_parent: None,
1348             },
1349             terminating_scopes: Default::default(),
1350         };
1351
1352         let body = tcx.hir().body(body_id);
1353         visitor.scope_tree.root_body = Some(body.value.hir_id);
1354
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) {
1359             Node::ImplItem(_) |
1360             Node::TraitItem(_) => {
1361                 visitor.scope_tree.root_parent = Some(tcx.hir().get_parent_item(id));
1362             }
1363             _ => {}
1364         }
1365
1366         visitor.visit_body(body);
1367
1368         visitor.scope_tree
1369     } else {
1370         ScopeTree::default()
1371     };
1372
1373     tcx.arena.alloc(scope_tree)
1374 }
1375
1376 pub fn provide(providers: &mut Providers<'_>) {
1377     *providers = Providers {
1378         region_scope_tree,
1379         ..*providers
1380     };
1381 }
1382
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>) {
1387         let ScopeTree {
1388             root_body,
1389             root_parent,
1390             ref body_expr_count,
1391             ref parent_map,
1392             ref var_map,
1393             ref destruction_scopes,
1394             ref rvalue_scopes,
1395             ref closure_tree,
1396             ref yield_in_scope,
1397         } = *self;
1398
1399         hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1400             root_body.hash_stable(hcx, hasher);
1401             root_parent.hash_stable(hcx, hasher);
1402         });
1403
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);
1411     }
1412 }