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 use hir::def::DefKind;
6 // Export these here so that Clippy can use them.
7 pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
8 
9 use rustc_data_structures::fx::FxIndexMap;
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::mir::FakeReadCause;
18 use rustc_middle::ty::{self, adjustment, AdtKind, Ty, TyCtxt};
19 use rustc_target::abi::VariantIdx;
20 use std::iter;
21 
22 use crate::mem_categorization as mc;
23 
24 /// This trait defines the callbacks you can expect to receive when
25 /// employing the ExprUseVisitor.
26 pub trait Delegate<'tcx> {
27     /// The value found at `place` is moved, depending
28     /// on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
29     ///
30     /// Use of a `Copy` type in a ByValue context is considered a use
31     /// by `ImmBorrow` and `borrow` is called instead. This is because
32     /// a shared borrow is the "minimum access" that would be needed
33     /// to perform a copy.
34     ///
35     ///
36     /// The parameter `diag_expr_id` indicates the HIR id that ought to be used for
37     /// diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
38     /// id will be the id of the expression `expr` but the place itself will have
39     /// the id of the binding in the pattern `pat`.
consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId)40     fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
41 
42     /// The value found at `place` is being borrowed with kind `bk`.
43     /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
borrow( &mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId, bk: ty::BorrowKind, )44     fn borrow(
45         &mut self,
46         place_with_id: &PlaceWithHirId<'tcx>,
47         diag_expr_id: hir::HirId,
48         bk: ty::BorrowKind,
49     );
50 
51     /// The path at `assignee_place` is being assigned to.
52     /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId)53     fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
54 
55     /// The `place` should be a fake read because of specified `cause`.
fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId)56     fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId);
57 }
58 
59 #[derive(Copy, Clone, PartialEq, Debug)]
60 enum ConsumeMode {
61     /// reference to x where x has a type that copies
62     Copy,
63     /// reference to x where x has a type that moves
64     Move,
65 }
66 
67 #[derive(Copy, Clone, PartialEq, Debug)]
68 pub enum MutateMode {
69     Init,
70     /// Example: `x = y`
71     JustWrite,
72     /// Example: `x += y`
73     WriteAndRead,
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
new( delegate: &'a mut (dyn Delegate<'tcx> + 'a), infcx: &'a InferCtxt<'a, 'tcx>, body_owner: LocalDefId, param_env: ty::ParamEnv<'tcx>, typeck_results: &'a ty::TypeckResults<'tcx>, ) -> Self110     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     #[instrument(skip(self), level = "debug")]
consume_body(&mut self, body: &hir::Body<'_>)125     pub fn consume_body(&mut self, body: &hir::Body<'_>) {
126         for param in body.params {
127             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(param.pat));
128             debug!("consume_body: param_ty = {:?}", param_ty);
129 
130             let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
131 
132             self.walk_irrefutable_pat(&param_place, param.pat);
133         }
134 
135         self.consume_expr(&body.value);
136     }
137 
tcx(&self) -> TyCtxt<'tcx>138     fn tcx(&self) -> TyCtxt<'tcx> {
139         self.mc.tcx()
140     }
141 
delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId)142     fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
143         delegate_consume(&self.mc, self.delegate, place_with_id, diag_expr_id)
144     }
145 
consume_exprs(&mut self, exprs: &[hir::Expr<'_>])146     fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
147         for expr in exprs {
148             self.consume_expr(expr);
149         }
150     }
151 
consume_expr(&mut self, expr: &hir::Expr<'_>)152     pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
153         debug!("consume_expr(expr={:?})", expr);
154 
155         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
156         self.delegate_consume(&place_with_id, place_with_id.hir_id);
157         self.walk_expr(expr);
158     }
159 
mutate_expr(&mut self, expr: &hir::Expr<'_>)160     fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
161         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
162         self.delegate.mutate(&place_with_id, place_with_id.hir_id);
163         self.walk_expr(expr);
164     }
165 
borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind)166     fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
167         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
168 
169         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
170         self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
171 
172         self.walk_expr(expr)
173     }
174 
select_from_expr(&mut self, expr: &hir::Expr<'_>)175     fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
176         self.walk_expr(expr)
177     }
178 
walk_expr(&mut self, expr: &hir::Expr<'_>)179     pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
180         debug!("walk_expr(expr={:?})", expr);
181 
182         self.walk_adjustment(expr);
183 
184         match expr.kind {
185             hir::ExprKind::Path(_) => {}
186 
187             hir::ExprKind::Type(subexpr, _) => self.walk_expr(subexpr),
188 
189             hir::ExprKind::Unary(hir::UnOp::Deref, base) => {
190                 // *base
191                 self.select_from_expr(base);
192             }
193 
194             hir::ExprKind::Field(base, _) => {
195                 // base.f
196                 self.select_from_expr(base);
197             }
198 
199             hir::ExprKind::Index(lhs, rhs) => {
200                 // lhs[rhs]
201                 self.select_from_expr(lhs);
202                 self.consume_expr(rhs);
203             }
204 
205             hir::ExprKind::Call(callee, args) => {
206                 // callee(args)
207                 self.consume_expr(callee);
208                 self.consume_exprs(args);
209             }
210 
211             hir::ExprKind::MethodCall(.., args, _) => {
212                 // callee.m(args)
213                 self.consume_exprs(args);
214             }
215 
216             hir::ExprKind::Struct(_, fields, ref opt_with) => {
217                 self.walk_struct_expr(fields, opt_with);
218             }
219 
220             hir::ExprKind::Tup(exprs) => {
221                 self.consume_exprs(exprs);
222             }
223 
224             hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
225                 self.consume_expr(cond_expr);
226                 self.consume_expr(then_expr);
227                 if let Some(ref else_expr) = *opt_else_expr {
228                     self.consume_expr(else_expr);
229                 }
230             }
231 
232             hir::ExprKind::Let(pat, ref expr, _) => {
233                 self.walk_local(expr, pat, |t| t.borrow_expr(expr, ty::ImmBorrow));
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::Path(qpath) => {
256                                 // A `Path` pattern is just a name like `Foo`. This is either a
257                                 // named constant or else it refers to an ADT variant
258 
259                                 let res = self.mc.typeck_results.qpath_res(qpath, pat.hir_id);
260                                 match res {
261                                     Res::Def(DefKind::Const, _)
262                                     | Res::Def(DefKind::AssocConst, _) => {
263                                         // Named constants have to be equated with the value
264                                         // being matched, so that's a read of the value being matched.
265                                         //
266                                         // FIXME: We don't actually  reads for ZSTs.
267                                         needs_to_be_read = true;
268                                     }
269                                     _ => {
270                                         // Otherwise, this is a struct/enum variant, and so it's
271                                         // only a read if we need to read the discriminant.
272                                         needs_to_be_read |= is_multivariant_adt(place.place.ty());
273                                     }
274                                 }
275                             }
276                             PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => {
277                                 // For `Foo(..)`, `Foo { ... }` and `(...)` patterns, check if we are matching
278                                 // against a multivariant enum or struct. In that case, we have to read
279                                 // the discriminant. Otherwise this kind of pattern doesn't actually
280                                 // read anything (we'll get invoked for the `...`, which may indeed
281                                 // perform some reads).
282 
283                                 let place_ty = place.place.ty();
284                                 needs_to_be_read |= is_multivariant_adt(place_ty);
285                             }
286                             PatKind::Lit(_) | PatKind::Range(..) => {
287                                 // If the PatKind is a Lit or a Range then we want
288                                 // to borrow discr.
289                                 needs_to_be_read = true;
290                             }
291                             PatKind::Or(_)
292                             | PatKind::Box(_)
293                             | PatKind::Slice(..)
294                             | PatKind::Ref(..)
295                             | PatKind::Wild => {
296                                 // If the PatKind is Or, Box, Slice or Ref, the decision is made later
297                                 // as these patterns contains subpatterns
298                                 // If the PatKind is Wild, the decision is made based on the other patterns being
299                                 // examined
300                             }
301                         }
302                     }));
303                 }
304 
305                 if needs_to_be_read {
306                     self.borrow_expr(discr, ty::ImmBorrow);
307                 } else {
308                     let closure_def_id = match discr_place.place.base {
309                         PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
310                         _ => None,
311                     };
312 
313                     self.delegate.fake_read(
314                         discr_place.place.clone(),
315                         FakeReadCause::ForMatchedPlace(closure_def_id),
316                         discr_place.hir_id,
317                     );
318 
319                     // We always want to walk the discriminant. We want to make sure, for instance,
320                     // that the discriminant has been initialized.
321                     self.walk_expr(discr);
322                 }
323 
324                 // treatment of the discriminant is handled while walking the arms.
325                 for arm in arms {
326                     self.walk_arm(&discr_place, arm);
327                 }
328             }
329 
330             hir::ExprKind::Array(exprs) => {
331                 self.consume_exprs(exprs);
332             }
333 
334             hir::ExprKind::AddrOf(_, m, ref base) => {
335                 // &base
336                 // make sure that the thing we are pointing out stays valid
337                 // for the lifetime `scope_r` of the resulting ptr:
338                 let bk = ty::BorrowKind::from_mutbl(m);
339                 self.borrow_expr(base, bk);
340             }
341 
342             hir::ExprKind::InlineAsm(asm) => {
343                 for (op, _op_sp) in asm.operands {
344                     match op {
345                         hir::InlineAsmOperand::In { expr, .. }
346                         | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
347                         hir::InlineAsmOperand::Out { expr: Some(expr), .. }
348                         | hir::InlineAsmOperand::InOut { expr, .. } => {
349                             self.mutate_expr(expr);
350                         }
351                         hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
352                             self.consume_expr(in_expr);
353                             if let Some(out_expr) = out_expr {
354                                 self.mutate_expr(out_expr);
355                             }
356                         }
357                         hir::InlineAsmOperand::Out { expr: None, .. }
358                         | hir::InlineAsmOperand::Const { .. } => {}
359                     }
360                 }
361             }
362 
363             hir::ExprKind::LlvmInlineAsm(ia) => {
364                 for (o, output) in iter::zip(&ia.inner.outputs, ia.outputs_exprs) {
365                     if o.is_indirect {
366                         self.consume_expr(output);
367                     } else {
368                         self.mutate_expr(output);
369                     }
370                 }
371                 self.consume_exprs(ia.inputs_exprs);
372             }
373 
374             hir::ExprKind::Continue(..)
375             | hir::ExprKind::Lit(..)
376             | hir::ExprKind::ConstBlock(..)
377             | hir::ExprKind::Err => {}
378 
379             hir::ExprKind::Loop(blk, ..) => {
380                 self.walk_block(blk);
381             }
382 
383             hir::ExprKind::Unary(_, lhs) => {
384                 self.consume_expr(lhs);
385             }
386 
387             hir::ExprKind::Binary(_, lhs, rhs) => {
388                 self.consume_expr(lhs);
389                 self.consume_expr(rhs);
390             }
391 
392             hir::ExprKind::Block(blk, _) => {
393                 self.walk_block(blk);
394             }
395 
396             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
397                 if let Some(expr) = *opt_expr {
398                     self.consume_expr(expr);
399                 }
400             }
401 
402             hir::ExprKind::Assign(lhs, rhs, _) => {
403                 self.mutate_expr(lhs);
404                 self.consume_expr(rhs);
405             }
406 
407             hir::ExprKind::Cast(base, _) => {
408                 self.consume_expr(base);
409             }
410 
411             hir::ExprKind::DropTemps(expr) => {
412                 self.consume_expr(expr);
413             }
414 
415             hir::ExprKind::AssignOp(_, lhs, rhs) => {
416                 if self.mc.typeck_results.is_method_call(expr) {
417                     self.consume_expr(lhs);
418                 } else {
419                     self.mutate_expr(lhs);
420                 }
421                 self.consume_expr(rhs);
422             }
423 
424             hir::ExprKind::Repeat(base, _) => {
425                 self.consume_expr(base);
426             }
427 
428             hir::ExprKind::Closure(..) => {
429                 self.walk_captures(expr);
430             }
431 
432             hir::ExprKind::Box(ref base) => {
433                 self.consume_expr(base);
434             }
435 
436             hir::ExprKind::Yield(value, _) => {
437                 self.consume_expr(value);
438             }
439         }
440     }
441 
walk_stmt(&mut self, stmt: &hir::Stmt<'_>)442     fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
443         match stmt.kind {
444             hir::StmtKind::Local(hir::Local { pat, init: Some(expr), .. }) => {
445                 self.walk_local(expr, pat, |_| {});
446             }
447 
448             hir::StmtKind::Local(_) => {}
449 
450             hir::StmtKind::Item(_) => {
451                 // We don't visit nested items in this visitor,
452                 // only the fn body we were given.
453             }
454 
455             hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
456                 self.consume_expr(expr);
457             }
458         }
459     }
460 
walk_local<F>(&mut self, expr: &hir::Expr<'_>, pat: &hir::Pat<'_>, mut f: F) where F: FnMut(&mut Self),461     fn walk_local<F>(&mut self, expr: &hir::Expr<'_>, pat: &hir::Pat<'_>, mut f: F)
462     where
463         F: FnMut(&mut Self),
464     {
465         self.walk_expr(expr);
466         let expr_place = return_if_err!(self.mc.cat_expr(expr));
467         f(self);
468         self.walk_irrefutable_pat(&expr_place, &pat);
469     }
470 
471     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
472     /// depending on its type.
walk_block(&mut self, blk: &hir::Block<'_>)473     fn walk_block(&mut self, blk: &hir::Block<'_>) {
474         debug!("walk_block(blk.hir_id={})", blk.hir_id);
475 
476         for stmt in blk.stmts {
477             self.walk_stmt(stmt);
478         }
479 
480         if let Some(ref tail_expr) = blk.expr {
481             self.consume_expr(tail_expr);
482         }
483     }
484 
walk_struct_expr( &mut self, fields: &[hir::ExprField<'_>], opt_with: &Option<&'hir hir::Expr<'_>>, )485     fn walk_struct_expr(
486         &mut self,
487         fields: &[hir::ExprField<'_>],
488         opt_with: &Option<&'hir hir::Expr<'_>>,
489     ) {
490         // Consume the expressions supplying values for each field.
491         for field in fields {
492             self.consume_expr(field.expr);
493         }
494 
495         let with_expr = match *opt_with {
496             Some(w) => &*w,
497             None => {
498                 return;
499             }
500         };
501 
502         let with_place = return_if_err!(self.mc.cat_expr(with_expr));
503 
504         // Select just those fields of the `with`
505         // expression that will actually be used
506         match with_place.place.ty().kind() {
507             ty::Adt(adt, substs) if adt.is_struct() => {
508                 // Consume those fields of the with expression that are needed.
509                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
510                     let is_mentioned = fields.iter().any(|f| {
511                         self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
512                     });
513                     if !is_mentioned {
514                         let field_place = self.mc.cat_projection(
515                             &*with_expr,
516                             with_place.clone(),
517                             with_field.ty(self.tcx(), substs),
518                             ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
519                         );
520                         self.delegate_consume(&field_place, field_place.hir_id);
521                     }
522                 }
523             }
524             _ => {
525                 // the base expression should always evaluate to a
526                 // struct; however, when EUV is run during typeck, it
527                 // may not. This will generate an error earlier in typeck,
528                 // so we can just ignore it.
529                 if !self.tcx().sess.has_errors() {
530                     span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
531                 }
532             }
533         }
534 
535         // walk the with expression so that complex expressions
536         // are properly handled.
537         self.walk_expr(with_expr);
538     }
539 
540     /// Invoke the appropriate delegate calls for anything that gets
541     /// consumed or borrowed as part of the automatic adjustment
542     /// process.
walk_adjustment(&mut self, expr: &hir::Expr<'_>)543     fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
544         let adjustments = self.mc.typeck_results.expr_adjustments(expr);
545         let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
546         for adjustment in adjustments {
547             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
548             match adjustment.kind {
549                 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
550                     // Creating a closure/fn-pointer or unsizing consumes
551                     // the input and stores it into the resulting rvalue.
552                     self.delegate_consume(&place_with_id, place_with_id.hir_id);
553                 }
554 
555                 adjustment::Adjust::Deref(None) => {}
556 
557                 // Autoderefs for overloaded Deref calls in fact reference
558                 // their receiver. That is, if we have `(*x)` where `x`
559                 // is of type `Rc<T>`, then this in fact is equivalent to
560                 // `x.deref()`. Since `deref()` is declared with `&self`,
561                 // this is an autoref of `x`.
562                 adjustment::Adjust::Deref(Some(ref deref)) => {
563                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
564                     self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
565                 }
566 
567                 adjustment::Adjust::Borrow(ref autoref) => {
568                     self.walk_autoref(expr, &place_with_id, autoref);
569                 }
570             }
571             place_with_id =
572                 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, adjustment));
573         }
574     }
575 
576     /// Walks the autoref `autoref` applied to the autoderef'd
577     /// `expr`. `base_place` is the mem-categorized form of `expr`
578     /// after all relevant autoderefs have occurred.
walk_autoref( &mut self, expr: &hir::Expr<'_>, base_place: &PlaceWithHirId<'tcx>, autoref: &adjustment::AutoBorrow<'tcx>, )579     fn walk_autoref(
580         &mut self,
581         expr: &hir::Expr<'_>,
582         base_place: &PlaceWithHirId<'tcx>,
583         autoref: &adjustment::AutoBorrow<'tcx>,
584     ) {
585         debug!(
586             "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
587             expr.hir_id, base_place, autoref
588         );
589 
590         match *autoref {
591             adjustment::AutoBorrow::Ref(_, m) => {
592                 self.delegate.borrow(
593                     base_place,
594                     base_place.hir_id,
595                     ty::BorrowKind::from_mutbl(m.into()),
596                 );
597             }
598 
599             adjustment::AutoBorrow::RawPtr(m) => {
600                 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
601 
602                 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
603             }
604         }
605     }
606 
walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>)607     fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
608         let closure_def_id = match discr_place.place.base {
609             PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
610             _ => None,
611         };
612 
613         self.delegate.fake_read(
614             discr_place.place.clone(),
615             FakeReadCause::ForMatchedPlace(closure_def_id),
616             discr_place.hir_id,
617         );
618         self.walk_pat(discr_place, arm.pat);
619 
620         if let Some(hir::Guard::If(e)) = arm.guard {
621             self.consume_expr(e)
622         } else if let Some(hir::Guard::IfLet(_, ref e)) = arm.guard {
623             self.consume_expr(e)
624         }
625 
626         self.consume_expr(arm.body);
627     }
628 
629     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
630     /// let binding, and *not* a match arm or nested pat.)
walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>)631     fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
632         let closure_def_id = match discr_place.place.base {
633             PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
634             _ => None,
635         };
636 
637         self.delegate.fake_read(
638             discr_place.place.clone(),
639             FakeReadCause::ForLet(closure_def_id),
640             discr_place.hir_id,
641         );
642         self.walk_pat(discr_place, pat);
643     }
644 
645     /// The core driver for walking a pattern
walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>)646     fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
647         debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
648 
649         let tcx = self.tcx();
650         let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
651         return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
652             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
653                 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
654                 if let Some(bm) =
655                     mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
656                 {
657                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
658 
659                     // pat_ty: the type of the binding being produced.
660                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
661                     debug!("walk_pat: pat_ty={:?}", pat_ty);
662 
663                     // Each match binding is effectively an assignment to the
664                     // binding being produced.
665                     let def = Res::Local(canonical_id);
666                     if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
667                         delegate.mutate(binding_place, binding_place.hir_id);
668                     }
669 
670                     // It is also a borrow or copy/move of the value being matched.
671                     // In a cases of pattern like `let pat = upvar`, don't use the span
672                     // of the pattern, as this just looks confusing, instead use the span
673                     // of the discriminant.
674                     match bm {
675                         ty::BindByReference(m) => {
676                             let bk = ty::BorrowKind::from_mutbl(m);
677                             delegate.borrow(place, discr_place.hir_id, bk);
678                         }
679                         ty::BindByValue(..) => {
680                             debug!("walk_pat binding consuming pat");
681                             delegate_consume(mc, *delegate, place, discr_place.hir_id);
682                         }
683                     }
684                 }
685             }
686         }));
687     }
688 
689     /// Handle the case where the current body contains a closure.
690     ///
691     /// When the current body being handled is a closure, then we must make sure that
692     /// - The parent closure only captures Places from the nested closure that are not local to it.
693     ///
694     /// In the following example the closures `c` only captures `p.x` even though `incr`
695     /// is a capture of the nested closure
696     ///
697     /// ```rust,ignore(cannot-test-this-because-pseudo-code)
698     /// let p = ..;
699     /// let c = || {
700     ///    let incr = 10;
701     ///    let nested = || p.x += incr;
702     /// }
703     /// ```
704     ///
705     /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
706     /// closure as the DefId.
walk_captures(&mut self, closure_expr: &hir::Expr<'_>)707     fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
708         fn upvar_is_local_variable(
709             upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
710             upvar_id: &hir::HirId,
711             body_owner_is_closure: bool,
712         ) -> bool {
713             upvars.map(|upvars| !upvars.contains_key(upvar_id)).unwrap_or(body_owner_is_closure)
714         }
715 
716         debug!("walk_captures({:?})", closure_expr);
717 
718         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
719         let upvars = self.tcx().upvars_mentioned(self.body_owner);
720 
721         // For purposes of this function, generator and closures are equivalent.
722         let body_owner_is_closure = matches!(
723             self.tcx().type_of(self.body_owner.to_def_id()).kind(),
724             ty::Closure(..) | ty::Generator(..)
725         );
726 
727         // If we have a nested closure, we want to include the fake reads present in the nested closure.
728         if let Some(fake_reads) = self.mc.typeck_results.closure_fake_reads.get(&closure_def_id) {
729             for (fake_read, cause, hir_id) in fake_reads.iter() {
730                 match fake_read.base {
731                     PlaceBase::Upvar(upvar_id) => {
732                         if upvar_is_local_variable(
733                             upvars,
734                             &upvar_id.var_path.hir_id,
735                             body_owner_is_closure,
736                         ) {
737                             // The nested closure might be fake reading the current (enclosing) closure's local variables.
738                             // The only places we want to fake read before creating the parent closure are the ones that
739                             // are not local to it/ defined by it.
740                             //
741                             // ```rust,ignore(cannot-test-this-because-pseudo-code)
742                             // let v1 = (0, 1);
743                             // let c = || { // fake reads: v1
744                             //    let v2 = (0, 1);
745                             //    let e = || { // fake reads: v1, v2
746                             //       let (_, t1) = v1;
747                             //       let (_, t2) = v2;
748                             //    }
749                             // }
750                             // ```
751                             // This check is performed when visiting the body of the outermost closure (`c`) and ensures
752                             // that we don't add a fake read of v2 in c.
753                             continue;
754                         }
755                     }
756                     _ => {
757                         bug!(
758                             "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
759                             fake_read.base
760                         );
761                     }
762                 };
763                 self.delegate.fake_read(fake_read.clone(), *cause, *hir_id);
764             }
765         }
766 
767         if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
768         {
769             for (var_hir_id, min_list) in min_captures.iter() {
770                 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
771                     // The nested closure might be capturing the current (enclosing) closure's local variables.
772                     // We check if the root variable is ever mentioned within the enclosing closure, if not
773                     // then for the current body (if it's a closure) these aren't captures, we will ignore them.
774                     continue;
775                 }
776                 for captured_place in min_list {
777                     let place = &captured_place.place;
778                     let capture_info = captured_place.info;
779 
780                     let place_base = if body_owner_is_closure {
781                         // Mark the place to be captured by the enclosing closure
782                         PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
783                     } else {
784                         // If the body owner isn't a closure then the variable must
785                         // be a local variable
786                         PlaceBase::Local(*var_hir_id)
787                     };
788                     let place_with_id = PlaceWithHirId::new(
789                         capture_info.path_expr_id.unwrap_or(
790                             capture_info.capture_kind_expr_id.unwrap_or(closure_expr.hir_id),
791                         ),
792                         place.base_ty,
793                         place_base,
794                         place.projections.clone(),
795                     );
796 
797                     match capture_info.capture_kind {
798                         ty::UpvarCapture::ByValue(_) => {
799                             self.delegate_consume(&place_with_id, place_with_id.hir_id);
800                         }
801                         ty::UpvarCapture::ByRef(upvar_borrow) => {
802                             self.delegate.borrow(
803                                 &place_with_id,
804                                 place_with_id.hir_id,
805                                 upvar_borrow.kind,
806                             );
807                         }
808                     }
809                 }
810             }
811         }
812     }
813 }
814 
copy_or_move<'a, 'tcx>( mc: &mc::MemCategorizationContext<'a, 'tcx>, place_with_id: &PlaceWithHirId<'tcx>, ) -> ConsumeMode815 fn copy_or_move<'a, 'tcx>(
816     mc: &mc::MemCategorizationContext<'a, 'tcx>,
817     place_with_id: &PlaceWithHirId<'tcx>,
818 ) -> ConsumeMode {
819     if !mc.type_is_copy_modulo_regions(
820         place_with_id.place.ty(),
821         mc.tcx().hir().span(place_with_id.hir_id),
822     ) {
823         ConsumeMode::Move
824     } else {
825         ConsumeMode::Copy
826     }
827 }
828 
829 // - If a place is used in a `ByValue` context then move it if it's not a `Copy` type.
830 // - If the place that is a `Copy` type consider it an `ImmBorrow`.
delegate_consume<'a, 'tcx>( mc: &mc::MemCategorizationContext<'a, 'tcx>, delegate: &mut (dyn Delegate<'tcx> + 'a), place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId, )831 fn delegate_consume<'a, 'tcx>(
832     mc: &mc::MemCategorizationContext<'a, 'tcx>,
833     delegate: &mut (dyn Delegate<'tcx> + 'a),
834     place_with_id: &PlaceWithHirId<'tcx>,
835     diag_expr_id: hir::HirId,
836 ) {
837     debug!("delegate_consume(place_with_id={:?})", place_with_id);
838 
839     let mode = copy_or_move(mc, place_with_id);
840 
841     match mode {
842         ConsumeMode::Move => delegate.consume(place_with_id, diag_expr_id),
843         ConsumeMode::Copy => {
844             delegate.borrow(place_with_id, diag_expr_id, ty::BorrowKind::ImmBorrow)
845         }
846     }
847 }
848 
is_multivariant_adt(ty: Ty<'tcx>) -> bool849 fn is_multivariant_adt(ty: Ty<'tcx>) -> bool {
850     if let ty::Adt(def, _) = ty.kind() {
851         // Note that if a non-exhaustive SingleVariant is defined in another crate, we need
852         // to assume that more cases will be added to the variant in the future. This mean
853         // that we should handle non-exhaustive SingleVariant the same way we would handle
854         // a MultiVariant.
855         // If the variant is not local it must be defined in another crate.
856         let is_non_exhaustive = match def.adt_kind() {
857             AdtKind::Struct | AdtKind::Union => {
858                 def.non_enum_variant().is_field_list_non_exhaustive()
859             }
860             AdtKind::Enum => def.is_variant_list_non_exhaustive(),
861         };
862         def.variants.len() > 1 || (!def.did.is_local() && is_non_exhaustive)
863     } else {
864         false
865     }
866 }
867