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