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