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.).
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
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
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.
23 //! Now, `cat_expr()` classifies the expression `Expr` and the address `A = ToAddr(Expr)`
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`.
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.
37 //! ## By-reference upvars
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:
45 //! let inc = || x += y;
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.
51 use rustc_middle::ty::adjustment;
52 use rustc_middle::ty::fold::TypeFoldable;
53 use rustc_middle::ty::{self, Ty, TyCtxt};
55 use rustc_data_structures::fx::FxIndexMap;
57 use rustc_hir::def::{CtorOf, DefKind, Res};
58 use rustc_hir::def_id::LocalDefId;
59 use rustc_hir::pat_util::EnumerateAndAdjustIterator;
60 use rustc_hir::PatKind;
61 use rustc_index::vec::Idx;
62 use rustc_infer::infer::InferCtxt;
64 use rustc_target::abi::VariantIdx;
65 use rustc_trait_selection::infer::InferCtxtExt;
67 #[derive(Clone, Debug)]
69 /// A temporary variable
71 /// A named `static` item
73 /// A named local variable
75 /// An upvar referenced by closure env
79 #[derive(Clone, Debug, Eq, PartialEq)]
80 pub enum ProjectionKind {
81 /// A dereference of a pointer, reference or `Box<T>` of the given type
84 /// `B.F` where `B` is the base expression and `F` is
85 /// the field. The field is identified by which variant
86 /// it appears in along with a field index. The variant
87 /// is used for enums.
88 Field(u32, VariantIdx),
90 /// Some index like `B[x]`, where `B` is the base
91 /// expression. We don't preserve the index `x` because
95 /// A subslice covering a range of values like `B[x..y]`.
99 #[derive(Clone, Debug)]
100 pub struct Projection<'tcx> {
101 // Type after the projection is being applied.
104 /// Defines the type of access
105 kind: ProjectionKind,
108 /// A `Place` represents how a value is located in memory.
110 /// This is an HIR version of `mir::Place`
111 #[derive(Clone, Debug)]
112 pub struct Place<'tcx> {
113 /// The type of the `PlaceBase`
114 pub base_ty: Ty<'tcx>,
115 /// The "outermost" place that holds this value.
117 /// How this place is derived from the base place.
118 pub projections: Vec<Projection<'tcx>>,
121 /// A `PlaceWithHirId` represents how a value is located in memory.
123 /// This is an HIR version of `mir::Place`
124 #[derive(Clone, Debug)]
125 pub struct PlaceWithHirId<'tcx> {
126 /// `HirId` of the expression or pattern producing this value.
127 pub hir_id: hir::HirId,
129 /// Information about the `Place`
130 pub place: Place<'tcx>,
133 impl<'tcx> PlaceWithHirId<'tcx> {
138 projections: Vec<Projection<'tcx>>,
139 ) -> PlaceWithHirId<'tcx> {
142 place: Place { base_ty: base_ty, base: base, projections: projections },
147 impl<'tcx> Place<'tcx> {
148 /// Returns an iterator of the types that have to be dereferenced to access
151 /// The types are in the reverse order that they are applied. So if
152 /// `x: &*const u32` and the `Place` is `**x`, then the types returned are
153 ///`*const u32` then `&*const u32`.
154 crate fn deref_tys(&self) -> impl Iterator<Item = Ty<'tcx>> + '_ {
155 self.projections.iter().enumerate().rev().filter_map(move |(index, proj)| {
156 if ProjectionKind::Deref == proj.kind {
157 Some(self.ty_before_projection(index))
164 // Returns the type of this `Place` after all projections have been applied.
165 pub fn ty(&self) -> Ty<'tcx> {
166 self.projections.last().map_or_else(|| self.base_ty, |proj| proj.ty)
169 // Returns the type of this `Place` immediately before `projection_index`th projection
171 crate fn ty_before_projection(&self, projection_index: usize) -> Ty<'tcx> {
172 assert!(projection_index < self.projections.len());
173 if projection_index == 0 { self.base_ty } else { self.projections[projection_index - 1].ty }
177 crate trait HirNode {
178 fn hir_id(&self) -> hir::HirId;
179 fn span(&self) -> Span;
182 impl HirNode for hir::Expr<'_> {
183 fn hir_id(&self) -> hir::HirId {
186 fn span(&self) -> Span {
191 impl HirNode for hir::Pat<'_> {
192 fn hir_id(&self) -> hir::HirId {
195 fn span(&self) -> Span {
201 crate struct MemCategorizationContext<'a, 'tcx> {
202 crate tables: &'a ty::TypeckTables<'tcx>,
203 infcx: &'a InferCtxt<'a, 'tcx>,
204 param_env: ty::ParamEnv<'tcx>,
205 body_owner: LocalDefId,
206 upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
209 crate type McResult<T> = Result<T, ()>;
211 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
212 /// Creates a `MemCategorizationContext`.
214 infcx: &'a InferCtxt<'a, 'tcx>,
215 param_env: ty::ParamEnv<'tcx>,
216 body_owner: LocalDefId,
217 tables: &'a ty::TypeckTables<'tcx>,
218 ) -> MemCategorizationContext<'a, 'tcx> {
219 MemCategorizationContext {
224 upvars: infcx.tcx.upvars_mentioned(body_owner),
228 crate fn tcx(&self) -> TyCtxt<'tcx> {
232 crate fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
233 self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span)
236 fn resolve_vars_if_possible<T>(&self, value: &T) -> T
238 T: TypeFoldable<'tcx>,
240 self.infcx.resolve_vars_if_possible(value)
243 fn is_tainted_by_errors(&self) -> bool {
244 self.infcx.is_tainted_by_errors()
247 fn resolve_type_vars_or_error(
250 ty: Option<Ty<'tcx>>,
251 ) -> McResult<Ty<'tcx>> {
254 let ty = self.resolve_vars_if_possible(&ty);
255 if ty.references_error() || ty.is_ty_var() {
256 debug!("resolve_type_vars_or_error: error from {:?}", ty);
263 None if self.is_tainted_by_errors() => Err(()),
266 "no type for node {}: {} in mem_categorization",
268 self.tcx().hir().node_to_string(id)
274 crate fn node_ty(&self, hir_id: hir::HirId) -> McResult<Ty<'tcx>> {
275 self.resolve_type_vars_or_error(hir_id, self.tables.node_type_opt(hir_id))
278 fn expr_ty(&self, expr: &hir::Expr<'_>) -> McResult<Ty<'tcx>> {
279 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
282 crate fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> McResult<Ty<'tcx>> {
283 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
286 /// Returns the type of value that this pattern matches against.
287 /// Some non-obvious cases:
289 /// - a `ref x` binding matches against a value of type `T` and gives
290 /// `x` the type `&T`; we return `T`.
291 /// - a pattern with implicit derefs (thanks to default binding
292 /// modes #42640) may look like `Some(x)` but in fact have
293 /// implicit deref patterns attached (e.g., it is really
294 /// `&Some(x)`). In that case, we return the "outermost" type
295 /// (e.g., `&Option<T>).
296 crate fn pat_ty_adjusted(&self, pat: &hir::Pat<'_>) -> McResult<Ty<'tcx>> {
297 // Check for implicit `&` types wrapping the pattern; note
298 // that these are never attached to binding patterns, so
299 // actually this is somewhat "disjoint" from the code below
300 // that aims to account for `ref x`.
301 if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
302 if let Some(first_ty) = vec.first() {
303 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
308 self.pat_ty_unadjusted(pat)
311 /// Like `pat_ty`, but ignores implicit `&` patterns.
312 fn pat_ty_unadjusted(&self, pat: &hir::Pat<'_>) -> McResult<Ty<'tcx>> {
313 let base_ty = self.node_ty(pat.hir_id)?;
314 debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
316 // This code detects whether we are looking at a `ref x`,
317 // and if so, figures out what the type *being borrowed* is.
318 let ret_ty = match pat.kind {
319 PatKind::Binding(..) => {
321 *self.tables.pat_binding_modes().get(pat.hir_id).expect("missing binding mode");
323 if let ty::BindByReference(_) = bm {
324 // a bind-by-ref means that the base_ty will be the type of the ident itself,
325 // but what we want here is the type of the underlying value being borrowed.
326 // So peel off one-level, turning the &T into T.
327 match base_ty.builtin_deref(false) {
330 debug!("By-ref binding of non-derefable type {:?}", base_ty);
340 debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
345 crate fn cat_expr(&self, expr: &hir::Expr<'_>) -> McResult<PlaceWithHirId<'tcx>> {
346 // This recursion helper avoids going through *too many*
347 // adjustments, since *only* non-overloaded deref recurses.
349 mc: &MemCategorizationContext<'a, 'tcx>,
350 expr: &hir::Expr<'_>,
351 adjustments: &[adjustment::Adjustment<'tcx>],
352 ) -> McResult<PlaceWithHirId<'tcx>> {
353 match adjustments.split_last() {
354 None => mc.cat_expr_unadjusted(expr),
355 Some((adjustment, previous)) => {
356 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
361 helper(self, expr, self.tables.expr_adjustments(expr))
364 crate fn cat_expr_adjusted(
366 expr: &hir::Expr<'_>,
367 previous: PlaceWithHirId<'tcx>,
368 adjustment: &adjustment::Adjustment<'tcx>,
369 ) -> McResult<PlaceWithHirId<'tcx>> {
370 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
373 fn cat_expr_adjusted_with<F>(
375 expr: &hir::Expr<'_>,
377 adjustment: &adjustment::Adjustment<'tcx>,
378 ) -> McResult<PlaceWithHirId<'tcx>>
380 F: FnOnce() -> McResult<PlaceWithHirId<'tcx>>,
382 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
383 let target = self.resolve_vars_if_possible(&adjustment.target);
384 match adjustment.kind {
385 adjustment::Adjust::Deref(overloaded) => {
386 // Equivalent to *expr or something similar.
387 let base = if let Some(deref) = overloaded {
390 .mk_ref(deref.region, ty::TypeAndMut { ty: target, mutbl: deref.mutbl });
391 self.cat_rvalue(expr.hir_id, expr.span, ref_ty)
395 self.cat_deref(expr, base)
398 adjustment::Adjust::NeverToAny
399 | adjustment::Adjust::Pointer(_)
400 | adjustment::Adjust::Borrow(_) => {
401 // Result is an rvalue.
402 Ok(self.cat_rvalue(expr.hir_id, expr.span, target))
407 crate fn cat_expr_unadjusted(&self, expr: &hir::Expr<'_>) -> McResult<PlaceWithHirId<'tcx>> {
408 debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr);
410 let expr_ty = self.expr_ty(expr)?;
412 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref e_base) => {
413 if self.tables.is_method_call(expr) {
414 self.cat_overloaded_place(expr, e_base)
416 let base = self.cat_expr(&e_base)?;
417 self.cat_deref(expr, base)
421 hir::ExprKind::Field(ref base, _) => {
422 let base = self.cat_expr(&base)?;
423 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}", expr.hir_id, expr, base);
430 .expect("Field index not found");
432 Ok(self.cat_projection(
436 ProjectionKind::Field(field_idx as u32, VariantIdx::new(0)),
440 hir::ExprKind::Index(ref base, _) => {
441 if self.tables.is_method_call(expr) {
442 // If this is an index implemented by a method call, then it
443 // will include an implicit deref of the result.
444 // The call to index() returns a `&T` value, which
445 // is an rvalue. That is what we will be
447 self.cat_overloaded_place(expr, base)
449 let base = self.cat_expr(&base)?;
450 Ok(self.cat_projection(expr, base, expr_ty, ProjectionKind::Index))
454 hir::ExprKind::Path(ref qpath) => {
455 let res = self.tables.qpath_res(qpath, expr.hir_id);
456 self.cat_res(expr.hir_id, expr.span, expr_ty, res)
459 hir::ExprKind::Type(ref e, _) => self.cat_expr(&e),
461 hir::ExprKind::AddrOf(..)
462 | hir::ExprKind::Call(..)
463 | hir::ExprKind::Assign(..)
464 | hir::ExprKind::AssignOp(..)
465 | hir::ExprKind::Closure(..)
466 | hir::ExprKind::Ret(..)
467 | hir::ExprKind::Unary(..)
468 | hir::ExprKind::Yield(..)
469 | hir::ExprKind::MethodCall(..)
470 | hir::ExprKind::Cast(..)
471 | hir::ExprKind::DropTemps(..)
472 | hir::ExprKind::Array(..)
473 | hir::ExprKind::Tup(..)
474 | hir::ExprKind::Binary(..)
475 | hir::ExprKind::Block(..)
476 | hir::ExprKind::Loop(..)
477 | hir::ExprKind::Match(..)
478 | hir::ExprKind::Lit(..)
479 | hir::ExprKind::Break(..)
480 | hir::ExprKind::Continue(..)
481 | hir::ExprKind::Struct(..)
482 | hir::ExprKind::Repeat(..)
483 | hir::ExprKind::InlineAsm(..)
484 | hir::ExprKind::LlvmInlineAsm(..)
485 | hir::ExprKind::Box(..)
486 | hir::ExprKind::Err => Ok(self.cat_rvalue(expr.hir_id, expr.span, expr_ty)),
496 ) -> McResult<PlaceWithHirId<'tcx>> {
497 debug!("cat_res: id={:?} expr={:?} def={:?}", hir_id, expr_ty, res);
503 | DefKind::ConstParam
504 | DefKind::AssocConst
509 | Res::SelfCtor(..) => Ok(self.cat_rvalue(hir_id, span, expr_ty)),
511 Res::Def(DefKind::Static, _) => {
512 Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::StaticItem, Vec::new()))
515 Res::Local(var_id) => {
516 if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) {
517 self.cat_upvar(hir_id, var_id)
519 Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Local(var_id), Vec::new()))
523 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def),
527 /// Categorize an upvar.
529 /// Note: the actual upvar access contains invisible derefs of closure
530 /// environment and upvar reference as appropriate. Only regionck cares
531 /// about these dereferences, so we let it compute them as needed.
532 fn cat_upvar(&self, hir_id: hir::HirId, var_id: hir::HirId) -> McResult<PlaceWithHirId<'tcx>> {
533 let closure_expr_def_id = self.body_owner;
535 let upvar_id = ty::UpvarId {
536 var_path: ty::UpvarPath { hir_id: var_id },
537 closure_expr_id: closure_expr_def_id,
539 let var_ty = self.node_ty(var_id)?;
541 let ret = PlaceWithHirId::new(hir_id, var_ty, PlaceBase::Upvar(upvar_id), Vec::new());
543 debug!("cat_upvar ret={:?}", ret);
552 ) -> PlaceWithHirId<'tcx> {
553 debug!("cat_rvalue hir_id={:?}, expr_ty={:?}, span={:?}", hir_id, expr_ty, span);
554 let ret = PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Rvalue, Vec::new());
555 debug!("cat_rvalue ret={:?}", ret);
559 crate fn cat_projection<N: HirNode>(
562 base_place: PlaceWithHirId<'tcx>,
564 kind: ProjectionKind,
565 ) -> PlaceWithHirId<'tcx> {
566 let mut projections = base_place.place.projections;
567 projections.push(Projection { kind: kind, ty: ty });
568 let ret = PlaceWithHirId::new(
570 base_place.place.base_ty,
571 base_place.place.base,
574 debug!("cat_field ret {:?}", ret);
578 fn cat_overloaded_place(
580 expr: &hir::Expr<'_>,
581 base: &hir::Expr<'_>,
582 ) -> McResult<PlaceWithHirId<'tcx>> {
583 debug!("cat_overloaded_place(expr={:?}, base={:?})", expr, base);
585 // Reconstruct the output assuming it's a reference with the
586 // same region and mutability as the receiver. This holds for
587 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
588 let place_ty = self.expr_ty(expr)?;
589 let base_ty = self.expr_ty_adjusted(base)?;
591 let (region, mutbl) = match base_ty.kind {
592 ty::Ref(region, _, mutbl) => (region, mutbl),
593 _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference"),
595 let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
597 let base = self.cat_rvalue(expr.hir_id, expr.span, ref_ty);
598 self.cat_deref(expr, base)
604 base_place: PlaceWithHirId<'tcx>,
605 ) -> McResult<PlaceWithHirId<'tcx>> {
606 debug!("cat_deref: base_place={:?}", base_place);
608 let base_curr_ty = base_place.place.ty();
609 let deref_ty = match base_curr_ty.builtin_deref(true) {
612 debug!("explicit deref of non-derefable type: {:?}", base_curr_ty);
616 let mut projections = base_place.place.projections;
617 projections.push(Projection { kind: ProjectionKind::Deref, ty: deref_ty });
619 let ret = PlaceWithHirId::new(
621 base_place.place.base_ty,
622 base_place.place.base,
625 debug!("cat_deref ret {:?}", ret);
629 crate fn cat_pattern<F>(
631 place: PlaceWithHirId<'tcx>,
636 F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>),
638 self.cat_pattern_(place, pat, &mut op)
641 /// Returns the variant index for an ADT used within a Struct or TupleStruct pattern
642 /// Here `pat_hir_id` is the HirId of the pattern itself.
643 fn variant_index_for_adt(
645 qpath: &hir::QPath<'_>,
646 pat_hir_id: hir::HirId,
648 ) -> McResult<VariantIdx> {
649 let res = self.tables.qpath_res(qpath, pat_hir_id);
650 let ty = self.tables.node_type(pat_hir_id);
651 let adt_def = match ty.kind {
652 ty::Adt(adt_def, _) => adt_def,
656 .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT");
662 Res::Def(DefKind::Variant, variant_id) => Ok(adt_def.variant_index_with_id(variant_id)),
663 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
664 Ok(adt_def.variant_index_with_ctor_id(variant_ctor_id))
666 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _)
667 | Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
669 | Res::SelfTy(..) => {
670 // Structs and Unions have only have one variant.
671 Ok(VariantIdx::new(0))
673 _ => bug!("expected ADT path, found={:?}", res),
677 /// Returns the total number of fields in an ADT variant used within a pattern.
678 /// Here `pat_hir_id` is the HirId of the pattern itself.
679 fn total_fields_in_adt_variant(
681 pat_hir_id: hir::HirId,
682 variant_index: VariantIdx,
684 ) -> McResult<usize> {
685 let ty = self.tables.node_type(pat_hir_id);
687 ty::Adt(adt_def, _) => Ok(adt_def.variants[variant_index].fields.len()),
691 .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT");
697 /// Returns the total number of fields in a tuple used within a Tuple pattern.
698 /// Here `pat_hir_id` is the HirId of the pattern itself.
699 fn total_fields_in_tuple(&self, pat_hir_id: hir::HirId, span: Span) -> McResult<usize> {
700 let ty = self.tables.node_type(pat_hir_id);
702 ty::Tuple(substs) => Ok(substs.len()),
704 self.tcx().sess.delay_span_bug(span, "tuple pattern not applied to a tuple");
710 // FIXME(#19596) This is a workaround, but there should be a better way to do this
713 mut place_with_id: PlaceWithHirId<'tcx>,
718 F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>),
720 // Here, `place` is the `PlaceWithHirId` being matched and pat is the pattern it
721 // is being matched against.
723 // In general, the way that this works is that we walk down the pattern,
724 // constructing a `PlaceWithHirId` that represents the path that will be taken
725 // to reach the value being matched.
727 debug!("cat_pattern(pat={:?}, place_with_id={:?})", pat, place_with_id);
729 // If (pattern) adjustments are active for this pattern, adjust the `PlaceWithHirId` correspondingly.
730 // `PlaceWithHirId`s are constructed differently from patterns. For example, in
734 // &&Some(x, ) => { ... },
739 // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
740 // corresponding `PlaceWithHirId` we start with the `PlaceWithHirId` for `foo`, and then, by traversing the
741 // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
743 // `&&Some(x,)` `place_foo`
744 // `&Some(x,)` `deref { place_foo}`
745 // `Some(x,)` `deref { deref { place_foo }}`
746 // (x,)` `field0 { deref { deref { place_foo }}}` <- resulting place
748 // The above example has no adjustments. If the code were instead the (after adjustments,
749 // equivalent) version
753 // Some(x, ) => { ... },
758 // Then we see that to get the same result, we must start with
759 // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)`
760 // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`.
761 for _ in 0..self.tables.pat_adjustments().get(pat.hir_id).map(|v| v.len()).unwrap_or(0) {
762 debug!("cat_pattern: applying adjustment to place_with_id={:?}", place_with_id);
763 place_with_id = self.cat_deref(pat, place_with_id)?;
765 let place_with_id = place_with_id; // lose mutability
766 debug!("cat_pattern: applied adjustment derefs to get place_with_id={:?}", place_with_id);
768 // Invoke the callback, but only now, after the `place_with_id` has adjusted.
770 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
771 // case, the initial `place_with_id` will be that for `&Some(3)` and the pattern is `Some(x)`. We
772 // don't want to call `op` with these incompatible values. As written, what happens instead
773 // is that `op` is called with the adjusted place (that for `*&Some(3)`) and the pattern
774 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
775 // result in the place `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
776 // that (where the `ref` on `x` is implied).
777 op(&place_with_id, pat);
780 PatKind::Tuple(ref subpats, dots_pos) => {
782 let total_fields = self.total_fields_in_tuple(pat.hir_id, pat.span)?;
784 for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
785 let subpat_ty = self.pat_ty_adjusted(&subpat)?;
786 let projection_kind = ProjectionKind::Field(i as u32, VariantIdx::new(0));
788 self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind);
789 self.cat_pattern_(sub_place, &subpat, op)?;
793 PatKind::TupleStruct(ref qpath, ref subpats, dots_pos) => {
795 let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?;
797 self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat.span)?;
799 for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
800 let subpat_ty = self.pat_ty_adjusted(&subpat)?;
801 let projection_kind = ProjectionKind::Field(i as u32, variant_index);
803 self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind);
804 self.cat_pattern_(sub_place, &subpat, op)?;
808 PatKind::Struct(ref qpath, field_pats, _) => {
809 // S { f1: p1, ..., fN: pN }
811 let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?;
813 for fp in field_pats {
814 let field_ty = self.pat_ty_adjusted(&fp.pat)?;
815 let field_index = self
820 .expect("no index for a field");
822 let field_place = self.cat_projection(
824 place_with_id.clone(),
826 ProjectionKind::Field(field_index as u32, variant_index),
828 self.cat_pattern_(field_place, &fp.pat, op)?;
832 PatKind::Or(pats) => {
834 self.cat_pattern_(place_with_id.clone(), &pat, op)?;
838 PatKind::Binding(.., Some(ref subpat)) => {
839 self.cat_pattern_(place_with_id, &subpat, op)?;
842 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
843 // box p1, &p1, &mut p1. we can ignore the mutability of
844 // PatKind::Ref since that information is already contained
846 let subplace = self.cat_deref(pat, place_with_id)?;
847 self.cat_pattern_(subplace, &subpat, op)?;
850 PatKind::Slice(before, ref slice, after) => {
851 let element_ty = match place_with_id.place.ty().builtin_index() {
854 debug!("explicit index of non-indexable type {:?}", place_with_id);
858 let elt_place = self.cat_projection(
860 place_with_id.clone(),
862 ProjectionKind::Index,
864 for before_pat in before {
865 self.cat_pattern_(elt_place.clone(), &before_pat, op)?;
867 if let Some(ref slice_pat) = *slice {
868 let slice_pat_ty = self.pat_ty_adjusted(&slice_pat)?;
869 let slice_place = self.cat_projection(
873 ProjectionKind::Subslice,
875 self.cat_pattern_(slice_place, &slice_pat, op)?;
877 for after_pat in after {
878 self.cat_pattern_(elt_place.clone(), &after_pat, op)?;
883 | PatKind::Binding(.., None)