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