]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
Merge pull request #20510 from tshepang/patch-6
[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::InteriorSafety::*;
69 pub use self::AliasableReason::*;
70 pub use self::Note::*;
71 pub use self::deref_kind::*;
72 pub use self::categorization::*;
73
74 use middle::def;
75 use middle::region;
76 use middle::ty::{self, Ty};
77 use util::nodemap::{NodeMap};
78 use util::ppaux::{Repr};
79
80 use syntax::ast::{MutImmutable, MutMutable};
81 use syntax::ast;
82 use syntax::ast_map;
83 use syntax::codemap::Span;
84 use syntax::print::pprust;
85 use syntax::parse::token;
86
87 use std::cell::RefCell;
88 use std::rc::Rc;
89
90 #[derive(Clone, PartialEq, Show)]
91 pub enum categorization<'tcx> {
92     cat_rvalue(ty::Region),                    // temporary val, argument is its scope
93     cat_static_item,
94     cat_upvar(Upvar),                          // upvar referenced by closure env
95     cat_local(ast::NodeId),                    // local variable
96     cat_deref(cmt<'tcx>, uint, PointerKind),   // deref of a ptr
97     cat_interior(cmt<'tcx>, InteriorKind),     // something interior: field, tuple, etc
98     cat_downcast(cmt<'tcx>, ast::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, Show)]
105 pub struct Upvar {
106     pub id: ty::UpvarId,
107     // Unboxed closure kinds are used even for old-style closures for simplicity
108     pub kind: ty::UnboxedClosureKind,
109     // Is this from an unboxed closure?  Used only for diagnostics.
110     pub is_unboxed: bool
111 }
112
113 // different kinds of pointers:
114 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
115 pub enum PointerKind {
116     Unique,
117     BorrowedPtr(ty::BorrowKind, ty::Region),
118     Implicit(ty::BorrowKind, ty::Region),     // Implicit deref of a borrowed ptr.
119     UnsafePtr(ast::Mutability)
120 }
121
122 // We use the term "interior" to mean "something reachable from the
123 // base without a pointer dereference", e.g. a field
124 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
125 pub enum InteriorKind {
126     InteriorField(FieldName),
127     InteriorElement(ElementKind),
128 }
129
130 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
131 pub enum FieldName {
132     NamedField(ast::Name),
133     PositionalField(uint)
134 }
135
136 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
137 pub enum ElementKind {
138     VecElement,
139     OtherElement,
140 }
141
142 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
143 pub enum MutabilityCategory {
144     McImmutable, // Immutable.
145     McDeclared,  // Directly declared as mutable.
146     McInherited, // Inherited from the fact that owner is mutable.
147 }
148
149 // A note about the provenance of a `cmt`.  This is used for
150 // special-case handling of upvars such as mutability inference.
151 // Upvar categorization can generate a variable number of nested
152 // derefs.  The note allows detecting them without deep pattern
153 // matching on the categorization.
154 #[derive(Clone, Copy, PartialEq, Show)]
155 pub enum Note {
156     NoteClosureEnv(ty::UpvarId), // Deref through closure env
157     NoteUpvarRef(ty::UpvarId),   // Deref through by-ref upvar
158     NoteNone                     // Nothing special
159 }
160
161 // `cmt`: "Category, Mutability, and Type".
162 //
163 // a complete categorization of a value indicating where it originated
164 // and how it is located, as well as the mutability of the memory in
165 // which the value is stored.
166 //
167 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
168 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
169 // always the `id` of the node producing the type; in an expression
170 // like `*x`, the type of this deref node is the deref'd type (`T`),
171 // but in a pattern like `@x`, the `@x` pattern is again a
172 // dereference, but its type is the type *before* the dereference
173 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
174 // fashion. For more details, see the method `cat_pattern`
175 #[derive(Clone, PartialEq, Show)]
176 pub struct cmt_<'tcx> {
177     pub id: ast::NodeId,           // id of expr/pat producing this value
178     pub span: Span,                // span of same expr/pat
179     pub cat: categorization<'tcx>, // categorization of expr
180     pub mutbl: MutabilityCategory, // mutability of expr as lvalue
181     pub ty: Ty<'tcx>,              // type of the expr (*see WARNING above*)
182     pub note: Note,                // Note about the provenance of this cmt
183 }
184
185 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
186
187 // We pun on *T to mean both actual deref of a ptr as well
188 // as accessing of components:
189 #[derive(Copy)]
190 pub enum deref_kind {
191     deref_ptr(PointerKind),
192     deref_interior(InteriorKind),
193 }
194
195 // Categorizes a derefable type.  Note that we include vectors and strings as
196 // derefable (we model an index as the combination of a deref and then a
197 // pointer adjustment).
198 pub fn deref_kind(t: Ty) -> McResult<deref_kind> {
199     match t.sty {
200         ty::ty_uniq(_) |
201         ty::ty_closure(box ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
202             Ok(deref_ptr(Unique))
203         }
204
205         ty::ty_rptr(r, mt) => {
206             let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
207             Ok(deref_ptr(BorrowedPtr(kind, *r)))
208         }
209
210         ty::ty_closure(box ty::ClosureTy {
211                 store: ty::RegionTraitStore(r, _),
212                 ..
213             }) => {
214             Ok(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
215         }
216
217         ty::ty_ptr(ref mt) => {
218             Ok(deref_ptr(UnsafePtr(mt.mutbl)))
219         }
220
221         ty::ty_enum(..) |
222         ty::ty_struct(..) => { // newtype
223             Ok(deref_interior(InteriorField(PositionalField(0))))
224         }
225
226         ty::ty_vec(_, _) | ty::ty_str => {
227             Ok(deref_interior(InteriorElement(element_kind(t))))
228         }
229
230         _ => Err(()),
231     }
232 }
233
234 pub trait ast_node {
235     fn id(&self) -> ast::NodeId;
236     fn span(&self) -> Span;
237 }
238
239 impl ast_node for ast::Expr {
240     fn id(&self) -> ast::NodeId { self.id }
241     fn span(&self) -> Span { self.span }
242 }
243
244 impl ast_node for ast::Pat {
245     fn id(&self) -> ast::NodeId { self.id }
246     fn span(&self) -> Span { self.span }
247 }
248
249 pub struct MemCategorizationContext<'t,TYPER:'t> {
250     typer: &'t TYPER
251 }
252
253 impl<'t,TYPER:'t> Copy for MemCategorizationContext<'t,TYPER> {}
254
255 pub type McResult<T> = Result<T, ()>;
256
257 /// The `Typer` trait provides the interface for the mem-categorization
258 /// module to the results of the type check. It can be used to query
259 /// the type assigned to an expression node, to inquire after adjustments,
260 /// and so on.
261 ///
262 /// This interface is needed because mem-categorization is used from
263 /// two places: `regionck` and `borrowck`. `regionck` executes before
264 /// type inference is complete, and hence derives types and so on from
265 /// intermediate tables.  This also implies that type errors can occur,
266 /// and hence `node_ty()` and friends return a `Result` type -- any
267 /// error will propagate back up through the mem-categorization
268 /// routines.
269 ///
270 /// In the borrow checker, in contrast, type checking is complete and we
271 /// know that no errors have occurred, so we simply consult the tcx and we
272 /// can be sure that only `Ok` results will occur.
273 pub trait Typer<'tcx> : ty::UnboxedClosureTyper<'tcx> {
274     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
275     fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>>;
276     fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>>;
277     fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool;
278     fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>>;
279     fn node_method_origin(&self, method_call: ty::MethodCall)
280                           -> Option<ty::MethodOrigin<'tcx>>;
281     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>>;
282     fn is_method_call(&self, id: ast::NodeId) -> bool;
283     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent>;
284     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow>;
285     fn capture_mode(&self, closure_expr_id: ast::NodeId)
286                     -> ast::CaptureClause;
287 }
288
289 impl MutabilityCategory {
290     pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
291         match m {
292             MutImmutable => McImmutable,
293             MutMutable => McDeclared
294         }
295     }
296
297     pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
298         match borrow_kind {
299             ty::ImmBorrow => McImmutable,
300             ty::UniqueImmBorrow => McImmutable,
301             ty::MutBorrow => McDeclared,
302         }
303     }
304
305     pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
306                              ptr: PointerKind) -> MutabilityCategory {
307         match ptr {
308             Unique => {
309                 base_mutbl.inherit()
310             }
311             BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
312                 MutabilityCategory::from_borrow_kind(borrow_kind)
313             }
314             UnsafePtr(m) => {
315                 MutabilityCategory::from_mutbl(m)
316             }
317         }
318     }
319
320     fn from_local(tcx: &ty::ctxt, id: ast::NodeId) -> MutabilityCategory {
321         match tcx.map.get(id) {
322             ast_map::NodeLocal(p) | ast_map::NodeArg(p) => match p.node {
323                 ast::PatIdent(bind_mode, _, _) => {
324                     if bind_mode == ast::BindByValue(ast::MutMutable) {
325                         McDeclared
326                     } else {
327                         McImmutable
328                     }
329                 }
330                 _ => tcx.sess.span_bug(p.span, "expected identifier pattern")
331             },
332             _ => tcx.sess.span_bug(tcx.map.span(id), "expected identifier pattern")
333         }
334     }
335
336     pub fn inherit(&self) -> MutabilityCategory {
337         match *self {
338             McImmutable => McImmutable,
339             McDeclared => McInherited,
340             McInherited => McInherited,
341         }
342     }
343
344     pub fn is_mutable(&self) -> bool {
345         match *self {
346             McImmutable => false,
347             McInherited => true,
348             McDeclared => true,
349         }
350     }
351
352     pub fn is_immutable(&self) -> bool {
353         match *self {
354             McImmutable => true,
355             McDeclared | McInherited => false
356         }
357     }
358
359     pub fn to_user_str(&self) -> &'static str {
360         match *self {
361             McDeclared | McInherited => "mutable",
362             McImmutable => "immutable",
363         }
364     }
365 }
366
367 impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
368     pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
369         MemCategorizationContext { typer: typer }
370     }
371
372     fn tcx(&self) -> &'t ty::ctxt<'tcx> {
373         self.typer.tcx()
374     }
375
376     fn expr_ty(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
377         self.typer.node_ty(expr.id)
378     }
379
380     fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
381         let unadjusted_ty = try!(self.expr_ty(expr));
382         Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
383                          self.typer.adjustments().borrow().get(&expr.id),
384                          |method_call| self.typer.node_method_ty(method_call)))
385     }
386
387     fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
388         self.typer.node_ty(id)
389     }
390
391     fn pat_ty(&self, pat: &ast::Pat) -> McResult<Ty<'tcx>> {
392         let tcx = self.typer.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             ast::PatIdent(ast::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 ty::deref(base_ty, false) {
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.repr(tcx), base_ty.repr(tcx), ret_ty.repr(tcx));
412         Ok(ret_ty)
413     }
414
415     pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
416         match self.typer.adjustments().borrow().get(&expr.id) {
417             None => {
418                 // No adjustments.
419                 self.cat_expr_unadjusted(expr)
420             }
421
422             Some(adjustment) => {
423                 match *adjustment {
424                     ty::AdjustAddEnv(..) | ty::AdjustReifyFnPointer(..) => {
425                         debug!("cat_expr(AdjustAddEnv|AdjustReifyFnPointer): {}",
426                                expr.repr(self.tcx()));
427                         // Convert a bare fn to a closure by adding NULL env.
428                         // Result is an rvalue.
429                         let expr_ty = try!(self.expr_ty_adjusted(expr));
430                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
431                     }
432
433                     ty::AdjustDerefRef(
434                         ty::AutoDerefRef {
435                             autoref: Some(_), ..}) => {
436                         debug!("cat_expr(AdjustDerefRef): {}",
437                                expr.repr(self.tcx()));
438                         // Equivalent to &*expr or something similar.
439                         // Result is an rvalue.
440                         let expr_ty = try!(self.expr_ty_adjusted(expr));
441                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
442                     }
443
444                     ty::AdjustDerefRef(
445                         ty::AutoDerefRef {
446                             autoref: None, autoderefs}) => {
447                         // Equivalent to *expr or something similar.
448                         self.cat_expr_autoderefd(expr, autoderefs)
449                     }
450                 }
451             }
452         }
453     }
454
455     pub fn cat_expr_autoderefd(&self,
456                                expr: &ast::Expr,
457                                autoderefs: uint)
458                                -> McResult<cmt<'tcx>> {
459         let mut cmt = try!(self.cat_expr_unadjusted(expr));
460         debug!("cat_expr_autoderefd: autoderefs={}, cmt={}",
461                autoderefs,
462                cmt.repr(self.tcx()));
463         for deref in range(1u, autoderefs + 1) {
464             cmt = try!(self.cat_deref(expr, cmt, deref, false));
465         }
466         return Ok(cmt);
467     }
468
469     pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
470         debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
471
472         let expr_ty = try!(self.expr_ty(expr));
473         match expr.node {
474           ast::ExprUnary(ast::UnDeref, ref e_base) => {
475             let base_cmt = try!(self.cat_expr(&**e_base));
476             self.cat_deref(expr, base_cmt, 0, false)
477           }
478
479           ast::ExprField(ref base, f_name) => {
480             let base_cmt = try!(self.cat_expr(&**base));
481             debug!("cat_expr(cat_field): id={} expr={} base={}",
482                    expr.id,
483                    expr.repr(self.tcx()),
484                    base_cmt.repr(self.tcx()));
485             Ok(self.cat_field(expr, base_cmt, f_name.node.name, expr_ty))
486           }
487
488           ast::ExprTupField(ref base, idx) => {
489             let base_cmt = try!(self.cat_expr(&**base));
490             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
491           }
492
493           ast::ExprIndex(ref base, ref idx) => {
494             match idx.node {
495                 ast::ExprRange(..) => {
496                     // Slicing syntax special case (KILLME).
497                     Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
498                 }
499                 _ => {
500                     let method_call = ty::MethodCall::expr(expr.id());
501                     match self.typer.node_method_ty(method_call) {
502                         Some(method_ty) => {
503                             // If this is an index implemented by a method call, then it will
504                             // include an implicit deref of the result.
505                             let ret_ty = ty::ty_fn_ret(method_ty).unwrap();
506                             self.cat_deref(expr,
507                                            self.cat_rvalue_node(expr.id(),
508                                                                 expr.span(),
509                                                                 ret_ty), 1, true)
510                         }
511                         None => {
512                             self.cat_index(expr, try!(self.cat_expr(&**base)))
513                         }
514                     }
515                 }
516             }
517           }
518
519           ast::ExprPath(_) => {
520             let def = (*self.tcx().def_map.borrow())[expr.id];
521             self.cat_def(expr.id, expr.span, expr_ty, def)
522           }
523
524           ast::ExprParen(ref e) => {
525             self.cat_expr(&**e)
526           }
527
528           ast::ExprAddrOf(..) | ast::ExprCall(..) |
529           ast::ExprAssign(..) | ast::ExprAssignOp(..) |
530           ast::ExprClosure(..) | ast::ExprRet(..) |
531           ast::ExprUnary(..) | ast::ExprRange(..) |
532           ast::ExprMethodCall(..) | ast::ExprCast(..) |
533           ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
534           ast::ExprBinary(..) | ast::ExprWhile(..) |
535           ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
536           ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
537           ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
538           ast::ExprInlineAsm(..) | ast::ExprBox(..) |
539           ast::ExprForLoop(..) => {
540             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
541           }
542
543           ast::ExprIfLet(..) => {
544             self.tcx().sess.span_bug(expr.span, "non-desugared ExprIfLet");
545           }
546           ast::ExprWhileLet(..) => {
547             self.tcx().sess.span_bug(expr.span, "non-desugared ExprWhileLet");
548           }
549         }
550     }
551
552     pub fn cat_def(&self,
553                    id: ast::NodeId,
554                    span: Span,
555                    expr_ty: Ty<'tcx>,
556                    def: def::Def)
557                    -> McResult<cmt<'tcx>> {
558         debug!("cat_def: id={} expr={} def={}",
559                id, expr_ty.repr(self.tcx()), def);
560
561         match def {
562           def::DefStruct(..) | def::DefVariant(..) | def::DefConst(..) |
563           def::DefFn(..) | def::DefStaticMethod(..) |  def::DefMethod(..) => {
564                 Ok(self.cat_rvalue_node(id, span, expr_ty))
565           }
566           def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
567           def::DefTrait(_) | def::DefTy(..) | def::DefPrimTy(_) |
568           def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
569           def::DefLabel(_) | def::DefSelfTy(..) |
570           def::DefAssociatedTy(..) | def::DefAssociatedPath(..)=> {
571               Ok(Rc::new(cmt_ {
572                   id:id,
573                   span:span,
574                   cat:cat_static_item,
575                   mutbl: McImmutable,
576                   ty:expr_ty,
577                   note: NoteNone
578               }))
579           }
580
581           def::DefStatic(_, mutbl) => {
582               Ok(Rc::new(cmt_ {
583                   id:id,
584                   span:span,
585                   cat:cat_static_item,
586                   mutbl: if mutbl { McDeclared } else { McImmutable},
587                   ty:expr_ty,
588                   note: NoteNone
589               }))
590           }
591
592           def::DefUpvar(var_id, fn_node_id, _) => {
593               let ty = try!(self.node_ty(fn_node_id));
594               match ty.sty {
595                   ty::ty_closure(ref closure_ty) => {
596                       // Translate old closure type info into unboxed
597                       // closure kind/capture mode
598                       let (mode, kind) = match (closure_ty.store, closure_ty.onceness) {
599                           // stack closure
600                           (ty::RegionTraitStore(..), ast::Many) => {
601                               (ast::CaptureByRef, ty::FnMutUnboxedClosureKind)
602                           }
603                           // proc or once closure
604                           (_, ast::Once) => {
605                               (ast::CaptureByValue, ty::FnOnceUnboxedClosureKind)
606                           }
607                           // There should be no such old closure type
608                           (ty::UniqTraitStore, ast::Many) => {
609                               self.tcx().sess.span_bug(span, "Impossible closure type");
610                           }
611                       };
612                       self.cat_upvar(id, span, var_id, fn_node_id, kind, mode, false)
613                   }
614                   ty::ty_unboxed_closure(closure_id, _, _) => {
615                       let kind = self.typer.unboxed_closure_kind(closure_id);
616                       let mode = self.typer.capture_mode(fn_node_id);
617                       self.cat_upvar(id, span, var_id, fn_node_id, kind, mode, true)
618                   }
619                   _ => {
620                       self.tcx().sess.span_bug(
621                           span,
622                           format!("Upvar of non-closure {} - {}",
623                                   fn_node_id,
624                                   ty.repr(self.tcx()))[]);
625                   }
626               }
627           }
628
629           def::DefLocal(vid) => {
630             Ok(Rc::new(cmt_ {
631                 id: id,
632                 span: span,
633                 cat: cat_local(vid),
634                 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
635                 ty: expr_ty,
636                 note: NoteNone
637             }))
638           }
639         }
640     }
641
642     // Categorize an upvar, complete with invisible derefs of closure
643     // environment and upvar reference as appropriate.
644     fn cat_upvar(&self,
645                  id: ast::NodeId,
646                  span: Span,
647                  var_id: ast::NodeId,
648                  fn_node_id: ast::NodeId,
649                  kind: ty::UnboxedClosureKind,
650                  mode: ast::CaptureClause,
651                  is_unboxed: bool)
652                  -> McResult<cmt<'tcx>> {
653         // An upvar can have up to 3 components.  The base is a
654         // `cat_upvar`.  Next, we add a deref through the implicit
655         // environment pointer with an anonymous free region 'env and
656         // appropriate borrow kind for closure kinds that take self by
657         // reference.  Finally, if the upvar was captured
658         // by-reference, we add a deref through that reference.  The
659         // region of this reference is an inference variable 'up that
660         // was previously generated and recorded in the upvar borrow
661         // map.  The borrow kind bk is inferred by based on how the
662         // upvar is used.
663         //
664         // This results in the following table for concrete closure
665         // types:
666         //
667         //                | move                 | ref
668         // ---------------+----------------------+-------------------------------
669         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
670         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
671         // FnOnce         | copied               | upvar -> &'up bk
672         // old stack      | N/A                  | upvar -> &'env mut -> &'up bk
673         // old proc/once  | copied               | N/A
674         let var_ty = try!(self.node_ty(var_id));
675
676         let upvar_id = ty::UpvarId { var_id: var_id,
677                                      closure_expr_id: fn_node_id };
678
679         // Mutability of original variable itself
680         let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
681
682         // Construct information about env pointer dereference, if any
683         let mutbl = match kind {
684             ty::FnOnceUnboxedClosureKind => None, // None, env is by-value
685             ty::FnMutUnboxedClosureKind => match mode { // Depends on capture type
686                 ast::CaptureByValue => Some(var_mutbl), // Mutable if the original var is
687                 ast::CaptureByRef => Some(McDeclared) // Mutable regardless
688             },
689             ty::FnUnboxedClosureKind => Some(McImmutable) // Never mutable
690         };
691         let env_info = mutbl.map(|env_mutbl| {
692             // Look up the node ID of the closure body so we can construct
693             // a free region within it
694             let fn_body_id = {
695                 let fn_expr = match self.tcx().map.find(fn_node_id) {
696                     Some(ast_map::NodeExpr(e)) => e,
697                     _ => unreachable!()
698                 };
699
700                 match fn_expr.node {
701                     ast::ExprClosure(_, _, _, ref body) => body.id,
702                     _ => unreachable!()
703                 }
704             };
705
706             // Region of environment pointer
707             let env_region = ty::ReFree(ty::FreeRegion {
708                 scope: region::CodeExtent::from_node_id(fn_body_id),
709                 bound_region: ty::BrEnv
710             });
711
712             let env_ptr = BorrowedPtr(if env_mutbl.is_mutable() {
713                 ty::MutBorrow
714             } else {
715                 ty::ImmBorrow
716             }, env_region);
717
718             (env_mutbl, env_ptr)
719         });
720
721         // First, switch by capture mode
722         Ok(match mode {
723             ast::CaptureByValue => {
724                 let mut base = cmt_ {
725                     id: id,
726                     span: span,
727                     cat: cat_upvar(Upvar {
728                         id: upvar_id,
729                         kind: kind,
730                         is_unboxed: is_unboxed
731                     }),
732                     mutbl: var_mutbl,
733                     ty: var_ty,
734                     note: NoteNone
735                 };
736
737                 match env_info {
738                     Some((env_mutbl, env_ptr)) => {
739                         // We need to add the env deref.  This means
740                         // that the above is actually immutable and
741                         // has a ref type.  However, nothing should
742                         // actually look at the type, so we can get
743                         // away with stuffing a `ty_err` in there
744                         // instead of bothering to construct a proper
745                         // one.
746                         base.mutbl = McImmutable;
747                         base.ty = self.tcx().types.err;
748                         Rc::new(cmt_ {
749                             id: id,
750                             span: span,
751                             cat: cat_deref(Rc::new(base), 0, env_ptr),
752                             mutbl: env_mutbl,
753                             ty: var_ty,
754                             note: NoteClosureEnv(upvar_id)
755                         })
756                     }
757                     None => Rc::new(base)
758                 }
759             },
760             ast::CaptureByRef => {
761                 // The type here is actually a ref (or ref of a ref),
762                 // but we can again get away with not constructing one
763                 // properly since it will never be used.
764                 let mut base = cmt_ {
765                     id: id,
766                     span: span,
767                     cat: cat_upvar(Upvar {
768                         id: upvar_id,
769                         kind: kind,
770                         is_unboxed: is_unboxed
771                     }),
772                     mutbl: McImmutable,
773                     ty: self.tcx().types.err,
774                     note: NoteNone
775                 };
776
777                 match env_info {
778                     Some((env_mutbl, env_ptr)) => {
779                         base = cmt_ {
780                             id: id,
781                             span: span,
782                             cat: cat_deref(Rc::new(base), 0, env_ptr),
783                             mutbl: env_mutbl,
784                             ty: self.tcx().types.err,
785                             note: NoteClosureEnv(upvar_id)
786                         };
787                     }
788                     None => {}
789                 }
790
791                 // Look up upvar borrow so we can get its region
792                 let upvar_borrow = self.typer.upvar_borrow(upvar_id).unwrap();
793                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
794
795                 Rc::new(cmt_ {
796                     id: id,
797                     span: span,
798                     cat: cat_deref(Rc::new(base), 0, ptr),
799                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
800                     ty: var_ty,
801                     note: NoteUpvarRef(upvar_id)
802                 })
803             }
804         })
805     }
806
807     pub fn cat_rvalue_node(&self,
808                            id: ast::NodeId,
809                            span: Span,
810                            expr_ty: Ty<'tcx>)
811                            -> cmt<'tcx> {
812         match self.typer.temporary_scope(id) {
813             Some(scope) => {
814                 match expr_ty.sty {
815                     ty::ty_vec(_, Some(0)) => self.cat_rvalue(id, span, ty::ReStatic, expr_ty),
816                     _ => self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
817                 }
818             }
819             None => {
820                 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
821             }
822         }
823     }
824
825     pub fn cat_rvalue(&self,
826                       cmt_id: ast::NodeId,
827                       span: Span,
828                       temp_scope: ty::Region,
829                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
830         Rc::new(cmt_ {
831             id:cmt_id,
832             span:span,
833             cat:cat_rvalue(temp_scope),
834             mutbl:McDeclared,
835             ty:expr_ty,
836             note: NoteNone
837         })
838     }
839
840     pub fn cat_field<N:ast_node>(&self,
841                                  node: &N,
842                                  base_cmt: cmt<'tcx>,
843                                  f_name: ast::Name,
844                                  f_ty: Ty<'tcx>)
845                                  -> cmt<'tcx> {
846         Rc::new(cmt_ {
847             id: node.id(),
848             span: node.span(),
849             mutbl: base_cmt.mutbl.inherit(),
850             cat: cat_interior(base_cmt, InteriorField(NamedField(f_name))),
851             ty: f_ty,
852             note: NoteNone
853         })
854     }
855
856     pub fn cat_tup_field<N:ast_node>(&self,
857                                      node: &N,
858                                      base_cmt: cmt<'tcx>,
859                                      f_idx: uint,
860                                      f_ty: Ty<'tcx>)
861                                      -> cmt<'tcx> {
862         Rc::new(cmt_ {
863             id: node.id(),
864             span: node.span(),
865             mutbl: base_cmt.mutbl.inherit(),
866             cat: cat_interior(base_cmt, InteriorField(PositionalField(f_idx))),
867             ty: f_ty,
868             note: NoteNone
869         })
870     }
871
872     fn cat_deref<N:ast_node>(&self,
873                              node: &N,
874                              base_cmt: cmt<'tcx>,
875                              deref_cnt: uint,
876                              implicit: bool)
877                              -> McResult<cmt<'tcx>> {
878         let adjustment = match self.typer.adjustments().borrow().get(&node.id()) {
879             Some(adj) if ty::adjust_is_object(adj) => ty::AutoObject,
880             _ if deref_cnt != 0 => ty::AutoDeref(deref_cnt),
881             _ => ty::NoAdjustment
882         };
883
884         let method_call = ty::MethodCall {
885             expr_id: node.id(),
886             adjustment: adjustment
887         };
888         let method_ty = self.typer.node_method_ty(method_call);
889
890         debug!("cat_deref: method_call={} method_ty={}",
891                method_call, method_ty.map(|ty| ty.repr(self.tcx())));
892
893         let base_cmt = match method_ty {
894             Some(method_ty) => {
895                 let ref_ty = ty::ty_fn_ret(method_ty).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 ty::deref(base_cmt_ty, true) {
902             Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, implicit),
903             None => {
904                 debug!("Explicit deref of non-derefable type: {}",
905                        base_cmt_ty.repr(self.tcx()));
906                 return Err(());
907             }
908         }
909     }
910
911     fn cat_deref_common<N:ast_node>(&self,
912                                     node: &N,
913                                     base_cmt: cmt<'tcx>,
914                                     deref_cnt: uint,
915                                     deref_ty: Ty<'tcx>,
916                                     implicit: bool)
917                                     -> McResult<cmt<'tcx>>
918     {
919         let (m, cat) = match try!(deref_kind(base_cmt.ty)) {
920             deref_ptr(ptr) => {
921                 let ptr = if implicit {
922                     match ptr {
923                         BorrowedPtr(bk, r) => Implicit(bk, r),
924                         _ => self.tcx().sess.span_bug(node.span(),
925                             "Implicit deref of non-borrowed pointer")
926                     }
927                 } else {
928                     ptr
929                 };
930                 // for unique ptrs, we inherit mutability from the
931                 // owning reference.
932                 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
933                  cat_deref(base_cmt, deref_cnt, ptr))
934             }
935             deref_interior(interior) => {
936                 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
937             }
938         };
939         Ok(Rc::new(cmt_ {
940             id: node.id(),
941             span: node.span(),
942             cat: cat,
943             mutbl: m,
944             ty: deref_ty,
945             note: NoteNone
946         }))
947     }
948
949     pub fn cat_index<N:ast_node>(&self,
950                                  elt: &N,
951                                  mut base_cmt: cmt<'tcx>)
952                                  -> McResult<cmt<'tcx>> {
953         //! Creates a cmt for an indexing operation (`[]`).
954         //!
955         //! One subtle aspect of indexing that may not be
956         //! immediately obvious: for anything other than a fixed-length
957         //! vector, an operation like `x[y]` actually consists of two
958         //! disjoint (from the point of view of borrowck) operations.
959         //! The first is a deref of `x` to create a pointer `p` that points
960         //! at the first element in the array. The second operation is
961         //! an index which adds `y*sizeof(T)` to `p` to obtain the
962         //! pointer to `x[y]`. `cat_index` will produce a resulting
963         //! cmt containing both this deref and the indexing,
964         //! presuming that `base_cmt` is not of fixed-length type.
965         //!
966         //! # Parameters
967         //! - `elt`: the AST node being indexed
968         //! - `base_cmt`: the cmt of `elt`
969
970         let method_call = ty::MethodCall::expr(elt.id());
971         let method_ty = self.typer.node_method_ty(method_call);
972
973         let element_ty = match method_ty {
974             Some(method_ty) => {
975                 let ref_ty = ty::ty_fn_ret(method_ty).unwrap();
976                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
977                 ty::ty_fn_args(method_ty)[0]
978             }
979             None => {
980                 match ty::array_element_ty(self.tcx(), base_cmt.ty) {
981                     Some(ty) => ty,
982                     None => {
983                         return Err(());
984                     }
985                 }
986             }
987         };
988
989         let m = base_cmt.mutbl.inherit();
990         return Ok(interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty));
991
992         fn interior<'tcx, N: ast_node>(elt: &N,
993                                        of_cmt: cmt<'tcx>,
994                                        vec_ty: Ty<'tcx>,
995                                        mutbl: MutabilityCategory,
996                                        element_ty: Ty<'tcx>) -> cmt<'tcx>
997         {
998             Rc::new(cmt_ {
999                 id:elt.id(),
1000                 span:elt.span(),
1001                 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
1002                 mutbl:mutbl,
1003                 ty:element_ty,
1004                 note: NoteNone
1005             })
1006         }
1007     }
1008
1009     // Takes either a vec or a reference to a vec and returns the cmt for the
1010     // underlying vec.
1011     fn deref_vec<N:ast_node>(&self,
1012                              elt: &N,
1013                              base_cmt: cmt<'tcx>)
1014                              -> McResult<cmt<'tcx>>
1015     {
1016         match try!(deref_kind(base_cmt.ty)) {
1017             deref_ptr(ptr) => {
1018                 // for unique ptrs, we inherit mutability from the
1019                 // owning reference.
1020                 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
1021
1022                 // the deref is explicit in the resulting cmt
1023                 Ok(Rc::new(cmt_ {
1024                     id:elt.id(),
1025                     span:elt.span(),
1026                     cat:cat_deref(base_cmt.clone(), 0, ptr),
1027                     mutbl:m,
1028                     ty: match ty::deref(base_cmt.ty, false) {
1029                         Some(mt) => mt.ty,
1030                         None => self.tcx().sess.bug("Found non-derefable type")
1031                     },
1032                     note: NoteNone
1033                 }))
1034             }
1035
1036             deref_interior(_) => {
1037                 Ok(base_cmt)
1038             }
1039         }
1040     }
1041
1042     /// Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is the cmt for `P`, `slice_pat` is
1043     /// the pattern `Q`, returns:
1044     ///
1045     /// * a cmt for `Q`
1046     /// * the mutability and region of the slice `Q`
1047     ///
1048     /// These last two bits of info happen to be things that borrowck needs.
1049     pub fn cat_slice_pattern(&self,
1050                              vec_cmt: cmt<'tcx>,
1051                              slice_pat: &ast::Pat)
1052                              -> McResult<(cmt<'tcx>, ast::Mutability, ty::Region)> {
1053         let slice_ty = try!(self.node_ty(slice_pat.id));
1054         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
1055                                                     slice_pat,
1056                                                     slice_ty);
1057         let cmt_slice = try!(self.cat_index(slice_pat, try!(self.deref_vec(slice_pat, vec_cmt))));
1058         return Ok((cmt_slice, slice_mutbl, slice_r));
1059
1060         /// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
1061         /// ..ref c], then the type of `ref c` will be `&&[]`, so to extract the slice details we
1062         /// have to recurse through rptrs.
1063         fn vec_slice_info(tcx: &ty::ctxt,
1064                           pat: &ast::Pat,
1065                           slice_ty: Ty)
1066                           -> (ast::Mutability, ty::Region) {
1067             match slice_ty.sty {
1068                 ty::ty_rptr(r, ref mt) => match mt.ty.sty {
1069                     ty::ty_vec(_, None) => (mt.mutbl, *r),
1070                     _ => vec_slice_info(tcx, pat, mt.ty),
1071                 },
1072
1073                 _ => {
1074                     tcx.sess.span_bug(pat.span,
1075                                       "type of slice pattern is not a slice");
1076                 }
1077             }
1078         }
1079     }
1080
1081     pub fn cat_imm_interior<N:ast_node>(&self,
1082                                         node: &N,
1083                                         base_cmt: cmt<'tcx>,
1084                                         interior_ty: Ty<'tcx>,
1085                                         interior: InteriorKind)
1086                                         -> cmt<'tcx> {
1087         Rc::new(cmt_ {
1088             id: node.id(),
1089             span: node.span(),
1090             mutbl: base_cmt.mutbl.inherit(),
1091             cat: cat_interior(base_cmt, interior),
1092             ty: interior_ty,
1093             note: NoteNone
1094         })
1095     }
1096
1097     pub fn cat_downcast<N:ast_node>(&self,
1098                                     node: &N,
1099                                     base_cmt: cmt<'tcx>,
1100                                     downcast_ty: Ty<'tcx>,
1101                                     variant_did: ast::DefId)
1102                                     -> cmt<'tcx> {
1103         Rc::new(cmt_ {
1104             id: node.id(),
1105             span: node.span(),
1106             mutbl: base_cmt.mutbl.inherit(),
1107             cat: cat_downcast(base_cmt, variant_did),
1108             ty: downcast_ty,
1109             note: NoteNone
1110         })
1111     }
1112
1113     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, mut op: F) -> McResult<()>
1114         where F: FnMut(&MemCategorizationContext<'t, TYPER>, cmt<'tcx>, &ast::Pat),
1115     {
1116         self.cat_pattern_(cmt, pat, &mut op)
1117     }
1118
1119     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1120     fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, op: &mut F)
1121                        -> McResult<()>
1122         where F : FnMut(&MemCategorizationContext<'t, TYPER>, cmt<'tcx>, &ast::Pat),
1123     {
1124         // Here, `cmt` is the categorization for the value being
1125         // matched and pat is the pattern it is being matched against.
1126         //
1127         // In general, the way that this works is that we walk down
1128         // the pattern, constructing a cmt that represents the path
1129         // that will be taken to reach the value being matched.
1130         //
1131         // When we encounter named bindings, we take the cmt that has
1132         // been built up and pass it off to guarantee_valid() so that
1133         // we can be sure that the binding will remain valid for the
1134         // duration of the arm.
1135         //
1136         // (*2) There is subtlety concerning the correspondence between
1137         // pattern ids and types as compared to *expression* ids and
1138         // types. This is explained briefly. on the definition of the
1139         // type `cmt`, so go off and read what it says there, then
1140         // come back and I'll dive into a bit more detail here. :) OK,
1141         // back?
1142         //
1143         // In general, the id of the cmt should be the node that
1144         // "produces" the value---patterns aren't executable code
1145         // exactly, but I consider them to "execute" when they match a
1146         // value, and I consider them to produce the value that was
1147         // matched. So if you have something like:
1148         //
1149         //     let x = @@3;
1150         //     match x {
1151         //       @@y { ... }
1152         //     }
1153         //
1154         // In this case, the cmt and the relevant ids would be:
1155         //
1156         //     CMT             Id                  Type of Id Type of cmt
1157         //
1158         //     local(x)->@->@
1159         //     ^~~~~~~^        `x` from discr      @@int      @@int
1160         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1161         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1162         //
1163         // You can see that the types of the id and the cmt are in
1164         // sync in the first line, because that id is actually the id
1165         // of an expression. But once we get to pattern ids, the types
1166         // step out of sync again. So you'll see below that we always
1167         // get the type of the *subpattern* and use that.
1168
1169         debug!("cat_pattern: id={} pat={} cmt={}",
1170                pat.id, pprust::pat_to_string(pat),
1171                cmt.repr(self.tcx()));
1172
1173         (*op)(self, cmt.clone(), pat);
1174
1175         let def_map = self.tcx().def_map.borrow();
1176         let opt_def = def_map.get(&pat.id);
1177
1178         // Note: This goes up here (rather than within the PatEnum arm
1179         // alone) because struct patterns can refer to struct types or
1180         // to struct variants within enums.
1181         let cmt = match opt_def {
1182             Some(&def::DefVariant(enum_did, variant_did, _))
1183                 // univariant enums do not need downcasts
1184                 if !ty::enum_is_univariant(self.tcx(), enum_did) => {
1185                     self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1186                 }
1187             _ => cmt
1188         };
1189
1190         match pat.node {
1191           ast::PatWild(_) => {
1192             // _
1193           }
1194
1195           ast::PatEnum(_, None) => {
1196             // variant(..)
1197           }
1198           ast::PatEnum(_, Some(ref subpats)) => {
1199             match opt_def {
1200                 Some(&def::DefVariant(..)) => {
1201                     // variant(x, y, z)
1202                     for (i, subpat) in subpats.iter().enumerate() {
1203                         let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1204
1205                         let subcmt =
1206                             self.cat_imm_interior(
1207                                 pat, cmt.clone(), subpat_ty,
1208                                 InteriorField(PositionalField(i)));
1209
1210                         try!(self.cat_pattern_(subcmt, &**subpat, op));
1211                     }
1212                 }
1213                 Some(&def::DefStruct(..)) => {
1214                     for (i, subpat) in subpats.iter().enumerate() {
1215                         let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1216                         let cmt_field =
1217                             self.cat_imm_interior(
1218                                 pat, cmt.clone(), subpat_ty,
1219                                 InteriorField(PositionalField(i)));
1220                         try!(self.cat_pattern_(cmt_field, &**subpat, op));
1221                     }
1222                 }
1223                 Some(&def::DefConst(..)) => {
1224                     for subpat in subpats.iter() {
1225                         try!(self.cat_pattern_(cmt.clone(), &**subpat, op));
1226                     }
1227                 }
1228                 _ => {
1229                     self.tcx().sess.span_bug(
1230                         pat.span,
1231                         "enum pattern didn't resolve to enum or struct");
1232                 }
1233             }
1234           }
1235
1236           ast::PatIdent(_, _, Some(ref subpat)) => {
1237               try!(self.cat_pattern_(cmt, &**subpat, op));
1238           }
1239
1240           ast::PatIdent(_, _, None) => {
1241               // nullary variant or identifier: ignore
1242           }
1243
1244           ast::PatStruct(_, ref field_pats, _) => {
1245             // {f1: p1, ..., fN: pN}
1246             for fp in field_pats.iter() {
1247                 let field_ty = try!(self.pat_ty(&*fp.node.pat)); // see (*2)
1248                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.ident.name, field_ty);
1249                 try!(self.cat_pattern_(cmt_field, &*fp.node.pat, op));
1250             }
1251           }
1252
1253           ast::PatTup(ref subpats) => {
1254             // (p1, ..., pN)
1255             for (i, subpat) in subpats.iter().enumerate() {
1256                 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1257                 let subcmt =
1258                     self.cat_imm_interior(
1259                         pat, cmt.clone(), subpat_ty,
1260                         InteriorField(PositionalField(i)));
1261                 try!(self.cat_pattern_(subcmt, &**subpat, op));
1262             }
1263           }
1264
1265           ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
1266             // @p1, ~p1, ref p1
1267             let subcmt = try!(self.cat_deref(pat, cmt, 0, false));
1268               try!(self.cat_pattern_(subcmt, &**subpat, op));
1269           }
1270
1271           ast::PatVec(ref before, ref slice, ref after) => {
1272               let elt_cmt = try!(self.cat_index(pat, try!(self.deref_vec(pat, cmt))));
1273               for before_pat in before.iter() {
1274                   try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op));
1275               }
1276               for slice_pat in slice.iter() {
1277                   let slice_ty = try!(self.pat_ty(&**slice_pat));
1278                   let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1279                   try!(self.cat_pattern_(slice_cmt, &**slice_pat, op));
1280               }
1281               for after_pat in after.iter() {
1282                   try!(self.cat_pattern_(elt_cmt.clone(), &**after_pat, op));
1283               }
1284           }
1285
1286           ast::PatLit(_) | ast::PatRange(_, _) => {
1287               /*always ok*/
1288           }
1289
1290           ast::PatMac(_) => {
1291               self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1292           }
1293         }
1294
1295         Ok(())
1296     }
1297 }
1298
1299 #[derive(Copy)]
1300 pub enum InteriorSafety {
1301     InteriorUnsafe,
1302     InteriorSafe
1303 }
1304
1305 #[derive(Copy)]
1306 pub enum AliasableReason {
1307     AliasableBorrowed,
1308     AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1309     AliasableOther,
1310     AliasableStatic(InteriorSafety),
1311     AliasableStaticMut(InteriorSafety),
1312 }
1313
1314 impl<'tcx> cmt_<'tcx> {
1315     pub fn guarantor(&self) -> cmt<'tcx> {
1316         //! Returns `self` after stripping away any owned pointer derefs or
1317         //! interior content. The return value is basically the `cmt` which
1318         //! determines how long the value in `self` remains live.
1319
1320         match self.cat {
1321             cat_rvalue(..) |
1322             cat_static_item |
1323             cat_local(..) |
1324             cat_deref(_, _, UnsafePtr(..)) |
1325             cat_deref(_, _, BorrowedPtr(..)) |
1326             cat_deref(_, _, Implicit(..)) |
1327             cat_upvar(..) => {
1328                 Rc::new((*self).clone())
1329             }
1330             cat_downcast(ref b, _) |
1331             cat_interior(ref b, _) |
1332             cat_deref(ref b, _, Unique) => {
1333                 b.guarantor()
1334             }
1335         }
1336     }
1337
1338     /// Returns `Some(_)` if this lvalue represents a freely aliasable pointer type.
1339     pub fn freely_aliasable(&self, ctxt: &ty::ctxt<'tcx>)
1340                             -> Option<AliasableReason> {
1341         // Maybe non-obvious: copied upvars can only be considered
1342         // non-aliasable in once closures, since any other kind can be
1343         // aliased and eventually recused.
1344
1345         match self.cat {
1346             cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1347             cat_deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1348             cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1349             cat_deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1350             cat_downcast(ref b, _) |
1351             cat_deref(ref b, _, Unique) |
1352             cat_interior(ref b, _) => {
1353                 // Aliasability depends on base cmt
1354                 b.freely_aliasable(ctxt)
1355             }
1356
1357             cat_rvalue(..) |
1358             cat_local(..) |
1359             cat_upvar(..) |
1360             cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1361                 None
1362             }
1363
1364             cat_static_item(..) => {
1365                 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1366                     InteriorUnsafe
1367                 } else {
1368                     InteriorSafe
1369                 };
1370
1371                 if self.mutbl.is_mutable() {
1372                     Some(AliasableStaticMut(int_safe))
1373                 } else {
1374                     Some(AliasableStatic(int_safe))
1375                 }
1376             }
1377
1378             cat_deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1379             cat_deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1380                 match base.cat {
1381                     cat_upvar(Upvar{ id, .. }) => Some(AliasableClosure(id.closure_expr_id)),
1382                     _ => Some(AliasableBorrowed)
1383                 }
1384             }
1385         }
1386     }
1387
1388     // Digs down through one or two layers of deref and grabs the cmt
1389     // for the upvar if a note indicates there is one.
1390     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1391         match self.note {
1392             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1393                 Some(match self.cat {
1394                     cat_deref(ref inner, _, _) => {
1395                         match inner.cat {
1396                             cat_deref(ref inner, _, _) => inner.clone(),
1397                             cat_upvar(..) => inner.clone(),
1398                             _ => unreachable!()
1399                         }
1400                     }
1401                     _ => unreachable!()
1402                 })
1403             }
1404             NoteNone => None
1405         }
1406     }
1407
1408
1409     pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String {
1410         fn upvar_to_string(upvar: &Upvar, is_copy: bool) -> String {
1411             if upvar.is_unboxed {
1412                 let kind = match upvar.kind {
1413                     ty::FnUnboxedClosureKind => "Fn",
1414                     ty::FnMutUnboxedClosureKind => "FnMut",
1415                     ty::FnOnceUnboxedClosureKind => "FnOnce"
1416                 };
1417                 format!("captured outer variable in an `{}` closure", kind)
1418             } else {
1419                 (match (upvar.kind, is_copy) {
1420                     (ty::FnOnceUnboxedClosureKind, true) => "captured outer variable in a proc",
1421                     _ => "captured outer variable"
1422                 }).to_string()
1423             }
1424         }
1425
1426         match self.cat {
1427             cat_static_item => {
1428                 "static item".to_string()
1429             }
1430             cat_rvalue(..) => {
1431                 "non-lvalue".to_string()
1432             }
1433             cat_local(vid) => {
1434                 match tcx.map.find(vid) {
1435                     Some(ast_map::NodeArg(_)) => {
1436                         "argument".to_string()
1437                     }
1438                     _ => "local variable".to_string()
1439                 }
1440             }
1441             cat_deref(_, _, pk) => {
1442                 let upvar = self.upvar();
1443                 match upvar.as_ref().map(|i| &i.cat) {
1444                     Some(&cat_upvar(ref var)) => {
1445                         upvar_to_string(var, false)
1446                     }
1447                     Some(_) => unreachable!(),
1448                     None => {
1449                         match pk {
1450                             Implicit(..) => {
1451                                 "dereference (dereference is implicit, due to indexing)".to_string()
1452                             }
1453                             Unique => format!("dereference of `{}`", ptr_sigil(pk)),
1454                             _ => format!("dereference of `{}`-pointer", ptr_sigil(pk))
1455                         }
1456                     }
1457                 }
1458             }
1459             cat_interior(_, InteriorField(NamedField(_))) => {
1460                 "field".to_string()
1461             }
1462             cat_interior(_, InteriorField(PositionalField(_))) => {
1463                 "anonymous field".to_string()
1464             }
1465             cat_interior(_, InteriorElement(VecElement)) => {
1466                 "vec content".to_string()
1467             }
1468             cat_interior(_, InteriorElement(OtherElement)) => {
1469                 "indexed content".to_string()
1470             }
1471             cat_upvar(ref var) => {
1472                 upvar_to_string(var, true)
1473             }
1474             cat_downcast(ref cmt, _) => {
1475                 cmt.descriptive_string(tcx)
1476             }
1477         }
1478     }
1479 }
1480
1481 impl<'tcx> Repr<'tcx> for cmt_<'tcx> {
1482     fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1483         format!("{{{} id:{} m:{} ty:{}}}",
1484                 self.cat.repr(tcx),
1485                 self.id,
1486                 self.mutbl,
1487                 self.ty.repr(tcx))
1488     }
1489 }
1490
1491 impl<'tcx> Repr<'tcx> for categorization<'tcx> {
1492     fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1493         match *self {
1494             cat_static_item |
1495             cat_rvalue(..) |
1496             cat_local(..) |
1497             cat_upvar(..) => {
1498                 format!("{}", *self)
1499             }
1500             cat_deref(ref cmt, derefs, ptr) => {
1501                 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
1502             }
1503             cat_interior(ref cmt, interior) => {
1504                 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1505             }
1506             cat_downcast(ref cmt, _) => {
1507                 format!("{}->(enum)", cmt.cat.repr(tcx))
1508             }
1509         }
1510     }
1511 }
1512
1513 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1514     match ptr {
1515         Unique => "Box",
1516         BorrowedPtr(ty::ImmBorrow, _) |
1517         Implicit(ty::ImmBorrow, _) => "&",
1518         BorrowedPtr(ty::MutBorrow, _) |
1519         Implicit(ty::MutBorrow, _) => "&mut",
1520         BorrowedPtr(ty::UniqueImmBorrow, _) |
1521         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1522         UnsafePtr(_) => "*"
1523     }
1524 }
1525
1526 impl<'tcx> Repr<'tcx> for InteriorKind {
1527     fn repr(&self, _tcx: &ty::ctxt) -> String {
1528         match *self {
1529             InteriorField(NamedField(fld)) => {
1530                 token::get_name(fld).get().to_string()
1531             }
1532             InteriorField(PositionalField(i)) => format!("#{}", i),
1533             InteriorElement(_) => "[]".to_string(),
1534         }
1535     }
1536 }
1537
1538 fn element_kind(t: Ty) -> ElementKind {
1539     match t.sty {
1540         ty::ty_rptr(_, ty::mt{ty, ..}) |
1541         ty::ty_uniq(ty) => match ty.sty {
1542             ty::ty_vec(_, None) => VecElement,
1543             _ => OtherElement
1544         },
1545         ty::ty_vec(..) => VecElement,
1546         _ => OtherElement
1547     }
1548 }