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