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 #![allow(non_camel_case_types)]
53 pub use self::PointerKind::*;
54 pub use self::InteriorKind::*;
55 pub use self::MutabilityCategory::*;
56 pub use self::AliasableReason::*;
57 pub use self::Note::*;
59 use self::Aliasability::*;
61 use crate::middle::region;
62 use crate::hir::def_id::{DefId, LocalDefId};
64 use crate::infer::InferCtxt;
65 use crate::hir::def::{Def, CtorKind};
66 use crate::ty::adjustment;
67 use crate::ty::{self, Ty, TyCtxt};
68 use crate::ty::fold::TypeFoldable;
69 use crate::ty::layout::VariantIdx;
71 use crate::hir::{MutImmutable, MutMutable, PatKind};
72 use crate::hir::pat_util::EnumerateAndAdjustIterator;
74 use syntax::ast::{self, Name};
79 use std::hash::{Hash, Hasher};
80 use rustc_data_structures::sync::Lrc;
81 use rustc_data_structures::indexed_vec::Idx;
83 use crate::util::nodemap::ItemLocalSet;
85 #[derive(Clone, Debug, PartialEq)]
86 pub enum Categorization<'tcx> {
87 Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
88 ThreadLocal(ty::Region<'tcx>), // value that cannot move, but still restricted in scope
90 Upvar(Upvar), // upvar referenced by closure env
91 Local(ast::NodeId), // local variable
92 Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
93 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
94 Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
96 // (*1) downcast is only required if the enum has more than one variant
99 // Represents any kind of upvar
100 #[derive(Clone, Copy, PartialEq)]
103 pub kind: ty::ClosureKind
106 // different kinds of pointers:
107 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108 pub enum PointerKind<'tcx> {
113 BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
116 UnsafePtr(hir::Mutability),
119 // We use the term "interior" to mean "something reachable from the
120 // base without a pointer dereference", e.g., a field
121 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
122 pub enum InteriorKind {
123 InteriorField(FieldIndex),
124 InteriorElement(InteriorOffsetKind),
127 // Contains index of a field that is actually used for loan path comparisons and
128 // string representation of the field that should be used only for diagnostics.
129 #[derive(Clone, Copy, Eq)]
130 pub struct FieldIndex(pub usize, pub Name);
132 impl PartialEq for FieldIndex {
133 fn eq(&self, rhs: &Self) -> bool {
138 impl Hash for FieldIndex {
139 fn hash<H: Hasher>(&self, h: &mut H) {
144 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
145 pub enum InteriorOffsetKind {
146 Index, // e.g., `array_expr[index_expr]`
147 Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }`
150 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
151 pub enum MutabilityCategory {
152 McImmutable, // Immutable.
153 McDeclared, // Directly declared as mutable.
154 McInherited, // Inherited from the fact that owner is mutable.
157 // A note about the provenance of a `cmt`. This is used for
158 // special-case handling of upvars such as mutability inference.
159 // Upvar categorization can generate a variable number of nested
160 // derefs. The note allows detecting them without deep pattern
161 // matching on the categorization.
162 #[derive(Clone, Copy, PartialEq, Debug)]
164 NoteClosureEnv(ty::UpvarId), // Deref through closure env
165 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
166 NoteIndex, // Deref as part of desugaring `x[]` into its two components
167 NoteNone // Nothing special
170 // `cmt`: "Category, Mutability, and Type".
172 // a complete categorization of a value indicating where it originated
173 // and how it is located, as well as the mutability of the memory in
174 // which the value is stored.
176 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
177 // result of `node_type(cmt.id)`.
179 // (FIXME: rewrite the following comment given that `@x` managed
180 // pointers have been obsolete for quite some time.)
182 // This is because the `id` is always the `id` of the node producing the
183 // type; in an expression like `*x`, the type of this deref node is the
184 // deref'd type (`T`), but in a pattern like `@x`, the `@x` pattern is
185 // again a dereference, but its type is the type *before* the
186 // dereference (`@T`). So use `cmt.ty` to find the type of the value in
187 // a consistent fashion. For more details, see the method `cat_pattern`
188 #[derive(Clone, Debug, PartialEq)]
189 pub struct cmt_<'tcx> {
190 pub hir_id: hir::HirId, // HIR id of expr/pat producing this value
191 pub span: Span, // span of same expr/pat
192 pub cat: Categorization<'tcx>, // categorization of expr
193 pub mutbl: MutabilityCategory, // mutability of expr as place
194 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
195 pub note: Note, // Note about the provenance of this cmt
198 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
200 pub enum ImmutabilityBlame<'tcx> {
201 ImmLocal(ast::NodeId),
202 ClosureEnv(LocalDefId),
203 LocalDeref(ast::NodeId),
204 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
207 impl<'tcx> cmt_<'tcx> {
208 fn resolve_field(&self, field_index: usize) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
210 let adt_def = match self.ty.sty {
211 ty::Adt(def, _) => def,
212 ty::Tuple(..) => return None,
213 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
214 _ => bug!("interior cmt {:?} is not an ADT", self)
216 let variant_def = match self.cat {
217 Categorization::Downcast(_, variant_did) => {
218 adt_def.variant_with_id(variant_did)
221 assert_eq!(adt_def.variants.len(), 1);
222 &adt_def.variants[VariantIdx::new(0)]
225 Some((adt_def, &variant_def.fields[field_index]))
228 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
230 Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) => {
231 // try to figure out where the immutable reference came from
233 Categorization::Local(node_id) =>
234 Some(ImmutabilityBlame::LocalDeref(node_id)),
235 Categorization::Interior(ref base_cmt, InteriorField(field_index)) => {
236 base_cmt.resolve_field(field_index.0).map(|(adt_def, field_def)| {
237 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
240 Categorization::Upvar(Upvar { id, .. }) => {
241 if let NoteClosureEnv(..) = self.note {
242 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
250 Categorization::Local(node_id) => {
251 Some(ImmutabilityBlame::ImmLocal(node_id))
253 Categorization::Rvalue(..) |
254 Categorization::Upvar(..) |
255 Categorization::Deref(_, UnsafePtr(..)) => {
256 // This should not be reachable up to inference limitations.
259 Categorization::Interior(ref base_cmt, _) |
260 Categorization::Downcast(ref base_cmt, _) |
261 Categorization::Deref(ref base_cmt, _) => {
262 base_cmt.immutability_blame()
264 Categorization::ThreadLocal(..) |
265 Categorization::StaticItem => {
266 // Do we want to do something here?
274 fn hir_id(&self) -> hir::HirId;
275 fn span(&self) -> Span;
278 impl HirNode for hir::Expr {
279 fn hir_id(&self) -> hir::HirId { self.hir_id }
280 fn span(&self) -> Span { self.span }
283 impl HirNode for hir::Pat {
284 fn hir_id(&self) -> hir::HirId { self.hir_id }
285 fn span(&self) -> Span { self.span }
289 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
290 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
291 pub region_scope_tree: &'a region::ScopeTree,
292 pub tables: &'a ty::TypeckTables<'tcx>,
293 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>,
294 infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>,
297 pub type McResult<T> = Result<T, ()>;
299 impl MutabilityCategory {
300 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
302 MutImmutable => McImmutable,
303 MutMutable => McDeclared
305 debug!("MutabilityCategory::{}({:?}) => {:?}",
306 "from_mutbl", m, ret);
310 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
311 let ret = match borrow_kind {
312 ty::ImmBorrow => McImmutable,
313 ty::UniqueImmBorrow => McImmutable,
314 ty::MutBorrow => McDeclared,
316 debug!("MutabilityCategory::{}({:?}) => {:?}",
317 "from_borrow_kind", borrow_kind, ret);
321 fn from_pointer_kind(base_mutbl: MutabilityCategory,
322 ptr: PointerKind<'_>) -> MutabilityCategory {
323 let ret = match ptr {
327 BorrowedPtr(borrow_kind, _) => {
328 MutabilityCategory::from_borrow_kind(borrow_kind)
331 MutabilityCategory::from_mutbl(m)
334 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
335 "from_pointer_kind", base_mutbl, ptr, ret);
339 fn from_local(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>,
340 id: ast::NodeId) -> MutabilityCategory {
341 let ret = match tcx.hir().get(id) {
342 Node::Binding(p) => match p.node {
343 PatKind::Binding(..) => {
344 let bm = *tables.pat_binding_modes()
346 .expect("missing binding mode");
347 if bm == ty::BindByValue(hir::MutMutable) {
353 _ => span_bug!(p.span, "expected identifier pattern")
355 _ => span_bug!(tcx.hir().span(id), "expected identifier pattern")
357 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
358 "from_local", id, ret);
362 pub fn inherit(&self) -> MutabilityCategory {
363 let ret = match *self {
364 McImmutable => McImmutable,
365 McDeclared => McInherited,
366 McInherited => McInherited,
368 debug!("{:?}.inherit() => {:?}", self, ret);
372 pub fn is_mutable(&self) -> bool {
373 let ret = match *self {
374 McImmutable => false,
378 debug!("{:?}.is_mutable() => {:?}", self, ret);
382 pub fn is_immutable(&self) -> bool {
383 let ret = match *self {
385 McDeclared | McInherited => false
387 debug!("{:?}.is_immutable() => {:?}", self, ret);
391 pub fn to_user_str(&self) -> &'static str {
393 McDeclared | McInherited => "mutable",
394 McImmutable => "immutable",
399 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> {
400 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
401 region_scope_tree: &'a region::ScopeTree,
402 tables: &'a ty::TypeckTables<'tcx>,
403 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
404 -> MemCategorizationContext<'a, 'tcx, 'tcx> {
405 MemCategorizationContext {
409 rvalue_promotable_map,
415 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
416 /// Creates a `MemCategorizationContext` during type inference.
417 /// This is used during upvar analysis and a few other places.
418 /// Because the typeck tables are not yet complete, the results
419 /// from the analysis must be used with caution:
421 /// - rvalue promotions are not known, so the lifetimes of
422 /// temporaries may be overly conservative;
423 /// - similarly, as the results of upvar analysis are not yet
424 /// known, the results around upvar accesses may be incorrect.
425 pub fn with_infer(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
426 region_scope_tree: &'a region::ScopeTree,
427 tables: &'a ty::TypeckTables<'tcx>)
428 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
431 // Subtle: we can't do rvalue promotion analysis until the
432 // typeck phase is complete, which means that you can't trust
433 // the rvalue lifetimes that result, but that's ok, since we
434 // don't need to know those during type inference.
435 let rvalue_promotable_map = None;
437 MemCategorizationContext {
441 rvalue_promotable_map,
446 pub fn type_is_copy_modulo_regions(
448 param_env: ty::ParamEnv<'tcx>,
452 self.infcx.map(|infcx| infcx.type_is_copy_modulo_regions(param_env, ty, span))
454 self.tcx.lift_to_global(&(param_env, ty)).map(|(param_env, ty)| {
455 ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span)
461 fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
462 where T: TypeFoldable<'tcx>
464 self.infcx.map(|infcx| infcx.resolve_type_vars_if_possible(value))
465 .unwrap_or_else(|| value.clone())
468 fn is_tainted_by_errors(&self) -> bool {
469 self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
472 fn resolve_type_vars_or_error(&self,
474 ty: Option<Ty<'tcx>>)
475 -> McResult<Ty<'tcx>> {
478 let ty = self.resolve_type_vars_if_possible(&ty);
479 if ty.references_error() || ty.is_ty_var() {
480 debug!("resolve_type_vars_or_error: error from {:?}", ty);
487 None if self.is_tainted_by_errors() => Err(()),
489 let id = self.tcx.hir().hir_to_node_id(id);
490 bug!("no type for node {}: {} in mem_categorization",
491 id, self.tcx.hir().node_to_string(id));
496 pub fn node_ty(&self,
498 -> McResult<Ty<'tcx>> {
499 self.resolve_type_vars_or_error(hir_id,
500 self.tables.node_type_opt(hir_id))
503 pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
504 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
507 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
508 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
511 /// Returns the type of value that this pattern matches against.
512 /// Some non-obvious cases:
514 /// - a `ref x` binding matches against a value of type `T` and gives
515 /// `x` the type `&T`; we return `T`.
516 /// - a pattern with implicit derefs (thanks to default binding
517 /// modes #42640) may look like `Some(x)` but in fact have
518 /// implicit deref patterns attached (e.g., it is really
519 /// `&Some(x)`). In that case, we return the "outermost" type
520 /// (e.g., `&Option<T>).
521 pub fn pat_ty_adjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
522 // Check for implicit `&` types wrapping the pattern; note
523 // that these are never attached to binding patterns, so
524 // actually this is somewhat "disjoint" from the code below
525 // that aims to account for `ref x`.
526 if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
527 if let Some(first_ty) = vec.first() {
528 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
533 self.pat_ty_unadjusted(pat)
537 /// Like `pat_ty`, but ignores implicit `&` patterns.
538 fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
539 let base_ty = self.node_ty(pat.hir_id)?;
540 debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
542 // This code detects whether we are looking at a `ref x`,
543 // and if so, figures out what the type *being borrowed* is.
544 let ret_ty = match pat.node {
545 PatKind::Binding(..) => {
546 let bm = *self.tables
549 .expect("missing binding mode");
551 if let ty::BindByReference(_) = bm {
552 // a bind-by-ref means that the base_ty will be the type of the ident itself,
553 // but what we want here is the type of the underlying value being borrowed.
554 // So peel off one-level, turning the &T into T.
555 match base_ty.builtin_deref(false) {
558 debug!("By-ref binding of non-derefable type {:?}", base_ty);
568 debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
573 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
574 // This recursion helper avoids going through *too many*
575 // adjustments, since *only* non-overloaded deref recurses.
576 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
578 adjustments: &[adjustment::Adjustment<'tcx>])
579 -> McResult<cmt_<'tcx>> {
580 match adjustments.split_last() {
581 None => mc.cat_expr_unadjusted(expr),
582 Some((adjustment, previous)) => {
583 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
588 helper(self, expr, self.tables.expr_adjustments(expr))
591 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
592 previous: cmt_<'tcx>,
593 adjustment: &adjustment::Adjustment<'tcx>)
594 -> McResult<cmt_<'tcx>> {
595 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
598 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
600 adjustment: &adjustment::Adjustment<'tcx>)
601 -> McResult<cmt_<'tcx>>
602 where F: FnOnce() -> McResult<cmt_<'tcx>>
604 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
605 let target = self.resolve_type_vars_if_possible(&adjustment.target);
606 match adjustment.kind {
607 adjustment::Adjust::Deref(overloaded) => {
608 // Equivalent to *expr or something similar.
609 let base = Rc::new(if let Some(deref) = overloaded {
610 let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
614 self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty)
618 self.cat_deref(expr, base, NoteNone)
621 adjustment::Adjust::NeverToAny |
622 adjustment::Adjust::ReifyFnPointer |
623 adjustment::Adjust::UnsafeFnPointer |
624 adjustment::Adjust::ClosureFnPointer |
625 adjustment::Adjust::MutToConstPointer |
626 adjustment::Adjust::Borrow(_) |
627 adjustment::Adjust::Unsize => {
628 // Result is an rvalue.
629 Ok(self.cat_rvalue_node(expr.hir_id, expr.span, target))
634 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
635 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
637 let expr_ty = self.expr_ty(expr)?;
639 hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
640 if self.tables.is_method_call(expr) {
641 self.cat_overloaded_place(expr, e_base, NoteNone)
643 let base_cmt = Rc::new(self.cat_expr(&e_base)?);
644 self.cat_deref(expr, base_cmt, NoteNone)
648 hir::ExprKind::Field(ref base, f_ident) => {
649 let base_cmt = Rc::new(self.cat_expr(&base)?);
650 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
654 let f_index = self.tcx.field_index(expr.id, self.tables);
655 Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
658 hir::ExprKind::Index(ref base, _) => {
659 if self.tables.is_method_call(expr) {
660 // If this is an index implemented by a method call, then it
661 // will include an implicit deref of the result.
662 // The call to index() returns a `&T` value, which
663 // is an rvalue. That is what we will be
665 self.cat_overloaded_place(expr, base, NoteIndex)
667 let base_cmt = Rc::new(self.cat_expr(&base)?);
668 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
672 hir::ExprKind::Path(ref qpath) => {
673 let def = self.tables.qpath_def(qpath, expr.hir_id);
674 self.cat_def(expr.hir_id, expr.span, expr_ty, def)
677 hir::ExprKind::Type(ref e, _) => {
681 hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
682 hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
683 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
684 hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
685 hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) |
686 hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::If(..) |
687 hir::ExprKind::Binary(..) | hir::ExprKind::While(..) |
688 hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
689 hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
690 hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
691 hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Err => {
692 Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
697 pub fn cat_def(&self,
702 -> McResult<cmt_<'tcx>> {
703 debug!("cat_def: id={:?} expr={:?} def={:?}",
704 hir_id, expr_ty, def);
707 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) | Def::ConstParam(..) |
708 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) | Def::SelfCtor(..) => {
709 Ok(self.cat_rvalue_node(hir_id, span, expr_ty))
712 Def::Static(def_id, mutbl) => {
713 // `#[thread_local]` statics may not outlive the current function, but
714 // they also cannot be moved out of.
715 let is_thread_local = self.tcx.get_attrs(def_id)[..]
717 .any(|attr| attr.check_name("thread_local"));
719 let cat = if is_thread_local {
720 let re = self.temporary_scope(hir_id.local_id);
721 Categorization::ThreadLocal(re)
723 Categorization::StaticItem
730 mutbl: if mutbl { McDeclared } else { McImmutable},
736 Def::Upvar(var_id, _, fn_node_id) => {
737 self.cat_upvar(hir_id, span, var_id, fn_node_id)
744 cat: Categorization::Local(vid),
745 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
751 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
755 // Categorize an upvar, complete with invisible derefs of closure
756 // environment and upvar reference as appropriate.
761 fn_node_id: ast::NodeId)
762 -> McResult<cmt_<'tcx>>
764 let fn_hir_id = self.tcx.hir().node_to_hir_id(fn_node_id);
766 // An upvar can have up to 3 components. We translate first to a
767 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
768 // field from the environment.
770 // `Categorization::Upvar`. Next, we add a deref through the implicit
771 // environment pointer with an anonymous free region 'env and
772 // appropriate borrow kind for closure kinds that take self by
773 // reference. Finally, if the upvar was captured
774 // by-reference, we add a deref through that reference. The
775 // region of this reference is an inference variable 'up that
776 // was previously generated and recorded in the upvar borrow
777 // map. The borrow kind bk is inferred by based on how the
780 // This results in the following table for concrete closure
784 // ---------------+----------------------+-------------------------------
785 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
786 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
787 // FnOnce | copied | upvar -> &'up bk
789 let kind = match self.node_ty(fn_hir_id)?.sty {
790 ty::Generator(..) => ty::ClosureKind::FnOnce,
791 ty::Closure(closure_def_id, closure_substs) => {
793 // During upvar inference we may not know the
794 // closure kind, just use the LATTICE_BOTTOM value.
796 infcx.closure_kind(closure_def_id, closure_substs)
797 .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
800 self.tcx.global_tcx()
801 .lift(&closure_substs)
802 .expect("no inference cx, but inference variables in closure ty")
803 .closure_kind(closure_def_id, self.tcx.global_tcx()),
806 ref t => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", t),
809 let closure_expr_def_id = self.tcx.hir().local_def_id(fn_node_id);
810 let var_hir_id = self.tcx.hir().node_to_hir_id(var_id);
811 let upvar_id = ty::UpvarId {
812 var_path: ty::UpvarPath { hir_id: var_hir_id },
813 closure_expr_id: closure_expr_def_id.to_local(),
816 let var_ty = self.node_ty(var_hir_id)?;
818 // Mutability of original variable itself
819 let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
821 // Construct the upvar. This represents access to the field
822 // from the environment (perhaps we should eventually desugar
823 // this field further, but it will do for now).
824 let cmt_result = cmt_ {
827 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
833 // If this is a `FnMut` or `Fn` closure, then the above is
834 // conceptually a `&mut` or `&` reference, so we have to add a
836 let cmt_result = match kind {
837 ty::ClosureKind::FnOnce => {
840 ty::ClosureKind::FnMut => {
841 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
843 ty::ClosureKind::Fn => {
844 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
848 // If this is a by-ref capture, then the upvar we loaded is
849 // actually a reference, so we have to add an implicit deref
851 let upvar_capture = self.tables.upvar_capture(upvar_id);
852 let cmt_result = match upvar_capture {
853 ty::UpvarCapture::ByValue => {
856 ty::UpvarCapture::ByRef(upvar_borrow) => {
857 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
861 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
862 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
864 note: NoteUpvarRef(upvar_id)
869 let ret = cmt_result;
870 debug!("cat_upvar ret={:?}", ret);
877 upvar_id: ty::UpvarId,
878 upvar_mutbl: MutabilityCategory,
879 env_borrow_kind: ty::BorrowKind,
880 cmt_result: cmt_<'tcx>)
883 // Region of environment pointer
884 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
885 // The environment of a closure is guaranteed to
886 // outlive any bindings introduced in the body of the
888 scope: upvar_id.closure_expr_id.to_def_id(),
889 bound_region: ty::BrEnv
892 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
894 let var_ty = cmt_result.ty;
896 // We need to add the env deref. This means
897 // that the above is actually immutable and
898 // has a ref type. However, nothing should
899 // actually look at the type, so we can get
900 // away with stuffing a `Error` in there
901 // instead of bothering to construct a proper
903 let cmt_result = cmt_ {
905 ty: self.tcx.types.err,
909 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
911 // Issue #18335. If variable is declared as immutable, override the
912 // mutability from the environment and substitute an `&T` anyway.
914 McImmutable => { deref_mutbl = McImmutable; }
915 McDeclared | McInherited => { }
921 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
924 note: NoteClosureEnv(upvar_id)
927 debug!("env_deref ret {:?}", ret);
932 /// Returns the lifetime of a temporary created by expr with id `id`.
933 /// This could be `'static` if `id` is part of a constant expression.
934 pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
935 let scope = self.region_scope_tree.temporary_scope(id);
936 self.tcx.mk_region(match scope {
937 Some(scope) => ty::ReScope(scope),
942 pub fn cat_rvalue_node(&self,
947 debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
948 hir_id, span, expr_ty);
950 let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
953 debug!("cat_rvalue_node: promotable = {:?}", promotable);
955 // Always promote `[T; 0]` (even when e.g., borrowed mutably).
956 let promotable = match expr_ty.sty {
957 ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true,
961 debug!("cat_rvalue_node: promotable = {:?} (2)", promotable);
963 // Compute maximum lifetime of this rvalue. This is 'static if
964 // we can promote to a constant, otherwise equal to enclosing temp
966 let re = if promotable {
967 self.tcx.types.re_static
969 self.temporary_scope(hir_id.local_id)
971 let ret = self.cat_rvalue(hir_id, span, re, expr_ty);
972 debug!("cat_rvalue_node ret {:?}", ret);
976 pub fn cat_rvalue(&self,
977 cmt_hir_id: hir::HirId,
979 temp_scope: ty::Region<'tcx>,
980 expr_ty: Ty<'tcx>) -> cmt_<'tcx> {
984 cat:Categorization::Rvalue(temp_scope),
989 debug!("cat_rvalue ret {:?}", ret);
993 pub fn cat_field<N: HirNode>(&self,
1001 hir_id: node.hir_id(),
1003 mutbl: base_cmt.mutbl.inherit(),
1004 cat: Categorization::Interior(base_cmt,
1005 InteriorField(FieldIndex(f_index, f_ident.name))),
1009 debug!("cat_field ret {:?}", ret);
1013 fn cat_overloaded_place(
1018 ) -> McResult<cmt_<'tcx>> {
1019 debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
1024 // Reconstruct the output assuming it's a reference with the
1025 // same region and mutability as the receiver. This holds for
1026 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1027 let place_ty = self.expr_ty(expr)?;
1028 let base_ty = self.expr_ty_adjusted(base)?;
1030 let (region, mutbl) = match base_ty.sty {
1031 ty::Ref(region, _, mutbl) => (region, mutbl),
1032 _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
1034 let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
1039 let base_cmt = Rc::new(self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty));
1040 self.cat_deref(expr, base_cmt, note)
1045 node: &impl HirNode,
1046 base_cmt: cmt<'tcx>,
1048 ) -> McResult<cmt_<'tcx>> {
1049 debug!("cat_deref: base_cmt={:?}", base_cmt);
1051 let base_cmt_ty = base_cmt.ty;
1052 let deref_ty = match base_cmt_ty.builtin_deref(true) {
1055 debug!("Explicit deref of non-derefable type: {:?}", base_cmt_ty);
1060 let ptr = match base_cmt.ty.sty {
1061 ty::Adt(def, ..) if def.is_box() => Unique,
1062 ty::RawPtr(ref mt) => UnsafePtr(mt.mutbl),
1063 ty::Ref(r, _, mutbl) => {
1064 let bk = ty::BorrowKind::from_mutbl(mutbl);
1067 ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
1070 hir_id: node.hir_id(),
1072 // For unique ptrs, we inherit mutability from the owning reference.
1073 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1074 cat: Categorization::Deref(base_cmt, ptr),
1078 debug!("cat_deref ret {:?}", ret);
1082 fn cat_index<N: HirNode>(&self,
1084 base_cmt: cmt<'tcx>,
1085 element_ty: Ty<'tcx>,
1086 context: InteriorOffsetKind)
1087 -> McResult<cmt_<'tcx>> {
1088 //! Creates a cmt for an indexing operation (`[]`).
1090 //! One subtle aspect of indexing that may not be
1091 //! immediately obvious: for anything other than a fixed-length
1092 //! vector, an operation like `x[y]` actually consists of two
1093 //! disjoint (from the point of view of borrowck) operations.
1094 //! The first is a deref of `x` to create a pointer `p` that points
1095 //! at the first element in the array. The second operation is
1096 //! an index which adds `y*sizeof(T)` to `p` to obtain the
1097 //! pointer to `x[y]`. `cat_index` will produce a resulting
1098 //! cmt containing both this deref and the indexing,
1099 //! presuming that `base_cmt` is not of fixed-length type.
1102 //! - `elt`: the HIR node being indexed
1103 //! - `base_cmt`: the cmt of `elt`
1105 let interior_elem = InteriorElement(context);
1106 let ret = self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1107 debug!("cat_index ret {:?}", ret);
1111 pub fn cat_imm_interior<N:HirNode>(&self,
1113 base_cmt: cmt<'tcx>,
1114 interior_ty: Ty<'tcx>,
1115 interior: InteriorKind)
1118 hir_id: node.hir_id(),
1120 mutbl: base_cmt.mutbl.inherit(),
1121 cat: Categorization::Interior(base_cmt, interior),
1125 debug!("cat_imm_interior ret={:?}", ret);
1129 pub fn cat_downcast_if_needed<N:HirNode>(&self,
1131 base_cmt: cmt<'tcx>,
1134 // univariant enums do not need downcasts
1135 let base_did = self.tcx.parent_def_id(variant_did).unwrap();
1136 if self.tcx.adt_def(base_did).variants.len() != 1 {
1137 let base_ty = base_cmt.ty;
1138 let ret = Rc::new(cmt_ {
1139 hir_id: node.hir_id(),
1141 mutbl: base_cmt.mutbl.inherit(),
1142 cat: Categorization::Downcast(base_cmt, variant_did),
1146 debug!("cat_downcast ret={:?}", ret);
1149 debug!("cat_downcast univariant={:?}", base_cmt);
1154 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1155 where F: FnMut(cmt<'tcx>, &hir::Pat),
1157 self.cat_pattern_(cmt, pat, &mut op)
1160 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1161 fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1162 where F : FnMut(cmt<'tcx>, &hir::Pat)
1164 // Here, `cmt` is the categorization for the value being
1165 // matched and pat is the pattern it is being matched against.
1167 // In general, the way that this works is that we walk down
1168 // the pattern, constructing a cmt that represents the path
1169 // that will be taken to reach the value being matched.
1171 // When we encounter named bindings, we take the cmt that has
1172 // been built up and pass it off to guarantee_valid() so that
1173 // we can be sure that the binding will remain valid for the
1174 // duration of the arm.
1176 // (*2) There is subtlety concerning the correspondence between
1177 // pattern ids and types as compared to *expression* ids and
1178 // types. This is explained briefly. on the definition of the
1179 // type `cmt`, so go off and read what it says there, then
1180 // come back and I'll dive into a bit more detail here. :) OK,
1183 // In general, the id of the cmt should be the node that
1184 // "produces" the value---patterns aren't executable code
1185 // exactly, but I consider them to "execute" when they match a
1186 // value, and I consider them to produce the value that was
1187 // matched. So if you have something like:
1189 // (FIXME: `@@3` is not legal code anymore!)
1196 // In this case, the cmt and the relevant ids would be:
1198 // CMT Id Type of Id Type of cmt
1201 // ^~~~~~~^ `x` from discr @@int @@int
1202 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1203 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1205 // You can see that the types of the id and the cmt are in
1206 // sync in the first line, because that id is actually the id
1207 // of an expression. But once we get to pattern ids, the types
1208 // step out of sync again. So you'll see below that we always
1209 // get the type of the *subpattern* and use that.
1211 debug!("cat_pattern(pat={:?}, cmt={:?})", pat, cmt);
1213 // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1214 // `cmt`s are constructed differently from patterns. For example, in
1218 // &&Some(x, ) => { ... },
1223 // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1224 // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1225 // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1227 // `&&Some(x,)` `cmt_foo`
1228 // `&Some(x,)` `deref { cmt_foo}`
1229 // `Some(x,)` `deref { deref { cmt_foo }}`
1230 // (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1232 // The above example has no adjustments. If the code were instead the (after adjustments,
1233 // equivalent) version
1237 // Some(x, ) => { ... },
1242 // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1243 // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1244 // though its assigned type is that of `&&Some(x,)`.
1245 for _ in 0..self.tables
1251 debug!("cat_pattern: applying adjustment to cmt={:?}", cmt);
1252 cmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1254 let cmt = cmt; // lose mutability
1255 debug!("cat_pattern: applied adjustment derefs to get cmt={:?}", cmt);
1257 // Invoke the callback, but only now, after the `cmt` has adjusted.
1259 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1260 // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1261 // don't want to call `op` with these incompatible values. As written, what happens instead
1262 // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1263 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1264 // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1265 // that (where the `ref` on `x` is implied).
1266 op(cmt.clone(), pat);
1269 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1270 let def = self.tables.qpath_def(qpath, pat.hir_id);
1271 let (cmt, expected_len) = match def {
1273 debug!("access to unresolvable pattern {:?}", pat);
1276 Def::VariantCtor(def_id, CtorKind::Fn) => {
1277 let enum_def = self.tcx.parent_def_id(def_id).unwrap();
1278 (self.cat_downcast_if_needed(pat, cmt, def_id),
1279 self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1281 Def::StructCtor(_, CtorKind::Fn) | Def::SelfCtor(..) => {
1282 match self.pat_ty_unadjusted(&pat)?.sty {
1283 ty::Adt(adt_def, _) => {
1284 (cmt, adt_def.non_enum_variant().fields.len())
1288 "tuple struct pattern unexpected type {:?}", ty);
1293 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1294 to variant or struct {:?}", def);
1298 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1299 let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1300 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1301 let subcmt = Rc::new(
1302 self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1303 self.cat_pattern_(subcmt, &subpat, op)?;
1307 PatKind::Struct(ref qpath, ref field_pats, _) => {
1308 // {f1: p1, ..., fN: pN}
1309 let def = self.tables.qpath_def(qpath, pat.hir_id);
1310 let cmt = match def {
1312 debug!("access to unresolvable pattern {:?}", pat);
1315 Def::Variant(variant_did) |
1316 Def::VariantCtor(variant_did, ..) => {
1317 self.cat_downcast_if_needed(pat, cmt, variant_did)
1322 for fp in field_pats {
1323 let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
1324 let f_index = self.tcx.field_index(fp.node.id, self.tables);
1325 let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
1326 fp.node.ident, field_ty));
1327 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1331 PatKind::Binding(.., Some(ref subpat)) => {
1332 self.cat_pattern_(cmt, &subpat, op)?;
1335 PatKind::Tuple(ref subpats, ddpos) => {
1337 let expected_len = match self.pat_ty_unadjusted(&pat)?.sty {
1338 ty::Tuple(ref tys) => tys.len(),
1339 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1341 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1342 let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1343 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1344 let subcmt = Rc::new(
1345 self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1346 self.cat_pattern_(subcmt, &subpat, op)?;
1350 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1351 // box p1, &p1, &mut p1. we can ignore the mutability of
1352 // PatKind::Ref since that information is already contained
1354 let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1355 self.cat_pattern_(subcmt, &subpat, op)?;
1358 PatKind::Slice(ref before, ref slice, ref after) => {
1359 let element_ty = match cmt.ty.builtin_index() {
1362 debug!("Explicit index of non-indexable type {:?}", cmt);
1366 let context = InteriorOffsetKind::Pattern;
1367 let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
1368 for before_pat in before {
1369 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1371 if let Some(ref slice_pat) = *slice {
1372 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1374 for after_pat in after {
1375 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1379 PatKind::Path(_) | PatKind::Binding(.., None) |
1380 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1389 #[derive(Clone, Debug)]
1390 pub enum Aliasability {
1391 FreelyAliasable(AliasableReason),
1393 ImmutableUnique(Box<Aliasability>),
1396 #[derive(Copy, Clone, Debug)]
1397 pub enum AliasableReason {
1403 impl<'tcx> cmt_<'tcx> {
1404 pub fn guarantor(&self) -> cmt_<'tcx> {
1405 //! Returns `self` after stripping away any derefs or
1406 //! interior content. The return value is basically the `cmt` which
1407 //! determines how long the value in `self` remains live.
1410 Categorization::Rvalue(..) |
1411 Categorization::StaticItem |
1412 Categorization::ThreadLocal(..) |
1413 Categorization::Local(..) |
1414 Categorization::Deref(_, UnsafePtr(..)) |
1415 Categorization::Deref(_, BorrowedPtr(..)) |
1416 Categorization::Upvar(..) => {
1419 Categorization::Downcast(ref b, _) |
1420 Categorization::Interior(ref b, _) |
1421 Categorization::Deref(ref b, Unique) => {
1427 /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1428 pub fn freely_aliasable(&self) -> Aliasability {
1429 // Maybe non-obvious: copied upvars can only be considered
1430 // non-aliasable in once closures, since any other kind can be
1431 // aliased and eventually recused.
1434 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1435 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1436 Categorization::Deref(ref b, Unique) |
1437 Categorization::Downcast(ref b, _) |
1438 Categorization::Interior(ref b, _) => {
1439 // Aliasability depends on base cmt
1440 b.freely_aliasable()
1443 Categorization::Rvalue(..) |
1444 Categorization::ThreadLocal(..) |
1445 Categorization::Local(..) |
1446 Categorization::Upvar(..) |
1447 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1451 Categorization::StaticItem => {
1452 if self.mutbl.is_mutable() {
1453 FreelyAliasable(AliasableStaticMut)
1455 FreelyAliasable(AliasableStatic)
1459 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) => {
1460 FreelyAliasable(AliasableBorrowed)
1465 // Digs down through one or two layers of deref and grabs the
1466 // Categorization of the cmt for the upvar if a note indicates there is
1468 pub fn upvar_cat(&self) -> Option<&Categorization<'tcx>> {
1470 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1471 Some(match self.cat {
1472 Categorization::Deref(ref inner, _) => {
1474 Categorization::Deref(ref inner, _) => &inner.cat,
1475 Categorization::Upvar(..) => &inner.cat,
1482 NoteIndex | NoteNone => None
1486 pub fn descriptive_string(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
1488 Categorization::StaticItem => {
1489 "static item".into()
1491 Categorization::ThreadLocal(..) => {
1492 "thread-local static item".into()
1494 Categorization::Rvalue(..) => {
1497 Categorization::Local(vid) => {
1498 if tcx.hir().is_argument(vid) {
1504 Categorization::Deref(_, pk) => {
1505 match self.upvar_cat() {
1506 Some(&Categorization::Upvar(ref var)) => {
1507 var.to_string().into()
1516 "dereference of raw pointer"
1518 BorrowedPtr(..) => {
1520 NoteIndex => "indexed content",
1521 _ => "borrowed content"
1528 Categorization::Interior(_, InteriorField(..)) => {
1531 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1532 "indexed content".into()
1534 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1535 "pattern-bound indexed content".into()
1537 Categorization::Upvar(ref var) => {
1538 var.to_string().into()
1540 Categorization::Downcast(ref cmt, _) => {
1541 cmt.descriptive_string(tcx).into()
1547 pub fn ptr_sigil(ptr: PointerKind<'_>) -> &'static str {
1550 BorrowedPtr(ty::ImmBorrow, _) => "&",
1551 BorrowedPtr(ty::MutBorrow, _) => "&mut",
1552 BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
1553 UnsafePtr(_) => "*",
1557 impl fmt::Debug for InteriorKind {
1558 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1560 InteriorField(FieldIndex(_, info)) => write!(f, "{}", info),
1561 InteriorElement(..) => write!(f, "[]"),
1566 impl fmt::Debug for Upvar {
1567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1568 write!(f, "{:?}/{:?}", self.id, self.kind)
1572 impl fmt::Display for Upvar {
1573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574 let kind = match self.kind {
1575 ty::ClosureKind::Fn => "Fn",
1576 ty::ClosureKind::FnMut => "FnMut",
1577 ty::ClosureKind::FnOnce => "FnOnce",
1579 write!(f, "captured outer variable in an `{}` closure", kind)