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