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