]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/expr_use_visitor.rs
Rollup merge of #83374 - reyk:fix/bsd-ancillary, r=joshtriplett
[rust.git] / compiler / rustc_typeck / src / expr_use_visitor.rs
1 //! A different sort of visitor for walking fn bodies. Unlike the
2 //! normal visitor, which just walks the entire body in one shot, the
3 //! `ExprUseVisitor` determines how expressions are being used.
4
5 pub use self::ConsumeMode::*;
6
7 // Export these here so that Clippy can use them.
8 pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
9
10 use rustc_data_structures::fx::FxIndexMap;
11 use rustc_hir as hir;
12 use rustc_hir::def::Res;
13 use rustc_hir::def_id::LocalDefId;
14 use rustc_hir::PatKind;
15 use rustc_index::vec::Idx;
16 use rustc_infer::infer::InferCtxt;
17 use rustc_middle::hir::place::ProjectionKind;
18 use rustc_middle::mir::FakeReadCause;
19 use rustc_middle::ty::{self, adjustment, TyCtxt};
20 use rustc_target::abi::VariantIdx;
21 use std::iter;
22
23 use crate::mem_categorization as mc;
24
25 ///////////////////////////////////////////////////////////////////////////
26 // The Delegate trait
27
28 /// This trait defines the callbacks you can expect to receive when
29 /// employing the ExprUseVisitor.
30 pub trait Delegate<'tcx> {
31     // The value found at `place` is either copied or moved, depending
32     // on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
33     //
34     // The parameter `diag_expr_id` indicates the HIR id that ought to be used for
35     // diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
36     // id will be the id of the expression `expr` but the place itself will have
37     // the id of the binding in the pattern `pat`.
38     fn consume(
39         &mut self,
40         place_with_id: &PlaceWithHirId<'tcx>,
41         diag_expr_id: hir::HirId,
42         mode: ConsumeMode,
43     );
44
45     // The value found at `place` is being borrowed with kind `bk`.
46     // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
47     fn borrow(
48         &mut self,
49         place_with_id: &PlaceWithHirId<'tcx>,
50         diag_expr_id: hir::HirId,
51         bk: ty::BorrowKind,
52     );
53
54     // The path at `assignee_place` is being assigned to.
55     // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
56     fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
57
58     // The `place` should be a fake read because of specified `cause`.
59     fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId);
60 }
61
62 #[derive(Copy, Clone, PartialEq, Debug)]
63 pub enum ConsumeMode {
64     Copy, // reference to x where x has a type that copies
65     Move, // reference to x where x has a type that moves
66 }
67
68 #[derive(Copy, Clone, PartialEq, Debug)]
69 pub enum MutateMode {
70     Init,
71     JustWrite,    // x = y
72     WriteAndRead, // x += y
73 }
74
75 ///////////////////////////////////////////////////////////////////////////
76 // The ExprUseVisitor type
77 //
78 // This is the code that actually walks the tree.
79 pub struct ExprUseVisitor<'a, 'tcx> {
80     mc: mc::MemCategorizationContext<'a, 'tcx>,
81     body_owner: LocalDefId,
82     delegate: &'a mut dyn Delegate<'tcx>,
83 }
84
85 // If the MC results in an error, it's because the type check
86 // failed (or will fail, when the error is uncovered and reported
87 // during writeback). In this case, we just ignore this part of the
88 // code.
89 //
90 // Note that this macro appears similar to try!(), but, unlike try!(),
91 // it does not propagate the error.
92 macro_rules! return_if_err {
93     ($inp: expr) => {
94         match $inp {
95             Ok(v) => v,
96             Err(()) => {
97                 debug!("mc reported err");
98                 return;
99             }
100         }
101     };
102 }
103
104 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
105     /// Creates the ExprUseVisitor, configuring it with the various options provided:
106     ///
107     /// - `delegate` -- who receives the callbacks
108     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
109     /// - `typeck_results` --- typeck results for the code being analyzed
110     pub fn new(
111         delegate: &'a mut (dyn Delegate<'tcx> + 'a),
112         infcx: &'a InferCtxt<'a, 'tcx>,
113         body_owner: LocalDefId,
114         param_env: ty::ParamEnv<'tcx>,
115         typeck_results: &'a ty::TypeckResults<'tcx>,
116     ) -> Self {
117         ExprUseVisitor {
118             mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
119             body_owner,
120             delegate,
121         }
122     }
123
124     pub fn consume_body(&mut self, body: &hir::Body<'_>) {
125         debug!("consume_body(body={:?})", body);
126
127         for param in body.params {
128             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(&param.pat));
129             debug!("consume_body: param_ty = {:?}", param_ty);
130
131             let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
132
133             self.walk_irrefutable_pat(&param_place, &param.pat);
134         }
135
136         self.consume_expr(&body.value);
137     }
138
139     fn tcx(&self) -> TyCtxt<'tcx> {
140         self.mc.tcx()
141     }
142
143     fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
144         debug!("delegate_consume(place_with_id={:?})", place_with_id);
145
146         let mode = copy_or_move(&self.mc, place_with_id);
147         self.delegate.consume(place_with_id, diag_expr_id, mode);
148     }
149
150     fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
151         for expr in exprs {
152             self.consume_expr(&expr);
153         }
154     }
155
156     pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
157         debug!("consume_expr(expr={:?})", expr);
158
159         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
160         self.delegate_consume(&place_with_id, place_with_id.hir_id);
161         self.walk_expr(expr);
162     }
163
164     fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
165         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
166         self.delegate.mutate(&place_with_id, place_with_id.hir_id);
167         self.walk_expr(expr);
168     }
169
170     fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
171         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
172
173         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
174         self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
175
176         self.walk_expr(expr)
177     }
178
179     fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
180         self.walk_expr(expr)
181     }
182
183     pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
184         debug!("walk_expr(expr={:?})", expr);
185
186         self.walk_adjustment(expr);
187
188         match expr.kind {
189             hir::ExprKind::Path(_) => {}
190
191             hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
192
193             hir::ExprKind::Unary(hir::UnOp::Deref, ref base) => {
194                 // *base
195                 self.select_from_expr(base);
196             }
197
198             hir::ExprKind::Field(ref base, _) => {
199                 // base.f
200                 self.select_from_expr(base);
201             }
202
203             hir::ExprKind::Index(ref lhs, ref rhs) => {
204                 // lhs[rhs]
205                 self.select_from_expr(lhs);
206                 self.consume_expr(rhs);
207             }
208
209             hir::ExprKind::Call(ref callee, ref args) => {
210                 // callee(args)
211                 self.consume_expr(callee);
212                 self.consume_exprs(args);
213             }
214
215             hir::ExprKind::MethodCall(.., ref args, _) => {
216                 // callee.m(args)
217                 self.consume_exprs(args);
218             }
219
220             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
221                 self.walk_struct_expr(fields, opt_with);
222             }
223
224             hir::ExprKind::Tup(ref exprs) => {
225                 self.consume_exprs(exprs);
226             }
227
228             hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
229                 self.consume_expr(&cond_expr);
230                 self.consume_expr(&then_expr);
231                 if let Some(ref else_expr) = *opt_else_expr {
232                     self.consume_expr(&else_expr);
233                 }
234             }
235
236             hir::ExprKind::Match(ref discr, arms, _) => {
237                 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
238
239                 // Matching should not always be considered a use of the place, hence
240                 // discr does not necessarily need to be borrowed.
241                 // We only want to borrow discr if the pattern contain something other
242                 // than wildcards.
243                 let ExprUseVisitor { ref mc, body_owner: _, delegate: _ } = *self;
244                 let mut needs_to_be_read = false;
245                 for arm in arms.iter() {
246                     return_if_err!(mc.cat_pattern(discr_place.clone(), &arm.pat, |place, pat| {
247                         match &pat.kind {
248                             PatKind::Binding(.., opt_sub_pat) => {
249                                 // If the opt_sub_pat is None, than the binding does not count as
250                                 // a wildcard for the purpose of borrowing discr.
251                                 if opt_sub_pat.is_none() {
252                                     needs_to_be_read = true;
253                                 }
254                             }
255                             PatKind::TupleStruct(..)
256                             | PatKind::Path(..)
257                             | PatKind::Struct(..)
258                             | PatKind::Tuple(..) => {
259                                 // If the PatKind is a TupleStruct, Struct or Tuple then we want to check
260                                 // whether the Variant is a MultiVariant or a SingleVariant. We only want
261                                 // to borrow discr if it is a MultiVariant.
262                                 // If it is a SingleVariant and creates a binding we will handle that when
263                                 // this callback gets called again.
264                                 if let ty::Adt(def, _) = place.place.base_ty.kind() {
265                                     if def.variants.len() > 1 {
266                                         needs_to_be_read = true;
267                                     }
268                                 }
269                             }
270                             PatKind::Lit(_) => {
271                                 // If the PatKind is a Lit then we want
272                                 // to borrow discr.
273                                 needs_to_be_read = true;
274                             }
275                             _ => {}
276                         }
277                     }));
278                 }
279
280                 if needs_to_be_read {
281                     self.borrow_expr(&discr, ty::ImmBorrow);
282                 } else {
283                     self.delegate.fake_read(
284                         discr_place.place.clone(),
285                         FakeReadCause::ForMatchedPlace,
286                         discr_place.hir_id,
287                     );
288
289                     // We always want to walk the discriminant. We want to make sure, for instance,
290                     // that the discriminant has been initialized.
291                     self.walk_expr(&discr);
292                 }
293
294                 // treatment of the discriminant is handled while walking the arms.
295                 for arm in arms {
296                     self.walk_arm(&discr_place, arm);
297                 }
298             }
299
300             hir::ExprKind::Array(ref exprs) => {
301                 self.consume_exprs(exprs);
302             }
303
304             hir::ExprKind::AddrOf(_, m, ref base) => {
305                 // &base
306                 // make sure that the thing we are pointing out stays valid
307                 // for the lifetime `scope_r` of the resulting ptr:
308                 let bk = ty::BorrowKind::from_mutbl(m);
309                 self.borrow_expr(&base, bk);
310             }
311
312             hir::ExprKind::InlineAsm(ref asm) => {
313                 for (op, _op_sp) in asm.operands {
314                     match op {
315                         hir::InlineAsmOperand::In { expr, .. }
316                         | hir::InlineAsmOperand::Const { expr, .. }
317                         | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
318                         hir::InlineAsmOperand::Out { expr, .. } => {
319                             if let Some(expr) = expr {
320                                 self.mutate_expr(expr);
321                             }
322                         }
323                         hir::InlineAsmOperand::InOut { expr, .. } => {
324                             self.mutate_expr(expr);
325                         }
326                         hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
327                             self.consume_expr(in_expr);
328                             if let Some(out_expr) = out_expr {
329                                 self.mutate_expr(out_expr);
330                             }
331                         }
332                     }
333                 }
334             }
335
336             hir::ExprKind::LlvmInlineAsm(ref ia) => {
337                 for (o, output) in iter::zip(&ia.inner.outputs, ia.outputs_exprs) {
338                     if o.is_indirect {
339                         self.consume_expr(output);
340                     } else {
341                         self.mutate_expr(output);
342                     }
343                 }
344                 self.consume_exprs(&ia.inputs_exprs);
345             }
346
347             hir::ExprKind::Continue(..)
348             | hir::ExprKind::Lit(..)
349             | hir::ExprKind::ConstBlock(..)
350             | hir::ExprKind::Err => {}
351
352             hir::ExprKind::Loop(ref blk, ..) => {
353                 self.walk_block(blk);
354             }
355
356             hir::ExprKind::Unary(_, ref lhs) => {
357                 self.consume_expr(lhs);
358             }
359
360             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
361                 self.consume_expr(lhs);
362                 self.consume_expr(rhs);
363             }
364
365             hir::ExprKind::Block(ref blk, _) => {
366                 self.walk_block(blk);
367             }
368
369             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
370                 if let Some(ref expr) = *opt_expr {
371                     self.consume_expr(expr);
372                 }
373             }
374
375             hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
376                 self.mutate_expr(lhs);
377                 self.consume_expr(rhs);
378             }
379
380             hir::ExprKind::Cast(ref base, _) => {
381                 self.consume_expr(base);
382             }
383
384             hir::ExprKind::DropTemps(ref expr) => {
385                 self.consume_expr(expr);
386             }
387
388             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
389                 if self.mc.typeck_results.is_method_call(expr) {
390                     self.consume_expr(lhs);
391                 } else {
392                     self.mutate_expr(lhs);
393                 }
394                 self.consume_expr(rhs);
395             }
396
397             hir::ExprKind::Repeat(ref base, _) => {
398                 self.consume_expr(base);
399             }
400
401             hir::ExprKind::Closure(..) => {
402                 self.walk_captures(expr);
403             }
404
405             hir::ExprKind::Box(ref base) => {
406                 self.consume_expr(base);
407             }
408
409             hir::ExprKind::Yield(ref value, _) => {
410                 self.consume_expr(value);
411             }
412         }
413     }
414
415     fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
416         match stmt.kind {
417             hir::StmtKind::Local(ref local) => {
418                 self.walk_local(&local);
419             }
420
421             hir::StmtKind::Item(_) => {
422                 // We don't visit nested items in this visitor,
423                 // only the fn body we were given.
424             }
425
426             hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
427                 self.consume_expr(&expr);
428             }
429         }
430     }
431
432     fn walk_local(&mut self, local: &hir::Local<'_>) {
433         if let Some(ref expr) = local.init {
434             // Variable declarations with
435             // initializers are considered
436             // "assigns", which is handled by
437             // `walk_pat`:
438             self.walk_expr(&expr);
439             let init_place = return_if_err!(self.mc.cat_expr(&expr));
440             self.walk_irrefutable_pat(&init_place, &local.pat);
441         }
442     }
443
444     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
445     /// depending on its type.
446     fn walk_block(&mut self, blk: &hir::Block<'_>) {
447         debug!("walk_block(blk.hir_id={})", blk.hir_id);
448
449         for stmt in blk.stmts {
450             self.walk_stmt(stmt);
451         }
452
453         if let Some(ref tail_expr) = blk.expr {
454             self.consume_expr(&tail_expr);
455         }
456     }
457
458     fn walk_struct_expr(
459         &mut self,
460         fields: &[hir::ExprField<'_>],
461         opt_with: &Option<&'hir hir::Expr<'_>>,
462     ) {
463         // Consume the expressions supplying values for each field.
464         for field in fields {
465             self.consume_expr(&field.expr);
466         }
467
468         let with_expr = match *opt_with {
469             Some(ref w) => &**w,
470             None => {
471                 return;
472             }
473         };
474
475         let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
476
477         // Select just those fields of the `with`
478         // expression that will actually be used
479         match with_place.place.ty().kind() {
480             ty::Adt(adt, substs) if adt.is_struct() => {
481                 // Consume those fields of the with expression that are needed.
482                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
483                     let is_mentioned = fields.iter().any(|f| {
484                         self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
485                     });
486                     if !is_mentioned {
487                         let field_place = self.mc.cat_projection(
488                             &*with_expr,
489                             with_place.clone(),
490                             with_field.ty(self.tcx(), substs),
491                             ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
492                         );
493                         self.delegate_consume(&field_place, field_place.hir_id);
494                     }
495                 }
496             }
497             _ => {
498                 // the base expression should always evaluate to a
499                 // struct; however, when EUV is run during typeck, it
500                 // may not. This will generate an error earlier in typeck,
501                 // so we can just ignore it.
502                 if !self.tcx().sess.has_errors() {
503                     span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
504                 }
505             }
506         }
507
508         // walk the with expression so that complex expressions
509         // are properly handled.
510         self.walk_expr(with_expr);
511     }
512
513     // Invoke the appropriate delegate calls for anything that gets
514     // consumed or borrowed as part of the automatic adjustment
515     // process.
516     fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
517         let adjustments = self.mc.typeck_results.expr_adjustments(expr);
518         let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
519         for adjustment in adjustments {
520             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
521             match adjustment.kind {
522                 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
523                     // Creating a closure/fn-pointer or unsizing consumes
524                     // the input and stores it into the resulting rvalue.
525                     self.delegate_consume(&place_with_id, place_with_id.hir_id);
526                 }
527
528                 adjustment::Adjust::Deref(None) => {}
529
530                 // Autoderefs for overloaded Deref calls in fact reference
531                 // their receiver. That is, if we have `(*x)` where `x`
532                 // is of type `Rc<T>`, then this in fact is equivalent to
533                 // `x.deref()`. Since `deref()` is declared with `&self`,
534                 // this is an autoref of `x`.
535                 adjustment::Adjust::Deref(Some(ref deref)) => {
536                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
537                     self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
538                 }
539
540                 adjustment::Adjust::Borrow(ref autoref) => {
541                     self.walk_autoref(expr, &place_with_id, autoref);
542                 }
543             }
544             place_with_id =
545                 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
546         }
547     }
548
549     /// Walks the autoref `autoref` applied to the autoderef'd
550     /// `expr`. `base_place` is the mem-categorized form of `expr`
551     /// after all relevant autoderefs have occurred.
552     fn walk_autoref(
553         &mut self,
554         expr: &hir::Expr<'_>,
555         base_place: &PlaceWithHirId<'tcx>,
556         autoref: &adjustment::AutoBorrow<'tcx>,
557     ) {
558         debug!(
559             "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
560             expr.hir_id, base_place, autoref
561         );
562
563         match *autoref {
564             adjustment::AutoBorrow::Ref(_, m) => {
565                 self.delegate.borrow(
566                     base_place,
567                     base_place.hir_id,
568                     ty::BorrowKind::from_mutbl(m.into()),
569                 );
570             }
571
572             adjustment::AutoBorrow::RawPtr(m) => {
573                 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
574
575                 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
576             }
577         }
578     }
579
580     fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
581         self.delegate.fake_read(
582             discr_place.place.clone(),
583             FakeReadCause::ForMatchedPlace,
584             discr_place.hir_id,
585         );
586         self.walk_pat(discr_place, &arm.pat);
587
588         if let Some(hir::Guard::If(ref e)) = arm.guard {
589             self.consume_expr(e)
590         }
591
592         self.consume_expr(&arm.body);
593     }
594
595     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
596     /// let binding, and *not* a match arm or nested pat.)
597     fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
598         self.delegate.fake_read(
599             discr_place.place.clone(),
600             FakeReadCause::ForLet,
601             discr_place.hir_id,
602         );
603         self.walk_pat(discr_place, pat);
604     }
605
606     /// The core driver for walking a pattern
607     fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
608         debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
609
610         let tcx = self.tcx();
611         let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
612         return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
613             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
614                 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
615                 if let Some(bm) =
616                     mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
617                 {
618                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
619
620                     // pat_ty: the type of the binding being produced.
621                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
622                     debug!("walk_pat: pat_ty={:?}", pat_ty);
623
624                     // Each match binding is effectively an assignment to the
625                     // binding being produced.
626                     let def = Res::Local(canonical_id);
627                     if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
628                         delegate.mutate(binding_place, binding_place.hir_id);
629                     }
630
631                     // It is also a borrow or copy/move of the value being matched.
632                     // In a cases of pattern like `let pat = upvar`, don't use the span
633                     // of the pattern, as this just looks confusing, instead use the span
634                     // of the discriminant.
635                     match bm {
636                         ty::BindByReference(m) => {
637                             let bk = ty::BorrowKind::from_mutbl(m);
638                             delegate.borrow(place, discr_place.hir_id, bk);
639                         }
640                         ty::BindByValue(..) => {
641                             let mode = copy_or_move(mc, &place);
642                             debug!("walk_pat binding consuming pat");
643                             delegate.consume(place, discr_place.hir_id, mode);
644                         }
645                     }
646                 }
647             }
648         }));
649     }
650
651     /// Handle the case where the current body contains a closure.
652     ///
653     /// When the current body being handled is a closure, then we must make sure that
654     /// - The parent closure only captures Places from the nested closure that are not local to it.
655     ///
656     /// In the following example the closures `c` only captures `p.x`` even though `incr`
657     /// is a capture of the nested closure
658     ///
659     /// ```rust,ignore(cannot-test-this-because-pseduo-code)
660     /// let p = ..;
661     /// let c = || {
662     ///    let incr = 10;
663     ///    let nested = || p.x += incr;
664     /// }
665     /// ```
666     ///
667     /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
668     /// closure as the DefId.
669     fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
670         fn upvar_is_local_variable(
671             upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
672             upvar_id: &hir::HirId,
673             body_owner_is_closure: bool,
674         ) -> bool {
675             upvars.map(|upvars| !upvars.contains_key(upvar_id)).unwrap_or(body_owner_is_closure)
676         }
677
678         debug!("walk_captures({:?})", closure_expr);
679
680         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
681         let upvars = self.tcx().upvars_mentioned(self.body_owner);
682
683         // For purposes of this function, generator and closures are equivalent.
684         let body_owner_is_closure = matches!(
685             self.tcx().type_of(self.body_owner.to_def_id()).kind(),
686             ty::Closure(..) | ty::Generator(..)
687         );
688
689         // If we have a nested closure, we want to include the fake reads present in the nested closure.
690         if let Some(fake_reads) = self.mc.typeck_results.closure_fake_reads.get(&closure_def_id) {
691             for (fake_read, cause, hir_id) in fake_reads.iter() {
692                 match fake_read.base {
693                     PlaceBase::Upvar(upvar_id) => {
694                         if upvar_is_local_variable(
695                             upvars,
696                             &upvar_id.var_path.hir_id,
697                             body_owner_is_closure,
698                         ) {
699                             // The nested closure might be fake reading the current (enclosing) closure's local variables.
700                             // The only places we want to fake read before creating the parent closure are the ones that
701                             // are not local to it/ defined by it.
702                             //
703                             // ```rust,ignore(cannot-test-this-because-pseduo-code)
704                             // let v1 = (0, 1);
705                             // let c = || { // fake reads: v1
706                             //    let v2 = (0, 1);
707                             //    let e = || { // fake reads: v1, v2
708                             //       let (_, t1) = v1;
709                             //       let (_, t2) = v2;
710                             //    }
711                             // }
712                             // ```
713                             // This check is performed when visiting the body of the outermost closure (`c`) and ensures
714                             // that we don't add a fake read of v2 in c.
715                             continue;
716                         }
717                     }
718                     _ => {
719                         bug!(
720                             "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
721                             fake_read.base
722                         );
723                     }
724                 };
725                 self.delegate.fake_read(fake_read.clone(), *cause, *hir_id);
726             }
727         }
728
729         if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
730         {
731             for (var_hir_id, min_list) in min_captures.iter() {
732                 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
733                     // The nested closure might be capturing the current (enclosing) closure's local variables.
734                     // We check if the root variable is ever mentioned within the enclosing closure, if not
735                     // then for the current body (if it's a closure) these aren't captures, we will ignore them.
736                     continue;
737                 }
738                 for captured_place in min_list {
739                     let place = &captured_place.place;
740                     let capture_info = captured_place.info;
741
742                     let place_base = if body_owner_is_closure {
743                         // Mark the place to be captured by the enclosing closure
744                         PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
745                     } else {
746                         // If the body owner isn't a closure then the variable must
747                         // be a local variable
748                         PlaceBase::Local(*var_hir_id)
749                     };
750                     let place_with_id = PlaceWithHirId::new(
751                         capture_info.path_expr_id.unwrap_or(closure_expr.hir_id),
752                         place.base_ty,
753                         place_base,
754                         place.projections.clone(),
755                     );
756
757                     match capture_info.capture_kind {
758                         ty::UpvarCapture::ByValue(_) => {
759                             let mode = copy_or_move(&self.mc, &place_with_id);
760                             self.delegate.consume(&place_with_id, place_with_id.hir_id, mode);
761                         }
762                         ty::UpvarCapture::ByRef(upvar_borrow) => {
763                             self.delegate.borrow(
764                                 &place_with_id,
765                                 place_with_id.hir_id,
766                                 upvar_borrow.kind,
767                             );
768                         }
769                     }
770                 }
771             }
772         }
773     }
774 }
775
776 fn copy_or_move<'a, 'tcx>(
777     mc: &mc::MemCategorizationContext<'a, 'tcx>,
778     place_with_id: &PlaceWithHirId<'tcx>,
779 ) -> ConsumeMode {
780     if !mc.type_is_copy_modulo_regions(
781         place_with_id.place.ty(),
782         mc.tcx().hir().span(place_with_id.hir_id),
783     ) {
784         Move
785     } else {
786         Copy
787     }
788 }