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