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