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