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