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