rustc_hir_analysis/check/
region.rs

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