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