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