Skip to main content

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::LocalDefId;
15use rustc_hir::intravisit::{self, Visitor};
16use rustc_hir::{Arm, Block, Expr, LetStmt, Pat, PatKind, Stmt};
17use rustc_index::Idx;
18use rustc_lint_defs::LintId;
19use rustc_lint_defs::builtin::TAIL_EXPR_DROP_ORDER;
20use rustc_middle::middle::region::*;
21use rustc_middle::ty::TyCtxt;
22use rustc_span::Spanned;
23use tracing::debug;
24
25#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Context {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Context",
            "var_parent", &self.var_parent, "parent", &&self.parent)
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for Context { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Context { }
#[automatically_derived]
impl ::core::clone::Clone for Context {
    #[inline]
    fn clone(&self) -> Context {
        let _: ::core::clone::AssertParamIsClone<Option<Scope>>;
        let _: ::core::clone::AssertParamIsClone<Option<Scope>>;
        *self
    }
}Clone)]
26struct Context {
27    /// The scope that contains any new variables declared.
28    var_parent: Option<Scope>,
29
30    /// Region parent of expressions, etc.
31    parent: Option<Scope>,
32}
33
34struct ScopeResolutionVisitor<'tcx> {
35    tcx: TyCtxt<'tcx>,
36
37    // The generated scope tree.
38    scope_tree: ScopeTree,
39
40    cx: Context,
41
42    extended_super_lets: FxHashMap<hir::ItemLocalId, Option<Scope>>,
43}
44
45/// Records the lifetime of a local variable as `cx.var_parent`
46fn record_var_lifetime(visitor: &mut ScopeResolutionVisitor<'_>, var_id: hir::ItemLocalId) {
47    match visitor.cx.var_parent {
48        None => {
49            // this can happen in extern fn declarations like
50            //
51            // extern fn isalnum(c: c_int) -> c_int
52        }
53        Some(parent_scope) => visitor.scope_tree.record_var_scope(var_id, parent_scope),
54    }
55}
56
57fn resolve_block<'tcx>(
58    visitor: &mut ScopeResolutionVisitor<'tcx>,
59    blk: &'tcx hir::Block<'tcx>,
60    terminating: bool,
61) {
62    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/region.rs:62",
                        "rustc_hir_analysis::check::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(62u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_block(blk.hir_id={0:?})",
                                                    blk.hir_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_block(blk.hir_id={:?})", blk.hir_id);
63
64    let prev_cx = visitor.cx;
65
66    // We treat the tail expression in the block (if any) somewhat
67    // differently from the statements. The issue has to do with
68    // temporary lifetimes. Consider the following:
69    //
70    //    quux({
71    //        let inner = ... (&bar()) ...;
72    //
73    //        (... (&foo()) ...) // (the tail expression)
74    //    }, other_argument());
75    //
76    // Each of the statements within the block is a terminating
77    // scope, and thus a temporary (e.g., the result of calling
78    // `bar()` in the initializer expression for `let inner = ...;`)
79    // will be cleaned up immediately after its corresponding
80    // statement (i.e., `let inner = ...;`) executes.
81    //
82    // On the other hand, temporaries associated with evaluating the
83    // tail expression for the block are assigned lifetimes so that
84    // they will be cleaned up as part of the terminating scope
85    // *surrounding* the block expression. Here, the terminating
86    // scope for the block expression is the `quux(..)` call; so
87    // those temporaries will only be cleaned up *after* both
88    // `other_argument()` has run and also the call to `quux(..)`
89    // itself has returned.
90
91    visitor.enter_node_scope_with_dtor(blk.hir_id.local_id, terminating);
92    visitor.cx.var_parent = visitor.cx.parent;
93
94    {
95        // This block should be kept approximately in sync with
96        // `intravisit::walk_block`. (We manually walk the block, rather
97        // than call `walk_block`, in order to maintain precise
98        // index information.)
99
100        for (i, statement) in blk.stmts.iter().enumerate() {
101            match statement.kind {
102                hir::StmtKind::Let(LetStmt { els: Some(els), .. }) => {
103                    // let-else has a special lexical structure for variables.
104                    // First we take a checkpoint of the current scope context here.
105                    let mut prev_cx = visitor.cx;
106
107                    visitor.enter_scope(Scope {
108                        local_id: blk.hir_id.local_id,
109                        data: ScopeData::Remainder(FirstStatementIndex::new(i)),
110                    });
111                    visitor.cx.var_parent = visitor.cx.parent;
112                    visitor.visit_stmt(statement);
113                    // We need to back out temporarily to the last enclosing scope
114                    // for the `else` block, so that even the temporaries receiving
115                    // extended lifetime will be dropped inside this block.
116                    // We are visiting the `else` block in this order so that
117                    // the sequence of visits agree with the order in the default
118                    // `hir::intravisit` visitor.
119                    mem::swap(&mut prev_cx, &mut visitor.cx);
120                    resolve_block(visitor, els, true);
121                    // From now on, we continue normally.
122                    visitor.cx = prev_cx;
123                }
124                hir::StmtKind::Let(..) => {
125                    // Each declaration introduces a subscope for bindings
126                    // introduced by the declaration; this subscope covers a
127                    // suffix of the block. Each subscope in a block has the
128                    // previous subscope in the block as a parent, except for
129                    // the first such subscope, which has the block itself as a
130                    // parent.
131                    visitor.enter_scope(Scope {
132                        local_id: blk.hir_id.local_id,
133                        data: ScopeData::Remainder(FirstStatementIndex::new(i)),
134                    });
135                    visitor.cx.var_parent = visitor.cx.parent;
136                    visitor.visit_stmt(statement)
137                }
138                hir::StmtKind::Item(..) => {
139                    // Don't create scopes for items, since they won't be
140                    // lowered to THIR and MIR.
141                }
142                hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => visitor.visit_stmt(statement),
143            }
144        }
145        if let Some(tail_expr) = blk.expr {
146            let local_id = tail_expr.hir_id.local_id;
147            let edition = blk.span.edition();
148            let terminating = edition.at_least_rust_2024();
149            if !terminating
150                && !visitor.tcx.skippable_lints(()).contains(&LintId::of(TAIL_EXPR_DROP_ORDER))
151            {
152                // If this temporary scope will be changing once the codebase adopts Rust 2024,
153                // and we are linting about possible semantic changes that would result,
154                // then record this node-id in the field `backwards_incompatible_scope`
155                // for future reference.
156                visitor
157                    .scope_tree
158                    .backwards_incompatible_scope
159                    .insert(local_id, Scope { local_id, data: ScopeData::Node });
160            }
161            resolve_expr(visitor, tail_expr, terminating);
162        }
163    }
164
165    visitor.cx = prev_cx;
166}
167
168/// Resolve a condition from an `if` expression or match guard so that it is a terminating scope
169/// if it doesn't contain `let` expressions.
170fn resolve_cond<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, cond: &'tcx hir::Expr<'tcx>) {
171    let terminate = match cond.kind {
172        // Temporaries for `let` expressions must live into the success branch.
173        hir::ExprKind::Let(_) => false,
174        // Logical operator chains are handled in `resolve_expr`. Since logical operator chains in
175        // conditions are lowered to control-flow rather than boolean temporaries, there's no
176        // temporary to drop for logical operators themselves. `resolve_expr` will also recursively
177        // wrap any operands in terminating scopes, other than `let` expressions (which we shouldn't
178        // terminate) and other logical operators (which don't need a terminating scope, since their
179        // operands will be terminated). Any temporaries that would need to be dropped will be
180        // dropped before we leave this operator's scope; terminating them here would be redundant.
181        hir::ExprKind::Binary(
182            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
183            _,
184            _,
185        ) => false,
186        // Otherwise, conditions should always drop their temporaries.
187        _ => true,
188    };
189    resolve_expr(visitor, cond, terminate);
190}
191
192fn resolve_arm<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, arm: &'tcx hir::Arm<'tcx>) {
193    let prev_cx = visitor.cx;
194
195    visitor.enter_node_scope_with_dtor(arm.hir_id.local_id, true);
196    visitor.cx.var_parent = visitor.cx.parent;
197
198    resolve_pat(visitor, arm.pat);
199    if let Some(guard) = arm.guard {
200        // We introduce a new scope to contain bindings and temporaries from `if let` guards, to
201        // ensure they're dropped before the arm's pattern's bindings. This extends to the end of
202        // the arm body and is the scope of its locals as well.
203        visitor.enter_scope(Scope { local_id: arm.hir_id.local_id, data: ScopeData::MatchGuard });
204        visitor.cx.var_parent = visitor.cx.parent;
205        resolve_cond(visitor, guard);
206    }
207    resolve_expr(visitor, arm.body, false);
208
209    visitor.cx = prev_cx;
210}
211
212{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_pat",
                                    "rustc_hir_analysis::check::region",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/region.rs"),
                                    ::tracing_core::__macro_support::Option::Some(212u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::region"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pat")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pat");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let PatKind::Binding(..) = pat.kind {
                record_var_lifetime(visitor, pat.hir_id.local_id);
            }
            intravisit::walk_pat(visitor, pat);
        }
    }
}#[tracing::instrument(level = "debug", skip(visitor))]
213fn resolve_pat<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) {
214    // If this is a binding then record the lifetime of that binding.
215    if let PatKind::Binding(..) = pat.kind {
216        record_var_lifetime(visitor, pat.hir_id.local_id);
217    }
218
219    intravisit::walk_pat(visitor, pat);
220}
221
222fn resolve_stmt<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) {
223    let stmt_id = stmt.hir_id.local_id;
224    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/region.rs:224",
                        "rustc_hir_analysis::check::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(224u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_stmt(stmt.id={0:?})",
                                                    stmt_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_stmt(stmt.id={:?})", stmt_id);
225
226    if let hir::StmtKind::Let(LetStmt { super_: Some(_), .. }) = stmt.kind {
227        // `super let` statement does not start a new scope, such that
228        //
229        //     { super let x = identity(&temp()); &x }.method();
230        //
231        // behaves exactly as
232        //
233        //     (&identity(&temp()).method();
234        intravisit::walk_stmt(visitor, stmt);
235    } else {
236        // Every statement will clean up the temporaries created during
237        // execution of that statement. Therefore each statement has an
238        // associated destruction scope that represents the scope of the
239        // statement plus its destructors, and thus the scope for which
240        // regions referenced by the destructors need to survive.
241
242        let prev_parent = visitor.cx.parent;
243        visitor.enter_node_scope_with_dtor(stmt_id, true);
244
245        intravisit::walk_stmt(visitor, stmt);
246
247        visitor.cx.parent = prev_parent;
248    }
249}
250
251{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_expr",
                                    "rustc_hir_analysis::check::region",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/region.rs"),
                                    ::tracing_core::__macro_support::Option::Some(251u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::region"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("terminating")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("terminating");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&terminating as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let prev_cx = visitor.cx;
            visitor.enter_node_scope_with_dtor(expr.hir_id.local_id,
                terminating);
            match expr.kind {
                hir::ExprKind::Binary(Spanned {
                    node: hir::BinOpKind::And | hir::BinOpKind::Or, .. }, left,
                    right) => {
                    let terminate_lhs =
                        match left.kind {
                            hir::ExprKind::Let(_) => false,
                            hir::ExprKind::Binary(Spanned {
                                node: hir::BinOpKind::And | hir::BinOpKind::Or, .. }, ..) =>
                                false,
                            _ => true,
                        };
                    let terminate_rhs =
                        !#[allow(non_exhaustive_omitted_patterns)] match right.kind
                                {
                                hir::ExprKind::Let(_) => true,
                                _ => false,
                            };
                    resolve_expr(visitor, left, terminate_lhs);
                    resolve_expr(visitor, right, terminate_rhs);
                }
                hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
                    let body = visitor.tcx.hir_body(body);
                    visitor.visit_body(body);
                }
                hir::ExprKind::AssignOp(_, left_expr, right_expr) => {
                    visitor.visit_expr(right_expr);
                    visitor.visit_expr(left_expr);
                }
                hir::ExprKind::If(cond, then, Some(otherwise)) => {
                    let expr_cx = visitor.cx;
                    let data =
                        if expr.span.at_least_rust_2024() {
                            ScopeData::IfThenRescope
                        } else { ScopeData::IfThen };
                    visitor.enter_scope(Scope {
                            local_id: then.hir_id.local_id,
                            data,
                        });
                    visitor.cx.var_parent = visitor.cx.parent;
                    resolve_cond(visitor, cond);
                    resolve_expr(visitor, then, true);
                    visitor.cx = expr_cx;
                    resolve_expr(visitor, otherwise, true);
                }
                hir::ExprKind::If(cond, then, None) => {
                    let expr_cx = visitor.cx;
                    let data =
                        if expr.span.at_least_rust_2024() {
                            ScopeData::IfThenRescope
                        } else { ScopeData::IfThen };
                    visitor.enter_scope(Scope {
                            local_id: then.hir_id.local_id,
                            data,
                        });
                    visitor.cx.var_parent = visitor.cx.parent;
                    resolve_cond(visitor, cond);
                    resolve_expr(visitor, then, true);
                    visitor.cx = expr_cx;
                }
                hir::ExprKind::Loop(body, _, _, _) => {
                    resolve_block(visitor, body, true);
                }
                hir::ExprKind::DropTemps(expr) => {
                    resolve_expr(visitor, expr, true);
                }
                _ => intravisit::walk_expr(visitor, expr),
            }
            visitor.cx = prev_cx;
        }
    }
}#[tracing::instrument(level = "debug", skip(visitor))]
252fn resolve_expr<'tcx>(
253    visitor: &mut ScopeResolutionVisitor<'tcx>,
254    expr: &'tcx hir::Expr<'tcx>,
255    terminating: bool,
256) {
257    let prev_cx = visitor.cx;
258    visitor.enter_node_scope_with_dtor(expr.hir_id.local_id, terminating);
259
260    match expr.kind {
261        // Conditional or repeating scopes are always terminating
262        // scopes, meaning that temporaries cannot outlive them.
263        // This ensures fixed size stacks.
264        hir::ExprKind::Binary(
265            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
266            left,
267            right,
268        ) => {
269            // expr is a short circuiting operator (|| or &&). As its
270            // functionality can't be overridden by traits, it always
271            // processes bool sub-expressions. bools are Copy and thus we
272            // can drop any temporaries in evaluation (read) order
273            // (with the exception of potentially failing let expressions).
274            // We achieve this by enclosing the operands in a terminating
275            // scope, both the LHS and the RHS.
276
277            // We optimize this a little in the presence of chains.
278            // Chains like a && b && c get lowered to AND(AND(a, b), c).
279            // In here, b and c are RHS, while a is the only LHS operand in
280            // that chain. This holds true for longer chains as well: the
281            // leading operand is always the only LHS operand that is not a
282            // binop itself. Putting a binop like AND(a, b) into a
283            // terminating scope is not useful, thus we only put the LHS
284            // into a terminating scope if it is not a binop.
285
286            let terminate_lhs = match left.kind {
287                // let expressions can create temporaries that live on
288                hir::ExprKind::Let(_) => false,
289                // binops already drop their temporaries, so there is no
290                // need to put them into a terminating scope.
291                // This is purely an optimization to reduce the number of
292                // terminating scopes.
293                hir::ExprKind::Binary(
294                    Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
295                    ..,
296                ) => false,
297                // otherwise: mark it as terminating
298                _ => true,
299            };
300
301            // `Let` expressions (in a let-chain) shouldn't be terminating, as their temporaries
302            // should live beyond the immediate expression
303            let terminate_rhs = !matches!(right.kind, hir::ExprKind::Let(_));
304
305            resolve_expr(visitor, left, terminate_lhs);
306            resolve_expr(visitor, right, terminate_rhs);
307        }
308        // Manually recurse over closures, because they are nested bodies
309        // that share the parent environment. We handle const blocks in
310        // `visit_inline_const`.
311        hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
312            let body = visitor.tcx.hir_body(body);
313            visitor.visit_body(body);
314        }
315        // Ordinarily, we can rely on the visit order of HIR intravisit
316        // to correspond to the actual execution order of statements.
317        // However, there's a weird corner case with compound assignment
318        // operators (e.g. `a += b`). The evaluation order depends on whether
319        // or not the operator is overloaded (e.g. whether or not a trait
320        // like AddAssign is implemented).
321        //
322        // For primitive types (which, despite having a trait impl, don't actually
323        // end up calling it), the evaluation order is right-to-left. For example,
324        // the following code snippet:
325        //
326        //    let y = &mut 0;
327        //    *{println!("LHS!"); y} += {println!("RHS!"); 1};
328        //
329        // will print:
330        //
331        // RHS!
332        // LHS!
333        //
334        // However, if the operator is used on a non-primitive type,
335        // the evaluation order will be left-to-right, since the operator
336        // actually get desugared to a method call. For example, this
337        // nearly identical code snippet:
338        //
339        //     let y = &mut String::new();
340        //    *{println!("LHS String"); y} += {println!("RHS String"); "hi"};
341        //
342        // will print:
343        // LHS String
344        // RHS String
345        //
346        // To determine the actual execution order, we need to perform
347        // trait resolution. Fortunately, we don't need to know the actual execution order.
348        hir::ExprKind::AssignOp(_, left_expr, right_expr) => {
349            visitor.visit_expr(right_expr);
350            visitor.visit_expr(left_expr);
351        }
352
353        hir::ExprKind::If(cond, then, Some(otherwise)) => {
354            let expr_cx = visitor.cx;
355            let data = if expr.span.at_least_rust_2024() {
356                ScopeData::IfThenRescope
357            } else {
358                ScopeData::IfThen
359            };
360            visitor.enter_scope(Scope { local_id: then.hir_id.local_id, data });
361            visitor.cx.var_parent = visitor.cx.parent;
362            resolve_cond(visitor, cond);
363            resolve_expr(visitor, then, true);
364            visitor.cx = expr_cx;
365            resolve_expr(visitor, otherwise, true);
366        }
367
368        hir::ExprKind::If(cond, then, None) => {
369            let expr_cx = visitor.cx;
370            let data = if expr.span.at_least_rust_2024() {
371                ScopeData::IfThenRescope
372            } else {
373                ScopeData::IfThen
374            };
375            visitor.enter_scope(Scope { local_id: then.hir_id.local_id, data });
376            visitor.cx.var_parent = visitor.cx.parent;
377            resolve_cond(visitor, cond);
378            resolve_expr(visitor, then, true);
379            visitor.cx = expr_cx;
380        }
381
382        hir::ExprKind::Loop(body, _, _, _) => {
383            resolve_block(visitor, body, true);
384        }
385
386        hir::ExprKind::DropTemps(expr) => {
387            // `DropTemps(expr)` does not denote a conditional scope.
388            // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`.
389            resolve_expr(visitor, expr, true);
390        }
391
392        _ => intravisit::walk_expr(visitor, expr),
393    }
394
395    visitor.cx = prev_cx;
396}
397
398#[derive(#[automatically_derived]
impl ::core::marker::Copy for LetKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LetKind { }
#[automatically_derived]
impl ::core::clone::Clone for LetKind {
    #[inline]
    fn clone(&self) -> LetKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for LetKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for LetKind {
    #[inline]
    fn eq(&self, other: &LetKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LetKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for LetKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LetKind::Regular => "Regular",
                LetKind::Super => "Super",
            })
    }
}Debug)]
399enum LetKind {
400    Regular,
401    Super,
402}
403
404fn resolve_local<'tcx>(
405    visitor: &mut ScopeResolutionVisitor<'tcx>,
406    pat: Option<&'tcx hir::Pat<'tcx>>,
407    init: Option<&'tcx hir::Expr<'tcx>>,
408    let_kind: LetKind,
409) {
410    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/region.rs:410",
                        "rustc_hir_analysis::check::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(410u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_local(pat={0:?}, init={1:?}, let_kind={2:?})",
                                                    pat, init, let_kind) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_local(pat={:?}, init={:?}, let_kind={:?})", pat, init, let_kind);
