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