]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
6bf0c5d1ba3e39478389c9fa1d60b95fec599f37
[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     fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
507         let base_ty = self.node_ty(pat.hir_id)?;
508         // This code detects whether we are looking at a `ref x`,
509         // and if so, figures out what the type *being borrowed* is.
510         let ret_ty = match pat.node {
511             PatKind::Binding(..) => {
512                 let bm = *self.tables
513                               .pat_binding_modes()
514                               .get(pat.hir_id)
515                               .expect("missing binding mode");
516
517                 if let ty::BindByReference(_) = bm {
518                     // a bind-by-ref means that the base_ty will be the type of the ident itself,
519                     // but what we want here is the type of the underlying value being borrowed.
520                     // So peel off one-level, turning the &T into T.
521                     match base_ty.builtin_deref(false) {
522                         Some(t) => t.ty,
523                         None => {
524                             debug!("By-ref binding of non-derefable type {:?}", base_ty);
525                             return Err(());
526                         }
527                     }
528                 } else {
529                     base_ty
530                 }
531             }
532             _ => base_ty,
533         };
534         debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
535                pat, base_ty, ret_ty);
536         Ok(ret_ty)
537     }
538
539     pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
540         // This recursion helper avoids going through *too many*
541         // adjustments, since *only* non-overloaded deref recurses.
542         fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
543                                   expr: &hir::Expr,
544                                   adjustments: &[adjustment::Adjustment<'tcx>])
545                                    -> McResult<cmt<'tcx>> {
546             match adjustments.split_last() {
547                 None => mc.cat_expr_unadjusted(expr),
548                 Some((adjustment, previous)) => {
549                     mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
550                 }
551             }
552         }
553
554         helper(self, expr, self.tables.expr_adjustments(expr))
555     }
556
557     pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
558                              previous: cmt<'tcx>,
559                              adjustment: &adjustment::Adjustment<'tcx>)
560                              -> McResult<cmt<'tcx>> {
561         self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
562     }
563
564     fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
565                                  previous: F,
566                                  adjustment: &adjustment::Adjustment<'tcx>)
567                                  -> McResult<cmt<'tcx>>
568         where F: FnOnce() -> McResult<cmt<'tcx>>
569     {
570         debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
571         let target = self.resolve_type_vars_if_possible(&adjustment.target);
572         match adjustment.kind {
573             adjustment::Adjust::Deref(overloaded) => {
574                 // Equivalent to *expr or something similar.
575                 let base = if let Some(deref) = overloaded {
576                     let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
577                         ty: target,
578                         mutbl: deref.mutbl,
579                     });
580                     self.cat_rvalue_node(expr.id, expr.span, ref_ty)
581                 } else {
582                     previous()?
583                 };
584                 self.cat_deref(expr, base, false)
585             }
586
587             adjustment::Adjust::NeverToAny |
588             adjustment::Adjust::ReifyFnPointer |
589             adjustment::Adjust::UnsafeFnPointer |
590             adjustment::Adjust::ClosureFnPointer |
591             adjustment::Adjust::MutToConstPointer |
592             adjustment::Adjust::Borrow(_) |
593             adjustment::Adjust::Unsize => {
594                 // Result is an rvalue.
595                 Ok(self.cat_rvalue_node(expr.id, expr.span, target))
596             }
597         }
598     }
599
600     pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
601         debug!("cat_expr: id={} expr={:?}", expr.id, expr);
602
603         let expr_ty = self.expr_ty(expr)?;
604         match expr.node {
605           hir::ExprUnary(hir::UnDeref, ref e_base) => {
606             if self.tables.is_method_call(expr) {
607                 self.cat_overloaded_place(expr, e_base, false)
608             } else {
609                 let base_cmt = self.cat_expr(&e_base)?;
610                 self.cat_deref(expr, base_cmt, false)
611             }
612           }
613
614           hir::ExprField(ref base, f_name) => {
615             let base_cmt = self.cat_expr(&base)?;
616             debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
617                    expr.id,
618                    expr,
619                    base_cmt);
620             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
621           }
622
623           hir::ExprTupField(ref base, idx) => {
624             let base_cmt = self.cat_expr(&base)?;
625             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
626           }
627
628           hir::ExprIndex(ref base, _) => {
629             if self.tables.is_method_call(expr) {
630                 // If this is an index implemented by a method call, then it
631                 // will include an implicit deref of the result.
632                 // The call to index() returns a `&T` value, which
633                 // is an rvalue. That is what we will be
634                 // dereferencing.
635                 self.cat_overloaded_place(expr, base, true)
636             } else {
637                 let base_cmt = self.cat_expr(&base)?;
638                 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
639             }
640           }
641
642           hir::ExprPath(ref qpath) => {
643             let def = self.tables.qpath_def(qpath, expr.hir_id);
644             self.cat_def(expr.id, expr.span, expr_ty, def)
645           }
646
647           hir::ExprType(ref e, _) => {
648             self.cat_expr(&e)
649           }
650
651           hir::ExprAddrOf(..) | hir::ExprCall(..) |
652           hir::ExprAssign(..) | hir::ExprAssignOp(..) |
653           hir::ExprClosure(..) | hir::ExprRet(..) |
654           hir::ExprUnary(..) | hir::ExprYield(..) |
655           hir::ExprMethodCall(..) | hir::ExprCast(..) |
656           hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
657           hir::ExprBinary(..) | hir::ExprWhile(..) |
658           hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
659           hir::ExprLit(..) | hir::ExprBreak(..) |
660           hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
661           hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
662             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
663           }
664         }
665     }
666
667     pub fn cat_def(&self,
668                    id: ast::NodeId,
669                    span: Span,
670                    expr_ty: Ty<'tcx>,
671                    def: Def)
672                    -> McResult<cmt<'tcx>> {
673         debug!("cat_def: id={} expr={:?} def={:?}",
674                id, expr_ty, def);
675
676         match def {
677           Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
678           Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
679                 Ok(self.cat_rvalue_node(id, span, expr_ty))
680           }
681
682           Def::Static(def_id, mutbl) => {
683             // `#[thread_local]` statics may not outlive the current function.
684             for attr in &self.tcx.get_attrs(def_id)[..] {
685                 if attr.check_name("thread_local") {
686                     return Ok(self.cat_rvalue_node(id, span, expr_ty));
687                 }
688             }
689               Ok(Rc::new(cmt_ {
690                   id:id,
691                   span:span,
692                   cat:Categorization::StaticItem,
693                   mutbl: if mutbl { McDeclared } else { McImmutable},
694                   ty:expr_ty,
695                   note: NoteNone
696               }))
697           }
698
699           Def::Upvar(var_id, _, fn_node_id) => {
700               self.cat_upvar(id, span, var_id, fn_node_id)
701           }
702
703           Def::Local(vid) => {
704             Ok(Rc::new(cmt_ {
705                 id,
706                 span,
707                 cat: Categorization::Local(vid),
708                 mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
709                 ty: expr_ty,
710                 note: NoteNone
711             }))
712           }
713
714           def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
715         }
716     }
717
718     // Categorize an upvar, complete with invisible derefs of closure
719     // environment and upvar reference as appropriate.
720     fn cat_upvar(&self,
721                  id: ast::NodeId,
722                  span: Span,
723                  var_id: ast::NodeId,
724                  fn_node_id: ast::NodeId)
725                  -> McResult<cmt<'tcx>>
726     {
727         let fn_hir_id = self.tcx.hir.node_to_hir_id(fn_node_id);
728
729         // An upvar can have up to 3 components. We translate first to a
730         // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
731         // field from the environment.
732         //
733         // `Categorization::Upvar`.  Next, we add a deref through the implicit
734         // environment pointer with an anonymous free region 'env and
735         // appropriate borrow kind for closure kinds that take self by
736         // reference.  Finally, if the upvar was captured
737         // by-reference, we add a deref through that reference.  The
738         // region of this reference is an inference variable 'up that
739         // was previously generated and recorded in the upvar borrow
740         // map.  The borrow kind bk is inferred by based on how the
741         // upvar is used.
742         //
743         // This results in the following table for concrete closure
744         // types:
745         //
746         //                | move                 | ref
747         // ---------------+----------------------+-------------------------------
748         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
749         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
750         // FnOnce         | copied               | upvar -> &'up bk
751
752         let kind = match self.node_ty(fn_hir_id)?.sty {
753             ty::TyGenerator(..) => ty::ClosureKind::FnOnce,
754             ty::TyClosure(closure_def_id, closure_substs) => {
755                 match self.infcx {
756                     // During upvar inference we may not know the
757                     // closure kind, just use the LATTICE_BOTTOM value.
758                     Some(infcx) =>
759                         infcx.closure_kind(closure_def_id, closure_substs)
760                              .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
761
762                     None =>
763                         self.tcx.global_tcx()
764                                 .lift(&closure_substs)
765                                 .expect("no inference cx, but inference variables in closure ty")
766                                 .closure_kind(closure_def_id, self.tcx.global_tcx()),
767                 }
768             }
769             ref t => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", t),
770         };
771
772         let closure_expr_def_id = self.tcx.hir.local_def_id(fn_node_id);
773         let var_hir_id = self.tcx.hir.node_to_hir_id(var_id);
774         let upvar_id = ty::UpvarId {
775             var_id: var_hir_id,
776             closure_expr_id: closure_expr_def_id.to_local(),
777         };
778
779         let var_ty = self.node_ty(var_hir_id)?;
780
781         // Mutability of original variable itself
782         let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
783
784         // Construct the upvar. This represents access to the field
785         // from the environment (perhaps we should eventually desugar
786         // this field further, but it will do for now).
787         let cmt_result = cmt_ {
788             id,
789             span,
790             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
791             mutbl: var_mutbl,
792             ty: var_ty,
793             note: NoteNone
794         };
795
796         // If this is a `FnMut` or `Fn` closure, then the above is
797         // conceptually a `&mut` or `&` reference, so we have to add a
798         // deref.
799         let cmt_result = match kind {
800             ty::ClosureKind::FnOnce => {
801                 cmt_result
802             }
803             ty::ClosureKind::FnMut => {
804                 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
805             }
806             ty::ClosureKind::Fn => {
807                 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
808             }
809         };
810
811         // If this is a by-ref capture, then the upvar we loaded is
812         // actually a reference, so we have to add an implicit deref
813         // for that.
814         let upvar_capture = self.tables.upvar_capture(upvar_id);
815         let cmt_result = match upvar_capture {
816             ty::UpvarCapture::ByValue => {
817                 cmt_result
818             }
819             ty::UpvarCapture::ByRef(upvar_borrow) => {
820                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
821                 cmt_ {
822                     id,
823                     span,
824                     cat: Categorization::Deref(Rc::new(cmt_result), ptr),
825                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
826                     ty: var_ty,
827                     note: NoteUpvarRef(upvar_id)
828                 }
829             }
830         };
831
832         let ret = Rc::new(cmt_result);
833         debug!("cat_upvar ret={:?}", ret);
834         Ok(ret)
835     }
836
837     fn env_deref(&self,
838                  id: ast::NodeId,
839                  span: Span,
840                  upvar_id: ty::UpvarId,
841                  upvar_mutbl: MutabilityCategory,
842                  env_borrow_kind: ty::BorrowKind,
843                  cmt_result: cmt_<'tcx>)
844                  -> cmt_<'tcx>
845     {
846         // Region of environment pointer
847         let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
848             // The environment of a closure is guaranteed to
849             // outlive any bindings introduced in the body of the
850             // closure itself.
851             scope: upvar_id.closure_expr_id.to_def_id(),
852             bound_region: ty::BrEnv
853         }));
854
855         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
856
857         let var_ty = cmt_result.ty;
858
859         // We need to add the env deref.  This means
860         // that the above is actually immutable and
861         // has a ref type.  However, nothing should
862         // actually look at the type, so we can get
863         // away with stuffing a `TyError` in there
864         // instead of bothering to construct a proper
865         // one.
866         let cmt_result = cmt_ {
867             mutbl: McImmutable,
868             ty: self.tcx.types.err,
869             ..cmt_result
870         };
871
872         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
873
874         // Issue #18335. If variable is declared as immutable, override the
875         // mutability from the environment and substitute an `&T` anyway.
876         match upvar_mutbl {
877             McImmutable => { deref_mutbl = McImmutable; }
878             McDeclared | McInherited => { }
879         }
880
881         let ret = cmt_ {
882             id,
883             span,
884             cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
885             mutbl: deref_mutbl,
886             ty: var_ty,
887             note: NoteClosureEnv(upvar_id)
888         };
889
890         debug!("env_deref ret {:?}", ret);
891
892         ret
893     }
894
895     /// Returns the lifetime of a temporary created by expr with id `id`.
896     /// This could be `'static` if `id` is part of a constant expression.
897     pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
898         let scope = self.region_scope_tree.temporary_scope(id);
899         self.tcx.mk_region(match scope {
900             Some(scope) => ty::ReScope(scope),
901             None => ty::ReStatic
902         })
903     }
904
905     pub fn cat_rvalue_node(&self,
906                            id: ast::NodeId,
907                            span: Span,
908                            expr_ty: Ty<'tcx>)
909                            -> cmt<'tcx> {
910         let hir_id = self.tcx.hir.node_to_hir_id(id);
911         let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
912                                                             .unwrap_or(false);
913
914         // Always promote `[T; 0]` (even when e.g. borrowed mutably).
915         let promotable = match expr_ty.sty {
916             ty::TyArray(_, len) if len.val.to_raw_bits() == Some(0) => true,
917             _ => promotable,
918         };
919
920         // Compute maximum lifetime of this rvalue. This is 'static if
921         // we can promote to a constant, otherwise equal to enclosing temp
922         // lifetime.
923         let re = if promotable {
924             self.tcx.types.re_static
925         } else {
926             self.temporary_scope(hir_id.local_id)
927         };
928         let ret = self.cat_rvalue(id, span, re, expr_ty);
929         debug!("cat_rvalue_node ret {:?}", ret);
930         ret
931     }
932
933     pub fn cat_rvalue(&self,
934                       cmt_id: ast::NodeId,
935                       span: Span,
936                       temp_scope: ty::Region<'tcx>,
937                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
938         let ret = Rc::new(cmt_ {
939             id:cmt_id,
940             span:span,
941             cat:Categorization::Rvalue(temp_scope),
942             mutbl:McDeclared,
943             ty:expr_ty,
944             note: NoteNone
945         });
946         debug!("cat_rvalue ret {:?}", ret);
947         ret
948     }
949
950     pub fn cat_field<N:ast_node>(&self,
951                                  node: &N,
952                                  base_cmt: cmt<'tcx>,
953                                  f_name: ast::Name,
954                                  f_ty: Ty<'tcx>)
955                                  -> cmt<'tcx> {
956         let ret = Rc::new(cmt_ {
957             id: node.id(),
958             span: node.span(),
959             mutbl: base_cmt.mutbl.inherit(),
960             cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
961             ty: f_ty,
962             note: NoteNone
963         });
964         debug!("cat_field ret {:?}", ret);
965         ret
966     }
967
968     pub fn cat_tup_field<N:ast_node>(&self,
969                                      node: &N,
970                                      base_cmt: cmt<'tcx>,
971                                      f_idx: usize,
972                                      f_ty: Ty<'tcx>)
973                                      -> cmt<'tcx> {
974         let ret = Rc::new(cmt_ {
975             id: node.id(),
976             span: node.span(),
977             mutbl: base_cmt.mutbl.inherit(),
978             cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
979             ty: f_ty,
980             note: NoteNone
981         });
982         debug!("cat_tup_field ret {:?}", ret);
983         ret
984     }
985
986     fn cat_overloaded_place(&self,
987                              expr: &hir::Expr,
988                              base: &hir::Expr,
989                              implicit: bool)
990                              -> McResult<cmt<'tcx>> {
991         debug!("cat_overloaded_place: implicit={}", implicit);
992
993         // Reconstruct the output assuming it's a reference with the
994         // same region and mutability as the receiver. This holds for
995         // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
996         let place_ty = self.expr_ty(expr)?;
997         let base_ty = self.expr_ty_adjusted(base)?;
998
999         let (region, mutbl) = match base_ty.sty {
1000             ty::TyRef(region, mt) => (region, mt.mutbl),
1001             _ => {
1002                 span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
1003             }
1004         };
1005         let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
1006             ty: place_ty,
1007             mutbl,
1008         });
1009
1010         let base_cmt = self.cat_rvalue_node(expr.id, expr.span, ref_ty);
1011         self.cat_deref(expr, base_cmt, implicit)
1012     }
1013
1014     pub fn cat_deref<N:ast_node>(&self,
1015                                  node: &N,
1016                                  base_cmt: cmt<'tcx>,
1017                                  implicit: bool)
1018                                  -> McResult<cmt<'tcx>> {
1019         debug!("cat_deref: base_cmt={:?}", base_cmt);
1020
1021         let base_cmt_ty = base_cmt.ty;
1022         let deref_ty = match base_cmt_ty.builtin_deref(true) {
1023             Some(mt) => mt.ty,
1024             None => {
1025                 debug!("Explicit deref of non-derefable type: {:?}",
1026                        base_cmt_ty);
1027                 return Err(());
1028             }
1029         };
1030
1031         let ptr = match base_cmt.ty.sty {
1032             ty::TyAdt(def, ..) if def.is_box() => Unique,
1033             ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
1034             ty::TyRef(r, mt) => {
1035                 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
1036                 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
1037             }
1038             ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
1039         };
1040         let ret = Rc::new(cmt_ {
1041             id: node.id(),
1042             span: node.span(),
1043             // For unique ptrs, we inherit mutability from the owning reference.
1044             mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1045             cat: Categorization::Deref(base_cmt, ptr),
1046             ty: deref_ty,
1047             note: NoteNone
1048         });
1049         debug!("cat_deref ret {:?}", ret);
1050         Ok(ret)
1051     }
1052
1053     fn cat_index<N:ast_node>(&self,
1054                              elt: &N,
1055                              base_cmt: cmt<'tcx>,
1056                              element_ty: Ty<'tcx>,
1057                              context: InteriorOffsetKind)
1058                              -> McResult<cmt<'tcx>> {
1059         //! Creates a cmt for an indexing operation (`[]`).
1060         //!
1061         //! One subtle aspect of indexing that may not be
1062         //! immediately obvious: for anything other than a fixed-length
1063         //! vector, an operation like `x[y]` actually consists of two
1064         //! disjoint (from the point of view of borrowck) operations.
1065         //! The first is a deref of `x` to create a pointer `p` that points
1066         //! at the first element in the array. The second operation is
1067         //! an index which adds `y*sizeof(T)` to `p` to obtain the
1068         //! pointer to `x[y]`. `cat_index` will produce a resulting
1069         //! cmt containing both this deref and the indexing,
1070         //! presuming that `base_cmt` is not of fixed-length type.
1071         //!
1072         //! # Parameters
1073         //! - `elt`: the AST node being indexed
1074         //! - `base_cmt`: the cmt of `elt`
1075
1076         let interior_elem = InteriorElement(context);
1077         let ret =
1078             self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1079         debug!("cat_index ret {:?}", ret);
1080         return Ok(ret);
1081     }
1082
1083     pub fn cat_imm_interior<N:ast_node>(&self,
1084                                         node: &N,
1085                                         base_cmt: cmt<'tcx>,
1086                                         interior_ty: Ty<'tcx>,
1087                                         interior: InteriorKind)
1088                                         -> cmt<'tcx> {
1089         let ret = Rc::new(cmt_ {
1090             id: node.id(),
1091             span: node.span(),
1092             mutbl: base_cmt.mutbl.inherit(),
1093             cat: Categorization::Interior(base_cmt, interior),
1094             ty: interior_ty,
1095             note: NoteNone
1096         });
1097         debug!("cat_imm_interior ret={:?}", ret);
1098         ret
1099     }
1100
1101     pub fn cat_downcast_if_needed<N:ast_node>(&self,
1102                                               node: &N,
1103                                               base_cmt: cmt<'tcx>,
1104                                               variant_did: DefId)
1105                                               -> cmt<'tcx> {
1106         // univariant enums do not need downcasts
1107         let base_did = self.tcx.parent_def_id(variant_did).unwrap();
1108         if self.tcx.adt_def(base_did).variants.len() != 1 {
1109             let base_ty = base_cmt.ty;
1110             let ret = Rc::new(cmt_ {
1111                 id: node.id(),
1112                 span: node.span(),
1113                 mutbl: base_cmt.mutbl.inherit(),
1114                 cat: Categorization::Downcast(base_cmt, variant_did),
1115                 ty: base_ty,
1116                 note: NoteNone
1117             });
1118             debug!("cat_downcast ret={:?}", ret);
1119             ret
1120         } else {
1121             debug!("cat_downcast univariant={:?}", base_cmt);
1122             base_cmt
1123         }
1124     }
1125
1126     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1127         where F: FnMut(cmt<'tcx>, &hir::Pat),
1128     {
1129         self.cat_pattern_(cmt, pat, &mut op)
1130     }
1131
1132     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1133     fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1134         where F : FnMut(cmt<'tcx>, &hir::Pat)
1135     {
1136         // Here, `cmt` is the categorization for the value being
1137         // matched and pat is the pattern it is being matched against.
1138         //
1139         // In general, the way that this works is that we walk down
1140         // the pattern, constructing a cmt that represents the path
1141         // that will be taken to reach the value being matched.
1142         //
1143         // When we encounter named bindings, we take the cmt that has
1144         // been built up and pass it off to guarantee_valid() so that
1145         // we can be sure that the binding will remain valid for the
1146         // duration of the arm.
1147         //
1148         // (*2) There is subtlety concerning the correspondence between
1149         // pattern ids and types as compared to *expression* ids and
1150         // types. This is explained briefly. on the definition of the
1151         // type `cmt`, so go off and read what it says there, then
1152         // come back and I'll dive into a bit more detail here. :) OK,
1153         // back?
1154         //
1155         // In general, the id of the cmt should be the node that
1156         // "produces" the value---patterns aren't executable code
1157         // exactly, but I consider them to "execute" when they match a
1158         // value, and I consider them to produce the value that was
1159         // matched. So if you have something like:
1160         //
1161         //     let x = @@3;
1162         //     match x {
1163         //       @@y { ... }
1164         //     }
1165         //
1166         // In this case, the cmt and the relevant ids would be:
1167         //
1168         //     CMT             Id                  Type of Id Type of cmt
1169         //
1170         //     local(x)->@->@
1171         //     ^~~~~~~^        `x` from discr      @@int      @@int
1172         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1173         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1174         //
1175         // You can see that the types of the id and the cmt are in
1176         // sync in the first line, because that id is actually the id
1177         // of an expression. But once we get to pattern ids, the types
1178         // step out of sync again. So you'll see below that we always
1179         // get the type of the *subpattern* and use that.
1180
1181         debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1182
1183         // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1184         // `cmt`s are constructed differently from patterns. For example, in
1185         //
1186         // ```
1187         // match foo {
1188         //     &&Some(x, ) => { ... },
1189         //     _ => { ... },
1190         // }
1191         // ```
1192         //
1193         // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1194         // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1195         // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1196         //
1197         // `&&Some(x,)` `cmt_foo`
1198         //  `&Some(x,)` `deref { cmt_foo}`
1199         //   `Some(x,)` `deref { deref { cmt_foo }}`
1200         //        (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1201         //
1202         // The above example has no adjustments. If the code were instead the (after adjustments,
1203         // equivalent) version
1204         //
1205         // ```
1206         // match foo {
1207         //     Some(x, ) => { ... },
1208         //     _ => { ... },
1209         // }
1210         // ```
1211         //
1212         // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1213         // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1214         // though its assigned type is that of `&&Some(x,)`.
1215         for _ in 0..self.tables
1216                         .pat_adjustments()
1217                         .get(pat.hir_id)
1218                         .map(|v| v.len())
1219                         .unwrap_or(0) {
1220             cmt = self.cat_deref(pat, cmt, true /* implicit */)?;
1221         }
1222         let cmt = cmt; // lose mutability
1223
1224         // Invoke the callback, but only now, after the `cmt` has adjusted.
1225         //
1226         // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1227         // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1228         // don't want to call `op` with these incompatible values. As written, what happens instead
1229         // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1230         // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1231         // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1232         // that (where the `ref` on `x` is implied).
1233         op(cmt.clone(), pat);
1234
1235         match pat.node {
1236           PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1237             let def = self.tables.qpath_def(qpath, pat.hir_id);
1238             let (cmt, expected_len) = match def {
1239                 Def::Err => {
1240                     debug!("access to unresolvable pattern {:?}", pat);
1241                     return Err(())
1242                 }
1243                 Def::VariantCtor(def_id, CtorKind::Fn) => {
1244                     let enum_def = self.tcx.parent_def_id(def_id).unwrap();
1245                     (self.cat_downcast_if_needed(pat, cmt, def_id),
1246                      self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1247                 }
1248                 Def::StructCtor(_, CtorKind::Fn) => {
1249                     match self.pat_ty(&pat)?.sty {
1250                         ty::TyAdt(adt_def, _) => {
1251                             (cmt, adt_def.non_enum_variant().fields.len())
1252                         }
1253                         ref ty => {
1254                             span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1255                         }
1256                     }
1257                 }
1258                 def => {
1259                     span_bug!(pat.span, "tuple struct pattern didn't resolve \
1260                                          to variant or struct {:?}", def);
1261                 }
1262             };
1263
1264             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1265                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1266                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1267                                                    InteriorField(PositionalField(i)));
1268                 self.cat_pattern_(subcmt, &subpat, op)?;
1269             }
1270           }
1271
1272           PatKind::Struct(ref qpath, ref field_pats, _) => {
1273             // {f1: p1, ..., fN: pN}
1274             let def = self.tables.qpath_def(qpath, pat.hir_id);
1275             let cmt = match def {
1276                 Def::Err => {
1277                     debug!("access to unresolvable pattern {:?}", pat);
1278                     return Err(())
1279                 },
1280                 Def::Variant(variant_did) |
1281                 Def::VariantCtor(variant_did, ..) => {
1282                     self.cat_downcast_if_needed(pat, cmt, variant_did)
1283                 },
1284                 _ => cmt
1285             };
1286
1287             for fp in field_pats {
1288                 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1289                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1290                 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1291             }
1292           }
1293
1294           PatKind::Binding(.., Some(ref subpat)) => {
1295               self.cat_pattern_(cmt, &subpat, op)?;
1296           }
1297
1298           PatKind::Tuple(ref subpats, ddpos) => {
1299             // (p1, ..., pN)
1300             let expected_len = match self.pat_ty(&pat)?.sty {
1301                 ty::TyTuple(ref tys) => tys.len(),
1302                 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1303             };
1304             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1305                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1306                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1307                                                    InteriorField(PositionalField(i)));
1308                 self.cat_pattern_(subcmt, &subpat, op)?;
1309             }
1310           }
1311
1312           PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1313             // box p1, &p1, &mut p1.  we can ignore the mutability of
1314             // PatKind::Ref since that information is already contained
1315             // in the type.
1316             let subcmt = self.cat_deref(pat, cmt, false)?;
1317             self.cat_pattern_(subcmt, &subpat, op)?;
1318           }
1319
1320           PatKind::Slice(ref before, ref slice, ref after) => {
1321             let element_ty = match cmt.ty.builtin_index() {
1322                 Some(ty) => ty,
1323                 None => {
1324                     debug!("Explicit index of non-indexable type {:?}", cmt);
1325                     return Err(());
1326                 }
1327             };
1328             let context = InteriorOffsetKind::Pattern;
1329             let elt_cmt = self.cat_index(pat, cmt, element_ty, context)?;
1330             for before_pat in before {
1331                 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1332             }
1333             if let Some(ref slice_pat) = *slice {
1334                 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1335             }
1336             for after_pat in after {
1337                 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1338             }
1339           }
1340
1341           PatKind::Path(_) | PatKind::Binding(.., None) |
1342           PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1343             // always ok
1344           }
1345         }
1346
1347         Ok(())
1348     }
1349 }
1350
1351 #[derive(Clone, Debug)]
1352 pub enum Aliasability {
1353     FreelyAliasable(AliasableReason),
1354     NonAliasable,
1355     ImmutableUnique(Box<Aliasability>),
1356 }
1357
1358 #[derive(Copy, Clone, Debug)]
1359 pub enum AliasableReason {
1360     AliasableBorrowed,
1361     AliasableStatic,
1362     AliasableStaticMut,
1363 }
1364
1365 impl<'tcx> cmt_<'tcx> {
1366     pub fn guarantor(&self) -> cmt<'tcx> {
1367         //! Returns `self` after stripping away any derefs or
1368         //! interior content. The return value is basically the `cmt` which
1369         //! determines how long the value in `self` remains live.
1370
1371         match self.cat {
1372             Categorization::Rvalue(..) |
1373             Categorization::StaticItem |
1374             Categorization::Local(..) |
1375             Categorization::Deref(_, UnsafePtr(..)) |
1376             Categorization::Deref(_, BorrowedPtr(..)) |
1377             Categorization::Deref(_, Implicit(..)) |
1378             Categorization::Upvar(..) => {
1379                 Rc::new((*self).clone())
1380             }
1381             Categorization::Downcast(ref b, _) |
1382             Categorization::Interior(ref b, _) |
1383             Categorization::Deref(ref b, Unique) => {
1384                 b.guarantor()
1385             }
1386         }
1387     }
1388
1389     /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1390     pub fn freely_aliasable(&self) -> Aliasability {
1391         // Maybe non-obvious: copied upvars can only be considered
1392         // non-aliasable in once closures, since any other kind can be
1393         // aliased and eventually recused.
1394
1395         match self.cat {
1396             Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1397             Categorization::Deref(ref b, Implicit(ty::MutBorrow, _)) |
1398             Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1399             Categorization::Deref(ref b, Implicit(ty::UniqueImmBorrow, _)) |
1400             Categorization::Deref(ref b, Unique) |
1401             Categorization::Downcast(ref b, _) |
1402             Categorization::Interior(ref b, _) => {
1403                 // Aliasability depends on base cmt
1404                 b.freely_aliasable()
1405             }
1406
1407             Categorization::Rvalue(..) |
1408             Categorization::Local(..) |
1409             Categorization::Upvar(..) |
1410             Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1411                 NonAliasable
1412             }
1413
1414             Categorization::StaticItem => {
1415                 if self.mutbl.is_mutable() {
1416                     FreelyAliasable(AliasableStaticMut)
1417                 } else {
1418                     FreelyAliasable(AliasableStatic)
1419                 }
1420             }
1421
1422             Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) |
1423             Categorization::Deref(_, Implicit(ty::ImmBorrow, _)) => {
1424                 FreelyAliasable(AliasableBorrowed)
1425             }
1426         }
1427     }
1428
1429     // Digs down through one or two layers of deref and grabs the cmt
1430     // for the upvar if a note indicates there is one.
1431     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1432         match self.note {
1433             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1434                 Some(match self.cat {
1435                     Categorization::Deref(ref inner, _) => {
1436                         match inner.cat {
1437                             Categorization::Deref(ref inner, _) => inner.clone(),
1438                             Categorization::Upvar(..) => inner.clone(),
1439                             _ => bug!()
1440                         }
1441                     }
1442                     _ => bug!()
1443                 })
1444             }
1445             NoteNone => None
1446         }
1447     }
1448
1449
1450     pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1451         match self.cat {
1452             Categorization::StaticItem => {
1453                 "static item".to_string()
1454             }
1455             Categorization::Rvalue(..) => {
1456                 "non-place".to_string()
1457             }
1458             Categorization::Local(vid) => {
1459                 if tcx.hir.is_argument(vid) {
1460                     "argument".to_string()
1461                 } else {
1462                     "local variable".to_string()
1463                 }
1464             }
1465             Categorization::Deref(_, pk) => {
1466                 let upvar = self.upvar();
1467                 match upvar.as_ref().map(|i| &i.cat) {
1468                     Some(&Categorization::Upvar(ref var)) => {
1469                         var.to_string()
1470                     }
1471                     Some(_) => bug!(),
1472                     None => {
1473                         match pk {
1474                             Implicit(..) => {
1475                                 format!("indexed content")
1476                             }
1477                             Unique => {
1478                                 format!("`Box` content")
1479                             }
1480                             UnsafePtr(..) => {
1481                                 format!("dereference of raw pointer")
1482                             }
1483                             BorrowedPtr(..) => {
1484                                 format!("borrowed content")
1485                             }
1486                         }
1487                     }
1488                 }
1489             }
1490             Categorization::Interior(_, InteriorField(NamedField(_))) => {
1491                 "field".to_string()
1492             }
1493             Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1494                 "anonymous field".to_string()
1495             }
1496             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1497                 "indexed content".to_string()
1498             }
1499             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1500                 "pattern-bound indexed content".to_string()
1501             }
1502             Categorization::Upvar(ref var) => {
1503                 var.to_string()
1504             }
1505             Categorization::Downcast(ref cmt, _) => {
1506                 cmt.descriptive_string(tcx)
1507             }
1508         }
1509     }
1510 }
1511
1512 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1513     match ptr {
1514         Unique => "Box",
1515         BorrowedPtr(ty::ImmBorrow, _) |
1516         Implicit(ty::ImmBorrow, _) => "&",
1517         BorrowedPtr(ty::MutBorrow, _) |
1518         Implicit(ty::MutBorrow, _) => "&mut",
1519         BorrowedPtr(ty::UniqueImmBorrow, _) |
1520         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1521         UnsafePtr(_) => "*",
1522     }
1523 }
1524
1525 impl fmt::Debug for InteriorKind {
1526     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1527         match *self {
1528             InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1529             InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1530             InteriorElement(..) => write!(f, "[]"),
1531         }
1532     }
1533 }
1534
1535 impl fmt::Debug for Upvar {
1536     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1537         write!(f, "{:?}/{:?}", self.id, self.kind)
1538     }
1539 }
1540
1541 impl fmt::Display for Upvar {
1542     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543         let kind = match self.kind {
1544             ty::ClosureKind::Fn => "Fn",
1545             ty::ClosureKind::FnMut => "FnMut",
1546             ty::ClosureKind::FnOnce => "FnOnce",
1547         };
1548         write!(f, "captured outer variable in an `{}` closure", kind)
1549     }
1550 }