1use std::cell::{Ref, RefCell};
6use std::ops::Deref;
7use std::slice::from_ref;
8
9use hir::Expr;
10use hir::def::DefKind;
11use hir::pat_util::EnumerateAndAdjustIterator as _;
12use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
13use rustc_data_structures::fx::FxIndexMap;
14use rustc_hir::def::{CtorOf, Res};
15use rustc_hir::def_id::LocalDefId;
16use rustc_hir::{self as hir, HirId, PatExpr, PatExprKind, PatKind};
17use rustc_lint::LateContext;
18use rustc_middle::hir::place::ProjectionKind;
19pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
21use rustc_middle::mir::FakeReadCause;
22use rustc_middle::ty::{
23 self, AdtKind, BorrowKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _, adjustment,
24};
25use rustc_middle::{bug, span_bug};
26use rustc_span::{ErrorGuaranteed, Span};
27use rustc_trait_selection::infer::InferCtxtExt;
28use tracing::{debug, trace};
29
30use crate::fn_ctxt::FnCtxt;
31
32pub trait Delegate<'tcx> {
35 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId);
49
50 fn borrow(
53 &mut self,
54 place_with_id: &PlaceWithHirId<'tcx>,
55 diag_expr_id: HirId,
56 bk: ty::BorrowKind,
57 );
58
59 fn copy(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
62 self.borrow(place_with_id, diag_expr_id, ty::BorrowKind::Immutable)
65 }
66
67 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId);
70
71 fn bind(&mut self, binding_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
75 self.mutate(binding_place, diag_expr_id)
78 }
79
80 fn fake_read(
82 &mut self,
83 place_with_id: &PlaceWithHirId<'tcx>,
84 cause: FakeReadCause,
85 diag_expr_id: HirId,
86 );
87}
88
89impl<'tcx, D: Delegate<'tcx>> Delegate<'tcx> for &mut D {
90 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
91 (**self).consume(place_with_id, diag_expr_id)
92 }
93
94 fn borrow(
95 &mut self,
96 place_with_id: &PlaceWithHirId<'tcx>,
97 diag_expr_id: HirId,
98 bk: ty::BorrowKind,
99 ) {
100 (**self).borrow(place_with_id, diag_expr_id, bk)
101 }
102
103 fn copy(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
104 (**self).copy(place_with_id, diag_expr_id)
105 }
106
107 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
108 (**self).mutate(assignee_place, diag_expr_id)
109 }
110
111 fn bind(&mut self, binding_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
112 (**self).bind(binding_place, diag_expr_id)
113 }
114
115 fn fake_read(
116 &mut self,
117 place_with_id: &PlaceWithHirId<'tcx>,
118 cause: FakeReadCause,
119 diag_expr_id: HirId,
120 ) {
121 (**self).fake_read(place_with_id, cause, diag_expr_id)
122 }
123}
124
125pub trait TypeInformationCtxt<'tcx> {
126 type TypeckResults<'a>: Deref<Target = ty::TypeckResults<'tcx>>
127 where
128 Self: 'a;
129
130 type Error;
131
132 fn typeck_results(&self) -> Self::TypeckResults<'_>;
133
134 fn resolve_vars_if_possible<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T;
135
136 fn try_structurally_resolve_type(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
137
138 fn report_error(&self, span: Span, msg: impl ToString) -> Self::Error;
139
140 fn error_reported_in_ty(&self, ty: Ty<'tcx>) -> Result<(), Self::Error>;
141
142 fn tainted_by_errors(&self) -> Result<(), Self::Error>;
143
144 fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>) -> bool;
145
146 fn body_owner_def_id(&self) -> LocalDefId;
147
148 fn tcx(&self) -> TyCtxt<'tcx>;
149}
150
151impl<'tcx> TypeInformationCtxt<'tcx> for &FnCtxt<'_, 'tcx> {
152 type TypeckResults<'a>
153 = Ref<'a, ty::TypeckResults<'tcx>>
154 where
155 Self: 'a;
156
157 type Error = ErrorGuaranteed;
158
159 fn typeck_results(&self) -> Self::TypeckResults<'_> {
160 self.typeck_results.borrow()
161 }
162
163 fn resolve_vars_if_possible<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
164 self.infcx.resolve_vars_if_possible(t)
165 }
166
167 fn try_structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
168 (**self).try_structurally_resolve_type(sp, ty)
169 }
170
171 fn report_error(&self, span: Span, msg: impl ToString) -> Self::Error {
172 self.dcx().span_delayed_bug(span, msg.to_string())
173 }
174
175 fn error_reported_in_ty(&self, ty: Ty<'tcx>) -> Result<(), Self::Error> {
176 ty.error_reported()
177 }
178
179 fn tainted_by_errors(&self) -> Result<(), ErrorGuaranteed> {
180 if let Some(guar) = self.infcx.tainted_by_errors() { Err(guar) } else { Ok(()) }
181 }
182
183 fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
184 self.infcx.type_is_copy_modulo_regions(self.param_env, ty)
185 }
186
187 fn body_owner_def_id(&self) -> LocalDefId {
188 self.body_id
189 }
190
191 fn tcx(&self) -> TyCtxt<'tcx> {
192 self.tcx
193 }
194}
195
196impl<'tcx> TypeInformationCtxt<'tcx> for (&LateContext<'tcx>, LocalDefId) {
197 type TypeckResults<'a>
198 = &'tcx ty::TypeckResults<'tcx>
199 where
200 Self: 'a;
201
202 type Error = !;
203
204 fn typeck_results(&self) -> Self::TypeckResults<'_> {
205 self.0.maybe_typeck_results().expect("expected typeck results")
206 }
207
208 fn try_structurally_resolve_type(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
209 ty
211 }
212
213 fn resolve_vars_if_possible<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
214 t
215 }
216
217 fn report_error(&self, span: Span, msg: impl ToString) -> ! {
218 span_bug!(span, "{}", msg.to_string())
219 }
220
221 fn error_reported_in_ty(&self, _ty: Ty<'tcx>) -> Result<(), !> {
222 Ok(())
223 }
224
225 fn tainted_by_errors(&self) -> Result<(), !> {
226 Ok(())
227 }
228
229 fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>) -> bool {
230 self.0.type_is_copy_modulo_regions(ty)
231 }
232
233 fn body_owner_def_id(&self) -> LocalDefId {
234 self.1
235 }
236
237 fn tcx(&self) -> TyCtxt<'tcx> {
238 self.0.tcx
239 }
240}
241
242pub struct ExprUseVisitor<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> {
246 cx: Cx,
247 delegate: RefCell<D>,
250 upvars: Option<&'tcx FxIndexMap<HirId, hir::Upvar>>,
251}
252
253impl<'a, 'tcx, D: Delegate<'tcx>> ExprUseVisitor<'tcx, (&'a LateContext<'tcx>, LocalDefId), D> {
254 pub fn for_clippy(cx: &'a LateContext<'tcx>, body_def_id: LocalDefId, delegate: D) -> Self {
255 Self::new((cx, body_def_id), delegate)
256 }
257}
258
259impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx, Cx, D> {
260 pub(crate) fn new(cx: Cx, delegate: D) -> Self {
266 ExprUseVisitor {
267 delegate: RefCell::new(delegate),
268 upvars: cx.tcx().upvars_mentioned(cx.body_owner_def_id()),
269 cx,
270 }
271 }
272
273 pub fn consume_body(&self, body: &hir::Body<'_>) -> Result<(), Cx::Error> {
274 for param in body.params {
275 let param_ty = self.pat_ty_adjusted(param.pat)?;
276 debug!("consume_body: param_ty = {:?}", param_ty);
277
278 let param_place = self.cat_rvalue(param.hir_id, param_ty);
279
280 self.walk_irrefutable_pat(¶m_place, param.pat)?;
281 }
282
283 self.consume_expr(body.value)?;
284
285 Ok(())
286 }
287
288 fn consume_or_copy(&self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
289 debug!("delegate_consume(place_with_id={:?})", place_with_id);
290
291 if self.cx.type_is_copy_modulo_regions(place_with_id.place.ty()) {
292 self.delegate.borrow_mut().copy(place_with_id, diag_expr_id);
293 } else {
294 self.delegate.borrow_mut().consume(place_with_id, diag_expr_id);
295 }
296 }
297
298 fn consume_exprs(&self, exprs: &[hir::Expr<'_>]) -> Result<(), Cx::Error> {
299 for expr in exprs {
300 self.consume_expr(expr)?;
301 }
302
303 Ok(())
304 }
305
306 pub fn consume_expr(&self, expr: &hir::Expr<'_>) -> Result<(), Cx::Error> {
308 debug!("consume_expr(expr={:?})", expr);
309
310 let place_with_id = self.cat_expr(expr)?;
311 self.consume_or_copy(&place_with_id, place_with_id.hir_id);
312 self.walk_expr(expr)?;
313 Ok(())
314 }
315
316 fn mutate_expr(&self, expr: &hir::Expr<'_>) -> Result<(), Cx::Error> {
317 let place_with_id = self.cat_expr(expr)?;
318 self.delegate.borrow_mut().mutate(&place_with_id, place_with_id.hir_id);
319 self.walk_expr(expr)?;
320 Ok(())
321 }
322
323 fn borrow_expr(&self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) -> Result<(), Cx::Error> {
324 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
325
326 let place_with_id = self.cat_expr(expr)?;
327 self.delegate.borrow_mut().borrow(&place_with_id, place_with_id.hir_id, bk);
328 self.walk_expr(expr)
329 }
330
331 pub fn walk_expr(&self, expr: &hir::Expr<'_>) -> Result<(), Cx::Error> {
332 debug!("walk_expr(expr={:?})", expr);
333
334 self.walk_adjustment(expr)?;
335
336 match expr.kind {
337 hir::ExprKind::Path(_) => {}
338
339 hir::ExprKind::Type(subexpr, _) => {
340 self.walk_expr(subexpr)?;
341 }
342
343 hir::ExprKind::UnsafeBinderCast(_, subexpr, _) => {
344 self.walk_expr(subexpr)?;
345 }
346
347 hir::ExprKind::Unary(hir::UnOp::Deref, base) => {
348 self.walk_expr(base)?;
350 }
351
352 hir::ExprKind::Field(base, _) => {
353 self.walk_expr(base)?;
355 }
356
357 hir::ExprKind::Index(lhs, rhs, _) => {
358 self.walk_expr(lhs)?;
360 self.consume_expr(rhs)?;
361 }
362
363 hir::ExprKind::Call(callee, args) => {
364 self.consume_expr(callee)?;
366 self.consume_exprs(args)?;
367 }
368
369 hir::ExprKind::MethodCall(.., receiver, args, _) => {
370 self.consume_expr(receiver)?;
372 self.consume_exprs(args)?;
373 }
374
375 hir::ExprKind::Struct(_, fields, ref opt_with) => {
376 self.walk_struct_expr(fields, opt_with)?;
377 }
378
379 hir::ExprKind::Tup(exprs) => {
380 self.consume_exprs(exprs)?;
381 }
382
383 hir::ExprKind::If(cond_expr, then_expr, ref opt_else_expr) => {
384 self.consume_expr(cond_expr)?;
385 self.consume_expr(then_expr)?;
386 if let Some(else_expr) = *opt_else_expr {
387 self.consume_expr(else_expr)?;
388 }
389 }
390
391 hir::ExprKind::Let(hir::LetExpr { pat, init, .. }) => {
392 self.walk_local(init, pat, None, || self.borrow_expr(init, BorrowKind::Immutable))?;
393 }
394
395 hir::ExprKind::Match(discr, arms, _) => {
396 let discr_place = self.cat_expr(discr)?;
397 self.maybe_read_scrutinee(
398 discr,
399 discr_place.clone(),
400 arms.iter().map(|arm| arm.pat),
401 )?;
402
403 for arm in arms {
405 self.walk_arm(&discr_place, arm)?;
406 }
407 }
408
409 hir::ExprKind::Array(exprs) => {
410 self.consume_exprs(exprs)?;
411 }
412
413 hir::ExprKind::AddrOf(_, m, base) => {
414 let bk = ty::BorrowKind::from_mutbl(m);
418 self.borrow_expr(base, bk)?;
419 }
420
421 hir::ExprKind::InlineAsm(asm) => {
422 for (op, _op_sp) in asm.operands {
423 match op {
424 hir::InlineAsmOperand::In { expr, .. } => {
425 self.consume_expr(expr)?;
426 }
427 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
428 | hir::InlineAsmOperand::InOut { expr, .. } => {
429 self.mutate_expr(expr)?;
430 }
431 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
432 self.consume_expr(in_expr)?;
433 if let Some(out_expr) = out_expr {
434 self.mutate_expr(out_expr)?;
435 }
436 }
437 hir::InlineAsmOperand::Out { expr: None, .. }
438 | hir::InlineAsmOperand::Const { .. }
439 | hir::InlineAsmOperand::SymFn { .. }
440 | hir::InlineAsmOperand::SymStatic { .. } => {}
441 hir::InlineAsmOperand::Label { block } => {
442 self.walk_block(block)?;
443 }
444 }
445 }
446 }
447
448 hir::ExprKind::Continue(..)
449 | hir::ExprKind::Lit(..)
450 | hir::ExprKind::ConstBlock(..)
451 | hir::ExprKind::OffsetOf(..)
452 | hir::ExprKind::Err(_) => {}
453
454 hir::ExprKind::Loop(blk, ..) => {
455 self.walk_block(blk)?;
456 }
457
458 hir::ExprKind::Unary(_, lhs) => {
459 self.consume_expr(lhs)?;
460 }
461
462 hir::ExprKind::Binary(_, lhs, rhs) => {
463 self.consume_expr(lhs)?;
464 self.consume_expr(rhs)?;
465 }
466
467 hir::ExprKind::Block(blk, _) => {
468 self.walk_block(blk)?;
469 }
470
471 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
472 if let Some(expr) = *opt_expr {
473 self.consume_expr(expr)?;
474 }
475 }
476
477 hir::ExprKind::Become(call) => {
478 self.consume_expr(call)?;
479 }
480
481 hir::ExprKind::Assign(lhs, rhs, _) => {
482 self.mutate_expr(lhs)?;
483 self.consume_expr(rhs)?;
484 }
485
486 hir::ExprKind::Cast(base, _) => {
487 self.consume_expr(base)?;
488 }
489
490 hir::ExprKind::DropTemps(expr) => {
491 self.consume_expr(expr)?;
492 }
493
494 hir::ExprKind::AssignOp(_, lhs, rhs) => {
495 if self.cx.typeck_results().is_method_call(expr) {
496 self.consume_expr(lhs)?;
497 } else {
498 self.mutate_expr(lhs)?;
499 }
500 self.consume_expr(rhs)?;
501 }
502
503 hir::ExprKind::Repeat(base, _) => {
504 self.consume_expr(base)?;
505 }
506
507 hir::ExprKind::Closure(closure) => {
508 self.walk_captures(closure)?;
509 }
510
511 hir::ExprKind::Yield(value, _) => {
512 self.consume_expr(value)?;
513 }
514 }
515
516 Ok(())
517 }
518
519 fn walk_stmt(&self, stmt: &hir::Stmt<'_>) -> Result<(), Cx::Error> {
520 match stmt.kind {
521 hir::StmtKind::Let(hir::LetStmt { pat, init: Some(expr), els, .. }) => {
522 self.walk_local(expr, pat, *els, || Ok(()))?;
523 }
524
525 hir::StmtKind::Let(_) => {}
526
527 hir::StmtKind::Item(_) => {
528 }
531
532 hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr) => {
533 self.consume_expr(expr)?;
534 }
535 }
536
537 Ok(())
538 }
539
540 fn maybe_read_scrutinee<'t>(
541 &self,
542 discr: &Expr<'_>,
543 discr_place: PlaceWithHirId<'tcx>,
544 pats: impl Iterator<Item = &'t hir::Pat<'t>>,
545 ) -> Result<(), Cx::Error> {
546 let mut needs_to_be_read = false;
551 for pat in pats {
552 self.cat_pattern(discr_place.clone(), pat, &mut |place, pat| {
553 match &pat.kind {
554 PatKind::Binding(.., opt_sub_pat) => {
555 if opt_sub_pat.is_none() {
558 needs_to_be_read = true;
559 }
560 }
561 PatKind::Never => {
562 needs_to_be_read = true;
565 }
566 PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => {
567 let res = self.cx.typeck_results().qpath_res(qpath, *hir_id);
571 match res {
572 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {
573 needs_to_be_read = true;
578 }
579 _ => {
580 needs_to_be_read |=
583 self.is_multivariant_adt(place.place.ty(), *span);
584 }
585 }
586 }
587 PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => {
588 let place_ty = place.place.ty();
595 needs_to_be_read |= self.is_multivariant_adt(place_ty, pat.span);
596 }
597 PatKind::Expr(_) | PatKind::Range(..) => {
598 needs_to_be_read = true;
601 }
602 PatKind::Slice(lhs, wild, rhs) => {
603 if matches!((lhs, wild, rhs), (&[], Some(_), &[]))
605 || place.place.ty().peel_refs().is_array()
608 {
609 } else {
610 needs_to_be_read = true;
611 }
612 }
613 PatKind::Or(_)
614 | PatKind::Box(_)
615 | PatKind::Deref(_)
616 | PatKind::Ref(..)
617 | PatKind::Guard(..)
618 | PatKind::Wild
619 | PatKind::Err(_) => {
620 }
625 }
626
627 Ok(())
628 })?
629 }
630
631 if needs_to_be_read {
632 self.borrow_expr(discr, BorrowKind::Immutable)?;
633 } else {
634 let closure_def_id = match discr_place.place.base {
635 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
636 _ => None,
637 };
638
639 self.delegate.borrow_mut().fake_read(
640 &discr_place,
641 FakeReadCause::ForMatchedPlace(closure_def_id),
642 discr_place.hir_id,
643 );
644
645 self.walk_expr(discr)?;
648 }
649 Ok(())
650 }
651
652 fn walk_local<F>(
653 &self,
654 expr: &hir::Expr<'_>,
655 pat: &hir::Pat<'_>,
656 els: Option<&hir::Block<'_>>,
657 mut f: F,
658 ) -> Result<(), Cx::Error>
659 where
660 F: FnMut() -> Result<(), Cx::Error>,
661 {
662 self.walk_expr(expr)?;
663 let expr_place = self.cat_expr(expr)?;
664 f()?;
665 if let Some(els) = els {
666 self.maybe_read_scrutinee(expr, expr_place.clone(), from_ref(pat).iter())?;
668 self.walk_block(els)?;
669 }
670 self.walk_irrefutable_pat(&expr_place, pat)?;
671 Ok(())
672 }
673
674 fn walk_block(&self, blk: &hir::Block<'_>) -> Result<(), Cx::Error> {
677 debug!("walk_block(blk.hir_id={})", blk.hir_id);
678
679 for stmt in blk.stmts {
680 self.walk_stmt(stmt)?;
681 }
682
683 if let Some(tail_expr) = blk.expr {
684 self.consume_expr(tail_expr)?;
685 }
686
687 Ok(())
688 }
689
690 fn walk_struct_expr<'hir>(
691 &self,
692 fields: &[hir::ExprField<'_>],
693 opt_with: &hir::StructTailExpr<'hir>,
694 ) -> Result<(), Cx::Error> {
695 for field in fields {
697 self.consume_expr(field.expr)?;
698
699 if self.cx.typeck_results().opt_field_index(field.hir_id).is_none() {
701 self.cx
702 .tcx()
703 .dcx()
704 .span_delayed_bug(field.span, "couldn't resolve index for field");
705 }
706 }
707
708 let with_expr = match *opt_with {
709 hir::StructTailExpr::Base(w) => &*w,
710 hir::StructTailExpr::DefaultFields(_) | hir::StructTailExpr::None => {
711 return Ok(());
712 }
713 };
714
715 let with_place = self.cat_expr(with_expr)?;
716
717 match self.cx.try_structurally_resolve_type(with_expr.span, with_place.place.ty()).kind() {
720 ty::Adt(adt, args) if adt.is_struct() => {
721 for (f_index, with_field) in adt.non_enum_variant().fields.iter_enumerated() {
723 let is_mentioned = fields.iter().any(|f| {
724 self.cx.typeck_results().opt_field_index(f.hir_id) == Some(f_index)
725 });
726 if !is_mentioned {
727 let field_place = self.cat_projection(
728 with_expr.hir_id,
729 with_place.clone(),
730 with_field.ty(self.cx.tcx(), args),
731 ProjectionKind::Field(f_index, FIRST_VARIANT),
732 );
733 self.consume_or_copy(&field_place, field_place.hir_id);
734 }
735 }
736 }
737 _ => {
738 if self.cx.tainted_by_errors().is_ok() {
743 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
744 }
745 }
746 }
747
748 self.walk_expr(with_expr)?;
751
752 Ok(())
753 }
754
755 fn walk_adjustment(&self, expr: &hir::Expr<'_>) -> Result<(), Cx::Error> {
759 let typeck_results = self.cx.typeck_results();
760 let adjustments = typeck_results.expr_adjustments(expr);
761 let mut place_with_id = self.cat_expr_unadjusted(expr)?;
762 for adjustment in adjustments {
763 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
764 match adjustment.kind {
765 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
766 self.consume_or_copy(&place_with_id, place_with_id.hir_id);
769 }
770
771 adjustment::Adjust::Deref(None) => {}
772
773 adjustment::Adjust::Deref(Some(ref deref)) => {
779 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
780 self.delegate.borrow_mut().borrow(&place_with_id, place_with_id.hir_id, bk);
781 }
782
783 adjustment::Adjust::Borrow(ref autoref) => {
784 self.walk_autoref(expr, &place_with_id, autoref);
785 }
786
787 adjustment::Adjust::ReborrowPin(mutbl) => {
788 let bk = match mutbl {
791 ty::Mutability::Not => ty::BorrowKind::Immutable,
792 ty::Mutability::Mut => ty::BorrowKind::Mutable,
793 };
794 self.delegate.borrow_mut().borrow(&place_with_id, place_with_id.hir_id, bk);
795 }
796 }
797 place_with_id = self.cat_expr_adjusted(expr, place_with_id, adjustment)?;
798 }
799
800 Ok(())
801 }
802
803 fn walk_autoref(
807 &self,
808 expr: &hir::Expr<'_>,
809 base_place: &PlaceWithHirId<'tcx>,
810 autoref: &adjustment::AutoBorrow,
811 ) {
812 debug!(
813 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
814 expr.hir_id, base_place, autoref
815 );
816
817 match *autoref {
818 adjustment::AutoBorrow::Ref(m) => {
819 self.delegate.borrow_mut().borrow(
820 base_place,
821 base_place.hir_id,
822 ty::BorrowKind::from_mutbl(m.into()),
823 );
824 }
825
826 adjustment::AutoBorrow::RawPtr(m) => {
827 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
828
829 self.delegate.borrow_mut().borrow(
830 base_place,
831 base_place.hir_id,
832 ty::BorrowKind::from_mutbl(m),
833 );
834 }
835 }
836 }
837
838 fn walk_arm(
839 &self,
840 discr_place: &PlaceWithHirId<'tcx>,
841 arm: &hir::Arm<'_>,
842 ) -> Result<(), Cx::Error> {
843 let closure_def_id = match discr_place.place.base {
844 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
845 _ => None,
846 };
847
848 self.delegate.borrow_mut().fake_read(
849 discr_place,
850 FakeReadCause::ForMatchedPlace(closure_def_id),
851 discr_place.hir_id,
852 );
853 self.walk_pat(discr_place, arm.pat, arm.guard.is_some())?;
854
855 if let Some(ref e) = arm.guard {
856 self.consume_expr(e)?;
857 }
858
859 self.consume_expr(arm.body)?;
860 Ok(())
861 }
862
863 fn walk_irrefutable_pat(
866 &self,
867 discr_place: &PlaceWithHirId<'tcx>,
868 pat: &hir::Pat<'_>,
869 ) -> Result<(), Cx::Error> {
870 let closure_def_id = match discr_place.place.base {
871 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
872 _ => None,
873 };
874
875 self.delegate.borrow_mut().fake_read(
876 discr_place,
877 FakeReadCause::ForLet(closure_def_id),
878 discr_place.hir_id,
879 );
880 self.walk_pat(discr_place, pat, false)?;
881 Ok(())
882 }
883
884 fn walk_pat(
886 &self,
887 discr_place: &PlaceWithHirId<'tcx>,
888 pat: &hir::Pat<'_>,
889 has_guard: bool,
890 ) -> Result<(), Cx::Error> {
891 debug!("walk_pat(discr_place={:?}, pat={:?}, has_guard={:?})", discr_place, pat, has_guard);
892
893 let tcx = self.cx.tcx();
894 self.cat_pattern(discr_place.clone(), pat, &mut |place, pat| {
895 match pat.kind {
896 PatKind::Binding(_, canonical_id, ..) => {
897 debug!("walk_pat: binding place={:?} pat={:?}", place, pat);
898 if let Some(bm) = self
899 .cx
900 .typeck_results()
901 .extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
902 {
903 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
904
905 let pat_ty = self.node_ty(pat.hir_id)?;
907 debug!("walk_pat: pat_ty={:?}", pat_ty);
908
909 let def = Res::Local(canonical_id);
910 if let Ok(ref binding_place) =
911 self.cat_res(pat.hir_id, pat.span, pat_ty, def)
912 {
913 self.delegate.borrow_mut().bind(binding_place, binding_place.hir_id);
914 }
915
916 if has_guard {
920 self.delegate.borrow_mut().borrow(
921 place,
922 discr_place.hir_id,
923 BorrowKind::Immutable,
924 );
925 }
926
927 match bm.0 {
932 hir::ByRef::Yes(m) => {
933 let bk = ty::BorrowKind::from_mutbl(m);
934 self.delegate.borrow_mut().borrow(place, discr_place.hir_id, bk);
935 }
936 hir::ByRef::No => {
937 debug!("walk_pat binding consuming pat");
938 self.consume_or_copy(place, discr_place.hir_id);
939 }
940 }
941 }
942 }
943 PatKind::Deref(subpattern) => {
944 let mutable = self.cx.typeck_results().pat_has_ref_mut_binding(subpattern);
949 let mutability =
950 if mutable { hir::Mutability::Mut } else { hir::Mutability::Not };
951 let bk = ty::BorrowKind::from_mutbl(mutability);
952 self.delegate.borrow_mut().borrow(place, discr_place.hir_id, bk);
953 }
954 PatKind::Never => {
955 self.delegate.borrow_mut().borrow(
958 place,
959 discr_place.hir_id,
960 BorrowKind::Immutable,
961 );
962 }
963 _ => {}
964 }
965
966 Ok(())
967 })
968 }
969
970 fn walk_captures(&self, closure_expr: &hir::Closure<'_>) -> Result<(), Cx::Error> {
990 fn upvar_is_local_variable(
991 upvars: Option<&FxIndexMap<HirId, hir::Upvar>>,
992 upvar_id: HirId,
993 body_owner_is_closure: bool,
994 ) -> bool {
995 upvars.map(|upvars| !upvars.contains_key(&upvar_id)).unwrap_or(body_owner_is_closure)
996 }
997
998 debug!("walk_captures({:?})", closure_expr);
999
1000 let tcx = self.cx.tcx();
1001 let closure_def_id = closure_expr.def_id;
1002 let body_owner_is_closure = matches!(
1004 tcx.hir().body_owner_kind(self.cx.body_owner_def_id()),
1005 hir::BodyOwnerKind::Closure
1006 );
1007
1008 if let Some(fake_reads) = self.cx.typeck_results().closure_fake_reads.get(&closure_def_id) {
1010 for (fake_read, cause, hir_id) in fake_reads.iter() {
1011 match fake_read.base {
1012 PlaceBase::Upvar(upvar_id) => {
1013 if upvar_is_local_variable(
1014 self.upvars,
1015 upvar_id.var_path.hir_id,
1016 body_owner_is_closure,
1017 ) {
1018 continue;
1035 }
1036 }
1037 _ => {
1038 bug!(
1039 "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
1040 fake_read.base
1041 );
1042 }
1043 };
1044 self.delegate.borrow_mut().fake_read(
1045 &PlaceWithHirId { place: fake_read.clone(), hir_id: *hir_id },
1046 *cause,
1047 *hir_id,
1048 );
1049 }
1050 }
1051
1052 if let Some(min_captures) =
1053 self.cx.typeck_results().closure_min_captures.get(&closure_def_id)
1054 {
1055 for (var_hir_id, min_list) in min_captures.iter() {
1056 if self
1057 .upvars
1058 .map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id))
1059 {
1060 continue;
1064 }
1065 for captured_place in min_list {
1066 let place = &captured_place.place;
1067 let capture_info = captured_place.info;
1068
1069 let place_base = if body_owner_is_closure {
1070 PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.cx.body_owner_def_id()))
1072 } else {
1073 PlaceBase::Local(*var_hir_id)
1076 };
1077 let closure_hir_id = tcx.local_def_id_to_hir_id(closure_def_id);
1078 let place_with_id = PlaceWithHirId::new(
1079 capture_info
1080 .path_expr_id
1081 .unwrap_or(capture_info.capture_kind_expr_id.unwrap_or(closure_hir_id)),
1082 place.base_ty,
1083 place_base,
1084 place.projections.clone(),
1085 );
1086
1087 match capture_info.capture_kind {
1088 ty::UpvarCapture::ByValue => {
1089 self.consume_or_copy(&place_with_id, place_with_id.hir_id);
1090 }
1091 ty::UpvarCapture::ByRef(upvar_borrow) => {
1092 self.delegate.borrow_mut().borrow(
1093 &place_with_id,
1094 place_with_id.hir_id,
1095 upvar_borrow,
1096 );
1097 }
1098 }
1099 }
1100 }
1101 }
1102
1103 Ok(())
1104 }
1105}
1106
1107impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx, Cx, D> {
1155 fn resolve_type_vars_or_error(
1156 &self,
1157 id: HirId,
1158 ty: Option<Ty<'tcx>>,
1159 ) -> Result<Ty<'tcx>, Cx::Error> {
1160 match ty {
1161 Some(ty) => {
1162 let ty = self.cx.resolve_vars_if_possible(ty);
1163 self.cx.error_reported_in_ty(ty)?;
1164 if ty.is_ty_var() {
1165 debug!("resolve_type_vars_or_error: infer var from {:?}", ty);
1166 Err(self
1167 .cx
1168 .report_error(self.cx.tcx().hir().span(id), "encountered type variable"))
1169 } else {
1170 Ok(ty)
1171 }
1172 }
1173 None => {
1174 self.cx.tainted_by_errors()?;
1176 bug!(
1177 "no type for node {} in mem_categorization",
1178 self.cx.tcx().hir().node_to_string(id)
1179 );
1180 }
1181 }
1182 }
1183
1184 fn node_ty(&self, hir_id: HirId) -> Result<Ty<'tcx>, Cx::Error> {
1185 self.resolve_type_vars_or_error(hir_id, self.cx.typeck_results().node_type_opt(hir_id))
1186 }
1187
1188 fn expr_ty(&self, expr: &hir::Expr<'_>) -> Result<Ty<'tcx>, Cx::Error> {
1189 self.resolve_type_vars_or_error(expr.hir_id, self.cx.typeck_results().expr_ty_opt(expr))
1190 }
1191
1192 fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Result<Ty<'tcx>, Cx::Error> {
1193 self.resolve_type_vars_or_error(
1194 expr.hir_id,
1195 self.cx.typeck_results().expr_ty_adjusted_opt(expr),
1196 )
1197 }
1198
1199 fn pat_ty_adjusted(&self, pat: &hir::Pat<'_>) -> Result<Ty<'tcx>, Cx::Error> {
1210 if let Some(vec) = self.cx.typeck_results().pat_adjustments().get(pat.hir_id) {
1215 if let Some(first_ty) = vec.first() {
1216 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
1217 return Ok(*first_ty);
1218 }
1219 } else if let PatKind::Ref(subpat, _) = pat.kind
1220 && self.cx.typeck_results().skipped_ref_pats().contains(pat.hir_id)
1221 {
1222 return self.pat_ty_adjusted(subpat);
1223 }
1224
1225 self.pat_ty_unadjusted(pat)
1226 }
1227
1228 fn pat_ty_unadjusted(&self, pat: &hir::Pat<'_>) -> Result<Ty<'tcx>, Cx::Error> {
1230 let base_ty = self.node_ty(pat.hir_id)?;
1231 trace!(?base_ty);
1232
1233 match pat.kind {
1236 PatKind::Binding(..) => {
1237 let bm = *self
1238 .cx
1239 .typeck_results()
1240 .pat_binding_modes()
1241 .get(pat.hir_id)
1242 .expect("missing binding mode");
1243
1244 if matches!(bm.0, hir::ByRef::Yes(_)) {
1245 match self
1249 .cx
1250 .try_structurally_resolve_type(pat.span, base_ty)
1251 .builtin_deref(false)
1252 {
1253 Some(ty) => Ok(ty),
1254 None => {
1255 debug!("By-ref binding of non-derefable type");
1256 Err(self
1257 .cx
1258 .report_error(pat.span, "by-ref binding of non-derefable type"))
1259 }
1260 }
1261 } else {
1262 Ok(base_ty)
1263 }
1264 }
1265 _ => Ok(base_ty),
1266 }
1267 }
1268
1269 fn cat_expr(&self, expr: &hir::Expr<'_>) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1270 self.cat_expr_(expr, self.cx.typeck_results().expr_adjustments(expr))
1271 }
1272
1273 fn cat_expr_(
1276 &self,
1277 expr: &hir::Expr<'_>,
1278 adjustments: &[adjustment::Adjustment<'tcx>],
1279 ) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1280 match adjustments.split_last() {
1281 None => self.cat_expr_unadjusted(expr),
1282 Some((adjustment, previous)) => {
1283 self.cat_expr_adjusted_with(expr, || self.cat_expr_(expr, previous), adjustment)
1284 }
1285 }
1286 }
1287
1288 fn cat_expr_adjusted(
1289 &self,
1290 expr: &hir::Expr<'_>,
1291 previous: PlaceWithHirId<'tcx>,
1292 adjustment: &adjustment::Adjustment<'tcx>,
1293 ) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1294 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
1295 }
1296
1297 fn cat_expr_adjusted_with<F>(
1298 &self,
1299 expr: &hir::Expr<'_>,
1300 previous: F,
1301 adjustment: &adjustment::Adjustment<'tcx>,
1302 ) -> Result<PlaceWithHirId<'tcx>, Cx::Error>
1303 where
1304 F: FnOnce() -> Result<PlaceWithHirId<'tcx>, Cx::Error>,
1305 {
1306 let target = self.cx.resolve_vars_if_possible(adjustment.target);
1307 match adjustment.kind {
1308 adjustment::Adjust::Deref(overloaded) => {
1309 let base = if let Some(deref) = overloaded {
1311 let ref_ty = Ty::new_ref(
1312 self.cx.tcx(),
1313 self.cx.tcx().lifetimes.re_erased,
1314 target,
1315 deref.mutbl,
1316 );
1317 self.cat_rvalue(expr.hir_id, ref_ty)
1318 } else {
1319 previous()?
1320 };
1321 self.cat_deref(expr.hir_id, base)
1322 }
1323
1324 adjustment::Adjust::NeverToAny
1325 | adjustment::Adjust::Pointer(_)
1326 | adjustment::Adjust::Borrow(_)
1327 | adjustment::Adjust::ReborrowPin(..) => {
1328 Ok(self.cat_rvalue(expr.hir_id, target))
1330 }
1331 }
1332 }
1333
1334 fn cat_expr_unadjusted(&self, expr: &hir::Expr<'_>) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1335 let expr_ty = self.expr_ty(expr)?;
1336 match expr.kind {
1337 hir::ExprKind::Unary(hir::UnOp::Deref, e_base) => {
1338 if self.cx.typeck_results().is_method_call(expr) {
1339 self.cat_overloaded_place(expr, e_base)
1340 } else {
1341 let base = self.cat_expr(e_base)?;
1342 self.cat_deref(expr.hir_id, base)
1343 }
1344 }
1345
1346 hir::ExprKind::Field(base, _) => {
1347 let base = self.cat_expr(base)?;
1348 debug!(?base);
1349
1350 let field_idx = self
1351 .cx
1352 .typeck_results()
1353 .field_indices()
1354 .get(expr.hir_id)
1355 .cloned()
1356 .expect("Field index not found");
1357
1358 Ok(self.cat_projection(
1359 expr.hir_id,
1360 base,
1361 expr_ty,
1362 ProjectionKind::Field(field_idx, FIRST_VARIANT),
1363 ))
1364 }
1365
1366 hir::ExprKind::Index(base, _, _) => {
1367 if self.cx.typeck_results().is_method_call(expr) {
1368 self.cat_overloaded_place(expr, base)
1374 } else {
1375 let base = self.cat_expr(base)?;
1376 Ok(self.cat_projection(expr.hir_id, base, expr_ty, ProjectionKind::Index))
1377 }
1378 }
1379
1380 hir::ExprKind::Path(ref qpath) => {
1381 let res = self.cx.typeck_results().qpath_res(qpath, expr.hir_id);
1382 self.cat_res(expr.hir_id, expr.span, expr_ty, res)
1383 }
1384
1385 hir::ExprKind::Type(e, _) => self.cat_expr(e),
1388 hir::ExprKind::UnsafeBinderCast(_, e, _) => self.cat_expr(e),
1389
1390 hir::ExprKind::AddrOf(..)
1391 | hir::ExprKind::Call(..)
1392 | hir::ExprKind::Assign(..)
1393 | hir::ExprKind::AssignOp(..)
1394 | hir::ExprKind::Closure { .. }
1395 | hir::ExprKind::Ret(..)
1396 | hir::ExprKind::Become(..)
1397 | hir::ExprKind::Unary(..)
1398 | hir::ExprKind::Yield(..)
1399 | hir::ExprKind::MethodCall(..)
1400 | hir::ExprKind::Cast(..)
1401 | hir::ExprKind::DropTemps(..)
1402 | hir::ExprKind::Array(..)
1403 | hir::ExprKind::If(..)
1404 | hir::ExprKind::Tup(..)
1405 | hir::ExprKind::Binary(..)
1406 | hir::ExprKind::Block(..)
1407 | hir::ExprKind::Let(..)
1408 | hir::ExprKind::Loop(..)
1409 | hir::ExprKind::Match(..)
1410 | hir::ExprKind::Lit(..)
1411 | hir::ExprKind::ConstBlock(..)
1412 | hir::ExprKind::Break(..)
1413 | hir::ExprKind::Continue(..)
1414 | hir::ExprKind::Struct(..)
1415 | hir::ExprKind::Repeat(..)
1416 | hir::ExprKind::InlineAsm(..)
1417 | hir::ExprKind::OffsetOf(..)
1418 | hir::ExprKind::Err(_) => Ok(self.cat_rvalue(expr.hir_id, expr_ty)),
1419 }
1420 }
1421
1422 fn cat_res(
1423 &self,
1424 hir_id: HirId,
1425 span: Span,
1426 expr_ty: Ty<'tcx>,
1427 res: Res,
1428 ) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1429 match res {
1430 Res::Def(
1431 DefKind::Ctor(..)
1432 | DefKind::Const
1433 | DefKind::ConstParam
1434 | DefKind::AssocConst
1435 | DefKind::Fn
1436 | DefKind::AssocFn,
1437 _,
1438 )
1439 | Res::SelfCtor(..) => Ok(self.cat_rvalue(hir_id, expr_ty)),
1440
1441 Res::Def(DefKind::Static { .. }, _) => {
1442 Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::StaticItem, Vec::new()))
1443 }
1444
1445 Res::Local(var_id) => {
1446 if self.upvars.is_some_and(|upvars| upvars.contains_key(&var_id)) {
1447 self.cat_upvar(hir_id, var_id)
1448 } else {
1449 Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Local(var_id), Vec::new()))
1450 }
1451 }
1452
1453 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def),
1454 }
1455 }
1456
1457 fn cat_upvar(&self, hir_id: HirId, var_id: HirId) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1463 let closure_expr_def_id = self.cx.body_owner_def_id();
1464
1465 let upvar_id = ty::UpvarId {
1466 var_path: ty::UpvarPath { hir_id: var_id },
1467 closure_expr_id: closure_expr_def_id,
1468 };
1469 let var_ty = self.node_ty(var_id)?;
1470
1471 Ok(PlaceWithHirId::new(hir_id, var_ty, PlaceBase::Upvar(upvar_id), Vec::new()))
1472 }
1473
1474 fn cat_rvalue(&self, hir_id: HirId, expr_ty: Ty<'tcx>) -> PlaceWithHirId<'tcx> {
1475 PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Rvalue, Vec::new())
1476 }
1477
1478 fn cat_projection(
1479 &self,
1480 node: HirId,
1481 base_place: PlaceWithHirId<'tcx>,
1482 ty: Ty<'tcx>,
1483 kind: ProjectionKind,
1484 ) -> PlaceWithHirId<'tcx> {
1485 let place_ty = base_place.place.ty();
1486 let mut projections = base_place.place.projections;
1487
1488 let node_ty = self.cx.typeck_results().node_type(node);
1489 if node_ty != place_ty
1493 && self
1494 .cx
1495 .try_structurally_resolve_type(
1496 self.cx.tcx().hir().span(base_place.hir_id),
1497 place_ty,
1498 )
1499 .is_impl_trait()
1500 {
1501 projections.push(Projection { kind: ProjectionKind::OpaqueCast, ty: node_ty });
1502 }
1503 projections.push(Projection { kind, ty });
1504 PlaceWithHirId::new(node, base_place.place.base_ty, base_place.place.base, projections)
1505 }
1506
1507 fn cat_overloaded_place(
1508 &self,
1509 expr: &hir::Expr<'_>,
1510 base: &hir::Expr<'_>,
1511 ) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1512 let place_ty = self.expr_ty(expr)?;
1516 let base_ty = self.expr_ty_adjusted(base)?;
1517
1518 let ty::Ref(region, _, mutbl) =
1519 *self.cx.try_structurally_resolve_type(base.span, base_ty).kind()
1520 else {
1521 span_bug!(expr.span, "cat_overloaded_place: base is not a reference");
1522 };
1523 let ref_ty = Ty::new_ref(self.cx.tcx(), region, place_ty, mutbl);
1524
1525 let base = self.cat_rvalue(expr.hir_id, ref_ty);
1526 self.cat_deref(expr.hir_id, base)
1527 }
1528
1529 fn cat_deref(
1530 &self,
1531 node: HirId,
1532 base_place: PlaceWithHirId<'tcx>,
1533 ) -> Result<PlaceWithHirId<'tcx>, Cx::Error> {
1534 let base_curr_ty = base_place.place.ty();
1535 let deref_ty = match self
1536 .cx
1537 .try_structurally_resolve_type(
1538 self.cx.tcx().hir().span(base_place.hir_id),
1539 base_curr_ty,
1540 )
1541 .builtin_deref(true)
1542 {
1543 Some(ty) => ty,
1544 None => {
1545 debug!("explicit deref of non-derefable type: {:?}", base_curr_ty);
1546 return Err(self.cx.report_error(
1547 self.cx.tcx().hir().span(node),
1548 "explicit deref of non-derefable type",
1549 ));
1550 }
1551 };
1552 let mut projections = base_place.place.projections;
1553 projections.push(Projection { kind: ProjectionKind::Deref, ty: deref_ty });
1554
1555 Ok(PlaceWithHirId::new(node, base_place.place.base_ty, base_place.place.base, projections))
1556 }
1557
1558 fn variant_index_for_adt(
1561 &self,
1562 qpath: &hir::QPath<'_>,
1563 pat_hir_id: HirId,
1564 span: Span,
1565 ) -> Result<VariantIdx, Cx::Error> {
1566 let res = self.cx.typeck_results().qpath_res(qpath, pat_hir_id);
1567 let ty = self.cx.typeck_results().node_type(pat_hir_id);
1568 let ty::Adt(adt_def, _) = self.cx.try_structurally_resolve_type(span, ty).kind() else {
1569 return Err(self
1570 .cx
1571 .report_error(span, "struct or tuple struct pattern not applied to an ADT"));
1572 };
1573
1574 match res {
1575 Res::Def(DefKind::Variant, variant_id) => Ok(adt_def.variant_index_with_id(variant_id)),
1576 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
1577 Ok(adt_def.variant_index_with_ctor_id(variant_ctor_id))
1578 }
1579 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
1580 | Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
1581 | Res::SelfCtor(..)
1582 | Res::SelfTyParam { .. }
1583 | Res::SelfTyAlias { .. } => {
1584 Ok(FIRST_VARIANT)
1586 }
1587 _ => bug!("expected ADT path, found={:?}", res),
1588 }
1589 }
1590
1591 fn total_fields_in_adt_variant(
1594 &self,
1595 pat_hir_id: HirId,
1596 variant_index: VariantIdx,
1597 span: Span,
1598 ) -> Result<usize, Cx::Error> {
1599 let ty = self.cx.typeck_results().node_type(pat_hir_id);
1600 match self.cx.try_structurally_resolve_type(span, ty).kind() {
1601 ty::Adt(adt_def, _) => Ok(adt_def.variant(variant_index).fields.len()),
1602 _ => {
1603 self.cx
1604 .tcx()
1605 .dcx()
1606 .span_bug(span, "struct or tuple struct pattern not applied to an ADT");
1607 }
1608 }
1609 }
1610
1611 fn total_fields_in_tuple(&self, pat_hir_id: HirId, span: Span) -> Result<usize, Cx::Error> {
1614 let ty = self.cx.typeck_results().node_type(pat_hir_id);
1615 match self.cx.try_structurally_resolve_type(span, ty).kind() {
1616 ty::Tuple(args) => Ok(args.len()),
1617 _ => Err(self.cx.report_error(span, "tuple pattern not applied to a tuple")),
1618 }
1619 }
1620
1621 fn cat_pattern<F>(
1628 &self,
1629 mut place_with_id: PlaceWithHirId<'tcx>,
1630 pat: &hir::Pat<'_>,
1631 op: &mut F,
1632 ) -> Result<(), Cx::Error>
1633 where
1634 F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>) -> Result<(), Cx::Error>,
1635 {
1636 for _ in
1669 0..self.cx.typeck_results().pat_adjustments().get(pat.hir_id).map_or(0, |v| v.len())
1670 {
1671 debug!("applying adjustment to place_with_id={:?}", place_with_id);
1672 place_with_id = self.cat_deref(pat.hir_id, place_with_id)?;
1673 }
1674 let place_with_id = place_with_id; debug!("applied adjustment derefs to get place_with_id={:?}", place_with_id);
1676
1677 op(&place_with_id, pat)?;
1687
1688 match pat.kind {
1689 PatKind::Tuple(subpats, dots_pos) => {
1690 let total_fields = self.total_fields_in_tuple(pat.hir_id, pat.span)?;
1692
1693 for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
1694 let subpat_ty = self.pat_ty_adjusted(subpat)?;
1695 let projection_kind =
1696 ProjectionKind::Field(FieldIdx::from_usize(i), FIRST_VARIANT);
1697 let sub_place = self.cat_projection(
1698 pat.hir_id,
1699 place_with_id.clone(),
1700 subpat_ty,
1701 projection_kind,
1702 );
1703 self.cat_pattern(sub_place, subpat, op)?;
1704 }
1705 }
1706
1707 PatKind::TupleStruct(ref qpath, subpats, dots_pos) => {
1708 let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?;
1710 let total_fields =
1711 self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat.span)?;
1712
1713 for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
1714 let subpat_ty = self.pat_ty_adjusted(subpat)?;
1715 let projection_kind =
1716 ProjectionKind::Field(FieldIdx::from_usize(i), variant_index);
1717 let sub_place = self.cat_projection(
1718 pat.hir_id,
1719 place_with_id.clone(),
1720 subpat_ty,
1721 projection_kind,
1722 );
1723 self.cat_pattern(sub_place, subpat, op)?;
1724 }
1725 }
1726
1727 PatKind::Struct(ref qpath, field_pats, _) => {
1728 let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?;
1731
1732 for fp in field_pats {
1733 let field_ty = self.pat_ty_adjusted(fp.pat)?;
1734 let field_index = self
1735 .cx
1736 .typeck_results()
1737 .field_indices()
1738 .get(fp.hir_id)
1739 .cloned()
1740 .expect("no index for a field");
1741
1742 let field_place = self.cat_projection(
1743 pat.hir_id,
1744 place_with_id.clone(),
1745 field_ty,
1746 ProjectionKind::Field(field_index, variant_index),
1747 );
1748 self.cat_pattern(field_place, fp.pat, op)?;
1749 }
1750 }
1751
1752 PatKind::Or(pats) => {
1753 for pat in pats {
1754 self.cat_pattern(place_with_id.clone(), pat, op)?;
1755 }
1756 }
1757
1758 PatKind::Binding(.., Some(subpat)) | PatKind::Guard(subpat, _) => {
1759 self.cat_pattern(place_with_id, subpat, op)?;
1760 }
1761
1762 PatKind::Ref(subpat, _)
1763 if self.cx.typeck_results().skipped_ref_pats().contains(pat.hir_id) =>
1764 {
1765 self.cat_pattern(place_with_id, subpat, op)?;
1766 }
1767
1768 PatKind::Box(subpat) | PatKind::Ref(subpat, _) => {
1769 let subplace = self.cat_deref(pat.hir_id, place_with_id)?;
1773 self.cat_pattern(subplace, subpat, op)?;
1774 }
1775 PatKind::Deref(subpat) => {
1776 let mutable = self.cx.typeck_results().pat_has_ref_mut_binding(subpat);
1777 let mutability = if mutable { hir::Mutability::Mut } else { hir::Mutability::Not };
1778 let re_erased = self.cx.tcx().lifetimes.re_erased;
1779 let ty = self.pat_ty_adjusted(subpat)?;
1780 let ty = Ty::new_ref(self.cx.tcx(), re_erased, ty, mutability);
1781 let place = self.cat_rvalue(pat.hir_id, ty);
1783 self.cat_pattern(place, subpat, op)?;
1784 }
1785
1786 PatKind::Slice(before, ref slice, after) => {
1787 let Some(element_ty) = self
1788 .cx
1789 .try_structurally_resolve_type(pat.span, place_with_id.place.ty())
1790 .builtin_index()
1791 else {
1792 debug!("explicit index of non-indexable type {:?}", place_with_id);
1793 return Err(self
1794 .cx
1795 .report_error(pat.span, "explicit index of non-indexable type"));
1796 };
1797 let elt_place = self.cat_projection(
1798 pat.hir_id,
1799 place_with_id.clone(),
1800 element_ty,
1801 ProjectionKind::Index,
1802 );
1803 for before_pat in before {
1804 self.cat_pattern(elt_place.clone(), before_pat, op)?;
1805 }
1806 if let Some(slice_pat) = *slice {
1807 let slice_pat_ty = self.pat_ty_adjusted(slice_pat)?;
1808 let slice_place = self.cat_projection(
1809 pat.hir_id,
1810 place_with_id,
1811 slice_pat_ty,
1812 ProjectionKind::Subslice,
1813 );
1814 self.cat_pattern(slice_place, slice_pat, op)?;
1815 }
1816 for after_pat in after {
1817 self.cat_pattern(elt_place.clone(), after_pat, op)?;
1818 }
1819 }
1820
1821 PatKind::Binding(.., None)
1822 | PatKind::Expr(..)
1823 | PatKind::Range(..)
1824 | PatKind::Never
1825 | PatKind::Wild
1826 | PatKind::Err(_) => {
1827 }
1829 }
1830
1831 Ok(())
1832 }
1833
1834 fn is_multivariant_adt(&self, ty: Ty<'tcx>, span: Span) -> bool {
1835 if let ty::Adt(def, _) = self.cx.try_structurally_resolve_type(span, ty).kind() {
1836 let is_non_exhaustive = match def.adt_kind() {
1842 AdtKind::Struct | AdtKind::Union => {
1843 def.non_enum_variant().is_field_list_non_exhaustive()
1844 }
1845 AdtKind::Enum => def.is_variant_list_non_exhaustive(),
1846 };
1847 def.variants().len() > 1 || (!def.did().is_local() && is_non_exhaustive)
1848 } else {
1849 false
1850 }
1851 }
1852}