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