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