411
412    // As an exception to the normal rules governing temporary
413    // lifetimes, initializers in a let have a temporary lifetime
414    // of the enclosing block. This means that e.g., a program
415    // like the following is legal:
416    //
417    //     let ref x = HashMap::new();
418    //
419    // Because the hash map will be freed in the enclosing block.
420    //
421    // We express the rules more formally based on 3 grammars (defined
422    // fully in the helpers below that implement them):
423    //
424    // 1. `E&`, which matches expressions like `&<rvalue>` that
425    //    own a pointer into the stack.
426    //
427    // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
428    //    y)` that produce ref bindings into the value they are
429    //    matched against or something (at least partially) owned by
430    //    the value they are matched against. (By partially owned,
431    //    I mean that creating a binding into a ref-counted or managed value
432    //    would still count.)
433    //
434    // 3. `ET`, which matches both rvalues like `foo()` as well as places
435    //    based on rvalues like `foo().x[2].y`.
436    //
437    // A subexpression `<rvalue>` that appears in a let initializer
438    // `let pat [: ty] = expr` has an extended temporary lifetime if
439    // any of the following conditions are met:
440    //
441    // A. `pat` matches `P&` and `expr` matches `ET`
442    //    (covers cases where `pat` creates ref bindings into an rvalue
443    //     produced by `expr`)
444    // B. `ty` is a borrowed pointer and `expr` matches `ET`
445    //    (covers cases where coercion creates a borrow)
446    // C. `expr` matches `E&`
447    //    (covers cases `expr` borrows an rvalue that is then assigned
448    //     to memory (at least partially) owned by the binding)
449    //
450    // Here are some examples hopefully giving an intuition where each
451    // rule comes into play and why:
452    //
453    // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
454    // would have an extended lifetime, but not `foo()`.
455    //
456    // Rule B. `let x = &foo().x`. The rvalue `foo()` would have extended
457    // lifetime.
458    //
459    // In some cases, multiple rules may apply (though not to the same
460    // rvalue). For example:
461    //
462    //     let ref x = [&a(), &b()];
463    //
464    // Here, the expression `[...]` has an extended lifetime due to rule
465    // A, but the inner rvalues `a()` and `b()` have an extended lifetime
466    // due to rule C.
467
468    let extend_initializer = match let_kind {
469        LetKind::Regular => true,
470        LetKind::Super
471            if let Some(scope) =
472                visitor.extended_super_lets.remove(&pat.unwrap().hir_id.local_id) =>
473        {
474            // This expression was lifetime-extended by a parent let binding. E.g.
475            //
476            //     let a = {
477            //         super let b = temp();
478            //         &b
479            //     };
480            //
481            // (Which needs to behave exactly as: let a = &temp();)
482            //
483            // Processing of `let a` will have already decided to extend the lifetime of this
484            // `super let` to its own var_scope. We use that scope.
485            visitor.cx.var_parent = scope;
486            // Extend temporaries to live in the same scope as the parent `let`'s bindings.
487            true
488        }
489        LetKind::Super => {
490            // This `super let` is not subject to lifetime extension from a parent let binding. E.g.
491            //
492            //     identity({ super let x = temp(); &x }).method();
493            //
494            // (Which needs to behave exactly as: identity(&temp()).method();)
495            //
496            // Iterate up to the enclosing destruction scope to find the same scope that will also
497            // be used for the result of the block itself.
498            if let Some(inner_scope) = visitor.cx.var_parent {
499                visitor.cx.var_parent =
500                    Some(visitor.scope_tree.default_temporary_scope(inner_scope).0)
501            }
502            // Don't lifetime-extend child `super let`s or block tail expressions' temporaries in
503            // the initializer when this `super let` is not itself extended by a parent `let`
504            // (#145784). Block tail expressions are temporary drop scopes in Editions 2024 and
505            // later, their temps shouldn't outlive the block in e.g. `f(pin!({ &temp() }))`.
506            false
507        }
508    };
509
510    if let Some(expr) = init
511        && extend_initializer
512    {
513        record_rvalue_scope_if_borrow_expr(visitor, expr, visitor.cx.var_parent);
514
515        if let Some(pat) = pat {
516            if is_binding_pat(pat) {
517                record_subexpr_extended_temp_scopes(
518                    &mut visitor.scope_tree,
519                    expr,
520                    visitor.cx.var_parent,
521                );
522            }
523        }
524    }
525
526    // Make sure we visit the initializer first.
527    // The correct order, as shared between drop_ranges and intravisitor,
528    // is to walk initializer, followed by pattern bindings, finally followed by the `else` block.
529    if let Some(expr) = init {
530        visitor.visit_expr(expr);
531    }
532
533    if let Some(pat) = pat {
534        visitor.visit_pat(pat);
535    }
536
537    /// Returns `true` if `pat` match the `P&` non-terminal.
538    ///
539    /// ```text
540    ///     P& = ref X
541    ///        | StructName { ..., P&, ... }
542    ///        | VariantName(..., P&, ...)
543    ///        | [ ..., P&, ... ]
544    ///        | ( ..., P&, ... )
545    ///        | ... "|" P& "|" ...
546    ///        | box P&
547    ///        | P& if ...
548    /// ```
549    fn is_binding_pat(pat: &hir::Pat<'_>) -> bool {
550        // Note that the code below looks for *explicit* refs only, that is, it won't
551        // know about *implicit* refs as introduced in #42640.
552        //
553        // This is not a problem. For example, consider
554        //
555        //      let (ref x, ref y) = (Foo { .. }, Bar { .. });
556        //
557        // Due to the explicit refs on the left hand side, the below code would signal
558        // that the temporary value on the right hand side should live until the end of
559        // the enclosing block (as opposed to being dropped after the let is complete).
560        //
561        // To create an implicit ref, however, you must have a borrowed value on the RHS
562        // already, as in this example (which won't compile before #42640):
563        //
564        //      let Foo { x, .. } = &Foo { x: ..., ... };
565        //
566        // in place of
567        //
568        //      let Foo { ref x, .. } = Foo { ... };
569        //
570        // In the former case (the implicit ref version), the temporary is created by the
571        // & expression, and its lifetime would be extended to the end of the block (due
572        // to a different rule, not the below code).
573        match pat.kind {
574            PatKind::Binding(hir::BindingMode(hir::ByRef::Yes(..), _), ..) => true,
575
576            PatKind::Struct(_, field_pats, _) => field_pats.iter().any(|fp| is_binding_pat(fp.pat)),
577
578            PatKind::Slice(pats1, pats2, pats3) => {
579                pats1.iter().any(|p| is_binding_pat(p))
580                    || pats2.iter().any(|p| is_binding_pat(p))
581                    || pats3.iter().any(|p| is_binding_pat(p))
582            }
583
584            PatKind::Or(subpats)
585            | PatKind::TupleStruct(_, subpats, _)
586            | PatKind::Tuple(subpats, _) => subpats.iter().any(|p| is_binding_pat(p)),
587
588            PatKind::Deref(subpat) | PatKind::Guard(subpat, _) => is_binding_pat(subpat),
589
590            PatKind::Ref(_, _, _)
591            | PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), ..)
592            | PatKind::Missing
593            | PatKind::Wild
594            | PatKind::Never
595            | PatKind::Expr(_)
596            | PatKind::Range(_, _, _)
597            | PatKind::Err(_) => false,
598        }
599    }
600
601    /// If `expr` matches the `E&` grammar, then records an extended temporary scope as appropriate:
602    ///
603    /// ```text
604    ///     E& = & ET
605    ///        | StructName { ..., f: E&, ... }
606    ///        | [ ..., E&, ... ]
607    ///        | ( ..., E&, ... )
608    ///        | {...; E&}
609    ///        | { super let ... = E&; ... }
610    ///        | if _ { ...; E& } else { ...; E& }
611    ///        | match _ { ..., _ => E&, ... }
612    ///        | box E&
613    ///        | E& as ...
614    ///        | ( E& )
615    /// ```
616    fn record_rvalue_scope_if_borrow_expr<'tcx>(
617        visitor: &mut ScopeResolutionVisitor<'tcx>,
618        expr: &hir::Expr<'_>,
619        blk_id: Option<Scope>,
620    ) {
621        match expr.kind {
622            hir::ExprKind::AddrOf(_, _, subexpr) => {
623                record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
624                record_subexpr_extended_temp_scopes(&mut visitor.scope_tree, subexpr, blk_id);
625            }
626            hir::ExprKind::Struct(_, fields, _) => {
627                for field in fields {
628                    record_rvalue_scope_if_borrow_expr(visitor, field.expr, blk_id);
629                }
630            }
631            hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => {
632                for subexpr in subexprs {
633                    record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
634                }
635            }
636            hir::ExprKind::Cast(subexpr, _) => {
637                record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id)
638            }
639            hir::ExprKind::Block(block, _) => {
640                if let Some(subexpr) = block.expr {
641                    record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
642                }
643                for stmt in block.stmts {
644                    if let hir::StmtKind::Let(local) = stmt.kind
645                        && let Some(_) = local.super_
646                    {
647                        visitor.extended_super_lets.insert(local.pat.hir_id.local_id, blk_id);
648                    }
649                }
650            }
651            hir::ExprKind::If(_, then_block, else_block) => {
652                record_rvalue_scope_if_borrow_expr(visitor, then_block, blk_id);
653                if let Some(else_block) = else_block {
654                    record_rvalue_scope_if_borrow_expr(visitor, else_block, blk_id);
655                }
656            }
657            hir::ExprKind::Match(_, arms, _) => {
658                for arm in arms {
659                    record_rvalue_scope_if_borrow_expr(visitor, arm.body, blk_id);
660                }
661            }
662            hir::ExprKind::Call(func, args) => {
663                // Recurse into tuple constructors, such as `Some(&temp())`.
664                //
665                // That way, there is no difference between `Some(..)` and `Some { 0: .. }`,
666                // even though the former is syntactically a function call.
667                if let hir::ExprKind::Path(path) = &func.kind
668                    && let hir::QPath::Resolved(None, path) = path
669                    && let Res::SelfCtor(_) | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) = path.res
670                {
671                    for arg in args {
672                        record_rvalue_scope_if_borrow_expr(visitor, arg, blk_id);
673                    }
674                }
675            }
676            _ => {}
677        }
678    }
679}
680
681/// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
682/// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
683/// case, the "temporary lifetime" of `expr` is extended to be the block enclosing the `let`
684/// statement.
685///
686/// More formally, if `expr` matches the grammar `ET`, record the temporary scope of the matching
687/// `<rvalue>` as `lifetime`:
688///
689/// ```text
690///     ET = *ET
691///        | ET[...]
692///        | ET.f
693///        | (ET)
694///        | <rvalue>
695/// ```
696///
697/// Note: ET is intended to match "rvalues or places based on rvalues".
698fn record_subexpr_extended_temp_scopes(
699    scope_tree: &mut ScopeTree,
700    expr: &hir::Expr<'_>,
701    lifetime: Option<Scope>,
702) {
703    // Note: give all the expressions matching `ET` with the
704    // extended temporary lifetime, not just the innermost rvalue,
705    // because in MIR building if we must compile e.g., `*rvalue()`
706    // into a temporary, we request the temporary scope of the
707    // outer expression.
708
709    scope_tree.record_extended_temp_scope(expr.hir_id.local_id, lifetime);
710
711    match expr.kind {
712        hir::ExprKind::AddrOf(_, _, subexpr)
713        | hir::ExprKind::Unary(hir::UnOp::Deref, subexpr)
714        | hir::ExprKind::Field(subexpr, _)
715        | hir::ExprKind::Index(subexpr, _, _) => {
716            record_subexpr_extended_temp_scopes(scope_tree, subexpr, lifetime);
717        }
718        _ => {}
719    }
720}
721
722impl<'tcx> ScopeResolutionVisitor<'tcx> {
723    /// Records the current parent (if any) as the parent of `child_scope`.
724    fn record_child_scope(&mut self, child_scope: Scope) {
725        let parent = self.cx.parent;
726        self.scope_tree.record_scope_parent(child_scope, parent);
727    }
728
729    /// Records the current parent (if any) as the parent of `child_scope`,
730    /// and sets `child_scope` as the new current parent.
731    fn enter_scope(&mut self, child_scope: Scope) {
732        self.record_child_scope(child_scope);
733        self.cx.parent = Some(child_scope);
734    }
735
736    fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId, terminating: bool) {
737        // If node was previously marked as a terminating scope during the
738        // recursive visit of its parent node in the HIR, then we need to
739        // account for the destruction scope representing the scope of
740        // the destructors that run immediately after it completes.
741        if terminating {
742            self.enter_scope(Scope { local_id: id, data: ScopeData::Destruction });
743        }
744        self.enter_scope(Scope { local_id: id, data: ScopeData::Node });
745    }
746
747    fn enter_body(&mut self, hir_id: hir::HirId, f: impl FnOnce(&mut Self)) {
748        let outer_cx = self.cx;
749
750        self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::CallSite });
751        self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::Arguments });
752
753        f(self);
754
755        // Restore context we had at the start.
756        self.cx = outer_cx;
757    }
758}
759
760impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
761    fn visit_block(&mut self, b: &'tcx Block<'tcx>) {
762        resolve_block(self, b, false);
763    }
764
765    fn visit_body(&mut self, body: &hir::Body<'tcx>) {
766        let body_id = body.id();
767        let owner_id = self.tcx.hir_body_owner_def_id(body_id);
768
769        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/region.rs:769",
                        "rustc_hir_analysis::check::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(769u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_body(id={0:?}, span={1:?}, body.id={2:?}, cx.parent={3:?})",
                                                    owner_id,
                                                    self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span),
                                                    body_id, self.cx.parent) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
