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