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