770            "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
771            owner_id,
772            self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span),
773            body_id,
774            self.cx.parent
775        );
776
777        self.enter_body(body.value.hir_id, |this| {
778            if this.tcx.hir_body_owner_kind(owner_id).is_fn_or_closure() {
779                // The arguments and `self` are parented to the fn.
780                this.cx.var_parent = this.cx.parent;
781                for param in body.params {
782                    this.visit_pat(param.pat);
783                }
784
785                // The body of the every fn is a root scope.
786                resolve_expr(this, body.value, true);
787            } else {
788                // All bodies have an outer temporary drop scope, but temporaries
789                // and `super let` bindings in constant initializers may be extended
790                // to have 'static lifetimes, using the same syntactical rules used
791                // for `let` initializers.
792                //
793                // e.g., in `let x = &f();`, the temporary holding the result from
794                // the `f()` call lives for the entirety of the surrounding block.
795                //
796                // Similarly, `const X: ... = &f();` would have the result of `f()`
797                // live for `'static`, implying (if Drop restrictions on constants
798                // ever get lifted) that the value *could* have a destructor, but
799                // it'd get leaked instead of the destructor running during the
800                // evaluation of `X` (if at all allowed by CTFE).
801                //
802                // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
803                // would *not* let the `f()` temporary escape into an outer scope
804                // (i.e., `'static`), which means that after `g` returns, it drops,
805                // and all the associated destruction scope rules apply.
806                this.cx.var_parent = None;
807                this.enter_scope(Scope {
808                    local_id: body.value.hir_id.local_id,
809                    data: ScopeData::Destruction,
810                });
811                resolve_local(this, None, Some(body.value), LetKind::Regular);
812            }
813        })
814    }
815
816    fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) {
817        resolve_arm(self, a);
818    }
819    fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
820        resolve_pat(self, p);
821    }
822    fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) {
823        resolve_stmt(self, s);
824    }
825    fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
826        resolve_expr(self, ex, false);
827    }
828    fn visit_local(&mut self, l: &'tcx LetStmt<'tcx>) {
829        let let_kind = match l.super_ {
830            Some(_) => LetKind::Super,
831            None => LetKind::Regular,
832        };
833        resolve_local(self, Some(l.pat), l.init, let_kind);
834    }
835    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
836        let body = self.tcx.hir_body(c.body);
837        self.visit_body(body);
838    }
839}
840
841/// Per-body `region::ScopeTree`. The `DefId` should be the owner `DefId` for the body;
842/// in the case of closures, this will be redirected to the enclosing function.
843///
844/// Performance: This is a query rather than a simple function to enable
845/// re-use in incremental scenarios. We may sometimes need to rerun the
846/// type checker even when the HIR hasn't changed, and in those cases
847/// we can avoid reconstructing the region scope tree.
848pub(crate) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &ScopeTree {
849    let typeck_root_def_id = tcx.typeck_root_def_id_local(def_id);
850    if typeck_root_def_id != def_id {
851        return tcx.region_scope_tree(typeck_root_def_id);
852    }
853
854    let scope_tree = if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
855        let mut visitor = ScopeResolutionVisitor {
856            tcx,
857            scope_tree: ScopeTree::default(),
858            cx: Context { parent: None, var_parent: None },
859            extended_super_lets: Default::default(),
860        };
861
862        visitor.scope_tree.root_body = Some(body.value.hir_id);
863        visitor.visit_body(&body);
864        visitor.scope_tree
865    } else {
866        ScopeTree::default()
867    };
868
869    tcx.arena.alloc(scope_tree)
870}