rustc_hir_typeck/
expr_use_visitor.rs

1//! A different sort of visitor for walking fn bodies. Unlike the
2//! normal visitor, which just walks the entire body in one shot, the
3//! `ExprUseVisitor` determines how expressions are being used.
4
5use 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;
19// Export these here so that Clippy can use them.
20pub 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
32/// This trait defines the callbacks you can expect to receive when
33/// employing the ExprUseVisitor.
34pub trait Delegate<'tcx> {
35    /// The value found at `place` is moved, depending
36    /// on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
37    ///
38    /// Use of a `Copy` type in a ByValue context is considered a use
39    /// by `ImmBorrow` and `borrow` is called instead. This is because
40    /// a shared borrow is the "minimum access" that would be needed
41    /// to perform a copy.
42    ///
43    ///
44    /// The parameter `diag_expr_id` indicates the HIR id that ought to be used for
45    /// diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
46    /// id will be the id of the expression `expr` but the place itself will have
47    /// the id of the binding in the pattern `pat`.
48    fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId);
49
50    /// The value found at `place` is being borrowed with kind `bk`.
51    /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
52    fn borrow(
53        &mut self,
54        place_with_id: &PlaceWithHirId<'tcx>,
55        diag_expr_id: HirId,
56        bk: ty::BorrowKind,
57    );
58
59    /// The value found at `place` is being copied.
60    /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
61    fn copy(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
62        // In most cases, copying data from `x` is equivalent to doing `*&x`, so by default
63        // we treat a copy of `x` as a borrow of `x`.
64        self.borrow(place_with_id, diag_expr_id, ty::BorrowKind::Immutable)
65    }
66
67    /// The path at `assignee_place` is being assigned to.
68    /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
69    fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId);
70
71    /// The path at `binding_place` is a binding that is being initialized.
72    ///
73    /// This covers cases such as `let x = 42;`
74    fn bind(&mut self, binding_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
75        // Bindings can normally be treated as a regular assignment, so by default we
76        // forward this to the mutate callback.
77        self.mutate(binding_place, diag_expr_id)
78    }
79
80    /// The `place` should be a fake read because of specified `cause`.
81    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        // FIXME: Maybe need to normalize here.
210        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
242/// The ExprUseVisitor type
243///
244/// This is the code that actually walks the tree.
245pub struct ExprUseVisitor<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> {
246    cx: Cx,
247    /// We use a `RefCell` here so that delegates can mutate themselves, but we can
248    /// still have calls to our own helper functions.
249    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    /// Creates the ExprUseVisitor, configuring it with the various options provided:
261    ///
262    /// - `delegate` -- who receives the callbacks
263    /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
264    /// - `typeck_results` --- typeck results for the code being analyzed
265    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(&param_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    // FIXME: It's suspicious that this is public; clippy should probably use `walk_expr`.
307    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                // *base
349                self.walk_expr(base)?;
350            }
351
352            hir::ExprKind::Field(base, _) => {
353                // base.f
354                self.walk_expr(base)?;
355            }
356
357            hir::ExprKind::Index(lhs, rhs, _) => {
358                // lhs[rhs]
359                self.walk_expr(lhs)?;
360                self.consume_expr(rhs)?;
361            }
362
363            hir::ExprKind::Call(callee, args) => {
364                // callee(args)
365                self.consume_expr(callee)?;
366                self.consume_exprs(args)?;
367            }
368
369            hir::ExprKind::MethodCall(.., receiver, args, _) => {
370                // callee.m(args)
371                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                // treatment of the discriminant is handled while walking the arms.
404                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                // &base
415                // make sure that the thing we are pointing out stays valid
416                // for the lifetime `scope_r` of the resulting ptr:
417                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                // We don't visit nested items in this visitor,
529                // only the fn body we were given.
530            }
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        // Matching should not always be considered a use of the place, hence
547        // discr does not necessarily need to be borrowed.
548        // We only want to borrow discr if the pattern contain something other
549        // than wildcards.
550        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 the opt_sub_pat is None, then the binding does not count as
556                        // a wildcard for the purpose of borrowing discr.
557                        if opt_sub_pat.is_none() {
558                            needs_to_be_read = true;
559                        }
560                    }
561                    PatKind::Never => {
562                        // A never pattern reads the value.
563                        // FIXME(never_patterns): does this do what I expect?
564                        needs_to_be_read = true;
565                    }
566                    PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => {
567                        // A `Path` pattern is just a name like `Foo`. This is either a
568                        // named constant or else it refers to an ADT variant
569
570                        let res = self.cx.typeck_results().qpath_res(qpath, *hir_id);
571                        match res {
572                            Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {
573                                // Named constants have to be equated with the value
574                                // being matched, so that's a read of the value being matched.
575                                //
576                                // FIXME: We don't actually reads for ZSTs.
577                                needs_to_be_read = true;
578                            }
579                            _ => {
580                                // Otherwise, this is a struct/enum variant, and so it's
581                                // only a read if we need to read the discriminant.
582                                needs_to_be_read |=
583                                    self.is_multivariant_adt(place.place.ty(), *span);
584                            }
585                        }
586                    }
587                    PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => {
588                        // For `Foo(..)`, `Foo { ... }` and `(...)` patterns, check if we are matching
589                        // against a multivariant enum or struct. In that case, we have to read
590                        // the discriminant. Otherwise this kind of pattern doesn't actually
591                        // read anything (we'll get invoked for the `...`, which may indeed
592                        // perform some reads).
593
594                        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                        // If the PatKind is a Lit or a Range then we want
599                        // to borrow discr.
600                        needs_to_be_read = true;
601                    }
602                    PatKind::Slice(lhs, wild, rhs) => {
603                        // We don't need to test the length if the pattern is `[..]`
604                        if matches!((lhs, wild, rhs), (&[], Some(_), &[]))
605                            // Arrays have a statically known size, so
606                            // there is no need to read their length
607                            || 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                        // If the PatKind is Or, Box, or Ref, the decision is made later
621                        // as these patterns contains subpatterns
622                        // If the PatKind is Wild or Err, the decision is made based on the other patterns
623                        // being examined
624                    }
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            // We always want to walk the discriminant. We want to make sure, for instance,
646            // that the discriminant has been initialized.
647            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            // borrowing because we need to test the discriminant
667            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    /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
675    /// depending on its type.
676    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        // Consume the expressions supplying values for each field.
696        for field in fields {
697            self.consume_expr(field.expr)?;
698
699            // The struct path probably didn't resolve
700            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        // Select just those fields of the `with`
718        // expression that will actually be used
719        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                // Consume those fields of the with expression that are needed.
722                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                // the base expression should always evaluate to a
739                // struct; however, when EUV is run during typeck, it
740                // may not. This will generate an error earlier in typeck,
741                // so we can just ignore it.
742                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        // walk the with expression so that complex expressions
749        // are properly handled.
750        self.walk_expr(with_expr)?;
751
752        Ok(())
753    }
754
755    /// Invoke the appropriate delegate calls for anything that gets
756    /// consumed or borrowed as part of the automatic adjustment
757    /// process.
758    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                    // Creating a closure/fn-pointer or unsizing consumes
767                    // the input and stores it into the resulting rvalue.
768                    self.consume_or_copy(&place_with_id, place_with_id.hir_id);
769                }
770
771                adjustment::Adjust::Deref(None) => {}
772
773                // Autoderefs for overloaded Deref calls in fact reference
774                // their receiver. That is, if we have `(*x)` where `x`
775                // is of type `Rc<T>`, then this in fact is equivalent to
776                // `x.deref()`. Since `deref()` is declared with `&self`,
777                // this is an autoref of `x`.
778                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                    // Reborrowing a Pin is like a combinations of a deref and a borrow, so we do
789                    // both.
790                    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    /// Walks the autoref `autoref` applied to the autoderef'd
804    /// `expr`. `base_place` is the mem-categorized form of `expr`
805    /// after all relevant autoderefs have occurred.
806    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    /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
864    /// let binding, and *not* a match arm or nested pat.)
865    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    /// The core driver for walking a pattern
885    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                        // pat_ty: the type of the binding being produced.
906                        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                        // Subtle: MIR desugaring introduces immutable borrows for each pattern
917                        // binding when lowering pattern guards to ensure that the guard does not
918                        // modify the scrutinee.
919                        if has_guard {
920                            self.delegate.borrow_mut().borrow(
921                                place,
922                                discr_place.hir_id,
923                                BorrowKind::Immutable,
924                            );
925                        }
926
927                        // It is also a borrow or copy/move of the value being matched.
928                        // In a cases of pattern like `let pat = upvar`, don't use the span
929                        // of the pattern, as this just looks confusing, instead use the span
930                        // of the discriminant.
931                        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                    // A deref pattern is a bit special: the binding mode of its inner bindings
945                    // determines whether to borrow *at the level of the deref pattern* rather than
946                    // borrowing the bound place (since that inner place is inside the temporary that
947                    // stores the result of calling `deref()`/`deref_mut()` so can't be captured).
948                    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                    // A `!` pattern always counts as an immutable read of the discriminant,
956                    // even in an irrefutable pattern.
957                    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    /// Handle the case where the current body contains a closure.
971    ///
972    /// When the current body being handled is a closure, then we must make sure that
973    /// - The parent closure only captures Places from the nested closure that are not local to it.
974    ///
975    /// In the following example the closures `c` only captures `p.x` even though `incr`
976    /// is a capture of the nested closure
977    ///
978    /// ```
979    /// struct P { x: i32 }
980    /// let mut p = P { x: 4 };
981    /// let c = || {
982    ///    let incr = 10;
983    ///    let nested = || p.x += incr;
984    /// };
985    /// ```
986    ///
987    /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
988    /// closure as the DefId.
989    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        // For purposes of this function, coroutine and closures are equivalent.
1003        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 we have a nested closure, we want to include the fake reads present in the nested closure.
1009        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                            // The nested closure might be fake reading the current (enclosing) closure's local variables.
1019                            // The only places we want to fake read before creating the parent closure are the ones that
1020                            // are not local to it/ defined by it.
1021                            //
1022                            // ```rust,ignore(cannot-test-this-because-pseudo-code)
1023                            // let v1 = (0, 1);
1024                            // let c = || { // fake reads: v1
1025                            //    let v2 = (0, 1);
1026                            //    let e = || { // fake reads: v1, v2
1027                            //       let (_, t1) = v1;
1028                            //       let (_, t2) = v2;
1029                            //    }
1030                            // }
1031                            // ```
1032                            // This check is performed when visiting the body of the outermost closure (`c`) and ensures
1033                            // that we don't add a fake read of v2 in c.
1034                            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                    // The nested closure might be capturing the current (enclosing) closure's local variables.
1061                    // We check if the root variable is ever mentioned within the enclosing closure, if not
1062                    // then for the current body (if it's a closure) these aren't captures, we will ignore them.
1063                    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                        // Mark the place to be captured by the enclosing closure
1071                        PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.cx.body_owner_def_id()))
1072                    } else {
1073                        // If the body owner isn't a closure then the variable must
1074                        // be a local variable
1075                        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
1107/// The job of the categorization methods is to analyze an expression to
1108/// determine what kind of memory is used in evaluating it (for example,
1109/// where dereferences occur and what kind of pointer is dereferenced;
1110/// whether the memory is mutable, etc.).
1111///
1112/// Categorization effectively transforms all of our expressions into
1113/// expressions of the following forms (the actual enum has many more
1114/// possibilities, naturally, but they are all variants of these base
1115/// forms):
1116/// ```ignore (not-rust)
1117/// E = rvalue    // some computed rvalue
1118///   | x         // address of a local variable or argument
1119///   | *E        // deref of a ptr
1120///   | E.comp    // access to an interior component
1121/// ```
1122/// Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
1123/// address where the result is to be found. If Expr is a place, then this
1124/// is the address of the place. If `Expr` is an rvalue, this is the address of
1125/// some temporary spot in memory where the result is stored.
1126///
1127/// Now, `cat_expr()` classifies the expression `Expr` and the address `A = ToAddr(Expr)`
1128/// as follows:
1129///
1130/// - `cat`: what kind of expression was this? This is a subset of the
1131///   full expression forms which only includes those that we care about
1132///   for the purpose of the analysis.
1133/// - `mutbl`: mutability of the address `A`.
1134/// - `ty`: the type of data found at the address `A`.
1135///
1136/// The resulting categorization tree differs somewhat from the expressions
1137/// themselves. For example, auto-derefs are explicit. Also, an index `a[b]` is
1138/// decomposed into two operations: a dereference to reach the array data and
1139/// then an index to jump forward to the relevant item.
1140///
1141/// ## By-reference upvars
1142///
1143/// One part of the codegen which may be non-obvious is that we translate
1144/// closure upvars into the dereference of a borrowed pointer; this more closely
1145/// resembles the runtime codegen. So, for example, if we had:
1146///
1147///     let mut x = 3;
1148///     let y = 5;
1149///     let inc = || x += y;
1150///
1151/// Then when we categorize `x` (*within* the closure) we would yield a
1152/// result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
1153/// tied to `x`. The type of `x'` will be a borrowed pointer.
1154impl<'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                // FIXME: We shouldn't be relying on the infcx being tainted.
1175                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    /// Returns the type of value that this pattern matches against.
1200    /// Some non-obvious cases:
1201    ///
1202    /// - a `ref x` binding matches against a value of type `T` and gives
1203    ///   `x` the type `&T`; we return `T`.
1204    /// - a pattern with implicit derefs (thanks to default binding
1205    ///   modes #42640) may look like `Some(x)` but in fact have
1206    ///   implicit deref patterns attached (e.g., it is really
1207    ///   `&Some(x)`). In that case, we return the "outermost" type
1208    ///   (e.g., `&Option<T>`).
1209    fn pat_ty_adjusted(&self, pat: &hir::Pat<'_>) -> Result<Ty<'tcx>, Cx::Error> {
1210        // Check for implicit `&` types wrapping the pattern; note
1211        // that these are never attached to binding patterns, so
1212        // actually this is somewhat "disjoint" from the code below
1213        // that aims to account for `ref x`.
1214        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    /// Like `TypeckResults::pat_ty`, but ignores implicit `&` patterns.
1229    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        // This code detects whether we are looking at a `ref x`,
1234        // and if so, figures out what the type *being borrowed* is.
1235        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                    // a bind-by-ref means that the base_ty will be the type of the ident itself,
1246                    // but what we want here is the type of the underlying value being borrowed.
1247                    // So peel off one-level, turning the &T into T.
1248                    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    /// This recursion helper avoids going through *too many*
1274    /// adjustments, since *only* non-overloaded deref recurses.
1275    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                // Equivalent to *expr or something similar.
1310                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                // Result is an rvalue.
1329                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                    // If this is an index implemented by a method call, then it
1369                    // will include an implicit deref of the result.
1370                    // The call to index() returns a `&T` value, which
1371                    // is an rvalue. That is what we will be
1372                    // dereferencing.
1373                    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            // both type ascription and unsafe binder casts don't affect
1386            // the place-ness of the subexpression.
1387            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    /// Categorize an upvar.
1458    ///
1459    /// Note: the actual upvar access contains invisible derefs of closure
1460    /// environment and upvar reference as appropriate. Only regionck cares
1461    /// about these dereferences, so we let it compute them as needed.
1462    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        // Opaque types can't have field projections, but we can instead convert
1490        // the current place in-place (heh) to the hidden type, and then apply all
1491        // follow up projections on that.
1492        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        // Reconstruct the output assuming it's a reference with the
1513        // same region and mutability as the receiver. This holds for
1514        // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1515        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    /// Returns the variant index for an ADT used within a Struct or TupleStruct pattern
1559    /// Here `pat_hir_id` is the HirId of the pattern itself.
1560    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                // Structs and Unions have only have one variant.
1585                Ok(FIRST_VARIANT)
1586            }
1587            _ => bug!("expected ADT path, found={:?}", res),
1588        }
1589    }
1590
1591    /// Returns the total number of fields in an ADT variant used within a pattern.
1592    /// Here `pat_hir_id` is the HirId of the pattern itself.
1593    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    /// Returns the total number of fields in a tuple used within a Tuple pattern.
1612    /// Here `pat_hir_id` is the HirId of the pattern itself.
1613    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    /// Here, `place` is the `PlaceWithHirId` being matched and pat is the pattern it
1622    /// is being matched against.
1623    ///
1624    /// In general, the way that this works is that we walk down the pattern,
1625    /// constructing a `PlaceWithHirId` that represents the path that will be taken
1626    /// to reach the value being matched.
1627    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        // If (pattern) adjustments are active for this pattern, adjust the `PlaceWithHirId` correspondingly.
1637        // `PlaceWithHirId`s are constructed differently from patterns. For example, in
1638        //
1639        // ```
1640        // match foo {
1641        //     &&Some(x, ) => { ... },
1642        //     _ => { ... },
1643        // }
1644        // ```
1645        //
1646        // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1647        // corresponding `PlaceWithHirId` we start with the `PlaceWithHirId` for `foo`, and then, by traversing the
1648        // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1649        //
1650        // `&&Some(x,)` `place_foo`
1651        //  `&Some(x,)` `deref { place_foo}`
1652        //   `Some(x,)` `deref { deref { place_foo }}`
1653        //       `(x,)` `field0 { deref { deref { place_foo }}}` <- resulting place
1654        //
1655        // The above example has no adjustments. If the code were instead the (after adjustments,
1656        // equivalent) version
1657        //
1658        // ```
1659        // match foo {
1660        //     Some(x, ) => { ... },
1661        //     _ => { ... },
1662        // }
1663        // ```
1664        //
1665        // Then we see that to get the same result, we must start with
1666        // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)`
1667        // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`.
1668        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; // lose mutability
1675        debug!("applied adjustment derefs to get place_with_id={:?}", place_with_id);
1676
1677        // Invoke the callback, but only now, after the `place_with_id` has adjusted.
1678        //
1679        // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1680        // case, the initial `place_with_id` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1681        // don't want to call `op` with these incompatible values. As written, what happens instead
1682        // is that `op` is called with the adjusted place (that for `*&Some(3)`) and the pattern
1683        // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1684        // result in the place `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1685        // that (where the `ref` on `x` is implied).
1686        op(&place_with_id, pat)?;
1687
1688        match pat.kind {
1689            PatKind::Tuple(subpats, dots_pos) => {
1690                // (p1, ..., pN)
1691                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                // S(p1, ..., pN)
1709                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                // S { f1: p1, ..., fN: pN }
1729
1730                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                // box p1, &p1, &mut p1. we can ignore the mutability of
1770                // PatKind::Ref since that information is already contained
1771                // in the type.
1772                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                // A deref pattern generates a temporary.
1782                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                // always ok
1828            }
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            // Note that if a non-exhaustive SingleVariant is defined in another crate, we need
1837            // to assume that more cases will be added to the variant in the future. This mean
1838            // that we should handle non-exhaustive SingleVariant the same way we would handle
1839            // a MultiVariant.
1840            // If the variant is not local it must be defined in another crate.
1841            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}