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