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