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    let extend_initializer = match let_kind {
471        LetKind::Regular => true,
472        LetKind::Super
473            if let Some(scope) =
474                visitor.extended_super_lets.remove(&pat.unwrap().hir_id.local_id) =>
475        {
476            // This expression was lifetime-extended by a parent let binding. E.g.
477            //
478            //     let a = {
479            //         super let b = temp();
480            //         &b
481            //     };
482            //
483            // (Which needs to behave exactly as: let a = &temp();)
484            //
485            // Processing of `let a` will have already decided to extend the lifetime of this
486            // `super let` to its own var_scope. We use that scope.
487            visitor.cx.var_parent = scope;
488            // Extend temporaries to live in the same scope as the parent `let`'s bindings.
489            true
490        }
491        LetKind::Super => {
492            // This `super let` is not subject to lifetime extension from a parent let binding. E.g.
493            //
494            //     identity({ super let x = temp(); &x }).method();
495            //
496            // (Which needs to behave exactly as: identity(&temp()).method();)
497            //
498            // Iterate up to the enclosing destruction scope to find the same scope that will also
499            // be used for the result of the block itself.
500            if let Some(inner_scope) = visitor.cx.var_parent {
501                (visitor.cx.var_parent, _) = visitor.scope_tree.default_temporary_scope(inner_scope)
502            }
503            // Don't lifetime-extend child `super let`s or block tail expressions' temporaries in
504            // the initializer when this `super let` is not itself extended by a parent `let`
505            // (#145784). Block tail expressions are temporary drop scopes in Editions 2024 and
506            // later, their temps shouldn't outlive the block in e.g. `f(pin!({ &temp() }))`.
507            false
508        }
509    };
510
511    if let Some(expr) = init
512        && extend_initializer
513    {
514        record_rvalue_scope_if_borrow_expr(visitor, expr, visitor.cx.var_parent);
515
516        if let Some(pat) = pat {
517            if is_binding_pat(pat) {
518                visitor.scope_tree.record_rvalue_candidate(
519                    expr.hir_id,
520                    RvalueCandidate {
521                        target: expr.hir_id.local_id,
522                        lifetime: visitor.cx.var_parent,
523                    },
524                );
525            }
526        }
527    }
528
529    // Make sure we visit the initializer first.
530    // The correct order, as shared between drop_ranges and intravisitor,
531    // is to walk initializer, followed by pattern bindings, finally followed by the `else` block.
532    if let Some(expr) = init {
533        visitor.visit_expr(expr);
534    }
535
536    if let Some(pat) = pat {
537        visitor.visit_pat(pat);
538    }
539
540    /// Returns `true` if `pat` match the `P&` non-terminal.
541    ///
542    /// ```text
543    ///     P& = ref X
544    ///        | StructName { ..., P&, ... }
545    ///        | VariantName(..., P&, ...)
546    ///        | [ ..., P&, ... ]
547    ///        | ( ..., P&, ... )
548    ///        | ... "|" P& "|" ...
549    ///        | box P&
550    ///        | P& if ...
551    /// ```
552    fn is_binding_pat(pat: &hir::Pat<'_>) -> bool {
553        // Note that the code below looks for *explicit* refs only, that is, it won't
554        // know about *implicit* refs as introduced in #42640.
555        //
556        // This is not a problem. For example, consider
557        //
558        //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
559        //
560        // Due to the explicit refs on the left hand side, the below code would signal
561        // that the temporary value on the right hand side should live until the end of
562        // the enclosing block (as opposed to being dropped after the let is complete).
563        //
564        // To create an implicit ref, however, you must have a borrowed value on the RHS
565        // already, as in this example (which won't compile before #42640):
566        //
567        //      let Foo { x, .. } = &Foo { x: ..., ... };
568        //
569        // in place of
570        //
571        //      let Foo { ref x, .. } = Foo { ... };
572        //
573        // In the former case (the implicit ref version), the temporary is created by the
574        // & expression, and its lifetime would be extended to the end of the block (due
575        // to a different rule, not the below code).
576        match pat.kind {
577            PatKind::Binding(hir::BindingMode(hir::ByRef::Yes(_), _), ..) => true,
578
579            PatKind::Struct(_, field_pats, _) => field_pats.iter().any(|fp| is_binding_pat(fp.pat)),
580
581            PatKind::Slice(pats1, pats2, pats3) => {
582                pats1.iter().any(|p| is_binding_pat(p))
583                    || pats2.iter().any(|p| is_binding_pat(p))
584                    || pats3.iter().any(|p| is_binding_pat(p))
585            }
586
587            PatKind::Or(subpats)
588            | PatKind::TupleStruct(_, subpats, _)
589            | PatKind::Tuple(subpats, _) => subpats.iter().any(|p| is_binding_pat(p)),
590
591            PatKind::Box(subpat) | PatKind::Deref(subpat) | PatKind::Guard(subpat, _) => {
592                is_binding_pat(subpat)
593            }
594
595            PatKind::Ref(_, _)
596            | PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), ..)
597            | PatKind::Missing
598            | PatKind::Wild
599            | PatKind::Never
600            | PatKind::Expr(_)
601            | PatKind::Range(_, _, _)
602            | PatKind::Err(_) => false,
603        }
604    }
605
606    /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
607    ///
608    /// ```text
609    ///     E& = & ET
610    ///        | StructName { ..., f: E&, ... }
611    ///        | [ ..., E&, ... ]
612    ///        | ( ..., E&, ... )
613    ///        | {...; E&}
614    ///        | { super let ... = E&; ... }
615    ///        | if _ { ...; E& } else { ...; E& }
616    ///        | match _ { ..., _ => E&, ... }
617    ///        | box E&
618    ///        | E& as ...
619    ///        | ( E& )
620    /// ```
621    fn record_rvalue_scope_if_borrow_expr<'tcx>(
622        visitor: &mut ScopeResolutionVisitor<'tcx>,
623        expr: &hir::Expr<'_>,
624        blk_id: Option<Scope>,
625    ) {
626        match expr.kind {
627            hir::ExprKind::AddrOf(_, _, subexpr) => {
628                record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
629                visitor.scope_tree.record_rvalue_candidate(
630                    subexpr.hir_id,
631                    RvalueCandidate { target: subexpr.hir_id.local_id, lifetime: blk_id },
632                );
633            }
634            hir::ExprKind::Struct(_, fields, _) => {
635                for field in fields {
636                    record_rvalue_scope_if_borrow_expr(visitor, field.expr, blk_id);
637                }
638            }
639            hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => {
640                for subexpr in subexprs {
641                    record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
642                }
643            }
644            hir::ExprKind::Cast(subexpr, _) => {
645                record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id)
646            }
647            hir::ExprKind::Block(block, _) => {
648                if let Some(subexpr) = block.expr {
649                    record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
650                }
651                for stmt in block.stmts {
652                    if let hir::StmtKind::Let(local) = stmt.kind
653                        && let Some(_) = local.super_
654                    {
655                        visitor.extended_super_lets.insert(local.pat.hir_id.local_id, blk_id);
656                    }
657                }
658            }
659            hir::ExprKind::If(_, then_block, else_block) => {
660                record_rvalue_scope_if_borrow_expr(visitor, then_block, blk_id);
661                if let Some(else_block) = else_block {
662                    record_rvalue_scope_if_borrow_expr(visitor, else_block, blk_id);
663                }
664            }
665            hir::ExprKind::Match(_, arms, _) => {
666                for arm in arms {
667                    record_rvalue_scope_if_borrow_expr(visitor, arm.body, blk_id);
668                }
669            }
670            hir::ExprKind::Call(func, args) => {
671                // Recurse into tuple constructors, such as `Some(&temp())`.
672                //
673                // That way, there is no difference between `Some(..)` and `Some { 0: .. }`,
674                // even though the former is syntactically a function call.
675                if let hir::ExprKind::Path(path) = &func.kind
676                    && let hir::QPath::Resolved(None, path) = path
677                    && let Res::SelfCtor(_) | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) = path.res
678                {
679                    for arg in args {
680                        record_rvalue_scope_if_borrow_expr(visitor, arg, blk_id);
681                    }
682                }
683            }
684            _ => {}
685        }
686    }
687}
688
689impl<'tcx> ScopeResolutionVisitor<'tcx> {
690    /// Records the current parent (if any) as the parent of `child_scope`.
691    fn record_child_scope(&mut self, child_scope: Scope) {
692        let parent = self.cx.parent;
693        self.scope_tree.record_scope_parent(child_scope, parent);
694    }
695
696    /// Records the current parent (if any) as the parent of `child_scope`,
697    /// and sets `child_scope` as the new current parent.
698    fn enter_scope(&mut self, child_scope: Scope) {
699        self.record_child_scope(child_scope);
700        self.cx.parent = Some(child_scope);
701    }
702
703    fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId, terminating: bool) {
704        // If node was previously marked as a terminating scope during the
705        // recursive visit of its parent node in the HIR, then we need to
706        // account for the destruction scope representing the scope of
707        // the destructors that run immediately after it completes.
708        if terminating {
709            self.enter_scope(Scope { local_id: id, data: ScopeData::Destruction });
710        }
711        self.enter_scope(Scope { local_id: id, data: ScopeData::Node });
712    }
713
714    fn enter_body(&mut self, hir_id: hir::HirId, f: impl FnOnce(&mut Self)) {
715        let outer_cx = self.cx;
716
717        self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::CallSite });
718        self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::Arguments });
719
720        f(self);
721
722        // Restore context we had at the start.
723        self.cx = outer_cx;
724    }
725}
726
727impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
728    fn visit_block(&mut self, b: &'tcx Block<'tcx>) {
729        resolve_block(self, b, false);
730    }
731
732    fn visit_body(&mut self, body: &hir::Body<'tcx>) {
733        let body_id = body.id();
734        let owner_id = self.tcx.hir_body_owner_def_id(body_id);
735
736        debug!(
737            "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
738            owner_id,
739            self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span),
740            body_id,
741            self.cx.parent
742        );
743
744        self.enter_body(body.value.hir_id, |this| {
745            if this.tcx.hir_body_owner_kind(owner_id).is_fn_or_closure() {
746                // The arguments and `self` are parented to the fn.
747                this.cx.var_parent = this.cx.parent;
748                for param in body.params {
749                    this.visit_pat(param.pat);
750                }
751
752                // The body of the every fn is a root scope.
753                resolve_expr(this, body.value, true);
754            } else {
755                // Only functions have an outer terminating (drop) scope, while
756                // temporaries in constant initializers may be 'static, but only
757                // according to rvalue lifetime semantics, using the same
758                // syntactical rules used for let initializers.
759                //
760                // e.g., in `let x = &f();`, the temporary holding the result from
761                // the `f()` call lives for the entirety of the surrounding block.
762                //
763                // Similarly, `const X: ... = &f();` would have the result of `f()`
764                // live for `'static`, implying (if Drop restrictions on constants
765                // ever get lifted) that the value *could* have a destructor, but
766                // it'd get leaked instead of the destructor running during the
767                // evaluation of `X` (if at all allowed by CTFE).
768                //
769                // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
770                // would *not* let the `f()` temporary escape into an outer scope
771                // (i.e., `'static`), which means that after `g` returns, it drops,
772                // and all the associated destruction scope rules apply.
773                this.cx.var_parent = None;
774                this.enter_scope(Scope {
775                    local_id: body.value.hir_id.local_id,
776                    data: ScopeData::Destruction,
777                });
778                resolve_local(this, None, Some(body.value), LetKind::Regular);
779            }
780        })
781    }
782
783    fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) {
784        resolve_arm(self, a);
785    }
786    fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
787        resolve_pat(self, p);
788    }
789    fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) {
790        resolve_stmt(self, s);
791    }
792    fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
793        resolve_expr(self, ex, false);
794    }
795    fn visit_local(&mut self, l: &'tcx LetStmt<'tcx>) {
796        let let_kind = match l.super_ {
797            Some(_) => LetKind::Super,
798            None => LetKind::Regular,
799        };
800        resolve_local(self, Some(l.pat), l.init, let_kind);
801    }
802    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
803        let body = self.tcx.hir_body(c.body);
804        self.visit_body(body);
805    }
806}
807
808/// Per-body `region::ScopeTree`. The `DefId` should be the owner `DefId` for the body;
809/// in the case of closures, this will be redirected to the enclosing function.
810///
811/// Performance: This is a query rather than a simple function to enable
812/// re-use in incremental scenarios. We may sometimes need to rerun the
813/// type checker even when the HIR hasn't changed, and in those cases
814/// we can avoid reconstructing the region scope tree.
815pub(crate) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree {
816    let typeck_root_def_id = tcx.typeck_root_def_id(def_id);
817    if typeck_root_def_id != def_id {
818        return tcx.region_scope_tree(typeck_root_def_id);
819    }
820
821    let scope_tree = if let Some(body) = tcx.hir_maybe_body_owned_by(def_id.expect_local()) {
822        let mut visitor = ScopeResolutionVisitor {
823            tcx,
824            scope_tree: ScopeTree::default(),
825            cx: Context { parent: None, var_parent: None },
826            extended_super_lets: Default::default(),
827        };
828
829        visitor.scope_tree.root_body = Some(body.value.hir_id);
830        visitor.visit_body(&body);
831        visitor.scope_tree
832    } else {
833        ScopeTree::default()
834    };
835
836    tcx.arena.alloc(scope_tree)
837}