]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
cbe69de4010322404032be88775a12510d6bf924
[rust.git] / src / librustc / middle / mem_categorization.rs
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.
4 //
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.
10
11 //! # Categorization
12 //!
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)
17 //!
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
21 //! forms):
22 //!
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
27 //!
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.
32 //!
33 //! Now, cat_expr() classifies the expression Expr and the address A=ToAddr(Expr)
34 //! as follows:
35 //!
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
41 //!
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.
46 //!
47 //! ## By-reference upvars
48 //!
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:
52 //!
53 //!     let mut x = 3;
54 //!     let y = 5;
55 //!     let inc = || x += y;
56 //!
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.
60
61 #![allow(non_camel_case_types)]
62
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::*;
70
71 use self::Aliasability::*;
72
73 use middle::region::RegionMaps;
74 use hir::def_id::DefId;
75 use hir::map as hir_map;
76 use infer::InferCtxt;
77 use hir::def::{Def, CtorKind};
78 use ty::adjustment;
79 use ty::{self, Ty, TyCtxt};
80
81 use hir::{MutImmutable, MutMutable, PatKind};
82 use hir::pat_util::EnumerateAndAdjustIterator;
83 use hir;
84 use syntax::ast;
85 use syntax_pos::Span;
86
87 use std::fmt;
88 use std::rc::Rc;
89
90 #[derive(Clone, PartialEq)]
91 pub enum Categorization<'tcx> {
92     // temporary val, argument is its scope
93     Rvalue(ty::Region<'tcx>, ty::Region<'tcx>),
94     StaticItem,
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)
100
101     // (*1) downcast is only required if the enum has more than one variant
102 }
103
104 // Represents any kind of upvar
105 #[derive(Clone, Copy, PartialEq)]
106 pub struct Upvar {
107     pub id: ty::UpvarId,
108     pub kind: ty::ClosureKind
109 }
110
111 // different kinds of pointers:
112 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
113 pub enum PointerKind<'tcx> {
114     /// `Box<T>`
115     Unique,
116
117     /// `&T`
118     BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
119
120     /// `*T`
121     UnsafePtr(hir::Mutability),
122
123     /// Implicit deref of the `&T` that results from an overloaded index `[]`.
124     Implicit(ty::BorrowKind, ty::Region<'tcx>),
125 }
126
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),
133 }
134
135 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
136 pub enum FieldName {
137     NamedField(ast::Name),
138     PositionalField(usize)
139 }
140
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]) { ... }`
145 }
146
147 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
148 pub enum ElementKind {
149     VecElement,
150     OtherElement,
151 }
152
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.
158 }
159
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)]
166 pub enum Note {
167     NoteClosureEnv(ty::UpvarId), // Deref through closure env
168     NoteUpvarRef(ty::UpvarId),   // Deref through by-ref upvar
169     NoteNone                     // Nothing special
170 }
171
172 // `cmt`: "Category, Mutability, and Type".
173 //
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.
177 //
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
194 }
195
196 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
197
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)
203 }
204
205 impl<'tcx> cmt_<'tcx> {
206     fn resolve_field(&self, field_name: FieldName) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
207     {
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)
213         };
214         let variant_def = match self.cat {
215             Categorization::Downcast(_, variant_did) => {
216                 adt_def.variant_with_id(variant_did)
217             }
218             _ => {
219                 assert!(adt_def.is_univariant());
220                 &adt_def.variants[0]
221             }
222         };
223         let field_def = match field_name {
224             NamedField(name) => variant_def.field_named(name),
225             PositionalField(idx) => &variant_def.fields[idx]
226         };
227         Some((adt_def, field_def))
228     }
229
230     pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
231         match self.cat {
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
235                 match base_cmt.cat {
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)
241                         })
242                     }
243                     Categorization::Upvar(Upvar { id, .. }) => {
244                         if let NoteClosureEnv(..) = self.note {
245                             Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
246                         } else {
247                             None
248                         }
249                     }
250                     _ => None
251                 }
252             }
253             Categorization::Local(node_id) => {
254                 Some(ImmutabilityBlame::ImmLocal(node_id))
255             }
256             Categorization::Rvalue(..) |
257             Categorization::Upvar(..) |
258             Categorization::Deref(.., UnsafePtr(..)) => {
259                 // This should not be reachable up to inference limitations.
260                 None
261             }
262             Categorization::Interior(ref base_cmt, _) |
263             Categorization::Downcast(ref base_cmt, _) |
264             Categorization::Deref(ref base_cmt, _, _) => {
265                 base_cmt.immutability_blame()
266             }
267             Categorization::StaticItem => {
268                 // Do we want to do something here?
269                 None
270             }
271         }
272     }
273 }
274
275 pub trait ast_node {
276     fn id(&self) -> ast::NodeId;
277     fn span(&self) -> Span;
278 }
279
280 impl ast_node for hir::Expr {
281     fn id(&self) -> ast::NodeId { self.id }
282     fn span(&self) -> Span { self.span }
283 }
284
285 impl ast_node for hir::Pat {
286     fn id(&self) -> ast::NodeId { self.id }
287     fn span(&self) -> Span { self.span }
288 }
289
290 #[derive(Clone)]
291 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
292     pub infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
293     pub region_maps: &'a RegionMaps<'tcx>,
294     options: MemCategorizationOptions,
295 }
296
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,
306 }
307
308 pub type McResult<T> = Result<T, ()>;
309
310 impl MutabilityCategory {
311     pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
312         let ret = match m {
313             MutImmutable => McImmutable,
314             MutMutable => McDeclared
315         };
316         debug!("MutabilityCategory::{}({:?}) => {:?}",
317                "from_mutbl", m, ret);
318         ret
319     }
320
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,
326         };
327         debug!("MutabilityCategory::{}({:?}) => {:?}",
328                "from_borrow_kind", borrow_kind, ret);
329         ret
330     }
331
332     fn from_pointer_kind(base_mutbl: MutabilityCategory,
333                          ptr: PointerKind) -> MutabilityCategory {
334         let ret = match ptr {
335             Unique => {
336                 base_mutbl.inherit()
337             }
338             BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
339                 MutabilityCategory::from_borrow_kind(borrow_kind)
340             }
341             UnsafePtr(m) => {
342                 MutabilityCategory::from_mutbl(m)
343             }
344         };
345         debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
346                "from_pointer_kind", base_mutbl, ptr, ret);
347         ret
348     }
349
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) {
355                         McDeclared
356                     } else {
357                         McImmutable
358                     }
359                 }
360                 _ => span_bug!(p.span, "expected identifier pattern")
361             },
362             _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
363         };
364         debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
365                "from_local", id, ret);
366         ret
367     }
368
369     pub fn inherit(&self) -> MutabilityCategory {
370         let ret = match *self {
371             McImmutable => McImmutable,
372             McDeclared => McInherited,
373             McInherited => McInherited,
374         };
375         debug!("{:?}.inherit() => {:?}", self, ret);
376         ret
377     }
378
379     pub fn is_mutable(&self) -> bool {
380         let ret = match *self {
381             McImmutable => false,
382             McInherited => true,
383             McDeclared => true,
384         };
385         debug!("{:?}.is_mutable() => {:?}", self, ret);
386         ret
387     }
388
389     pub fn is_immutable(&self) -> bool {
390         let ret = match *self {
391             McImmutable => true,
392             McDeclared | McInherited => false
393         };
394         debug!("{:?}.is_immutable() => {:?}", self, ret);
395         ret
396     }
397
398     pub fn to_user_str(&self) -> &'static str {
399         match *self {
400             McDeclared | McInherited => "mutable",
401             McImmutable => "immutable",
402         }
403     }
404 }
405
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<'tcx>)
410                -> MemCategorizationContext<'a, 'gcx, 'tcx> {
411         MemCategorizationContext::with_options(infcx, region_maps, MemCategorizationOptions::default())
412     }
413
414     pub fn with_options(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
415                         region_maps: &'a RegionMaps<'tcx>,
416                         options: MemCategorizationOptions)
417                         -> MemCategorizationContext<'a, 'gcx, 'tcx> {
418         MemCategorizationContext {
419             infcx: infcx,
420             region_maps: region_maps,
421             options: options,
422         }
423     }
424
425     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
426         self.infcx.tcx
427     }
428
429     fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
430         match self.infcx.node_ty(expr.id) {
431             Ok(t) => Ok(t),
432             Err(()) => {
433                 debug!("expr_ty({:?}) yielded Err", expr);
434                 Err(())
435             }
436         }
437     }
438
439     fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
440         self.infcx.expr_ty_adjusted(expr)
441     }
442
443     fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
444         self.infcx.node_ty(id)
445     }
446
447     fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
448         let base_ty = self.infcx.node_ty(pat.id)?;
449         // FIXME (Issue #18207): This code detects whether we are
450         // looking at a `ref x`, and if so, figures out what the type
451         // *being borrowed* is.  But ideally we would put in a more
452         // fundamental fix to this conflated use of the node id.
453         let ret_ty = match pat.node {
454             PatKind::Binding(hir::BindByRef(_), ..) => {
455                 // a bind-by-ref means that the base_ty will be the type of the ident itself,
456                 // but what we want here is the type of the underlying value being borrowed.
457                 // So peel off one-level, turning the &T into T.
458                 match base_ty.builtin_deref(false, ty::NoPreference) {
459                     Some(t) => t.ty,
460                     None => {
461                         debug!("By-ref binding of non-derefable type {:?}", base_ty);
462                         return Err(());
463                     }
464                 }
465             }
466             _ => base_ty,
467         };
468         debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
469                pat, base_ty, ret_ty);
470         Ok(ret_ty)
471     }
472
473     pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
474         match self.infcx.tables.borrow().adjustments.get(&expr.id) {
475             None => {
476                 // No adjustments.
477                 self.cat_expr_unadjusted(expr)
478             }
479
480             Some(adjustment) => {
481                 match adjustment.kind {
482                     adjustment::Adjust::DerefRef {
483                         autoderefs,
484                         autoref: None,
485                         unsize: false
486                     } => {
487                         // Equivalent to *expr or something similar.
488                         self.cat_expr_autoderefd(expr, autoderefs)
489                     }
490
491                     adjustment::Adjust::NeverToAny |
492                     adjustment::Adjust::ReifyFnPointer |
493                     adjustment::Adjust::UnsafeFnPointer |
494                     adjustment::Adjust::ClosureFnPointer |
495                     adjustment::Adjust::MutToConstPointer |
496                     adjustment::Adjust::DerefRef {..} => {
497                         debug!("cat_expr({:?}): {:?}",
498                                adjustment,
499                                expr);
500                         // Result is an rvalue.
501                         let expr_ty = self.expr_ty_adjusted(expr)?;
502                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
503                     }
504                 }
505             }
506         }
507     }
508
509     pub fn cat_expr_autoderefd(&self,
510                                expr: &hir::Expr,
511                                autoderefs: usize)
512                                -> McResult<cmt<'tcx>> {
513         let mut cmt = self.cat_expr_unadjusted(expr)?;
514         debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
515                autoderefs,
516                cmt);
517         for deref in 1..autoderefs + 1 {
518             cmt = self.cat_deref(expr, cmt, deref)?;
519         }
520         return Ok(cmt);
521     }
522
523     pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
524         debug!("cat_expr: id={} expr={:?}", expr.id, expr);
525
526         let expr_ty = self.expr_ty(expr)?;
527         match expr.node {
528           hir::ExprUnary(hir::UnDeref, ref e_base) => {
529             let base_cmt = self.cat_expr(&e_base)?;
530             self.cat_deref(expr, base_cmt, 0)
531           }
532
533           hir::ExprField(ref base, f_name) => {
534             let base_cmt = self.cat_expr(&base)?;
535             debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
536                    expr.id,
537                    expr,
538                    base_cmt);
539             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
540           }
541
542           hir::ExprTupField(ref base, idx) => {
543             let base_cmt = self.cat_expr(&base)?;
544             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
545           }
546
547           hir::ExprIndex(ref base, _) => {
548             let method_call = ty::MethodCall::expr(expr.id());
549             match self.infcx.node_method_ty(method_call) {
550                 Some(method_ty) => {
551                     // If this is an index implemented by a method call, then it
552                     // will include an implicit deref of the result.
553                     let ret_ty = self.overloaded_method_return_ty(method_ty);
554
555                     // The index method always returns an `&T`, so
556                     // dereference it to find the result type.
557                     let elem_ty = match ret_ty.sty {
558                         ty::TyRef(_, mt) => mt.ty,
559                         _ => {
560                             debug!("cat_expr_unadjusted: return type of overloaded index is {:?}?",
561                                    ret_ty);
562                             return Err(());
563                         }
564                     };
565
566                     // The call to index() returns a `&T` value, which
567                     // is an rvalue. That is what we will be
568                     // dereferencing.
569                     let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
570                     Ok(self.cat_deref_common(expr, base_cmt, 1, elem_ty, true))
571                 }
572                 None => {
573                     self.cat_index(expr, self.cat_expr(&base)?, InteriorOffsetKind::Index)
574                 }
575             }
576           }
577
578           hir::ExprPath(ref qpath) => {
579             let def = self.infcx.tables.borrow().qpath_def(qpath, expr.id);
580             self.cat_def(expr.id, expr.span, expr_ty, def)
581           }
582
583           hir::ExprType(ref e, _) => {
584             self.cat_expr(&e)
585           }
586
587           hir::ExprAddrOf(..) | hir::ExprCall(..) |
588           hir::ExprAssign(..) | hir::ExprAssignOp(..) |
589           hir::ExprClosure(..) | hir::ExprRet(..) |
590           hir::ExprUnary(..) |
591           hir::ExprMethodCall(..) | hir::ExprCast(..) |
592           hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
593           hir::ExprBinary(..) | hir::ExprWhile(..) |
594           hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
595           hir::ExprLit(..) | hir::ExprBreak(..) |
596           hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
597           hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
598             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
599           }
600         }
601     }
602
603     pub fn cat_def(&self,
604                    id: ast::NodeId,
605                    span: Span,
606                    expr_ty: Ty<'tcx>,
607                    def: Def)
608                    -> McResult<cmt<'tcx>> {
609         debug!("cat_def: id={} expr={:?} def={:?}",
610                id, expr_ty, def);
611
612         match def {
613           Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
614           Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
615                 Ok(self.cat_rvalue_node(id, span, expr_ty))
616           }
617
618           Def::Static(_, mutbl) => {
619               Ok(Rc::new(cmt_ {
620                   id:id,
621                   span:span,
622                   cat:Categorization::StaticItem,
623                   mutbl: if mutbl { McDeclared } else { McImmutable},
624                   ty:expr_ty,
625                   note: NoteNone
626               }))
627           }
628
629           Def::Upvar(def_id, _, fn_node_id) => {
630               let var_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
631               let ty = self.node_ty(fn_node_id)?;
632               match ty.sty {
633                   ty::TyClosure(closure_id, _) => {
634                       match self.infcx.closure_kind(closure_id) {
635                           Some(kind) => {
636                               self.cat_upvar(id, span, var_id, fn_node_id, kind)
637                           }
638                           None => {
639                               if !self.options.during_closure_kind_inference {
640                                   span_bug!(
641                                       span,
642                                       "No closure kind for {:?}",
643                                       closure_id);
644                               }
645
646                               // during closure kind inference, we
647                               // don't know the closure kind yet, but
648                               // it's ok because we detect that we are
649                               // accessing an upvar and handle that
650                               // case specially anyhow. Use Fn
651                               // arbitrarily.
652                               self.cat_upvar(id, span, var_id, fn_node_id, ty::ClosureKind::Fn)
653                           }
654                       }
655                   }
656                   _ => {
657                       span_bug!(
658                           span,
659                           "Upvar of non-closure {} - {:?}",
660                           fn_node_id,
661                           ty);
662                   }
663               }
664           }
665
666           Def::Local(def_id) => {
667             let vid = self.tcx().hir.as_local_node_id(def_id).unwrap();
668             Ok(Rc::new(cmt_ {
669                 id: id,
670                 span: span,
671                 cat: Categorization::Local(vid),
672                 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
673                 ty: expr_ty,
674                 note: NoteNone
675             }))
676           }
677
678           def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
679         }
680     }
681
682     // Categorize an upvar, complete with invisible derefs of closure
683     // environment and upvar reference as appropriate.
684     fn cat_upvar(&self,
685                  id: ast::NodeId,
686                  span: Span,
687                  var_id: ast::NodeId,
688                  fn_node_id: ast::NodeId,
689                  kind: ty::ClosureKind)
690                  -> McResult<cmt<'tcx>>
691     {
692         // An upvar can have up to 3 components. We translate first to a
693         // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
694         // field from the environment.
695         //
696         // `Categorization::Upvar`.  Next, we add a deref through the implicit
697         // environment pointer with an anonymous free region 'env and
698         // appropriate borrow kind for closure kinds that take self by
699         // reference.  Finally, if the upvar was captured
700         // by-reference, we add a deref through that reference.  The
701         // region of this reference is an inference variable 'up that
702         // was previously generated and recorded in the upvar borrow
703         // map.  The borrow kind bk is inferred by based on how the
704         // upvar is used.
705         //
706         // This results in the following table for concrete closure
707         // types:
708         //
709         //                | move                 | ref
710         // ---------------+----------------------+-------------------------------
711         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
712         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
713         // FnOnce         | copied               | upvar -> &'up bk
714
715         let upvar_id = ty::UpvarId { var_id: var_id,
716                                      closure_expr_id: fn_node_id };
717         let var_ty = self.node_ty(var_id)?;
718
719         // Mutability of original variable itself
720         let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
721
722         // Construct the upvar. This represents access to the field
723         // from the environment (perhaps we should eventually desugar
724         // this field further, but it will do for now).
725         let cmt_result = cmt_ {
726             id: id,
727             span: span,
728             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
729             mutbl: var_mutbl,
730             ty: var_ty,
731             note: NoteNone
732         };
733
734         // If this is a `FnMut` or `Fn` closure, then the above is
735         // conceptually a `&mut` or `&` reference, so we have to add a
736         // deref.
737         let cmt_result = match kind {
738             ty::ClosureKind::FnOnce => {
739                 cmt_result
740             }
741             ty::ClosureKind::FnMut => {
742                 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
743             }
744             ty::ClosureKind::Fn => {
745                 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
746             }
747         };
748
749         // If this is a by-ref capture, then the upvar we loaded is
750         // actually a reference, so we have to add an implicit deref
751         // for that.
752         let upvar_id = ty::UpvarId { var_id: var_id,
753                                      closure_expr_id: fn_node_id };
754         let upvar_capture = self.infcx.upvar_capture(upvar_id).unwrap();
755         let cmt_result = match upvar_capture {
756             ty::UpvarCapture::ByValue => {
757                 cmt_result
758             }
759             ty::UpvarCapture::ByRef(upvar_borrow) => {
760                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
761                 cmt_ {
762                     id: id,
763                     span: span,
764                     cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
765                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
766                     ty: var_ty,
767                     note: NoteUpvarRef(upvar_id)
768                 }
769             }
770         };
771
772         let ret = Rc::new(cmt_result);
773         debug!("cat_upvar ret={:?}", ret);
774         Ok(ret)
775     }
776
777     fn env_deref(&self,
778                  id: ast::NodeId,
779                  span: Span,
780                  upvar_id: ty::UpvarId,
781                  upvar_mutbl: MutabilityCategory,
782                  env_borrow_kind: ty::BorrowKind,
783                  cmt_result: cmt_<'tcx>)
784                  -> cmt_<'tcx>
785     {
786         // Look up the node ID of the closure body so we can construct
787         // a free region within it
788         let fn_body_id = {
789             let fn_expr = match self.tcx().hir.find(upvar_id.closure_expr_id) {
790                 Some(hir_map::NodeExpr(e)) => e,
791                 _ => bug!()
792             };
793
794             match fn_expr.node {
795                 hir::ExprClosure(.., body_id, _) => body_id,
796                 _ => bug!()
797             }
798         };
799
800         // Region of environment pointer
801         let env_region = self.tcx().mk_region(ty::ReFree(ty::FreeRegion {
802             // The environment of a closure is guaranteed to
803             // outlive any bindings introduced in the body of the
804             // closure itself.
805             scope: Some(self.tcx().item_extent(fn_body_id.node_id)),
806             bound_region: ty::BrEnv
807         }));
808
809         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
810
811         let var_ty = cmt_result.ty;
812
813         // We need to add the env deref.  This means
814         // that the above is actually immutable and
815         // has a ref type.  However, nothing should
816         // actually look at the type, so we can get
817         // away with stuffing a `TyError` in there
818         // instead of bothering to construct a proper
819         // one.
820         let cmt_result = cmt_ {
821             mutbl: McImmutable,
822             ty: self.tcx().types.err,
823             ..cmt_result
824         };
825
826         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
827
828         // Issue #18335. If variable is declared as immutable, override the
829         // mutability from the environment and substitute an `&T` anyway.
830         match upvar_mutbl {
831             McImmutable => { deref_mutbl = McImmutable; }
832             McDeclared | McInherited => { }
833         }
834
835         let ret = cmt_ {
836             id: id,
837             span: span,
838             cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
839             mutbl: deref_mutbl,
840             ty: var_ty,
841             note: NoteClosureEnv(upvar_id)
842         };
843
844         debug!("env_deref ret {:?}", ret);
845
846         ret
847     }
848
849     /// Returns the lifetime of a temporary created by expr with id `id`.
850     /// This could be `'static` if `id` is part of a constant expression.
851     pub fn temporary_scope(&self, id: ast::NodeId) -> (ty::Region<'tcx>, ty::Region<'tcx>)
852     {
853         let (scope, old_scope) =
854             self.region_maps.old_and_new_temporary_scope(self.tcx(), id);
855         (self.tcx().mk_region(match scope {
856             Some(scope) => ty::ReScope(scope),
857             None => ty::ReStatic
858         }),
859          self.tcx().mk_region(match old_scope {
860             Some(scope) => ty::ReScope(scope),
861             None => ty::ReStatic
862         }))
863     }
864
865     pub fn cat_rvalue_node(&self,
866                            id: ast::NodeId,
867                            span: Span,
868                            expr_ty: Ty<'tcx>)
869                            -> cmt<'tcx> {
870         let promotable = self.tcx().rvalue_promotable_to_static.borrow().get(&id).cloned()
871                                    .unwrap_or(false);
872
873         // When the corresponding feature isn't toggled, only promote `[T; 0]`.
874         let promotable = match expr_ty.sty {
875             ty::TyArray(_, 0) => true,
876             _ => promotable && self.tcx().sess.features.borrow().rvalue_static_promotion,
877         };
878
879         // Compute maximum lifetime of this rvalue. This is 'static if
880         // we can promote to a constant, otherwise equal to enclosing temp
881         // lifetime.
882         let (re, old_re) = if promotable {
883             (self.tcx().types.re_static,
884              self.tcx().types.re_static)
885         } else {
886             self.temporary_scope(id)
887         };
888         let ret = self.cat_rvalue(id, span, re, old_re, expr_ty);
889         debug!("cat_rvalue_node ret {:?}", ret);
890         ret
891     }
892
893     pub fn cat_rvalue(&self,
894                       cmt_id: ast::NodeId,
895                       span: Span,
896                       temp_scope: ty::Region<'tcx>,
897                       old_temp_scope: ty::Region<'tcx>,
898                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
899         let ret = Rc::new(cmt_ {
900             id:cmt_id,
901             span:span,
902             cat:Categorization::Rvalue(temp_scope, old_temp_scope),
903             mutbl:McDeclared,
904             ty:expr_ty,
905             note: NoteNone
906         });
907         debug!("cat_rvalue ret {:?}", ret);
908         ret
909     }
910
911     pub fn cat_field<N:ast_node>(&self,
912                                  node: &N,
913                                  base_cmt: cmt<'tcx>,
914                                  f_name: ast::Name,
915                                  f_ty: Ty<'tcx>)
916                                  -> cmt<'tcx> {
917         let ret = Rc::new(cmt_ {
918             id: node.id(),
919             span: node.span(),
920             mutbl: base_cmt.mutbl.inherit(),
921             cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
922             ty: f_ty,
923             note: NoteNone
924         });
925         debug!("cat_field ret {:?}", ret);
926         ret
927     }
928
929     pub fn cat_tup_field<N:ast_node>(&self,
930                                      node: &N,
931                                      base_cmt: cmt<'tcx>,
932                                      f_idx: usize,
933                                      f_ty: Ty<'tcx>)
934                                      -> cmt<'tcx> {
935         let ret = Rc::new(cmt_ {
936             id: node.id(),
937             span: node.span(),
938             mutbl: base_cmt.mutbl.inherit(),
939             cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
940             ty: f_ty,
941             note: NoteNone
942         });
943         debug!("cat_tup_field ret {:?}", ret);
944         ret
945     }
946
947     fn cat_deref<N:ast_node>(&self,
948                              node: &N,
949                              base_cmt: cmt<'tcx>,
950                              deref_cnt: usize)
951                              -> McResult<cmt<'tcx>> {
952         let method_call = ty::MethodCall {
953             expr_id: node.id(),
954             autoderef: deref_cnt as u32
955         };
956         let method_ty = self.infcx.node_method_ty(method_call);
957
958         debug!("cat_deref: method_call={:?} method_ty={:?}",
959                method_call, method_ty.map(|ty| ty));
960
961         let base_cmt = match method_ty {
962             Some(method_ty) => {
963                 let ref_ty =
964                     self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap();
965                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
966             }
967             None => base_cmt
968         };
969         let base_cmt_ty = base_cmt.ty;
970         match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
971             Some(mt) => {
972                 let ret = self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, false);
973                 debug!("cat_deref ret {:?}", ret);
974                 Ok(ret)
975             }
976             None => {
977                 debug!("Explicit deref of non-derefable type: {:?}",
978                        base_cmt_ty);
979                 return Err(());
980             }
981         }
982     }
983
984     fn cat_deref_common<N:ast_node>(&self,
985                                     node: &N,
986                                     base_cmt: cmt<'tcx>,
987                                     deref_cnt: usize,
988                                     deref_ty: Ty<'tcx>,
989                                     implicit: bool)
990                                     -> cmt<'tcx>
991     {
992         let ptr = match base_cmt.ty.sty {
993             ty::TyAdt(def, ..) if def.is_box() => Unique,
994             ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
995             ty::TyRef(r, mt) => {
996                 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
997                 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
998             }
999             ref ty => bug!("unexpected type in cat_deref_common: {:?}", ty)
1000         };
1001         let ret = Rc::new(cmt_ {
1002             id: node.id(),
1003             span: node.span(),
1004             // For unique ptrs, we inherit mutability from the owning reference.
1005             mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1006             cat: Categorization::Deref(base_cmt, deref_cnt, ptr),
1007             ty: deref_ty,
1008             note: NoteNone
1009         });
1010         debug!("cat_deref_common ret {:?}", ret);
1011         ret
1012     }
1013
1014     pub fn cat_index<N:ast_node>(&self,
1015                                  elt: &N,
1016                                  mut base_cmt: cmt<'tcx>,
1017                                  context: InteriorOffsetKind)
1018                                  -> McResult<cmt<'tcx>> {
1019         //! Creates a cmt for an indexing operation (`[]`).
1020         //!
1021         //! One subtle aspect of indexing that may not be
1022         //! immediately obvious: for anything other than a fixed-length
1023         //! vector, an operation like `x[y]` actually consists of two
1024         //! disjoint (from the point of view of borrowck) operations.
1025         //! The first is a deref of `x` to create a pointer `p` that points
1026         //! at the first element in the array. The second operation is
1027         //! an index which adds `y*sizeof(T)` to `p` to obtain the
1028         //! pointer to `x[y]`. `cat_index` will produce a resulting
1029         //! cmt containing both this deref and the indexing,
1030         //! presuming that `base_cmt` is not of fixed-length type.
1031         //!
1032         //! # Parameters
1033         //! - `elt`: the AST node being indexed
1034         //! - `base_cmt`: the cmt of `elt`
1035
1036         let method_call = ty::MethodCall::expr(elt.id());
1037         let method_ty = self.infcx.node_method_ty(method_call);
1038
1039         let (element_ty, element_kind) = match method_ty {
1040             Some(method_ty) => {
1041                 let ref_ty = self.overloaded_method_return_ty(method_ty);
1042                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
1043
1044                 (ref_ty.builtin_deref(false, ty::NoPreference).unwrap().ty,
1045                  ElementKind::OtherElement)
1046             }
1047             None => {
1048                 match base_cmt.ty.builtin_index() {
1049                     Some(ty) => (ty, ElementKind::VecElement),
1050                     None => {
1051                         debug!("Explicit index of non-indexable type {:?}", base_cmt);
1052                         return Err(());
1053                     }
1054                 }
1055             }
1056         };
1057
1058         let interior_elem = InteriorElement(context, element_kind);
1059         let ret =
1060             self.cat_imm_interior(elt, base_cmt.clone(), element_ty, interior_elem);
1061         debug!("cat_index ret {:?}", ret);
1062         return Ok(ret);
1063     }
1064
1065     pub fn cat_imm_interior<N:ast_node>(&self,
1066                                         node: &N,
1067                                         base_cmt: cmt<'tcx>,
1068                                         interior_ty: Ty<'tcx>,
1069                                         interior: InteriorKind)
1070                                         -> cmt<'tcx> {
1071         let ret = Rc::new(cmt_ {
1072             id: node.id(),
1073             span: node.span(),
1074             mutbl: base_cmt.mutbl.inherit(),
1075             cat: Categorization::Interior(base_cmt, interior),
1076             ty: interior_ty,
1077             note: NoteNone
1078         });
1079         debug!("cat_imm_interior ret={:?}", ret);
1080         ret
1081     }
1082
1083     pub fn cat_downcast<N:ast_node>(&self,
1084                                     node: &N,
1085                                     base_cmt: cmt<'tcx>,
1086                                     downcast_ty: Ty<'tcx>,
1087                                     variant_did: DefId)
1088                                     -> cmt<'tcx> {
1089         let ret = Rc::new(cmt_ {
1090             id: node.id(),
1091             span: node.span(),
1092             mutbl: base_cmt.mutbl.inherit(),
1093             cat: Categorization::Downcast(base_cmt, variant_did),
1094             ty: downcast_ty,
1095             note: NoteNone
1096         });
1097         debug!("cat_downcast ret={:?}", ret);
1098         ret
1099     }
1100
1101     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1102         where F: FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat),
1103     {
1104         self.cat_pattern_(cmt, pat, &mut op)
1105     }
1106
1107     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1108     fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1109         where F : FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat)
1110     {
1111         // Here, `cmt` is the categorization for the value being
1112         // matched and pat is the pattern it is being matched against.
1113         //
1114         // In general, the way that this works is that we walk down
1115         // the pattern, constructing a cmt that represents the path
1116         // that will be taken to reach the value being matched.
1117         //
1118         // When we encounter named bindings, we take the cmt that has
1119         // been built up and pass it off to guarantee_valid() so that
1120         // we can be sure that the binding will remain valid for the
1121         // duration of the arm.
1122         //
1123         // (*2) There is subtlety concerning the correspondence between
1124         // pattern ids and types as compared to *expression* ids and
1125         // types. This is explained briefly. on the definition of the
1126         // type `cmt`, so go off and read what it says there, then
1127         // come back and I'll dive into a bit more detail here. :) OK,
1128         // back?
1129         //
1130         // In general, the id of the cmt should be the node that
1131         // "produces" the value---patterns aren't executable code
1132         // exactly, but I consider them to "execute" when they match a
1133         // value, and I consider them to produce the value that was
1134         // matched. So if you have something like:
1135         //
1136         //     let x = @@3;
1137         //     match x {
1138         //       @@y { ... }
1139         //     }
1140         //
1141         // In this case, the cmt and the relevant ids would be:
1142         //
1143         //     CMT             Id                  Type of Id Type of cmt
1144         //
1145         //     local(x)->@->@
1146         //     ^~~~~~~^        `x` from discr      @@int      @@int
1147         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1148         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1149         //
1150         // You can see that the types of the id and the cmt are in
1151         // sync in the first line, because that id is actually the id
1152         // of an expression. But once we get to pattern ids, the types
1153         // step out of sync again. So you'll see below that we always
1154         // get the type of the *subpattern* and use that.
1155
1156         debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1157
1158         op(self, cmt.clone(), pat);
1159
1160         // Note: This goes up here (rather than within the PatKind::TupleStruct arm
1161         // alone) because PatKind::Struct can also refer to variants.
1162         let cmt = match pat.node {
1163             PatKind::Path(hir::QPath::Resolved(_, ref path)) |
1164             PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) |
1165             PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => {
1166                 match path.def {
1167                     Def::Err => {
1168                         debug!("access to unresolvable pattern {:?}", pat);
1169                         return Err(())
1170                     }
1171                     Def::Variant(variant_did) |
1172                     Def::VariantCtor(variant_did, ..) => {
1173                         // univariant enums do not need downcasts
1174                         let enum_did = self.tcx().parent_def_id(variant_did).unwrap();
1175                         if !self.tcx().adt_def(enum_did).is_univariant() {
1176                             self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1177                         } else {
1178                             cmt
1179                         }
1180                     }
1181                     _ => cmt
1182                 }
1183             }
1184             _ => cmt
1185         };
1186
1187         match pat.node {
1188           PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1189             let def = self.infcx.tables.borrow().qpath_def(qpath, pat.id);
1190             let expected_len = match def {
1191                 Def::VariantCtor(def_id, CtorKind::Fn) => {
1192                     let enum_def = self.tcx().parent_def_id(def_id).unwrap();
1193                     self.tcx().adt_def(enum_def).variant_with_id(def_id).fields.len()
1194                 }
1195                 Def::StructCtor(_, CtorKind::Fn) => {
1196                     match self.pat_ty(&pat)?.sty {
1197                         ty::TyAdt(adt_def, _) => {
1198                             adt_def.struct_variant().fields.len()
1199                         }
1200                         ref ty => {
1201                             span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1202                         }
1203                     }
1204                 }
1205                 def => {
1206                     span_bug!(pat.span, "tuple struct pattern didn't resolve \
1207                                          to variant or struct {:?}", def);
1208                 }
1209             };
1210
1211             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1212                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1213                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1214                                                    InteriorField(PositionalField(i)));
1215                 self.cat_pattern_(subcmt, &subpat, op)?;
1216             }
1217           }
1218
1219           PatKind::Struct(_, ref field_pats, _) => {
1220             // {f1: p1, ..., fN: pN}
1221             for fp in field_pats {
1222                 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1223                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1224                 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1225             }
1226           }
1227
1228           PatKind::Binding(.., Some(ref subpat)) => {
1229               self.cat_pattern_(cmt, &subpat, op)?;
1230           }
1231
1232           PatKind::Tuple(ref subpats, ddpos) => {
1233             // (p1, ..., pN)
1234             let expected_len = match self.pat_ty(&pat)?.sty {
1235                 ty::TyTuple(ref tys, _) => tys.len(),
1236                 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1237             };
1238             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1239                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1240                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1241                                                    InteriorField(PositionalField(i)));
1242                 self.cat_pattern_(subcmt, &subpat, op)?;
1243             }
1244           }
1245
1246           PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1247             // box p1, &p1, &mut p1.  we can ignore the mutability of
1248             // PatKind::Ref since that information is already contained
1249             // in the type.
1250             let subcmt = self.cat_deref(pat, cmt, 0)?;
1251             self.cat_pattern_(subcmt, &subpat, op)?;
1252           }
1253
1254           PatKind::Slice(ref before, ref slice, ref after) => {
1255             let context = InteriorOffsetKind::Pattern;
1256             let elt_cmt = self.cat_index(pat, cmt, context)?;
1257             for before_pat in before {
1258                 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1259             }
1260             if let Some(ref slice_pat) = *slice {
1261                 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1262             }
1263             for after_pat in after {
1264                 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1265             }
1266           }
1267
1268           PatKind::Path(_) | PatKind::Binding(.., None) |
1269           PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1270             // always ok
1271           }
1272         }
1273
1274         Ok(())
1275     }
1276
1277     fn overloaded_method_return_ty(&self,
1278                                    method_ty: Ty<'tcx>)
1279                                    -> Ty<'tcx>
1280     {
1281         // When we process an overloaded `*` or `[]` etc, we often
1282         // need to extract the return type of the method. These method
1283         // types are generated by method resolution and always have
1284         // all late-bound regions fully instantiated, so we just want
1285         // to skip past the binder.
1286         self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1287            .unwrap()
1288     }
1289 }
1290
1291 #[derive(Clone, Debug)]
1292 pub enum Aliasability {
1293     FreelyAliasable(AliasableReason),
1294     NonAliasable,
1295     ImmutableUnique(Box<Aliasability>),
1296 }
1297
1298 #[derive(Copy, Clone, Debug)]
1299 pub enum AliasableReason {
1300     AliasableBorrowed,
1301     AliasableStatic,
1302     AliasableStaticMut,
1303 }
1304
1305 impl<'tcx> cmt_<'tcx> {
1306     pub fn guarantor(&self) -> cmt<'tcx> {
1307         //! Returns `self` after stripping away any derefs or
1308         //! interior content. The return value is basically the `cmt` which
1309         //! determines how long the value in `self` remains live.
1310
1311         match self.cat {
1312             Categorization::Rvalue(..) |
1313             Categorization::StaticItem |
1314             Categorization::Local(..) |
1315             Categorization::Deref(.., UnsafePtr(..)) |
1316             Categorization::Deref(.., BorrowedPtr(..)) |
1317             Categorization::Deref(.., Implicit(..)) |
1318             Categorization::Upvar(..) => {
1319                 Rc::new((*self).clone())
1320             }
1321             Categorization::Downcast(ref b, _) |
1322             Categorization::Interior(ref b, _) |
1323             Categorization::Deref(ref b, _, Unique) => {
1324                 b.guarantor()
1325             }
1326         }
1327     }
1328
1329     /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1330     pub fn freely_aliasable(&self) -> Aliasability {
1331         // Maybe non-obvious: copied upvars can only be considered
1332         // non-aliasable in once closures, since any other kind can be
1333         // aliased and eventually recused.
1334
1335         match self.cat {
1336             Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1337             Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1338             Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1339             Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1340             Categorization::Deref(ref b, _, Unique) |
1341             Categorization::Downcast(ref b, _) |
1342             Categorization::Interior(ref b, _) => {
1343                 // Aliasability depends on base cmt
1344                 b.freely_aliasable()
1345             }
1346
1347             Categorization::Rvalue(..) |
1348             Categorization::Local(..) |
1349             Categorization::Upvar(..) |
1350             Categorization::Deref(.., UnsafePtr(..)) => { // yes, it's aliasable, but...
1351                 NonAliasable
1352             }
1353
1354             Categorization::StaticItem => {
1355                 if self.mutbl.is_mutable() {
1356                     FreelyAliasable(AliasableStaticMut)
1357                 } else {
1358                     FreelyAliasable(AliasableStatic)
1359                 }
1360             }
1361
1362             Categorization::Deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) |
1363             Categorization::Deref(_, _, Implicit(ty::ImmBorrow, _)) => {
1364                 FreelyAliasable(AliasableBorrowed)
1365             }
1366         }
1367     }
1368
1369     // Digs down through one or two layers of deref and grabs the cmt
1370     // for the upvar if a note indicates there is one.
1371     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1372         match self.note {
1373             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1374                 Some(match self.cat {
1375                     Categorization::Deref(ref inner, ..) => {
1376                         match inner.cat {
1377                             Categorization::Deref(ref inner, ..) => inner.clone(),
1378                             Categorization::Upvar(..) => inner.clone(),
1379                             _ => bug!()
1380                         }
1381                     }
1382                     _ => bug!()
1383                 })
1384             }
1385             NoteNone => None
1386         }
1387     }
1388
1389
1390     pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1391         match self.cat {
1392             Categorization::StaticItem => {
1393                 "static item".to_string()
1394             }
1395             Categorization::Rvalue(..) => {
1396                 "non-lvalue".to_string()
1397             }
1398             Categorization::Local(vid) => {
1399                 if tcx.hir.is_argument(vid) {
1400                     "argument".to_string()
1401                 } else {
1402                     "local variable".to_string()
1403                 }
1404             }
1405             Categorization::Deref(.., pk) => {
1406                 let upvar = self.upvar();
1407                 match upvar.as_ref().map(|i| &i.cat) {
1408                     Some(&Categorization::Upvar(ref var)) => {
1409                         var.to_string()
1410                     }
1411                     Some(_) => bug!(),
1412                     None => {
1413                         match pk {
1414                             Implicit(..) => {
1415                                 format!("indexed content")
1416                             }
1417                             Unique => {
1418                                 format!("`Box` content")
1419                             }
1420                             UnsafePtr(..) => {
1421                                 format!("dereference of raw pointer")
1422                             }
1423                             BorrowedPtr(..) => {
1424                                 format!("borrowed content")
1425                             }
1426                         }
1427                     }
1428                 }
1429             }
1430             Categorization::Interior(_, InteriorField(NamedField(_))) => {
1431                 "field".to_string()
1432             }
1433             Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1434                 "anonymous field".to_string()
1435             }
1436             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1437                                                         VecElement)) |
1438             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1439                                                         OtherElement)) => {
1440                 "indexed content".to_string()
1441             }
1442             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1443                                                         VecElement)) |
1444             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1445                                                         OtherElement)) => {
1446                 "pattern-bound indexed content".to_string()
1447             }
1448             Categorization::Upvar(ref var) => {
1449                 var.to_string()
1450             }
1451             Categorization::Downcast(ref cmt, _) => {
1452                 cmt.descriptive_string(tcx)
1453             }
1454         }
1455     }
1456 }
1457
1458 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1459     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1460         write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1461                self.cat,
1462                self.id,
1463                self.mutbl,
1464                self.ty)
1465     }
1466 }
1467
1468 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1469     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1470         match *self {
1471             Categorization::StaticItem => write!(f, "static"),
1472             Categorization::Rvalue(r, or) => {
1473                 write!(f, "rvalue({:?}, {:?})", r, or)
1474             }
1475             Categorization::Local(id) => {
1476                let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1477                write!(f, "local({})", name)
1478             }
1479             Categorization::Upvar(upvar) => {
1480                 write!(f, "upvar({:?})", upvar)
1481             }
1482             Categorization::Deref(ref cmt, derefs, ptr) => {
1483                 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1484             }
1485             Categorization::Interior(ref cmt, interior) => {
1486                 write!(f, "{:?}.{:?}", cmt.cat, interior)
1487             }
1488             Categorization::Downcast(ref cmt, _) => {
1489                 write!(f, "{:?}->(enum)", cmt.cat)
1490             }
1491         }
1492     }
1493 }
1494
1495 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1496     match ptr {
1497         Unique => "Box",
1498         BorrowedPtr(ty::ImmBorrow, _) |
1499         Implicit(ty::ImmBorrow, _) => "&",
1500         BorrowedPtr(ty::MutBorrow, _) |
1501         Implicit(ty::MutBorrow, _) => "&mut",
1502         BorrowedPtr(ty::UniqueImmBorrow, _) |
1503         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1504         UnsafePtr(_) => "*",
1505     }
1506 }
1507
1508 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1509     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510         match *self {
1511             Unique => write!(f, "Box"),
1512             BorrowedPtr(ty::ImmBorrow, ref r) |
1513             Implicit(ty::ImmBorrow, ref r) => {
1514                 write!(f, "&{:?}", r)
1515             }
1516             BorrowedPtr(ty::MutBorrow, ref r) |
1517             Implicit(ty::MutBorrow, ref r) => {
1518                 write!(f, "&{:?} mut", r)
1519             }
1520             BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1521             Implicit(ty::UniqueImmBorrow, ref r) => {
1522                 write!(f, "&{:?} uniq", r)
1523             }
1524             UnsafePtr(_) => write!(f, "*")
1525         }
1526     }
1527 }
1528
1529 impl fmt::Debug for InteriorKind {
1530     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1531         match *self {
1532             InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1533             InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1534             InteriorElement(..) => write!(f, "[]"),
1535         }
1536     }
1537 }
1538
1539 impl fmt::Debug for Upvar {
1540     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1541         write!(f, "{:?}/{:?}", self.id, self.kind)
1542     }
1543 }
1544
1545 impl fmt::Display for Upvar {
1546     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1547         let kind = match self.kind {
1548             ty::ClosureKind::Fn => "Fn",
1549             ty::ClosureKind::FnMut => "FnMut",
1550             ty::ClosureKind::FnOnce => "FnOnce",
1551         };
1552         write!(f, "captured outer variable in an `{}` closure", kind)
1553     }
1554 }