rustc_hir_analysis/check/
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
9use std::mem;
10
11use rustc_data_structures::fx::FxHashMap;
12use rustc_hir as hir;
13use rustc_hir::def::{CtorKind, DefKind, Res};
14use rustc_hir::def_id::DefId;
15use rustc_hir::intravisit::{self, Visitor};
16use rustc_hir::{Arm, Block, Expr, LetStmt, Pat, PatKind, Stmt};
17use rustc_index::Idx;
18use rustc_middle::middle::region::*;
19use rustc_middle::ty::TyCtxt;
20use rustc_session::lint;
21use rustc_span::source_map;
22use tracing::debug;
23
24#[derive(Debug, Copy, Clone)]
25struct Context {
26    /// The scope that contains any new variables declared.
27    var_parent: Option<Scope>,
28
29    /// Region parent of expressions, etc.
30    parent: Option<Scope>,
31}
32
33struct ScopeResolutionVisitor<'tcx> {
34    tcx: TyCtxt<'tcx>,
35
36    // The generated scope tree.
37    scope_tree: ScopeTree,
38
39    cx: Context,
40
41    extended_super_lets: FxHashMap<hir::ItemLocalId, Option<Scope>>,
42}
43
44/// Records the lifetime of a local variable as `cx.var_parent`
45fn record_var_lifetime(visitor: &mut ScopeResolutionVisitor<'_>, var_id: hir::ItemLocalId) {
46    match visitor.cx.var_parent {
47        None => {
48            // this can happen in extern fn declarations like
49            //
50            // extern fn isalnum(c: c_int) -> c_int
51        }
52        Some(parent_scope) => visitor.scope_tree.record_var_scope(var_id, parent_scope),
53    }
54}
55
56fn resolve_block<'tcx>(
57    visitor: &mut ScopeResolutionVisitor<'tcx>,
58    blk: &'tcx hir::Block<'tcx>,
59    terminating: bool,
60) {
61    debug!("resolve_block(blk.hir_id={:?})", blk.hir_id);
62
63    let prev_cx = visitor.cx;
64
65    // We treat the tail expression in the block (if any) somewhat
66    // differently from the statements. The issue has to do with
67    // temporary lifetimes. Consider the following:
68    //
69    //    quux({
70    //        let inner = ... (&bar()) ...;
71    //
72    //        (... (&foo()) ...) // (the tail expression)
73    //    }, other_argument());
74    //
75    // Each of the statements within the block is a terminating
76    // scope, and thus a temporary (e.g., the result of calling
77    // `bar()` in the initializer expression for `let inner = ...;`)
78    // will be cleaned up immediately after its corresponding
79    // statement (i.e., `let inner = ...;`) executes.
80    //
81    // On the other hand, temporaries associated with evaluating the
82    // tail expression for the block are assigned lifetimes so that
83    // they will be cleaned up as part of the terminating scope
84    // *surrounding* the block expression. Here, the terminating
85    // scope for the block expression is the `quux(..)` call; so
86    // those temporaries will only be cleaned up *after* both
87    // `other_argument()` has run and also the call to `quux(..)`
88    // itself has returned.
89
90    visitor.enter_node_scope_with_dtor(blk.hir_id.local_id, terminating);
91    visitor.cx.var_parent = visitor.cx.parent;
92
93    {
94        // This block should be kept approximately in sync with
95        // `intravisit::walk_block`. (We manually walk the block, rather
96        // than call `walk_block`, in order to maintain precise
97        // index information.)
98
99        for (i, statement) in blk.stmts.iter().enumerate() {
100            match statement.kind {
101                hir::StmtKind::Let(LetStmt { els: Some(els), .. }) => {
102                    // Let-else has a special lexical structure for variables.
103                    // First we take a checkpoint of the current scope context here.
104                    let mut prev_cx = visitor.cx;
105
106                    visitor.enter_scope(Scope {
107                        local_id: blk.hir_id.local_id,
108                        data: ScopeData::Remainder(FirstStatementIndex::new(i)),
109                    });
110                    visitor.cx.var_parent = visitor.cx.parent;
111                    visitor.visit_stmt(statement);
112                    // We need to back out temporarily to the last enclosing scope
113                    // for the `else` block, so that even the temporaries receiving
114                    // extended lifetime will be dropped inside this block.
115                    // We are visiting the `else` block in this order so that
116                    // the sequence of visits agree with the order in the default
117                    // `hir::intravisit` visitor.
118                    mem::swap(&mut prev_cx, &mut visitor.cx);
119                    resolve_block(visitor, els, true);
120                    // From now on, we continue normally.
121                    visitor.cx = prev_cx;
122                }
123                hir::StmtKind::Let(..) => {
124                    // Each declaration introduces a subscope for bindings
125                    // introduced by the declaration; this subscope covers a
126                    // suffix of the block. Each subscope in a block has the
127                    // previous subscope in the block as a parent, except for
128                    // the first such subscope, which has the block itself as a
129                    // parent.
130                    visitor.enter_scope(Scope {
131                        local_id: blk.hir_id.local_id,
132                        data: ScopeData::Remainder(FirstStatementIndex::new(i)),
133                    });
134                    visitor.cx.var_parent = visitor.cx.parent;
135                    visitor.visit_stmt(statement)
136                }
137                hir::StmtKind::Item(..) => {
138                    // Don't create scopes for items, since they won't be
139                    // lowered to THIR and MIR.
140                }
141                hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => visitor.visit_stmt(statement),
142            }
143        }
144        if let Some(tail_expr) = blk.expr {
145            let local_id = tail_expr.hir_id.local_id;
146            let edition = blk.span.edition();
147            let terminating = edition.at_least_rust_2024();
148            if !terminating
149                && !visitor
150                    .tcx
151                    .lints_that_dont_need_to_run(())
152                    .contains(&lint::LintId::of(lint::builtin::TAIL_EXPR_DROP_ORDER))
153            {
154                // If this temporary scope will be changing once the codebase adopts Rust 2024,
155                // and we are linting about possible semantic changes that would result,
156                // then record this node-id in the field `backwards_incompatible_scope`
157                // for future reference.
158                visitor
159                    .scope_tree
160                    .backwards_incompatible_scope
161                    .insert(local_id, Scope { local_id, data: ScopeData::Node });
162            }
163            resolve_expr(visitor, tail_expr, terminating);
164        }
165    }
166
167    visitor.cx = prev_cx;
168}
169
170/// Resolve a condition from an `if` expression or match guard so that it is a terminating scope
171/// if it doesn't contain `let` expressions.
172fn resolve_cond<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, cond: &'tcx hir::Expr<'tcx>) {
173    let terminate = match cond.kind {
174        // Temporaries for `let` expressions must live into the success branch.
175        hir::ExprKind::Let(_) => false,
176        // Logical operator chains are handled in `resolve_expr`. Since logical operator chains in
177        // conditions are lowered to control-flow rather than boolean temporaries, there's no
178        // temporary to drop for logical operators themselves. `resolve_expr` will also recursively
179        // wrap any operands in terminating scopes, other than `let` expressions (which we shouldn't
180        // terminate) and other logical operators (which don't need a terminating scope, since their
181        // operands will be terminated). Any temporaries that would need to be dropped will be
182        // dropped before we leave this operator's scope; terminating them here would be redundant.
183        hir::ExprKind::Binary(
184            source_map::Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
185            _,
186            _,
187        ) => false,
188        // Otherwise, conditions should always drop their temporaries.
189        _ => true,
190    };
191    resolve_expr(visitor, cond, terminate);
192}
193
194fn resolve_arm<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, arm: &'tcx hir::Arm<'tcx>) {
195    let prev_cx = visitor.cx;
196
197    visitor.enter_node_scope_with_dtor(arm.hir_id.local_id, true);
198    visitor.cx.var_parent = visitor.cx.parent;
199
200    resolve_pat(visitor, arm.pat);
201    if let Some(guard) = arm.guard {
202        // We introduce a new scope to contain bindings and temporaries from `if let` guards, to
203        // ensure they're dropped before the arm's pattern's bindings. This extends to the end of
204        // the arm body and is the scope of its locals as well.
205        visitor.enter_scope(Scope { local_id: arm.hir_id.local_id, data: ScopeData::MatchGuard });
206        visitor.cx.var_parent = visitor.cx.parent;
207        resolve_cond(visitor, guard);
208    }
209    resolve_expr(visitor, arm.body, false);
210
211    visitor.cx = prev_cx;
212}
213
214#[tracing::instrument(level = "debug", skip(visitor))]
215fn resolve_pat<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) {
216    // If this is a binding then record the lifetime of that binding.
217    if let PatKind::Binding(..) = pat.kind {
218        record_var_lifetime(visitor, pat.hir_id.local_id);
219    }
220
221    intravisit::walk_pat(visitor, pat);
222}
223
224fn resolve_stmt<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) {
225    let stmt_id = stmt.hir_id.local_id;
226    debug!("resolve_stmt(stmt.id={:?})", stmt_id);
227
228    if let hir::StmtKind::Let(LetStmt { super_: Some(_), .. }) = stmt.kind {
229        // `super let` statement does not start a new scope, such that
230        //
231        //     { super let x = identity(&temp()); &x }.method();
232        //
233        // behaves exactly as
234        //
235        //     (&identity(&temp()).method();
236        intravisit::walk_stmt(visitor, stmt);
237    } else {
238        // Every statement will clean up the temporaries created during
239        // execution of that statement. Therefore each statement has an
240        // associated destruction scope that represents the scope of the
241        // statement plus its destructors, and thus the scope for which
242        // regions referenced by the destructors need to survive.
243
244        let prev_parent = visitor.cx.parent;
245        visitor.enter_node_scope_with_dtor(stmt_id, true);
246
247        intravisit::walk_stmt(visitor, stmt);
248
249        visitor.cx.parent = prev_parent;
250    }
251}
252
253#[tracing::instrument(level = "debug", skip(visitor))]
254fn resolve_expr<'tcx>(
255    visitor: &mut ScopeResolutionVisitor<'tcx>,
256    expr: &'tcx hir::Expr<'tcx>,
257    terminating: bool,
258) {
259    let prev_cx = visitor.cx;
260    visitor.enter_node_scope_with_dtor(expr.hir_id.local_id, terminating);
261
262    match expr.kind {
263        // Conditional or repeating scopes are always terminating
264        // scopes, meaning that temporaries cannot outlive them.
265        // This ensures fixed size stacks.
266        hir::ExprKind::Binary(
267            source_map::Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
268            left,
269            right,
270        ) => {
271            // expr is a short circuiting operator (|| or &&). As its
272            // functionality can't be overridden by traits, it always
273            // processes bool sub-expressions. bools are Copy and thus we
274            // can drop any temporaries in evaluation (read) order
275            // (with the exception of potentially failing let expressions).
276            // We achieve this by enclosing the operands in a terminating
277            // scope, both the LHS and the RHS.
278
279            // We optimize this a little in the presence of chains.
280            // Chains like a && b && c get lowered to AND(AND(a, b), c).
281            // In here, b and c are RHS, while a is the only LHS operand in
282            // that chain. This holds true for longer chains as well: the
283            // leading operand is always the only LHS operand that is not a
284            // binop itself. Putting a binop like AND(a, b) into a
285            // terminating scope is not useful, thus we only put the LHS
286            // into a terminating scope if it is not a binop.
287
288            let terminate_lhs = match left.kind {
289                // let expressions can create temporaries that live on
290                hir::ExprKind::Let(_) => false,
291                // binops already drop their temporaries, so there is no
292                // need to put them into a terminating scope.
293                // This is purely an optimization to reduce the number of
294                // terminating scopes.
295                hir::ExprKind::Binary(
296                    source_map::Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
297                    ..,
298                ) => false,
299                // otherwise: mark it as terminating
300                _ => true,
301            };
302
303            // `Let` expressions (in a let-chain) shouldn't be terminating, as their temporaries
304            // should live beyond the immediate expression
305            let terminate_rhs = !matches!(right.kind, hir::ExprKind::Let(_));
306
307            resolve_expr(visitor, left, terminate_lhs);
308            resolve_expr(visitor, right, terminate_rhs);
309        }
310        // Manually recurse over closures, because they are nested bodies
311        // that share the parent environment. We handle const blocks in
312        // `visit_inline_const`.
313        hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
314            let body = visitor.tcx.hir_body(body);
315            visitor.visit_body(body);
316        }
317        // Ordinarily, we can rely on the visit order of HIR intravisit
318        // to correspond to the actual execution order of statements.
319        // However, there's a weird corner case with compound assignment
320        // operators (e.g. `a += b`). The evaluation order depends on whether
321        // or not the operator is overloaded (e.g. whether or not a trait
322        // like AddAssign is implemented).
323        //
324        // For primitive types (which, despite having a trait impl, don't actually
325        // end up calling it), the evaluation order is right-to-left. For example,
326        // the following code snippet:
327        //
328        //    let y = &mut 0;
329        //    *{println!("LHS!"); y} += {println!("RHS!"); 1};
330        //
331        // will print:
332        //
333        // RHS!
334        // LHS!
335        //
336        // However, if the operator is used on a non-primitive type,
337        // the evaluation order will be left-to-right, since the operator
338        // actually get desugared to a method call. For example, this
339        // nearly identical code snippet:
340        //
341        //     let y = &mut String::new();
342        //    *{println!("LHS String"); y} += {println!("RHS String"); "hi"};
343        //
344        // will print:
345        // LHS String
346        // RHS String
347        //
348        // To determine the actual execution order, we need to perform
349        // trait resolution. Fortunately, we don't need to know the actual execution order.
350        hir::ExprKind::AssignOp(_, left_expr, right_expr) => {
351            visitor.visit_expr(right_expr);
352            visitor.visit_expr(left_expr);
353        }
354
355        hir::ExprKind::If(cond, then, Some(otherwise)) => {
356            let expr_cx = visitor.cx;
357            let data = if expr.span.at_least_rust_2024() {
358                ScopeData::IfThenRescope
359            } else {
360                ScopeData::IfThen
361            };
362            visitor.enter_scope(Scope { local_id: then.hir_id.local_id, data });
363            visitor.cx.var_parent = visitor.cx.parent;
364            resolve_cond(visitor, cond);
365            resolve_expr(visitor, then, true);
366            visitor.cx = expr_cx;
367            resolve_expr(visitor, otherwise, true);
368        }
369
370        hir::ExprKind::If(cond, then, None) => {
371            let expr_cx = visitor.cx;
372            let data = if expr.span.at_least_rust_2024() {
373                ScopeData::IfThenRescope
374            } else {
375                ScopeData::IfThen
376            };
377            visitor.enter_scope(Scope { local_id: then.hir_id.local_id, data });
378            visitor.cx.var_parent = visitor.cx.parent;
379            resolve_cond(visitor, cond);
380            resolve_expr(visitor, then, true);
381            visitor.cx = expr_cx;
382        }
383
384        hir::ExprKind::Loop(body, _, _, _) => {
385            resolve_block(visitor, body, true);
386        }
387
388        hir::ExprKind::DropTemps(expr) => {
389            // `DropTemps(expr)` does not denote a conditional scope.
390            // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`.
391            resolve_expr(visitor, expr, true);
392        }
393
394        _ => intravisit::walk_expr(visitor, expr),
395    }
396
397    visitor.cx = prev_cx;
398}
399
400#[derive(Copy, Clone, PartialEq, Eq, Debug)]
401enum LetKind {
402    Regular,
403    Super,
404}
405
406fn resolve_local<'tcx>(
407    visitor: &mut ScopeResolutionVisitor<'tcx>,
408    pat: Option<&'tcx hir::Pat<'tcx>>,
409    init: Option<&'tcx hir::Expr<'tcx>>,
410    let_kind: LetKind,
411) {
412    debug!("resolve_local(pat={:?}, init={:?}, let_kind={:?})", pat, init, let_kind);
413
414    // As an exception to the normal rules governing temporary
415    // lifetimes, initializers in a let have a temporary lifetime
416    // of the enclosing block. This means that e.g., a program
417    // like the following is legal:
418    //
419    //     let ref x = HashMap::new();
420    //
421    // Because the hash map will be freed in the enclosing block.
422    //
423    // We express the rules more formally based on 3 grammars (defined
424    // fully in the helpers below that implement them):
425    //
426    // 1. `E&`, which matches expressions like `&<rvalue>` that
427    //    own a pointer into the stack.
428    //
429    // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
430    //    y)` that produce ref bindings into the value they are
431    //    matched against or something (at least partially) owned by
432    //    the value they are matched against. (By partially owned,
433    //    I mean that creating a binding into a ref-counted or managed value
434    //    would still count.)
435    //
436    // 3. `ET`, which matches both rvalues like `foo()` as well as places
437    //    based on rvalues like `foo().x[2].y`.
438    //
439    // A subexpression `<rvalue>` that appears in a let initializer
440    // `let pat [: ty] = expr` has an extended temporary lifetime if
441    // any of the following conditions are met:
442    //
443    // A. `pat` matches `P&` and `expr` matches `ET`
444    //    (covers cases where `pat` creates ref bindings into an rvalue
445    //     produced by `expr`)
446    // B. `ty` is a borrowed pointer and `expr` matches `ET`
447    //    (covers cases where coercion creates a borrow)
448    // C. `expr` matches `E&`
449    //    (covers cases `expr` borrows an rvalue that is then assigned
450    //     to memory (at least partially) owned by the binding)
451    //
452    // Here are some examples hopefully giving an intuition where each
453    // rule comes into play and why:
454    //
455    // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
456    // would have an extended lifetime, but not `foo()`.
457    //
458    // Rule B. `let x = &foo().x`. The rvalue `foo()` would have extended
459    // lifetime.
460    //
461    // In some cases, multiple rules may apply (though not to the same
462    // rvalue). For example:
463    //
464    //     let ref x = [&a(), &b()];
465    //
466    // Here, the expression `[...]` has an extended lifetime due to rule
467    // A, but the inner rvalues `a()` and `b()` have an extended lifetime
468    // due to rule C.
469
470    if let_kind == LetKind::Super {
471        if let Some(scope) = visitor.extended_super_lets.remove(&pat.unwrap().hir_id.local_id) {
472            // This expression was lifetime-extended by a parent let binding. E.g.
473            //
474            //     let a = {
475            //         super let b = temp();
476            //         &b
477            //     };
478            //
479            // (Which needs to behave exactly as: let a = &temp();)
480            //
481            // Processing of `let a` will have already decided to extend the lifetime of this
482            // `super let` to its own var_scope. We use that scope.
483            visitor.cx.var_parent = scope;
484        } else {
485            // This `super let` is not subject to lifetime extension from a parent let binding. E.g.
486            //
487            //     identity({ super let x = temp(); &x }).method();
488            //
489            // (Which needs to behave exactly as: identity(&temp()).method();)
490            //
491            // Iterate up to the enclosing destruction scope to find the same scope that will also
492            // be used for the result of the block itself.
493            if let Some(inner_scope) = visitor.cx.var_parent {
494                (visitor.cx.var_parent, _) = visitor.scope_tree.default_temporary_scope(inner_scope)
495            }
496        }
497    }
498
499    if let Some(expr) = init {
500        record_rvalue_scope_if_borrow_expr(visitor, expr, visitor.cx.var_parent);
501
502        if let Some(pat) = pat {
503            if is_binding_pat(pat) {
504                visitor.scope_tree.record_rvalue_candidate(
505                    expr.hir_id,
506                    RvalueCandidate {
507                        target: expr.hir_id.local_id,
508                        lifetime: visitor.cx.var_parent,
509                    },
510                );
511            }
512        }
513    }
514
515    // Make sure we visit the initializer first.
516    // The correct order, as shared between drop_ranges and intravisitor,
517    // is to walk initializer, followed by pattern bindings, finally followed by the `else` block.
518    if let Some(expr) = init {
519        visitor.visit_expr(expr);
520    }
521
522    if let Some(pat) = pat {
523        visitor.visit_pat(pat);
524    }
525
526    /// Returns `true` if `pat` match the `P&` non-terminal.
527    ///
528    /// ```text
529    ///     P& = ref X
530    ///        | StructName { ..., P&, ... }
531    ///        | VariantName(..., P&, ...)
532    ///        | [ ..., P&, ... ]
533    ///        | ( ..., P&, ... )
534    ///        | ... "|" P& "|" ...
535    ///        | box P&
536    ///        | P& if ...
537    /// ```
538    fn is_binding_pat(pat: &hir::Pat<'_>) -> bool {
539        // Note that the code below looks for *explicit* refs only, that is, it won't
540        // know about *implicit* refs as introduced in #42640.
541        //
542        // This is not a problem. For example, consider
543        //
544        //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
545        //
546        // Due to the explicit refs on the left hand side, the below code would signal
547        // that the temporary value on the right hand side should live until the end of
548        // the enclosing block (as opposed to being dropped after the let is complete).
549        //
550        // To create an implicit ref, however, you must have a borrowed value on the RHS
551        // already, as in this example (which won't compile before #42640):
552        //
553        //      let Foo { x, .. } = &Foo { x: ..., ... };
554        //
555        // in place of
556        //
557        //      let Foo { ref x, .. } = Foo { ... };
558        //
559        // In the former case (the implicit ref version), the temporary is created by the
560        // & expression, and its lifetime would be extended to the end of the block (due
561        // to a different rule, not the below code).
562        match pat.kind {
563            PatKind::Binding(hir::BindingMode(hir::ByRef::Yes(_), _), ..) => true,
564
565            PatKind::Struct(_, field_pats, _) => field_pats.iter().any(|fp| is_binding_pat(fp.pat)),
566
567            PatKind::Slice(pats1, pats2, pats3) => {
568                pats1.iter().any(|p| is_binding_pat(p))
569                    || pats2.iter().any(|p| is_binding_pat(p))
570                    || pats3.iter().any(|p| is_binding_pat(p))
571            }
572
573            PatKind::Or(subpats)
574            | PatKind::TupleStruct(_, subpats, _)
575            | PatKind::Tuple(subpats, _) => subpats.iter().any(|p| is_binding_pat(p)),
576
577            PatKind::Box(subpat) | PatKind::Deref(subpat) | PatKind::Guard(subpat, _) => {
578                is_binding_pat(subpat)
579            }
580
581            PatKind::Ref(_, _)
582            | PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), ..)
583            | PatKind::Missing
584            | PatKind::Wild
585            | PatKind::Never
586            | PatKind::Expr(_)
587            | PatKind::Range(_, _, _)
588            | PatKind::Err(_) => false,
589        }
590    }
591
592    /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
593    ///
594    /// ```text
595    ///     E& = & ET
596    ///        | StructName { ..., f: E&, ... }
597    ///        | [ ..., E&, ... ]
598    ///        | ( ..., E&, ... )
599    ///        | {...; E&}
600    ///        | { super let ... = E&; ... }
601    ///        | if _ { ...; E& } else { ...; E& }
602    ///        | match _ { ..., _ => E&, ... }
603    ///        | box E&
604    ///        | E& as ...
605    ///        | ( E& )
606    /// ```
607    fn record_rvalue_scope_if_borrow_expr<'tcx>(
608        visitor: &mut ScopeResolutionVisitor<'tcx>,
609        expr: &hir::Expr<'_>,
610        blk_id: Option<Scope>,
611    ) {
612        match expr.kind {
613            hir::ExprKind::AddrOf(_, _, subexpr) => {
614                record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
615                visitor.scope_tree.record_rvalue_candidate(
616                    subexpr.hir_id,
617                    RvalueCandidate { target: subexpr.hir_id.local_id, lifetime: blk_id },
618                );
619            }
620            hir::ExprKind::Struct(_, fields, _) => {
621                for field in fields {
622                    record_rvalue_scope_if_borrow_expr(visitor, field.expr, blk_id);
623                }
624            }
625            hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => {
626                for subexpr in subexprs {
627                    record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
628                }
629            }
630            hir::ExprKind::Cast(subexpr, _) => {
631                record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id)
632            }
633            hir::ExprKind::Block(block, _) => {
634                if let Some(subexpr) = block.expr {
635                    record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
636                }
637                for stmt in block.stmts {
638                    if let hir::StmtKind::Let(local) = stmt.kind
639                        && let Some(_) = local.super_
640                    {
641                        visitor.extended_super_lets.insert(local.pat.hir_id.local_id, blk_id);
642                    }
643                }
644            }
645            hir::ExprKind::If(_, then_block, else_block) => {
646                record_rvalue_scope_if_borrow_expr(visitor, then_block, blk_id);
647                if let Some(else_block) = else_block {
648                    record_rvalue_scope_if_borrow_expr(visitor, else_block, blk_id);
649                }
650            }
651            hir::ExprKind::Match(_, arms, _) => {
652                for arm in arms {
653                    record_rvalue_scope_if_borrow_expr(visitor, arm.body, blk_id);
654                }
655            }
656            hir::ExprKind::Call(func, args) => {
657                // Recurse into tuple constructors, such as `Some(&temp())`.
658                //
659                // That way, there is no difference between `Some(..)` and `Some { 0: .. }`,
660                // even though the former is syntactically a function call.
661                if let hir::ExprKind::Path(path) = &func.kind
662                    && let hir::QPath::Resolved(None, path) = path
663                    && let Res::SelfCtor(_) | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) = path.res
664                {
665                    for arg in args {
666                        record_rvalue_scope_if_borrow_expr(visitor, arg, blk_id);
667                    }
668                }
669            }
670            _ => {}
671        }
672    }
673}
674
675impl<'tcx> ScopeResolutionVisitor<'tcx> {
676    /// Records the current parent (if any) as the parent of `child_scope`.
677    fn record_child_scope(&mut self, child_scope: Scope) {
678        let parent = self.cx.parent;
679        self.scope_tree.record_scope_parent(child_scope, parent);
680    }
681
682    /// Records the current parent (if any) as the parent of `child_scope`,
683    /// and sets `child_scope` as the new current parent.
684    fn enter_scope(&mut self, child_scope: Scope) {
685        self.record_child_scope(child_scope);
686        self.cx.parent = Some(child_scope);
687    }
688
689    fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId, terminating: bool) {
690        // If node was previously marked as a terminating scope during the
691        // recursive visit of its parent node in the HIR, then we need to
692        // account for the destruction scope representing the scope of
693        // the destructors that run immediately after it completes.
694        if terminating {
695            self.enter_scope(Scope { local_id: id, data: ScopeData::Destruction });
696        }
697        self.enter_scope(Scope { local_id: id, data: ScopeData::Node });
698    }
699
700    fn enter_body(&mut self, hir_id: hir::HirId, f: impl FnOnce(&mut Self)) {
701        let outer_cx = self.cx;
702
703        self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::CallSite });
704        self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::Arguments });
705
706        f(self);
707
708        // Restore context we had at the start.
709        self.cx = outer_cx;
710    }
711}
712
713impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
714    fn visit_block(&mut self, b: &'tcx Block<'tcx>) {
715        resolve_block(self, b, false);
716    }
717
718    fn visit_body(&mut self, body: &hir::Body<'tcx>) {
719        let body_id = body.id();
720        let owner_id = self.tcx.hir_body_owner_def_id(body_id);
721
722        debug!(
723            "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
724            owner_id,
725            self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span),
726            body_id,
727            self.cx.parent
728        );
729
730        self.enter_body(body.value.hir_id, |this| {
731            if this.tcx.hir_body_owner_kind(owner_id).is_fn_or_closure() {
732                // The arguments and `self` are parented to the fn.
733                this.cx.var_parent = this.cx.parent;
734                for param in body.params {
735                    this.visit_pat(param.pat);
736                }
737
738                // The body of the every fn is a root scope.
739                resolve_expr(this, body.value, true);
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                this.cx.var_parent = None;
760                this.enter_scope(Scope {
761                    local_id: body.value.hir_id.local_id,
762                    data: ScopeData::Destruction,
763                });
764                resolve_local(this, None, Some(body.value), LetKind::Regular);
765            }
766        })
767    }
768
769    fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) {
770        resolve_arm(self, a);
771    }
772    fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
773        resolve_pat(self, p);
774    }
775    fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) {
776        resolve_stmt(self, s);
777    }
778    fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
779        resolve_expr(self, ex, false);
780    }
781    fn visit_local(&mut self, l: &'tcx LetStmt<'tcx>) {
782        let let_kind = match l.super_ {
783            Some(_) => LetKind::Super,
784            None => LetKind::Regular,
785        };
786        resolve_local(self, Some(l.pat), l.init, let_kind);
787    }
788    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
789        let body = self.tcx.hir_body(c.body);
790        self.visit_body(body);
791    }
792}
793
794/// Per-body `region::ScopeTree`. The `DefId` should be the owner `DefId` for the body;
795/// in the case of closures, this will be redirected to the enclosing function.
796///
797/// Performance: This is a query rather than a simple function to enable
798/// re-use in incremental scenarios. We may sometimes need to rerun the
799/// type checker even when the HIR hasn't changed, and in those cases
800/// we can avoid reconstructing the region scope tree.
801pub(crate) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree {
802    let typeck_root_def_id = tcx.typeck_root_def_id(def_id);
803    if typeck_root_def_id != def_id {
804        return tcx.region_scope_tree(typeck_root_def_id);
805    }
806
807    let scope_tree = if let Some(body) = tcx.hir_maybe_body_owned_by(def_id.expect_local()) {
808        let mut visitor = ScopeResolutionVisitor {
809            tcx,
810            scope_tree: ScopeTree::default(),
811            cx: Context { parent: None, var_parent: None },
812            extended_super_lets: Default::default(),
813        };
814
815        visitor.scope_tree.root_body = Some(body.value.hir_id);
816        visitor.visit_body(&body);
817        visitor.scope_tree
818    } else {
819        ScopeTree::default()
820    };
821
822    tcx.arena.alloc(scope_tree)
823}