]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
Rollup merge of #40445 - estebank:issue-18150, r=jonathandturner
[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 an lvalue, then this
30 //! is the address of the lvalue.  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 translation 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 translation. 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::FieldName::*;
66 pub use self::ElementKind::*;
67 pub use self::MutabilityCategory::*;
68 pub use self::AliasableReason::*;
69 pub use self::Note::*;
70
71 use self::Aliasability::*;
72
73 use hir::def_id::DefId;
74 use hir::map as hir_map;
75 use infer::InferCtxt;
76 use hir::def::{Def, CtorKind};
77 use ty::adjustment;
78 use ty::{self, Ty, TyCtxt};
79
80 use hir::{MutImmutable, MutMutable, PatKind};
81 use hir::pat_util::EnumerateAndAdjustIterator;
82 use hir;
83 use syntax::ast;
84 use syntax_pos::Span;
85
86 use std::fmt;
87 use std::rc::Rc;
88
89 #[derive(Clone, PartialEq)]
90 pub enum Categorization<'tcx> {
91     // temporary val, argument is its scope
92     Rvalue(&'tcx ty::Region, &'tcx ty::Region),
93     StaticItem,
94     Upvar(Upvar),                          // upvar referenced by closure env
95     Local(ast::NodeId),                    // local variable
96     Deref(cmt<'tcx>, usize, PointerKind<'tcx>),  // deref of a ptr
97     Interior(cmt<'tcx>, InteriorKind),     // something interior: field, tuple, etc
98     Downcast(cmt<'tcx>, DefId),            // selects a particular enum variant (*1)
99
100     // (*1) downcast is only required if the enum has more than one variant
101 }
102
103 // Represents any kind of upvar
104 #[derive(Clone, Copy, PartialEq)]
105 pub struct Upvar {
106     pub id: ty::UpvarId,
107     pub kind: ty::ClosureKind
108 }
109
110 // different kinds of pointers:
111 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
112 pub enum PointerKind<'tcx> {
113     /// `Box<T>`
114     Unique,
115
116     /// `&T`
117     BorrowedPtr(ty::BorrowKind, &'tcx ty::Region),
118
119     /// `*T`
120     UnsafePtr(hir::Mutability),
121
122     /// Implicit deref of the `&T` that results from an overloaded index `[]`.
123     Implicit(ty::BorrowKind, &'tcx ty::Region),
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(FieldName),
131     InteriorElement(InteriorOffsetKind, ElementKind),
132 }
133
134 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
135 pub enum FieldName {
136     NamedField(ast::Name),
137     PositionalField(usize)
138 }
139
140 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
141 pub enum InteriorOffsetKind {
142     Index,            // e.g. `array_expr[index_expr]`
143     Pattern,          // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
144 }
145
146 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
147 pub enum ElementKind {
148     VecElement,
149     OtherElement,
150 }
151
152 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
153 pub enum MutabilityCategory {
154     McImmutable, // Immutable.
155     McDeclared,  // Directly declared as mutable.
156     McInherited, // Inherited from the fact that owner is mutable.
157 }
158
159 // A note about the provenance of a `cmt`.  This is used for
160 // special-case handling of upvars such as mutability inference.
161 // Upvar categorization can generate a variable number of nested
162 // derefs.  The note allows detecting them without deep pattern
163 // matching on the categorization.
164 #[derive(Clone, Copy, PartialEq, Debug)]
165 pub enum Note {
166     NoteClosureEnv(ty::UpvarId), // Deref through closure env
167     NoteUpvarRef(ty::UpvarId),   // Deref through by-ref upvar
168     NoteNone                     // Nothing special
169 }
170
171 // `cmt`: "Category, Mutability, and Type".
172 //
173 // a complete categorization of a value indicating where it originated
174 // and how it is located, as well as the mutability of the memory in
175 // which the value is stored.
176 //
177 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
178 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
179 // always the `id` of the node producing the type; in an expression
180 // like `*x`, the type of this deref node is the deref'd type (`T`),
181 // but in a pattern like `@x`, the `@x` pattern is again a
182 // dereference, but its type is the type *before* the dereference
183 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
184 // fashion. For more details, see the method `cat_pattern`
185 #[derive(Clone, PartialEq)]
186 pub struct cmt_<'tcx> {
187     pub id: ast::NodeId,           // id of expr/pat producing this value
188     pub span: Span,                // span of same expr/pat
189     pub cat: Categorization<'tcx>, // categorization of expr
190     pub mutbl: MutabilityCategory, // mutability of expr as lvalue
191     pub ty: Ty<'tcx>,              // type of the expr (*see WARNING above*)
192     pub note: Note,                // Note about the provenance of this cmt
193 }
194
195 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
196
197 impl<'tcx> cmt_<'tcx> {
198     pub fn get_def(&self) -> Option<ast::NodeId> {
199         match self.cat {
200             Categorization::Deref(ref cmt, ..) |
201             Categorization::Interior(ref cmt, _) |
202             Categorization::Downcast(ref cmt, _) => {
203                 if let Categorization::Local(nid) = cmt.cat {
204                     Some(nid)
205                 } else {
206                     None
207                 }
208             }
209             _ => None
210         }
211     }
212
213     pub fn get_field(&self, name: ast::Name) -> Option<DefId> {
214         match self.cat {
215             Categorization::Deref(ref cmt, ..) |
216             Categorization::Interior(ref cmt, _) |
217             Categorization::Downcast(ref cmt, _) => {
218                 if let Categorization::Local(_) = cmt.cat {
219                     if let ty::TyAdt(def, _) = self.ty.sty {
220                         if def.is_struct() {
221                             return def.struct_variant().find_field_named(name).map(|x| x.did);
222                         }
223                     }
224                     None
225                 } else {
226                     cmt.get_field(name)
227                 }
228             }
229             _ => None
230         }
231     }
232
233     pub fn get_field_name(&self) -> Option<ast::Name> {
234         match self.cat {
235             Categorization::Interior(_, ref ik) => {
236                 if let InteriorKind::InteriorField(FieldName::NamedField(name)) = *ik {
237                     Some(name)
238                 } else {
239                     None
240                 }
241             }
242             Categorization::Deref(ref cmt, ..) |
243             Categorization::Downcast(ref cmt, _) => {
244                 cmt.get_field_name()
245             }
246             _ => None,
247         }
248     }
249
250     pub fn get_arg_if_immutable(&self, map: &hir_map::Map) -> Option<ast::NodeId> {
251         match self.cat {
252             Categorization::Deref(ref cmt, ..) |
253             Categorization::Interior(ref cmt, _) |
254             Categorization::Downcast(ref cmt, _) => {
255                 if let Categorization::Local(nid) = cmt.cat {
256                     if let ty::TyAdt(_, _) = self.ty.sty {
257                         if let ty::TyRef(_, ty::TypeAndMut{mutbl: MutImmutable, ..}) = cmt.ty.sty {
258                             return Some(nid);
259                         }
260                     }
261                     None
262                 } else {
263                     cmt.get_arg_if_immutable(map)
264                 }
265             }
266             _ => None
267         }
268     }
269 }
270
271 pub trait ast_node {
272     fn id(&self) -> ast::NodeId;
273     fn span(&self) -> Span;
274 }
275
276 impl ast_node for hir::Expr {
277     fn id(&self) -> ast::NodeId { self.id }
278     fn span(&self) -> Span { self.span }
279 }
280
281 impl ast_node for hir::Pat {
282     fn id(&self) -> ast::NodeId { self.id }
283     fn span(&self) -> Span { self.span }
284 }
285
286 #[derive(Copy, Clone)]
287 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
288     pub infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
289     options: MemCategorizationOptions,
290 }
291
292 #[derive(Copy, Clone, Default)]
293 pub struct MemCategorizationOptions {
294     // If true, then when analyzing a closure upvar, if the closure
295     // has a missing kind, we treat it like a Fn closure. When false,
296     // we ICE if the closure has a missing kind. Should be false
297     // except during closure kind inference. It is used by the
298     // mem-categorization code to be able to have stricter assertions
299     // (which are always true except during upvar inference).
300     pub during_closure_kind_inference: bool,
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, _) | Implicit(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, id: ast::NodeId) -> MutabilityCategory {
346         let ret = match tcx.hir.get(id) {
347             hir_map::NodeLocal(p) => match p.node {
348                 PatKind::Binding(bind_mode, ..) => {
349                     if bind_mode == hir::BindByValue(hir::MutMutable) {
350                         McDeclared
351                     } else {
352                         McImmutable
353                     }
354                 }
355                 _ => span_bug!(p.span, "expected identifier pattern")
356             },
357             _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
358         };
359         debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
360                "from_local", id, ret);
361         ret
362     }
363
364     pub fn inherit(&self) -> MutabilityCategory {
365         let ret = match *self {
366             McImmutable => McImmutable,
367             McDeclared => McInherited,
368             McInherited => McInherited,
369         };
370         debug!("{:?}.inherit() => {:?}", self, ret);
371         ret
372     }
373
374     pub fn is_mutable(&self) -> bool {
375         let ret = match *self {
376             McImmutable => false,
377             McInherited => true,
378             McDeclared => true,
379         };
380         debug!("{:?}.is_mutable() => {:?}", self, ret);
381         ret
382     }
383
384     pub fn is_immutable(&self) -> bool {
385         let ret = match *self {
386             McImmutable => true,
387             McDeclared | McInherited => false
388         };
389         debug!("{:?}.is_immutable() => {:?}", self, ret);
390         ret
391     }
392
393     pub fn to_user_str(&self) -> &'static str {
394         match *self {
395             McDeclared | McInherited => "mutable",
396             McImmutable => "immutable",
397         }
398     }
399 }
400
401 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
402     pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>)
403                -> MemCategorizationContext<'a, 'gcx, 'tcx> {
404         MemCategorizationContext::with_options(infcx, MemCategorizationOptions::default())
405     }
406
407     pub fn with_options(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
408                         options: MemCategorizationOptions)
409                         -> MemCategorizationContext<'a, 'gcx, 'tcx> {
410         MemCategorizationContext {
411             infcx: infcx,
412             options: options,
413         }
414     }
415
416     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
417         self.infcx.tcx
418     }
419
420     fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
421         match self.infcx.node_ty(expr.id) {
422             Ok(t) => Ok(t),
423             Err(()) => {
424                 debug!("expr_ty({:?}) yielded Err", expr);
425                 Err(())
426             }
427         }
428     }
429
430     fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
431         self.infcx.expr_ty_adjusted(expr)
432     }
433
434     fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
435         self.infcx.node_ty(id)
436     }
437
438     fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
439         let base_ty = self.infcx.node_ty(pat.id)?;
440         // FIXME (Issue #18207): This code detects whether we are
441         // looking at a `ref x`, and if so, figures out what the type
442         // *being borrowed* is.  But ideally we would put in a more
443         // fundamental fix to this conflated use of the node id.
444         let ret_ty = match pat.node {
445             PatKind::Binding(hir::BindByRef(_), ..) => {
446                 // a bind-by-ref means that the base_ty will be the type of the ident itself,
447                 // but what we want here is the type of the underlying value being borrowed.
448                 // So peel off one-level, turning the &T into T.
449                 match base_ty.builtin_deref(false, ty::NoPreference) {
450                     Some(t) => t.ty,
451                     None => { return Err(()); }
452                 }
453             }
454             _ => base_ty,
455         };
456         debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
457                pat, base_ty, ret_ty);
458         Ok(ret_ty)
459     }
460
461     pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
462         match self.infcx.tables.borrow().adjustments.get(&expr.id) {
463             None => {
464                 // No adjustments.
465                 self.cat_expr_unadjusted(expr)
466             }
467
468             Some(adjustment) => {
469                 match adjustment.kind {
470                     adjustment::Adjust::DerefRef {
471                         autoderefs,
472                         autoref: None,
473                         unsize: false
474                     } => {
475                         // Equivalent to *expr or something similar.
476                         self.cat_expr_autoderefd(expr, autoderefs)
477                     }
478
479                     adjustment::Adjust::NeverToAny |
480                     adjustment::Adjust::ReifyFnPointer |
481                     adjustment::Adjust::UnsafeFnPointer |
482                     adjustment::Adjust::ClosureFnPointer |
483                     adjustment::Adjust::MutToConstPointer |
484                     adjustment::Adjust::DerefRef {..} => {
485                         debug!("cat_expr({:?}): {:?}",
486                                adjustment,
487                                expr);
488                         // Result is an rvalue.
489                         let expr_ty = self.expr_ty_adjusted(expr)?;
490                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
491                     }
492                 }
493             }
494         }
495     }
496
497     pub fn cat_expr_autoderefd(&self,
498                                expr: &hir::Expr,
499                                autoderefs: usize)
500                                -> McResult<cmt<'tcx>> {
501         let mut cmt = self.cat_expr_unadjusted(expr)?;
502         debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
503                autoderefs,
504                cmt);
505         for deref in 1..autoderefs + 1 {
506             cmt = self.cat_deref(expr, cmt, deref)?;
507         }
508         return Ok(cmt);
509     }
510
511     pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
512         debug!("cat_expr: id={} expr={:?}", expr.id, expr);
513
514         let expr_ty = self.expr_ty(expr)?;
515         match expr.node {
516           hir::ExprUnary(hir::UnDeref, ref e_base) => {
517             let base_cmt = self.cat_expr(&e_base)?;
518             self.cat_deref(expr, base_cmt, 0)
519           }
520
521           hir::ExprField(ref base, f_name) => {
522             let base_cmt = self.cat_expr(&base)?;
523             debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
524                    expr.id,
525                    expr,
526                    base_cmt);
527             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
528           }
529
530           hir::ExprTupField(ref base, idx) => {
531             let base_cmt = self.cat_expr(&base)?;
532             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
533           }
534
535           hir::ExprIndex(ref base, _) => {
536             let method_call = ty::MethodCall::expr(expr.id());
537             match self.infcx.node_method_ty(method_call) {
538                 Some(method_ty) => {
539                     // If this is an index implemented by a method call, then it
540                     // will include an implicit deref of the result.
541                     let ret_ty = self.overloaded_method_return_ty(method_ty);
542
543                     // The index method always returns an `&T`, so
544                     // dereference it to find the result type.
545                     let elem_ty = match ret_ty.sty {
546                         ty::TyRef(_, mt) => mt.ty,
547                         _ => {
548                             debug!("cat_expr_unadjusted: return type of overloaded index is {:?}?",
549                                    ret_ty);
550                             return Err(());
551                         }
552                     };
553
554                     // The call to index() returns a `&T` value, which
555                     // is an rvalue. That is what we will be
556                     // dereferencing.
557                     let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
558                     Ok(self.cat_deref_common(expr, base_cmt, 1, elem_ty, true))
559                 }
560                 None => {
561                     self.cat_index(expr, self.cat_expr(&base)?, InteriorOffsetKind::Index)
562                 }
563             }
564           }
565
566           hir::ExprPath(ref qpath) => {
567             let def = self.infcx.tables.borrow().qpath_def(qpath, expr.id);
568             self.cat_def(expr.id, expr.span, expr_ty, def)
569           }
570
571           hir::ExprType(ref e, _) => {
572             self.cat_expr(&e)
573           }
574
575           hir::ExprAddrOf(..) | hir::ExprCall(..) |
576           hir::ExprAssign(..) | hir::ExprAssignOp(..) |
577           hir::ExprClosure(..) | hir::ExprRet(..) |
578           hir::ExprUnary(..) |
579           hir::ExprMethodCall(..) | hir::ExprCast(..) |
580           hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
581           hir::ExprBinary(..) | hir::ExprWhile(..) |
582           hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
583           hir::ExprLit(..) | hir::ExprBreak(..) |
584           hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
585           hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
586             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
587           }
588         }
589     }
590
591     pub fn cat_def(&self,
592                    id: ast::NodeId,
593                    span: Span,
594                    expr_ty: Ty<'tcx>,
595                    def: Def)
596                    -> McResult<cmt<'tcx>> {
597         debug!("cat_def: id={} expr={:?} def={:?}",
598                id, expr_ty, def);
599
600         match def {
601           Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
602           Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
603                 Ok(self.cat_rvalue_node(id, span, expr_ty))
604           }
605
606           Def::Static(_, mutbl) => {
607               Ok(Rc::new(cmt_ {
608                   id:id,
609                   span:span,
610                   cat:Categorization::StaticItem,
611                   mutbl: if mutbl { McDeclared } else { McImmutable},
612                   ty:expr_ty,
613                   note: NoteNone
614               }))
615           }
616
617           Def::Upvar(def_id, _, fn_node_id) => {
618               let var_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
619               let ty = self.node_ty(fn_node_id)?;
620               match ty.sty {
621                   ty::TyClosure(closure_id, _) => {
622                       match self.infcx.closure_kind(closure_id) {
623                           Some(kind) => {
624                               self.cat_upvar(id, span, var_id, fn_node_id, kind)
625                           }
626                           None => {
627                               if !self.options.during_closure_kind_inference {
628                                   span_bug!(
629                                       span,
630                                       "No closure kind for {:?}",
631                                       closure_id);
632                               }
633
634                               // during closure kind inference, we
635                               // don't know the closure kind yet, but
636                               // it's ok because we detect that we are
637                               // accessing an upvar and handle that
638                               // case specially anyhow. Use Fn
639                               // arbitrarily.
640                               self.cat_upvar(id, span, var_id, fn_node_id, ty::ClosureKind::Fn)
641                           }
642                       }
643                   }
644                   _ => {
645                       span_bug!(
646                           span,
647                           "Upvar of non-closure {} - {:?}",
648                           fn_node_id,
649                           ty);
650                   }
651               }
652           }
653
654           Def::Local(def_id) => {
655             let vid = self.tcx().hir.as_local_node_id(def_id).unwrap();
656             Ok(Rc::new(cmt_ {
657                 id: id,
658                 span: span,
659                 cat: Categorization::Local(vid),
660                 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
661                 ty: expr_ty,
662                 note: NoteNone
663             }))
664           }
665
666           def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
667         }
668     }
669
670     // Categorize an upvar, complete with invisible derefs of closure
671     // environment and upvar reference as appropriate.
672     fn cat_upvar(&self,
673                  id: ast::NodeId,
674                  span: Span,
675                  var_id: ast::NodeId,
676                  fn_node_id: ast::NodeId,
677                  kind: ty::ClosureKind)
678                  -> McResult<cmt<'tcx>>
679     {
680         // An upvar can have up to 3 components. We translate first to a
681         // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
682         // field from the environment.
683         //
684         // `Categorization::Upvar`.  Next, we add a deref through the implicit
685         // environment pointer with an anonymous free region 'env and
686         // appropriate borrow kind for closure kinds that take self by
687         // reference.  Finally, if the upvar was captured
688         // by-reference, we add a deref through that reference.  The
689         // region of this reference is an inference variable 'up that
690         // was previously generated and recorded in the upvar borrow
691         // map.  The borrow kind bk is inferred by based on how the
692         // upvar is used.
693         //
694         // This results in the following table for concrete closure
695         // types:
696         //
697         //                | move                 | ref
698         // ---------------+----------------------+-------------------------------
699         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
700         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
701         // FnOnce         | copied               | upvar -> &'up bk
702
703         let upvar_id = ty::UpvarId { var_id: var_id,
704                                      closure_expr_id: fn_node_id };
705         let var_ty = self.node_ty(var_id)?;
706
707         // Mutability of original variable itself
708         let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
709
710         // Construct the upvar. This represents access to the field
711         // from the environment (perhaps we should eventually desugar
712         // this field further, but it will do for now).
713         let cmt_result = cmt_ {
714             id: id,
715             span: span,
716             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
717             mutbl: var_mutbl,
718             ty: var_ty,
719             note: NoteNone
720         };
721
722         // If this is a `FnMut` or `Fn` closure, then the above is
723         // conceptually a `&mut` or `&` reference, so we have to add a
724         // deref.
725         let cmt_result = match kind {
726             ty::ClosureKind::FnOnce => {
727                 cmt_result
728             }
729             ty::ClosureKind::FnMut => {
730                 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
731             }
732             ty::ClosureKind::Fn => {
733                 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
734             }
735         };
736
737         // If this is a by-ref capture, then the upvar we loaded is
738         // actually a reference, so we have to add an implicit deref
739         // for that.
740         let upvar_id = ty::UpvarId { var_id: var_id,
741                                      closure_expr_id: fn_node_id };
742         let upvar_capture = self.infcx.upvar_capture(upvar_id).unwrap();
743         let cmt_result = match upvar_capture {
744             ty::UpvarCapture::ByValue => {
745                 cmt_result
746             }
747             ty::UpvarCapture::ByRef(upvar_borrow) => {
748                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
749                 cmt_ {
750                     id: id,
751                     span: span,
752                     cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
753                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
754                     ty: var_ty,
755                     note: NoteUpvarRef(upvar_id)
756                 }
757             }
758         };
759
760         let ret = Rc::new(cmt_result);
761         debug!("cat_upvar ret={:?}", ret);
762         Ok(ret)
763     }
764
765     fn env_deref(&self,
766                  id: ast::NodeId,
767                  span: Span,
768                  upvar_id: ty::UpvarId,
769                  upvar_mutbl: MutabilityCategory,
770                  env_borrow_kind: ty::BorrowKind,
771                  cmt_result: cmt_<'tcx>)
772                  -> cmt_<'tcx>
773     {
774         // Look up the node ID of the closure body so we can construct
775         // a free region within it
776         let fn_body_id = {
777             let fn_expr = match self.tcx().hir.find(upvar_id.closure_expr_id) {
778                 Some(hir_map::NodeExpr(e)) => e,
779                 _ => bug!()
780             };
781
782             match fn_expr.node {
783                 hir::ExprClosure(.., body_id, _) => body_id.node_id,
784                 _ => bug!()
785             }
786         };
787
788         // Region of environment pointer
789         let env_region = self.tcx().mk_region(ty::ReFree(ty::FreeRegion {
790             // The environment of a closure is guaranteed to
791             // outlive any bindings introduced in the body of the
792             // closure itself.
793             scope: self.tcx().region_maps.item_extent(fn_body_id),
794             bound_region: ty::BrEnv
795         }));
796
797         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
798
799         let var_ty = cmt_result.ty;
800
801         // We need to add the env deref.  This means
802         // that the above is actually immutable and
803         // has a ref type.  However, nothing should
804         // actually look at the type, so we can get
805         // away with stuffing a `TyError` in there
806         // instead of bothering to construct a proper
807         // one.
808         let cmt_result = cmt_ {
809             mutbl: McImmutable,
810             ty: self.tcx().types.err,
811             ..cmt_result
812         };
813
814         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
815
816         // Issue #18335. If variable is declared as immutable, override the
817         // mutability from the environment and substitute an `&T` anyway.
818         match upvar_mutbl {
819             McImmutable => { deref_mutbl = McImmutable; }
820             McDeclared | McInherited => { }
821         }
822
823         let ret = cmt_ {
824             id: id,
825             span: span,
826             cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
827             mutbl: deref_mutbl,
828             ty: var_ty,
829             note: NoteClosureEnv(upvar_id)
830         };
831
832         debug!("env_deref ret {:?}", ret);
833
834         ret
835     }
836
837     /// Returns the lifetime of a temporary created by expr with id `id`.
838     /// This could be `'static` if `id` is part of a constant expression.
839     pub fn temporary_scope(&self, id: ast::NodeId) -> (&'tcx ty::Region, &'tcx ty::Region)
840     {
841         let (scope, old_scope) =
842             self.tcx().region_maps.old_and_new_temporary_scope(id);
843         (self.tcx().mk_region(match scope {
844             Some(scope) => ty::ReScope(scope),
845             None => ty::ReStatic
846         }),
847          self.tcx().mk_region(match old_scope {
848             Some(scope) => ty::ReScope(scope),
849             None => ty::ReStatic
850         }))
851     }
852
853     pub fn cat_rvalue_node(&self,
854                            id: ast::NodeId,
855                            span: Span,
856                            expr_ty: Ty<'tcx>)
857                            -> cmt<'tcx> {
858         let promotable = self.tcx().rvalue_promotable_to_static.borrow().get(&id).cloned()
859                                    .unwrap_or(false);
860
861         // When the corresponding feature isn't toggled, only promote `[T; 0]`.
862         let promotable = match expr_ty.sty {
863             ty::TyArray(_, 0) => true,
864             _ => promotable && self.tcx().sess.features.borrow().rvalue_static_promotion,
865         };
866
867         // Compute maximum lifetime of this rvalue. This is 'static if
868         // we can promote to a constant, otherwise equal to enclosing temp
869         // lifetime.
870         let (re, old_re) = if promotable {
871             (self.tcx().mk_region(ty::ReStatic),
872              self.tcx().mk_region(ty::ReStatic))
873         } else {
874             self.temporary_scope(id)
875         };
876         let ret = self.cat_rvalue(id, span, re, old_re, expr_ty);
877         debug!("cat_rvalue_node ret {:?}", ret);
878         ret
879     }
880
881     pub fn cat_rvalue(&self,
882                       cmt_id: ast::NodeId,
883                       span: Span,
884                       temp_scope: &'tcx ty::Region,
885                       old_temp_scope: &'tcx ty::Region,
886                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
887         let ret = Rc::new(cmt_ {
888             id:cmt_id,
889             span:span,
890             cat:Categorization::Rvalue(temp_scope, old_temp_scope),
891             mutbl:McDeclared,
892             ty:expr_ty,
893             note: NoteNone
894         });
895         debug!("cat_rvalue ret {:?}", ret);
896         ret
897     }
898
899     pub fn cat_field<N:ast_node>(&self,
900                                  node: &N,
901                                  base_cmt: cmt<'tcx>,
902                                  f_name: ast::Name,
903                                  f_ty: Ty<'tcx>)
904                                  -> cmt<'tcx> {
905         let ret = Rc::new(cmt_ {
906             id: node.id(),
907             span: node.span(),
908             mutbl: base_cmt.mutbl.inherit(),
909             cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
910             ty: f_ty,
911             note: NoteNone
912         });
913         debug!("cat_field ret {:?}", ret);
914         ret
915     }
916
917     pub fn cat_tup_field<N:ast_node>(&self,
918                                      node: &N,
919                                      base_cmt: cmt<'tcx>,
920                                      f_idx: usize,
921                                      f_ty: Ty<'tcx>)
922                                      -> cmt<'tcx> {
923         let ret = Rc::new(cmt_ {
924             id: node.id(),
925             span: node.span(),
926             mutbl: base_cmt.mutbl.inherit(),
927             cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
928             ty: f_ty,
929             note: NoteNone
930         });
931         debug!("cat_tup_field ret {:?}", ret);
932         ret
933     }
934
935     fn cat_deref<N:ast_node>(&self,
936                              node: &N,
937                              base_cmt: cmt<'tcx>,
938                              deref_cnt: usize)
939                              -> McResult<cmt<'tcx>> {
940         let method_call = ty::MethodCall {
941             expr_id: node.id(),
942             autoderef: deref_cnt as u32
943         };
944         let method_ty = self.infcx.node_method_ty(method_call);
945
946         debug!("cat_deref: method_call={:?} method_ty={:?}",
947                method_call, method_ty.map(|ty| ty));
948
949         let base_cmt = match method_ty {
950             Some(method_ty) => {
951                 let ref_ty =
952                     self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap();
953                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
954             }
955             None => base_cmt
956         };
957         let base_cmt_ty = base_cmt.ty;
958         match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
959             Some(mt) => {
960                 let ret = self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, false);
961                 debug!("cat_deref ret {:?}", ret);
962                 Ok(ret)
963             }
964             None => {
965                 debug!("Explicit deref of non-derefable type: {:?}",
966                        base_cmt_ty);
967                 return Err(());
968             }
969         }
970     }
971
972     fn cat_deref_common<N:ast_node>(&self,
973                                     node: &N,
974                                     base_cmt: cmt<'tcx>,
975                                     deref_cnt: usize,
976                                     deref_ty: Ty<'tcx>,
977                                     implicit: bool)
978                                     -> cmt<'tcx>
979     {
980         let ptr = match base_cmt.ty.sty {
981             ty::TyAdt(def, ..) if def.is_box() => Unique,
982             ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
983             ty::TyRef(r, mt) => {
984                 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
985                 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
986             }
987             ref ty => bug!("unexpected type in cat_deref_common: {:?}", ty)
988         };
989         let ret = Rc::new(cmt_ {
990             id: node.id(),
991             span: node.span(),
992             // For unique ptrs, we inherit mutability from the owning reference.
993             mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
994             cat: Categorization::Deref(base_cmt, deref_cnt, ptr),
995             ty: deref_ty,
996             note: NoteNone
997         });
998         debug!("cat_deref_common ret {:?}", ret);
999         ret
1000     }
1001
1002     pub fn cat_index<N:ast_node>(&self,
1003                                  elt: &N,
1004                                  mut base_cmt: cmt<'tcx>,
1005                                  context: InteriorOffsetKind)
1006                                  -> McResult<cmt<'tcx>> {
1007         //! Creates a cmt for an indexing operation (`[]`).
1008         //!
1009         //! One subtle aspect of indexing that may not be
1010         //! immediately obvious: for anything other than a fixed-length
1011         //! vector, an operation like `x[y]` actually consists of two
1012         //! disjoint (from the point of view of borrowck) operations.
1013         //! The first is a deref of `x` to create a pointer `p` that points
1014         //! at the first element in the array. The second operation is
1015         //! an index which adds `y*sizeof(T)` to `p` to obtain the
1016         //! pointer to `x[y]`. `cat_index` will produce a resulting
1017         //! cmt containing both this deref and the indexing,
1018         //! presuming that `base_cmt` is not of fixed-length type.
1019         //!
1020         //! # Parameters
1021         //! - `elt`: the AST node being indexed
1022         //! - `base_cmt`: the cmt of `elt`
1023
1024         let method_call = ty::MethodCall::expr(elt.id());
1025         let method_ty = self.infcx.node_method_ty(method_call);
1026
1027         let (element_ty, element_kind) = match method_ty {
1028             Some(method_ty) => {
1029                 let ref_ty = self.overloaded_method_return_ty(method_ty);
1030                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
1031
1032                 (ref_ty.builtin_deref(false, ty::NoPreference).unwrap().ty,
1033                  ElementKind::OtherElement)
1034             }
1035             None => {
1036                 match base_cmt.ty.builtin_index() {
1037                     Some(ty) => (ty, ElementKind::VecElement),
1038                     None => {
1039                         return Err(());
1040                     }
1041                 }
1042             }
1043         };
1044
1045         let interior_elem = InteriorElement(context, element_kind);
1046         let ret =
1047             self.cat_imm_interior(elt, base_cmt.clone(), element_ty, interior_elem);
1048         debug!("cat_index ret {:?}", ret);
1049         return Ok(ret);
1050     }
1051
1052     pub fn cat_imm_interior<N:ast_node>(&self,
1053                                         node: &N,
1054                                         base_cmt: cmt<'tcx>,
1055                                         interior_ty: Ty<'tcx>,
1056                                         interior: InteriorKind)
1057                                         -> cmt<'tcx> {
1058         let ret = Rc::new(cmt_ {
1059             id: node.id(),
1060             span: node.span(),
1061             mutbl: base_cmt.mutbl.inherit(),
1062             cat: Categorization::Interior(base_cmt, interior),
1063             ty: interior_ty,
1064             note: NoteNone
1065         });
1066         debug!("cat_imm_interior ret={:?}", ret);
1067         ret
1068     }
1069
1070     pub fn cat_downcast<N:ast_node>(&self,
1071                                     node: &N,
1072                                     base_cmt: cmt<'tcx>,
1073                                     downcast_ty: Ty<'tcx>,
1074                                     variant_did: DefId)
1075                                     -> cmt<'tcx> {
1076         let ret = Rc::new(cmt_ {
1077             id: node.id(),
1078             span: node.span(),
1079             mutbl: base_cmt.mutbl.inherit(),
1080             cat: Categorization::Downcast(base_cmt, variant_did),
1081             ty: downcast_ty,
1082             note: NoteNone
1083         });
1084         debug!("cat_downcast ret={:?}", ret);
1085         ret
1086     }
1087
1088     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1089         where F: FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat),
1090     {
1091         self.cat_pattern_(cmt, pat, &mut op)
1092     }
1093
1094     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1095     fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1096         where F : FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat)
1097     {
1098         // Here, `cmt` is the categorization for the value being
1099         // matched and pat is the pattern it is being matched against.
1100         //
1101         // In general, the way that this works is that we walk down
1102         // the pattern, constructing a cmt that represents the path
1103         // that will be taken to reach the value being matched.
1104         //
1105         // When we encounter named bindings, we take the cmt that has
1106         // been built up and pass it off to guarantee_valid() so that
1107         // we can be sure that the binding will remain valid for the
1108         // duration of the arm.
1109         //
1110         // (*2) There is subtlety concerning the correspondence between
1111         // pattern ids and types as compared to *expression* ids and
1112         // types. This is explained briefly. on the definition of the
1113         // type `cmt`, so go off and read what it says there, then
1114         // come back and I'll dive into a bit more detail here. :) OK,
1115         // back?
1116         //
1117         // In general, the id of the cmt should be the node that
1118         // "produces" the value---patterns aren't executable code
1119         // exactly, but I consider them to "execute" when they match a
1120         // value, and I consider them to produce the value that was
1121         // matched. So if you have something like:
1122         //
1123         //     let x = @@3;
1124         //     match x {
1125         //       @@y { ... }
1126         //     }
1127         //
1128         // In this case, the cmt and the relevant ids would be:
1129         //
1130         //     CMT             Id                  Type of Id Type of cmt
1131         //
1132         //     local(x)->@->@
1133         //     ^~~~~~~^        `x` from discr      @@int      @@int
1134         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1135         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1136         //
1137         // You can see that the types of the id and the cmt are in
1138         // sync in the first line, because that id is actually the id
1139         // of an expression. But once we get to pattern ids, the types
1140         // step out of sync again. So you'll see below that we always
1141         // get the type of the *subpattern* and use that.
1142
1143         debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1144
1145         op(self, cmt.clone(), pat);
1146
1147         // Note: This goes up here (rather than within the PatKind::TupleStruct arm
1148         // alone) because PatKind::Struct can also refer to variants.
1149         let cmt = match pat.node {
1150             PatKind::Path(hir::QPath::Resolved(_, ref path)) |
1151             PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) |
1152             PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => {
1153                 match path.def {
1154                     Def::Err => return Err(()),
1155                     Def::Variant(variant_did) |
1156                     Def::VariantCtor(variant_did, ..) => {
1157                         // univariant enums do not need downcasts
1158                         let enum_did = self.tcx().parent_def_id(variant_did).unwrap();
1159                         if !self.tcx().lookup_adt_def(enum_did).is_univariant() {
1160                             self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1161                         } else {
1162                             cmt
1163                         }
1164                     }
1165                     _ => cmt
1166                 }
1167             }
1168             _ => cmt
1169         };
1170
1171         match pat.node {
1172           PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1173             let def = self.infcx.tables.borrow().qpath_def(qpath, pat.id);
1174             let expected_len = match def {
1175                 Def::VariantCtor(def_id, CtorKind::Fn) => {
1176                     let enum_def = self.tcx().parent_def_id(def_id).unwrap();
1177                     self.tcx().lookup_adt_def(enum_def).variant_with_id(def_id).fields.len()
1178                 }
1179                 Def::StructCtor(_, CtorKind::Fn) => {
1180                     match self.pat_ty(&pat)?.sty {
1181                         ty::TyAdt(adt_def, _) => {
1182                             adt_def.struct_variant().fields.len()
1183                         }
1184                         ref ty => {
1185                             span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1186                         }
1187                     }
1188                 }
1189                 def => {
1190                     span_bug!(pat.span, "tuple struct pattern didn't resolve \
1191                                          to variant or struct {:?}", def);
1192                 }
1193             };
1194
1195             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1196                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1197                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1198                                                    InteriorField(PositionalField(i)));
1199                 self.cat_pattern_(subcmt, &subpat, op)?;
1200             }
1201           }
1202
1203           PatKind::Struct(_, ref field_pats, _) => {
1204             // {f1: p1, ..., fN: pN}
1205             for fp in field_pats {
1206                 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1207                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1208                 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1209             }
1210           }
1211
1212           PatKind::Binding(.., Some(ref subpat)) => {
1213               self.cat_pattern_(cmt, &subpat, op)?;
1214           }
1215
1216           PatKind::Tuple(ref subpats, ddpos) => {
1217             // (p1, ..., pN)
1218             let expected_len = match self.pat_ty(&pat)?.sty {
1219                 ty::TyTuple(ref tys, _) => tys.len(),
1220                 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1221             };
1222             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1223                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1224                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1225                                                    InteriorField(PositionalField(i)));
1226                 self.cat_pattern_(subcmt, &subpat, op)?;
1227             }
1228           }
1229
1230           PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1231             // box p1, &p1, &mut p1.  we can ignore the mutability of
1232             // PatKind::Ref since that information is already contained
1233             // in the type.
1234             let subcmt = self.cat_deref(pat, cmt, 0)?;
1235             self.cat_pattern_(subcmt, &subpat, op)?;
1236           }
1237
1238           PatKind::Slice(ref before, ref slice, ref after) => {
1239             let context = InteriorOffsetKind::Pattern;
1240             let elt_cmt = self.cat_index(pat, cmt, context)?;
1241             for before_pat in before {
1242                 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1243             }
1244             if let Some(ref slice_pat) = *slice {
1245                 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1246             }
1247             for after_pat in after {
1248                 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1249             }
1250           }
1251
1252           PatKind::Path(_) | PatKind::Binding(.., None) |
1253           PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1254             // always ok
1255           }
1256         }
1257
1258         Ok(())
1259     }
1260
1261     fn overloaded_method_return_ty(&self,
1262                                    method_ty: Ty<'tcx>)
1263                                    -> Ty<'tcx>
1264     {
1265         // When we process an overloaded `*` or `[]` etc, we often
1266         // need to extract the return type of the method. These method
1267         // types are generated by method resolution and always have
1268         // all late-bound regions fully instantiated, so we just want
1269         // to skip past the binder.
1270         self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1271            .unwrap()
1272     }
1273 }
1274
1275 #[derive(Clone, Debug)]
1276 pub enum Aliasability {
1277     FreelyAliasable(AliasableReason),
1278     NonAliasable,
1279     ImmutableUnique(Box<Aliasability>),
1280 }
1281
1282 #[derive(Copy, Clone, Debug)]
1283 pub enum AliasableReason {
1284     AliasableBorrowed,
1285     AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1286     AliasableOther,
1287     UnaliasableImmutable, // Created as needed upon seeing ImmutableUnique
1288     AliasableStatic,
1289     AliasableStaticMut,
1290 }
1291
1292 impl<'tcx> cmt_<'tcx> {
1293     pub fn guarantor(&self) -> cmt<'tcx> {
1294         //! Returns `self` after stripping away any derefs or
1295         //! interior content. The return value is basically the `cmt` which
1296         //! determines how long the value in `self` remains live.
1297
1298         match self.cat {
1299             Categorization::Rvalue(..) |
1300             Categorization::StaticItem |
1301             Categorization::Local(..) |
1302             Categorization::Deref(.., UnsafePtr(..)) |
1303             Categorization::Deref(.., BorrowedPtr(..)) |
1304             Categorization::Deref(.., Implicit(..)) |
1305             Categorization::Upvar(..) => {
1306                 Rc::new((*self).clone())
1307             }
1308             Categorization::Downcast(ref b, _) |
1309             Categorization::Interior(ref b, _) |
1310             Categorization::Deref(ref b, _, Unique) => {
1311                 b.guarantor()
1312             }
1313         }
1314     }
1315
1316     /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1317     pub fn freely_aliasable(&self) -> Aliasability {
1318         // Maybe non-obvious: copied upvars can only be considered
1319         // non-aliasable in once closures, since any other kind can be
1320         // aliased and eventually recused.
1321
1322         match self.cat {
1323             Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1324             Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1325             Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1326             Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1327             Categorization::Downcast(ref b, _) |
1328             Categorization::Interior(ref b, _) => {
1329                 // Aliasability depends on base cmt
1330                 b.freely_aliasable()
1331             }
1332
1333             Categorization::Deref(ref b, _, Unique) => {
1334                 let sub = b.freely_aliasable();
1335                 if b.mutbl.is_mutable() {
1336                     // Aliasability depends on base cmt alone
1337                     sub
1338                 } else {
1339                     // Do not allow mutation through an immutable box.
1340                     ImmutableUnique(Box::new(sub))
1341                 }
1342             }
1343
1344             Categorization::Rvalue(..) |
1345             Categorization::Local(..) |
1346             Categorization::Upvar(..) |
1347             Categorization::Deref(.., UnsafePtr(..)) => { // yes, it's aliasable, but...
1348                 NonAliasable
1349             }
1350
1351             Categorization::StaticItem => {
1352                 if self.mutbl.is_mutable() {
1353                     FreelyAliasable(AliasableStaticMut)
1354                 } else {
1355                     FreelyAliasable(AliasableStatic)
1356                 }
1357             }
1358
1359             Categorization::Deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1360             Categorization::Deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1361                 match base.cat {
1362                     Categorization::Upvar(Upvar{ id, .. }) =>
1363                         FreelyAliasable(AliasableClosure(id.closure_expr_id)),
1364                     _ => FreelyAliasable(AliasableBorrowed)
1365                 }
1366             }
1367         }
1368     }
1369
1370     // Digs down through one or two layers of deref and grabs the cmt
1371     // for the upvar if a note indicates there is one.
1372     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1373         match self.note {
1374             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1375                 Some(match self.cat {
1376                     Categorization::Deref(ref inner, ..) => {
1377                         match inner.cat {
1378                             Categorization::Deref(ref inner, ..) => inner.clone(),
1379                             Categorization::Upvar(..) => inner.clone(),
1380                             _ => bug!()
1381                         }
1382                     }
1383                     _ => bug!()
1384                 })
1385             }
1386             NoteNone => None
1387         }
1388     }
1389
1390
1391     pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1392         match self.cat {
1393             Categorization::StaticItem => {
1394                 "static item".to_string()
1395             }
1396             Categorization::Rvalue(..) => {
1397                 "non-lvalue".to_string()
1398             }
1399             Categorization::Local(vid) => {
1400                 if tcx.hir.is_argument(vid) {
1401                     "argument".to_string()
1402                 } else {
1403                     "local variable".to_string()
1404                 }
1405             }
1406             Categorization::Deref(.., pk) => {
1407                 let upvar = self.upvar();
1408                 match upvar.as_ref().map(|i| &i.cat) {
1409                     Some(&Categorization::Upvar(ref var)) => {
1410                         var.to_string()
1411                     }
1412                     Some(_) => bug!(),
1413                     None => {
1414                         match pk {
1415                             Implicit(..) => {
1416                                 format!("indexed content")
1417                             }
1418                             Unique => {
1419                                 format!("`Box` content")
1420                             }
1421                             UnsafePtr(..) => {
1422                                 format!("dereference of raw pointer")
1423                             }
1424                             BorrowedPtr(..) => {
1425                                 format!("borrowed content")
1426                             }
1427                         }
1428                     }
1429                 }
1430             }
1431             Categorization::Interior(_, InteriorField(NamedField(_))) => {
1432                 "field".to_string()
1433             }
1434             Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1435                 "anonymous field".to_string()
1436             }
1437             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1438                                                         VecElement)) |
1439             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1440                                                         OtherElement)) => {
1441                 "indexed content".to_string()
1442             }
1443             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1444                                                         VecElement)) |
1445             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1446                                                         OtherElement)) => {
1447                 "pattern-bound indexed content".to_string()
1448             }
1449             Categorization::Upvar(ref var) => {
1450                 var.to_string()
1451             }
1452             Categorization::Downcast(ref cmt, _) => {
1453                 cmt.descriptive_string(tcx)
1454             }
1455         }
1456     }
1457 }
1458
1459 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1460     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1461         write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1462                self.cat,
1463                self.id,
1464                self.mutbl,
1465                self.ty)
1466     }
1467 }
1468
1469 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1470     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1471         match *self {
1472             Categorization::StaticItem => write!(f, "static"),
1473             Categorization::Rvalue(r, or) => {
1474                 write!(f, "rvalue({:?}, {:?})", r, or)
1475             }
1476             Categorization::Local(id) => {
1477                let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1478                write!(f, "local({})", name)
1479             }
1480             Categorization::Upvar(upvar) => {
1481                 write!(f, "upvar({:?})", upvar)
1482             }
1483             Categorization::Deref(ref cmt, derefs, ptr) => {
1484                 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1485             }
1486             Categorization::Interior(ref cmt, interior) => {
1487                 write!(f, "{:?}.{:?}", cmt.cat, interior)
1488             }
1489             Categorization::Downcast(ref cmt, _) => {
1490                 write!(f, "{:?}->(enum)", cmt.cat)
1491             }
1492         }
1493     }
1494 }
1495
1496 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1497     match ptr {
1498         Unique => "Box",
1499         BorrowedPtr(ty::ImmBorrow, _) |
1500         Implicit(ty::ImmBorrow, _) => "&",
1501         BorrowedPtr(ty::MutBorrow, _) |
1502         Implicit(ty::MutBorrow, _) => "&mut",
1503         BorrowedPtr(ty::UniqueImmBorrow, _) |
1504         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1505         UnsafePtr(_) => "*",
1506     }
1507 }
1508
1509 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1510     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511         match *self {
1512             Unique => write!(f, "Box"),
1513             BorrowedPtr(ty::ImmBorrow, ref r) |
1514             Implicit(ty::ImmBorrow, ref r) => {
1515                 write!(f, "&{:?}", r)
1516             }
1517             BorrowedPtr(ty::MutBorrow, ref r) |
1518             Implicit(ty::MutBorrow, ref r) => {
1519                 write!(f, "&{:?} mut", r)
1520             }
1521             BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1522             Implicit(ty::UniqueImmBorrow, ref r) => {
1523                 write!(f, "&{:?} uniq", r)
1524             }
1525             UnsafePtr(_) => write!(f, "*")
1526         }
1527     }
1528 }
1529
1530 impl fmt::Debug for InteriorKind {
1531     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1532         match *self {
1533             InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1534             InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1535             InteriorElement(..) => write!(f, "[]"),
1536         }
1537     }
1538 }
1539
1540 impl fmt::Debug for Upvar {
1541     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1542         write!(f, "{:?}/{:?}", self.id, self.kind)
1543     }
1544 }
1545
1546 impl fmt::Display for Upvar {
1547     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1548         let kind = match self.kind {
1549             ty::ClosureKind::Fn => "Fn",
1550             ty::ClosureKind::FnMut => "FnMut",
1551             ty::ClosureKind::FnOnce => "FnOnce",
1552         };
1553         write!(f, "captured outer variable in an `{}` closure", kind)
1554     }
1555 }