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 // We introduce a new scope to contain bindings and temporaries from `if let` guards, to
203 // ensure they're dropped before the arm's pattern's bindings. This extends to the end of
204 // the arm body and is the scope of its locals as well.
205 visitor.enter_scope(Scope { local_id: arm.hir_id.local_id, data: ScopeData::MatchGuard });
206 visitor.cx.var_parent = visitor.cx.parent;
207 resolve_cond(visitor, guard);
208 }
209 resolve_expr(visitor, arm.body, false);
210
211 visitor.cx = prev_cx;
212}
213
214#[tracing::instrument(level = "debug", skip(visitor))]
215fn resolve_pat<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) {
216 // If this is a binding then record the lifetime of that binding.
217 if let PatKind::Binding(..) = pat.kind {
218 record_var_lifetime(visitor, pat.hir_id.local_id);
219 }
220
221 intravisit::walk_pat(visitor, pat);
222}
223
224fn resolve_stmt<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) {
225 let stmt_id = stmt.hir_id.local_id;
226 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
227
228 if let hir::StmtKind::Let(LetStmt { super_: Some(_), .. }) = stmt.kind {
229 // `super let` statement does not start a new scope, such that
230 //
231 // { super let x = identity(&temp()); &x }.method();
232 //
233 // behaves exactly as
234 //
235 // (&identity(&temp()).method();
236 intravisit::walk_stmt(visitor, stmt);
237 } else {
238 // Every statement will clean up the temporaries created during
239 // execution of that statement. Therefore each statement has an
240 // associated destruction scope that represents the scope of the
241 // statement plus its destructors, and thus the scope for which
242 // regions referenced by the destructors need to survive.
243
244 let prev_parent = visitor.cx.parent;
245 visitor.enter_node_scope_with_dtor(stmt_id, true);
246
247 intravisit::walk_stmt(visitor, stmt);
248
249 visitor.cx.parent = prev_parent;
250 }
251}
252
253#[tracing::instrument(level = "debug", skip(visitor))]
254fn resolve_expr<'tcx>(
255 visitor: &mut ScopeResolutionVisitor<'tcx>,
256 expr: &'tcx hir::Expr<'tcx>,
257 terminating: bool,
258) {
259 let prev_cx = visitor.cx;
260 visitor.enter_node_scope_with_dtor(expr.hir_id.local_id, terminating);
261
262 match expr.kind {
263 // Conditional or repeating scopes are always terminating
264 // scopes, meaning that temporaries cannot outlive them.
265 // This ensures fixed size stacks.
266 hir::ExprKind::Binary(
267 source_map::Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
268 left,
269 right,
270 ) => {
271 // expr is a short circuiting operator (|| or &&). As its
272 // functionality can't be overridden by traits, it always
273 // processes bool sub-expressions. bools are Copy and thus we
274 // can drop any temporaries in evaluation (read) order
275 // (with the exception of potentially failing let expressions).
276 // We achieve this by enclosing the operands in a terminating
277 // scope, both the LHS and the RHS.
278
279 // We optimize this a little in the presence of chains.
280 // Chains like a && b && c get lowered to AND(AND(a, b), c).
281 // In here, b and c are RHS, while a is the only LHS operand in
282 // that chain. This holds true for longer chains as well: the
283 // leading operand is always the only LHS operand that is not a
284 // binop itself. Putting a binop like AND(a, b) into a
285 // terminating scope is not useful, thus we only put the LHS
286 // into a terminating scope if it is not a binop.
287
288 let terminate_lhs = match left.kind {
289 // let expressions can create temporaries that live on
290 hir::ExprKind::Let(_) => false,
291 // binops already drop their temporaries, so there is no
292 // need to put them into a terminating scope.
293 // This is purely an optimization to reduce the number of
294 // terminating scopes.
295 hir::ExprKind::Binary(
296 source_map::Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
297 ..,
298 ) => false,
299 // otherwise: mark it as terminating
300 _ => true,
301 };
302
303 // `Let` expressions (in a let-chain) shouldn't be terminating, as their temporaries
304 // should live beyond the immediate expression
305 let terminate_rhs = !matches!(right.kind, hir::ExprKind::Let(_));
306
307 resolve_expr(visitor, left, terminate_lhs);
308 resolve_expr(visitor, right, terminate_rhs);
309 }
310 // Manually recurse over closures, because they are nested bodies
311 // that share the parent environment. We handle const blocks in
312 // `visit_inline_const`.
313 hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
314 let body = visitor.tcx.hir_body(body);
315 visitor.visit_body(body);
316 }
317 // Ordinarily, we can rely on the visit order of HIR intravisit
318 // to correspond to the actual execution order of statements.
319 // However, there's a weird corner case with compound assignment
320 // operators (e.g. `a += b`). The evaluation order depends on whether
321 // or not the operator is overloaded (e.g. whether or not a trait
322 // like AddAssign is implemented).
323 //
324 // For primitive types (which, despite having a trait impl, don't actually
325 // end up calling it), the evaluation order is right-to-left. For example,
326 // the following code snippet:
327 //
328 // let y = &mut 0;
329 // *{println!("LHS!"); y} += {println!("RHS!"); 1};
330 //
331 // will print:
332 //
333 // RHS!
334 // LHS!
335 //
336 // However, if the operator is used on a non-primitive type,
337 // the evaluation order will be left-to-right, since the operator
338 // actually get desugared to a method call. For example, this
339 // nearly identical code snippet:
340 //
341 // let y = &mut String::new();
342 // *{println!("LHS String"); y} += {println!("RHS String"); "hi"};
343 //
344 // will print:
345 // LHS String
346 // RHS String
347 //
348 // To determine the actual execution order, we need to perform
349 // trait resolution. Fortunately, we don't need to know the actual execution order.
350 hir::ExprKind::AssignOp(_, left_expr, right_expr) => {
351 visitor.visit_expr(right_expr);
352 visitor.visit_expr(left_expr);
353 }
354
355 hir::ExprKind::If(cond, then, Some(otherwise)) => {
356 let expr_cx = visitor.cx;
357 let data = if expr.span.at_least_rust_2024() {
358 ScopeData::IfThenRescope
359 } else {
360 ScopeData::IfThen
361 };
362 visitor.enter_scope(Scope { local_id: then.hir_id.local_id, data });
363 visitor.cx.var_parent = visitor.cx.parent;
364 resolve_cond(visitor, cond);
365 resolve_expr(visitor, then, true);
366 visitor.cx = expr_cx;
367 resolve_expr(visitor, otherwise, true);
368 }
369
370 hir::ExprKind::If(cond, then, None) => {
371 let expr_cx = visitor.cx;
372 let data = if expr.span.at_least_rust_2024() {
373 ScopeData::IfThenRescope
374 } else {
375 ScopeData::IfThen
376 };
377 visitor.enter_scope(Scope { local_id: then.hir_id.local_id, data });
378 visitor.cx.var_parent = visitor.cx.parent;
379 resolve_cond(visitor, cond);
380 resolve_expr(visitor, then, true);
381 visitor.cx = expr_cx;
382 }
383
384 hir::ExprKind::Loop(body, _, _, _) => {
385 resolve_block(visitor, body, true);
386 }
387
388 hir::ExprKind::DropTemps(expr) => {
389 // `DropTemps(expr)` does not denote a conditional scope.
390 // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`.
391 resolve_expr(visitor, expr, true);
392 }
393
394 _ => intravisit::walk_expr(visitor, expr),
395 }
396
397 visitor.cx = prev_cx;
398}
399
400#[derive(Copy, Clone, PartialEq, Eq, Debug)]
401enum LetKind {
402 Regular,
403 Super,
404}
405
406fn resolve_local<'tcx>(
407 visitor: &mut ScopeResolutionVisitor<'tcx>,
408 pat: Option<&'tcx hir::Pat<'tcx>>,
409 init: Option<&'tcx hir::Expr<'tcx>>,
410 let_kind: LetKind,
411) {
412 debug!("resolve_local(pat={:?}, init={:?}, let_kind={:?})", pat, init, let_kind);
413
414 // As an exception to the normal rules governing temporary
415 // lifetimes, initializers in a let have a temporary lifetime
416 // of the enclosing block. This means that e.g., a program
417 // like the following is legal:
418 //
419 // let ref x = HashMap::new();
420 //
421 // Because the hash map will be freed in the enclosing block.
422 //
423 // We express the rules more formally based on 3 grammars (defined
424 // fully in the helpers below that implement them):
425 //
426 // 1. `E&`, which matches expressions like `&<rvalue>` that
427 // own a pointer into the stack.
428 //
429 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
430 // y)` that produce ref bindings into the value they are
431 // matched against or something (at least partially) owned by
432 // the value they are matched against. (By partially owned,
433 // I mean that creating a binding into a ref-counted or managed value
434 // would still count.)
435 //
436 // 3. `ET`, which matches both rvalues like `foo()` as well as places
437 // based on rvalues like `foo().x[2].y`.
438 //
439 // A subexpression `<rvalue>` that appears in a let initializer
440 // `let pat [: ty] = expr` has an extended temporary lifetime if
441 // any of the following conditions are met:
442 //
443 // A. `pat` matches `P&` and `expr` matches `ET`
444 // (covers cases where `pat` creates ref bindings into an rvalue
445 // produced by `expr`)
446 // B. `ty` is a borrowed pointer and `expr` matches `ET`
447 // (covers cases where coercion creates a borrow)
448 // C. `expr` matches `E&`
449 // (covers cases `expr` borrows an rvalue that is then assigned
450 // to memory (at least partially) owned by the binding)
451 //
452 // Here are some examples hopefully giving an intuition where each
453 // rule comes into play and why:
454 //
455 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
456 // would have an extended lifetime, but not `foo()`.
457 //
458 // Rule B. `let x = &foo().x`. The rvalue `foo()` would have extended
459 // lifetime.
460 //
461 // In some cases, multiple rules may apply (though not to the same
462 // rvalue). For example:
463 //
464 // let ref x = [&a(), &b()];
465 //
466 // Here, the expression `[...]` has an extended lifetime due to rule
467 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
468 // due to rule C.
469
470 let extend_initializer = match let_kind {
471 LetKind::Regular => true,
472 LetKind::Super
473 if let Some(scope) =
474 visitor.extended_super_lets.remove(&pat.unwrap().hir_id.local_id) =>
475 {
476 // This expression was lifetime-extended by a parent let binding. E.g.
477 //
478 // let a = {
479 // super let b = temp();
480 // &b
481 // };
482 //
483 // (Which needs to behave exactly as: let a = &temp();)
484 //
485 // Processing of `let a` will have already decided to extend the lifetime of this
486 // `super let` to its own var_scope. We use that scope.
487 visitor.cx.var_parent = scope;
488 // Extend temporaries to live in the same scope as the parent `let`'s bindings.
489 true
490 }
491 LetKind::Super => {
492 // This `super let` is not subject to lifetime extension from a parent let binding. E.g.
493 //
494 // identity({ super let x = temp(); &x }).method();
495 //
496 // (Which needs to behave exactly as: identity(&temp()).method();)
497 //
498 // Iterate up to the enclosing destruction scope to find the same scope that will also
499 // be used for the result of the block itself.
500 if let Some(inner_scope) = visitor.cx.var_parent {
501 visitor.cx.var_parent =
502 Some(visitor.scope_tree.default_temporary_scope(inner_scope).0)
503 }
504 // Don't lifetime-extend child `super let`s or block tail expressions' temporaries in
505 // the initializer when this `super let` is not itself extended by a parent `let`
506 // (#145784). Block tail expressions are temporary drop scopes in Editions 2024 and
507 // later, their temps shouldn't outlive the block in e.g. `f(pin!({ &temp() }))`.
508 false
509 }
510 };
511
512 if let Some(expr) = init
513 && extend_initializer
514 {
515 record_rvalue_scope_if_borrow_expr(visitor, expr, visitor.cx.var_parent);
516
517 if let Some(pat) = pat {
518 if is_binding_pat(pat) {
519 record_subexpr_extended_temp_scopes(
520 &mut visitor.scope_tree,
521 expr,
522 visitor.cx.var_parent,
523 );
524 }
525 }
526 }
527
528 // Make sure we visit the initializer first.
529 // The correct order, as shared between drop_ranges and intravisitor,
530 // is to walk initializer, followed by pattern bindings, finally followed by the `else` block.
531 if let Some(expr) = init {
532 visitor.visit_expr(expr);
533 }
534
535 if let Some(pat) = pat {
536 visitor.visit_pat(pat);
537 }
538
539 /// Returns `true` if `pat` match the `P&` non-terminal.
540 ///
541 /// ```text
542 /// P& = ref X
543 /// | StructName { ..., P&, ... }
544 /// | VariantName(..., P&, ...)
545 /// | [ ..., P&, ... ]
546 /// | ( ..., P&, ... )
547 /// | ... "|" P& "|" ...
548 /// | box P&
549 /// | P& if ...
550 /// ```
551 fn is_binding_pat(pat: &hir::Pat<'_>) -> bool {
552 // Note that the code below looks for *explicit* refs only, that is, it won't
553 // know about *implicit* refs as introduced in #42640.
554 //
555 // This is not a problem. For example, consider
556 //
557 // let (ref x, ref y) = (Foo { .. }, Bar { .. });
558 //
559 // Due to the explicit refs on the left hand side, the below code would signal
560 // that the temporary value on the right hand side should live until the end of
561 // the enclosing block (as opposed to being dropped after the let is complete).
562 //
563 // To create an implicit ref, however, you must have a borrowed value on the RHS
564 // already, as in this example (which won't compile before #42640):
565 //
566 // let Foo { x, .. } = &Foo { x: ..., ... };
567 //
568 // in place of
569 //
570 // let Foo { ref x, .. } = Foo { ... };
571 //
572 // In the former case (the implicit ref version), the temporary is created by the
573 // & expression, and its lifetime would be extended to the end of the block (due
574 // to a different rule, not the below code).
575 match pat.kind {
576 PatKind::Binding(hir::BindingMode(hir::ByRef::Yes(..), _), ..) => true,
577
578 PatKind::Struct(_, field_pats, _) => field_pats.iter().any(|fp| is_binding_pat(fp.pat)),
579
580 PatKind::Slice(pats1, pats2, pats3) => {
581 pats1.iter().any(|p| is_binding_pat(p))
582 || pats2.iter().any(|p| is_binding_pat(p))
583 || pats3.iter().any(|p| is_binding_pat(p))
584 }
585
586 PatKind::Or(subpats)
587 | PatKind::TupleStruct(_, subpats, _)
588 | PatKind::Tuple(subpats, _) => subpats.iter().any(|p| is_binding_pat(p)),
589
590 PatKind::Box(subpat) | PatKind::Deref(subpat) | PatKind::Guard(subpat, _) => {
591 is_binding_pat(subpat)
592 }
593
594 PatKind::Ref(_, _, _)
595 | PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), ..)
596 | PatKind::Missing
597 | PatKind::Wild
598 | PatKind::Never
599 | PatKind::Expr(_)
600 | PatKind::Range(_, _, _)
601 | PatKind::Err(_) => false,
602 }
603 }
604
605 /// If `expr` matches the `E&` grammar, then records an extended temporary scope as appropriate:
606 ///
607 /// ```text
608 /// E& = & ET
609 /// | StructName { ..., f: E&, ... }
610 /// | [ ..., E&, ... ]
611 /// | ( ..., E&, ... )
612 /// | {...; E&}
613 /// | { super let ... = E&; ... }
614 /// | if _ { ...; E& } else { ...; E& }
615 /// | match _ { ..., _ => E&, ... }
616 /// | box E&
617 /// | E& as ...
618 /// | ( E& )
619 /// ```
620 fn record_rvalue_scope_if_borrow_expr<'tcx>(
621 visitor: &mut ScopeResolutionVisitor<'tcx>,
622 expr: &hir::Expr<'_>,
623 blk_id: Option<Scope>,
624 ) {
625 match expr.kind {
626 hir::ExprKind::AddrOf(_, _, subexpr) => {
627 record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
628 record_subexpr_extended_temp_scopes(&mut visitor.scope_tree, subexpr, blk_id);
629 }
630 hir::ExprKind::Struct(_, fields, _) => {
631 for field in fields {
632 record_rvalue_scope_if_borrow_expr(visitor, field.expr, blk_id);
633 }
634 }
635 hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => {
636 for subexpr in subexprs {
637 record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
638 }
639 }
640 hir::ExprKind::Cast(subexpr, _) => {
641 record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id)
642 }
643 hir::ExprKind::Block(block, _) => {
644 if let Some(subexpr) = block.expr {
645 record_rvalue_scope_if_borrow_expr(visitor, subexpr, blk_id);
646 }
647 for stmt in block.stmts {
648 if let hir::StmtKind::Let(local) = stmt.kind
649 && let Some(_) = local.super_
650 {
651 visitor.extended_super_lets.insert(local.pat.hir_id.local_id, blk_id);
652 }
653 }
654 }
655 hir::ExprKind::If(_, then_block, else_block) => {
656 record_rvalue_scope_if_borrow_expr(visitor, then_block, blk_id);
657 if let Some(else_block) = else_block {
658 record_rvalue_scope_if_borrow_expr(visitor, else_block, blk_id);
659 }
660 }
661 hir::ExprKind::Match(_, arms, _) => {
662 for arm in arms {
663 record_rvalue_scope_if_borrow_expr(visitor, arm.body, blk_id);
664 }
665 }
666 hir::ExprKind::Call(func, args) => {
667 // Recurse into tuple constructors, such as `Some(&temp())`.
668 //
669 // That way, there is no difference between `Some(..)` and `Some { 0: .. }`,
670 // even though the former is syntactically a function call.
671 if let hir::ExprKind::Path(path) = &func.kind
672 && let hir::QPath::Resolved(None, path) = path
673 && let Res::SelfCtor(_) | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) = path.res
674 {
675 for arg in args {
676 record_rvalue_scope_if_borrow_expr(visitor, arg, blk_id);
677 }
678 }
679 }
680 _ => {}
681 }
682 }
683}
684
685/// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
686/// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
687/// case, the "temporary lifetime" of `expr` is extended to be the block enclosing the `let`
688/// statement.
689///
690/// More formally, if `expr` matches the grammar `ET`, record the temporary scope of the matching
691/// `<rvalue>` as `lifetime`:
692///
693/// ```text
694/// ET = *ET
695/// | ET[...]
696/// | ET.f
697/// | (ET)
698/// | <rvalue>
699/// ```
700///
701/// Note: ET is intended to match "rvalues or places based on rvalues".
702fn record_subexpr_extended_temp_scopes(
703 scope_tree: &mut ScopeTree,
704 mut expr: &hir::Expr<'_>,
705 lifetime: Option<Scope>,
706) {
707 debug!(?expr, ?lifetime);
708
709 loop {
710 // Note: give all the expressions matching `ET` with the
711 // extended temporary lifetime, not just the innermost rvalue,
712 // because in MIR building if we must compile e.g., `*rvalue()`
713 // into a temporary, we request the temporary scope of the
714 // outer expression.
715
716 scope_tree.record_extended_temp_scope(expr.hir_id.local_id, lifetime);
717
718 match expr.kind {
719 hir::ExprKind::AddrOf(_, _, subexpr)
720 | hir::ExprKind::Unary(hir::UnOp::Deref, subexpr)
721 | hir::ExprKind::Field(subexpr, _)
722 | hir::ExprKind::Index(subexpr, _, _) => {
723 expr = subexpr;
724 }
725 _ => {
726 return;
727 }
728 }
729 }
730}
731
732impl<'tcx> ScopeResolutionVisitor<'tcx> {
733 /// Records the current parent (if any) as the parent of `child_scope`.
734 fn record_child_scope(&mut self, child_scope: Scope) {
735 let parent = self.cx.parent;
736 self.scope_tree.record_scope_parent(child_scope, parent);
737 }
738
739 /// Records the current parent (if any) as the parent of `child_scope`,
740 /// and sets `child_scope` as the new current parent.
741 fn enter_scope(&mut self, child_scope: Scope) {
742 self.record_child_scope(child_scope);
743 self.cx.parent = Some(child_scope);
744 }
745
746 fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId, terminating: bool) {
747 // If node was previously marked as a terminating scope during the
748 // recursive visit of its parent node in the HIR, then we need to
749 // account for the destruction scope representing the scope of
750 // the destructors that run immediately after it completes.
751 if terminating {
752 self.enter_scope(Scope { local_id: id, data: ScopeData::Destruction });
753 }
754 self.enter_scope(Scope { local_id: id, data: ScopeData::Node });
755 }
756
757 fn enter_body(&mut self, hir_id: hir::HirId, f: impl FnOnce(&mut Self)) {
758 let outer_cx = self.cx;
759
760 self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::CallSite });
761 self.enter_scope(Scope { local_id: hir_id.local_id, data: ScopeData::Arguments });
762
763 f(self);
764
765 // Restore context we had at the start.
766 self.cx = outer_cx;
767 }
768}
769
770impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
771 fn visit_block(&mut self, b: &'tcx Block<'tcx>) {
772 resolve_block(self, b, false);
773 }
774
775 fn visit_body(&mut self, body: &hir::Body<'tcx>) {
776 let body_id = body.id();
777 let owner_id = self.tcx.hir_body_owner_def_id(body_id);
778
779 debug!(
780 "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
781 owner_id,
782 self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span),
783 body_id,
784 self.cx.parent
785 );
786
787 self.enter_body(body.value.hir_id, |this| {
788 if this.tcx.hir_body_owner_kind(owner_id).is_fn_or_closure() {
789 // The arguments and `self` are parented to the fn.
790 this.cx.var_parent = this.cx.parent;
791 for param in body.params {
792 this.visit_pat(param.pat);
793 }
794
795 // The body of the every fn is a root scope.
796 resolve_expr(this, body.value, true);
797 } else {
798 // All bodies have an outer temporary drop scope, but temporaries
799 // and `super let` bindings in constant initializers may be extended
800 // to have 'static lifetimes, using the same syntactical rules used
801 // for `let` initializers.
802 //
803 // e.g., in `let x = &f();`, the temporary holding the result from
804 // the `f()` call lives for the entirety of the surrounding block.
805 //
806 // Similarly, `const X: ... = &f();` would have the result of `f()`
807 // live for `'static`, implying (if Drop restrictions on constants
808 // ever get lifted) that the value *could* have a destructor, but
809 // it'd get leaked instead of the destructor running during the
810 // evaluation of `X` (if at all allowed by CTFE).
811 //
812 // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
813 // would *not* let the `f()` temporary escape into an outer scope
814 // (i.e., `'static`), which means that after `g` returns, it drops,
815 // and all the associated destruction scope rules apply.
816 this.cx.var_parent = None;
817 this.enter_scope(Scope {
818 local_id: body.value.hir_id.local_id,
819 data: ScopeData::Destruction,
820 });
821 resolve_local(this, None, Some(body.value), LetKind::Regular);
822 }
823 })
824 }
825
826 fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) {
827 resolve_arm(self, a);
828 }
829 fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) {
830 resolve_pat(self, p);
831 }
832 fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) {
833 resolve_stmt(self, s);
834 }
835 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
836 resolve_expr(self, ex, false);
837 }
838 fn visit_local(&mut self, l: &'tcx LetStmt<'tcx>) {
839 let let_kind = match l.super_ {
840 Some(_) => LetKind::Super,
841 None => LetKind::Regular,
842 };
843 resolve_local(self, Some(l.pat), l.init, let_kind);
844 }
845 fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
846 let body = self.tcx.hir_body(c.body);
847 self.visit_body(body);
848 }
849}
850
851/// Per-body `region::ScopeTree`. The `DefId` should be the owner `DefId` for the body;
852/// in the case of closures, this will be redirected to the enclosing function.
853///
854/// Performance: This is a query rather than a simple function to enable
855/// re-use in incremental scenarios. We may sometimes need to rerun the
856/// type checker even when the HIR hasn't changed, and in those cases
857/// we can avoid reconstructing the region scope tree.
858pub(crate) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree {
859 let typeck_root_def_id = tcx.typeck_root_def_id(def_id);
860 if typeck_root_def_id != def_id {
861 return tcx.region_scope_tree(typeck_root_def_id);
862 }
863
864 let scope_tree = if let Some(body) = tcx.hir_maybe_body_owned_by(def_id.expect_local()) {
865 let mut visitor = ScopeResolutionVisitor {
866 tcx,
867 scope_tree: ScopeTree::default(),
868 cx: Context { parent: None, var_parent: None },
869 extended_super_lets: Default::default(),
870 };
871
872 visitor.scope_tree.root_body = Some(body.value.hir_id);
873 visitor.visit_body(&body);
874 visitor.scope_tree
875 } else {
876 ScopeTree::default()
877 };
878
879 tcx.arena.alloc(scope_tree)
880}