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