1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! The job of the categorization module is to analyze an expression to
14 //! determine what kind of memory is used in evaluating it (for example,
15 //! where dereferences occur and what kind of pointer is dereferenced;
16 //! whether the memory is mutable; etc)
18 //! Categorization effectively transforms all of our expressions into
19 //! expressions of the following forms (the actual enum has many more
20 //! possibilities, naturally, but they are all variants of these base
23 //! E = rvalue // some computed rvalue
24 //! | x // address of a local variable or argument
25 //! | *E // deref of a ptr
26 //! | E.comp // access to an interior component
28 //! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
29 //! address where the result is to be found. If Expr is a place, then this
30 //! is the address of the place. If Expr is an rvalue, this is the address of
31 //! some temporary spot in memory where the result is stored.
33 //! Now, cat_expr() classifies the expression Expr and the address A=ToAddr(Expr)
36 //! - cat: what kind of expression was this? This is a subset of the
37 //! full expression forms which only includes those that we care about
38 //! for the purpose of the analysis.
39 //! - mutbl: mutability of the address A
40 //! - ty: the type of data found at the address A
42 //! The resulting categorization tree differs somewhat from the expressions
43 //! themselves. For example, auto-derefs are explicit. Also, an index a[b] is
44 //! decomposed into two operations: a dereference to reach the array data and
45 //! then an index to jump forward to the relevant item.
47 //! ## By-reference upvars
49 //! One part of the codegen which may be non-obvious is that we translate
50 //! closure upvars into the dereference of a borrowed pointer; this more closely
51 //! resembles the runtime codegen. So, for example, if we had:
55 //! let inc = || x += y;
57 //! Then when we categorize `x` (*within* the closure) we would yield a
58 //! result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
59 //! tied to `x`. The type of `x'` will be a borrowed pointer.
61 #![allow(non_camel_case_types)]
63 pub use self::PointerKind::*;
64 pub use self::InteriorKind::*;
65 pub use self::MutabilityCategory::*;
66 pub use self::AliasableReason::*;
67 pub use self::Note::*;
69 use self::Aliasability::*;
72 use hir::def_id::{DefId, LocalDefId};
75 use hir::def::{Def, CtorKind};
77 use ty::{self, Ty, TyCtxt};
78 use ty::fold::TypeFoldable;
80 use hir::{MutImmutable, MutMutable, PatKind};
81 use hir::pat_util::EnumerateAndAdjustIterator;
83 use syntax::ast::{self, Name};
88 use std::hash::{Hash, Hasher};
89 use rustc_data_structures::sync::Lrc;
91 use util::nodemap::ItemLocalSet;
93 #[derive(Clone, Debug, PartialEq)]
94 pub enum Categorization<'tcx> {
95 Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
97 Upvar(Upvar), // upvar referenced by closure env
98 Local(ast::NodeId), // local variable
99 Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
100 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
101 Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
103 // (*1) downcast is only required if the enum has more than one variant
106 // Represents any kind of upvar
107 #[derive(Clone, Copy, PartialEq)]
110 pub kind: ty::ClosureKind
113 // different kinds of pointers:
114 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
115 pub enum PointerKind<'tcx> {
120 BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
123 UnsafePtr(hir::Mutability),
126 // We use the term "interior" to mean "something reachable from the
127 // base without a pointer dereference", e.g. a field
128 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
129 pub enum InteriorKind {
130 InteriorField(FieldIndex),
131 InteriorElement(InteriorOffsetKind),
134 // Contains index of a field that is actually used for loan path comparisons and
135 // string representation of the field that should be used only for diagnostics.
136 #[derive(Clone, Copy, Eq)]
137 pub struct FieldIndex(pub usize, pub Name);
139 impl PartialEq for FieldIndex {
140 fn eq(&self, rhs: &Self) -> bool {
145 impl Hash for FieldIndex {
146 fn hash<H: Hasher>(&self, h: &mut H) {
151 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
152 pub enum InteriorOffsetKind {
153 Index, // e.g. `array_expr[index_expr]`
154 Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
157 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
158 pub enum MutabilityCategory {
159 McImmutable, // Immutable.
160 McDeclared, // Directly declared as mutable.
161 McInherited, // Inherited from the fact that owner is mutable.
164 // A note about the provenance of a `cmt`. This is used for
165 // special-case handling of upvars such as mutability inference.
166 // Upvar categorization can generate a variable number of nested
167 // derefs. The note allows detecting them without deep pattern
168 // matching on the categorization.
169 #[derive(Clone, Copy, PartialEq, Debug)]
171 NoteClosureEnv(ty::UpvarId), // Deref through closure env
172 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
173 NoteIndex, // Deref as part of desugaring `x[]` into its two components
174 NoteNone // Nothing special
177 // `cmt`: "Category, Mutability, and Type".
179 // a complete categorization of a value indicating where it originated
180 // and how it is located, as well as the mutability of the memory in
181 // which the value is stored.
183 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
184 // result of `node_id_to_type(cmt.id)`.
186 // (FIXME: rewrite the following comment given that `@x` managed
187 // pointers have been obsolete for quite some time.)
189 // This is because the `id` is always the `id` of the node producing the
190 // type; in an expression like `*x`, the type of this deref node is the
191 // deref'd type (`T`), but in a pattern like `@x`, the `@x` pattern is
192 // again a dereference, but its type is the type *before* the
193 // dereference (`@T`). So use `cmt.ty` to find the type of the value in
194 // a consistent fashion. For more details, see the method `cat_pattern`
195 #[derive(Clone, Debug, PartialEq)]
196 pub struct cmt_<'tcx> {
197 pub hir_id: hir::HirId, // HIR id of expr/pat producing this value
198 pub span: Span, // span of same expr/pat
199 pub cat: Categorization<'tcx>, // categorization of expr
200 pub mutbl: MutabilityCategory, // mutability of expr as place
201 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
202 pub note: Note, // Note about the provenance of this cmt
205 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
207 pub enum ImmutabilityBlame<'tcx> {
208 ImmLocal(ast::NodeId),
209 ClosureEnv(LocalDefId),
210 LocalDeref(ast::NodeId),
211 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
214 impl<'tcx> cmt_<'tcx> {
215 fn resolve_field(&self, field_index: usize) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
217 let adt_def = match self.ty.sty {
218 ty::Adt(def, _) => def,
219 ty::Tuple(..) => return None,
220 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
221 _ => bug!("interior cmt {:?} is not an ADT", self)
223 let variant_def = match self.cat {
224 Categorization::Downcast(_, variant_did) => {
225 adt_def.variant_with_id(variant_did)
228 assert_eq!(adt_def.variants.len(), 1);
232 Some((adt_def, &variant_def.fields[field_index]))
235 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
237 Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) => {
238 // try to figure out where the immutable reference came from
240 Categorization::Local(node_id) =>
241 Some(ImmutabilityBlame::LocalDeref(node_id)),
242 Categorization::Interior(ref base_cmt, InteriorField(field_index)) => {
243 base_cmt.resolve_field(field_index.0).map(|(adt_def, field_def)| {
244 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
247 Categorization::Upvar(Upvar { id, .. }) => {
248 if let NoteClosureEnv(..) = self.note {
249 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
257 Categorization::Local(node_id) => {
258 Some(ImmutabilityBlame::ImmLocal(node_id))
260 Categorization::Rvalue(..) |
261 Categorization::Upvar(..) |
262 Categorization::Deref(_, UnsafePtr(..)) => {
263 // This should not be reachable up to inference limitations.
266 Categorization::Interior(ref base_cmt, _) |
267 Categorization::Downcast(ref base_cmt, _) |
268 Categorization::Deref(ref base_cmt, _) => {
269 base_cmt.immutability_blame()
271 Categorization::StaticItem => {
272 // Do we want to do something here?
280 fn hir_id(&self) -> hir::HirId;
281 fn span(&self) -> Span;
284 impl HirNode for hir::Expr {
285 fn hir_id(&self) -> hir::HirId { self.hir_id }
286 fn span(&self) -> Span { self.span }
289 impl HirNode for hir::Pat {
290 fn hir_id(&self) -> hir::HirId { self.hir_id }
291 fn span(&self) -> Span { self.span }
295 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
296 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
297 pub region_scope_tree: &'a region::ScopeTree,
298 pub tables: &'a ty::TypeckTables<'tcx>,
299 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>,
300 infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>,
303 pub type McResult<T> = Result<T, ()>;
305 impl MutabilityCategory {
306 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
308 MutImmutable => McImmutable,
309 MutMutable => McDeclared
311 debug!("MutabilityCategory::{}({:?}) => {:?}",
312 "from_mutbl", m, ret);
316 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
317 let ret = match borrow_kind {
318 ty::ImmBorrow => McImmutable,
319 ty::UniqueImmBorrow => McImmutable,
320 ty::MutBorrow => McDeclared,
322 debug!("MutabilityCategory::{}({:?}) => {:?}",
323 "from_borrow_kind", borrow_kind, ret);
327 fn from_pointer_kind(base_mutbl: MutabilityCategory,
328 ptr: PointerKind<'_>) -> MutabilityCategory {
329 let ret = match ptr {
333 BorrowedPtr(borrow_kind, _) => {
334 MutabilityCategory::from_borrow_kind(borrow_kind)
337 MutabilityCategory::from_mutbl(m)
340 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
341 "from_pointer_kind", base_mutbl, ptr, ret);
345 fn from_local(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>,
346 id: ast::NodeId) -> MutabilityCategory {
347 let ret = match tcx.hir.get(id) {
348 Node::Binding(p) => match p.node {
349 PatKind::Binding(..) => {
350 let bm = *tables.pat_binding_modes()
352 .expect("missing binding mode");
353 if bm == ty::BindByValue(hir::MutMutable) {
359 _ => span_bug!(p.span, "expected identifier pattern")
361 _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
363 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
364 "from_local", id, ret);
368 pub fn inherit(&self) -> MutabilityCategory {
369 let ret = match *self {
370 McImmutable => McImmutable,
371 McDeclared => McInherited,
372 McInherited => McInherited,
374 debug!("{:?}.inherit() => {:?}", self, ret);
378 pub fn is_mutable(&self) -> bool {
379 let ret = match *self {
380 McImmutable => false,
384 debug!("{:?}.is_mutable() => {:?}", self, ret);
388 pub fn is_immutable(&self) -> bool {
389 let ret = match *self {
391 McDeclared | McInherited => false
393 debug!("{:?}.is_immutable() => {:?}", self, ret);
397 pub fn to_user_str(&self) -> &'static str {
399 McDeclared | McInherited => "mutable",
400 McImmutable => "immutable",
405 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> {
406 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
407 region_scope_tree: &'a region::ScopeTree,
408 tables: &'a ty::TypeckTables<'tcx>,
409 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
410 -> MemCategorizationContext<'a, 'tcx, 'tcx> {
411 MemCategorizationContext {
415 rvalue_promotable_map,
421 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
422 /// Creates a `MemCategorizationContext` during type inference.
423 /// This is used during upvar analysis and a few other places.
424 /// Because the typeck tables are not yet complete, the results
425 /// from the analysis must be used with caution:
427 /// - rvalue promotions are not known, so the lifetimes of
428 /// temporaries may be overly conservative;
429 /// - similarly, as the results of upvar analysis are not yet
430 /// known, the results around upvar accesses may be incorrect.
431 pub fn with_infer(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
432 region_scope_tree: &'a region::ScopeTree,
433 tables: &'a ty::TypeckTables<'tcx>)
434 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
437 // Subtle: we can't do rvalue promotion analysis until the
438 // typeck phase is complete, which means that you can't trust
439 // the rvalue lifetimes that result, but that's ok, since we
440 // don't need to know those during type inference.
441 let rvalue_promotable_map = None;
443 MemCategorizationContext {
447 rvalue_promotable_map,
452 pub fn type_moves_by_default(&self,
453 param_env: ty::ParamEnv<'tcx>,
457 self.infcx.map(|infcx| infcx.type_moves_by_default(param_env, ty, span))
459 self.tcx.lift_to_global(&(param_env, ty)).map(|(param_env, ty)| {
460 ty.moves_by_default(self.tcx.global_tcx(), param_env, span)
466 fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
467 where T: TypeFoldable<'tcx>
469 self.infcx.map(|infcx| infcx.resolve_type_vars_if_possible(value))
470 .unwrap_or_else(|| value.clone())
473 fn is_tainted_by_errors(&self) -> bool {
474 self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
477 fn resolve_type_vars_or_error(&self,
479 ty: Option<Ty<'tcx>>)
480 -> McResult<Ty<'tcx>> {
483 let ty = self.resolve_type_vars_if_possible(&ty);
484 if ty.references_error() || ty.is_ty_var() {
485 debug!("resolve_type_vars_or_error: error from {:?}", ty);
492 None if self.is_tainted_by_errors() => Err(()),
494 let id = self.tcx.hir.hir_to_node_id(id);
495 bug!("no type for node {}: {} in mem_categorization",
496 id, self.tcx.hir.node_to_string(id));
501 pub fn node_ty(&self,
503 -> McResult<Ty<'tcx>> {
504 self.resolve_type_vars_or_error(hir_id,
505 self.tables.node_id_to_type_opt(hir_id))
508 pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
509 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
512 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
513 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
516 /// Returns the type of value that this pattern matches against.
517 /// Some non-obvious cases:
519 /// - a `ref x` binding matches against a value of type `T` and gives
520 /// `x` the type `&T`; we return `T`.
521 /// - a pattern with implicit derefs (thanks to default binding
522 /// modes #42640) may look like `Some(x)` but in fact have
523 /// implicit deref patterns attached (e.g., it is really
524 /// `&Some(x)`). In that case, we return the "outermost" type
525 /// (e.g., `&Option<T>).
526 pub fn pat_ty_adjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
527 // Check for implicit `&` types wrapping the pattern; note
528 // that these are never attached to binding patterns, so
529 // actually this is somewhat "disjoint" from the code below
530 // that aims to account for `ref x`.
531 if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
532 if let Some(first_ty) = vec.first() {
533 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
538 self.pat_ty_unadjusted(pat)
542 /// Like `pat_ty`, but ignores implicit `&` patterns.
543 fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
544 let base_ty = self.node_ty(pat.hir_id)?;
545 debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
547 // This code detects whether we are looking at a `ref x`,
548 // and if so, figures out what the type *being borrowed* is.
549 let ret_ty = match pat.node {
550 PatKind::Binding(..) => {
551 let bm = *self.tables
554 .expect("missing binding mode");
556 if let ty::BindByReference(_) = bm {
557 // a bind-by-ref means that the base_ty will be the type of the ident itself,
558 // but what we want here is the type of the underlying value being borrowed.
559 // So peel off one-level, turning the &T into T.
560 match base_ty.builtin_deref(false) {
563 debug!("By-ref binding of non-derefable type {:?}", base_ty);
573 debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
578 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
579 // This recursion helper avoids going through *too many*
580 // adjustments, since *only* non-overloaded deref recurses.
581 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
583 adjustments: &[adjustment::Adjustment<'tcx>])
584 -> McResult<cmt_<'tcx>> {
585 match adjustments.split_last() {
586 None => mc.cat_expr_unadjusted(expr),
587 Some((adjustment, previous)) => {
588 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
593 helper(self, expr, self.tables.expr_adjustments(expr))
596 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
597 previous: cmt_<'tcx>,
598 adjustment: &adjustment::Adjustment<'tcx>)
599 -> McResult<cmt_<'tcx>> {
600 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
603 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
605 adjustment: &adjustment::Adjustment<'tcx>)
606 -> McResult<cmt_<'tcx>>
607 where F: FnOnce() -> McResult<cmt_<'tcx>>
609 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
610 let target = self.resolve_type_vars_if_possible(&adjustment.target);
611 match adjustment.kind {
612 adjustment::Adjust::Deref(overloaded) => {
613 // Equivalent to *expr or something similar.
614 let base = Rc::new(if let Some(deref) = overloaded {
615 let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
619 self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty)
623 self.cat_deref(expr, base, NoteNone)
626 adjustment::Adjust::NeverToAny |
627 adjustment::Adjust::ReifyFnPointer |
628 adjustment::Adjust::UnsafeFnPointer |
629 adjustment::Adjust::ClosureFnPointer |
630 adjustment::Adjust::MutToConstPointer |
631 adjustment::Adjust::Borrow(_) |
632 adjustment::Adjust::Unsize => {
633 // Result is an rvalue.
634 Ok(self.cat_rvalue_node(expr.hir_id, expr.span, target))
639 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
640 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
642 let expr_ty = self.expr_ty(expr)?;
644 hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
645 if self.tables.is_method_call(expr) {
646 self.cat_overloaded_place(expr, e_base, NoteNone)
648 let base_cmt = Rc::new(self.cat_expr(&e_base)?);
649 self.cat_deref(expr, base_cmt, NoteNone)
653 hir::ExprKind::Field(ref base, f_ident) => {
654 let base_cmt = Rc::new(self.cat_expr(&base)?);
655 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
659 let f_index = self.tcx.field_index(expr.id, self.tables);
660 Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
663 hir::ExprKind::Index(ref base, _) => {
664 if self.tables.is_method_call(expr) {
665 // If this is an index implemented by a method call, then it
666 // will include an implicit deref of the result.
667 // The call to index() returns a `&T` value, which
668 // is an rvalue. That is what we will be
670 self.cat_overloaded_place(expr, base, NoteIndex)
672 let base_cmt = Rc::new(self.cat_expr(&base)?);
673 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
677 hir::ExprKind::Path(ref qpath) => {
678 let def = self.tables.qpath_def(qpath, expr.hir_id);
679 self.cat_def(expr.hir_id, expr.span, expr_ty, def)
682 hir::ExprKind::Type(ref e, _) => {
686 hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
687 hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
688 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
689 hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
690 hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) |
691 hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::If(..) |
692 hir::ExprKind::Binary(..) | hir::ExprKind::While(..) |
693 hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
694 hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
695 hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
696 hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) => {
697 Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
702 pub fn cat_def(&self,
707 -> McResult<cmt_<'tcx>> {
708 debug!("cat_def: id={:?} expr={:?} def={:?}",
709 hir_id, expr_ty, def);
712 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
713 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) | Def::SelfCtor(..) => {
714 Ok(self.cat_rvalue_node(hir_id, span, expr_ty))
717 Def::Static(def_id, mutbl) => {
718 // `#[thread_local]` statics may not outlive the current function.
719 for attr in &self.tcx.get_attrs(def_id)[..] {
720 if attr.check_name("thread_local") {
721 return Ok(self.cat_rvalue_node(hir_id, span, expr_ty));
728 cat:Categorization::StaticItem,
729 mutbl: if mutbl { McDeclared } else { McImmutable},
735 Def::Upvar(var_id, _, fn_node_id) => {
736 self.cat_upvar(hir_id, span, var_id, fn_node_id)
743 cat: Categorization::Local(vid),
744 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
750 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
754 // Categorize an upvar, complete with invisible derefs of closure
755 // environment and upvar reference as appropriate.
760 fn_node_id: ast::NodeId)
761 -> McResult<cmt_<'tcx>>
763 let fn_hir_id = self.tcx.hir.node_to_hir_id(fn_node_id);
765 // An upvar can have up to 3 components. We translate first to a
766 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
767 // field from the environment.
769 // `Categorization::Upvar`. Next, we add a deref through the implicit
770 // environment pointer with an anonymous free region 'env and
771 // appropriate borrow kind for closure kinds that take self by
772 // reference. Finally, if the upvar was captured
773 // by-reference, we add a deref through that reference. The
774 // region of this reference is an inference variable 'up that
775 // was previously generated and recorded in the upvar borrow
776 // map. The borrow kind bk is inferred by based on how the
779 // This results in the following table for concrete closure
783 // ---------------+----------------------+-------------------------------
784 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
785 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
786 // FnOnce | copied | upvar -> &'up bk
788 let kind = match self.node_ty(fn_hir_id)?.sty {
789 ty::Generator(..) => ty::ClosureKind::FnOnce,
790 ty::Closure(closure_def_id, closure_substs) => {
792 // During upvar inference we may not know the
793 // closure kind, just use the LATTICE_BOTTOM value.
795 infcx.closure_kind(closure_def_id, closure_substs)
796 .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
799 self.tcx.global_tcx()
800 .lift(&closure_substs)
801 .expect("no inference cx, but inference variables in closure ty")
802 .closure_kind(closure_def_id, self.tcx.global_tcx()),
805 ref t => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", t),
808 let closure_expr_def_id = self.tcx.hir.local_def_id(fn_node_id);
809 let var_hir_id = self.tcx.hir.node_to_hir_id(var_id);
810 let upvar_id = ty::UpvarId {
812 closure_expr_id: closure_expr_def_id.to_local(),
815 let var_ty = self.node_ty(var_hir_id)?;
817 // Mutability of original variable itself
818 let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
820 // Construct the upvar. This represents access to the field
821 // from the environment (perhaps we should eventually desugar
822 // this field further, but it will do for now).
823 let cmt_result = cmt_ {
826 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
832 // If this is a `FnMut` or `Fn` closure, then the above is
833 // conceptually a `&mut` or `&` reference, so we have to add a
835 let cmt_result = match kind {
836 ty::ClosureKind::FnOnce => {
839 ty::ClosureKind::FnMut => {
840 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
842 ty::ClosureKind::Fn => {
843 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
847 // If this is a by-ref capture, then the upvar we loaded is
848 // actually a reference, so we have to add an implicit deref
850 let upvar_capture = self.tables.upvar_capture(upvar_id);
851 let cmt_result = match upvar_capture {
852 ty::UpvarCapture::ByValue => {
855 ty::UpvarCapture::ByRef(upvar_borrow) => {
856 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
860 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
861 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
863 note: NoteUpvarRef(upvar_id)
868 let ret = cmt_result;
869 debug!("cat_upvar ret={:?}", ret);
876 upvar_id: ty::UpvarId,
877 upvar_mutbl: MutabilityCategory,
878 env_borrow_kind: ty::BorrowKind,
879 cmt_result: cmt_<'tcx>)
882 // Region of environment pointer
883 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
884 // The environment of a closure is guaranteed to
885 // outlive any bindings introduced in the body of the
887 scope: upvar_id.closure_expr_id.to_def_id(),
888 bound_region: ty::BrEnv
891 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
893 let var_ty = cmt_result.ty;
895 // We need to add the env deref. This means
896 // that the above is actually immutable and
897 // has a ref type. However, nothing should
898 // actually look at the type, so we can get
899 // away with stuffing a `Error` in there
900 // instead of bothering to construct a proper
902 let cmt_result = cmt_ {
904 ty: self.tcx.types.err,
908 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
910 // Issue #18335. If variable is declared as immutable, override the
911 // mutability from the environment and substitute an `&T` anyway.
913 McImmutable => { deref_mutbl = McImmutable; }
914 McDeclared | McInherited => { }
920 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
923 note: NoteClosureEnv(upvar_id)
926 debug!("env_deref ret {:?}", ret);
931 /// Returns the lifetime of a temporary created by expr with id `id`.
932 /// This could be `'static` if `id` is part of a constant expression.
933 pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
934 let scope = self.region_scope_tree.temporary_scope(id);
935 self.tcx.mk_region(match scope {
936 Some(scope) => ty::ReScope(scope),
941 pub fn cat_rvalue_node(&self,
946 debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
947 hir_id, span, expr_ty);
949 let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
952 debug!("cat_rvalue_node: promotable = {:?}", promotable);
954 // Always promote `[T; 0]` (even when e.g. borrowed mutably).
955 let promotable = match expr_ty.sty {
956 ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true,
960 debug!("cat_rvalue_node: promotable = {:?} (2)", promotable);
962 // Compute maximum lifetime of this rvalue. This is 'static if
963 // we can promote to a constant, otherwise equal to enclosing temp
965 let re = if promotable {
966 self.tcx.types.re_static
968 self.temporary_scope(hir_id.local_id)
970 let ret = self.cat_rvalue(hir_id, span, re, expr_ty);
971 debug!("cat_rvalue_node ret {:?}", ret);
975 pub fn cat_rvalue(&self,
976 cmt_hir_id: hir::HirId,
978 temp_scope: ty::Region<'tcx>,
979 expr_ty: Ty<'tcx>) -> cmt_<'tcx> {
983 cat:Categorization::Rvalue(temp_scope),
988 debug!("cat_rvalue ret {:?}", ret);
992 pub fn cat_field<N: HirNode>(&self,
1000 hir_id: node.hir_id(),
1002 mutbl: base_cmt.mutbl.inherit(),
1003 cat: Categorization::Interior(base_cmt,
1004 InteriorField(FieldIndex(f_index, f_ident.name))),
1008 debug!("cat_field ret {:?}", ret);
1012 fn cat_overloaded_place(
1017 ) -> McResult<cmt_<'tcx>> {
1018 debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
1023 // Reconstruct the output assuming it's a reference with the
1024 // same region and mutability as the receiver. This holds for
1025 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1026 let place_ty = self.expr_ty(expr)?;
1027 let base_ty = self.expr_ty_adjusted(base)?;
1029 let (region, mutbl) = match base_ty.sty {
1030 ty::Ref(region, _, mutbl) => (region, mutbl),
1031 _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
1033 let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
1038 let base_cmt = Rc::new(self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty));
1039 self.cat_deref(expr, base_cmt, note)
1044 node: &impl HirNode,
1045 base_cmt: cmt<'tcx>,
1047 ) -> McResult<cmt_<'tcx>> {
1048 debug!("cat_deref: base_cmt={:?}", base_cmt);
1050 let base_cmt_ty = base_cmt.ty;
1051 let deref_ty = match base_cmt_ty.builtin_deref(true) {
1054 debug!("Explicit deref of non-derefable type: {:?}", base_cmt_ty);
1059 let ptr = match base_cmt.ty.sty {
1060 ty::Adt(def, ..) if def.is_box() => Unique,
1061 ty::RawPtr(ref mt) => UnsafePtr(mt.mutbl),
1062 ty::Ref(r, _, mutbl) => {
1063 let bk = ty::BorrowKind::from_mutbl(mutbl);
1066 ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
1069 hir_id: node.hir_id(),
1071 // For unique ptrs, we inherit mutability from the owning reference.
1072 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1073 cat: Categorization::Deref(base_cmt, ptr),
1077 debug!("cat_deref ret {:?}", ret);
1081 fn cat_index<N: HirNode>(&self,
1083 base_cmt: cmt<'tcx>,
1084 element_ty: Ty<'tcx>,
1085 context: InteriorOffsetKind)
1086 -> McResult<cmt_<'tcx>> {
1087 //! Creates a cmt for an indexing operation (`[]`).
1089 //! One subtle aspect of indexing that may not be
1090 //! immediately obvious: for anything other than a fixed-length
1091 //! vector, an operation like `x[y]` actually consists of two
1092 //! disjoint (from the point of view of borrowck) operations.
1093 //! The first is a deref of `x` to create a pointer `p` that points
1094 //! at the first element in the array. The second operation is
1095 //! an index which adds `y*sizeof(T)` to `p` to obtain the
1096 //! pointer to `x[y]`. `cat_index` will produce a resulting
1097 //! cmt containing both this deref and the indexing,
1098 //! presuming that `base_cmt` is not of fixed-length type.
1101 //! - `elt`: the HIR node being indexed
1102 //! - `base_cmt`: the cmt of `elt`
1104 let interior_elem = InteriorElement(context);
1105 let ret = self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1106 debug!("cat_index ret {:?}", ret);
1110 pub fn cat_imm_interior<N:HirNode>(&self,
1112 base_cmt: cmt<'tcx>,
1113 interior_ty: Ty<'tcx>,
1114 interior: InteriorKind)
1117 hir_id: node.hir_id(),
1119 mutbl: base_cmt.mutbl.inherit(),
1120 cat: Categorization::Interior(base_cmt, interior),
1124 debug!("cat_imm_interior ret={:?}", ret);
1128 pub fn cat_downcast_if_needed<N:HirNode>(&self,
1130 base_cmt: cmt<'tcx>,
1133 // univariant enums do not need downcasts
1134 let base_did = self.tcx.parent_def_id(variant_did).unwrap();
1135 if self.tcx.adt_def(base_did).variants.len() != 1 {
1136 let base_ty = base_cmt.ty;
1137 let ret = Rc::new(cmt_ {
1138 hir_id: node.hir_id(),
1140 mutbl: base_cmt.mutbl.inherit(),
1141 cat: Categorization::Downcast(base_cmt, variant_did),
1145 debug!("cat_downcast ret={:?}", ret);
1148 debug!("cat_downcast univariant={:?}", base_cmt);
1153 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1154 where F: FnMut(cmt<'tcx>, &hir::Pat),
1156 self.cat_pattern_(cmt, pat, &mut op)
1159 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1160 fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1161 where F : FnMut(cmt<'tcx>, &hir::Pat)
1163 // Here, `cmt` is the categorization for the value being
1164 // matched and pat is the pattern it is being matched against.
1166 // In general, the way that this works is that we walk down
1167 // the pattern, constructing a cmt that represents the path
1168 // that will be taken to reach the value being matched.
1170 // When we encounter named bindings, we take the cmt that has
1171 // been built up and pass it off to guarantee_valid() so that
1172 // we can be sure that the binding will remain valid for the
1173 // duration of the arm.
1175 // (*2) There is subtlety concerning the correspondence between
1176 // pattern ids and types as compared to *expression* ids and
1177 // types. This is explained briefly. on the definition of the
1178 // type `cmt`, so go off and read what it says there, then
1179 // come back and I'll dive into a bit more detail here. :) OK,
1182 // In general, the id of the cmt should be the node that
1183 // "produces" the value---patterns aren't executable code
1184 // exactly, but I consider them to "execute" when they match a
1185 // value, and I consider them to produce the value that was
1186 // matched. So if you have something like:
1188 // (FIXME: `@@3` is not legal code anymore!)
1195 // In this case, the cmt and the relevant ids would be:
1197 // CMT Id Type of Id Type of cmt
1200 // ^~~~~~~^ `x` from discr @@int @@int
1201 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1202 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1204 // You can see that the types of the id and the cmt are in
1205 // sync in the first line, because that id is actually the id
1206 // of an expression. But once we get to pattern ids, the types
1207 // step out of sync again. So you'll see below that we always
1208 // get the type of the *subpattern* and use that.
1210 debug!("cat_pattern(pat={:?}, cmt={:?})", pat, cmt);
1212 // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1213 // `cmt`s are constructed differently from patterns. For example, in
1217 // &&Some(x, ) => { ... },
1222 // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1223 // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1224 // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1226 // `&&Some(x,)` `cmt_foo`
1227 // `&Some(x,)` `deref { cmt_foo}`
1228 // `Some(x,)` `deref { deref { cmt_foo }}`
1229 // (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1231 // The above example has no adjustments. If the code were instead the (after adjustments,
1232 // equivalent) version
1236 // Some(x, ) => { ... },
1241 // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1242 // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1243 // though its assigned type is that of `&&Some(x,)`.
1244 for _ in 0..self.tables
1250 debug!("cat_pattern: applying adjustment to cmt={:?}", cmt);
1251 cmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1253 let cmt = cmt; // lose mutability
1254 debug!("cat_pattern: applied adjustment derefs to get cmt={:?}", cmt);
1256 // Invoke the callback, but only now, after the `cmt` has adjusted.
1258 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1259 // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1260 // don't want to call `op` with these incompatible values. As written, what happens instead
1261 // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1262 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1263 // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1264 // that (where the `ref` on `x` is implied).
1265 op(cmt.clone(), pat);
1268 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1269 let def = self.tables.qpath_def(qpath, pat.hir_id);
1270 let (cmt, expected_len) = match def {
1272 debug!("access to unresolvable pattern {:?}", pat);
1275 Def::VariantCtor(def_id, CtorKind::Fn) => {
1276 let enum_def = self.tcx.parent_def_id(def_id).unwrap();
1277 (self.cat_downcast_if_needed(pat, cmt, def_id),
1278 self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1280 Def::StructCtor(_, CtorKind::Fn) | Def::SelfCtor(..) => {
1281 match self.pat_ty_unadjusted(&pat)?.sty {
1282 ty::Adt(adt_def, _) => {
1283 (cmt, adt_def.non_enum_variant().fields.len())
1287 "tuple struct pattern unexpected type {:?}", ty);
1292 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1293 to variant or struct {:?}", def);
1297 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1298 let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1299 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1300 let subcmt = Rc::new(
1301 self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1302 self.cat_pattern_(subcmt, &subpat, op)?;
1306 PatKind::Struct(ref qpath, ref field_pats, _) => {
1307 // {f1: p1, ..., fN: pN}
1308 let def = self.tables.qpath_def(qpath, pat.hir_id);
1309 let cmt = match def {
1311 debug!("access to unresolvable pattern {:?}", pat);
1314 Def::Variant(variant_did) |
1315 Def::VariantCtor(variant_did, ..) => {
1316 self.cat_downcast_if_needed(pat, cmt, variant_did)
1321 for fp in field_pats {
1322 let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
1323 let f_index = self.tcx.field_index(fp.node.id, self.tables);
1324 let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
1325 fp.node.ident, field_ty));
1326 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1330 PatKind::Binding(.., Some(ref subpat)) => {
1331 self.cat_pattern_(cmt, &subpat, op)?;
1334 PatKind::Tuple(ref subpats, ddpos) => {
1336 let expected_len = match self.pat_ty_unadjusted(&pat)?.sty {
1337 ty::Tuple(ref tys) => tys.len(),
1338 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1340 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1341 let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1342 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1343 let subcmt = Rc::new(
1344 self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1345 self.cat_pattern_(subcmt, &subpat, op)?;
1349 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1350 // box p1, &p1, &mut p1. we can ignore the mutability of
1351 // PatKind::Ref since that information is already contained
1353 let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1354 self.cat_pattern_(subcmt, &subpat, op)?;
1357 PatKind::Slice(ref before, ref slice, ref after) => {
1358 let element_ty = match cmt.ty.builtin_index() {
1361 debug!("Explicit index of non-indexable type {:?}", cmt);
1365 let context = InteriorOffsetKind::Pattern;
1366 let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
1367 for before_pat in before {
1368 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1370 if let Some(ref slice_pat) = *slice {
1371 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1373 for after_pat in after {
1374 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1378 PatKind::Path(_) | PatKind::Binding(.., None) |
1379 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1388 #[derive(Clone, Debug)]
1389 pub enum Aliasability {
1390 FreelyAliasable(AliasableReason),
1392 ImmutableUnique(Box<Aliasability>),
1395 #[derive(Copy, Clone, Debug)]
1396 pub enum AliasableReason {
1402 impl<'tcx> cmt_<'tcx> {
1403 pub fn guarantor(&self) -> cmt_<'tcx> {
1404 //! Returns `self` after stripping away any derefs or
1405 //! interior content. The return value is basically the `cmt` which
1406 //! determines how long the value in `self` remains live.
1409 Categorization::Rvalue(..) |
1410 Categorization::StaticItem |
1411 Categorization::Local(..) |
1412 Categorization::Deref(_, UnsafePtr(..)) |
1413 Categorization::Deref(_, BorrowedPtr(..)) |
1414 Categorization::Upvar(..) => {
1417 Categorization::Downcast(ref b, _) |
1418 Categorization::Interior(ref b, _) |
1419 Categorization::Deref(ref b, Unique) => {
1425 /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1426 pub fn freely_aliasable(&self) -> Aliasability {
1427 // Maybe non-obvious: copied upvars can only be considered
1428 // non-aliasable in once closures, since any other kind can be
1429 // aliased and eventually recused.
1432 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1433 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1434 Categorization::Deref(ref b, Unique) |
1435 Categorization::Downcast(ref b, _) |
1436 Categorization::Interior(ref b, _) => {
1437 // Aliasability depends on base cmt
1438 b.freely_aliasable()
1441 Categorization::Rvalue(..) |
1442 Categorization::Local(..) |
1443 Categorization::Upvar(..) |
1444 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1448 Categorization::StaticItem => {
1449 if self.mutbl.is_mutable() {
1450 FreelyAliasable(AliasableStaticMut)
1452 FreelyAliasable(AliasableStatic)
1456 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) => {
1457 FreelyAliasable(AliasableBorrowed)
1462 // Digs down through one or two layers of deref and grabs the
1463 // Categorization of the cmt for the upvar if a note indicates there is
1465 pub fn upvar_cat(&self) -> Option<&Categorization<'tcx>> {
1467 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1468 Some(match self.cat {
1469 Categorization::Deref(ref inner, _) => {
1471 Categorization::Deref(ref inner, _) => &inner.cat,
1472 Categorization::Upvar(..) => &inner.cat,
1479 NoteIndex | NoteNone => None
1483 pub fn descriptive_string(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
1485 Categorization::StaticItem => {
1486 "static item".into()
1488 Categorization::Rvalue(..) => {
1491 Categorization::Local(vid) => {
1492 if tcx.hir.is_argument(vid) {
1498 Categorization::Deref(_, pk) => {
1499 match self.upvar_cat() {
1500 Some(&Categorization::Upvar(ref var)) => {
1501 var.to_string().into()
1510 "dereference of raw pointer"
1512 BorrowedPtr(..) => {
1514 NoteIndex => "indexed content",
1515 _ => "borrowed content"
1522 Categorization::Interior(_, InteriorField(..)) => {
1525 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1526 "indexed content".into()
1528 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1529 "pattern-bound indexed content".into()
1531 Categorization::Upvar(ref var) => {
1532 var.to_string().into()
1534 Categorization::Downcast(ref cmt, _) => {
1535 cmt.descriptive_string(tcx).into()
1541 pub fn ptr_sigil(ptr: PointerKind<'_>) -> &'static str {
1544 BorrowedPtr(ty::ImmBorrow, _) => "&",
1545 BorrowedPtr(ty::MutBorrow, _) => "&mut",
1546 BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
1547 UnsafePtr(_) => "*",
1551 impl fmt::Debug for InteriorKind {
1552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554 InteriorField(FieldIndex(_, info)) => write!(f, "{}", info),
1555 InteriorElement(..) => write!(f, "[]"),
1560 impl fmt::Debug for Upvar {
1561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1562 write!(f, "{:?}/{:?}", self.id, self.kind)
1566 impl fmt::Display for Upvar {
1567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1568 let kind = match self.kind {
1569 ty::ClosureKind::Fn => "Fn",
1570 ty::ClosureKind::FnMut => "FnMut",
1571 ty::ClosureKind::FnOnce => "FnOnce",
1573 write!(f, "captured outer variable in an `{}` closure", kind)