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