]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/mem_categorization.rs
Auto merge of #102189 - davidtwco:translation-derive-enums, r=compiler-errors
[rust.git] / compiler / rustc_typeck / src / mem_categorization.rs
1 //! # Categorization
2 //!
3 //! The job of the categorization module is to analyze an expression to
4 //! determine what kind of memory is used in evaluating it (for example,
5 //! where dereferences occur and what kind of pointer is dereferenced;
6 //! whether the memory is mutable, etc.).
7 //!
8 //! Categorization effectively transforms all of our expressions into
9 //! expressions of the following forms (the actual enum has many more
10 //! possibilities, naturally, but they are all variants of these base
11 //! forms):
12 //! ```ignore (not-rust)
13 //! E = rvalue    // some computed rvalue
14 //!   | x         // address of a local variable or argument
15 //!   | *E        // deref of a ptr
16 //!   | E.comp    // access to an interior component
17 //! ```
18 //! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
19 //! address where the result is to be found. If Expr is a place, then this
20 //! is the address of the place. If `Expr` is an rvalue, this is the address of
21 //! some temporary spot in memory where the result is stored.
22 //!
23 //! Now, `cat_expr()` classifies the expression `Expr` and the address `A = ToAddr(Expr)`
24 //! as follows:
25 //!
26 //! - `cat`: what kind of expression was this? This is a subset of the
27 //!   full expression forms which only includes those that we care about
28 //!   for the purpose of the analysis.
29 //! - `mutbl`: mutability of the address `A`.
30 //! - `ty`: the type of data found at the address `A`.
31 //!
32 //! The resulting categorization tree differs somewhat from the expressions
33 //! themselves. For example, auto-derefs are explicit. Also, an index `a[b]` is
34 //! decomposed into two operations: a dereference to reach the array data and
35 //! then an index to jump forward to the relevant item.
36 //!
37 //! ## By-reference upvars
38 //!
39 //! One part of the codegen which may be non-obvious is that we translate
40 //! closure upvars into the dereference of a borrowed pointer; this more closely
41 //! resembles the runtime codegen. So, for example, if we had:
42 //!
43 //!     let mut x = 3;
44 //!     let y = 5;
45 //!     let inc = || x += y;
46 //!
47 //! Then when we categorize `x` (*within* the closure) we would yield a
48 //! result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
49 //! tied to `x`. The type of `x'` will be a borrowed pointer.
50
51 use rustc_middle::hir::place::*;
52 use rustc_middle::ty::adjustment;
53 use rustc_middle::ty::fold::TypeFoldable;
54 use rustc_middle::ty::visit::TypeVisitable;
55 use rustc_middle::ty::{self, Ty, TyCtxt};
56
57 use rustc_data_structures::fx::FxIndexMap;
58 use rustc_hir as hir;
59 use rustc_hir::def::{CtorOf, DefKind, Res};
60 use rustc_hir::def_id::LocalDefId;
61 use rustc_hir::pat_util::EnumerateAndAdjustIterator;
62 use rustc_hir::PatKind;
63 use rustc_index::vec::Idx;
64 use rustc_infer::infer::InferCtxt;
65 use rustc_span::Span;
66 use rustc_target::abi::VariantIdx;
67 use rustc_trait_selection::infer::InferCtxtExt;
68
69 pub(crate) trait HirNode {
70     fn hir_id(&self) -> hir::HirId;
71     fn span(&self) -> Span;
72 }
73
74 impl HirNode for hir::Expr<'_> {
75     fn hir_id(&self) -> hir::HirId {
76         self.hir_id
77     }
78     fn span(&self) -> Span {
79         self.span
80     }
81 }
82
83 impl HirNode for hir::Pat<'_> {
84     fn hir_id(&self) -> hir::HirId {
85         self.hir_id
86     }
87     fn span(&self) -> Span {
88         self.span
89     }
90 }
91
92 #[derive(Clone)]
93 pub(crate) struct MemCategorizationContext<'a, 'tcx> {
94     pub(crate) typeck_results: &'a ty::TypeckResults<'tcx>,
95     infcx: &'a InferCtxt<'a, 'tcx>,
96     param_env: ty::ParamEnv<'tcx>,
97     body_owner: LocalDefId,
98     upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
99 }
100
101 pub(crate) type McResult<T> = Result<T, ()>;
102
103 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
104     /// Creates a `MemCategorizationContext`.
105     pub(crate) fn new(
106         infcx: &'a InferCtxt<'a, 'tcx>,
107         param_env: ty::ParamEnv<'tcx>,
108         body_owner: LocalDefId,
109         typeck_results: &'a ty::TypeckResults<'tcx>,
110     ) -> MemCategorizationContext<'a, 'tcx> {
111         MemCategorizationContext {
112             typeck_results,
113             infcx,
114             param_env,
115             body_owner,
116             upvars: infcx.tcx.upvars_mentioned(body_owner),
117         }
118     }
119
120     pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
121         self.infcx.tcx
122     }
123
124     pub(crate) fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
125         self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span)
126     }
127
128     fn resolve_vars_if_possible<T>(&self, value: T) -> T
129     where
130         T: TypeFoldable<'tcx>,
131     {
132         self.infcx.resolve_vars_if_possible(value)
133     }
134
135     fn is_tainted_by_errors(&self) -> bool {
136         self.infcx.is_tainted_by_errors()
137     }
138
139     fn resolve_type_vars_or_error(
140         &self,
141         id: hir::HirId,
142         ty: Option<Ty<'tcx>>,
143     ) -> McResult<Ty<'tcx>> {
144         match ty {
145             Some(ty) => {
146                 let ty = self.resolve_vars_if_possible(ty);
147                 if ty.references_error() || ty.is_ty_var() {
148                     debug!("resolve_type_vars_or_error: error from {:?}", ty);
149                     Err(())
150                 } else {
151                     Ok(ty)
152                 }
153             }
154             // FIXME
155             None if self.is_tainted_by_errors() => Err(()),
156             None => {
157                 bug!(
158                     "no type for node {}: {} in mem_categorization",
159                     id,
160                     self.tcx().hir().node_to_string(id)
161                 );
162             }
163         }
164     }
165
166     pub(crate) fn node_ty(&self, hir_id: hir::HirId) -> McResult<Ty<'tcx>> {
167         self.resolve_type_vars_or_error(hir_id, self.typeck_results.node_type_opt(hir_id))
168     }
169
170     fn expr_ty(&self, expr: &hir::Expr<'_>) -> McResult<Ty<'tcx>> {
171         self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_opt(expr))
172     }
173
174     pub(crate) fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> McResult<Ty<'tcx>> {
175         self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_adjusted_opt(expr))
176     }
177
178     /// Returns the type of value that this pattern matches against.
179     /// Some non-obvious cases:
180     ///
181     /// - a `ref x` binding matches against a value of type `T` and gives
182     ///   `x` the type `&T`; we return `T`.
183     /// - a pattern with implicit derefs (thanks to default binding
184     ///   modes #42640) may look like `Some(x)` but in fact have
185     ///   implicit deref patterns attached (e.g., it is really
186     ///   `&Some(x)`). In that case, we return the "outermost" type
187     ///   (e.g., `&Option<T>).
188     pub(crate) fn pat_ty_adjusted(&self, pat: &hir::Pat<'_>) -> McResult<Ty<'tcx>> {
189         // Check for implicit `&` types wrapping the pattern; note
190         // that these are never attached to binding patterns, so
191         // actually this is somewhat "disjoint" from the code below
192         // that aims to account for `ref x`.
193         if let Some(vec) = self.typeck_results.pat_adjustments().get(pat.hir_id) {
194             if let Some(first_ty) = vec.first() {
195                 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
196                 return Ok(*first_ty);
197             }
198         }
199
200         self.pat_ty_unadjusted(pat)
201     }
202
203     /// Like `pat_ty`, but ignores implicit `&` patterns.
204     fn pat_ty_unadjusted(&self, pat: &hir::Pat<'_>) -> McResult<Ty<'tcx>> {
205         let base_ty = self.node_ty(pat.hir_id)?;
206         debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
207
208         // This code detects whether we are looking at a `ref x`,
209         // and if so, figures out what the type *being borrowed* is.
210         let ret_ty = match pat.kind {
211             PatKind::Binding(..) => {
212                 let bm = *self
213                     .typeck_results
214                     .pat_binding_modes()
215                     .get(pat.hir_id)
216                     .expect("missing binding mode");
217
218                 if let ty::BindByReference(_) = bm {
219                     // a bind-by-ref means that the base_ty will be the type of the ident itself,
220                     // but what we want here is the type of the underlying value being borrowed.
221                     // So peel off one-level, turning the &T into T.
222                     match base_ty.builtin_deref(false) {
223                         Some(t) => t.ty,
224                         None => {
225                             debug!("By-ref binding of non-derefable type {:?}", base_ty);
226                             return Err(());
227                         }
228                     }
229                 } else {
230                     base_ty
231                 }
232             }
233             _ => base_ty,
234         };
235         debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
236
237         Ok(ret_ty)
238     }
239
240     pub(crate) fn cat_expr(&self, expr: &hir::Expr<'_>) -> McResult<PlaceWithHirId<'tcx>> {
241         // This recursion helper avoids going through *too many*
242         // adjustments, since *only* non-overloaded deref recurses.
243         fn helper<'a, 'tcx>(
244             mc: &MemCategorizationContext<'a, 'tcx>,
245             expr: &hir::Expr<'_>,
246             adjustments: &[adjustment::Adjustment<'tcx>],
247         ) -> McResult<PlaceWithHirId<'tcx>> {
248             match adjustments.split_last() {
249                 None => mc.cat_expr_unadjusted(expr),
250                 Some((adjustment, previous)) => {
251                     mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
252                 }
253             }
254         }
255
256         helper(self, expr, self.typeck_results.expr_adjustments(expr))
257     }
258
259     pub(crate) fn cat_expr_adjusted(
260         &self,
261         expr: &hir::Expr<'_>,
262         previous: PlaceWithHirId<'tcx>,
263         adjustment: &adjustment::Adjustment<'tcx>,
264     ) -> McResult<PlaceWithHirId<'tcx>> {
265         self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
266     }
267
268     #[instrument(level = "debug", skip(self, previous))]
269     fn cat_expr_adjusted_with<F>(
270         &self,
271         expr: &hir::Expr<'_>,
272         previous: F,
273         adjustment: &adjustment::Adjustment<'tcx>,
274     ) -> McResult<PlaceWithHirId<'tcx>>
275     where
276         F: FnOnce() -> McResult<PlaceWithHirId<'tcx>>,
277     {
278         let target = self.resolve_vars_if_possible(adjustment.target);
279         match adjustment.kind {
280             adjustment::Adjust::Deref(overloaded) => {
281                 // Equivalent to *expr or something similar.
282                 let base = if let Some(deref) = overloaded {
283                     let ref_ty = self
284                         .tcx()
285                         .mk_ref(deref.region, ty::TypeAndMut { ty: target, mutbl: deref.mutbl });
286                     self.cat_rvalue(expr.hir_id, expr.span, ref_ty)
287                 } else {
288                     previous()?
289                 };
290                 self.cat_deref(expr, base)
291             }
292
293             adjustment::Adjust::NeverToAny
294             | adjustment::Adjust::Pointer(_)
295             | adjustment::Adjust::Borrow(_) => {
296                 // Result is an rvalue.
297                 Ok(self.cat_rvalue(expr.hir_id, expr.span, target))
298             }
299         }
300     }
301
302     #[instrument(level = "debug", skip(self))]
303     pub(crate) fn cat_expr_unadjusted(
304         &self,
305         expr: &hir::Expr<'_>,
306     ) -> McResult<PlaceWithHirId<'tcx>> {
307         debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr);
308
309         let expr_ty = self.expr_ty(expr)?;
310         match expr.kind {
311             hir::ExprKind::Unary(hir::UnOp::Deref, ref e_base) => {
312                 if self.typeck_results.is_method_call(expr) {
313                     self.cat_overloaded_place(expr, e_base)
314                 } else {
315                     let base = self.cat_expr(e_base)?;
316                     self.cat_deref(expr, base)
317                 }
318             }
319
320             hir::ExprKind::Field(ref base, _) => {
321                 let base = self.cat_expr(base)?;
322                 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}", expr.hir_id, expr, base);
323
324                 let field_idx = self
325                     .typeck_results
326                     .field_indices()
327                     .get(expr.hir_id)
328                     .cloned()
329                     .expect("Field index not found");
330
331                 Ok(self.cat_projection(
332                     expr,
333                     base,
334                     expr_ty,
335                     ProjectionKind::Field(field_idx as u32, VariantIdx::new(0)),
336                 ))
337             }
338
339             hir::ExprKind::Index(ref base, _) => {
340                 if self.typeck_results.is_method_call(expr) {
341                     // If this is an index implemented by a method call, then it
342                     // will include an implicit deref of the result.
343                     // The call to index() returns a `&T` value, which
344                     // is an rvalue. That is what we will be
345                     // dereferencing.
346                     self.cat_overloaded_place(expr, base)
347                 } else {
348                     let base = self.cat_expr(base)?;
349                     Ok(self.cat_projection(expr, base, expr_ty, ProjectionKind::Index))
350                 }
351             }
352
353             hir::ExprKind::Path(ref qpath) => {
354                 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
355                 self.cat_res(expr.hir_id, expr.span, expr_ty, res)
356             }
357
358             hir::ExprKind::Type(ref e, _) => self.cat_expr(e),
359
360             hir::ExprKind::AddrOf(..)
361             | hir::ExprKind::Call(..)
362             | hir::ExprKind::Assign(..)
363             | hir::ExprKind::AssignOp(..)
364             | hir::ExprKind::Closure { .. }
365             | hir::ExprKind::Ret(..)
366             | hir::ExprKind::Unary(..)
367             | hir::ExprKind::Yield(..)
368             | hir::ExprKind::MethodCall(..)
369             | hir::ExprKind::Cast(..)
370             | hir::ExprKind::DropTemps(..)
371             | hir::ExprKind::Array(..)
372             | hir::ExprKind::If(..)
373             | hir::ExprKind::Tup(..)
374             | hir::ExprKind::Binary(..)
375             | hir::ExprKind::Block(..)
376             | hir::ExprKind::Let(..)
377             | hir::ExprKind::Loop(..)
378             | hir::ExprKind::Match(..)
379             | hir::ExprKind::Lit(..)
380             | hir::ExprKind::ConstBlock(..)
381             | hir::ExprKind::Break(..)
382             | hir::ExprKind::Continue(..)
383             | hir::ExprKind::Struct(..)
384             | hir::ExprKind::Repeat(..)
385             | hir::ExprKind::InlineAsm(..)
386             | hir::ExprKind::Box(..)
387             | hir::ExprKind::Err => Ok(self.cat_rvalue(expr.hir_id, expr.span, expr_ty)),
388         }
389     }
390
391     #[instrument(level = "debug", skip(self, span))]
392     pub(crate) fn cat_res(
393         &self,
394         hir_id: hir::HirId,
395         span: Span,
396         expr_ty: Ty<'tcx>,
397         res: Res,
398     ) -> McResult<PlaceWithHirId<'tcx>> {
399         match res {
400             Res::Def(
401                 DefKind::Ctor(..)
402                 | DefKind::Const
403                 | DefKind::ConstParam
404                 | DefKind::AssocConst
405                 | DefKind::Fn
406                 | DefKind::AssocFn,
407                 _,
408             )
409             | Res::SelfCtor(..) => Ok(self.cat_rvalue(hir_id, span, expr_ty)),
410
411             Res::Def(DefKind::Static(_), _) => {
412                 Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::StaticItem, Vec::new()))
413             }
414
415             Res::Local(var_id) => {
416                 if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) {
417                     self.cat_upvar(hir_id, var_id)
418                 } else {
419                     Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Local(var_id), Vec::new()))
420                 }
421             }
422
423             def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def),
424         }
425     }
426
427     /// Categorize an upvar.
428     ///
429     /// Note: the actual upvar access contains invisible derefs of closure
430     /// environment and upvar reference as appropriate. Only regionck cares
431     /// about these dereferences, so we let it compute them as needed.
432     fn cat_upvar(&self, hir_id: hir::HirId, var_id: hir::HirId) -> McResult<PlaceWithHirId<'tcx>> {
433         let closure_expr_def_id = self.body_owner;
434
435         let upvar_id = ty::UpvarId {
436             var_path: ty::UpvarPath { hir_id: var_id },
437             closure_expr_id: closure_expr_def_id,
438         };
439         let var_ty = self.node_ty(var_id)?;
440
441         let ret = PlaceWithHirId::new(hir_id, var_ty, PlaceBase::Upvar(upvar_id), Vec::new());
442
443         debug!("cat_upvar ret={:?}", ret);
444         Ok(ret)
445     }
446
447     pub(crate) fn cat_rvalue(
448         &self,
449         hir_id: hir::HirId,
450         span: Span,
451         expr_ty: Ty<'tcx>,
452     ) -> PlaceWithHirId<'tcx> {
453         debug!("cat_rvalue hir_id={:?}, expr_ty={:?}, span={:?}", hir_id, expr_ty, span);
454         let ret = PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Rvalue, Vec::new());
455         debug!("cat_rvalue ret={:?}", ret);
456         ret
457     }
458
459     pub(crate) fn cat_projection<N: HirNode>(
460         &self,
461         node: &N,
462         base_place: PlaceWithHirId<'tcx>,
463         ty: Ty<'tcx>,
464         kind: ProjectionKind,
465     ) -> PlaceWithHirId<'tcx> {
466         let mut projections = base_place.place.projections;
467         projections.push(Projection { kind, ty });
468         let ret = PlaceWithHirId::new(
469             node.hir_id(),
470             base_place.place.base_ty,
471             base_place.place.base,
472             projections,
473         );
474         debug!("cat_field ret {:?}", ret);
475         ret
476     }
477
478     #[instrument(level = "debug", skip(self))]
479     fn cat_overloaded_place(
480         &self,
481         expr: &hir::Expr<'_>,
482         base: &hir::Expr<'_>,
483     ) -> McResult<PlaceWithHirId<'tcx>> {
484         // Reconstruct the output assuming it's a reference with the
485         // same region and mutability as the receiver. This holds for
486         // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
487         let place_ty = self.expr_ty(expr)?;
488         let base_ty = self.expr_ty_adjusted(base)?;
489
490         let ty::Ref(region, _, mutbl) = *base_ty.kind() else {
491             span_bug!(expr.span, "cat_overloaded_place: base is not a reference");
492         };
493         let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
494
495         let base = self.cat_rvalue(expr.hir_id, expr.span, ref_ty);
496         self.cat_deref(expr, base)
497     }
498
499     #[instrument(level = "debug", skip(self, node))]
500     fn cat_deref(
501         &self,
502         node: &impl HirNode,
503         base_place: PlaceWithHirId<'tcx>,
504     ) -> McResult<PlaceWithHirId<'tcx>> {
505         let base_curr_ty = base_place.place.ty();
506         let deref_ty = match base_curr_ty.builtin_deref(true) {
507             Some(mt) => mt.ty,
508             None => {
509                 debug!("explicit deref of non-derefable type: {:?}", base_curr_ty);
510                 return Err(());
511             }
512         };
513         let mut projections = base_place.place.projections;
514         projections.push(Projection { kind: ProjectionKind::Deref, ty: deref_ty });
515
516         let ret = PlaceWithHirId::new(
517             node.hir_id(),
518             base_place.place.base_ty,
519             base_place.place.base,
520             projections,
521         );
522         debug!("cat_deref ret {:?}", ret);
523         Ok(ret)
524     }
525
526     pub(crate) fn cat_pattern<F>(
527         &self,
528         place: PlaceWithHirId<'tcx>,
529         pat: &hir::Pat<'_>,
530         mut op: F,
531     ) -> McResult<()>
532     where
533         F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>),
534     {
535         self.cat_pattern_(place, pat, &mut op)
536     }
537
538     /// Returns the variant index for an ADT used within a Struct or TupleStruct pattern
539     /// Here `pat_hir_id` is the HirId of the pattern itself.
540     fn variant_index_for_adt(
541         &self,
542         qpath: &hir::QPath<'_>,
543         pat_hir_id: hir::HirId,
544         span: Span,
545     ) -> McResult<VariantIdx> {
546         let res = self.typeck_results.qpath_res(qpath, pat_hir_id);
547         let ty = self.typeck_results.node_type(pat_hir_id);
548         let ty::Adt(adt_def, _) = ty.kind() else {
549             self.tcx()
550                 .sess
551                 .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT");
552             return Err(());
553         };
554
555         match res {
556             Res::Def(DefKind::Variant, variant_id) => Ok(adt_def.variant_index_with_id(variant_id)),
557             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
558                 Ok(adt_def.variant_index_with_ctor_id(variant_ctor_id))
559             }
560             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
561             | Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
562             | Res::SelfCtor(..)
563             | Res::SelfTy { .. } => {
564                 // Structs and Unions have only have one variant.
565                 Ok(VariantIdx::new(0))
566             }
567             _ => bug!("expected ADT path, found={:?}", res),
568         }
569     }
570
571     /// Returns the total number of fields in an ADT variant used within a pattern.
572     /// Here `pat_hir_id` is the HirId of the pattern itself.
573     fn total_fields_in_adt_variant(
574         &self,
575         pat_hir_id: hir::HirId,
576         variant_index: VariantIdx,
577         span: Span,
578     ) -> McResult<usize> {
579         let ty = self.typeck_results.node_type(pat_hir_id);
580         match ty.kind() {
581             ty::Adt(adt_def, _) => Ok(adt_def.variant(variant_index).fields.len()),
582             _ => {
583                 self.tcx()
584                     .sess
585                     .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT");
586                 Err(())
587             }
588         }
589     }
590
591     /// Returns the total number of fields in a tuple used within a Tuple pattern.
592     /// Here `pat_hir_id` is the HirId of the pattern itself.
593     fn total_fields_in_tuple(&self, pat_hir_id: hir::HirId, span: Span) -> McResult<usize> {
594         let ty = self.typeck_results.node_type(pat_hir_id);
595         match ty.kind() {
596             ty::Tuple(substs) => Ok(substs.len()),
597             _ => {
598                 self.tcx().sess.delay_span_bug(span, "tuple pattern not applied to a tuple");
599                 Err(())
600             }
601         }
602     }
603
604     // FIXME(#19596) This is a workaround, but there should be a better way to do this
605     fn cat_pattern_<F>(
606         &self,
607         mut place_with_id: PlaceWithHirId<'tcx>,
608         pat: &hir::Pat<'_>,
609         op: &mut F,
610     ) -> McResult<()>
611     where
612         F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>),
613     {
614         // Here, `place` is the `PlaceWithHirId` being matched and pat is the pattern it
615         // is being matched against.
616         //
617         // In general, the way that this works is that we walk down the pattern,
618         // constructing a `PlaceWithHirId` that represents the path that will be taken
619         // to reach the value being matched.
620
621         debug!("cat_pattern(pat={:?}, place_with_id={:?})", pat, place_with_id);
622
623         // If (pattern) adjustments are active for this pattern, adjust the `PlaceWithHirId` correspondingly.
624         // `PlaceWithHirId`s are constructed differently from patterns. For example, in
625         //
626         // ```
627         // match foo {
628         //     &&Some(x, ) => { ... },
629         //     _ => { ... },
630         // }
631         // ```
632         //
633         // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
634         // corresponding `PlaceWithHirId` we start with the `PlaceWithHirId` for `foo`, and then, by traversing the
635         // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
636         //
637         // `&&Some(x,)` `place_foo`
638         //  `&Some(x,)` `deref { place_foo}`
639         //   `Some(x,)` `deref { deref { place_foo }}`
640         //        (x,)` `field0 { deref { deref { place_foo }}}` <- resulting place
641         //
642         // The above example has no adjustments. If the code were instead the (after adjustments,
643         // equivalent) version
644         //
645         // ```
646         // match foo {
647         //     Some(x, ) => { ... },
648         //     _ => { ... },
649         // }
650         // ```
651         //
652         // Then we see that to get the same result, we must start with
653         // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)`
654         // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`.
655         for _ in 0..self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(0, |v| v.len()) {
656             debug!("cat_pattern: applying adjustment to place_with_id={:?}", place_with_id);
657             place_with_id = self.cat_deref(pat, place_with_id)?;
658         }
659         let place_with_id = place_with_id; // lose mutability
660         debug!("cat_pattern: applied adjustment derefs to get place_with_id={:?}", place_with_id);
661
662         // Invoke the callback, but only now, after the `place_with_id` has adjusted.
663         //
664         // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
665         // case, the initial `place_with_id` will be that for `&Some(3)` and the pattern is `Some(x)`. We
666         // don't want to call `op` with these incompatible values. As written, what happens instead
667         // is that `op` is called with the adjusted place (that for `*&Some(3)`) and the pattern
668         // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
669         // result in the place `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
670         // that (where the `ref` on `x` is implied).
671         op(&place_with_id, pat);
672
673         match pat.kind {
674             PatKind::Tuple(subpats, dots_pos) => {
675                 // (p1, ..., pN)
676                 let total_fields = self.total_fields_in_tuple(pat.hir_id, pat.span)?;
677
678                 for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
679                     let subpat_ty = self.pat_ty_adjusted(subpat)?;
680                     let projection_kind = ProjectionKind::Field(i as u32, VariantIdx::new(0));
681                     let sub_place =
682                         self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind);
683                     self.cat_pattern_(sub_place, subpat, op)?;
684                 }
685             }
686
687             PatKind::TupleStruct(ref qpath, subpats, dots_pos) => {
688                 // S(p1, ..., pN)
689                 let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?;
690                 let total_fields =
691                     self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat.span)?;
692
693                 for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
694                     let subpat_ty = self.pat_ty_adjusted(subpat)?;
695                     let projection_kind = ProjectionKind::Field(i as u32, variant_index);
696                     let sub_place =
697                         self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind);
698                     self.cat_pattern_(sub_place, subpat, op)?;
699                 }
700             }
701
702             PatKind::Struct(ref qpath, field_pats, _) => {
703                 // S { f1: p1, ..., fN: pN }
704
705                 let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?;
706
707                 for fp in field_pats {
708                     let field_ty = self.pat_ty_adjusted(fp.pat)?;
709                     let field_index = self
710                         .typeck_results
711                         .field_indices()
712                         .get(fp.hir_id)
713                         .cloned()
714                         .expect("no index for a field");
715
716                     let field_place = self.cat_projection(
717                         pat,
718                         place_with_id.clone(),
719                         field_ty,
720                         ProjectionKind::Field(field_index as u32, variant_index),
721                     );
722                     self.cat_pattern_(field_place, fp.pat, op)?;
723                 }
724             }
725
726             PatKind::Or(pats) => {
727                 for pat in pats {
728                     self.cat_pattern_(place_with_id.clone(), pat, op)?;
729                 }
730             }
731
732             PatKind::Binding(.., Some(ref subpat)) => {
733                 self.cat_pattern_(place_with_id, subpat, op)?;
734             }
735
736             PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
737                 // box p1, &p1, &mut p1.  we can ignore the mutability of
738                 // PatKind::Ref since that information is already contained
739                 // in the type.
740                 let subplace = self.cat_deref(pat, place_with_id)?;
741                 self.cat_pattern_(subplace, subpat, op)?;
742             }
743
744             PatKind::Slice(before, ref slice, after) => {
745                 let Some(element_ty) = place_with_id.place.ty().builtin_index() else {
746                     debug!("explicit index of non-indexable type {:?}", place_with_id);
747                     return Err(());
748                 };
749                 let elt_place = self.cat_projection(
750                     pat,
751                     place_with_id.clone(),
752                     element_ty,
753                     ProjectionKind::Index,
754                 );
755                 for before_pat in before {
756                     self.cat_pattern_(elt_place.clone(), before_pat, op)?;
757                 }
758                 if let Some(ref slice_pat) = *slice {
759                     let slice_pat_ty = self.pat_ty_adjusted(slice_pat)?;
760                     let slice_place = self.cat_projection(
761                         pat,
762                         place_with_id,
763                         slice_pat_ty,
764                         ProjectionKind::Subslice,
765                     );
766                     self.cat_pattern_(slice_place, slice_pat, op)?;
767                 }
768                 for after_pat in after {
769                     self.cat_pattern_(elt_place.clone(), after_pat, op)?;
770                 }
771             }
772
773             PatKind::Path(_)
774             | PatKind::Binding(.., None)
775             | PatKind::Lit(..)
776             | PatKind::Range(..)
777             | PatKind::Wild => {
778                 // always ok
779             }
780         }
781
782         Ok(())
783     }
784 }