]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
Rollup merge of #39604 - est31:i128_tests, 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 `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
71 use self::Aliasability::*;
72
73 use hir::def_id::DefId;
74 use hir::map as hir_map;
75 use infer::InferCtxt;
76 use hir::def::{Def, CtorKind};
77 use ty::adjustment;
78 use ty::{self, Ty, TyCtxt};
79
80 use hir::{MutImmutable, MutMutable, PatKind};
81 use hir::pat_util::EnumerateAndAdjustIterator;
82 use hir;
83 use syntax::ast;
84 use syntax_pos::Span;
85
86 use std::fmt;
87 use std::rc::Rc;
88
89 #[derive(Clone, PartialEq)]
90 pub enum Categorization<'tcx> {
91     // temporary val, argument is its scope
92     Rvalue(&'tcx ty::Region, &'tcx ty::Region),
93     StaticItem,
94     Upvar(Upvar),                          // upvar referenced by closure env
95     Local(ast::NodeId),                    // local variable
96     Deref(cmt<'tcx>, usize, PointerKind<'tcx>),  // 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<'tcx> {
113     /// `Box<T>`
114     Unique,
115
116     /// `&T`
117     BorrowedPtr(ty::BorrowKind, &'tcx 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, &'tcx 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 impl<'tcx> cmt_<'tcx> {
198     pub fn get_field(&self, name: ast::Name) -> Option<DefId> {
199         match self.cat {
200             Categorization::Deref(ref cmt, ..) |
201             Categorization::Interior(ref cmt, _) |
202             Categorization::Downcast(ref cmt, _) => {
203                 if let Categorization::Local(_) = cmt.cat {
204                     if let ty::TyAdt(def, _) = self.ty.sty {
205                         if def.is_struct() {
206                             return def.struct_variant().find_field_named(name).map(|x| x.did);
207                         }
208                     }
209                     None
210                 } else {
211                     cmt.get_field(name)
212                 }
213             }
214             _ => None
215         }
216     }
217
218     pub fn get_field_name(&self) -> Option<ast::Name> {
219         match self.cat {
220             Categorization::Interior(_, ref ik) => {
221                 if let InteriorKind::InteriorField(FieldName::NamedField(name)) = *ik {
222                     Some(name)
223                 } else {
224                     None
225                 }
226             }
227             Categorization::Deref(ref cmt, ..) |
228             Categorization::Downcast(ref cmt, _) => {
229                 cmt.get_field_name()
230             }
231             _ => None,
232         }
233     }
234
235     pub fn get_arg_if_immutable(&self, map: &hir_map::Map) -> Option<ast::NodeId> {
236         match self.cat {
237             Categorization::Deref(ref cmt, ..) |
238             Categorization::Interior(ref cmt, _) |
239             Categorization::Downcast(ref cmt, _) => {
240                 if let Categorization::Local(nid) = cmt.cat {
241                     if let ty::TyAdt(_, _) = self.ty.sty {
242                         if let ty::TyRef(_, ty::TypeAndMut{mutbl: MutImmutable, ..}) = cmt.ty.sty {
243                             return Some(nid);
244                         }
245                     }
246                     None
247                 } else {
248                     cmt.get_arg_if_immutable(map)
249                 }
250             }
251             _ => None
252         }
253     }
254 }
255
256 pub trait ast_node {
257     fn id(&self) -> ast::NodeId;
258     fn span(&self) -> Span;
259 }
260
261 impl ast_node for hir::Expr {
262     fn id(&self) -> ast::NodeId { self.id }
263     fn span(&self) -> Span { self.span }
264 }
265
266 impl ast_node for hir::Pat {
267     fn id(&self) -> ast::NodeId { self.id }
268     fn span(&self) -> Span { self.span }
269 }
270
271 #[derive(Copy, Clone)]
272 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
273     pub infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
274     options: MemCategorizationOptions,
275 }
276
277 #[derive(Copy, Clone, Default)]
278 pub struct MemCategorizationOptions {
279     // If true, then when analyzing a closure upvar, if the closure
280     // has a missing kind, we treat it like a Fn closure. When false,
281     // we ICE if the closure has a missing kind. Should be false
282     // except during closure kind inference. It is used by the
283     // mem-categorization code to be able to have stricter assertions
284     // (which are always true except during upvar inference).
285     pub during_closure_kind_inference: bool,
286 }
287
288 pub type McResult<T> = Result<T, ()>;
289
290 impl MutabilityCategory {
291     pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
292         let ret = match m {
293             MutImmutable => McImmutable,
294             MutMutable => McDeclared
295         };
296         debug!("MutabilityCategory::{}({:?}) => {:?}",
297                "from_mutbl", m, ret);
298         ret
299     }
300
301     pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
302         let ret = match borrow_kind {
303             ty::ImmBorrow => McImmutable,
304             ty::UniqueImmBorrow => McImmutable,
305             ty::MutBorrow => McDeclared,
306         };
307         debug!("MutabilityCategory::{}({:?}) => {:?}",
308                "from_borrow_kind", borrow_kind, ret);
309         ret
310     }
311
312     fn from_pointer_kind(base_mutbl: MutabilityCategory,
313                          ptr: PointerKind) -> MutabilityCategory {
314         let ret = match ptr {
315             Unique => {
316                 base_mutbl.inherit()
317             }
318             BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
319                 MutabilityCategory::from_borrow_kind(borrow_kind)
320             }
321             UnsafePtr(m) => {
322                 MutabilityCategory::from_mutbl(m)
323             }
324         };
325         debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
326                "from_pointer_kind", base_mutbl, ptr, ret);
327         ret
328     }
329
330     fn from_local(tcx: TyCtxt, id: ast::NodeId) -> MutabilityCategory {
331         let ret = match tcx.hir.get(id) {
332             hir_map::NodeLocal(p) => match p.node {
333                 PatKind::Binding(bind_mode, ..) => {
334                     if bind_mode == hir::BindByValue(hir::MutMutable) {
335                         McDeclared
336                     } else {
337                         McImmutable
338                     }
339                 }
340                 _ => span_bug!(p.span, "expected identifier pattern")
341             },
342             _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
343         };
344         debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
345                "from_local", id, ret);
346         ret
347     }
348
349     pub fn inherit(&self) -> MutabilityCategory {
350         let ret = match *self {
351             McImmutable => McImmutable,
352             McDeclared => McInherited,
353             McInherited => McInherited,
354         };
355         debug!("{:?}.inherit() => {:?}", self, ret);
356         ret
357     }
358
359     pub fn is_mutable(&self) -> bool {
360         let ret = match *self {
361             McImmutable => false,
362             McInherited => true,
363             McDeclared => true,
364         };
365         debug!("{:?}.is_mutable() => {:?}", self, ret);
366         ret
367     }
368
369     pub fn is_immutable(&self) -> bool {
370         let ret = match *self {
371             McImmutable => true,
372             McDeclared | McInherited => false
373         };
374         debug!("{:?}.is_immutable() => {:?}", self, ret);
375         ret
376     }
377
378     pub fn to_user_str(&self) -> &'static str {
379         match *self {
380             McDeclared | McInherited => "mutable",
381             McImmutable => "immutable",
382         }
383     }
384 }
385
386 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
387     pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>)
388                -> MemCategorizationContext<'a, 'gcx, 'tcx> {
389         MemCategorizationContext::with_options(infcx, MemCategorizationOptions::default())
390     }
391
392     pub fn with_options(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
393                         options: MemCategorizationOptions)
394                         -> MemCategorizationContext<'a, 'gcx, 'tcx> {
395         MemCategorizationContext {
396             infcx: infcx,
397             options: options,
398         }
399     }
400
401     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
402         self.infcx.tcx
403     }
404
405     fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
406         match self.infcx.node_ty(expr.id) {
407             Ok(t) => Ok(t),
408             Err(()) => {
409                 debug!("expr_ty({:?}) yielded Err", expr);
410                 Err(())
411             }
412         }
413     }
414
415     fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
416         self.infcx.expr_ty_adjusted(expr)
417     }
418
419     fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
420         self.infcx.node_ty(id)
421     }
422
423     fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
424         let base_ty = self.infcx.node_ty(pat.id)?;
425         // FIXME (Issue #18207): This code detects whether we are
426         // looking at a `ref x`, and if so, figures out what the type
427         // *being borrowed* is.  But ideally we would put in a more
428         // fundamental fix to this conflated use of the node id.
429         let ret_ty = match pat.node {
430             PatKind::Binding(hir::BindByRef(_), ..) => {
431                 // a bind-by-ref means that the base_ty will be the type of the ident itself,
432                 // but what we want here is the type of the underlying value being borrowed.
433                 // So peel off one-level, turning the &T into T.
434                 match base_ty.builtin_deref(false, ty::NoPreference) {
435                     Some(t) => t.ty,
436                     None => { return Err(()); }
437                 }
438             }
439             _ => base_ty,
440         };
441         debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
442                pat, base_ty, ret_ty);
443         Ok(ret_ty)
444     }
445
446     pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
447         match self.infcx.tables.borrow().adjustments.get(&expr.id) {
448             None => {
449                 // No adjustments.
450                 self.cat_expr_unadjusted(expr)
451             }
452
453             Some(adjustment) => {
454                 match adjustment.kind {
455                     adjustment::Adjust::DerefRef {
456                         autoderefs,
457                         autoref: None,
458                         unsize: false
459                     } => {
460                         // Equivalent to *expr or something similar.
461                         self.cat_expr_autoderefd(expr, autoderefs)
462                     }
463
464                     adjustment::Adjust::NeverToAny |
465                     adjustment::Adjust::ReifyFnPointer |
466                     adjustment::Adjust::UnsafeFnPointer |
467                     adjustment::Adjust::MutToConstPointer |
468                     adjustment::Adjust::DerefRef {..} => {
469                         debug!("cat_expr({:?}): {:?}",
470                                adjustment,
471                                expr);
472                         // Result is an rvalue.
473                         let expr_ty = self.expr_ty_adjusted(expr)?;
474                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
475                     }
476                 }
477             }
478         }
479     }
480
481     pub fn cat_expr_autoderefd(&self,
482                                expr: &hir::Expr,
483                                autoderefs: usize)
484                                -> McResult<cmt<'tcx>> {
485         let mut cmt = self.cat_expr_unadjusted(expr)?;
486         debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
487                autoderefs,
488                cmt);
489         for deref in 1..autoderefs + 1 {
490             cmt = self.cat_deref(expr, cmt, deref)?;
491         }
492         return Ok(cmt);
493     }
494
495     pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
496         debug!("cat_expr: id={} expr={:?}", expr.id, expr);
497
498         let expr_ty = self.expr_ty(expr)?;
499         match expr.node {
500           hir::ExprUnary(hir::UnDeref, ref e_base) => {
501             let base_cmt = self.cat_expr(&e_base)?;
502             self.cat_deref(expr, base_cmt, 0)
503           }
504
505           hir::ExprField(ref base, f_name) => {
506             let base_cmt = self.cat_expr(&base)?;
507             debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
508                    expr.id,
509                    expr,
510                    base_cmt);
511             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
512           }
513
514           hir::ExprTupField(ref base, idx) => {
515             let base_cmt = self.cat_expr(&base)?;
516             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
517           }
518
519           hir::ExprIndex(ref base, _) => {
520             let method_call = ty::MethodCall::expr(expr.id());
521             match self.infcx.node_method_ty(method_call) {
522                 Some(method_ty) => {
523                     // If this is an index implemented by a method call, then it
524                     // will include an implicit deref of the result.
525                     let ret_ty = self.overloaded_method_return_ty(method_ty);
526
527                     // The index method always returns an `&T`, so
528                     // dereference it to find the result type.
529                     let elem_ty = match ret_ty.sty {
530                         ty::TyRef(_, mt) => mt.ty,
531                         _ => {
532                             debug!("cat_expr_unadjusted: return type of overloaded index is {:?}?",
533                                    ret_ty);
534                             return Err(());
535                         }
536                     };
537
538                     // The call to index() returns a `&T` value, which
539                     // is an rvalue. That is what we will be
540                     // dereferencing.
541                     let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
542                     Ok(self.cat_deref_common(expr, base_cmt, 1, elem_ty, true))
543                 }
544                 None => {
545                     self.cat_index(expr, self.cat_expr(&base)?, InteriorOffsetKind::Index)
546                 }
547             }
548           }
549
550           hir::ExprPath(ref qpath) => {
551             let def = self.infcx.tables.borrow().qpath_def(qpath, expr.id);
552             self.cat_def(expr.id, expr.span, expr_ty, def)
553           }
554
555           hir::ExprType(ref e, _) => {
556             self.cat_expr(&e)
557           }
558
559           hir::ExprAddrOf(..) | hir::ExprCall(..) |
560           hir::ExprAssign(..) | hir::ExprAssignOp(..) |
561           hir::ExprClosure(..) | hir::ExprRet(..) |
562           hir::ExprUnary(..) |
563           hir::ExprMethodCall(..) | hir::ExprCast(..) |
564           hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
565           hir::ExprBinary(..) | hir::ExprWhile(..) |
566           hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
567           hir::ExprLit(..) | hir::ExprBreak(..) |
568           hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
569           hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
570             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
571           }
572         }
573     }
574
575     pub fn cat_def(&self,
576                    id: ast::NodeId,
577                    span: Span,
578                    expr_ty: Ty<'tcx>,
579                    def: Def)
580                    -> McResult<cmt<'tcx>> {
581         debug!("cat_def: id={} expr={:?} def={:?}",
582                id, expr_ty, def);
583
584         match def {
585           Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
586           Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
587                 Ok(self.cat_rvalue_node(id, span, expr_ty))
588           }
589
590           Def::Static(_, mutbl) => {
591               Ok(Rc::new(cmt_ {
592                   id:id,
593                   span:span,
594                   cat:Categorization::StaticItem,
595                   mutbl: if mutbl { McDeclared } else { McImmutable},
596                   ty:expr_ty,
597                   note: NoteNone
598               }))
599           }
600
601           Def::Upvar(def_id, _, fn_node_id) => {
602               let var_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
603               let ty = self.node_ty(fn_node_id)?;
604               match ty.sty {
605                   ty::TyClosure(closure_id, _) => {
606                       match self.infcx.closure_kind(closure_id) {
607                           Some(kind) => {
608                               self.cat_upvar(id, span, var_id, fn_node_id, kind)
609                           }
610                           None => {
611                               if !self.options.during_closure_kind_inference {
612                                   span_bug!(
613                                       span,
614                                       "No closure kind for {:?}",
615                                       closure_id);
616                               }
617
618                               // during closure kind inference, we
619                               // don't know the closure kind yet, but
620                               // it's ok because we detect that we are
621                               // accessing an upvar and handle that
622                               // case specially anyhow. Use Fn
623                               // arbitrarily.
624                               self.cat_upvar(id, span, var_id, fn_node_id, ty::ClosureKind::Fn)
625                           }
626                       }
627                   }
628                   _ => {
629                       span_bug!(
630                           span,
631                           "Upvar of non-closure {} - {:?}",
632                           fn_node_id,
633                           ty);
634                   }
635               }
636           }
637
638           Def::Local(def_id) => {
639             let vid = self.tcx().hir.as_local_node_id(def_id).unwrap();
640             Ok(Rc::new(cmt_ {
641                 id: id,
642                 span: span,
643                 cat: Categorization::Local(vid),
644                 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
645                 ty: expr_ty,
646                 note: NoteNone
647             }))
648           }
649
650           def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
651         }
652     }
653
654     // Categorize an upvar, complete with invisible derefs of closure
655     // environment and upvar reference as appropriate.
656     fn cat_upvar(&self,
657                  id: ast::NodeId,
658                  span: Span,
659                  var_id: ast::NodeId,
660                  fn_node_id: ast::NodeId,
661                  kind: ty::ClosureKind)
662                  -> McResult<cmt<'tcx>>
663     {
664         // An upvar can have up to 3 components. We translate first to a
665         // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
666         // field from the environment.
667         //
668         // `Categorization::Upvar`.  Next, we add a deref through the implicit
669         // environment pointer with an anonymous free region 'env and
670         // appropriate borrow kind for closure kinds that take self by
671         // reference.  Finally, if the upvar was captured
672         // by-reference, we add a deref through that reference.  The
673         // region of this reference is an inference variable 'up that
674         // was previously generated and recorded in the upvar borrow
675         // map.  The borrow kind bk is inferred by based on how the
676         // upvar is used.
677         //
678         // This results in the following table for concrete closure
679         // types:
680         //
681         //                | move                 | ref
682         // ---------------+----------------------+-------------------------------
683         // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
684         // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
685         // FnOnce         | copied               | upvar -> &'up bk
686
687         let upvar_id = ty::UpvarId { var_id: var_id,
688                                      closure_expr_id: fn_node_id };
689         let var_ty = self.node_ty(var_id)?;
690
691         // Mutability of original variable itself
692         let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
693
694         // Construct the upvar. This represents access to the field
695         // from the environment (perhaps we should eventually desugar
696         // this field further, but it will do for now).
697         let cmt_result = cmt_ {
698             id: id,
699             span: span,
700             cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
701             mutbl: var_mutbl,
702             ty: var_ty,
703             note: NoteNone
704         };
705
706         // If this is a `FnMut` or `Fn` closure, then the above is
707         // conceptually a `&mut` or `&` reference, so we have to add a
708         // deref.
709         let cmt_result = match kind {
710             ty::ClosureKind::FnOnce => {
711                 cmt_result
712             }
713             ty::ClosureKind::FnMut => {
714                 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
715             }
716             ty::ClosureKind::Fn => {
717                 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
718             }
719         };
720
721         // If this is a by-ref capture, then the upvar we loaded is
722         // actually a reference, so we have to add an implicit deref
723         // for that.
724         let upvar_id = ty::UpvarId { var_id: var_id,
725                                      closure_expr_id: fn_node_id };
726         let upvar_capture = self.infcx.upvar_capture(upvar_id).unwrap();
727         let cmt_result = match upvar_capture {
728             ty::UpvarCapture::ByValue => {
729                 cmt_result
730             }
731             ty::UpvarCapture::ByRef(upvar_borrow) => {
732                 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
733                 cmt_ {
734                     id: id,
735                     span: span,
736                     cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
737                     mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
738                     ty: var_ty,
739                     note: NoteUpvarRef(upvar_id)
740                 }
741             }
742         };
743
744         let ret = Rc::new(cmt_result);
745         debug!("cat_upvar ret={:?}", ret);
746         Ok(ret)
747     }
748
749     fn env_deref(&self,
750                  id: ast::NodeId,
751                  span: Span,
752                  upvar_id: ty::UpvarId,
753                  upvar_mutbl: MutabilityCategory,
754                  env_borrow_kind: ty::BorrowKind,
755                  cmt_result: cmt_<'tcx>)
756                  -> cmt_<'tcx>
757     {
758         // Look up the node ID of the closure body so we can construct
759         // a free region within it
760         let fn_body_id = {
761             let fn_expr = match self.tcx().hir.find(upvar_id.closure_expr_id) {
762                 Some(hir_map::NodeExpr(e)) => e,
763                 _ => bug!()
764             };
765
766             match fn_expr.node {
767                 hir::ExprClosure(.., body_id, _) => body_id.node_id,
768                 _ => bug!()
769             }
770         };
771
772         // Region of environment pointer
773         let env_region = self.tcx().mk_region(ty::ReFree(ty::FreeRegion {
774             // The environment of a closure is guaranteed to
775             // outlive any bindings introduced in the body of the
776             // closure itself.
777             scope: self.tcx().region_maps.item_extent(fn_body_id),
778             bound_region: ty::BrEnv
779         }));
780
781         let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
782
783         let var_ty = cmt_result.ty;
784
785         // We need to add the env deref.  This means
786         // that the above is actually immutable and
787         // has a ref type.  However, nothing should
788         // actually look at the type, so we can get
789         // away with stuffing a `TyError` in there
790         // instead of bothering to construct a proper
791         // one.
792         let cmt_result = cmt_ {
793             mutbl: McImmutable,
794             ty: self.tcx().types.err,
795             ..cmt_result
796         };
797
798         let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
799
800         // Issue #18335. If variable is declared as immutable, override the
801         // mutability from the environment and substitute an `&T` anyway.
802         match upvar_mutbl {
803             McImmutable => { deref_mutbl = McImmutable; }
804             McDeclared | McInherited => { }
805         }
806
807         let ret = cmt_ {
808             id: id,
809             span: span,
810             cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
811             mutbl: deref_mutbl,
812             ty: var_ty,
813             note: NoteClosureEnv(upvar_id)
814         };
815
816         debug!("env_deref ret {:?}", ret);
817
818         ret
819     }
820
821     /// Returns the lifetime of a temporary created by expr with id `id`.
822     /// This could be `'static` if `id` is part of a constant expression.
823     pub fn temporary_scope(&self, id: ast::NodeId) -> (&'tcx ty::Region, &'tcx ty::Region)
824     {
825         let (scope, old_scope) =
826             self.tcx().region_maps.old_and_new_temporary_scope(id);
827         (self.tcx().mk_region(match scope {
828             Some(scope) => ty::ReScope(scope),
829             None => ty::ReStatic
830         }),
831          self.tcx().mk_region(match old_scope {
832             Some(scope) => ty::ReScope(scope),
833             None => ty::ReStatic
834         }))
835     }
836
837     pub fn cat_rvalue_node(&self,
838                            id: ast::NodeId,
839                            span: Span,
840                            expr_ty: Ty<'tcx>)
841                            -> cmt<'tcx> {
842         let promotable = self.tcx().rvalue_promotable_to_static.borrow().get(&id).cloned()
843                                    .unwrap_or(false);
844
845         // Only promote `[T; 0]` before an RFC for rvalue promotions
846         // is accepted.
847         let promotable = match expr_ty.sty {
848             ty::TyArray(_, 0) => true,
849             _ => promotable & false
850         };
851
852         // Compute maximum lifetime of this rvalue. This is 'static if
853         // we can promote to a constant, otherwise equal to enclosing temp
854         // lifetime.
855         let (re, old_re) = if promotable {
856             (self.tcx().mk_region(ty::ReStatic),
857              self.tcx().mk_region(ty::ReStatic))
858         } else {
859             self.temporary_scope(id)
860         };
861         let ret = self.cat_rvalue(id, span, re, old_re, expr_ty);
862         debug!("cat_rvalue_node ret {:?}", ret);
863         ret
864     }
865
866     pub fn cat_rvalue(&self,
867                       cmt_id: ast::NodeId,
868                       span: Span,
869                       temp_scope: &'tcx ty::Region,
870                       old_temp_scope: &'tcx ty::Region,
871                       expr_ty: Ty<'tcx>) -> cmt<'tcx> {
872         let ret = Rc::new(cmt_ {
873             id:cmt_id,
874             span:span,
875             cat:Categorization::Rvalue(temp_scope, old_temp_scope),
876             mutbl:McDeclared,
877             ty:expr_ty,
878             note: NoteNone
879         });
880         debug!("cat_rvalue ret {:?}", ret);
881         ret
882     }
883
884     pub fn cat_field<N:ast_node>(&self,
885                                  node: &N,
886                                  base_cmt: cmt<'tcx>,
887                                  f_name: ast::Name,
888                                  f_ty: Ty<'tcx>)
889                                  -> cmt<'tcx> {
890         let ret = Rc::new(cmt_ {
891             id: node.id(),
892             span: node.span(),
893             mutbl: base_cmt.mutbl.inherit(),
894             cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
895             ty: f_ty,
896             note: NoteNone
897         });
898         debug!("cat_field ret {:?}", ret);
899         ret
900     }
901
902     pub fn cat_tup_field<N:ast_node>(&self,
903                                      node: &N,
904                                      base_cmt: cmt<'tcx>,
905                                      f_idx: usize,
906                                      f_ty: Ty<'tcx>)
907                                      -> cmt<'tcx> {
908         let ret = Rc::new(cmt_ {
909             id: node.id(),
910             span: node.span(),
911             mutbl: base_cmt.mutbl.inherit(),
912             cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
913             ty: f_ty,
914             note: NoteNone
915         });
916         debug!("cat_tup_field ret {:?}", ret);
917         ret
918     }
919
920     fn cat_deref<N:ast_node>(&self,
921                              node: &N,
922                              base_cmt: cmt<'tcx>,
923                              deref_cnt: usize)
924                              -> McResult<cmt<'tcx>> {
925         let method_call = ty::MethodCall {
926             expr_id: node.id(),
927             autoderef: deref_cnt as u32
928         };
929         let method_ty = self.infcx.node_method_ty(method_call);
930
931         debug!("cat_deref: method_call={:?} method_ty={:?}",
932                method_call, method_ty.map(|ty| ty));
933
934         let base_cmt = match method_ty {
935             Some(method_ty) => {
936                 let ref_ty =
937                     self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap();
938                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
939             }
940             None => base_cmt
941         };
942         let base_cmt_ty = base_cmt.ty;
943         match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
944             Some(mt) => {
945                 let ret = self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, false);
946                 debug!("cat_deref ret {:?}", ret);
947                 Ok(ret)
948             }
949             None => {
950                 debug!("Explicit deref of non-derefable type: {:?}",
951                        base_cmt_ty);
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                                     implicit: bool)
963                                     -> cmt<'tcx>
964     {
965         let ptr = match base_cmt.ty.sty {
966             ty::TyAdt(def, ..) if def.is_box() => Unique,
967             ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
968             ty::TyRef(r, mt) => {
969                 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
970                 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
971             }
972             ref ty => bug!("unexpected type in cat_deref_common: {:?}", ty)
973         };
974         let ret = Rc::new(cmt_ {
975             id: node.id(),
976             span: node.span(),
977             // For unique ptrs, we inherit mutability from the owning reference.
978             mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
979             cat: Categorization::Deref(base_cmt, deref_cnt, ptr),
980             ty: deref_ty,
981             note: NoteNone
982         });
983         debug!("cat_deref_common ret {:?}", ret);
984         ret
985     }
986
987     pub fn cat_index<N:ast_node>(&self,
988                                  elt: &N,
989                                  mut base_cmt: cmt<'tcx>,
990                                  context: InteriorOffsetKind)
991                                  -> McResult<cmt<'tcx>> {
992         //! Creates a cmt for an indexing operation (`[]`).
993         //!
994         //! One subtle aspect of indexing that may not be
995         //! immediately obvious: for anything other than a fixed-length
996         //! vector, an operation like `x[y]` actually consists of two
997         //! disjoint (from the point of view of borrowck) operations.
998         //! The first is a deref of `x` to create a pointer `p` that points
999         //! at the first element in the array. The second operation is
1000         //! an index which adds `y*sizeof(T)` to `p` to obtain the
1001         //! pointer to `x[y]`. `cat_index` will produce a resulting
1002         //! cmt containing both this deref and the indexing,
1003         //! presuming that `base_cmt` is not of fixed-length type.
1004         //!
1005         //! # Parameters
1006         //! - `elt`: the AST node being indexed
1007         //! - `base_cmt`: the cmt of `elt`
1008
1009         let method_call = ty::MethodCall::expr(elt.id());
1010         let method_ty = self.infcx.node_method_ty(method_call);
1011
1012         let (element_ty, element_kind) = match method_ty {
1013             Some(method_ty) => {
1014                 let ref_ty = self.overloaded_method_return_ty(method_ty);
1015                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
1016
1017                 (ref_ty.builtin_deref(false, ty::NoPreference).unwrap().ty,
1018                  ElementKind::OtherElement)
1019             }
1020             None => {
1021                 match base_cmt.ty.builtin_index() {
1022                     Some(ty) => (ty, ElementKind::VecElement),
1023                     None => {
1024                         return Err(());
1025                     }
1026                 }
1027             }
1028         };
1029
1030         let interior_elem = InteriorElement(context, element_kind);
1031         let ret =
1032             self.cat_imm_interior(elt, base_cmt.clone(), element_ty, interior_elem);
1033         debug!("cat_index ret {:?}", ret);
1034         return Ok(ret);
1035     }
1036
1037     pub fn cat_imm_interior<N:ast_node>(&self,
1038                                         node: &N,
1039                                         base_cmt: cmt<'tcx>,
1040                                         interior_ty: Ty<'tcx>,
1041                                         interior: InteriorKind)
1042                                         -> cmt<'tcx> {
1043         let ret = Rc::new(cmt_ {
1044             id: node.id(),
1045             span: node.span(),
1046             mutbl: base_cmt.mutbl.inherit(),
1047             cat: Categorization::Interior(base_cmt, interior),
1048             ty: interior_ty,
1049             note: NoteNone
1050         });
1051         debug!("cat_imm_interior ret={:?}", ret);
1052         ret
1053     }
1054
1055     pub fn cat_downcast<N:ast_node>(&self,
1056                                     node: &N,
1057                                     base_cmt: cmt<'tcx>,
1058                                     downcast_ty: Ty<'tcx>,
1059                                     variant_did: DefId)
1060                                     -> cmt<'tcx> {
1061         let ret = Rc::new(cmt_ {
1062             id: node.id(),
1063             span: node.span(),
1064             mutbl: base_cmt.mutbl.inherit(),
1065             cat: Categorization::Downcast(base_cmt, variant_did),
1066             ty: downcast_ty,
1067             note: NoteNone
1068         });
1069         debug!("cat_downcast ret={:?}", ret);
1070         ret
1071     }
1072
1073     pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1074         where F: FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat),
1075     {
1076         self.cat_pattern_(cmt, pat, &mut op)
1077     }
1078
1079     // FIXME(#19596) This is a workaround, but there should be a better way to do this
1080     fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1081         where F : FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat)
1082     {
1083         // Here, `cmt` is the categorization for the value being
1084         // matched and pat is the pattern it is being matched against.
1085         //
1086         // In general, the way that this works is that we walk down
1087         // the pattern, constructing a cmt that represents the path
1088         // that will be taken to reach the value being matched.
1089         //
1090         // When we encounter named bindings, we take the cmt that has
1091         // been built up and pass it off to guarantee_valid() so that
1092         // we can be sure that the binding will remain valid for the
1093         // duration of the arm.
1094         //
1095         // (*2) There is subtlety concerning the correspondence between
1096         // pattern ids and types as compared to *expression* ids and
1097         // types. This is explained briefly. on the definition of the
1098         // type `cmt`, so go off and read what it says there, then
1099         // come back and I'll dive into a bit more detail here. :) OK,
1100         // back?
1101         //
1102         // In general, the id of the cmt should be the node that
1103         // "produces" the value---patterns aren't executable code
1104         // exactly, but I consider them to "execute" when they match a
1105         // value, and I consider them to produce the value that was
1106         // matched. So if you have something like:
1107         //
1108         //     let x = @@3;
1109         //     match x {
1110         //       @@y { ... }
1111         //     }
1112         //
1113         // In this case, the cmt and the relevant ids would be:
1114         //
1115         //     CMT             Id                  Type of Id Type of cmt
1116         //
1117         //     local(x)->@->@
1118         //     ^~~~~~~^        `x` from discr      @@int      @@int
1119         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1120         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1121         //
1122         // You can see that the types of the id and the cmt are in
1123         // sync in the first line, because that id is actually the id
1124         // of an expression. But once we get to pattern ids, the types
1125         // step out of sync again. So you'll see below that we always
1126         // get the type of the *subpattern* and use that.
1127
1128         debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1129
1130         op(self, cmt.clone(), pat);
1131
1132         // Note: This goes up here (rather than within the PatKind::TupleStruct arm
1133         // alone) because PatKind::Struct can also refer to variants.
1134         let cmt = match pat.node {
1135             PatKind::Path(hir::QPath::Resolved(_, ref path)) |
1136             PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) |
1137             PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => {
1138                 match path.def {
1139                     Def::Err => return Err(()),
1140                     Def::Variant(variant_did) |
1141                     Def::VariantCtor(variant_did, ..) => {
1142                         // univariant enums do not need downcasts
1143                         let enum_did = self.tcx().parent_def_id(variant_did).unwrap();
1144                         if !self.tcx().lookup_adt_def(enum_did).is_univariant() {
1145                             self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1146                         } else {
1147                             cmt
1148                         }
1149                     }
1150                     _ => cmt
1151                 }
1152             }
1153             _ => cmt
1154         };
1155
1156         match pat.node {
1157           PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1158             let def = self.infcx.tables.borrow().qpath_def(qpath, pat.id);
1159             let expected_len = match def {
1160                 Def::VariantCtor(def_id, CtorKind::Fn) => {
1161                     let enum_def = self.tcx().parent_def_id(def_id).unwrap();
1162                     self.tcx().lookup_adt_def(enum_def).variant_with_id(def_id).fields.len()
1163                 }
1164                 Def::StructCtor(_, CtorKind::Fn) => {
1165                     match self.pat_ty(&pat)?.sty {
1166                         ty::TyAdt(adt_def, _) => {
1167                             adt_def.struct_variant().fields.len()
1168                         }
1169                         ref ty => {
1170                             span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1171                         }
1172                     }
1173                 }
1174                 def => {
1175                     span_bug!(pat.span, "tuple struct pattern didn't resolve \
1176                                          to variant or struct {:?}", def);
1177                 }
1178             };
1179
1180             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1181                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1182                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1183                                                    InteriorField(PositionalField(i)));
1184                 self.cat_pattern_(subcmt, &subpat, op)?;
1185             }
1186           }
1187
1188           PatKind::Struct(_, ref field_pats, _) => {
1189             // {f1: p1, ..., fN: pN}
1190             for fp in field_pats {
1191                 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1192                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1193                 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1194             }
1195           }
1196
1197           PatKind::Binding(.., Some(ref subpat)) => {
1198               self.cat_pattern_(cmt, &subpat, op)?;
1199           }
1200
1201           PatKind::Tuple(ref subpats, ddpos) => {
1202             // (p1, ..., pN)
1203             let expected_len = match self.pat_ty(&pat)?.sty {
1204                 ty::TyTuple(ref tys, _) => tys.len(),
1205                 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1206             };
1207             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1208                 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1209                 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1210                                                    InteriorField(PositionalField(i)));
1211                 self.cat_pattern_(subcmt, &subpat, op)?;
1212             }
1213           }
1214
1215           PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1216             // box p1, &p1, &mut p1.  we can ignore the mutability of
1217             // PatKind::Ref since that information is already contained
1218             // in the type.
1219             let subcmt = self.cat_deref(pat, cmt, 0)?;
1220             self.cat_pattern_(subcmt, &subpat, op)?;
1221           }
1222
1223           PatKind::Slice(ref before, ref slice, ref after) => {
1224             let context = InteriorOffsetKind::Pattern;
1225             let elt_cmt = self.cat_index(pat, cmt, context)?;
1226             for before_pat in before {
1227                 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1228             }
1229             if let Some(ref slice_pat) = *slice {
1230                 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1231             }
1232             for after_pat in after {
1233                 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1234             }
1235           }
1236
1237           PatKind::Path(_) | PatKind::Binding(.., None) |
1238           PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1239             // always ok
1240           }
1241         }
1242
1243         Ok(())
1244     }
1245
1246     fn overloaded_method_return_ty(&self,
1247                                    method_ty: Ty<'tcx>)
1248                                    -> Ty<'tcx>
1249     {
1250         // When we process an overloaded `*` or `[]` etc, we often
1251         // need to extract the return type of the method. These method
1252         // types are generated by method resolution and always have
1253         // all late-bound regions fully instantiated, so we just want
1254         // to skip past the binder.
1255         self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1256            .unwrap()
1257     }
1258 }
1259
1260 #[derive(Clone, Debug)]
1261 pub enum Aliasability {
1262     FreelyAliasable(AliasableReason),
1263     NonAliasable,
1264     ImmutableUnique(Box<Aliasability>),
1265 }
1266
1267 #[derive(Copy, Clone, Debug)]
1268 pub enum AliasableReason {
1269     AliasableBorrowed,
1270     AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1271     AliasableOther,
1272     UnaliasableImmutable, // Created as needed upon seeing ImmutableUnique
1273     AliasableStatic,
1274     AliasableStaticMut,
1275 }
1276
1277 impl<'tcx> cmt_<'tcx> {
1278     pub fn guarantor(&self) -> cmt<'tcx> {
1279         //! Returns `self` after stripping away any derefs or
1280         //! interior content. The return value is basically the `cmt` which
1281         //! determines how long the value in `self` remains live.
1282
1283         match self.cat {
1284             Categorization::Rvalue(..) |
1285             Categorization::StaticItem |
1286             Categorization::Local(..) |
1287             Categorization::Deref(.., UnsafePtr(..)) |
1288             Categorization::Deref(.., BorrowedPtr(..)) |
1289             Categorization::Deref(.., Implicit(..)) |
1290             Categorization::Upvar(..) => {
1291                 Rc::new((*self).clone())
1292             }
1293             Categorization::Downcast(ref b, _) |
1294             Categorization::Interior(ref b, _) |
1295             Categorization::Deref(ref b, _, Unique) => {
1296                 b.guarantor()
1297             }
1298         }
1299     }
1300
1301     /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1302     pub fn freely_aliasable(&self) -> Aliasability {
1303         // Maybe non-obvious: copied upvars can only be considered
1304         // non-aliasable in once closures, since any other kind can be
1305         // aliased and eventually recused.
1306
1307         match self.cat {
1308             Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1309             Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1310             Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1311             Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1312             Categorization::Downcast(ref b, _) |
1313             Categorization::Interior(ref b, _) => {
1314                 // Aliasability depends on base cmt
1315                 b.freely_aliasable()
1316             }
1317
1318             Categorization::Deref(ref b, _, Unique) => {
1319                 let sub = b.freely_aliasable();
1320                 if b.mutbl.is_mutable() {
1321                     // Aliasability depends on base cmt alone
1322                     sub
1323                 } else {
1324                     // Do not allow mutation through an immutable box.
1325                     ImmutableUnique(Box::new(sub))
1326                 }
1327             }
1328
1329             Categorization::Rvalue(..) |
1330             Categorization::Local(..) |
1331             Categorization::Upvar(..) |
1332             Categorization::Deref(.., UnsafePtr(..)) => { // yes, it's aliasable, but...
1333                 NonAliasable
1334             }
1335
1336             Categorization::StaticItem => {
1337                 if self.mutbl.is_mutable() {
1338                     FreelyAliasable(AliasableStaticMut)
1339                 } else {
1340                     FreelyAliasable(AliasableStatic)
1341                 }
1342             }
1343
1344             Categorization::Deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1345             Categorization::Deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1346                 match base.cat {
1347                     Categorization::Upvar(Upvar{ id, .. }) =>
1348                         FreelyAliasable(AliasableClosure(id.closure_expr_id)),
1349                     _ => FreelyAliasable(AliasableBorrowed)
1350                 }
1351             }
1352         }
1353     }
1354
1355     // Digs down through one or two layers of deref and grabs the cmt
1356     // for the upvar if a note indicates there is one.
1357     pub fn upvar(&self) -> Option<cmt<'tcx>> {
1358         match self.note {
1359             NoteClosureEnv(..) | NoteUpvarRef(..) => {
1360                 Some(match self.cat {
1361                     Categorization::Deref(ref inner, ..) => {
1362                         match inner.cat {
1363                             Categorization::Deref(ref inner, ..) => inner.clone(),
1364                             Categorization::Upvar(..) => inner.clone(),
1365                             _ => bug!()
1366                         }
1367                     }
1368                     _ => bug!()
1369                 })
1370             }
1371             NoteNone => None
1372         }
1373     }
1374
1375
1376     pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1377         match self.cat {
1378             Categorization::StaticItem => {
1379                 "static item".to_string()
1380             }
1381             Categorization::Rvalue(..) => {
1382                 "non-lvalue".to_string()
1383             }
1384             Categorization::Local(vid) => {
1385                 if tcx.hir.is_argument(vid) {
1386                     "argument".to_string()
1387                 } else {
1388                     "local variable".to_string()
1389                 }
1390             }
1391             Categorization::Deref(.., pk) => {
1392                 let upvar = self.upvar();
1393                 match upvar.as_ref().map(|i| &i.cat) {
1394                     Some(&Categorization::Upvar(ref var)) => {
1395                         var.to_string()
1396                     }
1397                     Some(_) => bug!(),
1398                     None => {
1399                         match pk {
1400                             Implicit(..) => {
1401                                 format!("indexed content")
1402                             }
1403                             Unique => {
1404                                 format!("`Box` content")
1405                             }
1406                             UnsafePtr(..) => {
1407                                 format!("dereference of raw pointer")
1408                             }
1409                             BorrowedPtr(..) => {
1410                                 format!("borrowed content")
1411                             }
1412                         }
1413                     }
1414                 }
1415             }
1416             Categorization::Interior(_, InteriorField(NamedField(_))) => {
1417                 "field".to_string()
1418             }
1419             Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1420                 "anonymous field".to_string()
1421             }
1422             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1423                                                         VecElement)) |
1424             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1425                                                         OtherElement)) => {
1426                 "indexed content".to_string()
1427             }
1428             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1429                                                         VecElement)) |
1430             Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1431                                                         OtherElement)) => {
1432                 "pattern-bound indexed content".to_string()
1433             }
1434             Categorization::Upvar(ref var) => {
1435                 var.to_string()
1436             }
1437             Categorization::Downcast(ref cmt, _) => {
1438                 cmt.descriptive_string(tcx)
1439             }
1440         }
1441     }
1442 }
1443
1444 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1445     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1446         write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1447                self.cat,
1448                self.id,
1449                self.mutbl,
1450                self.ty)
1451     }
1452 }
1453
1454 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1455     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1456         match *self {
1457             Categorization::StaticItem => write!(f, "static"),
1458             Categorization::Rvalue(r, or) => {
1459                 write!(f, "rvalue({:?}, {:?})", r, or)
1460             }
1461             Categorization::Local(id) => {
1462                let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1463                write!(f, "local({})", name)
1464             }
1465             Categorization::Upvar(upvar) => {
1466                 write!(f, "upvar({:?})", upvar)
1467             }
1468             Categorization::Deref(ref cmt, derefs, ptr) => {
1469                 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1470             }
1471             Categorization::Interior(ref cmt, interior) => {
1472                 write!(f, "{:?}.{:?}", cmt.cat, interior)
1473             }
1474             Categorization::Downcast(ref cmt, _) => {
1475                 write!(f, "{:?}->(enum)", cmt.cat)
1476             }
1477         }
1478     }
1479 }
1480
1481 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1482     match ptr {
1483         Unique => "Box",
1484         BorrowedPtr(ty::ImmBorrow, _) |
1485         Implicit(ty::ImmBorrow, _) => "&",
1486         BorrowedPtr(ty::MutBorrow, _) |
1487         Implicit(ty::MutBorrow, _) => "&mut",
1488         BorrowedPtr(ty::UniqueImmBorrow, _) |
1489         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1490         UnsafePtr(_) => "*",
1491     }
1492 }
1493
1494 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1495     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1496         match *self {
1497             Unique => write!(f, "Box"),
1498             BorrowedPtr(ty::ImmBorrow, ref r) |
1499             Implicit(ty::ImmBorrow, ref r) => {
1500                 write!(f, "&{:?}", r)
1501             }
1502             BorrowedPtr(ty::MutBorrow, ref r) |
1503             Implicit(ty::MutBorrow, ref r) => {
1504                 write!(f, "&{:?} mut", r)
1505             }
1506             BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1507             Implicit(ty::UniqueImmBorrow, ref r) => {
1508                 write!(f, "&{:?} uniq", r)
1509             }
1510             UnsafePtr(_) => write!(f, "*")
1511         }
1512     }
1513 }
1514
1515 impl fmt::Debug for InteriorKind {
1516     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1517         match *self {
1518             InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1519             InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1520             InteriorElement(..) => write!(f, "[]"),
1521         }
1522     }
1523 }
1524
1525 impl fmt::Debug for Upvar {
1526     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1527         write!(f, "{:?}/{:?}", self.id, self.kind)
1528     }
1529 }
1530
1531 impl fmt::Display for Upvar {
1532     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1533         let kind = match self.kind {
1534             ty::ClosureKind::Fn => "Fn",
1535             ty::ClosureKind::FnMut => "FnMut",
1536             ty::ClosureKind::FnOnce => "FnOnce",
1537         };
1538         write!(f, "captured outer variable in an `{}` closure", kind)
1539     }
1540 }