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