]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
Auto merge of #31144 - jseyfried:remove_import_ordering_restriction, r=nrc
[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 `Categorization::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
72 use self::Aliasability::*;
73
74 use middle::def_id::DefId;
75 use front::map as ast_map;
76 use middle::infer;
77 use middle::const_qualif::ConstQualif;
78 use middle::def::Def;
79 use middle::ty::adjustment;
80 use middle::ty::{self, Ty};
81
82 use rustc_front::hir::{MutImmutable, MutMutable};
83 use rustc_front::hir;
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     Rvalue(ty::Region),                    // temporary val, argument is its scope
93     StaticItem,
94     Upvar(Upvar),                          // upvar referenced by closure env
95     Local(ast::NodeId),                    // local variable
96     Deref(cmt<'tcx>, usize, PointerKind),  // deref of a ptr
97     Interior(cmt<'tcx>, InteriorKind),     // something interior: field, tuple, etc
98     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(hir::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 hir::Expr {
249     fn id(&self) -> ast::NodeId { self.id }
250     fn span(&self) -> Span { self.span }
251 }
252
253 impl ast_node for hir::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: hir::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) => match p.node {
308                 hir::PatIdent(bind_mode, _, _) => {
309                     if bind_mode == hir::BindByValue(hir::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: &hir::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: &hir::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: &hir::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             hir::PatIdent(hir::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, ty::NoPreference) {
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: &hir::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                     adjustment::AdjustDerefRef(
425                         adjustment::AutoDerefRef {
426                             autoref: None, unsize: None, autoderefs, ..}) => {
427                         // Equivalent to *expr or something similar.
428                         self.cat_expr_autoderefd(expr, autoderefs)
429                     }
430
431                     adjustment::AdjustReifyFnPointer |
432                     adjustment::AdjustUnsafeFnPointer |
433                     adjustment::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: &hir::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: &hir::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           hir::ExprUnary(hir::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           hir::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, expr_ty))
477           }
478
479           hir::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           hir::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           hir::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           hir::ExprType(ref e, _) => {
522             self.cat_expr(&**e)
523           }
524
525           hir::ExprAddrOf(..) | hir::ExprCall(..) |
526           hir::ExprAssign(..) | hir::ExprAssignOp(..) |
527           hir::ExprClosure(..) | hir::ExprRet(..) |
528           hir::ExprUnary(..) | hir::ExprRange(..) |
529           hir::ExprMethodCall(..) | hir::ExprCast(..) |
530           hir::ExprVec(..) | hir::ExprTup(..) | hir::ExprIf(..) |
531           hir::ExprBinary(..) | hir::ExprWhile(..) |
532           hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
533           hir::ExprLit(..) | hir::ExprBreak(..) |
534           hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
535           hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
536             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
537           }
538         }
539     }
540
541     pub fn cat_def(&self,
542                    id: ast::NodeId,
543                    span: Span,
544                    expr_ty: Ty<'tcx>,
545                    def: Def)
546                    -> McResult<cmt<'tcx>> {
547         debug!("cat_def: id={} expr={:?} def={:?}",
548                id, expr_ty, def);
549
550         match def {
551           Def::Struct(..) | Def::Variant(..) | Def::Const(..) |
552           Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
553                 Ok(self.cat_rvalue_node(id, span, expr_ty))
554           }
555
556           Def::Mod(_) | Def::ForeignMod(_) |
557           Def::Trait(_) | Def::Enum(..) | Def::TyAlias(..) | Def::PrimTy(_) |
558           Def::TyParam(..) |
559           Def::Label(_) | Def::SelfTy(..) |
560           Def::AssociatedTy(..) => {
561               self.tcx().sess.span_bug(span, &format!("Unexpected definition in \
562                                                        memory categorization: {:?}", def));
563           }
564
565           Def::Static(_, mutbl) => {
566               Ok(Rc::new(cmt_ {
567                   id:id,
568                   span:span,
569                   cat:Categorization::StaticItem,
570                   mutbl: if mutbl { McDeclared } else { McImmutable},
571                   ty:expr_ty,
572                   note: NoteNone
573               }))
574           }
575
576           Def::Upvar(_, var_id, _, fn_node_id) => {
577               let ty = try!(self.node_ty(fn_node_id));
578               match ty.sty {
579                   ty::TyClosure(closure_id, _) => {
580                       match self.typer.closure_kind(closure_id) {
581                           Some(kind) => {
582                               self.cat_upvar(id, span, var_id, fn_node_id, kind)
583                           }
584                           None => {
585                               self.tcx().sess.span_bug(
586                                   span,
587                                   &*format!("No closure kind for {:?}", closure_id));
588                           }
589                       }
590                   }
591                   _ => {
592                       self.tcx().sess.span_bug(
593                           span,
594                           &format!("Upvar of non-closure {} - {:?}",
595                                   fn_node_id,
596                                   ty));
597                   }
598               }
599           }
600
601           Def::Local(_, vid) => {
602             Ok(Rc::new(cmt_ {
603                 id: id,
604                 span: span,
605                 cat: Categorization::Local(vid),
606                 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
607                 ty: expr_ty,
608                 note: NoteNone
609             }))
610           }
611
612           Def::Err => panic!("Def::Err in memory categorization")
613         }
614     }
615
616     // Categorize an upvar, complete with invisible derefs of closure
617     // environment and upvar reference as appropriate.
618     fn cat_upvar(&self,
619                  id: ast::NodeId,
620                  span: Span,
621                  var_id: ast::NodeId,
622                  fn_node_id: ast::NodeId,
623                  kind: ty::ClosureKind)
624                  -> McResult<cmt<'tcx>>
625     {
626         // An upvar can have up to 3 components. We translate first to a
627         // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
628         // field from the environment.
629         //
630         // `Categorization::Upvar`.  Next, we add a deref through the implicit
631         // environment pointer with an anonymous free region 'env and
632         // appropriate borrow kind for closure kinds that take self by
633         // reference.  Finally, if the upvar was captured
634         // by-reference, we add a deref through that reference.  The
635         // region of this reference is an inference variable 'up that
636         // was previously generated and recorded in the upvar borrow
637         // map.  The borrow kind bk is inferred by based on how the
638         // upvar is used.
639         //
640         // This results in the following table for concrete closure
641         // types:
642         //
643         //                | move                 | ref
644         // ---------------+----------------------+-------------------------------
645         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
646         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
647         // FnOnce         | copied               | upvar -> &'up bk
648
649         let upvar_id = ty::UpvarId { var_id: var_id,
650                                      closure_expr_id: fn_node_id };
651         let var_ty = try!(self.node_ty(var_id));
652
653         // Mutability of original variable itself
654         let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
655
656         // Construct the upvar. This represents access to the field
657         // from the environment (perhaps we should eventually desugar
658         // this field further, but it will do for now).
659         let cmt_result = cmt_ {
660             id: id,
661             span: span,
662             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
663             mutbl: var_mutbl,
664             ty: var_ty,
665             note: NoteNone
666         };
667
668         // If this is a `FnMut` or `Fn` closure, then the above is
669         // conceptually a `&mut` or `&` reference, so we have to add a
670         // deref.
671         let cmt_result = match kind {
672             ty::FnOnceClosureKind => {
673                 cmt_result
674             }
675             ty::FnMutClosureKind => {
676                 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
677             }
678             ty::FnClosureKind => {
679                 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
680             }
681         };
682
683         // If this is a by-ref capture, then the upvar we loaded is
684         // actually a reference, so we have to add an implicit deref
685         // for that.
686         let upvar_id = ty::UpvarId { var_id: var_id,
687                                      closure_expr_id: fn_node_id };
688         let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
689         let cmt_result = match upvar_capture {
690             ty::UpvarCapture::ByValue => {
691                 cmt_result
692             }
693             ty::UpvarCapture::ByRef(upvar_borrow) => {
694                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
695                 cmt_ {
696                     id: id,
697                     span: span,
698                     cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
699                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
700                     ty: var_ty,
701                     note: NoteUpvarRef(upvar_id)
702                 }
703             }
704         };
705
706         let ret = Rc::new(cmt_result);
707         debug!("cat_upvar ret={:?}", ret);
708         Ok(ret)
709     }
710
711     fn env_deref(&self,
712                  id: ast::NodeId,
713                  span: Span,
714                  upvar_id: ty::UpvarId,
715                  upvar_mutbl: MutabilityCategory,
716                  env_borrow_kind: ty::BorrowKind,
717                  cmt_result: cmt_<'tcx>)
718                  -> cmt_<'tcx>
719     {
720         // Look up the node ID of the closure body so we can construct
721         // a free region within it
722         let fn_body_id = {
723             let fn_expr = match self.tcx().map.find(upvar_id.closure_expr_id) {
724                 Some(ast_map::NodeExpr(e)) => e,
725                 _ => unreachable!()
726             };
727
728             match fn_expr.node {
729                 hir::ExprClosure(_, _, ref body) => body.id,
730                 _ => unreachable!()
731             }
732         };
733
734         // Region of environment pointer
735         let env_region = ty::ReFree(ty::FreeRegion {
736             // The environment of a closure is guaranteed to
737             // outlive any bindings introduced in the body of the
738             // closure itself.
739             scope: self.tcx().region_maps.item_extent(fn_body_id),
740             bound_region: ty::BrEnv
741         });
742
743         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
744
745         let var_ty = cmt_result.ty;
746
747         // We need to add the env deref.  This means
748         // that the above is actually immutable and
749         // has a ref type.  However, nothing should
750         // actually look at the type, so we can get
751         // away with stuffing a `TyError` in there
752         // instead of bothering to construct a proper
753         // one.
754         let cmt_result = cmt_ {
755             mutbl: McImmutable,
756             ty: self.tcx().types.err,
757             ..cmt_result
758         };
759
760         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
761
762         // Issue #18335. If variable is declared as immutable, override the
763         // mutability from the environment and substitute an `&T` anyway.
764         match upvar_mutbl {
765             McImmutable => { deref_mutbl = McImmutable; }
766             McDeclared | McInherited => { }
767         }
768
769         let ret = cmt_ {
770             id: id,
771             span: span,
772             cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
773             mutbl: deref_mutbl,
774             ty: var_ty,
775             note: NoteClosureEnv(upvar_id)
776         };
777
778         debug!("env_deref ret {:?}", ret);
779
780         ret
781     }
782
783     /// Returns the lifetime of a temporary created by expr with id `id`.
784     /// This could be `'static` if `id` is part of a constant expression.
785     pub fn temporary_scope(&self, id: ast::NodeId) -> ty::Region {
786         match self.typer.temporary_scope(id) {
787             Some(scope) => ty::ReScope(scope),
788             None => ty::ReStatic
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         let qualif = self.tcx().const_qualif_map.borrow().get(&id).cloned()
798                                .unwrap_or(ConstQualif::NOT_CONST);
799
800         // Only promote `[T; 0]` before an RFC for rvalue promotions
801         // is accepted.
802         let qualif = match expr_ty.sty {
803             ty::TyArray(_, 0) => qualif,
804             _ => ConstQualif::NOT_CONST
805         };
806
807         // Compute maximum lifetime of this rvalue. This is 'static if
808         // we can promote to a constant, otherwise equal to enclosing temp
809         // lifetime.
810         let re = if qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
811             self.temporary_scope(id)
812         } else {
813             ty::ReStatic
814         };
815         let ret = self.cat_rvalue(id, span, re, expr_ty);
816         debug!("cat_rvalue_node ret {:?}", ret);
817         ret
818     }
819
820     pub fn cat_rvalue(&self,
821                       cmt_id: ast::NodeId,
822                       span: Span,
823                       temp_scope: ty::Region,
824                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
825         let ret = Rc::new(cmt_ {
826             id:cmt_id,
827             span:span,
828             cat:Categorization::Rvalue(temp_scope),
829             mutbl:McDeclared,
830             ty:expr_ty,
831             note: NoteNone
832         });
833         debug!("cat_rvalue ret {:?}", ret);
834         ret
835     }
836
837     pub fn cat_field<N:ast_node>(&self,
838                                  node: &N,
839                                  base_cmt: cmt<'tcx>,
840                                  f_name: ast::Name,
841                                  f_ty: Ty<'tcx>)
842                                  -> cmt<'tcx> {
843         let ret = Rc::new(cmt_ {
844             id: node.id(),
845             span: node.span(),
846             mutbl: base_cmt.mutbl.inherit(),
847             cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
848             ty: f_ty,
849             note: NoteNone
850         });
851         debug!("cat_field ret {:?}", ret);
852         ret
853     }
854
855     pub fn cat_tup_field<N:ast_node>(&self,
856                                      node: &N,
857                                      base_cmt: cmt<'tcx>,
858                                      f_idx: usize,
859                                      f_ty: Ty<'tcx>)
860                                      -> cmt<'tcx> {
861         let ret = Rc::new(cmt_ {
862             id: node.id(),
863             span: node.span(),
864             mutbl: base_cmt.mutbl.inherit(),
865             cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
866             ty: f_ty,
867             note: NoteNone
868         });
869         debug!("cat_tup_field ret {:?}", ret);
870         ret
871     }
872
873     fn cat_deref<N:ast_node>(&self,
874                              node: &N,
875                              base_cmt: cmt<'tcx>,
876                              deref_cnt: usize,
877                              deref_context: DerefKindContext)
878                              -> McResult<cmt<'tcx>> {
879         let method_call = ty::MethodCall {
880             expr_id: node.id(),
881             autoderef: deref_cnt as u32
882         };
883         let method_ty = self.typer.node_method_ty(method_call);
884
885         debug!("cat_deref: method_call={:?} method_ty={:?}",
886                method_call, method_ty.map(|ty| ty));
887
888         let base_cmt = match method_ty {
889             Some(method_ty) => {
890                 let ref_ty =
891                     self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
892                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
893             }
894             None => base_cmt
895         };
896         let base_cmt_ty = base_cmt.ty;
897         match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
898             Some(mt) => {
899                 let ret = self.cat_deref_common(node, base_cmt, deref_cnt,
900                                               mt.ty,
901                                               deref_context,
902                                                 /* implicit: */ false);
903                 debug!("cat_deref ret {:?}", ret);
904                 ret
905             }
906             None => {
907                 debug!("Explicit deref of non-derefable type: {:?}",
908                        base_cmt_ty);
909                 return Err(());
910             }
911         }
912     }
913
914     fn cat_deref_common<N:ast_node>(&self,
915                                     node: &N,
916                                     base_cmt: cmt<'tcx>,
917                                     deref_cnt: usize,
918                                     deref_ty: Ty<'tcx>,
919                                     deref_context: DerefKindContext,
920                                     implicit: bool)
921                                     -> McResult<cmt<'tcx>>
922     {
923         let (m, cat) = match try!(deref_kind(base_cmt.ty, deref_context)) {
924             deref_ptr(ptr) => {
925                 let ptr = if implicit {
926                     match ptr {
927                         BorrowedPtr(bk, r) => Implicit(bk, r),
928                         _ => self.tcx().sess.span_bug(node.span(),
929                             "Implicit deref of non-borrowed pointer")
930                     }
931                 } else {
932                     ptr
933                 };
934                 // for unique ptrs, we inherit mutability from the
935                 // owning reference.
936                 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
937                  Categorization::Deref(base_cmt, deref_cnt, ptr))
938             }
939             deref_interior(interior) => {
940                 (base_cmt.mutbl.inherit(), Categorization::Interior(base_cmt, interior))
941             }
942         };
943         let ret = Rc::new(cmt_ {
944             id: node.id(),
945             span: node.span(),
946             cat: cat,
947             mutbl: m,
948             ty: deref_ty,
949             note: NoteNone
950         });
951         debug!("cat_deref_common ret {:?}", ret);
952         Ok(ret)
953     }
954
955     pub fn cat_index<N:ast_node>(&self,
956                                  elt: &N,
957                                  mut base_cmt: cmt<'tcx>,
958                                  context: InteriorOffsetKind)
959                                  -> McResult<cmt<'tcx>> {
960         //! Creates a cmt for an indexing operation (`[]`).
961         //!
962         //! One subtle aspect of indexing that may not be
963         //! immediately obvious: for anything other than a fixed-length
964         //! vector, an operation like `x[y]` actually consists of two
965         //! disjoint (from the point of view of borrowck) operations.
966         //! The first is a deref of `x` to create a pointer `p` that points
967         //! at the first element in the array. The second operation is
968         //! an index which adds `y*sizeof(T)` to `p` to obtain the
969         //! pointer to `x[y]`. `cat_index` will produce a resulting
970         //! cmt containing both this deref and the indexing,
971         //! presuming that `base_cmt` is not of fixed-length type.
972         //!
973         //! # Parameters
974         //! - `elt`: the AST node being indexed
975         //! - `base_cmt`: the cmt of `elt`
976
977         let method_call = ty::MethodCall::expr(elt.id());
978         let method_ty = self.typer.node_method_ty(method_call);
979
980         let element_ty = match method_ty {
981             Some(method_ty) => {
982                 let ref_ty = self.overloaded_method_return_ty(method_ty);
983                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
984
985                 // FIXME(#20649) -- why are we using the `self_ty` as the element type...?
986                 let self_ty = method_ty.fn_sig().input(0);
987                 self.tcx().no_late_bound_regions(&self_ty).unwrap()
988             }
989             None => {
990                 match base_cmt.ty.builtin_index() {
991                     Some(ty) => ty,
992                     None => {
993                         return Err(());
994                     }
995                 }
996             }
997         };
998
999         let m = base_cmt.mutbl.inherit();
1000         let ret = interior(elt, base_cmt.clone(), base_cmt.ty,
1001                            m, context, element_ty);
1002         debug!("cat_index ret {:?}", ret);
1003         return Ok(ret);
1004
1005         fn interior<'tcx, N: ast_node>(elt: &N,
1006                                        of_cmt: cmt<'tcx>,
1007                                        vec_ty: Ty<'tcx>,
1008                                        mutbl: MutabilityCategory,
1009                                        context: InteriorOffsetKind,
1010                                        element_ty: Ty<'tcx>) -> cmt<'tcx>
1011         {
1012             let interior_elem = InteriorElement(context, element_kind(vec_ty));
1013             Rc::new(cmt_ {
1014                 id:elt.id(),
1015                 span:elt.span(),
1016                 cat:Categorization::Interior(of_cmt, interior_elem),
1017                 mutbl:mutbl,
1018                 ty:element_ty,
1019                 note: NoteNone
1020             })
1021         }
1022     }
1023
1024     // Takes either a vec or a reference to a vec and returns the cmt for the
1025     // underlying vec.
1026     fn deref_vec<N:ast_node>(&self,
1027                              elt: &N,
1028                              base_cmt: cmt<'tcx>,
1029                              context: InteriorOffsetKind)
1030                              -> McResult<cmt<'tcx>>
1031     {
1032         let ret = match try!(deref_kind(base_cmt.ty, Some(context))) {
1033             deref_ptr(ptr) => {
1034                 // for unique ptrs, we inherit mutability from the
1035                 // owning reference.
1036                 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
1037
1038                 // the deref is explicit in the resulting cmt
1039                 Rc::new(cmt_ {
1040                     id:elt.id(),
1041                     span:elt.span(),
1042                     cat:Categorization::Deref(base_cmt.clone(), 0, ptr),
1043                     mutbl:m,
1044                     ty: match base_cmt.ty.builtin_deref(false, ty::NoPreference) {
1045                         Some(mt) => mt.ty,
1046                         None => self.tcx().sess.bug("Found non-derefable type")
1047                     },
1048                     note: NoteNone
1049                 })
1050             }
1051
1052             deref_interior(_) => {
1053                 base_cmt
1054             }
1055         };
1056         debug!("deref_vec ret {:?}", ret);
1057         Ok(ret)
1058     }
1059
1060     /// Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is the cmt for `P`, `slice_pat` is
1061     /// the pattern `Q`, returns:
1062     ///
1063     /// * a cmt for `Q`
1064     /// * the mutability and region of the slice `Q`
1065     ///
1066     /// These last two bits of info happen to be things that borrowck needs.
1067     pub fn cat_slice_pattern(&self,
1068                              vec_cmt: cmt<'tcx>,
1069                              slice_pat: &hir::Pat)
1070                              -> McResult<(cmt<'tcx>, hir::Mutability, ty::Region)> {
1071         let slice_ty = try!(self.node_ty(slice_pat.id));
1072         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
1073                                                     slice_pat,
1074                                                     slice_ty);
1075         let context = InteriorOffsetKind::Pattern;
1076         let cmt_vec = try!(self.deref_vec(slice_pat, vec_cmt, context));
1077         let cmt_slice = try!(self.cat_index(slice_pat, cmt_vec, context));
1078         return Ok((cmt_slice, slice_mutbl, slice_r));
1079
1080         /// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
1081         /// ..ref c], then the type of `ref c` will be `&&[]`, so to extract the slice details we
1082         /// have to recurse through rptrs.
1083         fn vec_slice_info(tcx: &ty::ctxt,
1084                           pat: &hir::Pat,
1085                           slice_ty: Ty)
1086                           -> (hir::Mutability, ty::Region) {
1087             match slice_ty.sty {
1088                 ty::TyRef(r, ref mt) => match mt.ty.sty {
1089                     ty::TySlice(_) => (mt.mutbl, *r),
1090                     _ => vec_slice_info(tcx, pat, mt.ty),
1091                 },
1092
1093                 _ => {
1094                     tcx.sess.span_bug(pat.span,
1095                                       "type of slice pattern is not a slice");
1096                 }
1097             }
1098         }
1099     }
1100
1101     pub fn cat_imm_interior<N:ast_node>(&self,
1102                                         node: &N,
1103                                         base_cmt: cmt<'tcx>,
1104                                         interior_ty: Ty<'tcx>,
1105                                         interior: InteriorKind)
1106                                         -> cmt<'tcx> {
1107         let ret = Rc::new(cmt_ {
1108             id: node.id(),
1109             span: node.span(),
1110             mutbl: base_cmt.mutbl.inherit(),
1111             cat: Categorization::Interior(base_cmt, interior),
1112             ty: interior_ty,
1113             note: NoteNone
1114         });
1115         debug!("cat_imm_interior ret={:?}", ret);
1116         ret
1117     }
1118
1119     pub fn cat_downcast<N:ast_node>(&self,
1120                                     node: &N,
1121                                     base_cmt: cmt<'tcx>,
1122                                     downcast_ty: Ty<'tcx>,
1123                                     variant_did: DefId)
1124                                     -> cmt<'tcx> {
1125         let ret = Rc::new(cmt_ {
1126             id: node.id(),
1127             span: node.span(),
1128             mutbl: base_cmt.mutbl.inherit(),
1129             cat: Categorization::Downcast(base_cmt, variant_did),
1130             ty: downcast_ty,
1131             note: NoteNone
1132         });
1133         debug!("cat_downcast ret={:?}", ret);
1134         ret
1135     }
1136
1137     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1138         where F: FnMut(&MemCategorizationContext<'t, 'a, 'tcx>, cmt<'tcx>, &hir::Pat),
1139     {
1140         self.cat_pattern_(cmt, pat, &mut op)
1141     }
1142
1143     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1144     fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F)
1145                        -> McResult<()>
1146         where F : FnMut(&MemCategorizationContext<'t, 'a, 'tcx>, cmt<'tcx>, &hir::Pat),
1147     {
1148         // Here, `cmt` is the categorization for the value being
1149         // matched and pat is the pattern it is being matched against.
1150         //
1151         // In general, the way that this works is that we walk down
1152         // the pattern, constructing a cmt that represents the path
1153         // that will be taken to reach the value being matched.
1154         //
1155         // When we encounter named bindings, we take the cmt that has
1156         // been built up and pass it off to guarantee_valid() so that
1157         // we can be sure that the binding will remain valid for the
1158         // duration of the arm.
1159         //
1160         // (*2) There is subtlety concerning the correspondence between
1161         // pattern ids and types as compared to *expression* ids and
1162         // types. This is explained briefly. on the definition of the
1163         // type `cmt`, so go off and read what it says there, then
1164         // come back and I'll dive into a bit more detail here. :) OK,
1165         // back?
1166         //
1167         // In general, the id of the cmt should be the node that
1168         // "produces" the value---patterns aren't executable code
1169         // exactly, but I consider them to "execute" when they match a
1170         // value, and I consider them to produce the value that was
1171         // matched. So if you have something like:
1172         //
1173         //     let x = @@3;
1174         //     match x {
1175         //       @@y { ... }
1176         //     }
1177         //
1178         // In this case, the cmt and the relevant ids would be:
1179         //
1180         //     CMT             Id                  Type of Id Type of cmt
1181         //
1182         //     local(x)->@->@
1183         //     ^~~~~~~^        `x` from discr      @@int      @@int
1184         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1185         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1186         //
1187         // You can see that the types of the id and the cmt are in
1188         // sync in the first line, because that id is actually the id
1189         // of an expression. But once we get to pattern ids, the types
1190         // step out of sync again. So you'll see below that we always
1191         // get the type of the *subpattern* and use that.
1192
1193         debug!("cat_pattern: {:?} cmt={:?}",
1194                pat,
1195                cmt);
1196
1197         (*op)(self, cmt.clone(), pat);
1198
1199         let opt_def = if let Some(path_res) = self.tcx().def_map.borrow().get(&pat.id) {
1200             if path_res.depth != 0 || path_res.base_def == Def::Err {
1201                 // Since patterns can be associated constants
1202                 // which are resolved during typeck, we might have
1203                 // some unresolved patterns reaching this stage
1204                 // without aborting
1205                 return Err(());
1206             }
1207             Some(path_res.full_def())
1208         } else {
1209             None
1210         };
1211
1212         // Note: This goes up here (rather than within the PatEnum arm
1213         // alone) because struct patterns can refer to struct types or
1214         // to struct variants within enums.
1215         let cmt = match opt_def {
1216             Some(Def::Variant(enum_did, variant_did))
1217                 // univariant enums do not need downcasts
1218                 if !self.tcx().lookup_adt_def(enum_did).is_univariant() => {
1219                     self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1220                 }
1221             _ => cmt
1222         };
1223
1224         match pat.node {
1225           hir::PatWild => {
1226             // _
1227           }
1228
1229           hir::PatEnum(_, None) => {
1230             // variant(..)
1231           }
1232           hir::PatEnum(_, Some(ref subpats)) => {
1233             match opt_def {
1234                 Some(Def::Variant(..)) => {
1235                     // variant(x, y, z)
1236                     for (i, subpat) in subpats.iter().enumerate() {
1237                         let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1238
1239                         let subcmt =
1240                             self.cat_imm_interior(
1241                                 pat, cmt.clone(), subpat_ty,
1242                                 InteriorField(PositionalField(i)));
1243
1244                         try!(self.cat_pattern_(subcmt, &**subpat, op));
1245                     }
1246                 }
1247                 Some(Def::Struct(..)) => {
1248                     for (i, subpat) in subpats.iter().enumerate() {
1249                         let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1250                         let cmt_field =
1251                             self.cat_imm_interior(
1252                                 pat, cmt.clone(), subpat_ty,
1253                                 InteriorField(PositionalField(i)));
1254                         try!(self.cat_pattern_(cmt_field, &**subpat, op));
1255                     }
1256                 }
1257                 Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {
1258                     for subpat in subpats {
1259                         try!(self.cat_pattern_(cmt.clone(), &**subpat, op));
1260                     }
1261                 }
1262                 _ => {
1263                     self.tcx().sess.span_bug(
1264                         pat.span,
1265                         &format!("enum pattern didn't resolve to enum or struct {:?}", opt_def));
1266                 }
1267             }
1268           }
1269
1270           hir::PatQPath(..) => {
1271               // Lone constant: ignore
1272           }
1273
1274           hir::PatIdent(_, _, Some(ref subpat)) => {
1275               try!(self.cat_pattern_(cmt, &**subpat, op));
1276           }
1277
1278           hir::PatIdent(_, _, None) => {
1279               // nullary variant or identifier: ignore
1280           }
1281
1282           hir::PatStruct(_, ref field_pats, _) => {
1283             // {f1: p1, ..., fN: pN}
1284             for fp in field_pats {
1285                 let field_ty = try!(self.pat_ty(&*fp.node.pat)); // see (*2)
1286                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1287                 try!(self.cat_pattern_(cmt_field, &*fp.node.pat, op));
1288             }
1289           }
1290
1291           hir::PatTup(ref subpats) => {
1292             // (p1, ..., pN)
1293             for (i, subpat) in subpats.iter().enumerate() {
1294                 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1295                 let subcmt =
1296                     self.cat_imm_interior(
1297                         pat, cmt.clone(), subpat_ty,
1298                         InteriorField(PositionalField(i)));
1299                 try!(self.cat_pattern_(subcmt, &**subpat, op));
1300             }
1301           }
1302
1303           hir::PatBox(ref subpat) | hir::PatRegion(ref subpat, _) => {
1304             // box p1, &p1, &mut p1.  we can ignore the mutability of
1305             // PatRegion since that information is already contained
1306             // in the type.
1307             let subcmt = try!(self.cat_deref(pat, cmt, 0, None));
1308               try!(self.cat_pattern_(subcmt, &**subpat, op));
1309           }
1310
1311           hir::PatVec(ref before, ref slice, ref after) => {
1312               let context = InteriorOffsetKind::Pattern;
1313               let vec_cmt = try!(self.deref_vec(pat, cmt, context));
1314               let elt_cmt = try!(self.cat_index(pat, vec_cmt, context));
1315               for before_pat in before {
1316                   try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op));
1317               }
1318               if let Some(ref slice_pat) = *slice {
1319                   let slice_ty = try!(self.pat_ty(&**slice_pat));
1320                   let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1321                   try!(self.cat_pattern_(slice_cmt, &**slice_pat, op));
1322               }
1323               for after_pat in after {
1324                   try!(self.cat_pattern_(elt_cmt.clone(), &**after_pat, op));
1325               }
1326           }
1327
1328           hir::PatLit(_) | hir::PatRange(_, _) => {
1329               /*always ok*/
1330           }
1331         }
1332
1333         Ok(())
1334     }
1335
1336     fn overloaded_method_return_ty(&self,
1337                                    method_ty: Ty<'tcx>)
1338                                    -> Ty<'tcx>
1339     {
1340         // When we process an overloaded `*` or `[]` etc, we often
1341         // need to extract the return type of the method. These method
1342         // types are generated by method resolution and always have
1343         // all late-bound regions fully instantiated, so we just want
1344         // to skip past the binder.
1345         self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1346            .unwrap()
1347            .unwrap() // overloaded ops do not diverge, either
1348     }
1349 }
1350
1351 #[derive(Clone, Debug)]
1352 pub enum Aliasability {
1353     FreelyAliasable(AliasableReason),
1354     NonAliasable,
1355     ImmutableUnique(Box<Aliasability>),
1356 }
1357
1358 #[derive(Copy, Clone, Debug)]
1359 pub enum AliasableReason {
1360     AliasableBorrowed,
1361     AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1362     AliasableOther,
1363     UnaliasableImmutable, // Created as needed upon seeing ImmutableUnique
1364     AliasableStatic,
1365     AliasableStaticMut,
1366 }
1367
1368 impl<'tcx> cmt_<'tcx> {
1369     pub fn guarantor(&self) -> cmt<'tcx> {
1370         //! Returns `self` after stripping away any derefs or
1371         //! interior content. The return value is basically the `cmt` which
1372         //! determines how long the value in `self` remains live.
1373
1374         match self.cat {
1375             Categorization::Rvalue(..) |
1376             Categorization::StaticItem |
1377             Categorization::Local(..) |
1378             Categorization::Deref(_, _, UnsafePtr(..)) |
1379             Categorization::Deref(_, _, BorrowedPtr(..)) |
1380             Categorization::Deref(_, _, Implicit(..)) |
1381             Categorization::Upvar(..) => {
1382                 Rc::new((*self).clone())
1383             }
1384             Categorization::Downcast(ref b, _) |
1385             Categorization::Interior(ref b, _) |
1386             Categorization::Deref(ref b, _, Unique) => {
1387                 b.guarantor()
1388             }
1389         }
1390     }
1391
1392     /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1393     pub fn freely_aliasable(&self, ctxt: &ty::ctxt<'tcx>)
1394                             -> Aliasability {
1395         // Maybe non-obvious: copied upvars can only be considered
1396         // non-aliasable in once closures, since any other kind can be
1397         // aliased and eventually recused.
1398
1399         match self.cat {
1400             Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1401             Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1402             Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1403             Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1404             Categorization::Downcast(ref b, _) |
1405             Categorization::Interior(ref b, _) => {
1406                 // Aliasability depends on base cmt
1407                 b.freely_aliasable(ctxt)
1408             }
1409
1410             Categorization::Deref(ref b, _, Unique) => {
1411                 let sub = b.freely_aliasable(ctxt);
1412                 if b.mutbl.is_mutable() {
1413                     // Aliasability depends on base cmt alone
1414                     sub
1415                 } else {
1416                     // Do not allow mutation through an immutable box.
1417                     ImmutableUnique(Box::new(sub))
1418                 }
1419             }
1420
1421             Categorization::Rvalue(..) |
1422             Categorization::Local(..) |
1423             Categorization::Upvar(..) |
1424             Categorization::Deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1425                 NonAliasable
1426             }
1427
1428             Categorization::StaticItem => {
1429                 if self.mutbl.is_mutable() {
1430                     FreelyAliasable(AliasableStaticMut)
1431                 } else {
1432                     FreelyAliasable(AliasableStatic)
1433                 }
1434             }
1435
1436             Categorization::Deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1437             Categorization::Deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1438                 match base.cat {
1439                     Categorization::Upvar(Upvar{ id, .. }) =>
1440                         FreelyAliasable(AliasableClosure(id.closure_expr_id)),
1441                     _ => FreelyAliasable(AliasableBorrowed)
1442                 }
1443             }
1444         }
1445     }
1446
1447     // Digs down through one or two layers of deref and grabs the cmt
1448     // for the upvar if a note indicates there is one.
1449     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1450         match self.note {
1451             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1452                 Some(match self.cat {
1453                     Categorization::Deref(ref inner, _, _) => {
1454                         match inner.cat {
1455                             Categorization::Deref(ref inner, _, _) => inner.clone(),
1456                             Categorization::Upvar(..) => inner.clone(),
1457                             _ => unreachable!()
1458                         }
1459                     }
1460                     _ => unreachable!()
1461                 })
1462             }
1463             NoteNone => None
1464         }
1465     }
1466
1467
1468     pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String {
1469         match self.cat {
1470             Categorization::StaticItem => {
1471                 "static item".to_string()
1472             }
1473             Categorization::Rvalue(..) => {
1474                 "non-lvalue".to_string()
1475             }
1476             Categorization::Local(vid) => {
1477                 if tcx.map.is_argument(vid) {
1478                     "argument".to_string()
1479                 } else {
1480                     "local variable".to_string()
1481                 }
1482             }
1483             Categorization::Deref(_, _, pk) => {
1484                 let upvar = self.upvar();
1485                 match upvar.as_ref().map(|i| &i.cat) {
1486                     Some(&Categorization::Upvar(ref var)) => {
1487                         var.to_string()
1488                     }
1489                     Some(_) => unreachable!(),
1490                     None => {
1491                         match pk {
1492                             Implicit(..) => {
1493                                 format!("indexed content")
1494                             }
1495                             Unique => {
1496                                 format!("`Box` content")
1497                             }
1498                             UnsafePtr(..) => {
1499                                 format!("dereference of raw pointer")
1500                             }
1501                             BorrowedPtr(..) => {
1502                                 format!("borrowed content")
1503                             }
1504                         }
1505                     }
1506                 }
1507             }
1508             Categorization::Interior(_, InteriorField(NamedField(_))) => {
1509                 "field".to_string()
1510             }
1511             Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1512                 "anonymous field".to_string()
1513             }
1514             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1515                                                         VecElement)) |
1516             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1517                                                         OtherElement)) => {
1518                 "indexed content".to_string()
1519             }
1520             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1521                                                         VecElement)) |
1522             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1523                                                         OtherElement)) => {
1524                 "pattern-bound indexed content".to_string()
1525             }
1526             Categorization::Upvar(ref var) => {
1527                 var.to_string()
1528             }
1529             Categorization::Downcast(ref cmt, _) => {
1530                 cmt.descriptive_string(tcx)
1531             }
1532         }
1533     }
1534 }
1535
1536 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1537     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1538         write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1539                self.cat,
1540                self.id,
1541                self.mutbl,
1542                self.ty)
1543     }
1544 }
1545
1546 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1547     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1548         match *self {
1549             Categorization::StaticItem => write!(f, "static"),
1550             Categorization::Rvalue(r) => write!(f, "rvalue({:?})", r),
1551             Categorization::Local(id) => {
1552                let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1553                write!(f, "local({})", name)
1554             }
1555             Categorization::Upvar(upvar) => {
1556                 write!(f, "upvar({:?})", upvar)
1557             }
1558             Categorization::Deref(ref cmt, derefs, ptr) => {
1559                 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1560             }
1561             Categorization::Interior(ref cmt, interior) => {
1562                 write!(f, "{:?}.{:?}", cmt.cat, interior)
1563             }
1564             Categorization::Downcast(ref cmt, _) => {
1565                 write!(f, "{:?}->(enum)", cmt.cat)
1566             }
1567         }
1568     }
1569 }
1570
1571 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1572     match ptr {
1573         Unique => "Box",
1574         BorrowedPtr(ty::ImmBorrow, _) |
1575         Implicit(ty::ImmBorrow, _) => "&",
1576         BorrowedPtr(ty::MutBorrow, _) |
1577         Implicit(ty::MutBorrow, _) => "&mut",
1578         BorrowedPtr(ty::UniqueImmBorrow, _) |
1579         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1580         UnsafePtr(_) => "*",
1581     }
1582 }
1583
1584 impl fmt::Debug for PointerKind {
1585     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1586         match *self {
1587             Unique => write!(f, "Box"),
1588             BorrowedPtr(ty::ImmBorrow, ref r) |
1589             Implicit(ty::ImmBorrow, ref r) => {
1590                 write!(f, "&{:?}", r)
1591             }
1592             BorrowedPtr(ty::MutBorrow, ref r) |
1593             Implicit(ty::MutBorrow, ref r) => {
1594                 write!(f, "&{:?} mut", r)
1595             }
1596             BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1597             Implicit(ty::UniqueImmBorrow, ref r) => {
1598                 write!(f, "&{:?} uniq", r)
1599             }
1600             UnsafePtr(_) => write!(f, "*")
1601         }
1602     }
1603 }
1604
1605 impl fmt::Debug for InteriorKind {
1606     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1607         match *self {
1608             InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1609             InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1610             InteriorElement(..) => write!(f, "[]"),
1611         }
1612     }
1613 }
1614
1615 fn element_kind(t: Ty) -> ElementKind {
1616     match t.sty {
1617         ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
1618         ty::TyBox(ty) => match ty.sty {
1619             ty::TySlice(_) => VecElement,
1620             _ => OtherElement
1621         },
1622         ty::TyArray(..) | ty::TySlice(_) => VecElement,
1623         _ => OtherElement
1624     }
1625 }
1626
1627 impl fmt::Debug for Upvar {
1628     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1629         write!(f, "{:?}/{:?}", self.id, self.kind)
1630     }
1631 }
1632
1633 impl fmt::Display for Upvar {
1634     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1635         let kind = match self.kind {
1636             ty::FnClosureKind => "Fn",
1637             ty::FnMutClosureKind => "FnMut",
1638             ty::FnOnceClosureKind => "FnOnce",
1639         };
1640         write!(f, "captured outer variable in an `{}` closure", kind)
1641     }
1642 }