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