]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_typeck/src/expr_use_visitor.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / compiler / rustc_hir_typeck / src / expr_use_visitor.rs
CommitLineData
9fa01778 1//! A different sort of visitor for walking fn bodies. Unlike the
1a4d82fc
JJ
2//! normal visitor, which just walks the entire body in one shot, the
3//! `ExprUseVisitor` determines how expressions are being used.
4
064997fb
FG
5use std::slice::from_ref;
6
94222f64 7use hir::def::DefKind;
064997fb 8use hir::Expr;
60c5eb7d 9// Export these here so that Clippy can use them.
6a06907d 10pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
60c5eb7d 11
6a06907d 12use rustc_data_structures::fx::FxIndexMap;
dfeec247
XL
13use rustc_hir as hir;
14use rustc_hir::def::Res;
f9f354fc 15use rustc_hir::def_id::LocalDefId;
dfeec247 16use rustc_hir::PatKind;
3dfed10e 17use rustc_index::vec::Idx;
74b04a01 18use rustc_infer::infer::InferCtxt;
3dfed10e 19use rustc_middle::hir::place::ProjectionKind;
6a06907d 20use rustc_middle::mir::FakeReadCause;
94222f64 21use rustc_middle::ty::{self, adjustment, AdtKind, Ty, TyCtxt};
3dfed10e 22use rustc_target::abi::VariantIdx;
923072b8 23use ty::BorrowKind::ImmBorrow;
60c5eb7d
XL
24
25use crate::mem_categorization as mc;
1a4d82fc 26
1a4d82fc
JJ
27/// This trait defines the callbacks you can expect to receive when
28/// employing the ExprUseVisitor.
29pub trait Delegate<'tcx> {
94222f64
XL
30 /// The value found at `place` is moved, depending
31 /// on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
32 ///
33 /// Use of a `Copy` type in a ByValue context is considered a use
34 /// by `ImmBorrow` and `borrow` is called instead. This is because
35 /// a shared borrow is the "minimum access" that would be needed
36 /// to perform a copy.
37 ///
38 ///
39 /// The parameter `diag_expr_id` indicates the HIR id that ought to be used for
40 /// diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
41 /// id will be the id of the expression `expr` but the place itself will have
42 /// the id of the binding in the pattern `pat`.
136023e0 43 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
1a4d82fc 44
94222f64
XL
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).
29967ef6
XL
47 fn borrow(
48 &mut self,
49 place_with_id: &PlaceWithHirId<'tcx>,
50 diag_expr_id: hir::HirId,
51 bk: ty::BorrowKind,
52 );
53
5e7ed085
FG
54 /// The value found at `place` is being copied.
55 /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
56 fn copy(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
57 // In most cases, copying data from `x` is equivalent to doing `*&x`, so by default
58 // we treat a copy of `x` as a borrow of `x`.
59 self.borrow(place_with_id, diag_expr_id, ty::BorrowKind::ImmBorrow)
60 }
61
94222f64
XL
62 /// The path at `assignee_place` is being assigned to.
63 /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
29967ef6 64 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
6a06907d 65
5e7ed085
FG
66 /// The path at `binding_place` is a binding that is being initialized.
67 ///
68 /// This covers cases such as `let x = 42;`
69 fn bind(&mut self, binding_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
70 // Bindings can normally be treated as a regular assignment, so by default we
71 // forward this to the mutate callback.
72 self.mutate(binding_place, diag_expr_id)
73 }
74
94222f64 75 /// The `place` should be a fake read because of specified `cause`.
923072b8
FG
76 fn fake_read(
77 &mut self,
78 place_with_id: &PlaceWithHirId<'tcx>,
79 cause: FakeReadCause,
80 diag_expr_id: hir::HirId,
81 );
1a4d82fc
JJ
82}
83
c34b1796 84#[derive(Copy, Clone, PartialEq, Debug)]
136023e0 85enum ConsumeMode {
94222f64
XL
86 /// reference to x where x has a type that copies
87 Copy,
88 /// reference to x where x has a type that moves
89 Move,
1a4d82fc
JJ
90}
91
94222f64
XL
92/// The ExprUseVisitor type
93///
94/// This is the code that actually walks the tree.
dc9dc135
XL
95pub struct ExprUseVisitor<'a, 'tcx> {
96 mc: mc::MemCategorizationContext<'a, 'tcx>,
fc512014 97 body_owner: LocalDefId,
0531ce1d 98 delegate: &'a mut dyn Delegate<'tcx>,
1a4d82fc
JJ
99}
100
94222f64
XL
101/// If the MC results in an error, it's because the type check
102/// failed (or will fail, when the error is uncovered and reported
103/// during writeback). In this case, we just ignore this part of the
104/// code.
105///
106/// Note that this macro appears similar to try!(), but, unlike try!(),
107/// it does not propagate the error.
1a4d82fc 108macro_rules! return_if_err {
dfeec247 109 ($inp: expr) => {
1a4d82fc
JJ
110 match $inp {
111 Ok(v) => v,
c1a9b12d
SL
112 Err(()) => {
113 debug!("mc reported err");
dfeec247 114 return;
c1a9b12d 115 }
1a4d82fc 116 }
dfeec247 117 };
1a4d82fc
JJ
118}
119
dc9dc135 120impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
abe05a73
XL
121 /// Creates the ExprUseVisitor, configuring it with the various options provided:
122 ///
123 /// - `delegate` -- who receives the callbacks
124 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
3dfed10e 125 /// - `typeck_results` --- typeck results for the code being analyzed
dc9dc135 126 pub fn new(
dc9dc135 127 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
2b03887a 128 infcx: &'a InferCtxt<'tcx>,
f9f354fc 129 body_owner: LocalDefId,
dc9dc135 130 param_env: ty::ParamEnv<'tcx>,
3dfed10e 131 typeck_results: &'a ty::TypeckResults<'tcx>,
dc9dc135 132 ) -> Self {
a7813a04 133 ExprUseVisitor {
3dfed10e 134 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
fc512014 135 body_owner,
7cac9316 136 delegate,
a7813a04 137 }
1a4d82fc
JJ
138 }
139
94222f64 140 #[instrument(skip(self), level = "debug")]
dfeec247 141 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
dfeec247 142 for param in body.params {
c295e0f8 143 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(param.pat));
e1599b0c 144 debug!("consume_body: param_ty = {:?}", param_ty);
1a4d82fc 145
60c5eb7d 146 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
1a4d82fc 147
c295e0f8 148 self.walk_irrefutable_pat(&param_place, param.pat);
1a4d82fc 149 }
32a655c1
SL
150
151 self.consume_expr(&body.value);
1a4d82fc
JJ
152 }
153
dc9dc135 154 fn tcx(&self) -> TyCtxt<'tcx> {
60c5eb7d 155 self.mc.tcx()
1a4d82fc
JJ
156 }
157
29967ef6 158 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
136023e0 159 delegate_consume(&self.mc, self.delegate, place_with_id, diag_expr_id)
1a4d82fc
JJ
160 }
161
dfeec247 162 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
85aaf69f 163 for expr in exprs {
c295e0f8 164 self.consume_expr(expr);
1a4d82fc
JJ
165 }
166 }
167
dfeec247 168 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
62682a34 169 debug!("consume_expr(expr={:?})", expr);
1a4d82fc 170
f035d41b 171 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
29967ef6 172 self.delegate_consume(&place_with_id, place_with_id.hir_id);
1a4d82fc
JJ
173 self.walk_expr(expr);
174 }
175
dfeec247 176 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
f035d41b 177 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
29967ef6 178 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
1a4d82fc
JJ
179 self.walk_expr(expr);
180 }
181
dfeec247 182 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
e74abb32 183 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
1a4d82fc 184
f035d41b 185 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
29967ef6 186 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
1a4d82fc 187
1a4d82fc
JJ
188 self.walk_expr(expr)
189 }
190
dfeec247 191 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
1a4d82fc
JJ
192 self.walk_expr(expr)
193 }
194
dfeec247 195 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
62682a34 196 debug!("walk_expr(expr={:?})", expr);
1a4d82fc
JJ
197
198 self.walk_adjustment(expr);
199
e74abb32 200 match expr.kind {
dfeec247 201 hir::ExprKind::Path(_) => {}
1a4d82fc 202
c295e0f8 203 hir::ExprKind::Type(subexpr, _) => self.walk_expr(subexpr),
9cc50fc6 204
c295e0f8 205 hir::ExprKind::Unary(hir::UnOp::Deref, base) => {
dfeec247 206 // *base
e74abb32 207 self.select_from_expr(base);
1a4d82fc
JJ
208 }
209
c295e0f8 210 hir::ExprKind::Field(base, _) => {
dfeec247 211 // base.f
e74abb32 212 self.select_from_expr(base);
1a4d82fc
JJ
213 }
214
c295e0f8 215 hir::ExprKind::Index(lhs, rhs) => {
dfeec247 216 // lhs[rhs]
e74abb32
XL
217 self.select_from_expr(lhs);
218 self.consume_expr(rhs);
1a4d82fc
JJ
219 }
220
c295e0f8 221 hir::ExprKind::Call(callee, args) => {
dfeec247
XL
222 // callee(args)
223 self.consume_expr(callee);
1a4d82fc
JJ
224 self.consume_exprs(args);
225 }
226
f2b60f7d 227 hir::ExprKind::MethodCall(.., receiver, args, _) => {
dfeec247 228 // callee.m(args)
f2b60f7d 229 self.consume_expr(receiver);
1a4d82fc
JJ
230 self.consume_exprs(args);
231 }
232
c295e0f8 233 hir::ExprKind::Struct(_, fields, ref opt_with) => {
9e0c209e 234 self.walk_struct_expr(fields, opt_with);
1a4d82fc
JJ
235 }
236
c295e0f8 237 hir::ExprKind::Tup(exprs) => {
1a4d82fc
JJ
238 self.consume_exprs(exprs);
239 }
240
5869c6ff 241 hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
c295e0f8
XL
242 self.consume_expr(cond_expr);
243 self.consume_expr(then_expr);
5869c6ff 244 if let Some(ref else_expr) = *opt_else_expr {
c295e0f8 245 self.consume_expr(else_expr);
5869c6ff
XL
246 }
247 }
248
a2a8927a 249 hir::ExprKind::Let(hir::Let { pat, init, .. }) => {
064997fb 250 self.walk_local(init, pat, None, |t| t.borrow_expr(init, ty::ImmBorrow))
94222f64
XL
251 }
252
dfeec247 253 hir::ExprKind::Match(ref discr, arms, _) => {
c295e0f8 254 let discr_place = return_if_err!(self.mc.cat_expr(discr));
487cf647 255 return_if_err!(self.maybe_read_scrutinee(
064997fb
FG
256 discr,
257 discr_place.clone(),
258 arms.iter().map(|arm| arm.pat),
487cf647 259 ));
1a4d82fc
JJ
260
261 // treatment of the discriminant is handled while walking the arms.
85aaf69f 262 for arm in arms {
60c5eb7d 263 self.walk_arm(&discr_place, arm);
1a4d82fc
JJ
264 }
265 }
266
c295e0f8 267 hir::ExprKind::Array(exprs) => {
1a4d82fc
JJ
268 self.consume_exprs(exprs);
269 }
270
dfeec247
XL
271 hir::ExprKind::AddrOf(_, m, ref base) => {
272 // &base
1a4d82fc
JJ
273 // make sure that the thing we are pointing out stays valid
274 // for the lifetime `scope_r` of the resulting ptr:
e74abb32 275 let bk = ty::BorrowKind::from_mutbl(m);
c295e0f8 276 self.borrow_expr(base, bk);
1a4d82fc
JJ
277 }
278
c295e0f8 279 hir::ExprKind::InlineAsm(asm) => {
fc512014 280 for (op, _op_sp) in asm.operands {
f9f354fc 281 match op {
04454e1e 282 hir::InlineAsmOperand::In { expr, .. } => self.consume_expr(expr),
94222f64
XL
283 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
284 | hir::InlineAsmOperand::InOut { expr, .. } => {
f9f354fc
XL
285 self.mutate_expr(expr);
286 }
287 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
288 self.consume_expr(in_expr);
289 if let Some(out_expr) = out_expr {
290 self.mutate_expr(out_expr);
291 }
292 }
94222f64 293 hir::InlineAsmOperand::Out { expr: None, .. }
04454e1e
FG
294 | hir::InlineAsmOperand::Const { .. }
295 | hir::InlineAsmOperand::SymFn { .. }
296 | hir::InlineAsmOperand::SymStatic { .. } => {}
f9f354fc
XL
297 }
298 }
299 }
300
29967ef6
XL
301 hir::ExprKind::Continue(..)
302 | hir::ExprKind::Lit(..)
303 | hir::ExprKind::ConstBlock(..)
304 | hir::ExprKind::Err => {}
1a4d82fc 305
c295e0f8 306 hir::ExprKind::Loop(blk, ..) => {
e74abb32 307 self.walk_block(blk);
1a4d82fc
JJ
308 }
309
c295e0f8 310 hir::ExprKind::Unary(_, lhs) => {
e74abb32 311 self.consume_expr(lhs);
1a4d82fc
JJ
312 }
313
c295e0f8 314 hir::ExprKind::Binary(_, lhs, rhs) => {
e74abb32
XL
315 self.consume_expr(lhs);
316 self.consume_expr(rhs);
1a4d82fc
JJ
317 }
318
c295e0f8 319 hir::ExprKind::Block(blk, _) => {
e74abb32 320 self.walk_block(blk);
1a4d82fc
JJ
321 }
322
8faf50e0 323 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
c295e0f8 324 if let Some(expr) = *opt_expr {
e74abb32 325 self.consume_expr(expr);
1a4d82fc
JJ
326 }
327 }
328
c295e0f8 329 hir::ExprKind::Assign(lhs, rhs, _) => {
e74abb32
XL
330 self.mutate_expr(lhs);
331 self.consume_expr(rhs);
1a4d82fc
JJ
332 }
333
c295e0f8 334 hir::ExprKind::Cast(base, _) => {
e74abb32 335 self.consume_expr(base);
1a4d82fc
JJ
336 }
337
c295e0f8 338 hir::ExprKind::DropTemps(expr) => {
e74abb32 339 self.consume_expr(expr);
48663c56
XL
340 }
341
c295e0f8 342 hir::ExprKind::AssignOp(_, lhs, rhs) => {
3dfed10e 343 if self.mc.typeck_results.is_method_call(expr) {
7cac9316
XL
344 self.consume_expr(lhs);
345 } else {
e74abb32 346 self.mutate_expr(lhs);
b039eaaf 347 }
e74abb32 348 self.consume_expr(rhs);
1a4d82fc
JJ
349 }
350
c295e0f8 351 hir::ExprKind::Repeat(base, _) => {
e74abb32 352 self.consume_expr(base);
1a4d82fc
JJ
353 }
354
487cf647
FG
355 hir::ExprKind::Closure(closure) => {
356 self.walk_captures(closure);
1a4d82fc
JJ
357 }
358
8faf50e0 359 hir::ExprKind::Box(ref base) => {
e74abb32 360 self.consume_expr(base);
1a4d82fc 361 }
ea8adc8c 362
c295e0f8 363 hir::ExprKind::Yield(value, _) => {
e74abb32 364 self.consume_expr(value);
ea8adc8c 365 }
1a4d82fc
JJ
366 }
367 }
368
dfeec247 369 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
e74abb32 370 match stmt.kind {
064997fb
FG
371 hir::StmtKind::Local(hir::Local { pat, init: Some(expr), els, .. }) => {
372 self.walk_local(expr, pat, *els, |_| {})
9fa01778 373 }
1a4d82fc 374
94222f64
XL
375 hir::StmtKind::Local(_) => {}
376
9fa01778 377 hir::StmtKind::Item(_) => {
e1599b0c 378 // We don't visit nested items in this visitor,
9fa01778 379 // only the fn body we were given.
1a4d82fc
JJ
380 }
381
dfeec247 382 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
c295e0f8 383 self.consume_expr(expr);
1a4d82fc 384 }
1a4d82fc
JJ
385 }
386 }
387
064997fb
FG
388 fn maybe_read_scrutinee<'t>(
389 &mut self,
390 discr: &Expr<'_>,
391 discr_place: PlaceWithHirId<'tcx>,
392 pats: impl Iterator<Item = &'t hir::Pat<'t>>,
487cf647 393 ) -> Result<(), ()> {
064997fb
FG
394 // Matching should not always be considered a use of the place, hence
395 // discr does not necessarily need to be borrowed.
396 // We only want to borrow discr if the pattern contain something other
397 // than wildcards.
398 let ExprUseVisitor { ref mc, body_owner: _, delegate: _ } = *self;
399 let mut needs_to_be_read = false;
400 for pat in pats {
487cf647 401 mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
064997fb
FG
402 match &pat.kind {
403 PatKind::Binding(.., opt_sub_pat) => {
404 // If the opt_sub_pat is None, than the binding does not count as
405 // a wildcard for the purpose of borrowing discr.
406 if opt_sub_pat.is_none() {
407 needs_to_be_read = true;
408 }
409 }
410 PatKind::Path(qpath) => {
411 // A `Path` pattern is just a name like `Foo`. This is either a
412 // named constant or else it refers to an ADT variant
413
414 let res = self.mc.typeck_results.qpath_res(qpath, pat.hir_id);
415 match res {
416 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {
417 // Named constants have to be equated with the value
418 // being matched, so that's a read of the value being matched.
419 //
420 // FIXME: We don't actually reads for ZSTs.
421 needs_to_be_read = true;
422 }
423 _ => {
424 // Otherwise, this is a struct/enum variant, and so it's
425 // only a read if we need to read the discriminant.
426 needs_to_be_read |= is_multivariant_adt(place.place.ty());
427 }
428 }
429 }
430 PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => {
431 // For `Foo(..)`, `Foo { ... }` and `(...)` patterns, check if we are matching
432 // against a multivariant enum or struct. In that case, we have to read
433 // the discriminant. Otherwise this kind of pattern doesn't actually
434 // read anything (we'll get invoked for the `...`, which may indeed
435 // perform some reads).
436
437 let place_ty = place.place.ty();
438 needs_to_be_read |= is_multivariant_adt(place_ty);
439 }
440 PatKind::Lit(_) | PatKind::Range(..) => {
441 // If the PatKind is a Lit or a Range then we want
442 // to borrow discr.
443 needs_to_be_read = true;
444 }
445 PatKind::Or(_)
446 | PatKind::Box(_)
447 | PatKind::Slice(..)
448 | PatKind::Ref(..)
449 | PatKind::Wild => {
450 // If the PatKind is Or, Box, Slice or Ref, the decision is made later
451 // as these patterns contains subpatterns
452 // If the PatKind is Wild, the decision is made based on the other patterns being
453 // examined
454 }
455 }
487cf647 456 })?
064997fb
FG
457 }
458
459 if needs_to_be_read {
460 self.borrow_expr(discr, ty::ImmBorrow);
461 } else {
462 let closure_def_id = match discr_place.place.base {
463 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
464 _ => None,
465 };
466
467 self.delegate.fake_read(
468 &discr_place,
469 FakeReadCause::ForMatchedPlace(closure_def_id),
470 discr_place.hir_id,
471 );
472
473 // We always want to walk the discriminant. We want to make sure, for instance,
474 // that the discriminant has been initialized.
475 self.walk_expr(discr);
476 }
487cf647 477 Ok(())
064997fb
FG
478 }
479
480 fn walk_local<F>(
481 &mut self,
482 expr: &hir::Expr<'_>,
483 pat: &hir::Pat<'_>,
484 els: Option<&hir::Block<'_>>,
485 mut f: F,
486 ) where
94222f64
XL
487 F: FnMut(&mut Self),
488 {
c295e0f8
XL
489 self.walk_expr(expr);
490 let expr_place = return_if_err!(self.mc.cat_expr(expr));
94222f64 491 f(self);
064997fb 492 if let Some(els) = els {
f2b60f7d 493 // borrowing because we need to test the discriminant
487cf647
FG
494 return_if_err!(self.maybe_read_scrutinee(
495 expr,
496 expr_place.clone(),
497 from_ref(pat).iter()
498 ));
064997fb
FG
499 self.walk_block(els)
500 }
94222f64 501 self.walk_irrefutable_pat(&expr_place, &pat);
1a4d82fc
JJ
502 }
503
504 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
505 /// depending on its type.
dfeec247 506 fn walk_block(&mut self, blk: &hir::Block<'_>) {
532ac7d7 507 debug!("walk_block(blk.hir_id={})", blk.hir_id);
1a4d82fc 508
dfeec247 509 for stmt in blk.stmts {
92a42be0 510 self.walk_stmt(stmt);
1a4d82fc
JJ
511 }
512
85aaf69f 513 if let Some(ref tail_expr) = blk.expr {
c295e0f8 514 self.consume_expr(tail_expr);
1a4d82fc
JJ
515 }
516 }
517
a2a8927a 518 fn walk_struct_expr<'hir>(
dfeec247 519 &mut self,
6a06907d 520 fields: &[hir::ExprField<'_>],
dfeec247
XL
521 opt_with: &Option<&'hir hir::Expr<'_>>,
522 ) {
1a4d82fc 523 // Consume the expressions supplying values for each field.
85aaf69f 524 for field in fields {
c295e0f8 525 self.consume_expr(field.expr);
487cf647
FG
526
527 // The struct path probably didn't resolve
528 if self.mc.typeck_results.opt_field_index(field.hir_id).is_none() {
529 self.tcx().sess.delay_span_bug(field.span, "couldn't resolve index for field");
530 }
1a4d82fc
JJ
531 }
532
533 let with_expr = match *opt_with {
c295e0f8 534 Some(w) => &*w,
dfeec247
XL
535 None => {
536 return;
537 }
1a4d82fc
JJ
538 };
539
c295e0f8 540 let with_place = return_if_err!(self.mc.cat_expr(with_expr));
1a4d82fc
JJ
541
542 // Select just those fields of the `with`
543 // expression that will actually be used
1b1a35ee 544 match with_place.place.ty().kind() {
b7449926 545 ty::Adt(adt, substs) if adt.is_struct() => {
9e0c209e 546 // Consume those fields of the with expression that are needed.
83c7162d 547 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
487cf647
FG
548 let is_mentioned = fields
549 .iter()
550 .any(|f| self.mc.typeck_results.opt_field_index(f.hir_id) == Some(f_index));
83c7162d 551 if !is_mentioned {
60c5eb7d 552 let field_place = self.mc.cat_projection(
9e0c209e 553 &*with_expr,
60c5eb7d
XL
554 with_place.clone(),
555 with_field.ty(self.tcx(), substs),
3dfed10e 556 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
9e0c209e 557 );
29967ef6 558 self.delegate_consume(&field_place, field_place.hir_id);
9e0c209e 559 }
1a4d82fc 560 }
1a4d82fc 561 }
9e0c209e
SL
562 _ => {
563 // the base expression should always evaluate to a
564 // struct; however, when EUV is run during typeck, it
565 // may not. This will generate an error earlier in typeck,
566 // so we can just ignore it.
5e7ed085 567 if !self.tcx().sess.has_errors().is_some() {
dfeec247 568 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
9e0c209e 569 }
1a4d82fc 570 }
9e0c209e 571 }
1a4d82fc
JJ
572
573 // walk the with expression so that complex expressions
574 // are properly handled.
575 self.walk_expr(with_expr);
1a4d82fc
JJ
576 }
577
94222f64
XL
578 /// Invoke the appropriate delegate calls for anything that gets
579 /// consumed or borrowed as part of the automatic adjustment
580 /// process.
dfeec247 581 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
3dfed10e 582 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
f035d41b 583 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
7cac9316
XL
584 for adjustment in adjustments {
585 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
c30ab7b3 586 match adjustment.kind {
2b03887a
FG
587 adjustment::Adjust::NeverToAny
588 | adjustment::Adjust::Pointer(_)
589 | adjustment::Adjust::DynStar => {
9346a6ac
AL
590 // Creating a closure/fn-pointer or unsizing consumes
591 // the input and stores it into the resulting rvalue.
29967ef6 592 self.delegate_consume(&place_with_id, place_with_id.hir_id);
9346a6ac 593 }
c30ab7b3 594
7cac9316
XL
595 adjustment::Adjust::Deref(None) => {}
596
597 // Autoderefs for overloaded Deref calls in fact reference
598 // their receiver. That is, if we have `(*x)` where `x`
599 // is of type `Rc<T>`, then this in fact is equivalent to
600 // `x.deref()`. Since `deref()` is declared with `&self`,
601 // this is an autoref of `x`.
602 adjustment::Adjust::Deref(Some(ref deref)) => {
603 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
29967ef6 604 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
1a4d82fc 605 }
1a4d82fc 606
7cac9316 607 adjustment::Adjust::Borrow(ref autoref) => {
f035d41b 608 self.walk_autoref(expr, &place_with_id, autoref);
7cac9316 609 }
1a4d82fc 610 }
f035d41b 611 place_with_id =
c295e0f8 612 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, adjustment));
1a4d82fc
JJ
613 }
614 }
615
7cac9316 616 /// Walks the autoref `autoref` applied to the autoderef'd
60c5eb7d 617 /// `expr`. `base_place` is the mem-categorized form of `expr`
7cac9316 618 /// after all relevant autoderefs have occurred.
dfeec247
XL
619 fn walk_autoref(
620 &mut self,
621 expr: &hir::Expr<'_>,
3dfed10e 622 base_place: &PlaceWithHirId<'tcx>,
dfeec247
XL
623 autoref: &adjustment::AutoBorrow<'tcx>,
624 ) {
625 debug!(
626 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
627 expr.hir_id, base_place, autoref
628 );
1a4d82fc 629
9346a6ac 630 match *autoref {
e74abb32 631 adjustment::AutoBorrow::Ref(_, m) => {
29967ef6
XL
632 self.delegate.borrow(
633 base_place,
634 base_place.hir_id,
635 ty::BorrowKind::from_mutbl(m.into()),
636 );
1a4d82fc 637 }
9346a6ac 638
c30ab7b3 639 adjustment::AutoBorrow::RawPtr(m) => {
dfeec247 640 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
1a4d82fc 641
29967ef6 642 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
e74abb32 643 }
1a4d82fc 644 }
1a4d82fc
JJ
645 }
646
f035d41b 647 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
cdc7bbd5 648 let closure_def_id = match discr_place.place.base {
064997fb 649 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
cdc7bbd5
XL
650 _ => None,
651 };
652
6a06907d 653 self.delegate.fake_read(
923072b8 654 discr_place,
cdc7bbd5 655 FakeReadCause::ForMatchedPlace(closure_def_id),
6a06907d
XL
656 discr_place.hir_id,
657 );
923072b8 658 self.walk_pat(discr_place, arm.pat, arm.guard.is_some());
1a4d82fc 659
c295e0f8 660 if let Some(hir::Guard::If(e)) = arm.guard {
0bf4aa26 661 self.consume_expr(e)
923072b8
FG
662 } else if let Some(hir::Guard::IfLet(ref l)) = arm.guard {
663 self.consume_expr(l.init)
1a4d82fc
JJ
664 }
665
c295e0f8 666 self.consume_expr(arm.body);
1a4d82fc
JJ
667 }
668
9fa01778
XL
669 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
670 /// let binding, and *not* a match arm or nested pat.)
f035d41b 671 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
cdc7bbd5 672 let closure_def_id = match discr_place.place.base {
064997fb 673 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
cdc7bbd5
XL
674 _ => None,
675 };
676
6a06907d 677 self.delegate.fake_read(
923072b8 678 discr_place,
cdc7bbd5 679 FakeReadCause::ForLet(closure_def_id),
6a06907d
XL
680 discr_place.hir_id,
681 );
923072b8 682 self.walk_pat(discr_place, pat, false);
1a4d82fc
JJ
683 }
684
e74abb32 685 /// The core driver for walking a pattern
923072b8
FG
686 fn walk_pat(
687 &mut self,
688 discr_place: &PlaceWithHirId<'tcx>,
689 pat: &hir::Pat<'_>,
690 has_guard: bool,
691 ) {
692 debug!("walk_pat(discr_place={:?}, pat={:?}, has_guard={:?})", discr_place, pat, has_guard);
1a4d82fc 693
8faf50e0 694 let tcx = self.tcx();
fc512014 695 let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
60c5eb7d 696 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
e74abb32 697 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
064997fb 698 debug!("walk_pat: binding place={:?} pat={:?}", place, pat);
3dfed10e
XL
699 if let Some(bm) =
700 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
701 {
8faf50e0
XL
702 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
703
704 // pat_ty: the type of the binding being produced.
705 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
706 debug!("walk_pat: pat_ty={:?}", pat_ty);
707
48663c56 708 let def = Res::Local(canonical_id);
60c5eb7d 709 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
5e7ed085 710 delegate.bind(binding_place, binding_place.hir_id);
8faf50e0 711 }
5bcae85e 712
923072b8
FG
713 // Subtle: MIR desugaring introduces immutable borrows for each pattern
714 // binding when lowering pattern guards to ensure that the guard does not
715 // modify the scrutinee.
716 if has_guard {
717 delegate.borrow(place, discr_place.hir_id, ImmBorrow);
718 }
719
8faf50e0 720 // It is also a borrow or copy/move of the value being matched.
29967ef6
XL
721 // In a cases of pattern like `let pat = upvar`, don't use the span
722 // of the pattern, as this just looks confusing, instead use the span
723 // of the discriminant.
8faf50e0
XL
724 match bm {
725 ty::BindByReference(m) => {
e74abb32 726 let bk = ty::BorrowKind::from_mutbl(m);
29967ef6 727 delegate.borrow(place, discr_place.hir_id, bk);
8faf50e0
XL
728 }
729 ty::BindByValue(..) => {
8faf50e0 730 debug!("walk_pat binding consuming pat");
136023e0 731 delegate_consume(mc, *delegate, place, discr_place.hir_id);
c1a9b12d 732 }
1a4d82fc 733 }
1a4d82fc
JJ
734 }
735 }
736 }));
1a4d82fc
JJ
737 }
738
fc512014
XL
739 /// Handle the case where the current body contains a closure.
740 ///
741 /// When the current body being handled is a closure, then we must make sure that
742 /// - The parent closure only captures Places from the nested closure that are not local to it.
743 ///
94222f64 744 /// In the following example the closures `c` only captures `p.x` even though `incr`
fc512014
XL
745 /// is a capture of the nested closure
746 ///
04454e1e
FG
747 /// ```
748 /// struct P { x: i32 }
749 /// let mut p = P { x: 4 };
fc512014
XL
750 /// let c = || {
751 /// let incr = 10;
752 /// let nested = || p.x += incr;
04454e1e 753 /// };
fc512014
XL
754 /// ```
755 ///
756 /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
757 /// closure as the DefId.
487cf647 758 fn walk_captures(&mut self, closure_expr: &hir::Closure<'_>) {
a2a8927a 759 fn upvar_is_local_variable<'tcx>(
6a06907d 760 upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
5e7ed085 761 upvar_id: hir::HirId,
6a06907d
XL
762 body_owner_is_closure: bool,
763 ) -> bool {
5e7ed085 764 upvars.map(|upvars| !upvars.contains_key(&upvar_id)).unwrap_or(body_owner_is_closure)
6a06907d
XL
765 }
766
62682a34 767 debug!("walk_captures({:?})", closure_expr);
1a4d82fc 768
a2a8927a 769 let tcx = self.tcx();
487cf647 770 let closure_def_id = closure_expr.def_id;
a2a8927a 771 let upvars = tcx.upvars_mentioned(self.body_owner);
fc512014
XL
772
773 // For purposes of this function, generator and closures are equivalent.
5e7ed085
FG
774 let body_owner_is_closure =
775 matches!(tcx.hir().body_owner_kind(self.body_owner), hir::BodyOwnerKind::Closure,);
fc512014 776
6a06907d
XL
777 // If we have a nested closure, we want to include the fake reads present in the nested closure.
778 if let Some(fake_reads) = self.mc.typeck_results.closure_fake_reads.get(&closure_def_id) {
779 for (fake_read, cause, hir_id) in fake_reads.iter() {
780 match fake_read.base {
781 PlaceBase::Upvar(upvar_id) => {
782 if upvar_is_local_variable(
783 upvars,
5e7ed085 784 upvar_id.var_path.hir_id,
6a06907d
XL
785 body_owner_is_closure,
786 ) {
787 // The nested closure might be fake reading the current (enclosing) closure's local variables.
788 // The only places we want to fake read before creating the parent closure are the ones that
789 // are not local to it/ defined by it.
790 //
cdc7bbd5 791 // ```rust,ignore(cannot-test-this-because-pseudo-code)
6a06907d
XL
792 // let v1 = (0, 1);
793 // let c = || { // fake reads: v1
794 // let v2 = (0, 1);
795 // let e = || { // fake reads: v1, v2
796 // let (_, t1) = v1;
797 // let (_, t2) = v2;
798 // }
799 // }
800 // ```
801 // This check is performed when visiting the body of the outermost closure (`c`) and ensures
802 // that we don't add a fake read of v2 in c.
803 continue;
804 }
805 }
806 _ => {
807 bug!(
808 "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
809 fake_read.base
810 );
811 }
812 };
923072b8
FG
813 self.delegate.fake_read(
814 &PlaceWithHirId { place: fake_read.clone(), hir_id: *hir_id },
815 *cause,
816 *hir_id,
817 );
6a06907d
XL
818 }
819 }
820
fc512014
XL
821 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
822 {
823 for (var_hir_id, min_list) in min_captures.iter() {
824 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
825 // The nested closure might be capturing the current (enclosing) closure's local variables.
826 // We check if the root variable is ever mentioned within the enclosing closure, if not
827 // then for the current body (if it's a closure) these aren't captures, we will ignore them.
828 continue;
829 }
830 for captured_place in min_list {
831 let place = &captured_place.place;
832 let capture_info = captured_place.info;
833
834 let place_base = if body_owner_is_closure {
835 // Mark the place to be captured by the enclosing closure
836 PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
837 } else {
838 // If the body owner isn't a closure then the variable must
839 // be a local variable
840 PlaceBase::Local(*var_hir_id)
841 };
487cf647 842 let closure_hir_id = tcx.hir().local_def_id_to_hir_id(closure_def_id);
fc512014 843 let place_with_id = PlaceWithHirId::new(
487cf647
FG
844 capture_info
845 .path_expr_id
846 .unwrap_or(capture_info.capture_kind_expr_id.unwrap_or(closure_hir_id)),
fc512014
XL
847 place.base_ty,
848 place_base,
849 place.projections.clone(),
850 );
851
852 match capture_info.capture_kind {
5099ac24 853 ty::UpvarCapture::ByValue => {
136023e0 854 self.delegate_consume(&place_with_id, place_with_id.hir_id);
fc512014
XL
855 }
856 ty::UpvarCapture::ByRef(upvar_borrow) => {
857 self.delegate.borrow(
858 &place_with_id,
859 place_with_id.hir_id,
5099ac24 860 upvar_borrow,
fc512014
XL
861 );
862 }
85aaf69f 863 }
1a4d82fc
JJ
864 }
865 }
48663c56 866 }
1a4d82fc 867 }
1a4d82fc
JJ
868}
869
dc9dc135
XL
870fn copy_or_move<'a, 'tcx>(
871 mc: &mc::MemCategorizationContext<'a, 'tcx>,
f035d41b 872 place_with_id: &PlaceWithHirId<'tcx>,
dc9dc135 873) -> ConsumeMode {
f035d41b
XL
874 if !mc.type_is_copy_modulo_regions(
875 place_with_id.place.ty(),
876 mc.tcx().hir().span(place_with_id.hir_id),
877 ) {
136023e0 878 ConsumeMode::Move
f035d41b 879 } else {
136023e0
XL
880 ConsumeMode::Copy
881 }
882}
883
884// - If a place is used in a `ByValue` context then move it if it's not a `Copy` type.
94222f64 885// - If the place that is a `Copy` type consider it an `ImmBorrow`.
136023e0
XL
886fn delegate_consume<'a, 'tcx>(
887 mc: &mc::MemCategorizationContext<'a, 'tcx>,
888 delegate: &mut (dyn Delegate<'tcx> + 'a),
889 place_with_id: &PlaceWithHirId<'tcx>,
890 diag_expr_id: hir::HirId,
891) {
892 debug!("delegate_consume(place_with_id={:?})", place_with_id);
893
c295e0f8 894 let mode = copy_or_move(mc, place_with_id);
136023e0
XL
895
896 match mode {
897 ConsumeMode::Move => delegate.consume(place_with_id, diag_expr_id),
5e7ed085 898 ConsumeMode::Copy => delegate.copy(place_with_id, diag_expr_id),
f035d41b 899 }
1a4d82fc 900}
94222f64 901
a2a8927a 902fn is_multivariant_adt(ty: Ty<'_>) -> bool {
94222f64
XL
903 if let ty::Adt(def, _) = ty.kind() {
904 // Note that if a non-exhaustive SingleVariant is defined in another crate, we need
905 // to assume that more cases will be added to the variant in the future. This mean
906 // that we should handle non-exhaustive SingleVariant the same way we would handle
907 // a MultiVariant.
908 // If the variant is not local it must be defined in another crate.
909 let is_non_exhaustive = match def.adt_kind() {
910 AdtKind::Struct | AdtKind::Union => {
911 def.non_enum_variant().is_field_list_non_exhaustive()
912 }
913 AdtKind::Enum => def.is_variant_list_non_exhaustive(),
914 };
5e7ed085 915 def.variants().len() > 1 || (!def.did().is_local() && is_non_exhaustive)
94222f64
XL
916 } else {
917 false
918 }
919}