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::{CtorOf, Res, DefKind, CtorKind};
66 use crate::ty::adjustment;
67 use crate::ty::{self, DefIdTree, 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::indexed_vec::Idx;
82 use crate::util::nodemap::ItemLocalSet;
84 #[derive(Clone, Debug, PartialEq)]
85 pub enum Categorization<'tcx> {
86 Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
87 ThreadLocal(ty::Region<'tcx>), // value that cannot move, but still restricted in scope
89 Upvar(Upvar), // upvar referenced by closure env
90 Local(hir::HirId), // local variable
91 Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
92 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
93 Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
95 // (*1) downcast is only required if the enum has more than one variant
98 // Represents any kind of upvar
99 #[derive(Clone, Copy, PartialEq)]
102 pub kind: ty::ClosureKind
105 // different kinds of pointers:
106 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107 pub enum PointerKind<'tcx> {
112 BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
115 UnsafePtr(hir::Mutability),
118 // We use the term "interior" to mean "something reachable from the
119 // base without a pointer dereference", e.g., a field
120 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
121 pub enum InteriorKind {
122 InteriorField(FieldIndex),
123 InteriorElement(InteriorOffsetKind),
126 // Contains index of a field that is actually used for loan path comparisons and
127 // string representation of the field that should be used only for diagnostics.
128 #[derive(Clone, Copy, Eq)]
129 pub struct FieldIndex(pub usize, pub Name);
131 impl PartialEq for FieldIndex {
132 fn eq(&self, rhs: &Self) -> bool {
137 impl Hash for FieldIndex {
138 fn hash<H: Hasher>(&self, h: &mut H) {
143 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
144 pub enum InteriorOffsetKind {
145 Index, // e.g., `array_expr[index_expr]`
146 Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }`
149 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
150 pub enum MutabilityCategory {
151 McImmutable, // Immutable.
152 McDeclared, // Directly declared as mutable.
153 McInherited, // Inherited from the fact that owner is mutable.
156 // A note about the provenance of a `cmt`. This is used for
157 // special-case handling of upvars such as mutability inference.
158 // Upvar categorization can generate a variable number of nested
159 // derefs. The note allows detecting them without deep pattern
160 // matching on the categorization.
161 #[derive(Clone, Copy, PartialEq, Debug)]
163 NoteClosureEnv(ty::UpvarId), // Deref through closure env
164 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
165 NoteIndex, // Deref as part of desugaring `x[]` into its two components
166 NoteNone // Nothing special
169 // `cmt`: "Category, Mutability, and Type".
171 // a complete categorization of a value indicating where it originated
172 // and how it is located, as well as the mutability of the memory in
173 // which the value is stored.
175 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
176 // result of `node_type(cmt.id)`.
178 // (FIXME: rewrite the following comment given that `@x` managed
179 // pointers have been obsolete for quite some time.)
181 // This is because the `id` is always the `id` of the node producing the
182 // type; in an expression like `*x`, the type of this deref node is the
183 // deref'd type (`T`), but in a pattern like `@x`, the `@x` pattern is
184 // again a dereference, but its type is the type *before* the
185 // dereference (`@T`). So use `cmt.ty` to find the type of the value in
186 // a consistent fashion. For more details, see the method `cat_pattern`
187 #[derive(Clone, Debug, PartialEq)]
188 pub struct cmt_<'tcx> {
189 pub hir_id: hir::HirId, // HIR id of expr/pat producing this value
190 pub span: Span, // span of same expr/pat
191 pub cat: Categorization<'tcx>, // categorization of expr
192 pub mutbl: MutabilityCategory, // mutability of expr as place
193 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
194 pub note: Note, // Note about the provenance of this cmt
197 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
199 pub enum ImmutabilityBlame<'tcx> {
200 ImmLocal(hir::HirId),
201 ClosureEnv(LocalDefId),
202 LocalDeref(hir::HirId),
203 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
206 impl<'tcx> cmt_<'tcx> {
207 fn resolve_field(&self, field_index: usize) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
209 let adt_def = match self.ty.sty {
210 ty::Adt(def, _) => def,
211 ty::Tuple(..) => return None,
212 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
213 _ => bug!("interior cmt {:?} is not an ADT", self)
215 let variant_def = match self.cat {
216 Categorization::Downcast(_, variant_did) => {
217 adt_def.variant_with_id(variant_did)
220 assert_eq!(adt_def.variants.len(), 1);
221 &adt_def.variants[VariantIdx::new(0)]
224 Some((adt_def, &variant_def.fields[field_index]))
227 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
229 Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) => {
230 // try to figure out where the immutable reference came from
232 Categorization::Local(hir_id) =>
233 Some(ImmutabilityBlame::LocalDeref(hir_id)),
234 Categorization::Interior(ref base_cmt, InteriorField(field_index)) => {
235 base_cmt.resolve_field(field_index.0).map(|(adt_def, field_def)| {
236 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
239 Categorization::Upvar(Upvar { id, .. }) => {
240 if let NoteClosureEnv(..) = self.note {
241 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
249 Categorization::Local(hir_id) => {
250 Some(ImmutabilityBlame::ImmLocal(hir_id))
252 Categorization::Rvalue(..) |
253 Categorization::Upvar(..) |
254 Categorization::Deref(_, UnsafePtr(..)) => {
255 // This should not be reachable up to inference limitations.
258 Categorization::Interior(ref base_cmt, _) |
259 Categorization::Downcast(ref base_cmt, _) |
260 Categorization::Deref(ref base_cmt, _) => {
261 base_cmt.immutability_blame()
263 Categorization::ThreadLocal(..) |
264 Categorization::StaticItem => {
265 // Do we want to do something here?
273 fn hir_id(&self) -> hir::HirId;
274 fn span(&self) -> Span;
277 impl HirNode for hir::Expr {
278 fn hir_id(&self) -> hir::HirId { self.hir_id }
279 fn span(&self) -> Span { self.span }
282 impl HirNode for hir::Pat {
283 fn hir_id(&self) -> hir::HirId { self.hir_id }
284 fn span(&self) -> Span { self.span }
288 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
289 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
290 pub region_scope_tree: &'a region::ScopeTree,
291 pub tables: &'a ty::TypeckTables<'tcx>,
292 rvalue_promotable_map: Option<&'tcx ItemLocalSet>,
293 infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>,
296 pub type McResult<T> = Result<T, ()>;
298 impl MutabilityCategory {
299 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
301 MutImmutable => McImmutable,
302 MutMutable => McDeclared
304 debug!("MutabilityCategory::{}({:?}) => {:?}",
305 "from_mutbl", m, ret);
309 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
310 let ret = match borrow_kind {
311 ty::ImmBorrow => McImmutable,
312 ty::UniqueImmBorrow => McImmutable,
313 ty::MutBorrow => McDeclared,
315 debug!("MutabilityCategory::{}({:?}) => {:?}",
316 "from_borrow_kind", borrow_kind, ret);
320 fn from_pointer_kind(base_mutbl: MutabilityCategory,
321 ptr: PointerKind<'_>) -> MutabilityCategory {
322 let ret = match ptr {
326 BorrowedPtr(borrow_kind, _) => {
327 MutabilityCategory::from_borrow_kind(borrow_kind)
330 MutabilityCategory::from_mutbl(m)
333 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
334 "from_pointer_kind", base_mutbl, ptr, ret);
338 fn from_local(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>,
339 id: ast::NodeId) -> MutabilityCategory {
340 let ret = match tcx.hir().get(id) {
341 Node::Binding(p) => match p.node {
342 PatKind::Binding(..) => {
343 let bm = *tables.pat_binding_modes()
345 .expect("missing binding mode");
346 if bm == ty::BindByValue(hir::MutMutable) {
352 _ => span_bug!(p.span, "expected identifier pattern")
354 _ => span_bug!(tcx.hir().span(id), "expected identifier pattern")
356 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
357 "from_local", id, ret);
361 pub fn inherit(&self) -> MutabilityCategory {
362 let ret = match *self {
363 McImmutable => McImmutable,
364 McDeclared => McInherited,
365 McInherited => McInherited,
367 debug!("{:?}.inherit() => {:?}", self, ret);
371 pub fn is_mutable(&self) -> bool {
372 let ret = match *self {
373 McImmutable => false,
377 debug!("{:?}.is_mutable() => {:?}", self, ret);
381 pub fn is_immutable(&self) -> bool {
382 let ret = match *self {
384 McDeclared | McInherited => false
386 debug!("{:?}.is_immutable() => {:?}", self, ret);
390 pub fn to_user_str(&self) -> &'static str {
392 McDeclared | McInherited => "mutable",
393 McImmutable => "immutable",
398 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> {
399 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
400 region_scope_tree: &'a region::ScopeTree,
401 tables: &'a ty::TypeckTables<'tcx>,
402 rvalue_promotable_map: Option<&'tcx ItemLocalSet>)
403 -> MemCategorizationContext<'a, 'tcx, 'tcx> {
404 MemCategorizationContext {
408 rvalue_promotable_map,
414 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
415 /// Creates a `MemCategorizationContext` during type inference.
416 /// This is used during upvar analysis and a few other places.
417 /// Because the typeck tables are not yet complete, the results
418 /// from the analysis must be used with caution:
420 /// - rvalue promotions are not known, so the lifetimes of
421 /// temporaries may be overly conservative;
422 /// - similarly, as the results of upvar analysis are not yet
423 /// known, the results around upvar accesses may be incorrect.
424 pub fn with_infer(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
425 region_scope_tree: &'a region::ScopeTree,
426 tables: &'a ty::TypeckTables<'tcx>)
427 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
430 // Subtle: we can't do rvalue promotion analysis until the
431 // typeck phase is complete, which means that you can't trust
432 // the rvalue lifetimes that result, but that's ok, since we
433 // don't need to know those during type inference.
434 let rvalue_promotable_map = None;
436 MemCategorizationContext {
440 rvalue_promotable_map,
445 pub fn type_is_copy_modulo_regions(
447 param_env: ty::ParamEnv<'tcx>,
451 self.infcx.map(|infcx| infcx.type_is_copy_modulo_regions(param_env, ty, span))
453 self.tcx.lift_to_global(&(param_env, ty)).map(|(param_env, ty)| {
454 ty.is_copy_modulo_regions(self.tcx.global_tcx(), param_env, span)
460 fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
461 where T: TypeFoldable<'tcx>
463 self.infcx.map(|infcx| infcx.resolve_type_vars_if_possible(value))
464 .unwrap_or_else(|| value.clone())
467 fn is_tainted_by_errors(&self) -> bool {
468 self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
471 fn resolve_type_vars_or_error(&self,
473 ty: Option<Ty<'tcx>>)
474 -> McResult<Ty<'tcx>> {
477 let ty = self.resolve_type_vars_if_possible(&ty);
478 if ty.references_error() || ty.is_ty_var() {
479 debug!("resolve_type_vars_or_error: error from {:?}", ty);
486 None if self.is_tainted_by_errors() => Err(()),
488 let id = self.tcx.hir().hir_to_node_id(id);
489 bug!("no type for node {}: {} in mem_categorization",
490 id, self.tcx.hir().node_to_string(id));
495 pub fn node_ty(&self,
497 -> McResult<Ty<'tcx>> {
498 self.resolve_type_vars_or_error(hir_id,
499 self.tables.node_type_opt(hir_id))
502 pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
503 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
506 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
507 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
510 /// Returns the type of value that this pattern matches against.
511 /// Some non-obvious cases:
513 /// - a `ref x` binding matches against a value of type `T` and gives
514 /// `x` the type `&T`; we return `T`.
515 /// - a pattern with implicit derefs (thanks to default binding
516 /// modes #42640) may look like `Some(x)` but in fact have
517 /// implicit deref patterns attached (e.g., it is really
518 /// `&Some(x)`). In that case, we return the "outermost" type
519 /// (e.g., `&Option<T>).
520 pub fn pat_ty_adjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
521 // Check for implicit `&` types wrapping the pattern; note
522 // that these are never attached to binding patterns, so
523 // actually this is somewhat "disjoint" from the code below
524 // that aims to account for `ref x`.
525 if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
526 if let Some(first_ty) = vec.first() {
527 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
532 self.pat_ty_unadjusted(pat)
536 /// Like `pat_ty`, but ignores implicit `&` patterns.
537 fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
538 let base_ty = self.node_ty(pat.hir_id)?;
539 debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
541 // This code detects whether we are looking at a `ref x`,
542 // and if so, figures out what the type *being borrowed* is.
543 let ret_ty = match pat.node {
544 PatKind::Binding(..) => {
545 let bm = *self.tables
548 .expect("missing binding mode");
550 if let ty::BindByReference(_) = bm {
551 // a bind-by-ref means that the base_ty will be the type of the ident itself,
552 // but what we want here is the type of the underlying value being borrowed.
553 // So peel off one-level, turning the &T into T.
554 match base_ty.builtin_deref(false) {
557 debug!("By-ref binding of non-derefable type {:?}", base_ty);
567 debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
572 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
573 // This recursion helper avoids going through *too many*
574 // adjustments, since *only* non-overloaded deref recurses.
575 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
577 adjustments: &[adjustment::Adjustment<'tcx>])
578 -> McResult<cmt_<'tcx>> {
579 match adjustments.split_last() {
580 None => mc.cat_expr_unadjusted(expr),
581 Some((adjustment, previous)) => {
582 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
587 helper(self, expr, self.tables.expr_adjustments(expr))
590 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
591 previous: cmt_<'tcx>,
592 adjustment: &adjustment::Adjustment<'tcx>)
593 -> McResult<cmt_<'tcx>> {
594 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
597 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
599 adjustment: &adjustment::Adjustment<'tcx>)
600 -> McResult<cmt_<'tcx>>
601 where F: FnOnce() -> McResult<cmt_<'tcx>>
603 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
604 let target = self.resolve_type_vars_if_possible(&adjustment.target);
605 match adjustment.kind {
606 adjustment::Adjust::Deref(overloaded) => {
607 // Equivalent to *expr or something similar.
608 let base = Rc::new(if let Some(deref) = overloaded {
609 let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
613 self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty)
617 self.cat_deref(expr, base, NoteNone)
620 adjustment::Adjust::NeverToAny |
621 adjustment::Adjust::Pointer(_) |
622 adjustment::Adjust::Borrow(_) => {
623 // Result is an rvalue.
624 Ok(self.cat_rvalue_node(expr.hir_id, expr.span, target))
629 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
630 debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr);
632 let expr_ty = self.expr_ty(expr)?;
634 hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
635 if self.tables.is_method_call(expr) {
636 self.cat_overloaded_place(expr, e_base, NoteNone)
638 let base_cmt = Rc::new(self.cat_expr(&e_base)?);
639 self.cat_deref(expr, base_cmt, NoteNone)
643 hir::ExprKind::Field(ref base, f_ident) => {
644 let base_cmt = Rc::new(self.cat_expr(&base)?);
645 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
649 let f_index = self.tcx.field_index(expr.hir_id, self.tables);
650 Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
653 hir::ExprKind::Index(ref base, _) => {
654 if self.tables.is_method_call(expr) {
655 // If this is an index implemented by a method call, then it
656 // will include an implicit deref of the result.
657 // The call to index() returns a `&T` value, which
658 // is an rvalue. That is what we will be
660 self.cat_overloaded_place(expr, base, NoteIndex)
662 let base_cmt = Rc::new(self.cat_expr(&base)?);
663 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
667 hir::ExprKind::Path(ref qpath) => {
668 let res = self.tables.qpath_res(qpath, expr.hir_id);
669 self.cat_res(expr.hir_id, expr.span, expr_ty, res)
672 hir::ExprKind::Type(ref e, _) => {
676 hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
677 hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
678 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
679 hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
680 hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) |
681 hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) |
682 hir::ExprKind::Binary(..) | hir::ExprKind::While(..) |
683 hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
684 hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
685 hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
686 hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Err => {
687 Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
692 pub fn cat_res(&self,
697 -> McResult<cmt_<'tcx>> {
698 debug!("cat_res: id={:?} expr={:?} def={:?}",
699 hir_id, expr_ty, res);
702 Res::Def(DefKind::Ctor(..), _)
703 | Res::Def(DefKind::Const, _)
704 | Res::Def(DefKind::ConstParam, _)
705 | Res::Def(DefKind::AssociatedConst, _)
706 | Res::Def(DefKind::Fn, _)
707 | Res::Def(DefKind::Method, _)
708 | Res::SelfCtor(..) => {
709 Ok(self.cat_rvalue_node(hir_id, span, expr_ty))
712 Res::Def(DefKind::Static, def_id) => {
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: match self.tcx.static_mutability(def_id).unwrap() {
731 hir::MutImmutable => McImmutable,
732 hir::MutMutable => McDeclared,
739 Res::Upvar(var_id, _, fn_node_id) => {
740 let var_nid = self.tcx.hir().hir_to_node_id(var_id);
741 self.cat_upvar(hir_id, span, var_nid, fn_node_id)
745 let vnid = self.tcx.hir().hir_to_node_id(vid);
749 cat: Categorization::Local(vid),
750 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vnid),
756 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
760 // Categorize an upvar, complete with invisible derefs of closure
761 // environment and upvar reference as appropriate.
766 fn_node_id: ast::NodeId)
767 -> McResult<cmt_<'tcx>>
769 let fn_hir_id = self.tcx.hir().node_to_hir_id(fn_node_id);
771 // An upvar can have up to 3 components. We translate first to a
772 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
773 // field from the environment.
775 // `Categorization::Upvar`. Next, we add a deref through the implicit
776 // environment pointer with an anonymous free region 'env and
777 // appropriate borrow kind for closure kinds that take self by
778 // reference. Finally, if the upvar was captured
779 // by-reference, we add a deref through that reference. The
780 // region of this reference is an inference variable 'up that
781 // was previously generated and recorded in the upvar borrow
782 // map. The borrow kind bk is inferred by based on how the
785 // This results in the following table for concrete closure
789 // ---------------+----------------------+-------------------------------
790 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
791 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
792 // FnOnce | copied | upvar -> &'up bk
794 let ty = self.node_ty(fn_hir_id)?;
795 let kind = match ty.sty {
796 ty::Generator(..) => ty::ClosureKind::FnOnce,
797 ty::Closure(closure_def_id, closure_substs) => {
799 // During upvar inference we may not know the
800 // closure kind, just use the LATTICE_BOTTOM value.
802 infcx.closure_kind(closure_def_id, closure_substs)
803 .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
806 self.tcx.global_tcx()
807 .lift(&closure_substs)
808 .expect("no inference cx, but inference variables in closure ty")
809 .closure_kind(closure_def_id, self.tcx.global_tcx()),
812 _ => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", ty),
815 let closure_expr_def_id = self.tcx.hir().local_def_id(fn_node_id);
816 let var_hir_id = self.tcx.hir().node_to_hir_id(var_id);
817 let upvar_id = ty::UpvarId {
818 var_path: ty::UpvarPath { hir_id: var_hir_id },
819 closure_expr_id: closure_expr_def_id.to_local(),
822 let var_ty = self.node_ty(var_hir_id)?;
824 // Mutability of original variable itself
825 let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
827 // Construct the upvar. This represents access to the field
828 // from the environment (perhaps we should eventually desugar
829 // this field further, but it will do for now).
830 let cmt_result = cmt_ {
833 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
839 // If this is a `FnMut` or `Fn` closure, then the above is
840 // conceptually a `&mut` or `&` reference, so we have to add a
842 let cmt_result = match kind {
843 ty::ClosureKind::FnOnce => {
846 ty::ClosureKind::FnMut => {
847 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
849 ty::ClosureKind::Fn => {
850 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
854 // If this is a by-ref capture, then the upvar we loaded is
855 // actually a reference, so we have to add an implicit deref
857 let upvar_capture = self.tables.upvar_capture(upvar_id);
858 let cmt_result = match upvar_capture {
859 ty::UpvarCapture::ByValue => {
862 ty::UpvarCapture::ByRef(upvar_borrow) => {
863 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
867 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
868 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
870 note: NoteUpvarRef(upvar_id)
875 let ret = cmt_result;
876 debug!("cat_upvar ret={:?}", ret);
883 upvar_id: ty::UpvarId,
884 upvar_mutbl: MutabilityCategory,
885 env_borrow_kind: ty::BorrowKind,
886 cmt_result: cmt_<'tcx>)
889 // Region of environment pointer
890 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
891 // The environment of a closure is guaranteed to
892 // outlive any bindings introduced in the body of the
894 scope: upvar_id.closure_expr_id.to_def_id(),
895 bound_region: ty::BrEnv
898 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
900 let var_ty = cmt_result.ty;
902 // We need to add the env deref. This means
903 // that the above is actually immutable and
904 // has a ref type. However, nothing should
905 // actually look at the type, so we can get
906 // away with stuffing a `Error` in there
907 // instead of bothering to construct a proper
909 let cmt_result = cmt_ {
911 ty: self.tcx.types.err,
915 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
917 // Issue #18335. If variable is declared as immutable, override the
918 // mutability from the environment and substitute an `&T` anyway.
920 McImmutable => { deref_mutbl = McImmutable; }
921 McDeclared | McInherited => { }
927 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
930 note: NoteClosureEnv(upvar_id)
933 debug!("env_deref ret {:?}", ret);
938 /// Returns the lifetime of a temporary created by expr with id `id`.
939 /// This could be `'static` if `id` is part of a constant expression.
940 pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
941 let scope = self.region_scope_tree.temporary_scope(id);
942 self.tcx.mk_region(match scope {
943 Some(scope) => ty::ReScope(scope),
948 pub fn cat_rvalue_node(&self,
953 debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
954 hir_id, span, expr_ty);
956 let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
959 debug!("cat_rvalue_node: promotable = {:?}", promotable);
961 // Always promote `[T; 0]` (even when e.g., borrowed mutably).
962 let promotable = match expr_ty.sty {
963 ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true,
967 debug!("cat_rvalue_node: promotable = {:?} (2)", promotable);
969 // Compute maximum lifetime of this rvalue. This is 'static if
970 // we can promote to a constant, otherwise equal to enclosing temp
972 let re = if promotable {
973 self.tcx.lifetimes.re_static
975 self.temporary_scope(hir_id.local_id)
977 let ret = self.cat_rvalue(hir_id, span, re, expr_ty);
978 debug!("cat_rvalue_node ret {:?}", ret);
982 pub fn cat_rvalue(&self,
983 cmt_hir_id: hir::HirId,
985 temp_scope: ty::Region<'tcx>,
986 expr_ty: Ty<'tcx>) -> cmt_<'tcx> {
990 cat:Categorization::Rvalue(temp_scope),
995 debug!("cat_rvalue ret {:?}", ret);
999 pub fn cat_field<N: HirNode>(&self,
1001 base_cmt: cmt<'tcx>,
1003 f_ident: ast::Ident,
1007 hir_id: node.hir_id(),
1009 mutbl: base_cmt.mutbl.inherit(),
1010 cat: Categorization::Interior(base_cmt,
1011 InteriorField(FieldIndex(f_index, f_ident.name))),
1015 debug!("cat_field ret {:?}", ret);
1019 fn cat_overloaded_place(
1024 ) -> McResult<cmt_<'tcx>> {
1025 debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
1030 // Reconstruct the output assuming it's a reference with the
1031 // same region and mutability as the receiver. This holds for
1032 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1033 let place_ty = self.expr_ty(expr)?;
1034 let base_ty = self.expr_ty_adjusted(base)?;
1036 let (region, mutbl) = match base_ty.sty {
1037 ty::Ref(region, _, mutbl) => (region, mutbl),
1038 _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
1040 let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
1045 let base_cmt = Rc::new(self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty));
1046 self.cat_deref(expr, base_cmt, note)
1051 node: &impl HirNode,
1052 base_cmt: cmt<'tcx>,
1054 ) -> McResult<cmt_<'tcx>> {
1055 debug!("cat_deref: base_cmt={:?}", base_cmt);
1057 let base_cmt_ty = base_cmt.ty;
1058 let deref_ty = match base_cmt_ty.builtin_deref(true) {
1061 debug!("Explicit deref of non-derefable type: {:?}", base_cmt_ty);
1066 let ptr = match base_cmt.ty.sty {
1067 ty::Adt(def, ..) if def.is_box() => Unique,
1068 ty::RawPtr(ref mt) => UnsafePtr(mt.mutbl),
1069 ty::Ref(r, _, mutbl) => {
1070 let bk = ty::BorrowKind::from_mutbl(mutbl);
1073 _ => bug!("unexpected type in cat_deref: {:?}", base_cmt.ty)
1076 hir_id: node.hir_id(),
1078 // For unique ptrs, we inherit mutability from the owning reference.
1079 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1080 cat: Categorization::Deref(base_cmt, ptr),
1084 debug!("cat_deref ret {:?}", ret);
1088 fn cat_index<N: HirNode>(&self,
1090 base_cmt: cmt<'tcx>,
1091 element_ty: Ty<'tcx>,
1092 context: InteriorOffsetKind)
1093 -> McResult<cmt_<'tcx>> {
1094 //! Creates a cmt for an indexing operation (`[]`).
1096 //! One subtle aspect of indexing that may not be
1097 //! immediately obvious: for anything other than a fixed-length
1098 //! vector, an operation like `x[y]` actually consists of two
1099 //! disjoint (from the point of view of borrowck) operations.
1100 //! The first is a deref of `x` to create a pointer `p` that points
1101 //! at the first element in the array. The second operation is
1102 //! an index which adds `y*sizeof(T)` to `p` to obtain the
1103 //! pointer to `x[y]`. `cat_index` will produce a resulting
1104 //! cmt containing both this deref and the indexing,
1105 //! presuming that `base_cmt` is not of fixed-length type.
1108 //! - `elt`: the HIR node being indexed
1109 //! - `base_cmt`: the cmt of `elt`
1111 let interior_elem = InteriorElement(context);
1112 let ret = self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1113 debug!("cat_index ret {:?}", ret);
1117 pub fn cat_imm_interior<N:HirNode>(&self,
1119 base_cmt: cmt<'tcx>,
1120 interior_ty: Ty<'tcx>,
1121 interior: InteriorKind)
1124 hir_id: node.hir_id(),
1126 mutbl: base_cmt.mutbl.inherit(),
1127 cat: Categorization::Interior(base_cmt, interior),
1131 debug!("cat_imm_interior ret={:?}", ret);
1135 pub fn cat_downcast_if_needed<N:HirNode>(&self,
1137 base_cmt: cmt<'tcx>,
1140 // univariant enums do not need downcasts
1141 let base_did = self.tcx.parent(variant_did).unwrap();
1142 if self.tcx.adt_def(base_did).variants.len() != 1 {
1143 let base_ty = base_cmt.ty;
1144 let ret = Rc::new(cmt_ {
1145 hir_id: node.hir_id(),
1147 mutbl: base_cmt.mutbl.inherit(),
1148 cat: Categorization::Downcast(base_cmt, variant_did),
1152 debug!("cat_downcast ret={:?}", ret);
1155 debug!("cat_downcast univariant={:?}", base_cmt);
1160 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1161 where F: FnMut(cmt<'tcx>, &hir::Pat),
1163 self.cat_pattern_(cmt, pat, &mut op)
1166 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1167 fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1168 where F : FnMut(cmt<'tcx>, &hir::Pat)
1170 // Here, `cmt` is the categorization for the value being
1171 // matched and pat is the pattern it is being matched against.
1173 // In general, the way that this works is that we walk down
1174 // the pattern, constructing a cmt that represents the path
1175 // that will be taken to reach the value being matched.
1177 // When we encounter named bindings, we take the cmt that has
1178 // been built up and pass it off to guarantee_valid() so that
1179 // we can be sure that the binding will remain valid for the
1180 // duration of the arm.
1182 // (*2) There is subtlety concerning the correspondence between
1183 // pattern ids and types as compared to *expression* ids and
1184 // types. This is explained briefly. on the definition of the
1185 // type `cmt`, so go off and read what it says there, then
1186 // come back and I'll dive into a bit more detail here. :) OK,
1189 // In general, the id of the cmt should be the node that
1190 // "produces" the value---patterns aren't executable code
1191 // exactly, but I consider them to "execute" when they match a
1192 // value, and I consider them to produce the value that was
1193 // matched. So if you have something like:
1195 // (FIXME: `@@3` is not legal code anymore!)
1202 // In this case, the cmt and the relevant ids would be:
1204 // CMT Id Type of Id Type of cmt
1207 // ^~~~~~~^ `x` from discr @@int @@int
1208 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1209 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1211 // You can see that the types of the id and the cmt are in
1212 // sync in the first line, because that id is actually the id
1213 // of an expression. But once we get to pattern ids, the types
1214 // step out of sync again. So you'll see below that we always
1215 // get the type of the *subpattern* and use that.
1217 debug!("cat_pattern(pat={:?}, cmt={:?})", pat, cmt);
1219 // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1220 // `cmt`s are constructed differently from patterns. For example, in
1224 // &&Some(x, ) => { ... },
1229 // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1230 // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1231 // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1233 // `&&Some(x,)` `cmt_foo`
1234 // `&Some(x,)` `deref { cmt_foo}`
1235 // `Some(x,)` `deref { deref { cmt_foo }}`
1236 // (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1238 // The above example has no adjustments. If the code were instead the (after adjustments,
1239 // equivalent) version
1243 // Some(x, ) => { ... },
1248 // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1249 // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1250 // though its assigned type is that of `&&Some(x,)`.
1251 for _ in 0..self.tables
1257 debug!("cat_pattern: applying adjustment to cmt={:?}", cmt);
1258 cmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1260 let cmt = cmt; // lose mutability
1261 debug!("cat_pattern: applied adjustment derefs to get cmt={:?}", cmt);
1263 // Invoke the callback, but only now, after the `cmt` has adjusted.
1265 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1266 // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1267 // don't want to call `op` with these incompatible values. As written, what happens instead
1268 // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1269 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1270 // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1271 // that (where the `ref` on `x` is implied).
1272 op(cmt.clone(), pat);
1275 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1276 let res = self.tables.qpath_res(qpath, pat.hir_id);
1277 let (cmt, expected_len) = match res {
1279 debug!("access to unresolvable pattern {:?}", pat);
1282 Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), variant_ctor_did) => {
1283 let variant_did = self.tcx.parent(variant_ctor_did).unwrap();
1284 let enum_did = self.tcx.parent(variant_did).unwrap();
1285 (self.cat_downcast_if_needed(pat, cmt, variant_did),
1286 self.tcx.adt_def(enum_did)
1287 .variant_with_ctor_id(variant_ctor_did).fields.len())
1289 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1290 | Res::SelfCtor(..) => {
1291 let ty = self.pat_ty_unadjusted(&pat)?;
1293 ty::Adt(adt_def, _) => {
1294 (cmt, adt_def.non_enum_variant().fields.len())
1298 "tuple struct pattern unexpected type {:?}", ty);
1304 "tuple struct pattern didn't resolve to variant or struct {:?} at {:?}",
1308 self.tcx.sess.delay_span_bug(pat.span, &format!(
1309 "tuple struct pattern didn't resolve to variant or struct {:?}",
1316 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1317 let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1318 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1319 let subcmt = Rc::new(
1320 self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1321 self.cat_pattern_(subcmt, &subpat, op)?;
1325 PatKind::Struct(ref qpath, ref field_pats, _) => {
1326 // {f1: p1, ..., fN: pN}
1327 let res = self.tables.qpath_res(qpath, pat.hir_id);
1328 let cmt = match res {
1330 debug!("access to unresolvable pattern {:?}", pat);
1333 Res::Def(DefKind::Ctor(CtorOf::Variant, _), variant_ctor_did) => {
1334 let variant_did = self.tcx.parent(variant_ctor_did).unwrap();
1335 self.cat_downcast_if_needed(pat, cmt, variant_did)
1337 Res::Def(DefKind::Variant, variant_did) => {
1338 self.cat_downcast_if_needed(pat, cmt, variant_did)
1343 for fp in field_pats {
1344 let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
1345 let f_index = self.tcx.field_index(fp.node.hir_id, self.tables);
1346 let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
1347 fp.node.ident, field_ty));
1348 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1352 PatKind::Binding(.., Some(ref subpat)) => {
1353 self.cat_pattern_(cmt, &subpat, op)?;
1356 PatKind::Tuple(ref subpats, ddpos) => {
1358 let ty = self.pat_ty_unadjusted(&pat)?;
1359 let expected_len = match ty.sty {
1360 ty::Tuple(ref tys) => tys.len(),
1361 _ => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1363 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1364 let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1365 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1366 let subcmt = Rc::new(
1367 self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1368 self.cat_pattern_(subcmt, &subpat, op)?;
1372 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1373 // box p1, &p1, &mut p1. we can ignore the mutability of
1374 // PatKind::Ref since that information is already contained
1376 let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1377 self.cat_pattern_(subcmt, &subpat, op)?;
1380 PatKind::Slice(ref before, ref slice, ref after) => {
1381 let element_ty = match cmt.ty.builtin_index() {
1384 debug!("Explicit index of non-indexable type {:?}", cmt);
1388 let context = InteriorOffsetKind::Pattern;
1389 let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
1390 for before_pat in before {
1391 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1393 if let Some(ref slice_pat) = *slice {
1394 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1396 for after_pat in after {
1397 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1401 PatKind::Path(_) | PatKind::Binding(.., None) |
1402 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1411 #[derive(Clone, Debug)]
1412 pub enum Aliasability {
1413 FreelyAliasable(AliasableReason),
1415 ImmutableUnique(Box<Aliasability>),
1418 #[derive(Copy, Clone, Debug)]
1419 pub enum AliasableReason {
1425 impl<'tcx> cmt_<'tcx> {
1426 pub fn guarantor(&self) -> cmt_<'tcx> {
1427 //! Returns `self` after stripping away any derefs or
1428 //! interior content. The return value is basically the `cmt` which
1429 //! determines how long the value in `self` remains live.
1432 Categorization::Rvalue(..) |
1433 Categorization::StaticItem |
1434 Categorization::ThreadLocal(..) |
1435 Categorization::Local(..) |
1436 Categorization::Deref(_, UnsafePtr(..)) |
1437 Categorization::Deref(_, BorrowedPtr(..)) |
1438 Categorization::Upvar(..) => {
1441 Categorization::Downcast(ref b, _) |
1442 Categorization::Interior(ref b, _) |
1443 Categorization::Deref(ref b, Unique) => {
1449 /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1450 pub fn freely_aliasable(&self) -> Aliasability {
1451 // Maybe non-obvious: copied upvars can only be considered
1452 // non-aliasable in once closures, since any other kind can be
1453 // aliased and eventually recused.
1456 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1457 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1458 Categorization::Deref(ref b, Unique) |
1459 Categorization::Downcast(ref b, _) |
1460 Categorization::Interior(ref b, _) => {
1461 // Aliasability depends on base cmt
1462 b.freely_aliasable()
1465 Categorization::Rvalue(..) |
1466 Categorization::ThreadLocal(..) |
1467 Categorization::Local(..) |
1468 Categorization::Upvar(..) |
1469 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1473 Categorization::StaticItem => {
1474 if self.mutbl.is_mutable() {
1475 FreelyAliasable(AliasableStaticMut)
1477 FreelyAliasable(AliasableStatic)
1481 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) => {
1482 FreelyAliasable(AliasableBorrowed)
1487 // Digs down through one or two layers of deref and grabs the
1488 // Categorization of the cmt for the upvar if a note indicates there is
1490 pub fn upvar_cat(&self) -> Option<&Categorization<'tcx>> {
1492 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1493 Some(match self.cat {
1494 Categorization::Deref(ref inner, _) => {
1496 Categorization::Deref(ref inner, _) => &inner.cat,
1497 Categorization::Upvar(..) => &inner.cat,
1504 NoteIndex | NoteNone => None
1508 pub fn descriptive_string(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
1510 Categorization::StaticItem => {
1511 "static item".into()
1513 Categorization::ThreadLocal(..) => {
1514 "thread-local static item".into()
1516 Categorization::Rvalue(..) => {
1519 Categorization::Local(vid) => {
1520 if tcx.hir().is_argument(tcx.hir().hir_to_node_id(vid)) {
1526 Categorization::Deref(_, pk) => {
1527 match self.upvar_cat() {
1528 Some(&Categorization::Upvar(ref var)) => {
1529 var.to_string().into()
1538 "dereference of raw pointer"
1540 BorrowedPtr(..) => {
1542 NoteIndex => "indexed content",
1543 _ => "borrowed content"
1550 Categorization::Interior(_, InteriorField(..)) => {
1553 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1554 "indexed content".into()
1556 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1557 "pattern-bound indexed content".into()
1559 Categorization::Upvar(ref var) => {
1560 var.to_string().into()
1562 Categorization::Downcast(ref cmt, _) => {
1563 cmt.descriptive_string(tcx).into()
1569 pub fn ptr_sigil(ptr: PointerKind<'_>) -> &'static str {
1572 BorrowedPtr(ty::ImmBorrow, _) => "&",
1573 BorrowedPtr(ty::MutBorrow, _) => "&mut",
1574 BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
1575 UnsafePtr(_) => "*",
1579 impl fmt::Debug for InteriorKind {
1580 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582 InteriorField(FieldIndex(_, info)) => write!(f, "{}", info),
1583 InteriorElement(..) => write!(f, "[]"),
1588 impl fmt::Debug for Upvar {
1589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590 write!(f, "{:?}/{:?}", self.id, self.kind)
1594 impl fmt::Display for Upvar {
1595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1596 let kind = match self.kind {
1597 ty::ClosureKind::Fn => "Fn",
1598 ty::ClosureKind::FnMut => "FnMut",
1599 ty::ClosureKind::FnOnce => "FnOnce",
1601 write!(f, "captured outer variable in an `{}` closure", kind)