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 translation 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 translation. 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::FieldName::*;
66 pub use self::MutabilityCategory::*;
67 pub use self::AliasableReason::*;
68 pub use self::Note::*;
70 use self::Aliasability::*;
73 use hir::def_id::{DefId, LocalDefId};
74 use hir::map as hir_map;
76 use hir::def::{Def, CtorKind};
78 use ty::{self, Ty, TyCtxt};
79 use ty::fold::TypeFoldable;
81 use hir::{MutImmutable, MutMutable, PatKind};
82 use hir::pat_util::EnumerateAndAdjustIterator;
88 use rustc_data_structures::sync::Lrc;
90 use util::nodemap::ItemLocalSet;
92 #[derive(Clone, Debug, PartialEq)]
93 pub enum Categorization<'tcx> {
94 Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
96 Upvar(Upvar), // upvar referenced by closure env
97 Local(ast::NodeId), // local variable
98 Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
99 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
100 Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
102 // (*1) downcast is only required if the enum has more than one variant
105 // Represents any kind of upvar
106 #[derive(Clone, Copy, PartialEq)]
109 pub kind: ty::ClosureKind
112 // different kinds of pointers:
113 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
114 pub enum PointerKind<'tcx> {
119 BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
122 UnsafePtr(hir::Mutability),
124 /// Implicit deref of the `&T` that results from an overloaded index `[]`.
125 Implicit(ty::BorrowKind, ty::Region<'tcx>),
128 // We use the term "interior" to mean "something reachable from the
129 // base without a pointer dereference", e.g. a field
130 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
131 pub enum InteriorKind {
132 InteriorField(FieldName),
133 InteriorElement(InteriorOffsetKind),
136 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
138 NamedField(ast::Name),
139 PositionalField(usize)
142 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
143 pub enum InteriorOffsetKind {
144 Index, // e.g. `array_expr[index_expr]`
145 Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
148 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
149 pub enum MutabilityCategory {
150 McImmutable, // Immutable.
151 McDeclared, // Directly declared as mutable.
152 McInherited, // Inherited from the fact that owner is mutable.
155 // A note about the provenance of a `cmt`. This is used for
156 // special-case handling of upvars such as mutability inference.
157 // Upvar categorization can generate a variable number of nested
158 // derefs. The note allows detecting them without deep pattern
159 // matching on the categorization.
160 #[derive(Clone, Copy, PartialEq, Debug)]
162 NoteClosureEnv(ty::UpvarId), // Deref through closure env
163 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
164 NoteNone // Nothing special
167 // `cmt`: "Category, Mutability, and Type".
169 // a complete categorization of a value indicating where it originated
170 // and how it is located, as well as the mutability of the memory in
171 // which the value is stored.
173 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
174 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
175 // always the `id` of the node producing the type; in an expression
176 // like `*x`, the type of this deref node is the deref'd type (`T`),
177 // but in a pattern like `@x`, the `@x` pattern is again a
178 // dereference, but its type is the type *before* the dereference
179 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
180 // fashion. For more details, see the method `cat_pattern`
181 #[derive(Clone, Debug, PartialEq)]
182 pub struct cmt_<'tcx> {
183 pub id: ast::NodeId, // id of expr/pat producing this value
184 pub span: Span, // span of same expr/pat
185 pub cat: Categorization<'tcx>, // categorization of expr
186 pub mutbl: MutabilityCategory, // mutability of expr as place
187 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
188 pub note: Note, // Note about the provenance of this cmt
191 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
193 pub enum ImmutabilityBlame<'tcx> {
194 ImmLocal(ast::NodeId),
195 ClosureEnv(LocalDefId),
196 LocalDeref(ast::NodeId),
197 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
200 impl<'tcx> cmt_<'tcx> {
201 fn resolve_field(&self, field_name: FieldName) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
203 let adt_def = match self.ty.sty {
204 ty::TyAdt(def, _) => def,
205 ty::TyTuple(..) => return None,
206 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
207 _ => bug!("interior cmt {:?} is not an ADT", self)
209 let variant_def = match self.cat {
210 Categorization::Downcast(_, variant_did) => {
211 adt_def.variant_with_id(variant_did)
214 assert_eq!(adt_def.variants.len(), 1);
218 let field_def = match field_name {
219 NamedField(name) => variant_def.field_named(name),
220 PositionalField(idx) => &variant_def.fields[idx]
222 Some((adt_def, field_def))
225 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
227 Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) |
228 Categorization::Deref(ref base_cmt, Implicit(ty::ImmBorrow, _)) => {
229 // try to figure out where the immutable reference came from
231 Categorization::Local(node_id) =>
232 Some(ImmutabilityBlame::LocalDeref(node_id)),
233 Categorization::Interior(ref base_cmt, InteriorField(field_name)) => {
234 base_cmt.resolve_field(field_name).map(|(adt_def, field_def)| {
235 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
238 Categorization::Upvar(Upvar { id, .. }) => {
239 if let NoteClosureEnv(..) = self.note {
240 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
248 Categorization::Local(node_id) => {
249 Some(ImmutabilityBlame::ImmLocal(node_id))
251 Categorization::Rvalue(..) |
252 Categorization::Upvar(..) |
253 Categorization::Deref(_, UnsafePtr(..)) => {
254 // This should not be reachable up to inference limitations.
257 Categorization::Interior(ref base_cmt, _) |
258 Categorization::Downcast(ref base_cmt, _) |
259 Categorization::Deref(ref base_cmt, _) => {
260 base_cmt.immutability_blame()
262 Categorization::StaticItem => {
263 // Do we want to do something here?
271 fn id(&self) -> ast::NodeId;
272 fn span(&self) -> Span;
275 impl ast_node for hir::Expr {
276 fn id(&self) -> ast::NodeId { self.id }
277 fn span(&self) -> Span { self.span }
280 impl ast_node for hir::Pat {
281 fn id(&self) -> ast::NodeId { self.id }
282 fn span(&self) -> Span { self.span }
286 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
287 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
288 pub region_scope_tree: &'a region::ScopeTree,
289 pub tables: &'a ty::TypeckTables<'tcx>,
290 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>,
291 infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>,
294 pub type McResult<T> = Result<T, ()>;
296 impl MutabilityCategory {
297 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
299 MutImmutable => McImmutable,
300 MutMutable => McDeclared
302 debug!("MutabilityCategory::{}({:?}) => {:?}",
303 "from_mutbl", m, ret);
307 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
308 let ret = match borrow_kind {
309 ty::ImmBorrow => McImmutable,
310 ty::UniqueImmBorrow => McImmutable,
311 ty::MutBorrow => McDeclared,
313 debug!("MutabilityCategory::{}({:?}) => {:?}",
314 "from_borrow_kind", borrow_kind, ret);
318 fn from_pointer_kind(base_mutbl: MutabilityCategory,
319 ptr: PointerKind) -> MutabilityCategory {
320 let ret = match ptr {
324 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
325 MutabilityCategory::from_borrow_kind(borrow_kind)
328 MutabilityCategory::from_mutbl(m)
331 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
332 "from_pointer_kind", base_mutbl, ptr, ret);
336 fn from_local(tcx: TyCtxt, tables: &ty::TypeckTables, id: ast::NodeId) -> MutabilityCategory {
337 let ret = match tcx.hir.get(id) {
338 hir_map::NodeBinding(p) => match p.node {
339 PatKind::Binding(..) => {
340 let bm = *tables.pat_binding_modes()
342 .expect("missing binding mode");
343 if bm == ty::BindByValue(hir::MutMutable) {
349 _ => span_bug!(p.span, "expected identifier pattern")
351 _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
353 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
354 "from_local", id, ret);
358 pub fn inherit(&self) -> MutabilityCategory {
359 let ret = match *self {
360 McImmutable => McImmutable,
361 McDeclared => McInherited,
362 McInherited => McInherited,
364 debug!("{:?}.inherit() => {:?}", self, ret);
368 pub fn is_mutable(&self) -> bool {
369 let ret = match *self {
370 McImmutable => false,
374 debug!("{:?}.is_mutable() => {:?}", self, ret);
378 pub fn is_immutable(&self) -> bool {
379 let ret = match *self {
381 McDeclared | McInherited => false
383 debug!("{:?}.is_immutable() => {:?}", self, ret);
387 pub fn to_user_str(&self) -> &'static str {
389 McDeclared | McInherited => "mutable",
390 McImmutable => "immutable",
395 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> {
396 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
397 region_scope_tree: &'a region::ScopeTree,
398 tables: &'a ty::TypeckTables<'tcx>,
399 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
400 -> MemCategorizationContext<'a, 'tcx, 'tcx> {
401 MemCategorizationContext {
405 rvalue_promotable_map,
411 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
412 /// Creates a `MemCategorizationContext` during type inference.
413 /// This is used during upvar analysis and a few other places.
414 /// Because the typeck tables are not yet complete, the results
415 /// from the analysis must be used with caution:
417 /// - rvalue promotions are not known, so the lifetimes of
418 /// temporaries may be overly conservative;
419 /// - similarly, as the results of upvar analysis are not yet
420 /// known, the results around upvar accesses may be incorrect.
421 pub fn with_infer(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
422 region_scope_tree: &'a region::ScopeTree,
423 tables: &'a ty::TypeckTables<'tcx>)
424 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
427 // Subtle: we can't do rvalue promotion analysis until the
428 // typeck phase is complete, which means that you can't trust
429 // the rvalue lifetimes that result, but that's ok, since we
430 // don't need to know those during type inference.
431 let rvalue_promotable_map = None;
433 MemCategorizationContext {
437 rvalue_promotable_map,
442 pub fn type_moves_by_default(&self,
443 param_env: ty::ParamEnv<'tcx>,
447 self.infcx.map(|infcx| infcx.type_moves_by_default(param_env, ty, span))
449 self.tcx.lift_to_global(&(param_env, ty)).map(|(param_env, ty)| {
450 ty.moves_by_default(self.tcx.global_tcx(), param_env, span)
456 fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
457 where T: TypeFoldable<'tcx>
459 self.infcx.map(|infcx| infcx.resolve_type_vars_if_possible(value))
460 .unwrap_or_else(|| value.clone())
463 fn is_tainted_by_errors(&self) -> bool {
464 self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
467 fn resolve_type_vars_or_error(&self,
469 ty: Option<Ty<'tcx>>)
470 -> McResult<Ty<'tcx>> {
473 let ty = self.resolve_type_vars_if_possible(&ty);
474 if ty.references_error() || ty.is_ty_var() {
475 debug!("resolve_type_vars_or_error: error from {:?}", ty);
482 None if self.is_tainted_by_errors() => Err(()),
484 let id = self.tcx.hir.definitions().find_node_for_hir_id(id);
485 bug!("no type for node {}: {} in mem_categorization",
486 id, self.tcx.hir.node_to_string(id));
491 pub fn node_ty(&self,
493 -> McResult<Ty<'tcx>> {
494 self.resolve_type_vars_or_error(hir_id,
495 self.tables.node_id_to_type_opt(hir_id))
498 pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
499 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
502 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
503 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
506 /// Returns the type of value that this pattern matches against.
507 /// Some non-obvious cases:
509 /// - a `ref x` binding matches against a value of type `T` and gives
510 /// `x` the type `&T`; we return `T`.
511 /// - a pattern with implicit derefs (thanks to default binding
512 /// modes #42640) may look like `Some(x)` but in fact have
513 /// implicit deref patterns attached (e.g., it is really
514 /// `&Some(x)`). In that case, we return the "outermost" type
515 /// (e.g., `&Option<T>).
516 fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
517 // Check for implicit `&` types wrapping the pattern; note
518 // that these are never attached to binding patterns, so
519 // actually this is somewhat "disjoint" from the code below
520 // that aims to account for `ref x`.
521 if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
522 if let Some(first_ty) = vec.first() {
523 debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
528 self.pat_ty_unadjusted(pat)
532 /// Like `pat_ty`, but ignores implicit `&` patterns.
533 fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
534 let base_ty = self.node_ty(pat.hir_id)?;
535 debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
537 // This code detects whether we are looking at a `ref x`,
538 // and if so, figures out what the type *being borrowed* is.
539 let ret_ty = match pat.node {
540 PatKind::Binding(..) => {
541 let bm = *self.tables
544 .expect("missing binding mode");
546 if let ty::BindByReference(_) = bm {
547 // a bind-by-ref means that the base_ty will be the type of the ident itself,
548 // but what we want here is the type of the underlying value being borrowed.
549 // So peel off one-level, turning the &T into T.
550 match base_ty.builtin_deref(false) {
553 debug!("By-ref binding of non-derefable type {:?}", base_ty);
563 debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
568 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
569 // This recursion helper avoids going through *too many*
570 // adjustments, since *only* non-overloaded deref recurses.
571 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
573 adjustments: &[adjustment::Adjustment<'tcx>])
574 -> McResult<cmt<'tcx>> {
575 match adjustments.split_last() {
576 None => mc.cat_expr_unadjusted(expr),
577 Some((adjustment, previous)) => {
578 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
583 helper(self, expr, self.tables.expr_adjustments(expr))
586 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
588 adjustment: &adjustment::Adjustment<'tcx>)
589 -> McResult<cmt<'tcx>> {
590 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
593 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
595 adjustment: &adjustment::Adjustment<'tcx>)
596 -> McResult<cmt<'tcx>>
597 where F: FnOnce() -> McResult<cmt<'tcx>>
599 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
600 let target = self.resolve_type_vars_if_possible(&adjustment.target);
601 match adjustment.kind {
602 adjustment::Adjust::Deref(overloaded) => {
603 // Equivalent to *expr or something similar.
604 let base = if let Some(deref) = overloaded {
605 let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
609 self.cat_rvalue_node(expr.id, expr.span, ref_ty)
613 self.cat_deref(expr, base, false)
616 adjustment::Adjust::NeverToAny |
617 adjustment::Adjust::ReifyFnPointer |
618 adjustment::Adjust::UnsafeFnPointer |
619 adjustment::Adjust::ClosureFnPointer |
620 adjustment::Adjust::MutToConstPointer |
621 adjustment::Adjust::Borrow(_) |
622 adjustment::Adjust::Unsize => {
623 // Result is an rvalue.
624 Ok(self.cat_rvalue_node(expr.id, expr.span, target))
629 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
630 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
632 let expr_ty = self.expr_ty(expr)?;
634 hir::ExprUnary(hir::UnDeref, ref e_base) => {
635 if self.tables.is_method_call(expr) {
636 self.cat_overloaded_place(expr, e_base, false)
638 let base_cmt = self.cat_expr(&e_base)?;
639 self.cat_deref(expr, base_cmt, false)
643 hir::ExprField(ref base, f_name) => {
644 let base_cmt = self.cat_expr(&base)?;
645 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
649 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
652 hir::ExprTupField(ref base, idx) => {
653 let base_cmt = self.cat_expr(&base)?;
654 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
657 hir::ExprIndex(ref base, _) => {
658 if self.tables.is_method_call(expr) {
659 // If this is an index implemented by a method call, then it
660 // will include an implicit deref of the result.
661 // The call to index() returns a `&T` value, which
662 // is an rvalue. That is what we will be
664 self.cat_overloaded_place(expr, base, true)
666 let base_cmt = self.cat_expr(&base)?;
667 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
671 hir::ExprPath(ref qpath) => {
672 let def = self.tables.qpath_def(qpath, expr.hir_id);
673 self.cat_def(expr.id, expr.span, expr_ty, def)
676 hir::ExprType(ref e, _) => {
680 hir::ExprAddrOf(..) | hir::ExprCall(..) |
681 hir::ExprAssign(..) | hir::ExprAssignOp(..) |
682 hir::ExprClosure(..) | hir::ExprRet(..) |
683 hir::ExprUnary(..) | hir::ExprYield(..) |
684 hir::ExprMethodCall(..) | hir::ExprCast(..) |
685 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
686 hir::ExprBinary(..) | hir::ExprWhile(..) |
687 hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
688 hir::ExprLit(..) | hir::ExprBreak(..) |
689 hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
690 hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
691 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
696 pub fn cat_def(&self,
701 -> McResult<cmt<'tcx>> {
702 debug!("cat_def: id={} expr={:?} def={:?}",
706 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
707 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
708 Ok(self.cat_rvalue_node(id, span, expr_ty))
711 Def::Static(def_id, mutbl) => {
712 // `#[thread_local]` statics may not outlive the current function.
713 for attr in &self.tcx.get_attrs(def_id)[..] {
714 if attr.check_name("thread_local") {
715 return Ok(self.cat_rvalue_node(id, span, expr_ty));
721 cat:Categorization::StaticItem,
722 mutbl: if mutbl { McDeclared } else { McImmutable},
728 Def::Upvar(var_id, _, fn_node_id) => {
729 self.cat_upvar(id, span, var_id, fn_node_id)
736 cat: Categorization::Local(vid),
737 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
743 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
747 // Categorize an upvar, complete with invisible derefs of closure
748 // environment and upvar reference as appropriate.
753 fn_node_id: ast::NodeId)
754 -> McResult<cmt<'tcx>>
756 let fn_hir_id = self.tcx.hir.node_to_hir_id(fn_node_id);
758 // An upvar can have up to 3 components. We translate first to a
759 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
760 // field from the environment.
762 // `Categorization::Upvar`. Next, we add a deref through the implicit
763 // environment pointer with an anonymous free region 'env and
764 // appropriate borrow kind for closure kinds that take self by
765 // reference. Finally, if the upvar was captured
766 // by-reference, we add a deref through that reference. The
767 // region of this reference is an inference variable 'up that
768 // was previously generated and recorded in the upvar borrow
769 // map. The borrow kind bk is inferred by based on how the
772 // This results in the following table for concrete closure
776 // ---------------+----------------------+-------------------------------
777 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
778 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
779 // FnOnce | copied | upvar -> &'up bk
781 let kind = match self.node_ty(fn_hir_id)?.sty {
782 ty::TyGenerator(..) => ty::ClosureKind::FnOnce,
783 ty::TyClosure(closure_def_id, closure_substs) => {
785 // During upvar inference we may not know the
786 // closure kind, just use the LATTICE_BOTTOM value.
788 infcx.closure_kind(closure_def_id, closure_substs)
789 .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
792 self.tcx.global_tcx()
793 .lift(&closure_substs)
794 .expect("no inference cx, but inference variables in closure ty")
795 .closure_kind(closure_def_id, self.tcx.global_tcx()),
798 ref t => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", t),
801 let closure_expr_def_id = self.tcx.hir.local_def_id(fn_node_id);
802 let var_hir_id = self.tcx.hir.node_to_hir_id(var_id);
803 let upvar_id = ty::UpvarId {
805 closure_expr_id: closure_expr_def_id.to_local(),
808 let var_ty = self.node_ty(var_hir_id)?;
810 // Mutability of original variable itself
811 let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
813 // Construct the upvar. This represents access to the field
814 // from the environment (perhaps we should eventually desugar
815 // this field further, but it will do for now).
816 let cmt_result = cmt_ {
819 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
825 // If this is a `FnMut` or `Fn` closure, then the above is
826 // conceptually a `&mut` or `&` reference, so we have to add a
828 let cmt_result = match kind {
829 ty::ClosureKind::FnOnce => {
832 ty::ClosureKind::FnMut => {
833 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
835 ty::ClosureKind::Fn => {
836 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
840 // If this is a by-ref capture, then the upvar we loaded is
841 // actually a reference, so we have to add an implicit deref
843 let upvar_capture = self.tables.upvar_capture(upvar_id);
844 let cmt_result = match upvar_capture {
845 ty::UpvarCapture::ByValue => {
848 ty::UpvarCapture::ByRef(upvar_borrow) => {
849 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
853 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
854 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
856 note: NoteUpvarRef(upvar_id)
861 let ret = Rc::new(cmt_result);
862 debug!("cat_upvar ret={:?}", ret);
869 upvar_id: ty::UpvarId,
870 upvar_mutbl: MutabilityCategory,
871 env_borrow_kind: ty::BorrowKind,
872 cmt_result: cmt_<'tcx>)
875 // Region of environment pointer
876 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
877 // The environment of a closure is guaranteed to
878 // outlive any bindings introduced in the body of the
880 scope: upvar_id.closure_expr_id.to_def_id(),
881 bound_region: ty::BrEnv
884 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
886 let var_ty = cmt_result.ty;
888 // We need to add the env deref. This means
889 // that the above is actually immutable and
890 // has a ref type. However, nothing should
891 // actually look at the type, so we can get
892 // away with stuffing a `TyError` in there
893 // instead of bothering to construct a proper
895 let cmt_result = cmt_ {
897 ty: self.tcx.types.err,
901 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
903 // Issue #18335. If variable is declared as immutable, override the
904 // mutability from the environment and substitute an `&T` anyway.
906 McImmutable => { deref_mutbl = McImmutable; }
907 McDeclared | McInherited => { }
913 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
916 note: NoteClosureEnv(upvar_id)
919 debug!("env_deref ret {:?}", ret);
924 /// Returns the lifetime of a temporary created by expr with id `id`.
925 /// This could be `'static` if `id` is part of a constant expression.
926 pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
927 let scope = self.region_scope_tree.temporary_scope(id);
928 self.tcx.mk_region(match scope {
929 Some(scope) => ty::ReScope(scope),
934 pub fn cat_rvalue_node(&self,
939 let hir_id = self.tcx.hir.node_to_hir_id(id);
940 let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
943 // Always promote `[T; 0]` (even when e.g. borrowed mutably).
944 let promotable = match expr_ty.sty {
945 ty::TyArray(_, len) if len.val.to_raw_bits() == Some(0) => true,
949 // Compute maximum lifetime of this rvalue. This is 'static if
950 // we can promote to a constant, otherwise equal to enclosing temp
952 let re = if promotable {
953 self.tcx.types.re_static
955 self.temporary_scope(hir_id.local_id)
957 let ret = self.cat_rvalue(id, span, re, expr_ty);
958 debug!("cat_rvalue_node ret {:?}", ret);
962 pub fn cat_rvalue(&self,
965 temp_scope: ty::Region<'tcx>,
966 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
967 let ret = Rc::new(cmt_ {
970 cat:Categorization::Rvalue(temp_scope),
975 debug!("cat_rvalue ret {:?}", ret);
979 pub fn cat_field<N:ast_node>(&self,
985 let ret = Rc::new(cmt_ {
988 mutbl: base_cmt.mutbl.inherit(),
989 cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
993 debug!("cat_field ret {:?}", ret);
997 pub fn cat_tup_field<N:ast_node>(&self,
1003 let ret = Rc::new(cmt_ {
1006 mutbl: base_cmt.mutbl.inherit(),
1007 cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
1011 debug!("cat_tup_field ret {:?}", ret);
1015 fn cat_overloaded_place(&self,
1019 -> McResult<cmt<'tcx>> {
1020 debug!("cat_overloaded_place: implicit={}", implicit);
1022 // Reconstruct the output assuming it's a reference with the
1023 // same region and mutability as the receiver. This holds for
1024 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1025 let place_ty = self.expr_ty(expr)?;
1026 let base_ty = self.expr_ty_adjusted(base)?;
1028 let (region, mutbl) = match base_ty.sty {
1029 ty::TyRef(region, mt) => (region, mt.mutbl),
1031 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 = self.cat_rvalue_node(expr.id, expr.span, ref_ty);
1040 self.cat_deref(expr, base_cmt, implicit)
1043 pub fn cat_deref<N:ast_node>(&self,
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: {:?}",
1060 let ptr = match base_cmt.ty.sty {
1061 ty::TyAdt(def, ..) if def.is_box() => Unique,
1062 ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
1063 ty::TyRef(r, mt) => {
1064 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
1065 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
1067 ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
1069 let ret = Rc::new(cmt_ {
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:ast_node>(&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 AST node being indexed
1103 //! - `base_cmt`: the cmt of `elt`
1105 let interior_elem = InteriorElement(context);
1107 self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1108 debug!("cat_index ret {:?}", ret);
1112 pub fn cat_imm_interior<N:ast_node>(&self,
1114 base_cmt: cmt<'tcx>,
1115 interior_ty: Ty<'tcx>,
1116 interior: InteriorKind)
1118 let ret = Rc::new(cmt_ {
1121 mutbl: base_cmt.mutbl.inherit(),
1122 cat: Categorization::Interior(base_cmt, interior),
1126 debug!("cat_imm_interior ret={:?}", ret);
1130 pub fn cat_downcast_if_needed<N:ast_node>(&self,
1132 base_cmt: cmt<'tcx>,
1135 // univariant enums do not need downcasts
1136 let base_did = self.tcx.parent_def_id(variant_did).unwrap();
1137 if self.tcx.adt_def(base_did).variants.len() != 1 {
1138 let base_ty = base_cmt.ty;
1139 let ret = Rc::new(cmt_ {
1142 mutbl: base_cmt.mutbl.inherit(),
1143 cat: Categorization::Downcast(base_cmt, variant_did),
1147 debug!("cat_downcast ret={:?}", ret);
1150 debug!("cat_downcast univariant={:?}", base_cmt);
1155 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1156 where F: FnMut(cmt<'tcx>, &hir::Pat),
1158 self.cat_pattern_(cmt, pat, &mut op)
1161 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1162 fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1163 where F : FnMut(cmt<'tcx>, &hir::Pat)
1165 // Here, `cmt` is the categorization for the value being
1166 // matched and pat is the pattern it is being matched against.
1168 // In general, the way that this works is that we walk down
1169 // the pattern, constructing a cmt that represents the path
1170 // that will be taken to reach the value being matched.
1172 // When we encounter named bindings, we take the cmt that has
1173 // been built up and pass it off to guarantee_valid() so that
1174 // we can be sure that the binding will remain valid for the
1175 // duration of the arm.
1177 // (*2) There is subtlety concerning the correspondence between
1178 // pattern ids and types as compared to *expression* ids and
1179 // types. This is explained briefly. on the definition of the
1180 // type `cmt`, so go off and read what it says there, then
1181 // come back and I'll dive into a bit more detail here. :) OK,
1184 // In general, the id of the cmt should be the node that
1185 // "produces" the value---patterns aren't executable code
1186 // exactly, but I consider them to "execute" when they match a
1187 // value, and I consider them to produce the value that was
1188 // matched. So if you have something like:
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: {:?} 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
1249 cmt = self.cat_deref(pat, cmt, true /* implicit */)?;
1251 let cmt = cmt; // lose mutability
1253 // Invoke the callback, but only now, after the `cmt` has adjusted.
1255 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1256 // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1257 // don't want to call `op` with these incompatible values. As written, what happens instead
1258 // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1259 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1260 // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1261 // that (where the `ref` on `x` is implied).
1262 op(cmt.clone(), pat);
1265 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1266 let def = self.tables.qpath_def(qpath, pat.hir_id);
1267 let (cmt, expected_len) = match def {
1269 debug!("access to unresolvable pattern {:?}", pat);
1272 Def::VariantCtor(def_id, CtorKind::Fn) => {
1273 let enum_def = self.tcx.parent_def_id(def_id).unwrap();
1274 (self.cat_downcast_if_needed(pat, cmt, def_id),
1275 self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1277 Def::StructCtor(_, CtorKind::Fn) => {
1278 match self.pat_ty_unadjusted(&pat)?.sty {
1279 ty::TyAdt(adt_def, _) => {
1280 (cmt, adt_def.non_enum_variant().fields.len())
1283 span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1288 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1289 to variant or struct {:?}", def);
1293 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1294 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1295 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1296 InteriorField(PositionalField(i)));
1297 self.cat_pattern_(subcmt, &subpat, op)?;
1301 PatKind::Struct(ref qpath, ref field_pats, _) => {
1302 // {f1: p1, ..., fN: pN}
1303 let def = self.tables.qpath_def(qpath, pat.hir_id);
1304 let cmt = match def {
1306 debug!("access to unresolvable pattern {:?}", pat);
1309 Def::Variant(variant_did) |
1310 Def::VariantCtor(variant_did, ..) => {
1311 self.cat_downcast_if_needed(pat, cmt, variant_did)
1316 for fp in field_pats {
1317 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1318 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1319 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1323 PatKind::Binding(.., Some(ref subpat)) => {
1324 self.cat_pattern_(cmt, &subpat, op)?;
1327 PatKind::Tuple(ref subpats, ddpos) => {
1329 let expected_len = match self.pat_ty_unadjusted(&pat)?.sty {
1330 ty::TyTuple(ref tys) => tys.len(),
1331 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1333 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1334 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1335 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1336 InteriorField(PositionalField(i)));
1337 self.cat_pattern_(subcmt, &subpat, op)?;
1341 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1342 // box p1, &p1, &mut p1. we can ignore the mutability of
1343 // PatKind::Ref since that information is already contained
1345 let subcmt = self.cat_deref(pat, cmt, false)?;
1346 self.cat_pattern_(subcmt, &subpat, op)?;
1349 PatKind::Slice(ref before, ref slice, ref after) => {
1350 let element_ty = match cmt.ty.builtin_index() {
1353 debug!("Explicit index of non-indexable type {:?}", cmt);
1357 let context = InteriorOffsetKind::Pattern;
1358 let elt_cmt = self.cat_index(pat, cmt, element_ty, context)?;
1359 for before_pat in before {
1360 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1362 if let Some(ref slice_pat) = *slice {
1363 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1365 for after_pat in after {
1366 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1370 PatKind::Path(_) | PatKind::Binding(.., None) |
1371 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1380 #[derive(Clone, Debug)]
1381 pub enum Aliasability {
1382 FreelyAliasable(AliasableReason),
1384 ImmutableUnique(Box<Aliasability>),
1387 #[derive(Copy, Clone, Debug)]
1388 pub enum AliasableReason {
1394 impl<'tcx> cmt_<'tcx> {
1395 pub fn guarantor(&self) -> cmt<'tcx> {
1396 //! Returns `self` after stripping away any derefs or
1397 //! interior content. The return value is basically the `cmt` which
1398 //! determines how long the value in `self` remains live.
1401 Categorization::Rvalue(..) |
1402 Categorization::StaticItem |
1403 Categorization::Local(..) |
1404 Categorization::Deref(_, UnsafePtr(..)) |
1405 Categorization::Deref(_, BorrowedPtr(..)) |
1406 Categorization::Deref(_, Implicit(..)) |
1407 Categorization::Upvar(..) => {
1408 Rc::new((*self).clone())
1410 Categorization::Downcast(ref b, _) |
1411 Categorization::Interior(ref b, _) |
1412 Categorization::Deref(ref b, Unique) => {
1418 /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1419 pub fn freely_aliasable(&self) -> Aliasability {
1420 // Maybe non-obvious: copied upvars can only be considered
1421 // non-aliasable in once closures, since any other kind can be
1422 // aliased and eventually recused.
1425 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1426 Categorization::Deref(ref b, Implicit(ty::MutBorrow, _)) |
1427 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1428 Categorization::Deref(ref b, Implicit(ty::UniqueImmBorrow, _)) |
1429 Categorization::Deref(ref b, Unique) |
1430 Categorization::Downcast(ref b, _) |
1431 Categorization::Interior(ref b, _) => {
1432 // Aliasability depends on base cmt
1433 b.freely_aliasable()
1436 Categorization::Rvalue(..) |
1437 Categorization::Local(..) |
1438 Categorization::Upvar(..) |
1439 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1443 Categorization::StaticItem => {
1444 if self.mutbl.is_mutable() {
1445 FreelyAliasable(AliasableStaticMut)
1447 FreelyAliasable(AliasableStatic)
1451 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) |
1452 Categorization::Deref(_, Implicit(ty::ImmBorrow, _)) => {
1453 FreelyAliasable(AliasableBorrowed)
1458 // Digs down through one or two layers of deref and grabs the cmt
1459 // for the upvar if a note indicates there is one.
1460 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1462 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1463 Some(match self.cat {
1464 Categorization::Deref(ref inner, _) => {
1466 Categorization::Deref(ref inner, _) => inner.clone(),
1467 Categorization::Upvar(..) => inner.clone(),
1479 pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1481 Categorization::StaticItem => {
1482 "static item".to_string()
1484 Categorization::Rvalue(..) => {
1485 "non-place".to_string()
1487 Categorization::Local(vid) => {
1488 if tcx.hir.is_argument(vid) {
1489 "argument".to_string()
1491 "local variable".to_string()
1494 Categorization::Deref(_, pk) => {
1495 let upvar = self.upvar();
1496 match upvar.as_ref().map(|i| &i.cat) {
1497 Some(&Categorization::Upvar(ref var)) => {
1504 format!("indexed content")
1507 format!("`Box` content")
1510 format!("dereference of raw pointer")
1512 BorrowedPtr(..) => {
1513 format!("borrowed content")
1519 Categorization::Interior(_, InteriorField(NamedField(_))) => {
1522 Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1523 "anonymous field".to_string()
1525 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1526 "indexed content".to_string()
1528 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1529 "pattern-bound indexed content".to_string()
1531 Categorization::Upvar(ref var) => {
1534 Categorization::Downcast(ref cmt, _) => {
1535 cmt.descriptive_string(tcx)
1541 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1544 BorrowedPtr(ty::ImmBorrow, _) |
1545 Implicit(ty::ImmBorrow, _) => "&",
1546 BorrowedPtr(ty::MutBorrow, _) |
1547 Implicit(ty::MutBorrow, _) => "&mut",
1548 BorrowedPtr(ty::UniqueImmBorrow, _) |
1549 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1550 UnsafePtr(_) => "*",
1554 impl fmt::Debug for InteriorKind {
1555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1557 InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1558 InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1559 InteriorElement(..) => write!(f, "[]"),
1564 impl fmt::Debug for Upvar {
1565 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1566 write!(f, "{:?}/{:?}", self.id, self.kind)
1570 impl fmt::Display for Upvar {
1571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1572 let kind = match self.kind {
1573 ty::ClosureKind::Fn => "Fn",
1574 ty::ClosureKind::FnMut => "FnMut",
1575 ty::ClosureKind::FnOnce => "FnOnce",
1577 write!(f, "captured outer variable in an `{}` closure", kind)