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 an lvalue, then this
30 //! is the address of the lvalue. 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, DefIndex};
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;
90 #[derive(Clone, PartialEq)]
91 pub enum Categorization<'tcx> {
92 Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
94 Upvar(Upvar), // upvar referenced by closure env
95 Local(ast::NodeId), // local variable
96 Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
97 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
98 Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
100 // (*1) downcast is only required if the enum has more than one variant
103 // Represents any kind of upvar
104 #[derive(Clone, Copy, PartialEq)]
107 pub kind: ty::ClosureKind
110 // different kinds of pointers:
111 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
112 pub enum PointerKind<'tcx> {
117 BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
120 UnsafePtr(hir::Mutability),
122 /// Implicit deref of the `&T` that results from an overloaded index `[]`.
123 Implicit(ty::BorrowKind, ty::Region<'tcx>),
126 // We use the term "interior" to mean "something reachable from the
127 // base without a pointer dereference", e.g. a field
128 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
129 pub enum InteriorKind {
130 InteriorField(FieldName),
131 InteriorElement(InteriorOffsetKind),
134 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
136 NamedField(ast::Name),
137 PositionalField(usize)
140 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
141 pub enum InteriorOffsetKind {
142 Index, // e.g. `array_expr[index_expr]`
143 Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
146 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
147 pub enum MutabilityCategory {
148 McImmutable, // Immutable.
149 McDeclared, // Directly declared as mutable.
150 McInherited, // Inherited from the fact that owner is mutable.
153 // A note about the provenance of a `cmt`. This is used for
154 // special-case handling of upvars such as mutability inference.
155 // Upvar categorization can generate a variable number of nested
156 // derefs. The note allows detecting them without deep pattern
157 // matching on the categorization.
158 #[derive(Clone, Copy, PartialEq, Debug)]
160 NoteClosureEnv(ty::UpvarId), // Deref through closure env
161 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
162 NoteNone // Nothing special
165 // `cmt`: "Category, Mutability, and Type".
167 // a complete categorization of a value indicating where it originated
168 // and how it is located, as well as the mutability of the memory in
169 // which the value is stored.
171 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
172 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
173 // always the `id` of the node producing the type; in an expression
174 // like `*x`, the type of this deref node is the deref'd type (`T`),
175 // but in a pattern like `@x`, the `@x` pattern is again a
176 // dereference, but its type is the type *before* the dereference
177 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
178 // fashion. For more details, see the method `cat_pattern`
179 #[derive(Clone, PartialEq)]
180 pub struct cmt_<'tcx> {
181 pub id: ast::NodeId, // id of expr/pat producing this value
182 pub span: Span, // span of same expr/pat
183 pub cat: Categorization<'tcx>, // categorization of expr
184 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
185 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
186 pub note: Note, // Note about the provenance of this cmt
189 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
191 pub enum ImmutabilityBlame<'tcx> {
192 ImmLocal(ast::NodeId),
193 ClosureEnv(DefIndex),
194 LocalDeref(ast::NodeId),
195 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
198 impl<'tcx> cmt_<'tcx> {
199 fn resolve_field(&self, field_name: FieldName) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
201 let adt_def = match self.ty.sty {
202 ty::TyAdt(def, _) => def,
203 ty::TyTuple(..) => return None,
204 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
205 _ => bug!("interior cmt {:?} is not an ADT", self)
207 let variant_def = match self.cat {
208 Categorization::Downcast(_, variant_did) => {
209 adt_def.variant_with_id(variant_did)
212 assert!(adt_def.is_univariant());
216 let field_def = match field_name {
217 NamedField(name) => variant_def.field_named(name),
218 PositionalField(idx) => &variant_def.fields[idx]
220 Some((adt_def, field_def))
223 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
225 Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) |
226 Categorization::Deref(ref base_cmt, Implicit(ty::ImmBorrow, _)) => {
227 // try to figure out where the immutable reference came from
229 Categorization::Local(node_id) =>
230 Some(ImmutabilityBlame::LocalDeref(node_id)),
231 Categorization::Interior(ref base_cmt, InteriorField(field_name)) => {
232 base_cmt.resolve_field(field_name).map(|(adt_def, field_def)| {
233 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
236 Categorization::Upvar(Upvar { id, .. }) => {
237 if let NoteClosureEnv(..) = self.note {
238 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
246 Categorization::Local(node_id) => {
247 Some(ImmutabilityBlame::ImmLocal(node_id))
249 Categorization::Rvalue(..) |
250 Categorization::Upvar(..) |
251 Categorization::Deref(_, UnsafePtr(..)) => {
252 // This should not be reachable up to inference limitations.
255 Categorization::Interior(ref base_cmt, _) |
256 Categorization::Downcast(ref base_cmt, _) |
257 Categorization::Deref(ref base_cmt, _) => {
258 base_cmt.immutability_blame()
260 Categorization::StaticItem => {
261 // Do we want to do something here?
269 fn id(&self) -> ast::NodeId;
270 fn span(&self) -> Span;
273 impl ast_node for hir::Expr {
274 fn id(&self) -> ast::NodeId { self.id }
275 fn span(&self) -> Span { self.span }
278 impl ast_node for hir::Pat {
279 fn id(&self) -> ast::NodeId { self.id }
280 fn span(&self) -> Span { self.span }
284 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
285 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
286 pub region_scope_tree: &'a region::ScopeTree,
287 pub tables: &'a ty::TypeckTables<'tcx>,
288 infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>,
291 pub type McResult<T> = Result<T, ()>;
293 impl MutabilityCategory {
294 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
296 MutImmutable => McImmutable,
297 MutMutable => McDeclared
299 debug!("MutabilityCategory::{}({:?}) => {:?}",
300 "from_mutbl", m, ret);
304 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
305 let ret = match borrow_kind {
306 ty::ImmBorrow => McImmutable,
307 ty::UniqueImmBorrow => McImmutable,
308 ty::MutBorrow => McDeclared,
310 debug!("MutabilityCategory::{}({:?}) => {:?}",
311 "from_borrow_kind", borrow_kind, ret);
315 fn from_pointer_kind(base_mutbl: MutabilityCategory,
316 ptr: PointerKind) -> MutabilityCategory {
317 let ret = match ptr {
321 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
322 MutabilityCategory::from_borrow_kind(borrow_kind)
325 MutabilityCategory::from_mutbl(m)
328 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
329 "from_pointer_kind", base_mutbl, ptr, ret);
333 fn from_local(tcx: TyCtxt, tables: &ty::TypeckTables, id: ast::NodeId) -> MutabilityCategory {
334 let ret = match tcx.hir.get(id) {
335 hir_map::NodeBinding(p) => match p.node {
336 PatKind::Binding(..) => {
337 let bm = *tables.pat_binding_modes()
339 .expect("missing binding mode");
340 if bm == ty::BindByValue(hir::MutMutable) {
346 _ => span_bug!(p.span, "expected identifier pattern")
348 _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
350 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
351 "from_local", id, ret);
355 pub fn inherit(&self) -> MutabilityCategory {
356 let ret = match *self {
357 McImmutable => McImmutable,
358 McDeclared => McInherited,
359 McInherited => McInherited,
361 debug!("{:?}.inherit() => {:?}", self, ret);
365 pub fn is_mutable(&self) -> bool {
366 let ret = match *self {
367 McImmutable => false,
371 debug!("{:?}.is_mutable() => {:?}", self, ret);
375 pub fn is_immutable(&self) -> bool {
376 let ret = match *self {
378 McDeclared | McInherited => false
380 debug!("{:?}.is_immutable() => {:?}", self, ret);
384 pub fn to_user_str(&self) -> &'static str {
386 McDeclared | McInherited => "mutable",
387 McImmutable => "immutable",
392 impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> {
393 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
394 region_scope_tree: &'a region::ScopeTree,
395 tables: &'a ty::TypeckTables<'tcx>)
396 -> MemCategorizationContext<'a, 'tcx, 'tcx> {
397 MemCategorizationContext { tcx, region_scope_tree, tables, infcx: None }
401 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
402 pub fn with_infer(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
403 region_scope_tree: &'a region::ScopeTree,
404 tables: &'a ty::TypeckTables<'tcx>)
405 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
406 MemCategorizationContext {
414 pub fn type_moves_by_default(&self,
415 param_env: ty::ParamEnv<'tcx>,
419 self.infcx.map(|infcx| infcx.type_moves_by_default(param_env, ty, span))
421 self.tcx.lift_to_global(&(param_env, ty)).map(|(param_env, ty)| {
422 ty.moves_by_default(self.tcx.global_tcx(), param_env, span)
428 fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
429 where T: TypeFoldable<'tcx>
431 self.infcx.map(|infcx| infcx.resolve_type_vars_if_possible(value))
432 .unwrap_or_else(|| value.clone())
435 fn is_tainted_by_errors(&self) -> bool {
436 self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
439 fn resolve_type_vars_or_error(&self,
441 ty: Option<Ty<'tcx>>)
442 -> McResult<Ty<'tcx>> {
445 let ty = self.resolve_type_vars_if_possible(&ty);
446 if ty.references_error() || ty.is_ty_var() {
447 debug!("resolve_type_vars_or_error: error from {:?}", ty);
454 None if self.is_tainted_by_errors() => Err(()),
456 let id = self.tcx.hir.definitions().find_node_for_hir_id(id);
457 bug!("no type for node {}: {} in mem_categorization",
458 id, self.tcx.hir.node_to_string(id));
463 pub fn node_ty(&self,
465 -> McResult<Ty<'tcx>> {
466 self.resolve_type_vars_or_error(hir_id,
467 self.tables.node_id_to_type_opt(hir_id))
470 pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
471 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
474 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
475 self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
478 fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
479 let base_ty = self.node_ty(pat.hir_id)?;
480 // FIXME (Issue #18207): This code detects whether we are
481 // looking at a `ref x`, and if so, figures out what the type
482 // *being borrowed* is. But ideally we would put in a more
483 // fundamental fix to this conflated use of the node id.
484 let ret_ty = match pat.node {
485 PatKind::Binding(..) => {
486 let bm = *self.tables
489 .expect("missing binding mode");
491 if let ty::BindByReference(_) = bm {
492 // a bind-by-ref means that the base_ty will be the type of the ident itself,
493 // but what we want here is the type of the underlying value being borrowed.
494 // So peel off one-level, turning the &T into T.
495 match base_ty.builtin_deref(false, ty::NoPreference) {
498 debug!("By-ref binding of non-derefable type {:?}", base_ty);
508 debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
509 pat, base_ty, ret_ty);
513 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
514 // This recursion helper avoids going through *too many*
515 // adjustments, since *only* non-overloaded deref recurses.
516 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
518 adjustments: &[adjustment::Adjustment<'tcx>])
519 -> McResult<cmt<'tcx>> {
520 match adjustments.split_last() {
521 None => mc.cat_expr_unadjusted(expr),
522 Some((adjustment, previous)) => {
523 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
528 helper(self, expr, self.tables.expr_adjustments(expr))
531 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
533 adjustment: &adjustment::Adjustment<'tcx>)
534 -> McResult<cmt<'tcx>> {
535 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
538 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
540 adjustment: &adjustment::Adjustment<'tcx>)
541 -> McResult<cmt<'tcx>>
542 where F: FnOnce() -> McResult<cmt<'tcx>>
544 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
545 let target = self.resolve_type_vars_if_possible(&adjustment.target);
546 match adjustment.kind {
547 adjustment::Adjust::Deref(overloaded) => {
548 // Equivalent to *expr or something similar.
549 let base = if let Some(deref) = overloaded {
550 let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
554 self.cat_rvalue_node(expr.id, expr.span, ref_ty)
558 self.cat_deref(expr, base, false)
561 adjustment::Adjust::NeverToAny |
562 adjustment::Adjust::ReifyFnPointer |
563 adjustment::Adjust::UnsafeFnPointer |
564 adjustment::Adjust::ClosureFnPointer |
565 adjustment::Adjust::MutToConstPointer |
566 adjustment::Adjust::Borrow(_) |
567 adjustment::Adjust::Unsize => {
568 // Result is an rvalue.
569 Ok(self.cat_rvalue_node(expr.id, expr.span, target))
574 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
575 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
577 let expr_ty = self.expr_ty(expr)?;
579 hir::ExprUnary(hir::UnDeref, ref e_base) => {
580 if self.tables.is_method_call(expr) {
581 self.cat_overloaded_lvalue(expr, e_base, false)
583 let base_cmt = self.cat_expr(&e_base)?;
584 self.cat_deref(expr, base_cmt, false)
588 hir::ExprField(ref base, f_name) => {
589 let base_cmt = self.cat_expr(&base)?;
590 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
594 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
597 hir::ExprTupField(ref base, idx) => {
598 let base_cmt = self.cat_expr(&base)?;
599 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
602 hir::ExprIndex(ref base, _) => {
603 if self.tables.is_method_call(expr) {
604 // If this is an index implemented by a method call, then it
605 // will include an implicit deref of the result.
606 // The call to index() returns a `&T` value, which
607 // is an rvalue. That is what we will be
609 self.cat_overloaded_lvalue(expr, base, true)
611 let base_cmt = self.cat_expr(&base)?;
612 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
616 hir::ExprPath(ref qpath) => {
617 let def = self.tables.qpath_def(qpath, expr.hir_id);
618 self.cat_def(expr.id, expr.span, expr_ty, def)
621 hir::ExprType(ref e, _) => {
625 hir::ExprAddrOf(..) | hir::ExprCall(..) |
626 hir::ExprAssign(..) | hir::ExprAssignOp(..) |
627 hir::ExprClosure(..) | hir::ExprRet(..) |
628 hir::ExprUnary(..) | hir::ExprYield(..) |
629 hir::ExprMethodCall(..) | hir::ExprCast(..) |
630 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
631 hir::ExprBinary(..) | hir::ExprWhile(..) |
632 hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
633 hir::ExprLit(..) | hir::ExprBreak(..) |
634 hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
635 hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
636 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
641 pub fn cat_def(&self,
646 -> McResult<cmt<'tcx>> {
647 debug!("cat_def: id={} expr={:?} def={:?}",
651 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
652 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
653 Ok(self.cat_rvalue_node(id, span, expr_ty))
656 Def::Static(def_id, mutbl) => {
657 // `#[thread_local]` statics may not outlive the current function.
658 for attr in &self.tcx.get_attrs(def_id)[..] {
659 if attr.check_name("thread_local") {
660 return Ok(self.cat_rvalue_node(id, span, expr_ty));
666 cat:Categorization::StaticItem,
667 mutbl: if mutbl { McDeclared } else { McImmutable},
673 Def::Upvar(var_id, _, fn_node_id) => {
674 self.cat_upvar(id, span, var_id, fn_node_id)
681 cat: Categorization::Local(vid),
682 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
688 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
692 // Categorize an upvar, complete with invisible derefs of closure
693 // environment and upvar reference as appropriate.
698 fn_node_id: ast::NodeId)
699 -> McResult<cmt<'tcx>>
701 let fn_hir_id = self.tcx.hir.node_to_hir_id(fn_node_id);
703 // An upvar can have up to 3 components. We translate first to a
704 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
705 // field from the environment.
707 // `Categorization::Upvar`. Next, we add a deref through the implicit
708 // environment pointer with an anonymous free region 'env and
709 // appropriate borrow kind for closure kinds that take self by
710 // reference. Finally, if the upvar was captured
711 // by-reference, we add a deref through that reference. The
712 // region of this reference is an inference variable 'up that
713 // was previously generated and recorded in the upvar borrow
714 // map. The borrow kind bk is inferred by based on how the
717 // This results in the following table for concrete closure
721 // ---------------+----------------------+-------------------------------
722 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
723 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
724 // FnOnce | copied | upvar -> &'up bk
726 let kind = match self.node_ty(fn_hir_id)?.sty {
727 ty::TyGenerator(..) => ty::ClosureKind::FnOnce,
729 match self.tables.closure_kinds().get(fn_hir_id) {
730 Some(&(kind, _)) => kind,
731 None => span_bug!(span, "missing closure kind"),
736 let closure_expr_def_index = self.tcx.hir.local_def_id(fn_node_id).index;
737 let var_hir_id = self.tcx.hir.node_to_hir_id(var_id);
738 let upvar_id = ty::UpvarId {
740 closure_expr_id: closure_expr_def_index
743 let var_ty = self.node_ty(var_hir_id)?;
745 // Mutability of original variable itself
746 let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
748 // Construct the upvar. This represents access to the field
749 // from the environment (perhaps we should eventually desugar
750 // this field further, but it will do for now).
751 let cmt_result = cmt_ {
754 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
760 // If this is a `FnMut` or `Fn` closure, then the above is
761 // conceptually a `&mut` or `&` reference, so we have to add a
763 let cmt_result = match kind {
764 ty::ClosureKind::FnOnce => {
767 ty::ClosureKind::FnMut => {
768 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
770 ty::ClosureKind::Fn => {
771 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
775 // If this is a by-ref capture, then the upvar we loaded is
776 // actually a reference, so we have to add an implicit deref
778 let upvar_capture = self.tables.upvar_capture(upvar_id);
779 let cmt_result = match upvar_capture {
780 ty::UpvarCapture::ByValue => {
783 ty::UpvarCapture::ByRef(upvar_borrow) => {
784 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
788 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
789 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
791 note: NoteUpvarRef(upvar_id)
796 let ret = Rc::new(cmt_result);
797 debug!("cat_upvar ret={:?}", ret);
804 upvar_id: ty::UpvarId,
805 upvar_mutbl: MutabilityCategory,
806 env_borrow_kind: ty::BorrowKind,
807 cmt_result: cmt_<'tcx>)
810 // Region of environment pointer
811 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
812 // The environment of a closure is guaranteed to
813 // outlive any bindings introduced in the body of the
815 scope: DefId::local(upvar_id.closure_expr_id),
816 bound_region: ty::BrEnv
819 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
821 let var_ty = cmt_result.ty;
823 // We need to add the env deref. This means
824 // that the above is actually immutable and
825 // has a ref type. However, nothing should
826 // actually look at the type, so we can get
827 // away with stuffing a `TyError` in there
828 // instead of bothering to construct a proper
830 let cmt_result = cmt_ {
832 ty: self.tcx.types.err,
836 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
838 // Issue #18335. If variable is declared as immutable, override the
839 // mutability from the environment and substitute an `&T` anyway.
841 McImmutable => { deref_mutbl = McImmutable; }
842 McDeclared | McInherited => { }
848 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
851 note: NoteClosureEnv(upvar_id)
854 debug!("env_deref ret {:?}", ret);
859 /// Returns the lifetime of a temporary created by expr with id `id`.
860 /// This could be `'static` if `id` is part of a constant expression.
861 pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
862 let scope = self.region_scope_tree.temporary_scope(id);
863 self.tcx.mk_region(match scope {
864 Some(scope) => ty::ReScope(scope),
869 pub fn cat_rvalue_node(&self,
874 let promotable = self.tcx.rvalue_promotable_to_static.borrow().get(&id).cloned()
877 // Always promote `[T; 0]` (even when e.g. borrowed mutably).
878 let promotable = match expr_ty.sty {
879 ty::TyArray(_, len) if
880 len.val.to_const_int().and_then(|i| i.to_u64()) == Some(0) => true,
884 // Compute maximum lifetime of this rvalue. This is 'static if
885 // we can promote to a constant, otherwise equal to enclosing temp
887 let re = if promotable {
888 self.tcx.types.re_static
890 self.temporary_scope(self.tcx.hir.node_to_hir_id(id).local_id)
892 let ret = self.cat_rvalue(id, span, re, expr_ty);
893 debug!("cat_rvalue_node ret {:?}", ret);
897 pub fn cat_rvalue(&self,
900 temp_scope: ty::Region<'tcx>,
901 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
902 let ret = Rc::new(cmt_ {
905 cat:Categorization::Rvalue(temp_scope),
910 debug!("cat_rvalue ret {:?}", ret);
914 pub fn cat_field<N:ast_node>(&self,
920 let ret = Rc::new(cmt_ {
923 mutbl: base_cmt.mutbl.inherit(),
924 cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
928 debug!("cat_field ret {:?}", ret);
932 pub fn cat_tup_field<N:ast_node>(&self,
938 let ret = Rc::new(cmt_ {
941 mutbl: base_cmt.mutbl.inherit(),
942 cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
946 debug!("cat_tup_field ret {:?}", ret);
950 fn cat_overloaded_lvalue(&self,
954 -> McResult<cmt<'tcx>> {
955 debug!("cat_overloaded_lvalue: implicit={}", implicit);
957 // Reconstruct the output assuming it's a reference with the
958 // same region and mutability as the receiver. This holds for
959 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
960 let lvalue_ty = self.expr_ty(expr)?;
961 let base_ty = self.expr_ty_adjusted(base)?;
963 let (region, mutbl) = match base_ty.sty {
964 ty::TyRef(region, mt) => (region, mt.mutbl),
966 span_bug!(expr.span, "cat_overloaded_lvalue: base is not a reference")
969 let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
974 let base_cmt = self.cat_rvalue_node(expr.id, expr.span, ref_ty);
975 self.cat_deref(expr, base_cmt, implicit)
978 pub fn cat_deref<N:ast_node>(&self,
982 -> McResult<cmt<'tcx>> {
983 debug!("cat_deref: base_cmt={:?}", base_cmt);
985 let base_cmt_ty = base_cmt.ty;
986 let deref_ty = match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
989 debug!("Explicit deref of non-derefable type: {:?}",
995 let ptr = match base_cmt.ty.sty {
996 ty::TyAdt(def, ..) if def.is_box() => Unique,
997 ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
998 ty::TyRef(r, mt) => {
999 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
1000 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
1002 ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
1004 let ret = Rc::new(cmt_ {
1007 // For unique ptrs, we inherit mutability from the owning reference.
1008 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1009 cat: Categorization::Deref(base_cmt, ptr),
1013 debug!("cat_deref ret {:?}", ret);
1017 fn cat_index<N:ast_node>(&self,
1019 base_cmt: cmt<'tcx>,
1020 element_ty: Ty<'tcx>,
1021 context: InteriorOffsetKind)
1022 -> McResult<cmt<'tcx>> {
1023 //! Creates a cmt for an indexing operation (`[]`).
1025 //! One subtle aspect of indexing that may not be
1026 //! immediately obvious: for anything other than a fixed-length
1027 //! vector, an operation like `x[y]` actually consists of two
1028 //! disjoint (from the point of view of borrowck) operations.
1029 //! The first is a deref of `x` to create a pointer `p` that points
1030 //! at the first element in the array. The second operation is
1031 //! an index which adds `y*sizeof(T)` to `p` to obtain the
1032 //! pointer to `x[y]`. `cat_index` will produce a resulting
1033 //! cmt containing both this deref and the indexing,
1034 //! presuming that `base_cmt` is not of fixed-length type.
1037 //! - `elt`: the AST node being indexed
1038 //! - `base_cmt`: the cmt of `elt`
1040 let interior_elem = InteriorElement(context);
1042 self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1043 debug!("cat_index ret {:?}", ret);
1047 pub fn cat_imm_interior<N:ast_node>(&self,
1049 base_cmt: cmt<'tcx>,
1050 interior_ty: Ty<'tcx>,
1051 interior: InteriorKind)
1053 let ret = Rc::new(cmt_ {
1056 mutbl: base_cmt.mutbl.inherit(),
1057 cat: Categorization::Interior(base_cmt, interior),
1061 debug!("cat_imm_interior ret={:?}", ret);
1065 pub fn cat_downcast_if_needed<N:ast_node>(&self,
1067 base_cmt: cmt<'tcx>,
1070 // univariant enums do not need downcasts
1071 let base_did = self.tcx.parent_def_id(variant_did).unwrap();
1072 if !self.tcx.adt_def(base_did).is_univariant() {
1073 let base_ty = base_cmt.ty;
1074 let ret = Rc::new(cmt_ {
1077 mutbl: base_cmt.mutbl.inherit(),
1078 cat: Categorization::Downcast(base_cmt, variant_did),
1082 debug!("cat_downcast ret={:?}", ret);
1085 debug!("cat_downcast univariant={:?}", base_cmt);
1090 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1091 where F: FnMut(cmt<'tcx>, &hir::Pat),
1093 self.cat_pattern_(cmt, pat, &mut op)
1096 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1097 fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1098 where F : FnMut(cmt<'tcx>, &hir::Pat)
1100 // Here, `cmt` is the categorization for the value being
1101 // matched and pat is the pattern it is being matched against.
1103 // In general, the way that this works is that we walk down
1104 // the pattern, constructing a cmt that represents the path
1105 // that will be taken to reach the value being matched.
1107 // When we encounter named bindings, we take the cmt that has
1108 // been built up and pass it off to guarantee_valid() so that
1109 // we can be sure that the binding will remain valid for the
1110 // duration of the arm.
1112 // (*2) There is subtlety concerning the correspondence between
1113 // pattern ids and types as compared to *expression* ids and
1114 // types. This is explained briefly. on the definition of the
1115 // type `cmt`, so go off and read what it says there, then
1116 // come back and I'll dive into a bit more detail here. :) OK,
1119 // In general, the id of the cmt should be the node that
1120 // "produces" the value---patterns aren't executable code
1121 // exactly, but I consider them to "execute" when they match a
1122 // value, and I consider them to produce the value that was
1123 // matched. So if you have something like:
1130 // In this case, the cmt and the relevant ids would be:
1132 // CMT Id Type of Id Type of cmt
1135 // ^~~~~~~^ `x` from discr @@int @@int
1136 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1137 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1139 // You can see that the types of the id and the cmt are in
1140 // sync in the first line, because that id is actually the id
1141 // of an expression. But once we get to pattern ids, the types
1142 // step out of sync again. So you'll see below that we always
1143 // get the type of the *subpattern* and use that.
1145 debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1147 // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1148 // `cmt`s are constructed differently from patterns. For example, in
1152 // &&Some(x, ) => { ... },
1157 // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1158 // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1159 // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1161 // `&&Some(x,)` `cmt_foo`
1162 // `&Some(x,)` `deref { cmt_foo}`
1163 // `Some(x,)` `deref { deref { cmt_foo }}`
1164 // (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1166 // The above example has no adjustments. If the code were instead the (after adjustments,
1167 // equivalent) version
1171 // Some(x, ) => { ... },
1176 // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1177 // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1178 // though its assigned type is that of `&&Some(x,)`.
1179 for _ in 0..self.tables
1184 cmt = self.cat_deref(pat, cmt, true /* implicit */)?;
1186 let cmt = cmt; // lose mutability
1188 // Invoke the callback, but only now, after the `cmt` has adjusted.
1190 // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1191 // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1192 // don't want to call `op` with these incompatible values. As written, what happens instead
1193 // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1194 // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1195 // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1196 // that (where the `ref` on `x` is implied).
1197 op(cmt.clone(), pat);
1200 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1201 let def = self.tables.qpath_def(qpath, pat.hir_id);
1202 let (cmt, expected_len) = match def {
1204 debug!("access to unresolvable pattern {:?}", pat);
1207 Def::VariantCtor(def_id, CtorKind::Fn) => {
1208 let enum_def = self.tcx.parent_def_id(def_id).unwrap();
1209 (self.cat_downcast_if_needed(pat, cmt, def_id),
1210 self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1212 Def::StructCtor(_, CtorKind::Fn) => {
1213 match self.pat_ty(&pat)?.sty {
1214 ty::TyAdt(adt_def, _) => {
1215 (cmt, adt_def.struct_variant().fields.len())
1218 span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1223 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1224 to variant or struct {:?}", def);
1228 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1229 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1230 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1231 InteriorField(PositionalField(i)));
1232 self.cat_pattern_(subcmt, &subpat, op)?;
1236 PatKind::Struct(ref qpath, ref field_pats, _) => {
1237 // {f1: p1, ..., fN: pN}
1238 let def = self.tables.qpath_def(qpath, pat.hir_id);
1239 let cmt = match def {
1241 debug!("access to unresolvable pattern {:?}", pat);
1244 Def::Variant(variant_did) |
1245 Def::VariantCtor(variant_did, ..) => {
1246 self.cat_downcast_if_needed(pat, cmt, variant_did)
1251 for fp in field_pats {
1252 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1253 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1254 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1258 PatKind::Binding(.., Some(ref subpat)) => {
1259 self.cat_pattern_(cmt, &subpat, op)?;
1262 PatKind::Tuple(ref subpats, ddpos) => {
1264 let expected_len = match self.pat_ty(&pat)?.sty {
1265 ty::TyTuple(ref tys, _) => tys.len(),
1266 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1268 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1269 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1270 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1271 InteriorField(PositionalField(i)));
1272 self.cat_pattern_(subcmt, &subpat, op)?;
1276 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1277 // box p1, &p1, &mut p1. we can ignore the mutability of
1278 // PatKind::Ref since that information is already contained
1280 let subcmt = self.cat_deref(pat, cmt, false)?;
1281 self.cat_pattern_(subcmt, &subpat, op)?;
1284 PatKind::Slice(ref before, ref slice, ref after) => {
1285 let element_ty = match cmt.ty.builtin_index() {
1288 debug!("Explicit index of non-indexable type {:?}", cmt);
1292 let context = InteriorOffsetKind::Pattern;
1293 let elt_cmt = self.cat_index(pat, cmt, element_ty, context)?;
1294 for before_pat in before {
1295 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1297 if let Some(ref slice_pat) = *slice {
1298 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1300 for after_pat in after {
1301 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1305 PatKind::Path(_) | PatKind::Binding(.., None) |
1306 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1315 #[derive(Clone, Debug)]
1316 pub enum Aliasability {
1317 FreelyAliasable(AliasableReason),
1319 ImmutableUnique(Box<Aliasability>),
1322 #[derive(Copy, Clone, Debug)]
1323 pub enum AliasableReason {
1329 impl<'tcx> cmt_<'tcx> {
1330 pub fn guarantor(&self) -> cmt<'tcx> {
1331 //! Returns `self` after stripping away any derefs or
1332 //! interior content. The return value is basically the `cmt` which
1333 //! determines how long the value in `self` remains live.
1336 Categorization::Rvalue(..) |
1337 Categorization::StaticItem |
1338 Categorization::Local(..) |
1339 Categorization::Deref(_, UnsafePtr(..)) |
1340 Categorization::Deref(_, BorrowedPtr(..)) |
1341 Categorization::Deref(_, Implicit(..)) |
1342 Categorization::Upvar(..) => {
1343 Rc::new((*self).clone())
1345 Categorization::Downcast(ref b, _) |
1346 Categorization::Interior(ref b, _) |
1347 Categorization::Deref(ref b, Unique) => {
1353 /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1354 pub fn freely_aliasable(&self) -> Aliasability {
1355 // Maybe non-obvious: copied upvars can only be considered
1356 // non-aliasable in once closures, since any other kind can be
1357 // aliased and eventually recused.
1360 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1361 Categorization::Deref(ref b, Implicit(ty::MutBorrow, _)) |
1362 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1363 Categorization::Deref(ref b, Implicit(ty::UniqueImmBorrow, _)) |
1364 Categorization::Deref(ref b, Unique) |
1365 Categorization::Downcast(ref b, _) |
1366 Categorization::Interior(ref b, _) => {
1367 // Aliasability depends on base cmt
1368 b.freely_aliasable()
1371 Categorization::Rvalue(..) |
1372 Categorization::Local(..) |
1373 Categorization::Upvar(..) |
1374 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1378 Categorization::StaticItem => {
1379 if self.mutbl.is_mutable() {
1380 FreelyAliasable(AliasableStaticMut)
1382 FreelyAliasable(AliasableStatic)
1386 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) |
1387 Categorization::Deref(_, Implicit(ty::ImmBorrow, _)) => {
1388 FreelyAliasable(AliasableBorrowed)
1393 // Digs down through one or two layers of deref and grabs the cmt
1394 // for the upvar if a note indicates there is one.
1395 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1397 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1398 Some(match self.cat {
1399 Categorization::Deref(ref inner, _) => {
1401 Categorization::Deref(ref inner, _) => inner.clone(),
1402 Categorization::Upvar(..) => inner.clone(),
1414 pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1416 Categorization::StaticItem => {
1417 "static item".to_string()
1419 Categorization::Rvalue(..) => {
1420 "non-lvalue".to_string()
1422 Categorization::Local(vid) => {
1423 if tcx.hir.is_argument(vid) {
1424 "argument".to_string()
1426 "local variable".to_string()
1429 Categorization::Deref(_, pk) => {
1430 let upvar = self.upvar();
1431 match upvar.as_ref().map(|i| &i.cat) {
1432 Some(&Categorization::Upvar(ref var)) => {
1439 format!("indexed content")
1442 format!("`Box` content")
1445 format!("dereference of raw pointer")
1447 BorrowedPtr(..) => {
1448 format!("borrowed content")
1454 Categorization::Interior(_, InteriorField(NamedField(_))) => {
1457 Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1458 "anonymous field".to_string()
1460 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1461 "indexed content".to_string()
1463 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1464 "pattern-bound indexed content".to_string()
1466 Categorization::Upvar(ref var) => {
1469 Categorization::Downcast(ref cmt, _) => {
1470 cmt.descriptive_string(tcx)
1476 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1477 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1478 write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1486 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1487 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1489 Categorization::StaticItem => write!(f, "static"),
1490 Categorization::Rvalue(r) => { write!(f, "rvalue({:?})", r) }
1491 Categorization::Local(id) => {
1492 let name = ty::tls::with(|tcx| tcx.hir.name(id));
1493 write!(f, "local({})", name)
1495 Categorization::Upvar(upvar) => {
1496 write!(f, "upvar({:?})", upvar)
1498 Categorization::Deref(ref cmt, ptr) => {
1499 write!(f, "{:?}-{:?}->", cmt.cat, ptr)
1501 Categorization::Interior(ref cmt, interior) => {
1502 write!(f, "{:?}.{:?}", cmt.cat, interior)
1504 Categorization::Downcast(ref cmt, _) => {
1505 write!(f, "{:?}->(enum)", cmt.cat)
1511 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1514 BorrowedPtr(ty::ImmBorrow, _) |
1515 Implicit(ty::ImmBorrow, _) => "&",
1516 BorrowedPtr(ty::MutBorrow, _) |
1517 Implicit(ty::MutBorrow, _) => "&mut",
1518 BorrowedPtr(ty::UniqueImmBorrow, _) |
1519 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1520 UnsafePtr(_) => "*",
1524 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1527 Unique => write!(f, "Box"),
1528 BorrowedPtr(ty::ImmBorrow, ref r) |
1529 Implicit(ty::ImmBorrow, ref r) => {
1530 write!(f, "&{:?}", r)
1532 BorrowedPtr(ty::MutBorrow, ref r) |
1533 Implicit(ty::MutBorrow, ref r) => {
1534 write!(f, "&{:?} mut", r)
1536 BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1537 Implicit(ty::UniqueImmBorrow, ref r) => {
1538 write!(f, "&{:?} uniq", r)
1540 UnsafePtr(_) => write!(f, "*")
1545 impl fmt::Debug for InteriorKind {
1546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1548 InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1549 InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1550 InteriorElement(..) => write!(f, "[]"),
1555 impl fmt::Debug for Upvar {
1556 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1557 write!(f, "{:?}/{:?}", self.id, self.kind)
1561 impl fmt::Display for Upvar {
1562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1563 let kind = match self.kind {
1564 ty::ClosureKind::Fn => "Fn",
1565 ty::ClosureKind::FnMut => "FnMut",
1566 ty::ClosureKind::FnOnce => "FnOnce",
1568 write!(f, "captured outer variable in an `{}` closure", kind)