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 fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
507 let base_ty = self.node_ty(pat.hir_id)?;
508 // This code detects whether we are looking at a `ref x`,
509 // and if so, figures out what the type *being borrowed* is.
510 let ret_ty = match pat.node {
511 PatKind::Binding(..) => {
512 let bm = *self.tables
515 .expect("missing binding mode");
517 if let ty::BindByReference(_) = bm {
518 // a bind-by-ref means that the base_ty will be the type of the ident itself,
519 // but what we want here is the type of the underlying value being borrowed.
520 // So peel off one-level, turning the &T into T.
521 match base_ty.builtin_deref(false) {
524 debug!("By-ref binding of non-derefable type {:?}", base_ty);
534 debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
535 pat, base_ty, ret_ty);
539 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
540 // This recursion helper avoids going through *too many*
541 // adjustments, since *only* non-overloaded deref recurses.
542 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
544 adjustments: &[adjustment::Adjustment<'tcx>])
545 -> McResult<cmt<'tcx>> {
546 match adjustments.split_last() {
547 None => mc.cat_expr_unadjusted(expr),
548 Some((adjustment, previous)) => {
549 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
554 helper(self, expr, self.tables.expr_adjustments(expr))
557 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
559 adjustment: &adjustment::Adjustment<'tcx>)
560 -> McResult<cmt<'tcx>> {
561 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
564 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
566 adjustment: &adjustment::Adjustment<'tcx>)
567 -> McResult<cmt<'tcx>>
568 where F: FnOnce() -> McResult<cmt<'tcx>>
570 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
571 let target = self.resolve_type_vars_if_possible(&adjustment.target);
572 match adjustment.kind {
573 adjustment::Adjust::Deref(overloaded) => {
574 // Equivalent to *expr or something similar.
575 let base = if let Some(deref) = overloaded {
576 let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
580 self.cat_rvalue_node(expr.id, expr.span, ref_ty)
584 self.cat_deref(expr, base, false)
587 adjustment::Adjust::NeverToAny |
588 adjustment::Adjust::ReifyFnPointer |
589 adjustment::Adjust::UnsafeFnPointer |
590 adjustment::Adjust::ClosureFnPointer |
591 adjustment::Adjust::MutToConstPointer |
592 adjustment::Adjust::Borrow(_) |
593 adjustment::Adjust::Unsize => {
594 // Result is an rvalue.
595 Ok(self.cat_rvalue_node(expr.id, expr.span, target))
600 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
601 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
603 let expr_ty = self.expr_ty(expr)?;
605 hir::ExprUnary(hir::UnDeref, ref e_base) => {
606 if self.tables.is_method_call(expr) {
607 self.cat_overloaded_place(expr, e_base, false)
609 let base_cmt = self.cat_expr(&e_base)?;
610 self.cat_deref(expr, base_cmt, false)
614 hir::ExprField(ref base, f_name) => {
615 let base_cmt = self.cat_expr(&base)?;
616 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
620 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
623 hir::ExprTupField(ref base, idx) => {
624 let base_cmt = self.cat_expr(&base)?;
625 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
628 hir::ExprIndex(ref base, _) => {
629 if self.tables.is_method_call(expr) {
630 // If this is an index implemented by a method call, then it
631 // will include an implicit deref of the result.
632 // The call to index() returns a `&T` value, which
633 // is an rvalue. That is what we will be
635 self.cat_overloaded_place(expr, base, true)
637 let base_cmt = self.cat_expr(&base)?;
638 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
642 hir::ExprPath(ref qpath) => {
643 let def = self.tables.qpath_def(qpath, expr.hir_id);
644 self.cat_def(expr.id, expr.span, expr_ty, def)
647 hir::ExprType(ref e, _) => {
651 hir::ExprAddrOf(..) | hir::ExprCall(..) |
652 hir::ExprAssign(..) | hir::ExprAssignOp(..) |
653 hir::ExprClosure(..) | hir::ExprRet(..) |
654 hir::ExprUnary(..) | hir::ExprYield(..) |
655 hir::ExprMethodCall(..) | hir::ExprCast(..) |
656 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
657 hir::ExprBinary(..) | hir::ExprWhile(..) |
658 hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
659 hir::ExprLit(..) | hir::ExprBreak(..) |
660 hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
661 hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
662 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
667 pub fn cat_def(&self,
672 -> McResult<cmt<'tcx>> {
673 debug!("cat_def: id={} expr={:?} def={:?}",
677 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
678 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
679 Ok(self.cat_rvalue_node(id, span, expr_ty))
682 Def::Static(def_id, mutbl) => {
683 // `#[thread_local]` statics may not outlive the current function.
684 for attr in &self.tcx.get_attrs(def_id)[..] {
685 if attr.check_name("thread_local") {
686 return Ok(self.cat_rvalue_node(id, span, expr_ty));
692 cat:Categorization::StaticItem,
693 mutbl: if mutbl { McDeclared } else { McImmutable},
699 Def::Upvar(var_id, _, fn_node_id) => {
700 self.cat_upvar(id, span, var_id, fn_node_id)
707 cat: Categorization::Local(vid),
708 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
714 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
718 // Categorize an upvar, complete with invisible derefs of closure
719 // environment and upvar reference as appropriate.
724 fn_node_id: ast::NodeId)
725 -> McResult<cmt<'tcx>>
727 let fn_hir_id = self.tcx.hir.node_to_hir_id(fn_node_id);
729 // An upvar can have up to 3 components. We translate first to a
730 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
731 // field from the environment.
733 // `Categorization::Upvar`. Next, we add a deref through the implicit
734 // environment pointer with an anonymous free region 'env and
735 // appropriate borrow kind for closure kinds that take self by
736 // reference. Finally, if the upvar was captured
737 // by-reference, we add a deref through that reference. The
738 // region of this reference is an inference variable 'up that
739 // was previously generated and recorded in the upvar borrow
740 // map. The borrow kind bk is inferred by based on how the
743 // This results in the following table for concrete closure
747 // ---------------+----------------------+-------------------------------
748 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
749 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
750 // FnOnce | copied | upvar -> &'up bk
752 let kind = match self.node_ty(fn_hir_id)?.sty {
753 ty::TyGenerator(..) => ty::ClosureKind::FnOnce,
754 ty::TyClosure(closure_def_id, closure_substs) => {
756 // During upvar inference we may not know the
757 // closure kind, just use the LATTICE_BOTTOM value.
759 infcx.closure_kind(closure_def_id, closure_substs)
760 .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
763 self.tcx.global_tcx()
764 .lift(&closure_substs)
765 .expect("no inference cx, but inference variables in closure ty")
766 .closure_kind(closure_def_id, self.tcx.global_tcx()),
769 ref t => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", t),
772 let closure_expr_def_id = self.tcx.hir.local_def_id(fn_node_id);
773 let var_hir_id = self.tcx.hir.node_to_hir_id(var_id);
774 let upvar_id = ty::UpvarId {
776 closure_expr_id: closure_expr_def_id.to_local(),
779 let var_ty = self.node_ty(var_hir_id)?;
781 // Mutability of original variable itself
782 let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
784 // Construct the upvar. This represents access to the field
785 // from the environment (perhaps we should eventually desugar
786 // this field further, but it will do for now).
787 let cmt_result = cmt_ {
790 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
796 // If this is a `FnMut` or `Fn` closure, then the above is
797 // conceptually a `&mut` or `&` reference, so we have to add a
799 let cmt_result = match kind {
800 ty::ClosureKind::FnOnce => {
803 ty::ClosureKind::FnMut => {
804 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
806 ty::ClosureKind::Fn => {
807 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
811 // If this is a by-ref capture, then the upvar we loaded is
812 // actually a reference, so we have to add an implicit deref
814 let upvar_capture = self.tables.upvar_capture(upvar_id);
815 let cmt_result = match upvar_capture {
816 ty::UpvarCapture::ByValue => {
819 ty::UpvarCapture::ByRef(upvar_borrow) => {
820 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
824 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
825 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
827 note: NoteUpvarRef(upvar_id)
832 let ret = Rc::new(cmt_result);
833 debug!("cat_upvar ret={:?}", ret);
840 upvar_id: ty::UpvarId,
841 upvar_mutbl: MutabilityCategory,
842 env_borrow_kind: ty::BorrowKind,
843 cmt_result: cmt_<'tcx>)
846 // Region of environment pointer
847 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
848 // The environment of a closure is guaranteed to
849 // outlive any bindings introduced in the body of the
851 scope: upvar_id.closure_expr_id.to_def_id(),
852 bound_region: ty::BrEnv
855 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
857 let var_ty = cmt_result.ty;
859 // We need to add the env deref. This means
860 // that the above is actually immutable and
861 // has a ref type. However, nothing should
862 // actually look at the type, so we can get
863 // away with stuffing a `TyError` in there
864 // instead of bothering to construct a proper
866 let cmt_result = cmt_ {
868 ty: self.tcx.types.err,
872 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
874 // Issue #18335. If variable is declared as immutable, override the
875 // mutability from the environment and substitute an `&T` anyway.
877 McImmutable => { deref_mutbl = McImmutable; }
878 McDeclared | McInherited => { }
884 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
887 note: NoteClosureEnv(upvar_id)
890 debug!("env_deref ret {:?}", ret);
895 /// Returns the lifetime of a temporary created by expr with id `id`.
896 /// This could be `'static` if `id` is part of a constant expression.
897 pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
898 let scope = self.region_scope_tree.temporary_scope(id);
899 self.tcx.mk_region(match scope {
900 Some(scope) => ty::ReScope(scope),
905 pub fn cat_rvalue_node(&self,
910 let hir_id = self.tcx.hir.node_to_hir_id(id);
911 let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
914 // Always promote `[T; 0]` (even when e.g. borrowed mutably).
915 let promotable = match expr_ty.sty {
916 ty::TyArray(_, len) if len.val.to_raw_bits() == Some(0) => true,
920 // Compute maximum lifetime of this rvalue. This is 'static if
921 // we can promote to a constant, otherwise equal to enclosing temp
923 let re = if promotable {
924 self.tcx.types.re_static
926 self.temporary_scope(hir_id.local_id)
928 let ret = self.cat_rvalue(id, span, re, expr_ty);
929 debug!("cat_rvalue_node ret {:?}", ret);
933 pub fn cat_rvalue(&self,
936 temp_scope: ty::Region<'tcx>,
937 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
938 let ret = Rc::new(cmt_ {
941 cat:Categorization::Rvalue(temp_scope),
946 debug!("cat_rvalue ret {:?}", ret);
950 pub fn cat_field<N:ast_node>(&self,
956 let ret = Rc::new(cmt_ {
959 mutbl: base_cmt.mutbl.inherit(),
960 cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
964 debug!("cat_field ret {:?}", ret);
968 pub fn cat_tup_field<N:ast_node>(&self,
974 let ret = Rc::new(cmt_ {
977 mutbl: base_cmt.mutbl.inherit(),
978 cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
982 debug!("cat_tup_field ret {:?}", ret);
986 fn cat_overloaded_place(&self,
990 -> McResult<cmt<'tcx>> {
991 debug!("cat_overloaded_place: implicit={}", implicit);
993 // Reconstruct the output assuming it's a reference with the
994 // same region and mutability as the receiver. This holds for
995 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
996 let place_ty = self.expr_ty(expr)?;
997 let base_ty = self.expr_ty_adjusted(base)?;
999 let (region, mutbl) = match base_ty.sty {
1000 ty::TyRef(region, mt) => (region, mt.mutbl),
1002 span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
1005 let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
1010 let base_cmt = self.cat_rvalue_node(expr.id, expr.span, ref_ty);
1011 self.cat_deref(expr, base_cmt, implicit)
1014 pub fn cat_deref<N:ast_node>(&self,
1016 base_cmt: cmt<'tcx>,
1018 -> McResult<cmt<'tcx>> {
1019 debug!("cat_deref: base_cmt={:?}", base_cmt);
1021 let base_cmt_ty = base_cmt.ty;
1022 let deref_ty = match base_cmt_ty.builtin_deref(true) {
1025 debug!("Explicit deref of non-derefable type: {:?}",
1031 let ptr = match base_cmt.ty.sty {
1032 ty::TyAdt(def, ..) if def.is_box() => Unique,
1033 ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
1034 ty::TyRef(r, mt) => {
1035 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
1036 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
1038 ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
1040 let ret = Rc::new(cmt_ {
1043 // For unique ptrs, we inherit mutability from the owning reference.
1044 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1045 cat: Categorization::Deref(base_cmt, ptr),
1049 debug!("cat_deref ret {:?}", ret);
1053 fn cat_index<N:ast_node>(&self,
1055 base_cmt: cmt<'tcx>,
1056 element_ty: Ty<'tcx>,
1057 context: InteriorOffsetKind)
1058 -> McResult<cmt<'tcx>> {
1059 //! Creates a cmt for an indexing operation (`[]`).
1061 //! One subtle aspect of indexing that may not be
1062 //! immediately obvious: for anything other than a fixed-length
1063 //! vector, an operation like `x[y]` actually consists of two
1064 //! disjoint (from the point of view of borrowck) operations.
1065 //! The first is a deref of `x` to create a pointer `p` that points
1066 //! at the first element in the array. The second operation is
1067 //! an index which adds `y*sizeof(T)` to `p` to obtain the
1068 //! pointer to `x[y]`. `cat_index` will produce a resulting
1069 //! cmt containing both this deref and the indexing,
1070 //! presuming that `base_cmt` is not of fixed-length type.
1073 //! - `elt`: the AST node being indexed
1074 //! - `base_cmt`: the cmt of `elt`
1076 let interior_elem = InteriorElement(context);
1078 self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1079 debug!("cat_index ret {:?}", ret);
1083 pub fn cat_imm_interior<N:ast_node>(&self,
1085 base_cmt: cmt<'tcx>,
1086 interior_ty: Ty<'tcx>,
1087 interior: InteriorKind)
1089 let ret = Rc::new(cmt_ {
1092 mutbl: base_cmt.mutbl.inherit(),
1093 cat: Categorization::Interior(base_cmt, interior),
1097 debug!("cat_imm_interior ret={:?}", ret);
1101 pub fn cat_downcast_if_needed<N:ast_node>(&self,
1103 base_cmt: cmt<'tcx>,
1106 // univariant enums do not need downcasts
1107 let base_did = self.tcx.parent_def_id(variant_did).unwrap();
1108 if self.tcx.adt_def(base_did).variants.len() != 1 {
1109 let base_ty = base_cmt.ty;
1110 let ret = Rc::new(cmt_ {
1113 mutbl: base_cmt.mutbl.inherit(),
1114 cat: Categorization::Downcast(base_cmt, variant_did),
1118 debug!("cat_downcast ret={:?}", ret);
1121 debug!("cat_downcast univariant={:?}", base_cmt);
1126 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1127 where F: FnMut(cmt<'tcx>, &hir::Pat),
1129 self.cat_pattern_(cmt, pat, &mut op)
1132 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1133 fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1134 where F : FnMut(cmt<'tcx>, &hir::Pat)
1136 // Here, `cmt` is the categorization for the value being
1137 // matched and pat is the pattern it is being matched against.
1139 // In general, the way that this works is that we walk down
1140 // the pattern, constructing a cmt that represents the path
1141 // that will be taken to reach the value being matched.
1143 // When we encounter named bindings, we take the cmt that has
1144 // been built up and pass it off to guarantee_valid() so that
1145 // we can be sure that the binding will remain valid for the
1146 // duration of the arm.
1148 // (*2) There is subtlety concerning the correspondence between
1149 // pattern ids and types as compared to *expression* ids and
1150 // types. This is explained briefly. on the definition of the
1151 // type `cmt`, so go off and read what it says there, then
1152 // come back and I'll dive into a bit more detail here. :) OK,
1155 // In general, the id of the cmt should be the node that
1156 // "produces" the value---patterns aren't executable code
1157 // exactly, but I consider them to "execute" when they match a
1158 // value, and I consider them to produce the value that was
1159 // matched. So if you have something like:
1166 // In this case, the cmt and the relevant ids would be:
1168 // CMT Id Type of Id Type of cmt
1171 // ^~~~~~~^ `x` from discr @@int @@int
1172 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1173 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1175 // You can see that the types of the id and the cmt are in
1176 // sync in the first line, because that id is actually the id
1177 // of an expression. But once we get to pattern ids, the types
1178 // step out of sync again. So you'll see below that we always
1179 // get the type of the *subpattern* and use that.
1181 debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1183 // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1184 // `cmt`s are constructed differently from patterns. For example, in
1188 // &&Some(x, ) => { ... },
1193 // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1194 // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1195 // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1197 // `&&Some(x,)` `cmt_foo`
1198 // `&Some(x,)` `deref { cmt_foo}`
1199 // `Some(x,)` `deref { deref { cmt_foo }}`
1200 // (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1202 // The above example has no adjustments. If the code were instead the (after adjustments,
1203 // equivalent) version
1207 // Some(x, ) => { ... },
1212 // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1213 // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1214 // though its assigned type is that of `&&Some(x,)`.
1215 for _ in 0..self.tables
1220 cmt = self.cat_deref(pat, cmt, true /* implicit */)?;
1222 let cmt = cmt; // lose mutability
1224 // Invoke the callback, but only now, after the `cmt` has adjusted.
1226 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1227 // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1228 // don't want to call `op` with these incompatible values. As written, what happens instead
1229 // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1230 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1231 // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1232 // that (where the `ref` on `x` is implied).
1233 op(cmt.clone(), pat);
1236 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1237 let def = self.tables.qpath_def(qpath, pat.hir_id);
1238 let (cmt, expected_len) = match def {
1240 debug!("access to unresolvable pattern {:?}", pat);
1243 Def::VariantCtor(def_id, CtorKind::Fn) => {
1244 let enum_def = self.tcx.parent_def_id(def_id).unwrap();
1245 (self.cat_downcast_if_needed(pat, cmt, def_id),
1246 self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1248 Def::StructCtor(_, CtorKind::Fn) => {
1249 match self.pat_ty(&pat)?.sty {
1250 ty::TyAdt(adt_def, _) => {
1251 (cmt, adt_def.non_enum_variant().fields.len())
1254 span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1259 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1260 to variant or struct {:?}", def);
1264 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1265 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1266 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1267 InteriorField(PositionalField(i)));
1268 self.cat_pattern_(subcmt, &subpat, op)?;
1272 PatKind::Struct(ref qpath, ref field_pats, _) => {
1273 // {f1: p1, ..., fN: pN}
1274 let def = self.tables.qpath_def(qpath, pat.hir_id);
1275 let cmt = match def {
1277 debug!("access to unresolvable pattern {:?}", pat);
1280 Def::Variant(variant_did) |
1281 Def::VariantCtor(variant_did, ..) => {
1282 self.cat_downcast_if_needed(pat, cmt, variant_did)
1287 for fp in field_pats {
1288 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1289 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1290 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1294 PatKind::Binding(.., Some(ref subpat)) => {
1295 self.cat_pattern_(cmt, &subpat, op)?;
1298 PatKind::Tuple(ref subpats, ddpos) => {
1300 let expected_len = match self.pat_ty(&pat)?.sty {
1301 ty::TyTuple(ref tys) => tys.len(),
1302 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1304 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1305 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1306 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1307 InteriorField(PositionalField(i)));
1308 self.cat_pattern_(subcmt, &subpat, op)?;
1312 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1313 // box p1, &p1, &mut p1. we can ignore the mutability of
1314 // PatKind::Ref since that information is already contained
1316 let subcmt = self.cat_deref(pat, cmt, false)?;
1317 self.cat_pattern_(subcmt, &subpat, op)?;
1320 PatKind::Slice(ref before, ref slice, ref after) => {
1321 let element_ty = match cmt.ty.builtin_index() {
1324 debug!("Explicit index of non-indexable type {:?}", cmt);
1328 let context = InteriorOffsetKind::Pattern;
1329 let elt_cmt = self.cat_index(pat, cmt, element_ty, context)?;
1330 for before_pat in before {
1331 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1333 if let Some(ref slice_pat) = *slice {
1334 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1336 for after_pat in after {
1337 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1341 PatKind::Path(_) | PatKind::Binding(.., None) |
1342 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1351 #[derive(Clone, Debug)]
1352 pub enum Aliasability {
1353 FreelyAliasable(AliasableReason),
1355 ImmutableUnique(Box<Aliasability>),
1358 #[derive(Copy, Clone, Debug)]
1359 pub enum AliasableReason {
1365 impl<'tcx> cmt_<'tcx> {
1366 pub fn guarantor(&self) -> cmt<'tcx> {
1367 //! Returns `self` after stripping away any derefs or
1368 //! interior content. The return value is basically the `cmt` which
1369 //! determines how long the value in `self` remains live.
1372 Categorization::Rvalue(..) |
1373 Categorization::StaticItem |
1374 Categorization::Local(..) |
1375 Categorization::Deref(_, UnsafePtr(..)) |
1376 Categorization::Deref(_, BorrowedPtr(..)) |
1377 Categorization::Deref(_, Implicit(..)) |
1378 Categorization::Upvar(..) => {
1379 Rc::new((*self).clone())
1381 Categorization::Downcast(ref b, _) |
1382 Categorization::Interior(ref b, _) |
1383 Categorization::Deref(ref b, Unique) => {
1389 /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1390 pub fn freely_aliasable(&self) -> Aliasability {
1391 // Maybe non-obvious: copied upvars can only be considered
1392 // non-aliasable in once closures, since any other kind can be
1393 // aliased and eventually recused.
1396 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1397 Categorization::Deref(ref b, Implicit(ty::MutBorrow, _)) |
1398 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1399 Categorization::Deref(ref b, Implicit(ty::UniqueImmBorrow, _)) |
1400 Categorization::Deref(ref b, Unique) |
1401 Categorization::Downcast(ref b, _) |
1402 Categorization::Interior(ref b, _) => {
1403 // Aliasability depends on base cmt
1404 b.freely_aliasable()
1407 Categorization::Rvalue(..) |
1408 Categorization::Local(..) |
1409 Categorization::Upvar(..) |
1410 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1414 Categorization::StaticItem => {
1415 if self.mutbl.is_mutable() {
1416 FreelyAliasable(AliasableStaticMut)
1418 FreelyAliasable(AliasableStatic)
1422 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) |
1423 Categorization::Deref(_, Implicit(ty::ImmBorrow, _)) => {
1424 FreelyAliasable(AliasableBorrowed)
1429 // Digs down through one or two layers of deref and grabs the cmt
1430 // for the upvar if a note indicates there is one.
1431 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1433 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1434 Some(match self.cat {
1435 Categorization::Deref(ref inner, _) => {
1437 Categorization::Deref(ref inner, _) => inner.clone(),
1438 Categorization::Upvar(..) => inner.clone(),
1450 pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1452 Categorization::StaticItem => {
1453 "static item".to_string()
1455 Categorization::Rvalue(..) => {
1456 "non-place".to_string()
1458 Categorization::Local(vid) => {
1459 if tcx.hir.is_argument(vid) {
1460 "argument".to_string()
1462 "local variable".to_string()
1465 Categorization::Deref(_, pk) => {
1466 let upvar = self.upvar();
1467 match upvar.as_ref().map(|i| &i.cat) {
1468 Some(&Categorization::Upvar(ref var)) => {
1475 format!("indexed content")
1478 format!("`Box` content")
1481 format!("dereference of raw pointer")
1483 BorrowedPtr(..) => {
1484 format!("borrowed content")
1490 Categorization::Interior(_, InteriorField(NamedField(_))) => {
1493 Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1494 "anonymous field".to_string()
1496 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1497 "indexed content".to_string()
1499 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1500 "pattern-bound indexed content".to_string()
1502 Categorization::Upvar(ref var) => {
1505 Categorization::Downcast(ref cmt, _) => {
1506 cmt.descriptive_string(tcx)
1512 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1515 BorrowedPtr(ty::ImmBorrow, _) |
1516 Implicit(ty::ImmBorrow, _) => "&",
1517 BorrowedPtr(ty::MutBorrow, _) |
1518 Implicit(ty::MutBorrow, _) => "&mut",
1519 BorrowedPtr(ty::UniqueImmBorrow, _) |
1520 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1521 UnsafePtr(_) => "*",
1525 impl fmt::Debug for InteriorKind {
1526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1528 InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1529 InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1530 InteriorElement(..) => write!(f, "[]"),
1535 impl fmt::Debug for Upvar {
1536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1537 write!(f, "{:?}/{:?}", self.id, self.kind)
1541 impl fmt::Display for Upvar {
1542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543 let kind = match self.kind {
1544 ty::ClosureKind::Fn => "Fn",
1545 ty::ClosureKind::FnMut => "FnMut",
1546 ty::ClosureKind::FnOnce => "FnOnce",
1548 write!(f, "captured outer variable in an `{}` closure", kind)