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