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