rustc_hir_analysis/check/
region.rs

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