]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/region.rs
b1d6cce11f438f3aeabcbe8a16bda26146965735
[rust.git] / src / librustc / middle / region.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This file builds up the `ScopeTree`, which describes
12 //! the parent links in the region hierarchy.
13 //!
14 //! For more information about how MIR-based region-checking works,
15 //! see the [rustc guide].
16 //!
17 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir/borrowck.html
18
19 use ich::{StableHashingContext, NodeIdHashingMode};
20 use util::nodemap::{FxHashMap, FxHashSet};
21 use ty;
22
23 use std::mem;
24 use rustc_data_structures::sync::Lrc;
25 use syntax::source_map;
26 use syntax::ast;
27 use syntax_pos::{Span, DUMMY_SP};
28 use ty::TyCtxt;
29 use ty::query::Providers;
30
31 use hir;
32 use hir::Node;
33 use hir::def_id::DefId;
34 use hir::intravisit::{self, Visitor, NestedVisitorMap};
35 use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
36 use rustc_data_structures::indexed_vec::Idx;
37 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
38                                            StableHasherResult};
39
40 /// Scope represents a statically-describable scope that can be
41 /// used to bound the lifetime/region for values.
42 ///
43 /// `Node(node_id)`: Any AST node that has any scope at all has the
44 /// `Node(node_id)` scope. Other variants represent special cases not
45 /// immediately derivable from the abstract syntax tree structure.
46 ///
47 /// `DestructionScope(node_id)` represents the scope of destructors
48 /// implicitly-attached to `node_id` that run immediately after the
49 /// expression for `node_id` itself. Not every AST node carries a
50 /// `DestructionScope`, but those that are `terminating_scopes` do;
51 /// see discussion with `ScopeTree`.
52 ///
53 /// `Remainder(BlockRemainder { block, statement_index })` represents
54 /// the scope of user code running immediately after the initializer
55 /// expression for the indexed statement, until the end of the block.
56 ///
57 /// So: the following code can be broken down into the scopes beneath:
58 ///
59 /// ```text
60 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y)  }   ) ;
61 ///
62 ///                                                              +-+ (D12.)
63 ///                                                        +-+       (D11.)
64 ///                                              +---------+         (R10.)
65 ///                                              +-+                  (D9.)
66 ///                                   +----------+                    (M8.)
67 ///                                 +----------------------+          (R7.)
68 ///                                 +-+                               (D6.)
69 ///                      +----------+                                 (M5.)
70 ///                    +-----------------------------------+          (M4.)
71 ///         +--------------------------------------------------+      (M3.)
72 ///         +--+                                                      (M2.)
73 /// +-----------------------------------------------------------+     (M1.)
74 ///
75 ///  (M1.): Node scope of the whole `let a = ...;` statement.
76 ///  (M2.): Node scope of the `f()` expression.
77 ///  (M3.): Node scope of the `f().g(..)` expression.
78 ///  (M4.): Node scope of the block labeled `'b:`.
79 ///  (M5.): Node scope of the `let x = d();` statement
80 ///  (D6.): DestructionScope for temporaries created during M5.
81 ///  (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
82 ///  (M8.): Node scope of the `let y = d();` statement.
83 ///  (D9.): DestructionScope for temporaries created during M8.
84 /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
85 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
86 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
87 /// ```
88 ///
89 /// Note that while the above picture shows the destruction scopes
90 /// as following their corresponding node scopes, in the internal
91 /// data structures of the compiler the destruction scopes are
92 /// represented as enclosing parents. This is sound because we use the
93 /// enclosing parent relationship just to ensure that referenced
94 /// values live long enough; phrased another way, the starting point
95 /// of each range is not really the important thing in the above
96 /// picture, but rather the ending point.
97 ///
98 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
99 /// placate the same deriving in `ty::FreeRegion`, but we may want to
100 /// actually attach a more meaningful ordering to scopes than the one
101 /// generated via deriving here.
102 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
103 pub struct Scope {
104     pub(crate) id: hir::ItemLocalId,
105     pub(crate) data: ScopeData,
106 }
107
108 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
109 pub enum ScopeData {
110     Node,
111
112     // Scope of the call-site for a function or closure
113     // (outlives the arguments as well as the body).
114     CallSite,
115
116     // Scope of arguments passed to a function or closure
117     // (they outlive its body).
118     Arguments,
119
120     // Scope of destructors for temporaries of node-id.
121     Destruction,
122
123     // Scope following a `let id = expr;` binding in a block.
124     Remainder(FirstStatementIndex)
125 }
126
127 /// Represents a subscope of `block` for a binding that is introduced
128 /// by `block.stmts[first_statement_index]`. Such subscopes represent
129 /// a suffix of the block. Note that each subscope does not include
130 /// the initializer expression, if any, for the statement indexed by
131 /// `first_statement_index`.
132 ///
133 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
134 ///
135 /// * the subscope with `first_statement_index == 0` is scope of both
136 ///   `a` and `b`; it does not include EXPR_1, but does include
137 ///   everything after that first `let`. (If you want a scope that
138 ///   includes EXPR_1 as well, then do not use `Scope::Remainder`,
139 ///   but instead another `Scope` that encompasses the whole block,
140 ///   e.g. `Scope::Node`.
141 ///
142 /// * the subscope with `first_statement_index == 1` is scope of `c`,
143 ///   and thus does not include EXPR_2, but covers the `...`.
144
145 newtype_index! {
146     pub struct FirstStatementIndex { .. }
147 }
148
149 impl_stable_hash_for!(struct ::middle::region::FirstStatementIndex { private });
150
151 // compilation error if size of `ScopeData` is not the same as a `u32`
152 #[allow(dead_code)]
153 // only works on stage 1 when the rustc_layout_scalar_valid_range attribute actually exists
154 #[cfg(not(stage0))]
155 static ASSERT: () = [()][!(mem::size_of::<ScopeData>() == 4) as usize];
156
157 #[allow(non_snake_case)]
158 impl Scope {
159     #[inline]
160     pub fn data(self) -> ScopeData {
161         self.data
162         }
163
164     #[inline]
165     pub fn new(id: hir::ItemLocalId, data: ScopeData) -> Self {
166         Scope { id, data }
167     }
168
169     #[inline]
170     pub fn Node(id: hir::ItemLocalId) -> Self {
171         Self::new(id, ScopeData::Node)
172     }
173
174     #[inline]
175     pub fn CallSite(id: hir::ItemLocalId) -> Self {
176         Self::new(id, ScopeData::CallSite)
177     }
178
179     #[inline]
180     pub fn Arguments(id: hir::ItemLocalId) -> Self {
181         Self::new(id, ScopeData::Arguments)
182     }
183
184     #[inline]
185     pub fn Destruction(id: hir::ItemLocalId) -> Self {
186         Self::new(id, ScopeData::Destruction)
187     }
188
189     #[inline]
190     pub fn Remainder(
191         id: hir::ItemLocalId,
192         first: FirstStatementIndex,
193     ) -> Self {
194         Self::new(id, ScopeData::Remainder(first))
195     }
196 }
197
198
199 impl Scope {
200     /// Returns a item-local id associated with this scope.
201     ///
202     /// NB: likely to be replaced as API is refined; e.g. pnkfelix
203     /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
204     pub fn item_local_id(&self) -> hir::ItemLocalId {
205         self.id
206     }
207
208     pub fn node_id(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> ast::NodeId {
209         match scope_tree.root_body {
210             Some(hir_id) => {
211                 tcx.hir.hir_to_node_id(hir::HirId {
212                     owner: hir_id.owner,
213                     local_id: self.item_local_id()
214                 })
215             }
216             None => ast::DUMMY_NODE_ID
217         }
218     }
219
220     /// Returns the span of this Scope.  Note that in general the
221     /// returned span may not correspond to the span of any node id in
222     /// the AST.
223     pub fn span(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> Span {
224         let node_id = self.node_id(tcx, scope_tree);
225         if node_id == ast::DUMMY_NODE_ID {
226             return DUMMY_SP;
227         }
228         let span = tcx.hir.span(node_id);
229         if let ScopeData::Remainder(first_statement_index) = self.data() {
230             if let Node::Block(ref blk) = tcx.hir.get(node_id) {
231                 // Want span for scope starting after the
232                 // indexed statement and ending at end of
233                 // `blk`; reuse span of `blk` and shift `lo`
234                 // forward to end of indexed statement.
235                 //
236                 // (This is the special case aluded to in the
237                 // doc-comment for this method)
238
239                 let stmt_span = blk.stmts[first_statement_index.index()].span;
240
241                 // To avoid issues with macro-generated spans, the span
242                 // of the statement must be nested in that of the block.
243                 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
244                     return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
245                 }
246             }
247          }
248          span
249     }
250 }
251
252 pub type ScopeDepth = u32;
253
254 /// The region scope tree encodes information about region relationships.
255 #[derive(Default, Debug)]
256 pub struct ScopeTree {
257     /// If not empty, this body is the root of this region hierarchy.
258     root_body: Option<hir::HirId>,
259
260     /// The parent of the root body owner, if the latter is an
261     /// an associated const or method, as impls/traits can also
262     /// have lifetime parameters free in this body.
263     root_parent: Option<ast::NodeId>,
264
265     /// `parent_map` maps from a scope id to the enclosing scope id;
266     /// this is usually corresponding to the lexical nesting, though
267     /// in the case of closures the parent scope is the innermost
268     /// conditional expression or repeating block. (Note that the
269     /// enclosing scope id for the block associated with a closure is
270     /// the closure itself.)
271     parent_map: FxHashMap<Scope, (Scope, ScopeDepth)>,
272
273     /// `var_map` maps from a variable or binding id to the block in
274     /// which that variable is declared.
275     var_map: FxHashMap<hir::ItemLocalId, Scope>,
276
277     /// maps from a node-id to the associated destruction scope (if any)
278     destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
279
280     /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
281     /// larger than the default. The map goes from the expression id
282     /// to the cleanup scope id. For rvalues not present in this
283     /// table, the appropriate cleanup scope is the innermost
284     /// enclosing statement, conditional expression, or repeating
285     /// block (see `terminating_scopes`).
286     /// In constants, None is used to indicate that certain expressions
287     /// escape into 'static and should have no local cleanup scope.
288     rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
289
290     /// Encodes the hierarchy of fn bodies. Every fn body (including
291     /// closures) forms its own distinct region hierarchy, rooted in
292     /// the block that is the fn body. This map points from the id of
293     /// that root block to the id of the root block for the enclosing
294     /// fn, if any. Thus the map structures the fn bodies into a
295     /// hierarchy based on their lexical mapping. This is used to
296     /// handle the relationships between regions in a fn and in a
297     /// closure defined by that fn. See the "Modeling closures"
298     /// section of the README in infer::region_constraints for
299     /// more details.
300     closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
301
302     /// If there are any `yield` nested within a scope, this map
303     /// stores the `Span` of the last one and its index in the
304     /// postorder of the Visitor traversal on the HIR.
305     ///
306     /// HIR Visitor postorder indexes might seem like a peculiar
307     /// thing to care about. but it turns out that HIR bindings
308     /// and the temporary results of HIR expressions are never
309     /// storage-live at the end of HIR nodes with postorder indexes
310     /// lower than theirs, and therefore don't need to be suspended
311     /// at yield-points at these indexes.
312     ///
313     /// For an example, suppose we have some code such as:
314     /// ```rust,ignore (example)
315     ///     foo(f(), yield y, bar(g()))
316     /// ```
317     ///
318     /// With the HIR tree (calls numbered for expository purposes)
319     /// ```
320     ///     Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
321     /// ```
322     ///
323     /// Obviously, the result of `f()` was created before the yield
324     /// (and therefore needs to be kept valid over the yield) while
325     /// the result of `g()` occurs after the yield (and therefore
326     /// doesn't). If we want to infer that, we can look at the
327     /// postorder traversal:
328     /// ```plain,ignore
329     ///     `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
330     /// ```
331     ///
332     /// In which we can easily see that `Call#1` occurs before the yield,
333     /// and `Call#3` after it.
334     ///
335     /// To see that this method works, consider:
336     ///
337     /// Let `D` be our binding/temporary and `U` be our other HIR node, with
338     /// `HIR-postorder(U) < HIR-postorder(D)` (in our example, U would be
339     /// the yield and D would be one of the calls). Let's show that
340     /// `D` is storage-dead at `U`.
341     ///
342     /// Remember that storage-live/storage-dead refers to the state of
343     /// the *storage*, and does not consider moves/drop flags.
344     ///
345     /// Then:
346     ///     1. From the ordering guarantee of HIR visitors (see
347     ///     `rustc::hir::intravisit`), `D` does not dominate `U`.
348     ///     2. Therefore, `D` is *potentially* storage-dead at `U` (because
349     ///     we might visit `U` without ever getting to `D`).
350     ///     3. However, we guarantee that at each HIR point, each
351     ///     binding/temporary is always either always storage-live
352     ///     or always storage-dead. This is what is being guaranteed
353     ///     by `terminating_scopes` including all blocks where the
354     ///     count of executions is not guaranteed.
355     ///     4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
356     ///     QED.
357     ///
358     /// I don't think this property relies on `3.` in an essential way - it
359     /// is probably still correct even if we have "unrestricted" terminating
360     /// scopes. However, why use the complicated proof when a simple one
361     /// works?
362     ///
363     /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
364     /// might seem that a `box` expression creates a `Box<T>` temporary
365     /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
366     /// be true in the MIR desugaring, but it is not important in the semantics.
367     ///
368     /// The reason is that semantically, until the `box` expression returns,
369     /// the values are still owned by their containing expressions. So
370     /// we'll see that `&x`.
371     yield_in_scope: FxHashMap<Scope, (Span, usize)>,
372
373     /// The number of visit_expr and visit_pat calls done in the body.
374     /// Used to sanity check visit_expr/visit_pat call count when
375     /// calculating generator interiors.
376     body_expr_count: FxHashMap<hir::BodyId, usize>,
377 }
378
379 #[derive(Debug, Copy, Clone)]
380 pub struct Context {
381     /// the root of the current region tree. This is typically the id
382     /// of the innermost fn body. Each fn forms its own disjoint tree
383     /// in the region hierarchy. These fn bodies are themselves
384     /// arranged into a tree. See the "Modeling closures" section of
385     /// the README in infer::region_constraints for more
386     /// details.
387     root_id: Option<hir::ItemLocalId>,
388
389     /// The scope that contains any new variables declared, plus its depth in
390     /// the scope tree.
391     var_parent: Option<(Scope, ScopeDepth)>,
392
393     /// Region parent of expressions, etc., plus its depth in the scope tree.
394     parent: Option<(Scope, ScopeDepth)>,
395 }
396
397 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
398     tcx: TyCtxt<'a, 'tcx, 'tcx>,
399
400     // The number of expressions and patterns visited in the current body
401     expr_and_pat_count: usize,
402
403     // Generated scope tree:
404     scope_tree: ScopeTree,
405
406     cx: Context,
407
408     /// `terminating_scopes` is a set containing the ids of each
409     /// statement, or conditional/repeating expression. These scopes
410     /// are calling "terminating scopes" because, when attempting to
411     /// find the scope of a temporary, by default we search up the
412     /// enclosing scopes until we encounter the terminating scope. A
413     /// conditional/repeating expression is one which is not
414     /// guaranteed to execute exactly once upon entering the parent
415     /// scope. This could be because the expression only executes
416     /// conditionally, such as the expression `b` in `a && b`, or
417     /// because the expression may execute many times, such as a loop
418     /// body. The reason that we distinguish such expressions is that,
419     /// upon exiting the parent scope, we cannot statically know how
420     /// many times the expression executed, and thus if the expression
421     /// creates temporaries we cannot know statically how many such
422     /// temporaries we would have to cleanup. Therefore we ensure that
423     /// the temporaries never outlast the conditional/repeating
424     /// expression, preventing the need for dynamic checks and/or
425     /// arbitrary amounts of stack space. Terminating scopes end
426     /// up being contained in a DestructionScope that contains the
427     /// destructor's execution.
428     terminating_scopes: FxHashSet<hir::ItemLocalId>,
429 }
430
431 struct ExprLocatorVisitor {
432     hir_id: hir::HirId,
433     result: Option<usize>,
434     expr_and_pat_count: usize,
435 }
436
437 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor
438 // since `expr_count` is compared against the results there.
439 impl<'tcx> Visitor<'tcx> for ExprLocatorVisitor {
440     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
441         NestedVisitorMap::None
442     }
443
444     fn visit_pat(&mut self, pat: &'tcx Pat) {
445         intravisit::walk_pat(self, pat);
446
447         self.expr_and_pat_count += 1;
448
449         if pat.hir_id == self.hir_id {
450             self.result = Some(self.expr_and_pat_count);
451         }
452     }
453
454     fn visit_expr(&mut self, expr: &'tcx Expr) {
455         debug!("ExprLocatorVisitor - pre-increment {} expr = {:?}",
456                self.expr_and_pat_count,
457                expr);
458
459         intravisit::walk_expr(self, expr);
460
461         self.expr_and_pat_count += 1;
462
463         debug!("ExprLocatorVisitor - post-increment {} expr = {:?}",
464                self.expr_and_pat_count,
465                expr);
466
467         if expr.hir_id == self.hir_id {
468             self.result = Some(self.expr_and_pat_count);
469         }
470     }
471 }
472
473 impl<'tcx> ScopeTree {
474     pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) {
475         debug!("{:?}.parent = {:?}", child, parent);
476
477         if let Some(p) = parent {
478             let prev = self.parent_map.insert(child, p);
479             assert!(prev.is_none());
480         }
481
482         // record the destruction scopes for later so we can query them
483         if let ScopeData::Destruction = child.data() {
484             self.destruction_scopes.insert(child.item_local_id(), child);
485         }
486     }
487
488     pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) {
489         for (&child, &parent) in &self.parent_map {
490             e(child, parent.0)
491         }
492     }
493
494     pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) {
495         for (child, &parent) in self.var_map.iter() {
496             e(child, parent)
497         }
498     }
499
500     pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
501         self.destruction_scopes.get(&n).cloned()
502     }
503
504     /// Records that `sub_closure` is defined within `sup_closure`. These ids
505     /// should be the id of the block that is the fn body, which is
506     /// also the root of the region hierarchy for that fn.
507     fn record_closure_parent(&mut self,
508                              sub_closure: hir::ItemLocalId,
509                              sup_closure: hir::ItemLocalId) {
510         debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
511                sub_closure, sup_closure);
512         assert!(sub_closure != sup_closure);
513         let previous = self.closure_tree.insert(sub_closure, sup_closure);
514         assert!(previous.is_none());
515     }
516
517     fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
518         debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
519         assert!(var != lifetime.item_local_id());
520         self.var_map.insert(var, lifetime);
521     }
522
523     fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
524         debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
525         if let Some(lifetime) = lifetime {
526             assert!(var != lifetime.item_local_id());
527         }
528         self.rvalue_scopes.insert(var, lifetime);
529     }
530
531     pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
532         //! Returns the narrowest scope that encloses `id`, if any.
533         self.parent_map.get(&id).cloned().map(|(p, _)| p)
534     }
535
536     #[allow(dead_code)] // used in cfg
537     pub fn encl_scope(&self, id: Scope) -> Scope {
538         //! Returns the narrowest scope that encloses `id`, if any.
539         self.opt_encl_scope(id).unwrap()
540     }
541
542     /// Returns the lifetime of the local variable `var_id`
543     pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
544         match self.var_map.get(&var_id) {
545             Some(&r) => r,
546             None => { bug!("no enclosing scope for id {:?}", var_id); }
547         }
548     }
549
550     pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
551         //! Returns the scope when temp created by expr_id will be cleaned up
552
553         // check for a designated rvalue scope
554         if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
555             debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
556             return s;
557         }
558
559         // else, locate the innermost terminating scope
560         // if there's one. Static items, for instance, won't
561         // have an enclosing scope, hence no scope will be
562         // returned.
563         let mut id = Scope::Node(expr_id);
564
565         while let Some(&(p, _)) = self.parent_map.get(&id) {
566             match p.data() {
567                 ScopeData::Destruction => {
568                     debug!("temporary_scope({:?}) = {:?} [enclosing]",
569                            expr_id, id);
570                     return Some(id);
571                 }
572                 _ => id = p
573             }
574         }
575
576         debug!("temporary_scope({:?}) = None", expr_id);
577         return None;
578     }
579
580     pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
581         //! Returns the lifetime of the variable `id`.
582
583         let scope = ty::ReScope(self.var_scope(id));
584         debug!("var_region({:?}) = {:?}", id, scope);
585         scope
586     }
587
588     pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope)
589                             -> bool {
590         self.is_subscope_of(scope1, scope2) ||
591         self.is_subscope_of(scope2, scope1)
592     }
593
594     /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
595     /// otherwise.
596     pub fn is_subscope_of(&self,
597                           subscope: Scope,
598                           superscope: Scope)
599                           -> bool {
600         let mut s = subscope;
601         debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
602         while superscope != s {
603             match self.opt_encl_scope(s) {
604                 None => {
605                     debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
606                            subscope, superscope, s);
607                     return false;
608                 }
609                 Some(scope) => s = scope
610             }
611         }
612
613         debug!("is_subscope_of({:?}, {:?})=true",
614                subscope, superscope);
615
616         return true;
617     }
618
619     /// Returns the id of the innermost containing body
620     pub fn containing_body(&self, mut scope: Scope)-> Option<hir::ItemLocalId> {
621         loop {
622             if let ScopeData::CallSite = scope.data() {
623                 return Some(scope.item_local_id());
624             }
625
626             match self.opt_encl_scope(scope) {
627                 None => return None,
628                 Some(parent) => scope = parent,
629             }
630         }
631     }
632
633     /// Finds the nearest common ancestor of two scopes.  That is, finds the
634     /// smallest scope which is greater than or equal to both `scope_a` and
635     /// `scope_b`.
636     pub fn nearest_common_ancestor(&self, scope_a: Scope, scope_b: Scope) -> Scope {
637         if scope_a == scope_b { return scope_a; }
638
639         let mut a = scope_a;
640         let mut b = scope_b;
641
642         // Get the depth of each scope's parent. If either scope has no parent,
643         // it must be the root, which means we can stop immediately because the
644         // root must be the nearest common ancestor. (In practice, this is
645         // moderately common.)
646         let (parent_a, parent_a_depth) = match self.parent_map.get(&a) {
647             Some(pd) => *pd,
648             None => return a,
649         };
650         let (parent_b, parent_b_depth) = match self.parent_map.get(&b) {
651             Some(pd) => *pd,
652             None => return b,
653         };
654
655         if parent_a_depth > parent_b_depth {
656             // `a` is lower than `b`. Move `a` up until it's at the same depth
657             // as `b`. The first move up is trivial because we already found
658             // `parent_a` above; the loop does the remaining N-1 moves.
659             a = parent_a;
660             for _ in 0..(parent_a_depth - parent_b_depth - 1) {
661                 a = self.parent_map.get(&a).unwrap().0;
662             }
663         } else if parent_b_depth > parent_a_depth {
664             // `b` is lower than `a`.
665             b = parent_b;
666             for _ in 0..(parent_b_depth - parent_a_depth - 1) {
667                 b = self.parent_map.get(&b).unwrap().0;
668             }
669         } else {
670             // Both scopes are at the same depth, and we know they're not equal
671             // because that case was tested for at the top of this function. So
672             // we can trivially move them both up one level now.
673             assert!(parent_a_depth != 0);
674             a = parent_a;
675             b = parent_b;
676         }
677
678         // Now both scopes are at the same level. We move upwards in lockstep
679         // until they match. In practice, this loop is almost always executed
680         // zero times because `a` is almost always a direct ancestor of `b` or
681         // vice versa.
682         while a != b {
683             a = self.parent_map.get(&a).unwrap().0;
684             b = self.parent_map.get(&b).unwrap().0;
685         };
686
687         a
688     }
689
690     /// Assuming that the provided region was defined within this `ScopeTree`,
691     /// returns the outermost `Scope` that the region outlives.
692     pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
693                                        br: &ty::EarlyBoundRegion)
694                                        -> Scope {
695         let param_owner = tcx.parent_def_id(br.def_id).unwrap();
696
697         let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
698         let scope = tcx.hir.maybe_body_owned_by(param_owner_id).map(|body_id| {
699             tcx.hir.body(body_id).value.hir_id.local_id
700         }).unwrap_or_else(|| {
701             // The lifetime was defined on node that doesn't own a body,
702             // which in practice can only mean a trait or an impl, that
703             // is the parent of a method, and that is enforced below.
704             assert_eq!(Some(param_owner_id), self.root_parent,
705                        "free_scope: {:?} not recognized by the \
706                         region scope tree for {:?} / {:?}",
707                        param_owner,
708                        self.root_parent.map(|id| tcx.hir.local_def_id(id)),
709                        self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
710
711             // The trait/impl lifetime is in scope for the method's body.
712             self.root_body.unwrap().local_id
713         });
714
715         Scope::CallSite(scope)
716     }
717
718     /// Assuming that the provided region was defined within this `ScopeTree`,
719     /// returns the outermost `Scope` that the region outlives.
720     pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
721                                  -> Scope {
722         let param_owner = match fr.bound_region {
723             ty::BoundRegion::BrNamed(def_id, _) => {
724                 tcx.parent_def_id(def_id).unwrap()
725             }
726             _ => fr.scope
727         };
728
729         // Ensure that the named late-bound lifetimes were defined
730         // on the same function that they ended up being freed in.
731         assert_eq!(param_owner, fr.scope);
732
733         let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
734         let body_id = tcx.hir.body_owned_by(param_owner_id);
735         Scope::CallSite(tcx.hir.body(body_id).value.hir_id.local_id)
736     }
737
738     /// Checks whether the given scope contains a `yield`. If so,
739     /// returns `Some((span, expr_count))` with the span of a yield we found and
740     /// the number of expressions and patterns appearing before the `yield` in the body + 1.
741     /// If there a are multiple yields in a scope, the one with the highest number is returned.
742     pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
743         self.yield_in_scope.get(&scope).cloned()
744     }
745
746     /// Checks whether the given scope contains a `yield` and if that yield could execute
747     /// after `expr`. If so, it returns the span of that `yield`.
748     /// `scope` must be inside the body.
749     pub fn yield_in_scope_for_expr(&self,
750                                    scope: Scope,
751                                    expr_hir_id: hir::HirId,
752                                    body: &'tcx hir::Body) -> Option<Span> {
753         self.yield_in_scope(scope).and_then(|(span, count)| {
754             let mut visitor = ExprLocatorVisitor {
755                 hir_id: expr_hir_id,
756                 result: None,
757                 expr_and_pat_count: 0,
758             };
759             visitor.visit_body(body);
760             if count >= visitor.result.unwrap() {
761                 Some(span)
762             } else {
763                 None
764             }
765         })
766     }
767
768     /// Gives the number of expressions visited in a body.
769     /// Used to sanity check visit_expr call count when
770     /// calculating generator interiors.
771     pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
772         self.body_expr_count.get(&body_id).map(|r| *r)
773     }
774 }
775
776 /// Records the lifetime of a local variable as `cx.var_parent`
777 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
778                        var_id: hir::ItemLocalId,
779                        _sp: Span) {
780     match visitor.cx.var_parent {
781         None => {
782             // this can happen in extern fn declarations like
783             //
784             // extern fn isalnum(c: c_int) -> c_int
785         }
786         Some((parent_scope, _)) =>
787             visitor.scope_tree.record_var_scope(var_id, parent_scope),
788     }
789 }
790
791 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
792     debug!("resolve_block(blk.id={:?})", blk.id);
793
794     let prev_cx = visitor.cx;
795
796     // We treat the tail expression in the block (if any) somewhat
797     // differently from the statements. The issue has to do with
798     // temporary lifetimes. Consider the following:
799     //
800     //    quux({
801     //        let inner = ... (&bar()) ...;
802     //
803     //        (... (&foo()) ...) // (the tail expression)
804     //    }, other_argument());
805     //
806     // Each of the statements within the block is a terminating
807     // scope, and thus a temporary (e.g. the result of calling
808     // `bar()` in the initializer expression for `let inner = ...;`)
809     // will be cleaned up immediately after its corresponding
810     // statement (i.e. `let inner = ...;`) executes.
811     //
812     // On the other hand, temporaries associated with evaluating the
813     // tail expression for the block are assigned lifetimes so that
814     // they will be cleaned up as part of the terminating scope
815     // *surrounding* the block expression. Here, the terminating
816     // scope for the block expression is the `quux(..)` call; so
817     // those temporaries will only be cleaned up *after* both
818     // `other_argument()` has run and also the call to `quux(..)`
819     // itself has returned.
820
821     visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
822     visitor.cx.var_parent = visitor.cx.parent;
823
824     {
825         // This block should be kept approximately in sync with
826         // `intravisit::walk_block`. (We manually walk the block, rather
827         // than call `walk_block`, in order to maintain precise
828         // index information.)
829
830         for (i, statement) in blk.stmts.iter().enumerate() {
831             if let hir::StmtKind::Decl(..) = statement.node {
832                 // Each StmtKind::Decl introduces a subscope for bindings
833                 // introduced by the declaration; this subscope covers
834                 // a suffix of the block . Each subscope in a block
835                 // has the previous subscope in the block as a parent,
836                 // except for the first such subscope, which has the
837                 // block itself as a parent.
838                 visitor.enter_scope(
839                     Scope::Remainder(blk.hir_id.local_id, FirstStatementIndex::new(i))
840                 );
841                 visitor.cx.var_parent = visitor.cx.parent;
842             }
843             visitor.visit_stmt(statement)
844         }
845         walk_list!(visitor, visit_expr, &blk.expr);
846     }
847
848     visitor.cx = prev_cx;
849 }
850
851 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
852     visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
853
854     if let Some(ref g) = arm.guard {
855         match g {
856             hir::Guard::If(ref expr) => visitor.terminating_scopes.insert(expr.hir_id.local_id),
857         };
858     }
859
860     intravisit::walk_arm(visitor, arm);
861 }
862
863 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
864     visitor.record_child_scope(Scope::Node(pat.hir_id.local_id));
865
866     // If this is a binding then record the lifetime of that binding.
867     if let PatKind::Binding(..) = pat.node {
868         record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
869     }
870
871     debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
872
873     intravisit::walk_pat(visitor, pat);
874
875     visitor.expr_and_pat_count += 1;
876
877     debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
878 }
879
880 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
881     let stmt_id = visitor.tcx.hir.node_to_hir_id(stmt.node.id()).local_id;
882     debug!("resolve_stmt(stmt.id={:?})", stmt_id);
883
884     // Every statement will clean up the temporaries created during
885     // execution of that statement. Therefore each statement has an
886     // associated destruction scope that represents the scope of the
887     // statement plus its destructors, and thus the scope for which
888     // regions referenced by the destructors need to survive.
889     visitor.terminating_scopes.insert(stmt_id);
890
891     let prev_parent = visitor.cx.parent;
892     visitor.enter_node_scope_with_dtor(stmt_id);
893
894     intravisit::walk_stmt(visitor, stmt);
895
896     visitor.cx.parent = prev_parent;
897 }
898
899 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
900     debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr);
901
902     let prev_cx = visitor.cx;
903     visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
904
905     {
906         let terminating_scopes = &mut visitor.terminating_scopes;
907         let mut terminating = |id: hir::ItemLocalId| {
908             terminating_scopes.insert(id);
909         };
910         match expr.node {
911             // Conditional or repeating scopes are always terminating
912             // scopes, meaning that temporaries cannot outlive them.
913             // This ensures fixed size stacks.
914
915             hir::ExprKind::Binary(
916                 source_map::Spanned { node: hir::BinOpKind::And, .. },
917                 _, ref r) |
918             hir::ExprKind::Binary(
919                 source_map::Spanned { node: hir::BinOpKind::Or, .. },
920                 _, ref r) => {
921                     // For shortcircuiting operators, mark the RHS as a terminating
922                     // scope since it only executes conditionally.
923                     terminating(r.hir_id.local_id);
924             }
925
926             hir::ExprKind::If(ref expr, ref then, Some(ref otherwise)) => {
927                 terminating(expr.hir_id.local_id);
928                 terminating(then.hir_id.local_id);
929                 terminating(otherwise.hir_id.local_id);
930             }
931
932             hir::ExprKind::If(ref expr, ref then, None) => {
933                 terminating(expr.hir_id.local_id);
934                 terminating(then.hir_id.local_id);
935             }
936
937             hir::ExprKind::Loop(ref body, _, _) => {
938                 terminating(body.hir_id.local_id);
939             }
940
941             hir::ExprKind::While(ref expr, ref body, _) => {
942                 terminating(expr.hir_id.local_id);
943                 terminating(body.hir_id.local_id);
944             }
945
946             hir::ExprKind::Match(..) => {
947                 visitor.cx.var_parent = visitor.cx.parent;
948             }
949
950             hir::ExprKind::AssignOp(..) | hir::ExprKind::Index(..) |
951             hir::ExprKind::Unary(..) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) => {
952                 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
953                 //
954                 // The lifetimes for a call or method call look as follows:
955                 //
956                 // call.id
957                 // - arg0.id
958                 // - ...
959                 // - argN.id
960                 // - call.callee_id
961                 //
962                 // The idea is that call.callee_id represents *the time when
963                 // the invoked function is actually running* and call.id
964                 // represents *the time to prepare the arguments and make the
965                 // call*.  See the section "Borrows in Calls" borrowck/README.md
966                 // for an extended explanation of why this distinction is
967                 // important.
968                 //
969                 // record_superlifetime(new_cx, expr.callee_id);
970             }
971
972             _ => {}
973         }
974     }
975
976     match expr.node {
977         // Manually recurse over closures, because they are the only
978         // case of nested bodies that share the parent environment.
979         hir::ExprKind::Closure(.., body, _, _) => {
980             let body = visitor.tcx.hir.body(body);
981             visitor.visit_body(body);
982         }
983
984         _ => intravisit::walk_expr(visitor, expr)
985     }
986
987     visitor.expr_and_pat_count += 1;
988
989     debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
990
991     if let hir::ExprKind::Yield(..) = expr.node {
992         // Mark this expr's scope and all parent scopes as containing `yield`.
993         let mut scope = Scope::Node(expr.hir_id.local_id);
994         loop {
995             visitor.scope_tree.yield_in_scope.insert(scope,
996                 (expr.span, visitor.expr_and_pat_count));
997
998             // Keep traversing up while we can.
999             match visitor.scope_tree.parent_map.get(&scope) {
1000                 // Don't cross from closure bodies to their parent.
1001                 Some(&(superscope, _)) => match superscope.data() {
1002                     ScopeData::CallSite => break,
1003                     _ => scope = superscope
1004                 },
1005                 None => break
1006             }
1007         }
1008     }
1009
1010     visitor.cx = prev_cx;
1011 }
1012
1013 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1014                            pat: Option<&'tcx hir::Pat>,
1015                            init: Option<&'tcx hir::Expr>) {
1016     debug!("resolve_local(pat={:?}, init={:?})", pat, init);
1017
1018     let blk_scope = visitor.cx.var_parent.map(|(p, _)| p);
1019
1020     // As an exception to the normal rules governing temporary
1021     // lifetimes, initializers in a let have a temporary lifetime
1022     // of the enclosing block. This means that e.g. a program
1023     // like the following is legal:
1024     //
1025     //     let ref x = HashMap::new();
1026     //
1027     // Because the hash map will be freed in the enclosing block.
1028     //
1029     // We express the rules more formally based on 3 grammars (defined
1030     // fully in the helpers below that implement them):
1031     //
1032     // 1. `E&`, which matches expressions like `&<rvalue>` that
1033     //    own a pointer into the stack.
1034     //
1035     // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
1036     //    y)` that produce ref bindings into the value they are
1037     //    matched against or something (at least partially) owned by
1038     //    the value they are matched against. (By partially owned,
1039     //    I mean that creating a binding into a ref-counted or managed value
1040     //    would still count.)
1041     //
1042     // 3. `ET`, which matches both rvalues like `foo()` as well as places
1043     //    based on rvalues like `foo().x[2].y`.
1044     //
1045     // A subexpression `<rvalue>` that appears in a let initializer
1046     // `let pat [: ty] = expr` has an extended temporary lifetime if
1047     // any of the following conditions are met:
1048     //
1049     // A. `pat` matches `P&` and `expr` matches `ET`
1050     //    (covers cases where `pat` creates ref bindings into an rvalue
1051     //     produced by `expr`)
1052     // B. `ty` is a borrowed pointer and `expr` matches `ET`
1053     //    (covers cases where coercion creates a borrow)
1054     // C. `expr` matches `E&`
1055     //    (covers cases `expr` borrows an rvalue that is then assigned
1056     //     to memory (at least partially) owned by the binding)
1057     //
1058     // Here are some examples hopefully giving an intuition where each
1059     // rule comes into play and why:
1060     //
1061     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1062     // would have an extended lifetime, but not `foo()`.
1063     //
1064     // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1065     // lifetime.
1066     //
1067     // In some cases, multiple rules may apply (though not to the same
1068     // rvalue). For example:
1069     //
1070     //     let ref x = [&a(), &b()];
1071     //
1072     // Here, the expression `[...]` has an extended lifetime due to rule
1073     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1074     // due to rule C.
1075
1076     if let Some(expr) = init {
1077         record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1078
1079         if let Some(pat) = pat {
1080             if is_binding_pat(pat) {
1081                 record_rvalue_scope(visitor, &expr, blk_scope);
1082             }
1083         }
1084     }
1085
1086     // Make sure we visit the initializer first, so expr_and_pat_count remains correct
1087     if let Some(expr) = init {
1088         visitor.visit_expr(expr);
1089     }
1090     if let Some(pat) = pat {
1091         visitor.visit_pat(pat);
1092     }
1093
1094     /// True if `pat` match the `P&` nonterminal:
1095     ///
1096     ///     P& = ref X
1097     ///        | StructName { ..., P&, ... }
1098     ///        | VariantName(..., P&, ...)
1099     ///        | [ ..., P&, ... ]
1100     ///        | ( ..., P&, ... )
1101     ///        | box P&
1102     fn is_binding_pat(pat: &hir::Pat) -> bool {
1103         // Note that the code below looks for *explicit* refs only, that is, it won't
1104         // know about *implicit* refs as introduced in #42640.
1105         //
1106         // This is not a problem. For example, consider
1107         //
1108         //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
1109         //
1110         // Due to the explicit refs on the left hand side, the below code would signal
1111         // that the temporary value on the right hand side should live until the end of
1112         // the enclosing block (as opposed to being dropped after the let is complete).
1113         //
1114         // To create an implicit ref, however, you must have a borrowed value on the RHS
1115         // already, as in this example (which won't compile before #42640):
1116         //
1117         //      let Foo { x, .. } = &Foo { x: ..., ... };
1118         //
1119         // in place of
1120         //
1121         //      let Foo { ref x, .. } = Foo { ... };
1122         //
1123         // In the former case (the implicit ref version), the temporary is created by the
1124         // & expression, and its lifetime would be extended to the end of the block (due
1125         // to a different rule, not the below code).
1126         match pat.node {
1127             PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1128             PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1129
1130             PatKind::Struct(_, ref field_pats, _) => {
1131                 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1132             }
1133
1134             PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
1135                 pats1.iter().any(|p| is_binding_pat(&p)) ||
1136                 pats2.iter().any(|p| is_binding_pat(&p)) ||
1137                 pats3.iter().any(|p| is_binding_pat(&p))
1138             }
1139
1140             PatKind::TupleStruct(_, ref subpats, _) |
1141             PatKind::Tuple(ref subpats, _) => {
1142                 subpats.iter().any(|p| is_binding_pat(&p))
1143             }
1144
1145             PatKind::Box(ref subpat) => {
1146                 is_binding_pat(&subpat)
1147             }
1148
1149             _ => false,
1150         }
1151     }
1152
1153     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1154     ///
1155     ///     E& = & ET
1156     ///        | StructName { ..., f: E&, ... }
1157     ///        | [ ..., E&, ... ]
1158     ///        | ( ..., E&, ... )
1159     ///        | {...; E&}
1160     ///        | box E&
1161     ///        | E& as ...
1162     ///        | ( E& )
1163     fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1164         visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1165         expr: &hir::Expr,
1166         blk_id: Option<Scope>)
1167     {
1168         match expr.node {
1169             hir::ExprKind::AddrOf(_, ref subexpr) => {
1170                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1171                 record_rvalue_scope(visitor, &subexpr, blk_id);
1172             }
1173             hir::ExprKind::Struct(_, ref fields, _) => {
1174                 for field in fields {
1175                     record_rvalue_scope_if_borrow_expr(
1176                         visitor, &field.expr, blk_id);
1177                 }
1178             }
1179             hir::ExprKind::Array(ref subexprs) |
1180             hir::ExprKind::Tup(ref subexprs) => {
1181                 for subexpr in subexprs {
1182                     record_rvalue_scope_if_borrow_expr(
1183                         visitor, &subexpr, blk_id);
1184                 }
1185             }
1186             hir::ExprKind::Cast(ref subexpr, _) => {
1187                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1188             }
1189             hir::ExprKind::Block(ref block, _) => {
1190                 if let Some(ref subexpr) = block.expr {
1191                     record_rvalue_scope_if_borrow_expr(
1192                         visitor, &subexpr, blk_id);
1193                 }
1194             }
1195             _ => {}
1196         }
1197     }
1198
1199     /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1200     /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1201     /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1202     /// statement.
1203     ///
1204     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1205     /// `<rvalue>` as `blk_id`:
1206     ///
1207     ///     ET = *ET
1208     ///        | ET[...]
1209     ///        | ET.f
1210     ///        | (ET)
1211     ///        | <rvalue>
1212     ///
1213     /// Note: ET is intended to match "rvalues or places based on rvalues".
1214     fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1215                                      expr: &hir::Expr,
1216                                      blk_scope: Option<Scope>) {
1217         let mut expr = expr;
1218         loop {
1219             // Note: give all the expressions matching `ET` with the
1220             // extended temporary lifetime, not just the innermost rvalue,
1221             // because in codegen if we must compile e.g. `*rvalue()`
1222             // into a temporary, we request the temporary scope of the
1223             // outer expression.
1224             visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1225
1226             match expr.node {
1227                 hir::ExprKind::AddrOf(_, ref subexpr) |
1228                 hir::ExprKind::Unary(hir::UnDeref, ref subexpr) |
1229                 hir::ExprKind::Field(ref subexpr, _) |
1230                 hir::ExprKind::Index(ref subexpr, _) => {
1231                     expr = &subexpr;
1232                 }
1233                 _ => {
1234                     return;
1235                 }
1236             }
1237         }
1238     }
1239 }
1240
1241 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1242     /// Records the current parent (if any) as the parent of `child_scope`.
1243     /// Returns the depth of `child_scope`.
1244     fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth {
1245         let parent = self.cx.parent;
1246         self.scope_tree.record_scope_parent(child_scope, parent);
1247         // If `child_scope` has no parent, it must be the root node, and so has
1248         // a depth of 1. Otherwise, its depth is one more than its parent's.
1249         parent.map_or(1, |(_p, d)| d + 1)
1250     }
1251
1252     /// Records the current parent (if any) as the parent of `child_scope`,
1253     /// and sets `child_scope` as the new current parent.
1254     fn enter_scope(&mut self, child_scope: Scope) {
1255         let child_depth = self.record_child_scope(child_scope);
1256         self.cx.parent = Some((child_scope, child_depth));
1257     }
1258
1259     fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1260         // If node was previously marked as a terminating scope during the
1261         // recursive visit of its parent node in the AST, then we need to
1262         // account for the destruction scope representing the scope of
1263         // the destructors that run immediately after it completes.
1264         if self.terminating_scopes.contains(&id) {
1265             self.enter_scope(Scope::Destruction(id));
1266         }
1267         self.enter_scope(Scope::Node(id));
1268     }
1269 }
1270
1271 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1272     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1273         NestedVisitorMap::None
1274     }
1275
1276     fn visit_block(&mut self, b: &'tcx Block) {
1277         resolve_block(self, b);
1278     }
1279
1280     fn visit_body(&mut self, body: &'tcx hir::Body) {
1281         let body_id = body.id();
1282         let owner_id = self.tcx.hir.body_owner(body_id);
1283
1284         debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1285                owner_id,
1286                self.tcx.sess.source_map().span_to_string(body.value.span),
1287                body_id,
1288                self.cx.parent);
1289
1290         let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
1291         let outer_cx = self.cx;
1292         let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet());
1293         self.terminating_scopes.insert(body.value.hir_id.local_id);
1294
1295         if let Some(root_id) = self.cx.root_id {
1296             self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1297         }
1298         self.cx.root_id = Some(body.value.hir_id.local_id);
1299
1300         self.enter_scope(Scope::CallSite(body.value.hir_id.local_id));
1301         self.enter_scope(Scope::Arguments(body.value.hir_id.local_id));
1302
1303         // The arguments and `self` are parented to the fn.
1304         self.cx.var_parent = self.cx.parent.take();
1305         for argument in &body.arguments {
1306             self.visit_pat(&argument.pat);
1307         }
1308
1309         // The body of the every fn is a root scope.
1310         self.cx.parent = self.cx.var_parent;
1311         if let hir::BodyOwnerKind::Fn = self.tcx.hir.body_owner_kind(owner_id) {
1312             self.visit_expr(&body.value);
1313         } else {
1314             // Only functions have an outer terminating (drop) scope, while
1315             // temporaries in constant initializers may be 'static, but only
1316             // according to rvalue lifetime semantics, using the same
1317             // syntactical rules used for let initializers.
1318             //
1319             // E.g. in `let x = &f();`, the temporary holding the result from
1320             // the `f()` call lives for the entirety of the surrounding block.
1321             //
1322             // Similarly, `const X: ... = &f();` would have the result of `f()`
1323             // live for `'static`, implying (if Drop restrictions on constants
1324             // ever get lifted) that the value *could* have a destructor, but
1325             // it'd get leaked instead of the destructor running during the
1326             // evaluation of `X` (if at all allowed by CTFE).
1327             //
1328             // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1329             // would *not* let the `f()` temporary escape into an outer scope
1330             // (i.e. `'static`), which means that after `g` returns, it drops,
1331             // and all the associated destruction scope rules apply.
1332             self.cx.var_parent = None;
1333             resolve_local(self, None, Some(&body.value));
1334         }
1335
1336         if body.is_generator {
1337             self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1338         }
1339
1340         // Restore context we had at the start.
1341         self.expr_and_pat_count = outer_ec;
1342         self.cx = outer_cx;
1343         self.terminating_scopes = outer_ts;
1344     }
1345
1346     fn visit_arm(&mut self, a: &'tcx Arm) {
1347         resolve_arm(self, a);
1348     }
1349     fn visit_pat(&mut self, p: &'tcx Pat) {
1350         resolve_pat(self, p);
1351     }
1352     fn visit_stmt(&mut self, s: &'tcx Stmt) {
1353         resolve_stmt(self, s);
1354     }
1355     fn visit_expr(&mut self, ex: &'tcx Expr) {
1356         resolve_expr(self, ex);
1357     }
1358     fn visit_local(&mut self, l: &'tcx Local) {
1359         resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1360     }
1361 }
1362
1363 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1364     -> Lrc<ScopeTree>
1365 {
1366     let closure_base_def_id = tcx.closure_base_def_id(def_id);
1367     if closure_base_def_id != def_id {
1368         return tcx.region_scope_tree(closure_base_def_id);
1369     }
1370
1371     let id = tcx.hir.as_local_node_id(def_id).unwrap();
1372     let scope_tree = if let Some(body_id) = tcx.hir.maybe_body_owned_by(id) {
1373         let mut visitor = RegionResolutionVisitor {
1374             tcx,
1375             scope_tree: ScopeTree::default(),
1376             expr_and_pat_count: 0,
1377             cx: Context {
1378                 root_id: None,
1379                 parent: None,
1380                 var_parent: None,
1381             },
1382             terminating_scopes: FxHashSet(),
1383         };
1384
1385         let body = tcx.hir.body(body_id);
1386         visitor.scope_tree.root_body = Some(body.value.hir_id);
1387
1388         // If the item is an associated const or a method,
1389         // record its impl/trait parent, as it can also have
1390         // lifetime parameters free in this body.
1391         match tcx.hir.get(id) {
1392             Node::ImplItem(_) |
1393             Node::TraitItem(_) => {
1394                 visitor.scope_tree.root_parent = Some(tcx.hir.get_parent(id));
1395             }
1396             _ => {}
1397         }
1398
1399         visitor.visit_body(body);
1400
1401         visitor.scope_tree
1402     } else {
1403         ScopeTree::default()
1404     };
1405
1406     Lrc::new(scope_tree)
1407 }
1408
1409 pub fn provide(providers: &mut Providers) {
1410     *providers = Providers {
1411         region_scope_tree,
1412         ..*providers
1413     };
1414 }
1415
1416 impl<'a> HashStable<StableHashingContext<'a>> for ScopeTree {
1417     fn hash_stable<W: StableHasherResult>(&self,
1418                                           hcx: &mut StableHashingContext<'a>,
1419                                           hasher: &mut StableHasher<W>) {
1420         let ScopeTree {
1421             root_body,
1422             root_parent,
1423             ref body_expr_count,
1424             ref parent_map,
1425             ref var_map,
1426             ref destruction_scopes,
1427             ref rvalue_scopes,
1428             ref closure_tree,
1429             ref yield_in_scope,
1430         } = *self;
1431
1432         hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1433             root_body.hash_stable(hcx, hasher);
1434             root_parent.hash_stable(hcx, hasher);
1435         });
1436
1437         body_expr_count.hash_stable(hcx, hasher);
1438         parent_map.hash_stable(hcx, hasher);
1439         var_map.hash_stable(hcx, hasher);
1440         destruction_scopes.hash_stable(hcx, hasher);
1441         rvalue_scopes.hash_stable(hcx, hasher);
1442         closure_tree.hash_stable(hcx, hasher);
1443         yield_in_scope.hash_stable(hcx, hasher);
1444     }
1445 }