]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
Fix the fallout
[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 pub use self::deref_kind::*;
71
72 use self::Aliasability::*;
73
74 use middle::def_id::DefId;
75 use front::map as ast_map;
76 use middle::infer;
77 use middle::check_const;
78 use middle::def;
79 use middle::ty::adjustment;
80 use middle::ty::{self, Ty};
81
82 use rustc_front::hir::{MutImmutable, MutMutable};
83 use rustc_front::hir;
84 use syntax::ast;
85 use syntax::codemap::Span;
86
87 use std::fmt;
88 use std::rc::Rc;
89
90 #[derive(Clone, PartialEq)]
91 pub enum Categorization<'tcx> {
92     Rvalue(ty::Region),                    // temporary val, argument is its scope
93     StaticItem,
94     Upvar(Upvar),                          // upvar referenced by closure env
95     Local(ast::NodeId),                    // local variable
96     Deref(cmt<'tcx>, usize, PointerKind),  // 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 {
113     /// `Box<T>`
114     Unique,
115
116     /// `&T`
117     BorrowedPtr(ty::BorrowKind, 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, 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 // We pun on *T to mean both actual deref of a ptr as well
198 // as accessing of components:
199 #[derive(Copy, Clone)]
200 pub enum deref_kind {
201     deref_ptr(PointerKind),
202     deref_interior(InteriorKind),
203 }
204
205 type DerefKindContext = Option<InteriorOffsetKind>;
206
207 // Categorizes a derefable type.  Note that we include vectors and strings as
208 // derefable (we model an index as the combination of a deref and then a
209 // pointer adjustment).
210 fn deref_kind(t: Ty, context: DerefKindContext) -> McResult<deref_kind> {
211     match t.sty {
212         ty::TyBox(_) => {
213             Ok(deref_ptr(Unique))
214         }
215
216         ty::TyRef(r, mt) => {
217             let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
218             Ok(deref_ptr(BorrowedPtr(kind, *r)))
219         }
220
221         ty::TyRawPtr(ref mt) => {
222             Ok(deref_ptr(UnsafePtr(mt.mutbl)))
223         }
224
225         ty::TyEnum(..) |
226         ty::TyStruct(..) => { // newtype
227             Ok(deref_interior(InteriorField(PositionalField(0))))
228         }
229
230         ty::TyArray(_, _) | ty::TySlice(_) | ty::TyStr => {
231             // no deref of indexed content without supplying InteriorOffsetKind
232             if let Some(context) = context {
233                 Ok(deref_interior(InteriorElement(context, element_kind(t))))
234             } else {
235                 Err(())
236             }
237         }
238
239         _ => Err(()),
240     }
241 }
242
243 pub trait ast_node {
244     fn id(&self) -> ast::NodeId;
245     fn span(&self) -> Span;
246 }
247
248 impl ast_node for hir::Expr {
249     fn id(&self) -> ast::NodeId { self.id }
250     fn span(&self) -> Span { self.span }
251 }
252
253 impl ast_node for hir::Pat {
254     fn id(&self) -> ast::NodeId { self.id }
255     fn span(&self) -> Span { self.span }
256 }
257
258 #[derive(Copy, Clone)]
259 pub struct MemCategorizationContext<'t, 'a: 't, 'tcx : 'a> {
260     pub typer: &'t infer::InferCtxt<'a, 'tcx>,
261 }
262
263 pub type McResult<T> = Result<T, ()>;
264
265 impl MutabilityCategory {
266     pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
267         let ret = match m {
268             MutImmutable => McImmutable,
269             MutMutable => McDeclared
270         };
271         debug!("MutabilityCategory::{}({:?}) => {:?}",
272                "from_mutbl", m, ret);
273         ret
274     }
275
276     pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
277         let ret = match borrow_kind {
278             ty::ImmBorrow => McImmutable,
279             ty::UniqueImmBorrow => McImmutable,
280             ty::MutBorrow => McDeclared,
281         };
282         debug!("MutabilityCategory::{}({:?}) => {:?}",
283                "from_borrow_kind", borrow_kind, ret);
284         ret
285     }
286
287     fn from_pointer_kind(base_mutbl: MutabilityCategory,
288                          ptr: PointerKind) -> MutabilityCategory {
289         let ret = match ptr {
290             Unique => {
291                 base_mutbl.inherit()
292             }
293             BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
294                 MutabilityCategory::from_borrow_kind(borrow_kind)
295             }
296             UnsafePtr(m) => {
297                 MutabilityCategory::from_mutbl(m)
298             }
299         };
300         debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
301                "from_pointer_kind", base_mutbl, ptr, ret);
302         ret
303     }
304
305     fn from_local(tcx: &ty::ctxt, id: ast::NodeId) -> MutabilityCategory {
306         let ret = match tcx.map.get(id) {
307             ast_map::NodeLocal(p) => match p.node {
308                 hir::PatIdent(bind_mode, _, _) => {
309                     if bind_mode == hir::BindByValue(hir::MutMutable) {
310                         McDeclared
311                     } else {
312                         McImmutable
313                     }
314                 }
315                 _ => tcx.sess.span_bug(p.span, "expected identifier pattern")
316             },
317             _ => tcx.sess.span_bug(tcx.map.span(id), "expected identifier pattern")
318         };
319         debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
320                "from_local", id, ret);
321         ret
322     }
323
324     pub fn inherit(&self) -> MutabilityCategory {
325         let ret = match *self {
326             McImmutable => McImmutable,
327             McDeclared => McInherited,
328             McInherited => McInherited,
329         };
330         debug!("{:?}.inherit() => {:?}", self, ret);
331         ret
332     }
333
334     pub fn is_mutable(&self) -> bool {
335         let ret = match *self {
336             McImmutable => false,
337             McInherited => true,
338             McDeclared => true,
339         };
340         debug!("{:?}.is_mutable() => {:?}", self, ret);
341         ret
342     }
343
344     pub fn is_immutable(&self) -> bool {
345         let ret = match *self {
346             McImmutable => true,
347             McDeclared | McInherited => false
348         };
349         debug!("{:?}.is_immutable() => {:?}", self, ret);
350         ret
351     }
352
353     pub fn to_user_str(&self) -> &'static str {
354         match *self {
355             McDeclared | McInherited => "mutable",
356             McImmutable => "immutable",
357         }
358     }
359 }
360
361 impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
362     pub fn new(typer: &'t infer::InferCtxt<'a, 'tcx>) -> MemCategorizationContext<'t, 'a, 'tcx> {
363         MemCategorizationContext { typer: typer }
364     }
365
366     fn tcx(&self) -> &'a ty::ctxt<'tcx> {
367         self.typer.tcx
368     }
369
370     fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
371         match self.typer.node_ty(expr.id) {
372             Ok(t) => Ok(t),
373             Err(()) => {
374                 debug!("expr_ty({:?}) yielded Err", expr);
375                 Err(())
376             }
377         }
378     }
379
380     fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
381         let unadjusted_ty = try!(self.expr_ty(expr));
382         Ok(unadjusted_ty.adjust(
383             self.tcx(), expr.span, expr.id,
384             self.typer.adjustments().get(&expr.id),
385             |method_call| self.typer.node_method_ty(method_call)))
386     }
387
388     fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
389         self.typer.node_ty(id)
390     }
391
392     fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
393         let base_ty = try!(self.typer.node_ty(pat.id));
394         // FIXME (Issue #18207): This code detects whether we are
395         // looking at a `ref x`, and if so, figures out what the type
396         // *being borrowed* is.  But ideally we would put in a more
397         // fundamental fix to this conflated use of the node id.
398         let ret_ty = match pat.node {
399             hir::PatIdent(hir::BindByRef(_), _, _) => {
400                 // a bind-by-ref means that the base_ty will be the type of the ident itself,
401                 // but what we want here is the type of the underlying value being borrowed.
402                 // So peel off one-level, turning the &T into T.
403                 match base_ty.builtin_deref(false, ty::NoPreference) {
404                     Some(t) => t.ty,
405                     None => { return Err(()); }
406                 }
407             }
408             _ => base_ty,
409         };
410         debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
411                pat, base_ty, ret_ty);
412         Ok(ret_ty)
413     }
414
415     pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
416         match self.typer.adjustments().get(&expr.id) {
417             None => {
418                 // No adjustments.
419                 self.cat_expr_unadjusted(expr)
420             }
421
422             Some(adjustment) => {
423                 match *adjustment {
424                     adjustment::AdjustDerefRef(
425                         adjustment::AutoDerefRef {
426                             autoref: None, unsize: None, autoderefs, ..}) => {
427                         // Equivalent to *expr or something similar.
428                         self.cat_expr_autoderefd(expr, autoderefs)
429                     }
430
431                     adjustment::AdjustReifyFnPointer |
432                     adjustment::AdjustUnsafeFnPointer |
433                     adjustment::AdjustDerefRef(_) => {
434                         debug!("cat_expr({:?}): {:?}",
435                                adjustment,
436                                expr);
437                         // Result is an rvalue.
438                         let expr_ty = try!(self.expr_ty_adjusted(expr));
439                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
440                     }
441                 }
442             }
443         }
444     }
445
446     pub fn cat_expr_autoderefd(&self,
447                                expr: &hir::Expr,
448                                autoderefs: usize)
449                                -> McResult<cmt<'tcx>> {
450         let mut cmt = try!(self.cat_expr_unadjusted(expr));
451         debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
452                autoderefs,
453                cmt);
454         for deref in 1..autoderefs + 1 {
455             cmt = try!(self.cat_deref(expr, cmt, deref, None));
456         }
457         return Ok(cmt);
458     }
459
460     pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
461         debug!("cat_expr: id={} expr={:?}", expr.id, expr);
462
463         let expr_ty = try!(self.expr_ty(expr));
464         match expr.node {
465           hir::ExprUnary(hir::UnDeref, ref e_base) => {
466             let base_cmt = try!(self.cat_expr(&**e_base));
467             self.cat_deref(expr, base_cmt, 0, None)
468           }
469
470           hir::ExprField(ref base, f_name) => {
471             let base_cmt = try!(self.cat_expr(&**base));
472             debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
473                    expr.id,
474                    expr,
475                    base_cmt);
476             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
477           }
478
479           hir::ExprTupField(ref base, idx) => {
480             let base_cmt = try!(self.cat_expr(&**base));
481             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
482           }
483
484           hir::ExprIndex(ref base, _) => {
485             let method_call = ty::MethodCall::expr(expr.id());
486             let context = InteriorOffsetKind::Index;
487             match self.typer.node_method_ty(method_call) {
488                 Some(method_ty) => {
489                     // If this is an index implemented by a method call, then it
490                     // will include an implicit deref of the result.
491                     let ret_ty = self.overloaded_method_return_ty(method_ty);
492
493                     // The index method always returns an `&T`, so
494                     // dereference it to find the result type.
495                     let elem_ty = match ret_ty.sty {
496                         ty::TyRef(_, mt) => mt.ty,
497                         _ => {
498                             debug!("cat_expr_unadjusted: return type of overloaded index is {:?}?",
499                                    ret_ty);
500                             return Err(());
501                         }
502                     };
503
504                     // The call to index() returns a `&T` value, which
505                     // is an rvalue. That is what we will be
506                     // dereferencing.
507                     let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
508                     self.cat_deref_common(expr, base_cmt, 1, elem_ty, Some(context), true)
509                 }
510                 None => {
511                     self.cat_index(expr, try!(self.cat_expr(&**base)), context)
512                 }
513             }
514           }
515
516           hir::ExprPath(..) => {
517             let def = self.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
518             self.cat_def(expr.id, expr.span, expr_ty, def)
519           }
520
521           hir::ExprAddrOf(..) | hir::ExprCall(..) |
522           hir::ExprAssign(..) | hir::ExprAssignOp(..) |
523           hir::ExprClosure(..) | hir::ExprRet(..) |
524           hir::ExprUnary(..) | hir::ExprRange(..) |
525           hir::ExprMethodCall(..) | hir::ExprCast(..) |
526           hir::ExprVec(..) | hir::ExprTup(..) | hir::ExprIf(..) |
527           hir::ExprBinary(..) | hir::ExprWhile(..) |
528           hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
529           hir::ExprLit(..) | hir::ExprBreak(..) |
530           hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
531           hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
532             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
533           }
534         }
535     }
536
537     pub fn cat_def(&self,
538                    id: ast::NodeId,
539                    span: Span,
540                    expr_ty: Ty<'tcx>,
541                    def: def::Def)
542                    -> McResult<cmt<'tcx>> {
543         debug!("cat_def: id={} expr={:?} def={:?}",
544                id, expr_ty, def);
545
546         match def {
547           def::DefStruct(..) | def::DefVariant(..) | def::DefConst(..) |
548           def::DefAssociatedConst(..) | def::DefFn(..) | def::DefMethod(..) => {
549                 Ok(self.cat_rvalue_node(id, span, expr_ty))
550           }
551           def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
552           def::DefTrait(_) | def::DefTy(..) | def::DefPrimTy(_) |
553           def::DefTyParam(..) |
554           def::DefLabel(_) | def::DefSelfTy(..) |
555           def::DefAssociatedTy(..) => {
556               Ok(Rc::new(cmt_ {
557                   id:id,
558                   span:span,
559                   cat:Categorization::StaticItem,
560                   mutbl: McImmutable,
561                   ty:expr_ty,
562                   note: NoteNone
563               }))
564           }
565
566           def::DefStatic(_, mutbl) => {
567               Ok(Rc::new(cmt_ {
568                   id:id,
569                   span:span,
570                   cat:Categorization::StaticItem,
571                   mutbl: if mutbl { McDeclared } else { McImmutable},
572                   ty:expr_ty,
573                   note: NoteNone
574               }))
575           }
576
577           def::DefUpvar(_, var_id, _, fn_node_id) => {
578               let ty = try!(self.node_ty(fn_node_id));
579               match ty.sty {
580                   ty::TyClosure(closure_id, _) => {
581                       match self.typer.closure_kind(closure_id) {
582                           Some(kind) => {
583                               self.cat_upvar(id, span, var_id, fn_node_id, kind)
584                           }
585                           None => {
586                               self.tcx().sess.span_bug(
587                                   span,
588                                   &*format!("No closure kind for {:?}", closure_id));
589                           }
590                       }
591                   }
592                   _ => {
593                       self.tcx().sess.span_bug(
594                           span,
595                           &format!("Upvar of non-closure {} - {:?}",
596                                   fn_node_id,
597                                   ty));
598                   }
599               }
600           }
601
602           def::DefLocal(_, vid) => {
603             Ok(Rc::new(cmt_ {
604                 id: id,
605                 span: span,
606                 cat: Categorization::Local(vid),
607                 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
608                 ty: expr_ty,
609                 note: NoteNone
610             }))
611           }
612         }
613     }
614
615     // Categorize an upvar, complete with invisible derefs of closure
616     // environment and upvar reference as appropriate.
617     fn cat_upvar(&self,
618                  id: ast::NodeId,
619                  span: Span,
620                  var_id: ast::NodeId,
621                  fn_node_id: ast::NodeId,
622                  kind: ty::ClosureKind)
623                  -> McResult<cmt<'tcx>>
624     {
625         // An upvar can have up to 3 components. We translate first to a
626         // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
627         // field from the environment.
628         //
629         // `Categorization::Upvar`.  Next, we add a deref through the implicit
630         // environment pointer with an anonymous free region 'env and
631         // appropriate borrow kind for closure kinds that take self by
632         // reference.  Finally, if the upvar was captured
633         // by-reference, we add a deref through that reference.  The
634         // region of this reference is an inference variable 'up that
635         // was previously generated and recorded in the upvar borrow
636         // map.  The borrow kind bk is inferred by based on how the
637         // upvar is used.
638         //
639         // This results in the following table for concrete closure
640         // types:
641         //
642         //                | move                 | ref
643         // ---------------+----------------------+-------------------------------
644         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
645         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
646         // FnOnce         | copied               | upvar -> &'up bk
647
648         let upvar_id = ty::UpvarId { var_id: var_id,
649                                      closure_expr_id: fn_node_id };
650         let var_ty = try!(self.node_ty(var_id));
651
652         // Mutability of original variable itself
653         let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
654
655         // Construct the upvar. This represents access to the field
656         // from the environment (perhaps we should eventually desugar
657         // this field further, but it will do for now).
658         let cmt_result = cmt_ {
659             id: id,
660             span: span,
661             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
662             mutbl: var_mutbl,
663             ty: var_ty,
664             note: NoteNone
665         };
666
667         // If this is a `FnMut` or `Fn` closure, then the above is
668         // conceptually a `&mut` or `&` reference, so we have to add a
669         // deref.
670         let cmt_result = match kind {
671             ty::FnOnceClosureKind => {
672                 cmt_result
673             }
674             ty::FnMutClosureKind => {
675                 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
676             }
677             ty::FnClosureKind => {
678                 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
679             }
680         };
681
682         // If this is a by-ref capture, then the upvar we loaded is
683         // actually a reference, so we have to add an implicit deref
684         // for that.
685         let upvar_id = ty::UpvarId { var_id: var_id,
686                                      closure_expr_id: fn_node_id };
687         let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
688         let cmt_result = match upvar_capture {
689             ty::UpvarCapture::ByValue => {
690                 cmt_result
691             }
692             ty::UpvarCapture::ByRef(upvar_borrow) => {
693                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
694                 cmt_ {
695                     id: id,
696                     span: span,
697                     cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
698                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
699                     ty: var_ty,
700                     note: NoteUpvarRef(upvar_id)
701                 }
702             }
703         };
704
705         let ret = Rc::new(cmt_result);
706         debug!("cat_upvar ret={:?}", ret);
707         Ok(ret)
708     }
709
710     fn env_deref(&self,
711                  id: ast::NodeId,
712                  span: Span,
713                  upvar_id: ty::UpvarId,
714                  upvar_mutbl: MutabilityCategory,
715                  env_borrow_kind: ty::BorrowKind,
716                  cmt_result: cmt_<'tcx>)
717                  -> cmt_<'tcx>
718     {
719         // Look up the node ID of the closure body so we can construct
720         // a free region within it
721         let fn_body_id = {
722             let fn_expr = match self.tcx().map.find(upvar_id.closure_expr_id) {
723                 Some(ast_map::NodeExpr(e)) => e,
724                 _ => unreachable!()
725             };
726
727             match fn_expr.node {
728                 hir::ExprClosure(_, _, ref body) => body.id,
729                 _ => unreachable!()
730             }
731         };
732
733         // Region of environment pointer
734         let env_region = ty::ReFree(ty::FreeRegion {
735             // The environment of a closure is guaranteed to
736             // outlive any bindings introduced in the body of the
737             // closure itself.
738             scope: self.tcx().region_maps.item_extent(fn_body_id),
739             bound_region: ty::BrEnv
740         });
741
742         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
743
744         let var_ty = cmt_result.ty;
745
746         // We need to add the env deref.  This means
747         // that the above is actually immutable and
748         // has a ref type.  However, nothing should
749         // actually look at the type, so we can get
750         // away with stuffing a `TyError` in there
751         // instead of bothering to construct a proper
752         // one.
753         let cmt_result = cmt_ {
754             mutbl: McImmutable,
755             ty: self.tcx().types.err,
756             ..cmt_result
757         };
758
759         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
760
761         // Issue #18335. If variable is declared as immutable, override the
762         // mutability from the environment and substitute an `&T` anyway.
763         match upvar_mutbl {
764             McImmutable => { deref_mutbl = McImmutable; }
765             McDeclared | McInherited => { }
766         }
767
768         let ret = cmt_ {
769             id: id,
770             span: span,
771             cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
772             mutbl: deref_mutbl,
773             ty: var_ty,
774             note: NoteClosureEnv(upvar_id)
775         };
776
777         debug!("env_deref ret {:?}", ret);
778
779         ret
780     }
781
782     /// Returns the lifetime of a temporary created by expr with id `id`.
783     /// This could be `'static` if `id` is part of a constant expression.
784     pub fn temporary_scope(&self, id: ast::NodeId) -> ty::Region {
785         match self.typer.temporary_scope(id) {
786             Some(scope) => ty::ReScope(scope),
787             None => ty::ReStatic
788         }
789     }
790
791     pub fn cat_rvalue_node(&self,
792                            id: ast::NodeId,
793                            span: Span,
794                            expr_ty: Ty<'tcx>)
795                            -> cmt<'tcx> {
796         let qualif = self.tcx().const_qualif_map.borrow().get(&id).cloned()
797                                .unwrap_or(check_const::ConstQualif::NOT_CONST);
798
799         // Only promote `[T; 0]` before an RFC for rvalue promotions
800         // is accepted.
801         let qualif = match expr_ty.sty {
802             ty::TyArray(_, 0) => qualif,
803             _ => check_const::ConstQualif::NOT_CONST
804         };
805
806         // Compute maximum lifetime of this rvalue. This is 'static if
807         // we can promote to a constant, otherwise equal to enclosing temp
808         // lifetime.
809         let re = if qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS) {
810             self.temporary_scope(id)
811         } else {
812             ty::ReStatic
813         };
814         let ret = self.cat_rvalue(id, span, re, expr_ty);
815         debug!("cat_rvalue_node ret {:?}", ret);
816         ret
817     }
818
819     pub fn cat_rvalue(&self,
820                       cmt_id: ast::NodeId,
821                       span: Span,
822                       temp_scope: ty::Region,
823                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
824         let ret = Rc::new(cmt_ {
825             id:cmt_id,
826             span:span,
827             cat:Categorization::Rvalue(temp_scope),
828             mutbl:McDeclared,
829             ty:expr_ty,
830             note: NoteNone
831         });
832         debug!("cat_rvalue ret {:?}", ret);
833         ret
834     }
835
836     pub fn cat_field<N:ast_node>(&self,
837                                  node: &N,
838                                  base_cmt: cmt<'tcx>,
839                                  f_name: ast::Name,
840                                  f_ty: Ty<'tcx>)
841                                  -> cmt<'tcx> {
842         let ret = Rc::new(cmt_ {
843             id: node.id(),
844             span: node.span(),
845             mutbl: base_cmt.mutbl.inherit(),
846             cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
847             ty: f_ty,
848             note: NoteNone
849         });
850         debug!("cat_field ret {:?}", ret);
851         ret
852     }
853
854     pub fn cat_tup_field<N:ast_node>(&self,
855                                      node: &N,
856                                      base_cmt: cmt<'tcx>,
857                                      f_idx: usize,
858                                      f_ty: Ty<'tcx>)
859                                      -> cmt<'tcx> {
860         let ret = Rc::new(cmt_ {
861             id: node.id(),
862             span: node.span(),
863             mutbl: base_cmt.mutbl.inherit(),
864             cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
865             ty: f_ty,
866             note: NoteNone
867         });
868         debug!("cat_tup_field ret {:?}", ret);
869         ret
870     }
871
872     fn cat_deref<N:ast_node>(&self,
873                              node: &N,
874                              base_cmt: cmt<'tcx>,
875                              deref_cnt: usize,
876                              deref_context: DerefKindContext)
877                              -> McResult<cmt<'tcx>> {
878         let method_call = ty::MethodCall {
879             expr_id: node.id(),
880             autoderef: deref_cnt as u32
881         };
882         let method_ty = self.typer.node_method_ty(method_call);
883
884         debug!("cat_deref: method_call={:?} method_ty={:?}",
885                method_call, method_ty.map(|ty| ty));
886
887         let base_cmt = match method_ty {
888             Some(method_ty) => {
889                 let ref_ty =
890                     self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
891                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
892             }
893             None => base_cmt
894         };
895         let base_cmt_ty = base_cmt.ty;
896         match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
897             Some(mt) => {
898                 let ret = self.cat_deref_common(node, base_cmt, deref_cnt,
899                                               mt.ty,
900                                               deref_context,
901                                                 /* implicit: */ false);
902                 debug!("cat_deref ret {:?}", ret);
903                 ret
904             }
905             None => {
906                 debug!("Explicit deref of non-derefable type: {:?}",
907                        base_cmt_ty);
908                 return Err(());
909             }
910         }
911     }
912
913     fn cat_deref_common<N:ast_node>(&self,
914                                     node: &N,
915                                     base_cmt: cmt<'tcx>,
916                                     deref_cnt: usize,
917                                     deref_ty: Ty<'tcx>,
918                                     deref_context: DerefKindContext,
919                                     implicit: bool)
920                                     -> McResult<cmt<'tcx>>
921     {
922         let (m, cat) = match try!(deref_kind(base_cmt.ty, deref_context)) {
923             deref_ptr(ptr) => {
924                 let ptr = if implicit {
925                     match ptr {
926                         BorrowedPtr(bk, r) => Implicit(bk, r),
927                         _ => self.tcx().sess.span_bug(node.span(),
928                             "Implicit deref of non-borrowed pointer")
929                     }
930                 } else {
931                     ptr
932                 };
933                 // for unique ptrs, we inherit mutability from the
934                 // owning reference.
935                 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
936                  Categorization::Deref(base_cmt, deref_cnt, ptr))
937             }
938             deref_interior(interior) => {
939                 (base_cmt.mutbl.inherit(), Categorization::Interior(base_cmt, interior))
940             }
941         };
942         let ret = Rc::new(cmt_ {
943             id: node.id(),
944             span: node.span(),
945             cat: cat,
946             mutbl: m,
947             ty: deref_ty,
948             note: NoteNone
949         });
950         debug!("cat_deref_common ret {:?}", ret);
951         Ok(ret)
952     }
953
954     pub fn cat_index<N:ast_node>(&self,
955                                  elt: &N,
956                                  mut base_cmt: cmt<'tcx>,
957                                  context: InteriorOffsetKind)
958                                  -> McResult<cmt<'tcx>> {
959         //! Creates a cmt for an indexing operation (`[]`).
960         //!
961         //! One subtle aspect of indexing that may not be
962         //! immediately obvious: for anything other than a fixed-length
963         //! vector, an operation like `x[y]` actually consists of two
964         //! disjoint (from the point of view of borrowck) operations.
965         //! The first is a deref of `x` to create a pointer `p` that points
966         //! at the first element in the array. The second operation is
967         //! an index which adds `y*sizeof(T)` to `p` to obtain the
968         //! pointer to `x[y]`. `cat_index` will produce a resulting
969         //! cmt containing both this deref and the indexing,
970         //! presuming that `base_cmt` is not of fixed-length type.
971         //!
972         //! # Parameters
973         //! - `elt`: the AST node being indexed
974         //! - `base_cmt`: the cmt of `elt`
975
976         let method_call = ty::MethodCall::expr(elt.id());
977         let method_ty = self.typer.node_method_ty(method_call);
978
979         let element_ty = match method_ty {
980             Some(method_ty) => {
981                 let ref_ty = self.overloaded_method_return_ty(method_ty);
982                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
983
984                 // FIXME(#20649) -- why are we using the `self_ty` as the element type...?
985                 let self_ty = method_ty.fn_sig().input(0);
986                 self.tcx().no_late_bound_regions(&self_ty).unwrap()
987             }
988             None => {
989                 match base_cmt.ty.builtin_index() {
990                     Some(ty) => ty,
991                     None => {
992                         return Err(());
993                     }
994                 }
995             }
996         };
997
998         let m = base_cmt.mutbl.inherit();
999         let ret = interior(elt, base_cmt.clone(), base_cmt.ty,
1000                            m, context, element_ty);
1001         debug!("cat_index ret {:?}", ret);
1002         return Ok(ret);
1003
1004         fn interior<'tcx, N: ast_node>(elt: &N,
1005                                        of_cmt: cmt<'tcx>,
1006                                        vec_ty: Ty<'tcx>,
1007                                        mutbl: MutabilityCategory,
1008                                        context: InteriorOffsetKind,
1009                                        element_ty: Ty<'tcx>) -> cmt<'tcx>
1010         {
1011             let interior_elem = InteriorElement(context, element_kind(vec_ty));
1012             Rc::new(cmt_ {
1013                 id:elt.id(),
1014                 span:elt.span(),
1015                 cat:Categorization::Interior(of_cmt, interior_elem),
1016                 mutbl:mutbl,
1017                 ty:element_ty,
1018                 note: NoteNone
1019             })
1020         }
1021     }
1022
1023     // Takes either a vec or a reference to a vec and returns the cmt for the
1024     // underlying vec.
1025     fn deref_vec<N:ast_node>(&self,
1026                              elt: &N,
1027                              base_cmt: cmt<'tcx>,
1028                              context: InteriorOffsetKind)
1029                              -> McResult<cmt<'tcx>>
1030     {
1031         let ret = match try!(deref_kind(base_cmt.ty, Some(context))) {
1032             deref_ptr(ptr) => {
1033                 // for unique ptrs, we inherit mutability from the
1034                 // owning reference.
1035                 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
1036
1037                 // the deref is explicit in the resulting cmt
1038                 Rc::new(cmt_ {
1039                     id:elt.id(),
1040                     span:elt.span(),
1041                     cat:Categorization::Deref(base_cmt.clone(), 0, ptr),
1042                     mutbl:m,
1043                     ty: match base_cmt.ty.builtin_deref(false, ty::NoPreference) {
1044                         Some(mt) => mt.ty,
1045                         None => self.tcx().sess.bug("Found non-derefable type")
1046                     },
1047                     note: NoteNone
1048                 })
1049             }
1050
1051             deref_interior(_) => {
1052                 base_cmt
1053             }
1054         };
1055         debug!("deref_vec ret {:?}", ret);
1056         Ok(ret)
1057     }
1058
1059     /// Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is the cmt for `P`, `slice_pat` is
1060     /// the pattern `Q`, returns:
1061     ///
1062     /// * a cmt for `Q`
1063     /// * the mutability and region of the slice `Q`
1064     ///
1065     /// These last two bits of info happen to be things that borrowck needs.
1066     pub fn cat_slice_pattern(&self,
1067                              vec_cmt: cmt<'tcx>,
1068                              slice_pat: &hir::Pat)
1069                              -> McResult<(cmt<'tcx>, hir::Mutability, ty::Region)> {
1070         let slice_ty = try!(self.node_ty(slice_pat.id));
1071         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
1072                                                     slice_pat,
1073                                                     slice_ty);
1074         let context = InteriorOffsetKind::Pattern;
1075         let cmt_vec = try!(self.deref_vec(slice_pat, vec_cmt, context));
1076         let cmt_slice = try!(self.cat_index(slice_pat, cmt_vec, context));
1077         return Ok((cmt_slice, slice_mutbl, slice_r));
1078
1079         /// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
1080         /// ..ref c], then the type of `ref c` will be `&&[]`, so to extract the slice details we
1081         /// have to recurse through rptrs.
1082         fn vec_slice_info(tcx: &ty::ctxt,
1083                           pat: &hir::Pat,
1084                           slice_ty: Ty)
1085                           -> (hir::Mutability, ty::Region) {
1086             match slice_ty.sty {
1087                 ty::TyRef(r, ref mt) => match mt.ty.sty {
1088                     ty::TySlice(_) => (mt.mutbl, *r),
1089                     _ => vec_slice_info(tcx, pat, mt.ty),
1090                 },
1091
1092                 _ => {
1093                     tcx.sess.span_bug(pat.span,
1094                                       "type of slice pattern is not a slice");
1095                 }
1096             }
1097         }
1098     }
1099
1100     pub fn cat_imm_interior<N:ast_node>(&self,
1101                                         node: &N,
1102                                         base_cmt: cmt<'tcx>,
1103                                         interior_ty: Ty<'tcx>,
1104                                         interior: InteriorKind)
1105                                         -> cmt<'tcx> {
1106         let ret = Rc::new(cmt_ {
1107             id: node.id(),
1108             span: node.span(),
1109             mutbl: base_cmt.mutbl.inherit(),
1110             cat: Categorization::Interior(base_cmt, interior),
1111             ty: interior_ty,
1112             note: NoteNone
1113         });
1114         debug!("cat_imm_interior ret={:?}", ret);
1115         ret
1116     }
1117
1118     pub fn cat_downcast<N:ast_node>(&self,
1119                                     node: &N,
1120                                     base_cmt: cmt<'tcx>,
1121                                     downcast_ty: Ty<'tcx>,
1122                                     variant_did: DefId)
1123                                     -> cmt<'tcx> {
1124         let ret = Rc::new(cmt_ {
1125             id: node.id(),
1126             span: node.span(),
1127             mutbl: base_cmt.mutbl.inherit(),
1128             cat: Categorization::Downcast(base_cmt, variant_did),
1129             ty: downcast_ty,
1130             note: NoteNone
1131         });
1132         debug!("cat_downcast ret={:?}", ret);
1133         ret
1134     }
1135
1136     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1137         where F: FnMut(&MemCategorizationContext<'t, 'a, 'tcx>, cmt<'tcx>, &hir::Pat),
1138     {
1139         self.cat_pattern_(cmt, pat, &mut op)
1140     }
1141
1142     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1143     fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F)
1144                        -> McResult<()>
1145         where F : FnMut(&MemCategorizationContext<'t, 'a, 'tcx>, cmt<'tcx>, &hir::Pat),
1146     {
1147         // Here, `cmt` is the categorization for the value being
1148         // matched and pat is the pattern it is being matched against.
1149         //
1150         // In general, the way that this works is that we walk down
1151         // the pattern, constructing a cmt that represents the path
1152         // that will be taken to reach the value being matched.
1153         //
1154         // When we encounter named bindings, we take the cmt that has
1155         // been built up and pass it off to guarantee_valid() so that
1156         // we can be sure that the binding will remain valid for the
1157         // duration of the arm.
1158         //
1159         // (*2) There is subtlety concerning the correspondence between
1160         // pattern ids and types as compared to *expression* ids and
1161         // types. This is explained briefly. on the definition of the
1162         // type `cmt`, so go off and read what it says there, then
1163         // come back and I'll dive into a bit more detail here. :) OK,
1164         // back?
1165         //
1166         // In general, the id of the cmt should be the node that
1167         // "produces" the value---patterns aren't executable code
1168         // exactly, but I consider them to "execute" when they match a
1169         // value, and I consider them to produce the value that was
1170         // matched. So if you have something like:
1171         //
1172         //     let x = @@3;
1173         //     match x {
1174         //       @@y { ... }
1175         //     }
1176         //
1177         // In this case, the cmt and the relevant ids would be:
1178         //
1179         //     CMT             Id                  Type of Id Type of cmt
1180         //
1181         //     local(x)->@->@
1182         //     ^~~~~~~^        `x` from discr      @@int      @@int
1183         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1184         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1185         //
1186         // You can see that the types of the id and the cmt are in
1187         // sync in the first line, because that id is actually the id
1188         // of an expression. But once we get to pattern ids, the types
1189         // step out of sync again. So you'll see below that we always
1190         // get the type of the *subpattern* and use that.
1191
1192         debug!("cat_pattern: {:?} cmt={:?}",
1193                pat,
1194                cmt);
1195
1196         (*op)(self, cmt.clone(), pat);
1197
1198         let opt_def = if let Some(path_res) = self.tcx().def_map.borrow().get(&pat.id) {
1199             if path_res.depth != 0 {
1200                 // Since patterns can be associated constants
1201                 // which are resolved during typeck, we might have
1202                 // some unresolved patterns reaching this stage
1203                 // without aborting
1204                 return Err(());
1205             }
1206             Some(path_res.full_def())
1207         } else {
1208             None
1209         };
1210
1211         // Note: This goes up here (rather than within the PatEnum arm
1212         // alone) because struct patterns can refer to struct types or
1213         // to struct variants within enums.
1214         let cmt = match opt_def {
1215             Some(def::DefVariant(enum_did, variant_did, _))
1216                 // univariant enums do not need downcasts
1217                 if !self.tcx().lookup_adt_def(enum_did).is_univariant() => {
1218                     self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1219                 }
1220             _ => cmt
1221         };
1222
1223         match pat.node {
1224           hir::PatWild => {
1225             // _
1226           }
1227
1228           hir::PatEnum(_, None) => {
1229             // variant(..)
1230           }
1231           hir::PatEnum(_, Some(ref subpats)) => {
1232             match opt_def {
1233                 Some(def::DefVariant(..)) => {
1234                     // variant(x, y, z)
1235                     for (i, subpat) in subpats.iter().enumerate() {
1236                         let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1237
1238                         let subcmt =
1239                             self.cat_imm_interior(
1240                                 pat, cmt.clone(), subpat_ty,
1241                                 InteriorField(PositionalField(i)));
1242
1243                         try!(self.cat_pattern_(subcmt, &**subpat, op));
1244                     }
1245                 }
1246                 Some(def::DefStruct(..)) => {
1247                     for (i, subpat) in subpats.iter().enumerate() {
1248                         let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1249                         let cmt_field =
1250                             self.cat_imm_interior(
1251                                 pat, cmt.clone(), subpat_ty,
1252                                 InteriorField(PositionalField(i)));
1253                         try!(self.cat_pattern_(cmt_field, &**subpat, op));
1254                     }
1255                 }
1256                 Some(def::DefConst(..)) | Some(def::DefAssociatedConst(..)) => {
1257                     for subpat in subpats {
1258                         try!(self.cat_pattern_(cmt.clone(), &**subpat, op));
1259                     }
1260                 }
1261                 _ => {
1262                     self.tcx().sess.span_bug(
1263                         pat.span,
1264                         "enum pattern didn't resolve to enum or struct");
1265                 }
1266             }
1267           }
1268
1269           hir::PatQPath(..) => {
1270               // Lone constant: ignore
1271           }
1272
1273           hir::PatIdent(_, _, Some(ref subpat)) => {
1274               try!(self.cat_pattern_(cmt, &**subpat, op));
1275           }
1276
1277           hir::PatIdent(_, _, None) => {
1278               // nullary variant or identifier: ignore
1279           }
1280
1281           hir::PatStruct(_, ref field_pats, _) => {
1282             // {f1: p1, ..., fN: pN}
1283             for fp in field_pats {
1284                 let field_ty = try!(self.pat_ty(&*fp.node.pat)); // see (*2)
1285                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1286                 try!(self.cat_pattern_(cmt_field, &*fp.node.pat, op));
1287             }
1288           }
1289
1290           hir::PatTup(ref subpats) => {
1291             // (p1, ..., pN)
1292             for (i, subpat) in subpats.iter().enumerate() {
1293                 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1294                 let subcmt =
1295                     self.cat_imm_interior(
1296                         pat, cmt.clone(), subpat_ty,
1297                         InteriorField(PositionalField(i)));
1298                 try!(self.cat_pattern_(subcmt, &**subpat, op));
1299             }
1300           }
1301
1302           hir::PatBox(ref subpat) | hir::PatRegion(ref subpat, _) => {
1303             // box p1, &p1, &mut p1.  we can ignore the mutability of
1304             // PatRegion since that information is already contained
1305             // in the type.
1306             let subcmt = try!(self.cat_deref(pat, cmt, 0, None));
1307               try!(self.cat_pattern_(subcmt, &**subpat, op));
1308           }
1309
1310           hir::PatVec(ref before, ref slice, ref after) => {
1311               let context = InteriorOffsetKind::Pattern;
1312               let vec_cmt = try!(self.deref_vec(pat, cmt, context));
1313               let elt_cmt = try!(self.cat_index(pat, vec_cmt, context));
1314               for before_pat in before {
1315                   try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op));
1316               }
1317               if let Some(ref slice_pat) = *slice {
1318                   let slice_ty = try!(self.pat_ty(&**slice_pat));
1319                   let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1320                   try!(self.cat_pattern_(slice_cmt, &**slice_pat, op));
1321               }
1322               for after_pat in after {
1323                   try!(self.cat_pattern_(elt_cmt.clone(), &**after_pat, op));
1324               }
1325           }
1326
1327           hir::PatLit(_) | hir::PatRange(_, _) => {
1328               /*always ok*/
1329           }
1330         }
1331
1332         Ok(())
1333     }
1334
1335     fn overloaded_method_return_ty(&self,
1336                                    method_ty: Ty<'tcx>)
1337                                    -> Ty<'tcx>
1338     {
1339         // When we process an overloaded `*` or `[]` etc, we often
1340         // need to extract the return type of the method. These method
1341         // types are generated by method resolution and always have
1342         // all late-bound regions fully instantiated, so we just want
1343         // to skip past the binder.
1344         self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1345            .unwrap()
1346            .unwrap() // overloaded ops do not diverge, either
1347     }
1348 }
1349
1350 #[derive(Clone, Debug)]
1351 pub enum Aliasability {
1352     FreelyAliasable(AliasableReason),
1353     NonAliasable,
1354     ImmutableUnique(Box<Aliasability>),
1355 }
1356
1357 #[derive(Copy, Clone, Debug)]
1358 pub enum AliasableReason {
1359     AliasableBorrowed,
1360     AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1361     AliasableOther,
1362     UnaliasableImmutable, // Created as needed upon seeing ImmutableUnique
1363     AliasableStatic,
1364     AliasableStaticMut,
1365 }
1366
1367 impl<'tcx> cmt_<'tcx> {
1368     pub fn guarantor(&self) -> cmt<'tcx> {
1369         //! Returns `self` after stripping away any derefs or
1370         //! interior content. The return value is basically the `cmt` which
1371         //! determines how long the value in `self` remains live.
1372
1373         match self.cat {
1374             Categorization::Rvalue(..) |
1375             Categorization::StaticItem |
1376             Categorization::Local(..) |
1377             Categorization::Deref(_, _, UnsafePtr(..)) |
1378             Categorization::Deref(_, _, BorrowedPtr(..)) |
1379             Categorization::Deref(_, _, Implicit(..)) |
1380             Categorization::Upvar(..) => {
1381                 Rc::new((*self).clone())
1382             }
1383             Categorization::Downcast(ref b, _) |
1384             Categorization::Interior(ref b, _) |
1385             Categorization::Deref(ref b, _, Unique) => {
1386                 b.guarantor()
1387             }
1388         }
1389     }
1390
1391     /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1392     pub fn freely_aliasable(&self, ctxt: &ty::ctxt<'tcx>)
1393                             -> Aliasability {
1394         // Maybe non-obvious: copied upvars can only be considered
1395         // non-aliasable in once closures, since any other kind can be
1396         // aliased and eventually recused.
1397
1398         match self.cat {
1399             Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1400             Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1401             Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1402             Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1403             Categorization::Downcast(ref b, _) |
1404             Categorization::Interior(ref b, _) => {
1405                 // Aliasability depends on base cmt
1406                 b.freely_aliasable(ctxt)
1407             }
1408
1409             Categorization::Deref(ref b, _, Unique) => {
1410                 let sub = b.freely_aliasable(ctxt);
1411                 if b.mutbl.is_mutable() {
1412                     // Aliasability depends on base cmt alone
1413                     sub
1414                 } else {
1415                     // Do not allow mutation through an immutable box.
1416                     ImmutableUnique(Box::new(sub))
1417                 }
1418             }
1419
1420             Categorization::Rvalue(..) |
1421             Categorization::Local(..) |
1422             Categorization::Upvar(..) |
1423             Categorization::Deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1424                 NonAliasable
1425             }
1426
1427             Categorization::StaticItem => {
1428                 if self.mutbl.is_mutable() {
1429                     FreelyAliasable(AliasableStaticMut)
1430                 } else {
1431                     FreelyAliasable(AliasableStatic)
1432                 }
1433             }
1434
1435             Categorization::Deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1436             Categorization::Deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1437                 match base.cat {
1438                     Categorization::Upvar(Upvar{ id, .. }) =>
1439                         FreelyAliasable(AliasableClosure(id.closure_expr_id)),
1440                     _ => FreelyAliasable(AliasableBorrowed)
1441                 }
1442             }
1443         }
1444     }
1445
1446     // Digs down through one or two layers of deref and grabs the cmt
1447     // for the upvar if a note indicates there is one.
1448     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1449         match self.note {
1450             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1451                 Some(match self.cat {
1452                     Categorization::Deref(ref inner, _, _) => {
1453                         match inner.cat {
1454                             Categorization::Deref(ref inner, _, _) => inner.clone(),
1455                             Categorization::Upvar(..) => inner.clone(),
1456                             _ => unreachable!()
1457                         }
1458                     }
1459                     _ => unreachable!()
1460                 })
1461             }
1462             NoteNone => None
1463         }
1464     }
1465
1466
1467     pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String {
1468         match self.cat {
1469             Categorization::StaticItem => {
1470                 "static item".to_string()
1471             }
1472             Categorization::Rvalue(..) => {
1473                 "non-lvalue".to_string()
1474             }
1475             Categorization::Local(vid) => {
1476                 if tcx.map.is_argument(vid) {
1477                     "argument".to_string()
1478                 } else {
1479                     "local variable".to_string()
1480                 }
1481             }
1482             Categorization::Deref(_, _, pk) => {
1483                 let upvar = self.upvar();
1484                 match upvar.as_ref().map(|i| &i.cat) {
1485                     Some(&Categorization::Upvar(ref var)) => {
1486                         var.to_string()
1487                     }
1488                     Some(_) => unreachable!(),
1489                     None => {
1490                         match pk {
1491                             Implicit(..) => {
1492                                 format!("indexed content")
1493                             }
1494                             Unique => {
1495                                 format!("`Box` content")
1496                             }
1497                             UnsafePtr(..) => {
1498                                 format!("dereference of raw pointer")
1499                             }
1500                             BorrowedPtr(..) => {
1501                                 format!("borrowed content")
1502                             }
1503                         }
1504                     }
1505                 }
1506             }
1507             Categorization::Interior(_, InteriorField(NamedField(_))) => {
1508                 "field".to_string()
1509             }
1510             Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1511                 "anonymous field".to_string()
1512             }
1513             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1514                                                         VecElement)) |
1515             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1516                                                         OtherElement)) => {
1517                 "indexed content".to_string()
1518             }
1519             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1520                                                         VecElement)) |
1521             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1522                                                         OtherElement)) => {
1523                 "pattern-bound indexed content".to_string()
1524             }
1525             Categorization::Upvar(ref var) => {
1526                 var.to_string()
1527             }
1528             Categorization::Downcast(ref cmt, _) => {
1529                 cmt.descriptive_string(tcx)
1530             }
1531         }
1532     }
1533 }
1534
1535 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1536     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1537         write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1538                self.cat,
1539                self.id,
1540                self.mutbl,
1541                self.ty)
1542     }
1543 }
1544
1545 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1546     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1547         match *self {
1548             Categorization::StaticItem => write!(f, "static"),
1549             Categorization::Rvalue(r) => write!(f, "rvalue({:?})", r),
1550             Categorization::Local(id) => {
1551                let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1552                write!(f, "local({})", name)
1553             }
1554             Categorization::Upvar(upvar) => {
1555                 write!(f, "upvar({:?})", upvar)
1556             }
1557             Categorization::Deref(ref cmt, derefs, ptr) => {
1558                 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1559             }
1560             Categorization::Interior(ref cmt, interior) => {
1561                 write!(f, "{:?}.{:?}", cmt.cat, interior)
1562             }
1563             Categorization::Downcast(ref cmt, _) => {
1564                 write!(f, "{:?}->(enum)", cmt.cat)
1565             }
1566         }
1567     }
1568 }
1569
1570 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1571     match ptr {
1572         Unique => "Box",
1573         BorrowedPtr(ty::ImmBorrow, _) |
1574         Implicit(ty::ImmBorrow, _) => "&",
1575         BorrowedPtr(ty::MutBorrow, _) |
1576         Implicit(ty::MutBorrow, _) => "&mut",
1577         BorrowedPtr(ty::UniqueImmBorrow, _) |
1578         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1579         UnsafePtr(_) => "*",
1580     }
1581 }
1582
1583 impl fmt::Debug for PointerKind {
1584     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1585         match *self {
1586             Unique => write!(f, "Box"),
1587             BorrowedPtr(ty::ImmBorrow, ref r) |
1588             Implicit(ty::ImmBorrow, ref r) => {
1589                 write!(f, "&{:?}", r)
1590             }
1591             BorrowedPtr(ty::MutBorrow, ref r) |
1592             Implicit(ty::MutBorrow, ref r) => {
1593                 write!(f, "&{:?} mut", r)
1594             }
1595             BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1596             Implicit(ty::UniqueImmBorrow, ref r) => {
1597                 write!(f, "&{:?} uniq", r)
1598             }
1599             UnsafePtr(_) => write!(f, "*")
1600         }
1601     }
1602 }
1603
1604 impl fmt::Debug for InteriorKind {
1605     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1606         match *self {
1607             InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1608             InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1609             InteriorElement(..) => write!(f, "[]"),
1610         }
1611     }
1612 }
1613
1614 fn element_kind(t: Ty) -> ElementKind {
1615     match t.sty {
1616         ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
1617         ty::TyBox(ty) => match ty.sty {
1618             ty::TySlice(_) => VecElement,
1619             _ => OtherElement
1620         },
1621         ty::TyArray(..) | ty::TySlice(_) => VecElement,
1622         _ => OtherElement
1623     }
1624 }
1625
1626 impl fmt::Debug for Upvar {
1627     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1628         write!(f, "{:?}/{:?}", self.id, self.kind)
1629     }
1630 }
1631
1632 impl fmt::Display for Upvar {
1633     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1634         let kind = match self.kind {
1635             ty::FnClosureKind => "Fn",
1636             ty::FnMutClosureKind => "FnMut",
1637             ty::FnOnceClosureKind => "FnOnce",
1638         };
1639         write!(f, "captured outer variable in an `{}` closure", kind)
1640     }
1641 }