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