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::ElementKind::*;
67 pub use self::MutabilityCategory::*;
68 pub use self::AliasableReason::*;
69 pub use self::Note::*;
71 use self::Aliasability::*;
73 use middle::region::RegionMaps;
74 use hir::def_id::DefId;
75 use hir::map as hir_map;
77 use hir::def::{Def, CtorKind};
79 use ty::{self, Ty, TyCtxt};
81 use hir::{MutImmutable, MutMutable, PatKind};
82 use hir::pat_util::EnumerateAndAdjustIterator;
90 #[derive(Clone, PartialEq)]
91 pub enum Categorization<'tcx> {
92 // temporary val, argument is its scope
93 Rvalue(ty::Region<'tcx>, ty::Region<'tcx>),
95 Upvar(Upvar), // upvar referenced by closure env
96 Local(ast::NodeId), // local variable
97 Deref(cmt<'tcx>, usize, PointerKind<'tcx>), // deref of a ptr
98 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
99 Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
101 // (*1) downcast is only required if the enum has more than one variant
104 // Represents any kind of upvar
105 #[derive(Clone, Copy, PartialEq)]
108 pub kind: ty::ClosureKind
111 // different kinds of pointers:
112 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
113 pub enum PointerKind<'tcx> {
118 BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
121 UnsafePtr(hir::Mutability),
123 /// Implicit deref of the `&T` that results from an overloaded index `[]`.
124 Implicit(ty::BorrowKind, ty::Region<'tcx>),
127 // We use the term "interior" to mean "something reachable from the
128 // base without a pointer dereference", e.g. a field
129 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
130 pub enum InteriorKind {
131 InteriorField(FieldName),
132 InteriorElement(InteriorOffsetKind, ElementKind),
135 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
137 NamedField(ast::Name),
138 PositionalField(usize)
141 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
142 pub enum InteriorOffsetKind {
143 Index, // e.g. `array_expr[index_expr]`
144 Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
147 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
148 pub enum ElementKind {
153 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
154 pub enum MutabilityCategory {
155 McImmutable, // Immutable.
156 McDeclared, // Directly declared as mutable.
157 McInherited, // Inherited from the fact that owner is mutable.
160 // A note about the provenance of a `cmt`. This is used for
161 // special-case handling of upvars such as mutability inference.
162 // Upvar categorization can generate a variable number of nested
163 // derefs. The note allows detecting them without deep pattern
164 // matching on the categorization.
165 #[derive(Clone, Copy, PartialEq, Debug)]
167 NoteClosureEnv(ty::UpvarId), // Deref through closure env
168 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
169 NoteNone // Nothing special
172 // `cmt`: "Category, Mutability, and Type".
174 // a complete categorization of a value indicating where it originated
175 // and how it is located, as well as the mutability of the memory in
176 // which the value is stored.
178 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
179 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
180 // always the `id` of the node producing the type; in an expression
181 // like `*x`, the type of this deref node is the deref'd type (`T`),
182 // but in a pattern like `@x`, the `@x` pattern is again a
183 // dereference, but its type is the type *before* the dereference
184 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
185 // fashion. For more details, see the method `cat_pattern`
186 #[derive(Clone, PartialEq)]
187 pub struct cmt_<'tcx> {
188 pub id: ast::NodeId, // id of expr/pat producing this value
189 pub span: Span, // span of same expr/pat
190 pub cat: Categorization<'tcx>, // categorization of expr
191 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
192 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
193 pub note: Note, // Note about the provenance of this cmt
196 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
198 pub enum ImmutabilityBlame<'tcx> {
199 ImmLocal(ast::NodeId),
200 ClosureEnv(ast::NodeId),
201 LocalDeref(ast::NodeId),
202 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
205 impl<'tcx> cmt_<'tcx> {
206 fn resolve_field(&self, field_name: FieldName) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
208 let adt_def = match self.ty.sty {
209 ty::TyAdt(def, _) => def,
210 ty::TyTuple(..) => return None,
211 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
212 _ => bug!("interior cmt {:?} is not an ADT", self)
214 let variant_def = match self.cat {
215 Categorization::Downcast(_, variant_did) => {
216 adt_def.variant_with_id(variant_did)
219 assert!(adt_def.is_univariant());
223 let field_def = match field_name {
224 NamedField(name) => variant_def.field_named(name),
225 PositionalField(idx) => &variant_def.fields[idx]
227 Some((adt_def, field_def))
230 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
232 Categorization::Deref(ref base_cmt, _, BorrowedPtr(ty::ImmBorrow, _)) |
233 Categorization::Deref(ref base_cmt, _, Implicit(ty::ImmBorrow, _)) => {
234 // try to figure out where the immutable reference came from
236 Categorization::Local(node_id) =>
237 Some(ImmutabilityBlame::LocalDeref(node_id)),
238 Categorization::Interior(ref base_cmt, InteriorField(field_name)) => {
239 base_cmt.resolve_field(field_name).map(|(adt_def, field_def)| {
240 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
243 Categorization::Upvar(Upvar { id, .. }) => {
244 if let NoteClosureEnv(..) = self.note {
245 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
253 Categorization::Local(node_id) => {
254 Some(ImmutabilityBlame::ImmLocal(node_id))
256 Categorization::Rvalue(..) |
257 Categorization::Upvar(..) |
258 Categorization::Deref(.., UnsafePtr(..)) => {
259 // This should not be reachable up to inference limitations.
262 Categorization::Interior(ref base_cmt, _) |
263 Categorization::Downcast(ref base_cmt, _) |
264 Categorization::Deref(ref base_cmt, _, _) => {
265 base_cmt.immutability_blame()
267 Categorization::StaticItem => {
268 // Do we want to do something here?
276 fn id(&self) -> ast::NodeId;
277 fn span(&self) -> Span;
280 impl ast_node for hir::Expr {
281 fn id(&self) -> ast::NodeId { self.id }
282 fn span(&self) -> Span { self.span }
285 impl ast_node for hir::Pat {
286 fn id(&self) -> ast::NodeId { self.id }
287 fn span(&self) -> Span { self.span }
291 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
292 pub infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
293 pub region_maps: &'a RegionMaps,
294 options: MemCategorizationOptions,
297 #[derive(Copy, Clone, Default)]
298 pub struct MemCategorizationOptions {
299 // If true, then when analyzing a closure upvar, if the closure
300 // has a missing kind, we treat it like a Fn closure. When false,
301 // we ICE if the closure has a missing kind. Should be false
302 // except during closure kind inference. It is used by the
303 // mem-categorization code to be able to have stricter assertions
304 // (which are always true except during upvar inference).
305 pub during_closure_kind_inference: bool,
308 pub type McResult<T> = Result<T, ()>;
310 impl MutabilityCategory {
311 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
313 MutImmutable => McImmutable,
314 MutMutable => McDeclared
316 debug!("MutabilityCategory::{}({:?}) => {:?}",
317 "from_mutbl", m, ret);
321 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
322 let ret = match borrow_kind {
323 ty::ImmBorrow => McImmutable,
324 ty::UniqueImmBorrow => McImmutable,
325 ty::MutBorrow => McDeclared,
327 debug!("MutabilityCategory::{}({:?}) => {:?}",
328 "from_borrow_kind", borrow_kind, ret);
332 fn from_pointer_kind(base_mutbl: MutabilityCategory,
333 ptr: PointerKind) -> MutabilityCategory {
334 let ret = match ptr {
338 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
339 MutabilityCategory::from_borrow_kind(borrow_kind)
342 MutabilityCategory::from_mutbl(m)
345 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
346 "from_pointer_kind", base_mutbl, ptr, ret);
350 fn from_local(tcx: TyCtxt, id: ast::NodeId) -> MutabilityCategory {
351 let ret = match tcx.hir.get(id) {
352 hir_map::NodeLocal(p) => match p.node {
353 PatKind::Binding(bind_mode, ..) => {
354 if bind_mode == hir::BindByValue(hir::MutMutable) {
360 _ => span_bug!(p.span, "expected identifier pattern")
362 _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
364 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
365 "from_local", id, ret);
369 pub fn inherit(&self) -> MutabilityCategory {
370 let ret = match *self {
371 McImmutable => McImmutable,
372 McDeclared => McInherited,
373 McInherited => McInherited,
375 debug!("{:?}.inherit() => {:?}", self, ret);
379 pub fn is_mutable(&self) -> bool {
380 let ret = match *self {
381 McImmutable => false,
385 debug!("{:?}.is_mutable() => {:?}", self, ret);
389 pub fn is_immutable(&self) -> bool {
390 let ret = match *self {
392 McDeclared | McInherited => false
394 debug!("{:?}.is_immutable() => {:?}", self, ret);
398 pub fn to_user_str(&self) -> &'static str {
400 McDeclared | McInherited => "mutable",
401 McImmutable => "immutable",
406 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
407 /// Context should be the `DefId` we use to fetch region-maps.
408 pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
409 region_maps: &'a RegionMaps)
410 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
411 MemCategorizationContext::with_options(infcx,
413 MemCategorizationOptions::default())
416 pub fn with_options(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
417 region_maps: &'a RegionMaps,
418 options: MemCategorizationOptions)
419 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
420 MemCategorizationContext {
422 region_maps: region_maps,
427 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
431 fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
432 match self.infcx.node_ty(expr.id) {
435 debug!("expr_ty({:?}) yielded Err", expr);
441 fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
442 self.infcx.expr_ty_adjusted(expr)
445 fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
446 self.infcx.node_ty(id)
449 fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
450 let base_ty = self.infcx.node_ty(pat.id)?;
451 // FIXME (Issue #18207): This code detects whether we are
452 // looking at a `ref x`, and if so, figures out what the type
453 // *being borrowed* is. But ideally we would put in a more
454 // fundamental fix to this conflated use of the node id.
455 let ret_ty = match pat.node {
456 PatKind::Binding(hir::BindByRef(_), ..) => {
457 // a bind-by-ref means that the base_ty will be the type of the ident itself,
458 // but what we want here is the type of the underlying value being borrowed.
459 // So peel off one-level, turning the &T into T.
460 match base_ty.builtin_deref(false, ty::NoPreference) {
463 debug!("By-ref binding of non-derefable type {:?}", base_ty);
470 debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
471 pat, base_ty, ret_ty);
475 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
476 match self.infcx.tables.borrow().adjustments.get(&expr.id) {
479 self.cat_expr_unadjusted(expr)
482 Some(adjustment) => {
483 match adjustment.kind {
484 adjustment::Adjust::DerefRef {
489 // Equivalent to *expr or something similar.
490 self.cat_expr_autoderefd(expr, autoderefs)
493 adjustment::Adjust::NeverToAny |
494 adjustment::Adjust::ReifyFnPointer |
495 adjustment::Adjust::UnsafeFnPointer |
496 adjustment::Adjust::ClosureFnPointer |
497 adjustment::Adjust::MutToConstPointer |
498 adjustment::Adjust::DerefRef {..} => {
499 debug!("cat_expr({:?}): {:?}",
502 // Result is an rvalue.
503 let expr_ty = self.expr_ty_adjusted(expr)?;
504 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
511 pub fn cat_expr_autoderefd(&self,
514 -> McResult<cmt<'tcx>> {
515 let mut cmt = self.cat_expr_unadjusted(expr)?;
516 debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
519 for deref in 1..autoderefs + 1 {
520 cmt = self.cat_deref(expr, cmt, deref)?;
525 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
526 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
528 let expr_ty = self.expr_ty(expr)?;
530 hir::ExprUnary(hir::UnDeref, ref e_base) => {
531 let base_cmt = self.cat_expr(&e_base)?;
532 self.cat_deref(expr, base_cmt, 0)
535 hir::ExprField(ref base, f_name) => {
536 let base_cmt = self.cat_expr(&base)?;
537 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
541 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
544 hir::ExprTupField(ref base, idx) => {
545 let base_cmt = self.cat_expr(&base)?;
546 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
549 hir::ExprIndex(ref base, _) => {
550 let method_call = ty::MethodCall::expr(expr.id());
551 match self.infcx.node_method_ty(method_call) {
553 // If this is an index implemented by a method call, then it
554 // will include an implicit deref of the result.
555 let ret_ty = self.overloaded_method_return_ty(method_ty);
557 // The index method always returns an `&T`, so
558 // dereference it to find the result type.
559 let elem_ty = match ret_ty.sty {
560 ty::TyRef(_, mt) => mt.ty,
562 debug!("cat_expr_unadjusted: return type of overloaded index is {:?}?",
568 // The call to index() returns a `&T` value, which
569 // is an rvalue. That is what we will be
571 let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
572 Ok(self.cat_deref_common(expr, base_cmt, 1, elem_ty, true))
575 self.cat_index(expr, self.cat_expr(&base)?, InteriorOffsetKind::Index)
580 hir::ExprPath(ref qpath) => {
581 let def = self.infcx.tables.borrow().qpath_def(qpath, expr.id);
582 self.cat_def(expr.id, expr.span, expr_ty, def)
585 hir::ExprType(ref e, _) => {
589 hir::ExprAddrOf(..) | hir::ExprCall(..) |
590 hir::ExprAssign(..) | hir::ExprAssignOp(..) |
591 hir::ExprClosure(..) | hir::ExprRet(..) |
593 hir::ExprMethodCall(..) | hir::ExprCast(..) |
594 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
595 hir::ExprBinary(..) | hir::ExprWhile(..) |
596 hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
597 hir::ExprLit(..) | hir::ExprBreak(..) |
598 hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
599 hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
600 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
605 pub fn cat_def(&self,
610 -> McResult<cmt<'tcx>> {
611 debug!("cat_def: id={} expr={:?} def={:?}",
615 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
616 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
617 Ok(self.cat_rvalue_node(id, span, expr_ty))
620 Def::Static(_, mutbl) => {
624 cat:Categorization::StaticItem,
625 mutbl: if mutbl { McDeclared } else { McImmutable},
631 Def::Upvar(def_id, _, fn_node_id) => {
632 let var_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
633 let ty = self.node_ty(fn_node_id)?;
635 ty::TyClosure(closure_id, _) => {
636 match self.infcx.closure_kind(closure_id) {
638 self.cat_upvar(id, span, var_id, fn_node_id, kind)
641 if !self.options.during_closure_kind_inference {
644 "No closure kind for {:?}",
648 // during closure kind inference, we
649 // don't know the closure kind yet, but
650 // it's ok because we detect that we are
651 // accessing an upvar and handle that
652 // case specially anyhow. Use Fn
654 self.cat_upvar(id, span, var_id, fn_node_id, ty::ClosureKind::Fn)
661 "Upvar of non-closure {} - {:?}",
668 Def::Local(def_id) => {
669 let vid = self.tcx().hir.as_local_node_id(def_id).unwrap();
673 cat: Categorization::Local(vid),
674 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
680 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
684 // Categorize an upvar, complete with invisible derefs of closure
685 // environment and upvar reference as appropriate.
690 fn_node_id: ast::NodeId,
691 kind: ty::ClosureKind)
692 -> McResult<cmt<'tcx>>
694 // An upvar can have up to 3 components. We translate first to a
695 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
696 // field from the environment.
698 // `Categorization::Upvar`. Next, we add a deref through the implicit
699 // environment pointer with an anonymous free region 'env and
700 // appropriate borrow kind for closure kinds that take self by
701 // reference. Finally, if the upvar was captured
702 // by-reference, we add a deref through that reference. The
703 // region of this reference is an inference variable 'up that
704 // was previously generated and recorded in the upvar borrow
705 // map. The borrow kind bk is inferred by based on how the
708 // This results in the following table for concrete closure
712 // ---------------+----------------------+-------------------------------
713 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
714 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
715 // FnOnce | copied | upvar -> &'up bk
717 let upvar_id = ty::UpvarId { var_id: var_id,
718 closure_expr_id: fn_node_id };
719 let var_ty = self.node_ty(var_id)?;
721 // Mutability of original variable itself
722 let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
724 // Construct the upvar. This represents access to the field
725 // from the environment (perhaps we should eventually desugar
726 // this field further, but it will do for now).
727 let cmt_result = cmt_ {
730 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
736 // If this is a `FnMut` or `Fn` closure, then the above is
737 // conceptually a `&mut` or `&` reference, so we have to add a
739 let cmt_result = match kind {
740 ty::ClosureKind::FnOnce => {
743 ty::ClosureKind::FnMut => {
744 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
746 ty::ClosureKind::Fn => {
747 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
751 // If this is a by-ref capture, then the upvar we loaded is
752 // actually a reference, so we have to add an implicit deref
754 let upvar_id = ty::UpvarId { var_id: var_id,
755 closure_expr_id: fn_node_id };
756 let upvar_capture = self.infcx.upvar_capture(upvar_id).unwrap();
757 let cmt_result = match upvar_capture {
758 ty::UpvarCapture::ByValue => {
761 ty::UpvarCapture::ByRef(upvar_borrow) => {
762 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
766 cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
767 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
769 note: NoteUpvarRef(upvar_id)
774 let ret = Rc::new(cmt_result);
775 debug!("cat_upvar ret={:?}", ret);
782 upvar_id: ty::UpvarId,
783 upvar_mutbl: MutabilityCategory,
784 env_borrow_kind: ty::BorrowKind,
785 cmt_result: cmt_<'tcx>)
788 // Region of environment pointer
789 let env_region = self.tcx().mk_region(ty::ReFree(ty::FreeRegion {
790 // The environment of a closure is guaranteed to
791 // outlive any bindings introduced in the body of the
793 scope: self.tcx().hir.local_def_id(upvar_id.closure_expr_id),
794 bound_region: ty::BrEnv
797 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
799 let var_ty = cmt_result.ty;
801 // We need to add the env deref. This means
802 // that the above is actually immutable and
803 // has a ref type. However, nothing should
804 // actually look at the type, so we can get
805 // away with stuffing a `TyError` in there
806 // instead of bothering to construct a proper
808 let cmt_result = cmt_ {
810 ty: self.tcx().types.err,
814 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
816 // Issue #18335. If variable is declared as immutable, override the
817 // mutability from the environment and substitute an `&T` anyway.
819 McImmutable => { deref_mutbl = McImmutable; }
820 McDeclared | McInherited => { }
826 cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
829 note: NoteClosureEnv(upvar_id)
832 debug!("env_deref ret {:?}", ret);
837 /// Returns the lifetime of a temporary created by expr with id `id`.
838 /// This could be `'static` if `id` is part of a constant expression.
839 pub fn temporary_scope(&self, id: ast::NodeId) -> (ty::Region<'tcx>, ty::Region<'tcx>)
841 let (scope, old_scope) =
842 self.region_maps.old_and_new_temporary_scope(id);
843 (self.tcx().mk_region(match scope {
844 Some(scope) => ty::ReScope(scope),
847 self.tcx().mk_region(match old_scope {
848 Some(scope) => ty::ReScope(scope),
853 pub fn cat_rvalue_node(&self,
858 let promotable = self.tcx().rvalue_promotable_to_static.borrow().get(&id).cloned()
861 // When the corresponding feature isn't toggled, only promote `[T; 0]`.
862 let promotable = match expr_ty.sty {
863 ty::TyArray(_, 0) => true,
864 _ => promotable && self.tcx().sess.features.borrow().rvalue_static_promotion,
867 // Compute maximum lifetime of this rvalue. This is 'static if
868 // we can promote to a constant, otherwise equal to enclosing temp
870 let (re, old_re) = if promotable {
871 (self.tcx().types.re_static,
872 self.tcx().types.re_static)
874 self.temporary_scope(id)
876 let ret = self.cat_rvalue(id, span, re, old_re, expr_ty);
877 debug!("cat_rvalue_node ret {:?}", ret);
881 pub fn cat_rvalue(&self,
884 temp_scope: ty::Region<'tcx>,
885 old_temp_scope: ty::Region<'tcx>,
886 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
887 let ret = Rc::new(cmt_ {
890 cat:Categorization::Rvalue(temp_scope, old_temp_scope),
895 debug!("cat_rvalue ret {:?}", ret);
899 pub fn cat_field<N:ast_node>(&self,
905 let ret = Rc::new(cmt_ {
908 mutbl: base_cmt.mutbl.inherit(),
909 cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
913 debug!("cat_field ret {:?}", ret);
917 pub fn cat_tup_field<N:ast_node>(&self,
923 let ret = Rc::new(cmt_ {
926 mutbl: base_cmt.mutbl.inherit(),
927 cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
931 debug!("cat_tup_field ret {:?}", ret);
935 fn cat_deref<N:ast_node>(&self,
939 -> McResult<cmt<'tcx>> {
940 let method_call = ty::MethodCall {
942 autoderef: deref_cnt as u32
944 let method_ty = self.infcx.node_method_ty(method_call);
946 debug!("cat_deref: method_call={:?} method_ty={:?}",
947 method_call, method_ty.map(|ty| ty));
949 let base_cmt = match method_ty {
952 self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap();
953 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
957 let base_cmt_ty = base_cmt.ty;
958 match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
960 let ret = self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, false);
961 debug!("cat_deref ret {:?}", ret);
965 debug!("Explicit deref of non-derefable type: {:?}",
972 fn cat_deref_common<N:ast_node>(&self,
980 let ptr = match base_cmt.ty.sty {
981 ty::TyAdt(def, ..) if def.is_box() => Unique,
982 ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
983 ty::TyRef(r, mt) => {
984 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
985 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
987 ref ty => bug!("unexpected type in cat_deref_common: {:?}", ty)
989 let ret = Rc::new(cmt_ {
992 // For unique ptrs, we inherit mutability from the owning reference.
993 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
994 cat: Categorization::Deref(base_cmt, deref_cnt, ptr),
998 debug!("cat_deref_common ret {:?}", ret);
1002 pub fn cat_index<N:ast_node>(&self,
1004 mut base_cmt: cmt<'tcx>,
1005 context: InteriorOffsetKind)
1006 -> McResult<cmt<'tcx>> {
1007 //! Creates a cmt for an indexing operation (`[]`).
1009 //! One subtle aspect of indexing that may not be
1010 //! immediately obvious: for anything other than a fixed-length
1011 //! vector, an operation like `x[y]` actually consists of two
1012 //! disjoint (from the point of view of borrowck) operations.
1013 //! The first is a deref of `x` to create a pointer `p` that points
1014 //! at the first element in the array. The second operation is
1015 //! an index which adds `y*sizeof(T)` to `p` to obtain the
1016 //! pointer to `x[y]`. `cat_index` will produce a resulting
1017 //! cmt containing both this deref and the indexing,
1018 //! presuming that `base_cmt` is not of fixed-length type.
1021 //! - `elt`: the AST node being indexed
1022 //! - `base_cmt`: the cmt of `elt`
1024 let method_call = ty::MethodCall::expr(elt.id());
1025 let method_ty = self.infcx.node_method_ty(method_call);
1027 let (element_ty, element_kind) = match method_ty {
1028 Some(method_ty) => {
1029 let ref_ty = self.overloaded_method_return_ty(method_ty);
1030 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
1032 (ref_ty.builtin_deref(false, ty::NoPreference).unwrap().ty,
1033 ElementKind::OtherElement)
1036 match base_cmt.ty.builtin_index() {
1037 Some(ty) => (ty, ElementKind::VecElement),
1039 debug!("Explicit index of non-indexable type {:?}", base_cmt);
1046 let interior_elem = InteriorElement(context, element_kind);
1048 self.cat_imm_interior(elt, base_cmt.clone(), element_ty, interior_elem);
1049 debug!("cat_index ret {:?}", ret);
1053 pub fn cat_imm_interior<N:ast_node>(&self,
1055 base_cmt: cmt<'tcx>,
1056 interior_ty: Ty<'tcx>,
1057 interior: InteriorKind)
1059 let ret = Rc::new(cmt_ {
1062 mutbl: base_cmt.mutbl.inherit(),
1063 cat: Categorization::Interior(base_cmt, interior),
1067 debug!("cat_imm_interior ret={:?}", ret);
1071 pub fn cat_downcast<N:ast_node>(&self,
1073 base_cmt: cmt<'tcx>,
1074 downcast_ty: Ty<'tcx>,
1077 let ret = Rc::new(cmt_ {
1080 mutbl: base_cmt.mutbl.inherit(),
1081 cat: Categorization::Downcast(base_cmt, variant_did),
1085 debug!("cat_downcast ret={:?}", ret);
1089 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1090 where F: FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat),
1092 self.cat_pattern_(cmt, pat, &mut op)
1095 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1096 fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1097 where F : FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat)
1099 // Here, `cmt` is the categorization for the value being
1100 // matched and pat is the pattern it is being matched against.
1102 // In general, the way that this works is that we walk down
1103 // the pattern, constructing a cmt that represents the path
1104 // that will be taken to reach the value being matched.
1106 // When we encounter named bindings, we take the cmt that has
1107 // been built up and pass it off to guarantee_valid() so that
1108 // we can be sure that the binding will remain valid for the
1109 // duration of the arm.
1111 // (*2) There is subtlety concerning the correspondence between
1112 // pattern ids and types as compared to *expression* ids and
1113 // types. This is explained briefly. on the definition of the
1114 // type `cmt`, so go off and read what it says there, then
1115 // come back and I'll dive into a bit more detail here. :) OK,
1118 // In general, the id of the cmt should be the node that
1119 // "produces" the value---patterns aren't executable code
1120 // exactly, but I consider them to "execute" when they match a
1121 // value, and I consider them to produce the value that was
1122 // matched. So if you have something like:
1129 // In this case, the cmt and the relevant ids would be:
1131 // CMT Id Type of Id Type of cmt
1134 // ^~~~~~~^ `x` from discr @@int @@int
1135 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1136 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1138 // You can see that the types of the id and the cmt are in
1139 // sync in the first line, because that id is actually the id
1140 // of an expression. But once we get to pattern ids, the types
1141 // step out of sync again. So you'll see below that we always
1142 // get the type of the *subpattern* and use that.
1144 debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1146 op(self, cmt.clone(), pat);
1148 // Note: This goes up here (rather than within the PatKind::TupleStruct arm
1149 // alone) because PatKind::Struct can also refer to variants.
1150 let cmt = match pat.node {
1151 PatKind::Path(hir::QPath::Resolved(_, ref path)) |
1152 PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) |
1153 PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => {
1156 debug!("access to unresolvable pattern {:?}", pat);
1159 Def::Variant(variant_did) |
1160 Def::VariantCtor(variant_did, ..) => {
1161 // univariant enums do not need downcasts
1162 let enum_did = self.tcx().parent_def_id(variant_did).unwrap();
1163 if !self.tcx().adt_def(enum_did).is_univariant() {
1164 self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1176 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1177 let def = self.infcx.tables.borrow().qpath_def(qpath, pat.id);
1178 let expected_len = match def {
1179 Def::VariantCtor(def_id, CtorKind::Fn) => {
1180 let enum_def = self.tcx().parent_def_id(def_id).unwrap();
1181 self.tcx().adt_def(enum_def).variant_with_id(def_id).fields.len()
1183 Def::StructCtor(_, CtorKind::Fn) => {
1184 match self.pat_ty(&pat)?.sty {
1185 ty::TyAdt(adt_def, _) => {
1186 adt_def.struct_variant().fields.len()
1189 span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1194 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1195 to variant or struct {:?}", def);
1199 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1200 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1201 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1202 InteriorField(PositionalField(i)));
1203 self.cat_pattern_(subcmt, &subpat, op)?;
1207 PatKind::Struct(_, ref field_pats, _) => {
1208 // {f1: p1, ..., fN: pN}
1209 for fp in field_pats {
1210 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1211 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1212 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1216 PatKind::Binding(.., Some(ref subpat)) => {
1217 self.cat_pattern_(cmt, &subpat, op)?;
1220 PatKind::Tuple(ref subpats, ddpos) => {
1222 let expected_len = match self.pat_ty(&pat)?.sty {
1223 ty::TyTuple(ref tys, _) => tys.len(),
1224 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1226 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1227 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1228 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1229 InteriorField(PositionalField(i)));
1230 self.cat_pattern_(subcmt, &subpat, op)?;
1234 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1235 // box p1, &p1, &mut p1. we can ignore the mutability of
1236 // PatKind::Ref since that information is already contained
1238 let subcmt = self.cat_deref(pat, cmt, 0)?;
1239 self.cat_pattern_(subcmt, &subpat, op)?;
1242 PatKind::Slice(ref before, ref slice, ref after) => {
1243 let context = InteriorOffsetKind::Pattern;
1244 let elt_cmt = self.cat_index(pat, cmt, context)?;
1245 for before_pat in before {
1246 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1248 if let Some(ref slice_pat) = *slice {
1249 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1251 for after_pat in after {
1252 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1256 PatKind::Path(_) | PatKind::Binding(.., None) |
1257 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1265 fn overloaded_method_return_ty(&self,
1266 method_ty: Ty<'tcx>)
1269 // When we process an overloaded `*` or `[]` etc, we often
1270 // need to extract the return type of the method. These method
1271 // types are generated by method resolution and always have
1272 // all late-bound regions fully instantiated, so we just want
1273 // to skip past the binder.
1274 self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1279 #[derive(Clone, Debug)]
1280 pub enum Aliasability {
1281 FreelyAliasable(AliasableReason),
1283 ImmutableUnique(Box<Aliasability>),
1286 #[derive(Copy, Clone, Debug)]
1287 pub enum AliasableReason {
1293 impl<'tcx> cmt_<'tcx> {
1294 pub fn guarantor(&self) -> cmt<'tcx> {
1295 //! Returns `self` after stripping away any derefs or
1296 //! interior content. The return value is basically the `cmt` which
1297 //! determines how long the value in `self` remains live.
1300 Categorization::Rvalue(..) |
1301 Categorization::StaticItem |
1302 Categorization::Local(..) |
1303 Categorization::Deref(.., UnsafePtr(..)) |
1304 Categorization::Deref(.., BorrowedPtr(..)) |
1305 Categorization::Deref(.., Implicit(..)) |
1306 Categorization::Upvar(..) => {
1307 Rc::new((*self).clone())
1309 Categorization::Downcast(ref b, _) |
1310 Categorization::Interior(ref b, _) |
1311 Categorization::Deref(ref b, _, Unique) => {
1317 /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1318 pub fn freely_aliasable(&self) -> Aliasability {
1319 // Maybe non-obvious: copied upvars can only be considered
1320 // non-aliasable in once closures, since any other kind can be
1321 // aliased and eventually recused.
1324 Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1325 Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1326 Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1327 Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1328 Categorization::Deref(ref b, _, Unique) |
1329 Categorization::Downcast(ref b, _) |
1330 Categorization::Interior(ref b, _) => {
1331 // Aliasability depends on base cmt
1332 b.freely_aliasable()
1335 Categorization::Rvalue(..) |
1336 Categorization::Local(..) |
1337 Categorization::Upvar(..) |
1338 Categorization::Deref(.., UnsafePtr(..)) => { // yes, it's aliasable, but...
1342 Categorization::StaticItem => {
1343 if self.mutbl.is_mutable() {
1344 FreelyAliasable(AliasableStaticMut)
1346 FreelyAliasable(AliasableStatic)
1350 Categorization::Deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) |
1351 Categorization::Deref(_, _, Implicit(ty::ImmBorrow, _)) => {
1352 FreelyAliasable(AliasableBorrowed)
1357 // Digs down through one or two layers of deref and grabs the cmt
1358 // for the upvar if a note indicates there is one.
1359 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1361 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1362 Some(match self.cat {
1363 Categorization::Deref(ref inner, ..) => {
1365 Categorization::Deref(ref inner, ..) => inner.clone(),
1366 Categorization::Upvar(..) => inner.clone(),
1378 pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1380 Categorization::StaticItem => {
1381 "static item".to_string()
1383 Categorization::Rvalue(..) => {
1384 "non-lvalue".to_string()
1386 Categorization::Local(vid) => {
1387 if tcx.hir.is_argument(vid) {
1388 "argument".to_string()
1390 "local variable".to_string()
1393 Categorization::Deref(.., pk) => {
1394 let upvar = self.upvar();
1395 match upvar.as_ref().map(|i| &i.cat) {
1396 Some(&Categorization::Upvar(ref var)) => {
1403 format!("indexed content")
1406 format!("`Box` content")
1409 format!("dereference of raw pointer")
1411 BorrowedPtr(..) => {
1412 format!("borrowed content")
1418 Categorization::Interior(_, InteriorField(NamedField(_))) => {
1421 Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1422 "anonymous field".to_string()
1424 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1426 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1428 "indexed content".to_string()
1430 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1432 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1434 "pattern-bound indexed content".to_string()
1436 Categorization::Upvar(ref var) => {
1439 Categorization::Downcast(ref cmt, _) => {
1440 cmt.descriptive_string(tcx)
1446 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448 write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1456 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1457 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1459 Categorization::StaticItem => write!(f, "static"),
1460 Categorization::Rvalue(r, or) => {
1461 write!(f, "rvalue({:?}, {:?})", r, or)
1463 Categorization::Local(id) => {
1464 let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1465 write!(f, "local({})", name)
1467 Categorization::Upvar(upvar) => {
1468 write!(f, "upvar({:?})", upvar)
1470 Categorization::Deref(ref cmt, derefs, ptr) => {
1471 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1473 Categorization::Interior(ref cmt, interior) => {
1474 write!(f, "{:?}.{:?}", cmt.cat, interior)
1476 Categorization::Downcast(ref cmt, _) => {
1477 write!(f, "{:?}->(enum)", cmt.cat)
1483 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1486 BorrowedPtr(ty::ImmBorrow, _) |
1487 Implicit(ty::ImmBorrow, _) => "&",
1488 BorrowedPtr(ty::MutBorrow, _) |
1489 Implicit(ty::MutBorrow, _) => "&mut",
1490 BorrowedPtr(ty::UniqueImmBorrow, _) |
1491 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1492 UnsafePtr(_) => "*",
1496 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 Unique => write!(f, "Box"),
1500 BorrowedPtr(ty::ImmBorrow, ref r) |
1501 Implicit(ty::ImmBorrow, ref r) => {
1502 write!(f, "&{:?}", r)
1504 BorrowedPtr(ty::MutBorrow, ref r) |
1505 Implicit(ty::MutBorrow, ref r) => {
1506 write!(f, "&{:?} mut", r)
1508 BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1509 Implicit(ty::UniqueImmBorrow, ref r) => {
1510 write!(f, "&{:?} uniq", r)
1512 UnsafePtr(_) => write!(f, "*")
1517 impl fmt::Debug for InteriorKind {
1518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1520 InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1521 InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1522 InteriorElement(..) => write!(f, "[]"),
1527 impl fmt::Debug for Upvar {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529 write!(f, "{:?}/{:?}", self.id, self.kind)
1533 impl fmt::Display for Upvar {
1534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1535 let kind = match self.kind {
1536 ty::ClosureKind::Fn => "Fn",
1537 ty::ClosureKind::FnMut => "FnMut",
1538 ty::ClosureKind::FnOnce => "FnOnce",
1540 write!(f, "captured outer variable in an `{}` closure", kind)