]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
Improve some compiletest documentation
[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, 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::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(hir::HirId),                   // local variable
92     Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
93     Interior(cmt<'tcx>, InteriorKind),   // something interior: field, tuple, etc
94     Downcast(cmt<'tcx>, DefId),          // selects a particular enum variant (*1)
95
96     // (*1) downcast is only required if the enum has more than one variant
97 }
98
99 // Represents any kind of upvar
100 #[derive(Clone, Copy, PartialEq)]
101 pub struct Upvar {
102     pub id: ty::UpvarId,
103     pub kind: ty::ClosureKind
104 }
105
106 // different kinds of pointers:
107 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108 pub enum PointerKind<'tcx> {
109     /// `Box<T>`
110     Unique,
111
112     /// `&T`
113     BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
114
115     /// `*T`
116     UnsafePtr(hir::Mutability),
117 }
118
119 // We use the term "interior" to mean "something reachable from the
120 // base without a pointer dereference", e.g., a field
121 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
122 pub enum InteriorKind {
123     InteriorField(FieldIndex),
124     InteriorElement(InteriorOffsetKind),
125 }
126
127 // Contains index of a field that is actually used for loan path comparisons and
128 // string representation of the field that should be used only for diagnostics.
129 #[derive(Clone, Copy, Eq)]
130 pub struct FieldIndex(pub usize, pub Name);
131
132 impl PartialEq for FieldIndex {
133     fn eq(&self, rhs: &Self) -> bool {
134         self.0 == rhs.0
135     }
136 }
137
138 impl Hash for FieldIndex {
139     fn hash<H: Hasher>(&self, h: &mut H) {
140         self.0.hash(h)
141     }
142 }
143
144 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
145 pub enum InteriorOffsetKind {
146     Index,   // e.g., `array_expr[index_expr]`
147     Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }`
148 }
149
150 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
151 pub enum MutabilityCategory {
152     McImmutable, // Immutable.
153     McDeclared,  // Directly declared as mutable.
154     McInherited, // Inherited from the fact that owner is mutable.
155 }
156
157 // A note about the provenance of a `cmt`.  This is used for
158 // special-case handling of upvars such as mutability inference.
159 // Upvar categorization can generate a variable number of nested
160 // derefs.  The note allows detecting them without deep pattern
161 // matching on the categorization.
162 #[derive(Clone, Copy, PartialEq, Debug)]
163 pub enum Note {
164     NoteClosureEnv(ty::UpvarId), // Deref through closure env
165     NoteUpvarRef(ty::UpvarId),   // Deref through by-ref upvar
166     NoteIndex,                   // Deref as part of desugaring `x[]` into its two components
167     NoteNone                     // Nothing special
168 }
169
170 // `cmt`: "Category, Mutability, and Type".
171 //
172 // a complete categorization of a value indicating where it originated
173 // and how it is located, as well as the mutability of the memory in
174 // which the value is stored.
175 //
176 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
177 // result of `node_type(cmt.id)`.
178 //
179 // (FIXME: rewrite the following comment given that `@x` managed
180 // pointers have been obsolete for quite some time.)
181 //
182 // This is because the `id` is always the `id` of the node producing the
183 // type; in an expression like `*x`, the type of this deref node is the
184 // deref'd type (`T`), but in a pattern like `@x`, the `@x` pattern is
185 // again a dereference, but its type is the type *before* the
186 // dereference (`@T`). So use `cmt.ty` to find the type of the value in
187 // a consistent fashion. For more details, see the method `cat_pattern`
188 #[derive(Clone, Debug, PartialEq)]
189 pub struct cmt_<'tcx> {
190     pub hir_id: hir::HirId,        // HIR id of expr/pat producing this value
191     pub span: Span,                // span of same expr/pat
192     pub cat: Categorization<'tcx>, // categorization of expr
193     pub mutbl: MutabilityCategory, // mutability of expr as place
194     pub ty: Ty<'tcx>,              // type of the expr (*see WARNING above*)
195     pub note: Note,                // Note about the provenance of this cmt
196 }
197
198 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
199
200 pub enum ImmutabilityBlame<'tcx> {
201     ImmLocal(hir::HirId),
202     ClosureEnv(LocalDefId),
203     LocalDeref(hir::HirId),
204     AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
205 }
206
207 impl<'tcx> cmt_<'tcx> {
208     fn resolve_field(&self, field_index: usize) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
209     {
210         let adt_def = match self.ty.sty {
211             ty::Adt(def, _) => def,
212             ty::Tuple(..) => return None,
213             // closures get `Categorization::Upvar` rather than `Categorization::Interior`
214             _ =>  bug!("interior cmt {:?} is not an ADT", self)
215         };
216         let variant_def = match self.cat {
217             Categorization::Downcast(_, variant_did) => {
218                 adt_def.variant_with_id(variant_did)
219             }
220             _ => {
221                 assert_eq!(adt_def.variants.len(), 1);
222                 &adt_def.variants[VariantIdx::new(0)]
223             }
224         };
225         Some((adt_def, &variant_def.fields[field_index]))
226     }
227
228     pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
229         match self.cat {
230             Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) => {
231                 // try to figure out where the immutable reference came from
232                 match base_cmt.cat {
233                     Categorization::Local(hir_id) =>
234                         Some(ImmutabilityBlame::LocalDeref(hir_id)),
235                     Categorization::Interior(ref base_cmt, InteriorField(field_index)) => {
236                         base_cmt.resolve_field(field_index.0).map(|(adt_def, field_def)| {
237                             ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
238                         })
239                     }
240                     Categorization::Upvar(Upvar { id, .. }) => {
241                         if let NoteClosureEnv(..) = self.note {
242                             Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
243                         } else {
244                             None
245                         }
246                     }
247                     _ => None
248                 }
249             }
250             Categorization::Local(hir_id) => {
251                 Some(ImmutabilityBlame::ImmLocal(hir_id))
252             }
253             Categorization::Rvalue(..) |
254             Categorization::Upvar(..) |
255             Categorization::Deref(_, UnsafePtr(..)) => {
256                 // This should not be reachable up to inference limitations.
257                 None
258             }
259             Categorization::Interior(ref base_cmt, _) |
260             Categorization::Downcast(ref base_cmt, _) |
261             Categorization::Deref(ref base_cmt, _) => {
262                 base_cmt.immutability_blame()
263             }
264             Categorization::ThreadLocal(..) |
265             Categorization::StaticItem => {
266                 // Do we want to do something here?
267                 None
268             }
269         }
270     }
271 }
272
273 pub trait HirNode {
274     fn hir_id(&self) -> hir::HirId;
275     fn span(&self) -> Span;
276 }
277
278 impl HirNode for hir::Expr {
279     fn hir_id(&self) -> hir::HirId { self.hir_id }
280     fn span(&self) -> Span { self.span }
281 }
282
283 impl HirNode for hir::Pat {
284     fn hir_id(&self) -> hir::HirId { self.hir_id }
285     fn span(&self) -> Span { self.span }
286 }
287
288 #[derive(Clone)]
289 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
290     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
291     pub region_scope_tree: &'a region::ScopeTree,
292     pub tables: &'a ty::TypeckTables<'tcx>,
293     rvalue_promotable_map: Option<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.hir_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.hir_id,
652                        expr,
653                        base_cmt);
654                 let f_index = self.tcx.field_index(expr.hir_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(..) | Def::ConstParam(..) |
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(self.tcx.hir().node_to_hir_id(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 ty = self.node_ty(fn_hir_id)?;
790         let kind = match ty.sty {
791             ty::Generator(..) => ty::ClosureKind::FnOnce,
792             ty::Closure(closure_def_id, closure_substs) => {
793                 match self.infcx {
794                     // During upvar inference we may not know the
795                     // closure kind, just use the LATTICE_BOTTOM value.
796                     Some(infcx) =>
797                         infcx.closure_kind(closure_def_id, closure_substs)
798                              .unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
799
800                     None =>
801                         self.tcx.global_tcx()
802                                 .lift(&closure_substs)
803                                 .expect("no inference cx, but inference variables in closure ty")
804                                 .closure_kind(closure_def_id, self.tcx.global_tcx()),
805                 }
806             }
807             _ => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", ty),
808         };
809
810         let closure_expr_def_id = self.tcx.hir().local_def_id(fn_node_id);
811         let var_hir_id = self.tcx.hir().node_to_hir_id(var_id);
812         let upvar_id = ty::UpvarId {
813             var_path: ty::UpvarPath { hir_id: var_hir_id },
814             closure_expr_id: closure_expr_def_id.to_local(),
815         };
816
817         let var_ty = self.node_ty(var_hir_id)?;
818
819         // Mutability of original variable itself
820         let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
821
822         // Construct the upvar. This represents access to the field
823         // from the environment (perhaps we should eventually desugar
824         // this field further, but it will do for now).
825         let cmt_result = cmt_ {
826             hir_id,
827             span,
828             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
829             mutbl: var_mutbl,
830             ty: var_ty,
831             note: NoteNone
832         };
833
834         // If this is a `FnMut` or `Fn` closure, then the above is
835         // conceptually a `&mut` or `&` reference, so we have to add a
836         // deref.
837         let cmt_result = match kind {
838             ty::ClosureKind::FnOnce => {
839                 cmt_result
840             }
841             ty::ClosureKind::FnMut => {
842                 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
843             }
844             ty::ClosureKind::Fn => {
845                 self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
846             }
847         };
848
849         // If this is a by-ref capture, then the upvar we loaded is
850         // actually a reference, so we have to add an implicit deref
851         // for that.
852         let upvar_capture = self.tables.upvar_capture(upvar_id);
853         let cmt_result = match upvar_capture {
854             ty::UpvarCapture::ByValue => {
855                 cmt_result
856             }
857             ty::UpvarCapture::ByRef(upvar_borrow) => {
858                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
859                 cmt_ {
860                     hir_id,
861                     span,
862                     cat: Categorization::Deref(Rc::new(cmt_result), ptr),
863                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
864                     ty: var_ty,
865                     note: NoteUpvarRef(upvar_id)
866                 }
867             }
868         };
869
870         let ret = cmt_result;
871         debug!("cat_upvar ret={:?}", ret);
872         Ok(ret)
873     }
874
875     fn env_deref(&self,
876                  hir_id: hir::HirId,
877                  span: Span,
878                  upvar_id: ty::UpvarId,
879                  upvar_mutbl: MutabilityCategory,
880                  env_borrow_kind: ty::BorrowKind,
881                  cmt_result: cmt_<'tcx>)
882                  -> cmt_<'tcx>
883     {
884         // Region of environment pointer
885         let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
886             // The environment of a closure is guaranteed to
887             // outlive any bindings introduced in the body of the
888             // closure itself.
889             scope: upvar_id.closure_expr_id.to_def_id(),
890             bound_region: ty::BrEnv
891         }));
892
893         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
894
895         let var_ty = cmt_result.ty;
896
897         // We need to add the env deref.  This means
898         // that the above is actually immutable and
899         // has a ref type.  However, nothing should
900         // actually look at the type, so we can get
901         // away with stuffing a `Error` in there
902         // instead of bothering to construct a proper
903         // one.
904         let cmt_result = cmt_ {
905             mutbl: McImmutable,
906             ty: self.tcx.types.err,
907             ..cmt_result
908         };
909
910         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
911
912         // Issue #18335. If variable is declared as immutable, override the
913         // mutability from the environment and substitute an `&T` anyway.
914         match upvar_mutbl {
915             McImmutable => { deref_mutbl = McImmutable; }
916             McDeclared | McInherited => { }
917         }
918
919         let ret = cmt_ {
920             hir_id,
921             span,
922             cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
923             mutbl: deref_mutbl,
924             ty: var_ty,
925             note: NoteClosureEnv(upvar_id)
926         };
927
928         debug!("env_deref ret {:?}", ret);
929
930         ret
931     }
932
933     /// Returns the lifetime of a temporary created by expr with id `id`.
934     /// This could be `'static` if `id` is part of a constant expression.
935     pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
936         let scope = self.region_scope_tree.temporary_scope(id);
937         self.tcx.mk_region(match scope {
938             Some(scope) => ty::ReScope(scope),
939             None => ty::ReStatic
940         })
941     }
942
943     pub fn cat_rvalue_node(&self,
944                            hir_id: hir::HirId,
945                            span: Span,
946                            expr_ty: Ty<'tcx>)
947                            -> cmt_<'tcx> {
948         debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
949                hir_id, span, expr_ty);
950
951         let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
952                                                             .unwrap_or(false);
953
954         debug!("cat_rvalue_node: promotable = {:?}", promotable);
955
956         // Always promote `[T; 0]` (even when e.g., borrowed mutably).
957         let promotable = match expr_ty.sty {
958             ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true,
959             _ => promotable,
960         };
961
962         debug!("cat_rvalue_node: promotable = {:?} (2)", promotable);
963
964         // Compute maximum lifetime of this rvalue. This is 'static if
965         // we can promote to a constant, otherwise equal to enclosing temp
966         // lifetime.
967         let re = if promotable {
968             self.tcx.types.re_static
969         } else {
970             self.temporary_scope(hir_id.local_id)
971         };
972         let ret = self.cat_rvalue(hir_id, span, re, expr_ty);
973         debug!("cat_rvalue_node ret {:?}", ret);
974         ret
975     }
976
977     pub fn cat_rvalue(&self,
978                       cmt_hir_id: hir::HirId,
979                       span: Span,
980                       temp_scope: ty::Region<'tcx>,
981                       expr_ty: Ty<'tcx>) -> cmt_<'tcx> {
982         let ret = cmt_ {
983             hir_id: cmt_hir_id,
984             span:span,
985             cat:Categorization::Rvalue(temp_scope),
986             mutbl:McDeclared,
987             ty:expr_ty,
988             note: NoteNone
989         };
990         debug!("cat_rvalue ret {:?}", ret);
991         ret
992     }
993
994     pub fn cat_field<N: HirNode>(&self,
995                                  node: &N,
996                                  base_cmt: cmt<'tcx>,
997                                  f_index: usize,
998                                  f_ident: ast::Ident,
999                                  f_ty: Ty<'tcx>)
1000                                  -> cmt_<'tcx> {
1001         let ret = cmt_ {
1002             hir_id: node.hir_id(),
1003             span: node.span(),
1004             mutbl: base_cmt.mutbl.inherit(),
1005             cat: Categorization::Interior(base_cmt,
1006                                           InteriorField(FieldIndex(f_index, f_ident.name))),
1007             ty: f_ty,
1008             note: NoteNone
1009         };
1010         debug!("cat_field ret {:?}", ret);
1011         ret
1012     }
1013
1014     fn cat_overloaded_place(
1015         &self,
1016         expr: &hir::Expr,
1017         base: &hir::Expr,
1018         note: Note,
1019     ) -> McResult<cmt_<'tcx>> {
1020         debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
1021                expr,
1022                base,
1023                note);
1024
1025         // Reconstruct the output assuming it's a reference with the
1026         // same region and mutability as the receiver. This holds for
1027         // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1028         let place_ty = self.expr_ty(expr)?;
1029         let base_ty = self.expr_ty_adjusted(base)?;
1030
1031         let (region, mutbl) = match base_ty.sty {
1032             ty::Ref(region, _, mutbl) => (region, mutbl),
1033             _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
1034         };
1035         let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
1036             ty: place_ty,
1037             mutbl,
1038         });
1039
1040         let base_cmt = Rc::new(self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty));
1041         self.cat_deref(expr, base_cmt, note)
1042     }
1043
1044     pub fn cat_deref(
1045         &self,
1046         node: &impl HirNode,
1047         base_cmt: cmt<'tcx>,
1048         note: Note,
1049     ) -> McResult<cmt_<'tcx>> {
1050         debug!("cat_deref: base_cmt={:?}", base_cmt);
1051
1052         let base_cmt_ty = base_cmt.ty;
1053         let deref_ty = match base_cmt_ty.builtin_deref(true) {
1054             Some(mt) => mt.ty,
1055             None => {
1056                 debug!("Explicit deref of non-derefable type: {:?}", base_cmt_ty);
1057                 return Err(());
1058             }
1059         };
1060
1061         let ptr = match base_cmt.ty.sty {
1062             ty::Adt(def, ..) if def.is_box() => Unique,
1063             ty::RawPtr(ref mt) => UnsafePtr(mt.mutbl),
1064             ty::Ref(r, _, mutbl) => {
1065                 let bk = ty::BorrowKind::from_mutbl(mutbl);
1066                 BorrowedPtr(bk, r)
1067             }
1068             _ => bug!("unexpected type in cat_deref: {:?}", base_cmt.ty)
1069         };
1070         let ret = cmt_ {
1071             hir_id: node.hir_id(),
1072             span: node.span(),
1073             // For unique ptrs, we inherit mutability from the owning reference.
1074             mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
1075             cat: Categorization::Deref(base_cmt, ptr),
1076             ty: deref_ty,
1077             note: note,
1078         };
1079         debug!("cat_deref ret {:?}", ret);
1080         Ok(ret)
1081     }
1082
1083     fn cat_index<N: HirNode>(&self,
1084                              elt: &N,
1085                              base_cmt: cmt<'tcx>,
1086                              element_ty: Ty<'tcx>,
1087                              context: InteriorOffsetKind)
1088                              -> McResult<cmt_<'tcx>> {
1089         //! Creates a cmt for an indexing operation (`[]`).
1090         //!
1091         //! One subtle aspect of indexing that may not be
1092         //! immediately obvious: for anything other than a fixed-length
1093         //! vector, an operation like `x[y]` actually consists of two
1094         //! disjoint (from the point of view of borrowck) operations.
1095         //! The first is a deref of `x` to create a pointer `p` that points
1096         //! at the first element in the array. The second operation is
1097         //! an index which adds `y*sizeof(T)` to `p` to obtain the
1098         //! pointer to `x[y]`. `cat_index` will produce a resulting
1099         //! cmt containing both this deref and the indexing,
1100         //! presuming that `base_cmt` is not of fixed-length type.
1101         //!
1102         //! # Parameters
1103         //! - `elt`: the HIR node being indexed
1104         //! - `base_cmt`: the cmt of `elt`
1105
1106         let interior_elem = InteriorElement(context);
1107         let ret = self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
1108         debug!("cat_index ret {:?}", ret);
1109         return Ok(ret);
1110     }
1111
1112     pub fn cat_imm_interior<N:HirNode>(&self,
1113                                        node: &N,
1114                                        base_cmt: cmt<'tcx>,
1115                                        interior_ty: Ty<'tcx>,
1116                                        interior: InteriorKind)
1117                                        -> cmt_<'tcx> {
1118         let ret = cmt_ {
1119             hir_id: node.hir_id(),
1120             span: node.span(),
1121             mutbl: base_cmt.mutbl.inherit(),
1122             cat: Categorization::Interior(base_cmt, interior),
1123             ty: interior_ty,
1124             note: NoteNone
1125         };
1126         debug!("cat_imm_interior ret={:?}", ret);
1127         ret
1128     }
1129
1130     pub fn cat_downcast_if_needed<N:HirNode>(&self,
1131                                              node: &N,
1132                                              base_cmt: cmt<'tcx>,
1133                                              variant_did: DefId)
1134                                              -> cmt<'tcx> {
1135         // univariant enums do not need downcasts
1136         let base_did = self.tcx.parent(variant_did).unwrap();
1137         if self.tcx.adt_def(base_did).variants.len() != 1 {
1138             let base_ty = base_cmt.ty;
1139             let ret = Rc::new(cmt_ {
1140                 hir_id: node.hir_id(),
1141                 span: node.span(),
1142                 mutbl: base_cmt.mutbl.inherit(),
1143                 cat: Categorization::Downcast(base_cmt, variant_did),
1144                 ty: base_ty,
1145                 note: NoteNone
1146             });
1147             debug!("cat_downcast ret={:?}", ret);
1148             ret
1149         } else {
1150             debug!("cat_downcast univariant={:?}", base_cmt);
1151             base_cmt
1152         }
1153     }
1154
1155     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1156         where F: FnMut(cmt<'tcx>, &hir::Pat),
1157     {
1158         self.cat_pattern_(cmt, pat, &mut op)
1159     }
1160
1161     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1162     fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1163         where F : FnMut(cmt<'tcx>, &hir::Pat)
1164     {
1165         // Here, `cmt` is the categorization for the value being
1166         // matched and pat is the pattern it is being matched against.
1167         //
1168         // In general, the way that this works is that we walk down
1169         // the pattern, constructing a cmt that represents the path
1170         // that will be taken to reach the value being matched.
1171         //
1172         // When we encounter named bindings, we take the cmt that has
1173         // been built up and pass it off to guarantee_valid() so that
1174         // we can be sure that the binding will remain valid for the
1175         // duration of the arm.
1176         //
1177         // (*2) There is subtlety concerning the correspondence between
1178         // pattern ids and types as compared to *expression* ids and
1179         // types. This is explained briefly. on the definition of the
1180         // type `cmt`, so go off and read what it says there, then
1181         // come back and I'll dive into a bit more detail here. :) OK,
1182         // back?
1183         //
1184         // In general, the id of the cmt should be the node that
1185         // "produces" the value---patterns aren't executable code
1186         // exactly, but I consider them to "execute" when they match a
1187         // value, and I consider them to produce the value that was
1188         // matched. So if you have something like:
1189         //
1190         // (FIXME: `@@3` is not legal code anymore!)
1191         //
1192         //     let x = @@3;
1193         //     match x {
1194         //       @@y { ... }
1195         //     }
1196         //
1197         // In this case, the cmt and the relevant ids would be:
1198         //
1199         //     CMT             Id                  Type of Id Type of cmt
1200         //
1201         //     local(x)->@->@
1202         //     ^~~~~~~^        `x` from discr      @@int      @@int
1203         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1204         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1205         //
1206         // You can see that the types of the id and the cmt are in
1207         // sync in the first line, because that id is actually the id
1208         // of an expression. But once we get to pattern ids, the types
1209         // step out of sync again. So you'll see below that we always
1210         // get the type of the *subpattern* and use that.
1211
1212         debug!("cat_pattern(pat={:?}, cmt={:?})", pat, cmt);
1213
1214         // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
1215         // `cmt`s are constructed differently from patterns. For example, in
1216         //
1217         // ```
1218         // match foo {
1219         //     &&Some(x, ) => { ... },
1220         //     _ => { ... },
1221         // }
1222         // ```
1223         //
1224         // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
1225         // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
1226         // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
1227         //
1228         // `&&Some(x,)` `cmt_foo`
1229         //  `&Some(x,)` `deref { cmt_foo}`
1230         //   `Some(x,)` `deref { deref { cmt_foo }}`
1231         //        (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
1232         //
1233         // The above example has no adjustments. If the code were instead the (after adjustments,
1234         // equivalent) version
1235         //
1236         // ```
1237         // match foo {
1238         //     Some(x, ) => { ... },
1239         //     _ => { ... },
1240         // }
1241         // ```
1242         //
1243         // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
1244         // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
1245         // though its assigned type is that of `&&Some(x,)`.
1246         for _ in 0..self.tables
1247                         .pat_adjustments()
1248                         .get(pat.hir_id)
1249                         .map(|v| v.len())
1250                         .unwrap_or(0)
1251         {
1252             debug!("cat_pattern: applying adjustment to cmt={:?}", cmt);
1253             cmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1254         }
1255         let cmt = cmt; // lose mutability
1256         debug!("cat_pattern: applied adjustment derefs to get cmt={:?}", cmt);
1257
1258         // Invoke the callback, but only now, after the `cmt` has adjusted.
1259         //
1260         // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
1261         // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
1262         // don't want to call `op` with these incompatible values. As written, what happens instead
1263         // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
1264         // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
1265         // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
1266         // that (where the `ref` on `x` is implied).
1267         op(cmt.clone(), pat);
1268
1269         match pat.node {
1270             PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1271                 let def = self.tables.qpath_def(qpath, pat.hir_id);
1272                 let (cmt, expected_len) = match def {
1273                     Def::Err => {
1274                         debug!("access to unresolvable pattern {:?}", pat);
1275                         return Err(())
1276                     }
1277                     Def::VariantCtor(def_id, CtorKind::Fn) => {
1278                         let enum_def = self.tcx.parent(def_id).unwrap();
1279                         (self.cat_downcast_if_needed(pat, cmt, def_id),
1280                         self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
1281                     }
1282                     Def::StructCtor(_, CtorKind::Fn) | Def::SelfCtor(..) => {
1283                         let ty = self.pat_ty_unadjusted(&pat)?;
1284                         match ty.sty {
1285                             ty::Adt(adt_def, _) => {
1286                                 (cmt, adt_def.non_enum_variant().fields.len())
1287                             }
1288                             _ => {
1289                                 span_bug!(pat.span,
1290                                           "tuple struct pattern unexpected type {:?}", ty);
1291                             }
1292                         }
1293                     }
1294                     def => {
1295                         span_bug!(pat.span, "tuple struct pattern didn't resolve \
1296                                              to variant or struct {:?}", def);
1297                     }
1298                 };
1299
1300                 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1301                     let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1302                     let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1303                     let subcmt = Rc::new(
1304                         self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1305                     self.cat_pattern_(subcmt, &subpat, op)?;
1306                 }
1307             }
1308
1309             PatKind::Struct(ref qpath, ref field_pats, _) => {
1310                 // {f1: p1, ..., fN: pN}
1311                 let def = self.tables.qpath_def(qpath, pat.hir_id);
1312                 let cmt = match def {
1313                     Def::Err => {
1314                         debug!("access to unresolvable pattern {:?}", pat);
1315                         return Err(())
1316                     }
1317                     Def::Variant(variant_did) |
1318                     Def::VariantCtor(variant_did, ..) => {
1319                         self.cat_downcast_if_needed(pat, cmt, variant_did)
1320                     }
1321                     _ => cmt,
1322                 };
1323
1324                 for fp in field_pats {
1325                     let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
1326                     let f_index = self.tcx.field_index(fp.node.hir_id, self.tables);
1327                     let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
1328                                                            fp.node.ident, field_ty));
1329                     self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1330                 }
1331             }
1332
1333             PatKind::Binding(.., Some(ref subpat)) => {
1334                 self.cat_pattern_(cmt, &subpat, op)?;
1335             }
1336
1337             PatKind::Tuple(ref subpats, ddpos) => {
1338                 // (p1, ..., pN)
1339                 let ty = self.pat_ty_unadjusted(&pat)?;
1340                 let expected_len = match ty.sty {
1341                     ty::Tuple(ref tys) => tys.len(),
1342                     _ => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1343                 };
1344                 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1345                     let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
1346                     let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
1347                     let subcmt = Rc::new(
1348                         self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
1349                     self.cat_pattern_(subcmt, &subpat, op)?;
1350                 }
1351             }
1352
1353             PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1354                 // box p1, &p1, &mut p1.  we can ignore the mutability of
1355                 // PatKind::Ref since that information is already contained
1356                 // in the type.
1357                 let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
1358                 self.cat_pattern_(subcmt, &subpat, op)?;
1359             }
1360
1361             PatKind::Slice(ref before, ref slice, ref after) => {
1362                 let element_ty = match cmt.ty.builtin_index() {
1363                     Some(ty) => ty,
1364                     None => {
1365                         debug!("Explicit index of non-indexable type {:?}", cmt);
1366                         return Err(());
1367                     }
1368                 };
1369                 let context = InteriorOffsetKind::Pattern;
1370                 let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
1371                 for before_pat in before {
1372                     self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1373                 }
1374                 if let Some(ref slice_pat) = *slice {
1375                     self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1376                 }
1377                 for after_pat in after {
1378                     self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1379                 }
1380             }
1381
1382             PatKind::Path(_) | PatKind::Binding(.., None) |
1383             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1384                 // always ok
1385             }
1386         }
1387
1388         Ok(())
1389     }
1390 }
1391
1392 #[derive(Clone, Debug)]
1393 pub enum Aliasability {
1394     FreelyAliasable(AliasableReason),
1395     NonAliasable,
1396     ImmutableUnique(Box<Aliasability>),
1397 }
1398
1399 #[derive(Copy, Clone, Debug)]
1400 pub enum AliasableReason {
1401     AliasableBorrowed,
1402     AliasableStatic,
1403     AliasableStaticMut,
1404 }
1405
1406 impl<'tcx> cmt_<'tcx> {
1407     pub fn guarantor(&self) -> cmt_<'tcx> {
1408         //! Returns `self` after stripping away any derefs or
1409         //! interior content. The return value is basically the `cmt` which
1410         //! determines how long the value in `self` remains live.
1411
1412         match self.cat {
1413             Categorization::Rvalue(..) |
1414             Categorization::StaticItem |
1415             Categorization::ThreadLocal(..) |
1416             Categorization::Local(..) |
1417             Categorization::Deref(_, UnsafePtr(..)) |
1418             Categorization::Deref(_, BorrowedPtr(..)) |
1419             Categorization::Upvar(..) => {
1420                 (*self).clone()
1421             }
1422             Categorization::Downcast(ref b, _) |
1423             Categorization::Interior(ref b, _) |
1424             Categorization::Deref(ref b, Unique) => {
1425                 b.guarantor()
1426             }
1427         }
1428     }
1429
1430     /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
1431     pub fn freely_aliasable(&self) -> Aliasability {
1432         // Maybe non-obvious: copied upvars can only be considered
1433         // non-aliasable in once closures, since any other kind can be
1434         // aliased and eventually recused.
1435
1436         match self.cat {
1437             Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1438             Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1439             Categorization::Deref(ref b, Unique) |
1440             Categorization::Downcast(ref b, _) |
1441             Categorization::Interior(ref b, _) => {
1442                 // Aliasability depends on base cmt
1443                 b.freely_aliasable()
1444             }
1445
1446             Categorization::Rvalue(..) |
1447             Categorization::ThreadLocal(..) |
1448             Categorization::Local(..) |
1449             Categorization::Upvar(..) |
1450             Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1451                 NonAliasable
1452             }
1453
1454             Categorization::StaticItem => {
1455                 if self.mutbl.is_mutable() {
1456                     FreelyAliasable(AliasableStaticMut)
1457                 } else {
1458                     FreelyAliasable(AliasableStatic)
1459                 }
1460             }
1461
1462             Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) => {
1463                 FreelyAliasable(AliasableBorrowed)
1464             }
1465         }
1466     }
1467
1468     // Digs down through one or two layers of deref and grabs the
1469     // Categorization of the cmt for the upvar if a note indicates there is
1470     // one.
1471     pub fn upvar_cat(&self) -> Option<&Categorization<'tcx>> {
1472         match self.note {
1473             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1474                 Some(match self.cat {
1475                     Categorization::Deref(ref inner, _) => {
1476                         match inner.cat {
1477                             Categorization::Deref(ref inner, _) => &inner.cat,
1478                             Categorization::Upvar(..) => &inner.cat,
1479                             _ => bug!()
1480                         }
1481                     }
1482                     _ => bug!()
1483                 })
1484             }
1485             NoteIndex | NoteNone => None
1486         }
1487     }
1488
1489     pub fn descriptive_string(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
1490         match self.cat {
1491             Categorization::StaticItem => {
1492                 "static item".into()
1493             }
1494             Categorization::ThreadLocal(..) => {
1495                 "thread-local static item".into()
1496             }
1497             Categorization::Rvalue(..) => {
1498                 "non-place".into()
1499             }
1500             Categorization::Local(vid) => {
1501                 if tcx.hir().is_argument(tcx.hir().hir_to_node_id(vid)) {
1502                     "argument"
1503                 } else {
1504                     "local variable"
1505                 }.into()
1506             }
1507             Categorization::Deref(_, pk) => {
1508                 match self.upvar_cat() {
1509                     Some(&Categorization::Upvar(ref var)) => {
1510                         var.to_string().into()
1511                     }
1512                     Some(_) => bug!(),
1513                     None => {
1514                         match pk {
1515                             Unique => {
1516                                 "`Box` content"
1517                             }
1518                             UnsafePtr(..) => {
1519                                 "dereference of raw pointer"
1520                             }
1521                             BorrowedPtr(..) => {
1522                                 match self.note {
1523                                     NoteIndex => "indexed content",
1524                                     _ => "borrowed content"
1525                                 }
1526                             }
1527                         }.into()
1528                     }
1529                 }
1530             }
1531             Categorization::Interior(_, InteriorField(..)) => {
1532                 "field".into()
1533             }
1534             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1535                 "indexed content".into()
1536             }
1537             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1538                 "pattern-bound indexed content".into()
1539             }
1540             Categorization::Upvar(ref var) => {
1541                 var.to_string().into()
1542             }
1543             Categorization::Downcast(ref cmt, _) => {
1544                 cmt.descriptive_string(tcx).into()
1545             }
1546         }
1547     }
1548 }
1549
1550 pub fn ptr_sigil(ptr: PointerKind<'_>) -> &'static str {
1551     match ptr {
1552         Unique => "Box",
1553         BorrowedPtr(ty::ImmBorrow, _) => "&",
1554         BorrowedPtr(ty::MutBorrow, _) => "&mut",
1555         BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
1556         UnsafePtr(_) => "*",
1557     }
1558 }
1559
1560 impl fmt::Debug for InteriorKind {
1561     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1562         match *self {
1563             InteriorField(FieldIndex(_, info)) => write!(f, "{}", info),
1564             InteriorElement(..) => write!(f, "[]"),
1565         }
1566     }
1567 }
1568
1569 impl fmt::Debug for Upvar {
1570     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1571         write!(f, "{:?}/{:?}", self.id, self.kind)
1572     }
1573 }
1574
1575 impl fmt::Display for Upvar {
1576     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1577         let kind = match self.kind {
1578             ty::ClosureKind::Fn => "Fn",
1579             ty::ClosureKind::FnMut => "FnMut",
1580             ty::ClosureKind::FnOnce => "FnOnce",
1581         };
1582         write!(f, "captured outer variable in an `{}` closure", kind)
1583     }
1584 }