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