]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/region.rs
Auto merge of #66899 - msizanoen1:riscv-std, r=alexcrichton
[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 rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc::middle::region::*;
11 use rustc::ty::query::Providers;
12 use rustc::ty::TyCtxt;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_hir as hir;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::{Arm, Block, Expr, Local, Node, Pat, PatKind, Stmt};
17 use rustc_index::vec::Idx;
18 use rustc_span::source_map;
19 use rustc_span::Span;
20
21 use std::mem;
22
23 #[derive(Debug, Copy, Clone)]
24 pub struct Context {
25     /// The root of the current region tree. This is typically the id
26     /// of the innermost fn body. Each fn forms its own disjoint tree
27     /// in the region hierarchy. These fn bodies are themselves
28     /// arranged into a tree. See the "Modeling closures" section of
29     /// the README in `infer::region_constraints` for more
30     /// details.
31     root_id: Option<hir::ItemLocalId>,
32
33     /// The scope that contains any new variables declared, plus its depth in
34     /// the scope tree.
35     var_parent: Option<(Scope, ScopeDepth)>,
36
37     /// Region parent of expressions, etc., plus its depth in the scope tree.
38     parent: Option<(Scope, ScopeDepth)>,
39 }
40
41 struct RegionResolutionVisitor<'tcx> {
42     tcx: TyCtxt<'tcx>,
43
44     // The number of expressions and patterns visited in the current body.
45     expr_and_pat_count: usize,
46     // When this is `true`, we record the `Scopes` we encounter
47     // when processing a Yield expression. This allows us to fix
48     // up their indices.
49     pessimistic_yield: bool,
50     // Stores scopes when `pessimistic_yield` is `true`.
51     fixup_scopes: Vec<Scope>,
52     // The generated scope tree.
53     scope_tree: ScopeTree,
54
55     cx: Context,
56
57     /// `terminating_scopes` is a set containing the ids of each
58     /// statement, or conditional/repeating expression. These scopes
59     /// are calling "terminating scopes" because, when attempting to
60     /// find the scope of a temporary, by default we search up the
61     /// enclosing scopes until we encounter the terminating scope. A
62     /// conditional/repeating expression is one which is not
63     /// guaranteed to execute exactly once upon entering the parent
64     /// scope. This could be because the expression only executes
65     /// conditionally, such as the expression `b` in `a && b`, or
66     /// because the expression may execute many times, such as a loop
67     /// body. The reason that we distinguish such expressions is that,
68     /// upon exiting the parent scope, we cannot statically know how
69     /// many times the expression executed, and thus if the expression
70     /// creates temporaries we cannot know statically how many such
71     /// temporaries we would have to cleanup. Therefore, we ensure that
72     /// the temporaries never outlast the conditional/repeating
73     /// expression, preventing the need for dynamic checks and/or
74     /// arbitrary amounts of stack space. Terminating scopes end
75     /// up being contained in a DestructionScope that contains the
76     /// destructor's execution.
77     terminating_scopes: FxHashSet<hir::ItemLocalId>,
78 }
79
80 /// Records the lifetime of a local variable as `cx.var_parent`
81 fn record_var_lifetime(
82     visitor: &mut RegionResolutionVisitor<'_>,
83     var_id: hir::ItemLocalId,
84     _sp: Span,
85 ) {
86     match visitor.cx.var_parent {
87         None => {
88             // this can happen in extern fn declarations like
89             //
90             // extern fn isalnum(c: c_int) -> c_int
91         }
92         Some((parent_scope, _)) => visitor.scope_tree.record_var_scope(var_id, parent_scope),
93     }
94 }
95
96 fn resolve_block<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, blk: &'tcx hir::Block<'tcx>) {
97     debug!("resolve_block(blk.hir_id={:?})", blk.hir_id);
98
99     let prev_cx = visitor.cx;
100
101     // We treat the tail expression in the block (if any) somewhat
102     // differently from the statements. The issue has to do with
103     // temporary lifetimes. Consider the following:
104     //
105     //    quux({
106     //        let inner = ... (&bar()) ...;
107     //
108     //        (... (&foo()) ...) // (the tail expression)
109     //    }, other_argument());
110     //
111     // Each of the statements within the block is a terminating
112     // scope, and thus a temporary (e.g., the result of calling
113     // `bar()` in the initializer expression for `let inner = ...;`)
114     // will be cleaned up immediately after its corresponding
115     // statement (i.e., `let inner = ...;`) executes.
116     //
117     // On the other hand, temporaries associated with evaluating the
118     // tail expression for the block are assigned lifetimes so that
119     // they will be cleaned up as part of the terminating scope
120     // *surrounding* the block expression. Here, the terminating
121     // scope for the block expression is the `quux(..)` call; so
122     // those temporaries will only be cleaned up *after* both
123     // `other_argument()` has run and also the call to `quux(..)`
124     // itself has returned.
125
126     visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
127     visitor.cx.var_parent = visitor.cx.parent;
128
129     {
130         // This block should be kept approximately in sync with
131         // `intravisit::walk_block`. (We manually walk the block, rather
132         // than call `walk_block`, in order to maintain precise
133         // index information.)
134
135         for (i, statement) in blk.stmts.iter().enumerate() {
136             match statement.kind {
137                 hir::StmtKind::Local(..) | hir::StmtKind::Item(..) => {
138                     // Each declaration introduces a subscope for bindings
139                     // introduced by the declaration; this subscope covers a
140                     // suffix of the block. Each subscope in a block has the
141                     // previous subscope in the block as a parent, except for
142                     // the first such subscope, which has the block itself as a
143                     // parent.
144                     visitor.enter_scope(Scope {
145                         id: blk.hir_id.local_id,
146                         data: ScopeData::Remainder(FirstStatementIndex::new(i)),
147                     });
148                     visitor.cx.var_parent = visitor.cx.parent;
149                 }
150                 hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {}
151             }
152             visitor.visit_stmt(statement)
153         }
154         walk_list!(visitor, visit_expr, &blk.expr);
155     }
156
157     visitor.cx = prev_cx;
158 }
159
160 fn resolve_arm<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, arm: &'tcx hir::Arm<'tcx>) {
161     let prev_cx = visitor.cx;
162
163     visitor.enter_scope(Scope { id: arm.hir_id.local_id, data: ScopeData::Node });
164     visitor.cx.var_parent = visitor.cx.parent;
165
166     visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
167
168     if let Some(hir::Guard::If(ref expr)) = arm.guard {
169         visitor.terminating_scopes.insert(expr.hir_id.local_id);
170     }
171
172     intravisit::walk_arm(visitor, arm);
173
174     visitor.cx = prev_cx;
175 }
176
177 fn resolve_pat<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) {
178     visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node });
179
180     // If this is a binding then record the lifetime of that binding.
181     if let PatKind::Binding(..) = pat.kind {
182         record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
183     }
184
185     debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
186
187     intravisit::walk_pat(visitor, pat);
188
189     visitor.expr_and_pat_count += 1;
190
191     debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat);
192 }
193
194 fn resolve_stmt<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) {
195     let stmt_id = stmt.hir_id.local_id;
196     debug!("resolve_stmt(stmt.id={:?})", stmt_id);
197
198     // Every statement will clean up the temporaries created during
199     // execution of that statement. Therefore each statement has an
200     // associated destruction scope that represents the scope of the
201     // statement plus its destructors, and thus the scope for which
202     // regions referenced by the destructors need to survive.
203     visitor.terminating_scopes.insert(stmt_id);
204
205     let prev_parent = visitor.cx.parent;
206     visitor.enter_node_scope_with_dtor(stmt_id);
207
208     intravisit::walk_stmt(visitor, stmt);
209
210     visitor.cx.parent = prev_parent;
211 }
212
213 fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
214     debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr);
215
216     let prev_cx = visitor.cx;
217     visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
218
219     {
220         let terminating_scopes = &mut visitor.terminating_scopes;
221         let mut terminating = |id: hir::ItemLocalId| {
222             terminating_scopes.insert(id);
223         };
224         match expr.kind {
225             // Conditional or repeating scopes are always terminating
226             // scopes, meaning that temporaries cannot outlive them.
227             // This ensures fixed size stacks.
228             hir::ExprKind::Binary(
229                 source_map::Spanned { node: hir::BinOpKind::And, .. },
230                 _,
231                 ref r,
232             )
233             | hir::ExprKind::Binary(
234                 source_map::Spanned { node: hir::BinOpKind::Or, .. },
235                 _,
236                 ref r,
237             ) => {
238                 // For shortcircuiting operators, mark the RHS as a terminating
239                 // scope since it only executes conditionally.
240                 terminating(r.hir_id.local_id);
241             }
242
243             hir::ExprKind::Loop(ref body, _, _) => {
244                 terminating(body.hir_id.local_id);
245             }
246
247             hir::ExprKind::DropTemps(ref expr) => {
248                 // `DropTemps(expr)` does not denote a conditional scope.
249                 // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`.
250                 terminating(expr.hir_id.local_id);
251             }
252
253             hir::ExprKind::AssignOp(..)
254             | hir::ExprKind::Index(..)
255             | hir::ExprKind::Unary(..)
256             | hir::ExprKind::Call(..)
257             | hir::ExprKind::MethodCall(..) => {
258                 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
259                 //
260                 // The lifetimes for a call or method call look as follows:
261                 //
262                 // call.id
263                 // - arg0.id
264                 // - ...
265                 // - argN.id
266                 // - call.callee_id
267                 //
268                 // The idea is that call.callee_id represents *the time when
269                 // the invoked function is actually running* and call.id
270                 // represents *the time to prepare the arguments and make the
271                 // call*.  See the section "Borrows in Calls" borrowck/README.md
272                 // for an extended explanation of why this distinction is
273                 // important.
274                 //
275                 // record_superlifetime(new_cx, expr.callee_id);
276             }
277
278             _ => {}
279         }
280     }
281
282     let prev_pessimistic = visitor.pessimistic_yield;
283
284     // Ordinarily, we can rely on the visit order of HIR intravisit
285     // to correspond to the actual execution order of statements.
286     // However, there's a weird corner case with compund assignment
287     // operators (e.g. `a += b`). The evaluation order depends on whether
288     // or not the operator is overloaded (e.g. whether or not a trait
289     // like AddAssign is implemented).
290
291     // For primitive types (which, despite having a trait impl, don't actually
292     // end up calling it), the evluation order is right-to-left. For example,
293     // the following code snippet:
294     //
295     //    let y = &mut 0;
296     //    *{println!("LHS!"); y} += {println!("RHS!"); 1};
297     //
298     // will print:
299     //
300     // RHS!
301     // LHS!
302     //
303     // However, if the operator is used on a non-primitive type,
304     // the evaluation order will be left-to-right, since the operator
305     // actually get desugared to a method call. For example, this
306     // nearly identical code snippet:
307     //
308     //     let y = &mut String::new();
309     //    *{println!("LHS String"); y} += {println!("RHS String"); "hi"};
310     //
311     // will print:
312     // LHS String
313     // RHS String
314     //
315     // To determine the actual execution order, we need to perform
316     // trait resolution. Unfortunately, we need to be able to compute
317     // yield_in_scope before type checking is even done, as it gets
318     // used by AST borrowcheck.
319     //
320     // Fortunately, we don't need to know the actual execution order.
321     // It suffices to know the 'worst case' order with respect to yields.
322     // Specifically, we need to know the highest 'expr_and_pat_count'
323     // that we could assign to the yield expression. To do this,
324     // we pick the greater of the two values from the left-hand
325     // and right-hand expressions. This makes us overly conservative
326     // about what types could possibly live across yield points,
327     // but we will never fail to detect that a type does actually
328     // live across a yield point. The latter part is critical -
329     // we're already overly conservative about what types will live
330     // across yield points, as the generated MIR will determine
331     // when things are actually live. However, for typecheck to work
332     // properly, we can't miss any types.
333
334     match expr.kind {
335         // Manually recurse over closures, because they are the only
336         // case of nested bodies that share the parent environment.
337         hir::ExprKind::Closure(.., body, _, _) => {
338             let body = visitor.tcx.hir().body(body);
339             visitor.visit_body(body);
340         }
341         hir::ExprKind::AssignOp(_, ref left_expr, ref right_expr) => {
342             debug!(
343                 "resolve_expr - enabling pessimistic_yield, was previously {}",
344                 prev_pessimistic
345             );
346
347             let start_point = visitor.fixup_scopes.len();
348             visitor.pessimistic_yield = true;
349
350             // If the actual execution order turns out to be right-to-left,
351             // then we're fine. However, if the actual execution order is left-to-right,
352             // then we'll assign too low a count to any `yield` expressions
353             // we encounter in 'right_expression' - they should really occur after all of the
354             // expressions in 'left_expression'.
355             visitor.visit_expr(&right_expr);
356             visitor.pessimistic_yield = prev_pessimistic;
357
358             debug!("resolve_expr - restoring pessimistic_yield to {}", prev_pessimistic);
359             visitor.visit_expr(&left_expr);
360             debug!("resolve_expr - fixing up counts to {}", visitor.expr_and_pat_count);
361
362             // Remove and process any scopes pushed by the visitor
363             let target_scopes = visitor.fixup_scopes.drain(start_point..);
364
365             for scope in target_scopes {
366                 let mut yield_data = visitor.scope_tree.yield_in_scope.get_mut(&scope).unwrap();
367                 let count = yield_data.expr_and_pat_count;
368                 let span = yield_data.span;
369
370                 // expr_and_pat_count never decreases. Since we recorded counts in yield_in_scope
371                 // before walking the left-hand side, it should be impossible for the recorded
372                 // count to be greater than the left-hand side count.
373                 if count > visitor.expr_and_pat_count {
374                     bug!(
375                         "Encountered greater count {} at span {:?} - expected no greater than {}",
376                         count,
377                         span,
378                         visitor.expr_and_pat_count
379                     );
380                 }
381                 let new_count = visitor.expr_and_pat_count;
382                 debug!(
383                     "resolve_expr - increasing count for scope {:?} from {} to {} at span {:?}",
384                     scope, count, new_count, span
385                 );
386
387                 yield_data.expr_and_pat_count = new_count;
388             }
389         }
390
391         _ => intravisit::walk_expr(visitor, expr),
392     }
393
394     visitor.expr_and_pat_count += 1;
395
396     debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr);
397
398     if let hir::ExprKind::Yield(_, source) = &expr.kind {
399         // Mark this expr's scope and all parent scopes as containing `yield`.
400         let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node };
401         loop {
402             let data = YieldData {
403                 span: expr.span,
404                 expr_and_pat_count: visitor.expr_and_pat_count,
405                 source: *source,
406             };
407             visitor.scope_tree.yield_in_scope.insert(scope, data);
408             if visitor.pessimistic_yield {
409                 debug!("resolve_expr in pessimistic_yield - marking scope {:?} for fixup", scope);
410                 visitor.fixup_scopes.push(scope);
411             }
412
413             // Keep traversing up while we can.
414             match visitor.scope_tree.parent_map.get(&scope) {
415                 // Don't cross from closure bodies to their parent.
416                 Some(&(superscope, _)) => match superscope.data {
417                     ScopeData::CallSite => break,
418                     _ => scope = superscope,
419                 },
420                 None => break,
421             }
422         }
423     }
424
425     visitor.cx = prev_cx;
426 }
427
428 fn resolve_local<'tcx>(
429     visitor: &mut RegionResolutionVisitor<'tcx>,
430     pat: Option<&'tcx hir::Pat<'tcx>>,
431     init: Option<&'tcx hir::Expr<'tcx>>,
432 ) {
433     debug!("resolve_local(pat={:?}, init={:?})", pat, init);
434
435     let blk_scope = visitor.cx.var_parent.map(|(p, _)| p);
436
437     // As an exception to the normal rules governing temporary
438     // lifetimes, initializers in a let have a temporary lifetime
439     // of the enclosing block. This means that e.g., a program
440     // like the following is legal:
441     //
442     //     let ref x = HashMap::new();
443     //
444     // Because the hash map will be freed in the enclosing block.
445     //
446     // We express the rules more formally based on 3 grammars (defined
447     // fully in the helpers below that implement them):
448     //
449     // 1. `E&`, which matches expressions like `&<rvalue>` that
450     //    own a pointer into the stack.
451     //
452     // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
453     //    y)` that produce ref bindings into the value they are
454     //    matched against or something (at least partially) owned by
455     //    the value they are matched against. (By partially owned,
456     //    I mean that creating a binding into a ref-counted or managed value
457     //    would still count.)
458     //
459     // 3. `ET`, which matches both rvalues like `foo()` as well as places
460     //    based on rvalues like `foo().x[2].y`.
461     //
462     // A subexpression `<rvalue>` that appears in a let initializer
463     // `let pat [: ty] = expr` has an extended temporary lifetime if
464     // any of the following conditions are met:
465     //
466     // A. `pat` matches `P&` and `expr` matches `ET`
467     //    (covers cases where `pat` creates ref bindings into an rvalue
468     //     produced by `expr`)
469     // B. `ty` is a borrowed pointer and `expr` matches `ET`
470     //    (covers cases where coercion creates a borrow)
471     // C. `expr` matches `E&`
472     //    (covers cases `expr` borrows an rvalue that is then assigned
473     //     to memory (at least partially) owned by the binding)
474     //
475     // Here are some examples hopefully giving an intuition where each
476     // rule comes into play and why:
477     //
478     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
479     // would have an extended lifetime, but not `foo()`.
480     //
481     // Rule B. `let x = &foo().x`. The rvalue `foo()` would have extended
482     // lifetime.
483     //
484     // In some cases, multiple rules may apply (though not to the same
485     // rvalue). For example:
486     //
487     //     let ref x = [&a(), &b()];
488     //
489     // Here, the expression `[...]` has an extended lifetime due to rule
490     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
491     // due to rule C.
492
493     if let Some(expr) = init {
494         record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
495
496         if let Some(pat) = pat {
497             if is_binding_pat(pat) {
498                 record_rvalue_scope(visitor, &expr, blk_scope);
499             }
500         }
501     }
502
503     // Make sure we visit the initializer first, so expr_and_pat_count remains correct
504     if let Some(expr) = init {
505         visitor.visit_expr(expr);
506     }
507     if let Some(pat) = pat {
508         visitor.visit_pat(pat);
509     }
510
511     /// Returns `true` if `pat` match the `P&` non-terminal.
512     ///
513     /// ```text
514     ///     P& = ref X
515     ///        | StructName { ..., P&, ... }
516     ///        | VariantName(..., P&, ...)
517     ///        | [ ..., P&, ... ]
518     ///        | ( ..., P&, ... )
519     ///        | ... "|" P& "|" ...
520     ///        | box P&
521     /// ```
522     fn is_binding_pat(pat: &hir::Pat<'_>) -> bool {
523         // Note that the code below looks for *explicit* refs only, that is, it won't
524         // know about *implicit* refs as introduced in #42640.
525         //
526         // This is not a problem. For example, consider
527         //
528         //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
529         //
530         // Due to the explicit refs on the left hand side, the below code would signal
531         // that the temporary value on the right hand side should live until the end of
532         // the enclosing block (as opposed to being dropped after the let is complete).
533         //
534         // To create an implicit ref, however, you must have a borrowed value on the RHS
535         // already, as in this example (which won't compile before #42640):
536         //
537         //      let Foo { x, .. } = &Foo { x: ..., ... };
538         //
539         // in place of
540         //
541         //      let Foo { ref x, .. } = Foo { ... };
542         //
543         // In the former case (the implicit ref version), the temporary is created by the
544         // & expression, and its lifetime would be extended to the end of the block (due
545         // to a different rule, not the below code).
546         match pat.kind {
547             PatKind::Binding(hir::BindingAnnotation::Ref, ..)
548             | PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
549
550             PatKind::Struct(_, ref field_pats, _) => {
551                 field_pats.iter().any(|fp| is_binding_pat(&fp.pat))
552             }
553
554             PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
555                 pats1.iter().any(|p| is_binding_pat(&p))
556                     || pats2.iter().any(|p| is_binding_pat(&p))
557                     || pats3.iter().any(|p| is_binding_pat(&p))
558             }
559
560             PatKind::Or(ref subpats)
561             | PatKind::TupleStruct(_, ref subpats, _)
562             | PatKind::Tuple(ref subpats, _) => subpats.iter().any(|p| is_binding_pat(&p)),
563
564             PatKind::Box(ref subpat) => is_binding_pat(&subpat),
565
566             PatKind::Ref(_, _)
567             | PatKind::Binding(hir::BindingAnnotation::Unannotated, ..)
568             | PatKind::Binding(hir::BindingAnnotation::Mutable, ..)
569             | PatKind::Wild
570             | PatKind::Path(_)
571             | PatKind::Lit(_)
572             | PatKind::Range(_, _, _) => false,
573         }
574     }
575
576     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
577     ///
578     /// ```text
579     ///     E& = & ET
580     ///        | StructName { ..., f: E&, ... }
581     ///        | [ ..., E&, ... ]
582     ///        | ( ..., E&, ... )
583     ///        | {...; E&}
584     ///        | box E&
585     ///        | E& as ...
586     ///        | ( E& )
587     /// ```
588     fn record_rvalue_scope_if_borrow_expr<'tcx>(
589         visitor: &mut RegionResolutionVisitor<'tcx>,
590         expr: &hir::Expr<'_>,
591         blk_id: Option<Scope>,
592     ) {
593         match expr.kind {
594             hir::ExprKind::AddrOf(_, _, ref subexpr) => {
595                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
596                 record_rvalue_scope(visitor, &subexpr, blk_id);
597             }
598             hir::ExprKind::Struct(_, fields, _) => {
599                 for field in fields {
600                     record_rvalue_scope_if_borrow_expr(visitor, &field.expr, blk_id);
601                 }
602             }
603             hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => {
604                 for subexpr in subexprs {
605                     record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
606                 }
607             }
608             hir::ExprKind::Cast(ref subexpr, _) => {
609                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
610             }
611             hir::ExprKind::Block(ref block, _) => {
612                 if let Some(ref subexpr) = block.expr {
613                     record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
614                 }
615             }
616             _ => {}
617         }
618     }
619
620     /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
621     /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
622     /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
623     /// statement.
624     ///
625     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
626     /// `<rvalue>` as `blk_id`:
627     ///
628     /// ```text
629     ///     ET = *ET
630     ///        | ET[...]
631     ///        | ET.f
632     ///        | (ET)
633     ///        | <rvalue>
634     /// ```
635     ///
636     /// Note: ET is intended to match "rvalues or places based on rvalues".
637     fn record_rvalue_scope<'tcx>(
638         visitor: &mut RegionResolutionVisitor<'tcx>,
639         expr: &hir::Expr<'_>,
640         blk_scope: Option<Scope>,
641     ) {
642         let mut expr = expr;
643         loop {
644             // Note: give all the expressions matching `ET` with the
645             // extended temporary lifetime, not just the innermost rvalue,
646             // because in codegen if we must compile e.g., `*rvalue()`
647             // into a temporary, we request the temporary scope of the
648             // outer expression.
649             visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
650
651             match expr.kind {
652                 hir::ExprKind::AddrOf(_, _, ref subexpr)
653                 | hir::ExprKind::Unary(hir::UnOp::UnDeref, ref subexpr)
654                 | hir::ExprKind::Field(ref subexpr, _)
655                 | hir::ExprKind::Index(ref subexpr, _) => {
656                     expr = &subexpr;
657                 }
658                 _ => {
659                     return;
660                 }
661             }
662         }
663     }
664 }
665
666 impl<'tcx> RegionResolutionVisitor<'tcx> {
667     /// Records the current parent (if any) as the parent of `child_scope`.
668     /// Returns the depth of `child_scope`.
669     fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth {
670         let parent = self.cx.parent;
671         self.scope_tree.record_scope_parent(child_scope, parent);
672         // If `child_scope` has no parent, it must be the root node, and so has
673         // a depth of 1. Otherwise, its depth is one more than its parent's.
674         parent.map_or(1, |(_p, d)| d + 1)
675     }
676
677     /// Records the current parent (if any) as the parent of `child_scope`,
678     /// and sets `child_scope` as the new current parent.
679     fn enter_scope(&mut self, child_scope: Scope) {
680         let child_depth = self.record_child_scope(child_scope);
681         self.cx.parent = Some((child_scope, child_depth));
682     }
683
684     fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
685         // If node was previously marked as a terminating scope during the
686         // recursive visit of its parent node in the AST, then we need to
687         // account for the destruction scope representing the scope of
688         // the destructors that run immediately after it completes.
689         if self.terminating_scopes.contains(&id) {
690             self.enter_scope(Scope { id, data: ScopeData::Destruction });
691         }
692         self.enter_scope(Scope { id, data: ScopeData::Node });
693     }
694 }
695
696 impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> {
697     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
698         NestedVisitorMap::None
699     }
700
701     fn visit_block(&mut self, b: &'tcx Block<'tcx>) {
702         resolve_block(self, b);
703     }
704
705     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
706         let body_id = body.id();
707         let owner_id = self.tcx.hir().body_owner(body_id);
708
709         debug!(
710             "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
711             owner_id,
712             self.tcx.sess.source_map().span_to_string(body.value.span),
713             body_id,
714             self.cx.parent
715         );
716
717         let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
718         let outer_cx = self.cx;
719         let outer_ts = mem::take(&mut self.terminating_scopes);
720         self.terminating_scopes.insert(body.value.hir_id.local_id);
721
722         if let Some(root_id) = self.cx.root_id {
723             self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
724         }
725         self.cx.root_id = Some(body.value.hir_id.local_id);
726
727         self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite });
728         self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments });
729
730         // The arguments and `self` are parented to the fn.
731         self.cx.var_parent = self.cx.parent.take();
732         for param in body.params {
733             self.visit_pat(&param.pat);
734         }
735
736         // The body of the every fn is a root scope.
737         self.cx.parent = self.cx.var_parent;
738         if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() {
739             self.visit_expr(&body.value)
740         } else {
741             // Only functions have an outer terminating (drop) scope, while
742             // temporaries in constant initializers may be 'static, but only
743             // according to rvalue lifetime semantics, using the same
744             // syntactical rules used for let initializers.
745             //
746             // e.g., in `let x = &f();`, the temporary holding the result from
747             // the `f()` call lives for the entirety of the surrounding block.
748             //
749             // Similarly, `const X: ... = &f();` would have the result of `f()`
750             // live for `'static`, implying (if Drop restrictions on constants
751             // ever get lifted) that the value *could* have a destructor, but
752             // it'd get leaked instead of the destructor running during the
753             // evaluation of `X` (if at all allowed by CTFE).
754             //
755             // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
756             // would *not* let the `f()` temporary escape into an outer scope
757             // (i.e., `'static`), which means that after `g` returns, it drops,
758             // and all the associated destruction scope rules apply.
759             self.cx.var_parent = None;
760             resolve_local(self, None, Some(&body.value));
761         }
762
763         if body.generator_kind.is_some() {
764             self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
765         }
766
767         // Restore context we had at the start.
768         self.expr_and_pat_count = outer_ec;
769         self.cx = outer_cx;
770         self.terminating_scopes = outer_ts;
771     }
772
773     fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) {
774         resolve_arm(self, a);
775     }
776     fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
777         resolve_pat(self, p);
778     }
779     fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) {
780         resolve_stmt(self, s);
781     }
782     fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
783         resolve_expr(self, ex);
784     }
785     fn visit_local(&mut self, l: &'tcx Local<'tcx>) {
786         resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
787     }
788 }
789
790 fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree {
791     let closure_base_def_id = tcx.closure_base_def_id(def_id);
792     if closure_base_def_id != def_id {
793         return tcx.region_scope_tree(closure_base_def_id);
794     }
795
796     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
797     let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) {
798         let mut visitor = RegionResolutionVisitor {
799             tcx,
800             scope_tree: ScopeTree::default(),
801             expr_and_pat_count: 0,
802             cx: Context { root_id: None, parent: None, var_parent: None },
803             terminating_scopes: Default::default(),
804             pessimistic_yield: false,
805             fixup_scopes: vec![],
806         };
807
808         let body = tcx.hir().body(body_id);
809         visitor.scope_tree.root_body = Some(body.value.hir_id);
810
811         // If the item is an associated const or a method,
812         // record its impl/trait parent, as it can also have
813         // lifetime parameters free in this body.
814         match tcx.hir().get(id) {
815             Node::ImplItem(_) | Node::TraitItem(_) => {
816                 visitor.scope_tree.root_parent = Some(tcx.hir().get_parent_item(id));
817             }
818             _ => {}
819         }
820
821         visitor.visit_body(body);
822
823         visitor.scope_tree
824     } else {
825         ScopeTree::default()
826     };
827
828     tcx.arena.alloc(scope_tree)
829 }
830
831 pub fn provide(providers: &mut Providers<'_>) {
832     *providers = Providers { region_scope_tree, ..*providers };
833 }