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