]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
auto merge of #17341 : alexcrichton/rust/unignore, r=brson
[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 /*!
12  * # Categorization
13  *
14  * The job of the categorization module is to analyze an expression to
15  * determine what kind of memory is used in evaluating it (for example,
16  * where dereferences occur and what kind of pointer is dereferenced;
17  * whether the memory is mutable; etc)
18  *
19  * Categorization effectively transforms all of our expressions into
20  * expressions of the following forms (the actual enum has many more
21  * possibilities, naturally, but they are all variants of these base
22  * forms):
23  *
24  *     E = rvalue    // some computed rvalue
25  *       | x         // address of a local variable or argument
26  *       | *E        // deref of a ptr
27  *       | E.comp    // access to an interior component
28  *
29  * Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
30  * address where the result is to be found.  If Expr is an lvalue, then this
31  * is the address of the lvalue.  If Expr is an rvalue, this is the address of
32  * some temporary spot in memory where the result is stored.
33  *
34  * Now, cat_expr() classifies the expression Expr and the address A=ToAddr(Expr)
35  * as follows:
36  *
37  * - cat: what kind of expression was this?  This is a subset of the
38  *   full expression forms which only includes those that we care about
39  *   for the purpose of the analysis.
40  * - mutbl: mutability of the address A
41  * - ty: the type of data found at the address A
42  *
43  * The resulting categorization tree differs somewhat from the expressions
44  * themselves.  For example, auto-derefs are explicit.  Also, an index a[b] is
45  * decomposed into two operations: a dereference to reach the array data and
46  * then an index to jump forward to the relevant item.
47  *
48  * ## By-reference upvars
49  *
50  * One part of the translation which may be non-obvious is that we translate
51  * closure upvars into the dereference of a borrowed pointer; this more closely
52  * resembles the runtime translation. So, for example, if we had:
53  *
54  *     let mut x = 3;
55  *     let y = 5;
56  *     let inc = || x += y;
57  *
58  * Then when we categorize `x` (*within* the closure) we would yield a
59  * result of `*x'`, effectively, where `x'` is a `cat_upvar` reference
60  * tied to `x`. The type of `x'` will be a borrowed pointer.
61  */
62
63 #![allow(non_camel_case_types)]
64
65 use middle::def;
66 use middle::freevars;
67 use middle::ty;
68 use middle::typeck;
69 use util::nodemap::{DefIdMap, NodeMap};
70 use util::ppaux::{ty_to_string, Repr};
71
72 use syntax::ast::{MutImmutable, MutMutable};
73 use syntax::ast;
74 use syntax::codemap::Span;
75 use syntax::print::pprust;
76 use syntax::parse::token;
77
78 use std::cell::RefCell;
79 use std::rc::Rc;
80
81 #[deriving(Clone, PartialEq)]
82 pub enum categorization {
83     cat_rvalue(ty::Region),            // temporary val, argument is its scope
84     cat_static_item,
85     cat_copied_upvar(CopiedUpvar),     // upvar copied into proc env
86     cat_upvar(ty::UpvarId, ty::UpvarBorrow), // by ref upvar from stack closure
87     cat_local(ast::NodeId),            // local variable
88     cat_arg(ast::NodeId),              // formal argument
89     cat_deref(cmt, uint, PointerKind), // deref of a ptr
90     cat_interior(cmt, InteriorKind),   // something interior: field, tuple, etc
91     cat_downcast(cmt),                 // selects a particular enum variant (*1)
92     cat_discr(cmt, ast::NodeId),       // match discriminant (see preserve())
93
94     // (*1) downcast is only required if the enum has more than one variant
95 }
96
97 #[deriving(Clone, PartialEq)]
98 pub struct CopiedUpvar {
99     pub upvar_id: ast::NodeId,
100     pub onceness: ast::Onceness,
101     pub capturing_proc: ast::NodeId,
102 }
103
104 // different kinds of pointers:
105 #[deriving(Clone, PartialEq, Eq, Hash)]
106 pub enum PointerKind {
107     OwnedPtr,
108     GcPtr,
109     BorrowedPtr(ty::BorrowKind, ty::Region),
110     Implicit(ty::BorrowKind, ty::Region),     // Implicit deref of a borrowed ptr.
111     UnsafePtr(ast::Mutability)
112 }
113
114 // We use the term "interior" to mean "something reachable from the
115 // base without a pointer dereference", e.g. a field
116 #[deriving(Clone, PartialEq, Eq, Hash)]
117 pub enum InteriorKind {
118     InteriorField(FieldName),
119     InteriorElement(ElementKind),
120 }
121
122 #[deriving(Clone, PartialEq, Eq, Hash)]
123 pub enum FieldName {
124     NamedField(ast::Name),
125     PositionalField(uint)
126 }
127
128 #[deriving(Clone, PartialEq, Eq, Hash)]
129 pub enum ElementKind {
130     VecElement,
131     OtherElement,
132 }
133
134 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
135 pub enum MutabilityCategory {
136     McImmutable, // Immutable.
137     McDeclared,  // Directly declared as mutable.
138     McInherited, // Inherited from the fact that owner is mutable.
139 }
140
141 // `cmt`: "Category, Mutability, and Type".
142 //
143 // a complete categorization of a value indicating where it originated
144 // and how it is located, as well as the mutability of the memory in
145 // which the value is stored.
146 //
147 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
148 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
149 // always the `id` of the node producing the type; in an expression
150 // like `*x`, the type of this deref node is the deref'd type (`T`),
151 // but in a pattern like `@x`, the `@x` pattern is again a
152 // dereference, but its type is the type *before* the dereference
153 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
154 // fashion. For more details, see the method `cat_pattern`
155 #[deriving(Clone, PartialEq)]
156 pub struct cmt_ {
157     pub id: ast::NodeId,          // id of expr/pat producing this value
158     pub span: Span,                // span of same expr/pat
159     pub cat: categorization,       // categorization of expr
160     pub mutbl: MutabilityCategory, // mutability of expr as lvalue
161     pub ty: ty::t                  // type of the expr (*see WARNING above*)
162 }
163
164 pub type cmt = Rc<cmt_>;
165
166 // We pun on *T to mean both actual deref of a ptr as well
167 // as accessing of components:
168 pub enum deref_kind {
169     deref_ptr(PointerKind),
170     deref_interior(InteriorKind),
171 }
172
173 // Categorizes a derefable type.  Note that we include vectors and strings as
174 // derefable (we model an index as the combination of a deref and then a
175 // pointer adjustment).
176 pub fn opt_deref_kind(t: ty::t) -> Option<deref_kind> {
177     match ty::get(t).sty {
178         ty::ty_uniq(_) |
179         ty::ty_closure(box ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
180             Some(deref_ptr(OwnedPtr))
181         }
182
183         ty::ty_rptr(r, mt) => {
184             let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
185             Some(deref_ptr(BorrowedPtr(kind, r)))
186         }
187
188         ty::ty_closure(box ty::ClosureTy {
189                 store: ty::RegionTraitStore(r, _),
190                 ..
191             }) => {
192             Some(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
193         }
194
195         ty::ty_box(..) => {
196             Some(deref_ptr(GcPtr))
197         }
198
199         ty::ty_ptr(ref mt) => {
200             Some(deref_ptr(UnsafePtr(mt.mutbl)))
201         }
202
203         ty::ty_enum(..) |
204         ty::ty_struct(..) => { // newtype
205             Some(deref_interior(InteriorField(PositionalField(0))))
206         }
207
208         ty::ty_vec(_, _) | ty::ty_str => {
209             Some(deref_interior(InteriorElement(element_kind(t))))
210         }
211
212         _ => None
213     }
214 }
215
216 pub fn deref_kind(tcx: &ty::ctxt, t: ty::t) -> deref_kind {
217     debug!("deref_kind {}", ty_to_string(tcx, t));
218     match opt_deref_kind(t) {
219       Some(k) => k,
220       None => {
221         tcx.sess.bug(
222             format!("deref_kind() invoked on non-derefable type {}",
223                     ty_to_string(tcx, t)).as_slice());
224       }
225     }
226 }
227
228 trait ast_node {
229     fn id(&self) -> ast::NodeId;
230     fn span(&self) -> Span;
231 }
232
233 impl ast_node for ast::Expr {
234     fn id(&self) -> ast::NodeId { self.id }
235     fn span(&self) -> Span { self.span }
236 }
237
238 impl ast_node for ast::Pat {
239     fn id(&self) -> ast::NodeId { self.id }
240     fn span(&self) -> Span { self.span }
241 }
242
243 pub struct MemCategorizationContext<'t,TYPER:'t> {
244     typer: &'t TYPER
245 }
246
247 pub type McResult<T> = Result<T, ()>;
248
249 /**
250  * The `Typer` trait provides the interface for the mem-categorization
251  * module to the results of the type check. It can be used to query
252  * the type assigned to an expression node, to inquire after adjustments,
253  * and so on.
254  *
255  * This interface is needed because mem-categorization is used from
256  * two places: `regionck` and `borrowck`. `regionck` executes before
257  * type inference is complete, and hence derives types and so on from
258  * intermediate tables.  This also implies that type errors can occur,
259  * and hence `node_ty()` and friends return a `Result` type -- any
260  * error will propagate back up through the mem-categorization
261  * routines.
262  *
263  * In the borrow checker, in contrast, type checking is complete and we
264  * know that no errors have occurred, so we simply consult the tcx and we
265  * can be sure that only `Ok` results will occur.
266  */
267 pub trait Typer<'tcx> {
268     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
269     fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t>;
270     fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t>;
271     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>>;
272     fn is_method_call(&self, id: ast::NodeId) -> bool;
273     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId>;
274     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow;
275     fn capture_mode(&self, closure_expr_id: ast::NodeId)
276                     -> freevars::CaptureMode;
277     fn unboxed_closures<'a>(&'a self)
278                         -> &'a RefCell<DefIdMap<ty::UnboxedClosure>>;
279 }
280
281 impl MutabilityCategory {
282     pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
283         match m {
284             MutImmutable => McImmutable,
285             MutMutable => McDeclared
286         }
287     }
288
289     pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
290         match borrow_kind {
291             ty::ImmBorrow => McImmutable,
292             ty::UniqueImmBorrow => McImmutable,
293             ty::MutBorrow => McDeclared,
294         }
295     }
296
297     pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
298                              ptr: PointerKind) -> MutabilityCategory {
299         match ptr {
300             OwnedPtr => {
301                 base_mutbl.inherit()
302             }
303             BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
304                 MutabilityCategory::from_borrow_kind(borrow_kind)
305             }
306             GcPtr => {
307                 McImmutable
308             }
309             UnsafePtr(m) => {
310                 MutabilityCategory::from_mutbl(m)
311             }
312         }
313     }
314
315     fn from_def(def: &def::Def) -> MutabilityCategory {
316         match *def {
317             def::DefFn(..) | def::DefStaticMethod(..) | def::DefSelfTy(..) |
318             def::DefMod(..) | def::DefForeignMod(..) | def::DefVariant(..) |
319             def::DefTy(..) | def::DefTrait(..) | def::DefPrimTy(..) |
320             def::DefTyParam(..) | def::DefUse(..) | def::DefStruct(..) |
321             def::DefTyParamBinder(..) | def::DefRegion(..) | def::DefLabel(..) |
322             def::DefMethod(..) | def::DefAssociatedTy(..) => {
323                 fail!("no MutabilityCategory for def: {}", *def)
324             }
325
326             def::DefStatic(_, false) => McImmutable,
327             def::DefStatic(_, true) => McDeclared,
328
329             def::DefArg(_, binding_mode) |
330             def::DefBinding(_, binding_mode) |
331             def::DefLocal(_, binding_mode)  => match binding_mode {
332                 ast::BindByValue(ast::MutMutable) => McDeclared,
333                 _ => McImmutable
334             },
335
336             def::DefUpvar(_, def, _, _) => MutabilityCategory::from_def(&*def)
337         }
338     }
339
340     pub fn inherit(&self) -> MutabilityCategory {
341         match *self {
342             McImmutable => McImmutable,
343             McDeclared => McInherited,
344             McInherited => McInherited,
345         }
346     }
347
348     pub fn is_mutable(&self) -> bool {
349         match *self {
350             McImmutable => false,
351             McInherited => true,
352             McDeclared => true,
353         }
354     }
355
356     pub fn is_immutable(&self) -> bool {
357         match *self {
358             McImmutable => true,
359             McDeclared | McInherited => false
360         }
361     }
362
363     pub fn to_user_str(&self) -> &'static str {
364         match *self {
365             McDeclared | McInherited => "mutable",
366             McImmutable => "immutable",
367         }
368     }
369 }
370
371 macro_rules! if_ok(
372     ($inp: expr) => (
373         match $inp {
374             Ok(v) => { v }
375             Err(e) => { return Err(e); }
376         }
377     )
378 )
379
380 impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
381     pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
382         MemCategorizationContext { typer: typer }
383     }
384
385     fn tcx(&self) -> &'t ty::ctxt<'tcx> {
386         self.typer.tcx()
387     }
388
389     fn expr_ty(&self, expr: &ast::Expr) -> McResult<ty::t> {
390         self.typer.node_ty(expr.id)
391     }
392
393     fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<ty::t> {
394         let unadjusted_ty = if_ok!(self.expr_ty(expr));
395         Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
396                          self.typer.adjustments().borrow().find(&expr.id),
397                          |method_call| self.typer.node_method_ty(method_call)))
398     }
399
400     fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t> {
401         self.typer.node_ty(id)
402     }
403
404     fn pat_ty(&self, pat: &ast::Pat) -> McResult<ty::t> {
405         self.typer.node_ty(pat.id)
406     }
407
408     pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt> {
409         match self.typer.adjustments().borrow().find(&expr.id) {
410             None => {
411                 // No adjustments.
412                 self.cat_expr_unadjusted(expr)
413             }
414
415             Some(adjustment) => {
416                 match *adjustment {
417                     ty::AutoAddEnv(..) => {
418                         // Convert a bare fn to a closure by adding NULL env.
419                         // Result is an rvalue.
420                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
421                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
422                     }
423
424                     ty::AutoDerefRef(
425                         ty::AutoDerefRef {
426                             autoref: Some(_), ..}) => {
427                         // Equivalent to &*expr or something similar.
428                         // Result is an rvalue.
429                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
430                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
431                     }
432
433                     ty::AutoDerefRef(
434                         ty::AutoDerefRef {
435                             autoref: None, autoderefs: autoderefs}) => {
436                         // Equivalent to *expr or something similar.
437                         self.cat_expr_autoderefd(expr, autoderefs)
438                     }
439                 }
440             }
441         }
442     }
443
444     pub fn cat_expr_autoderefd(&self,
445                                expr: &ast::Expr,
446                                autoderefs: uint)
447                                -> McResult<cmt> {
448         let mut cmt = if_ok!(self.cat_expr_unadjusted(expr));
449         for deref in range(1u, autoderefs + 1) {
450             cmt = self.cat_deref(expr, cmt, deref, false);
451         }
452         return Ok(cmt);
453     }
454
455     pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt> {
456         debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
457
458         let expr_ty = if_ok!(self.expr_ty(expr));
459         match expr.node {
460           ast::ExprUnary(ast::UnDeref, ref e_base) => {
461             let base_cmt = if_ok!(self.cat_expr(&**e_base));
462             Ok(self.cat_deref(expr, base_cmt, 0, false))
463           }
464
465           ast::ExprField(ref base, f_name, _) => {
466             let base_cmt = if_ok!(self.cat_expr(&**base));
467             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
468           }
469
470           ast::ExprTupField(ref base, idx, _) => {
471             let base_cmt = if_ok!(self.cat_expr(&**base));
472             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
473           }
474
475           ast::ExprIndex(ref base, _) => {
476             let method_call = typeck::MethodCall::expr(expr.id());
477             match self.typer.node_method_ty(method_call) {
478                 Some(method_ty) => {
479                     // If this is an index implemented by a method call, then it will
480                     // include an implicit deref of the result.
481                     let ret_ty = ty::ty_fn_ret(method_ty);
482                     Ok(self.cat_deref(expr,
483                                       self.cat_rvalue_node(expr.id(),
484                                                            expr.span(),
485                                                            ret_ty), 1, true))
486                 }
487                 None => {
488                     let base_cmt = if_ok!(self.cat_expr(&**base));
489                     Ok(self.cat_index(expr, base_cmt))
490                 }
491             }
492           }
493
494           ast::ExprPath(_) => {
495             let def = *self.tcx().def_map.borrow().get(&expr.id);
496             self.cat_def(expr.id, expr.span, expr_ty, def)
497           }
498
499           ast::ExprParen(ref e) => {
500             self.cat_expr(&**e)
501           }
502
503           ast::ExprAddrOf(..) | ast::ExprCall(..) |
504           ast::ExprAssign(..) | ast::ExprAssignOp(..) |
505           ast::ExprFnBlock(..) | ast::ExprProc(..) |
506           ast::ExprUnboxedFn(..) | ast::ExprRet(..) |
507           ast::ExprUnary(..) |
508           ast::ExprMethodCall(..) | ast::ExprCast(..) |
509           ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
510           ast::ExprBinary(..) | ast::ExprWhile(..) |
511           ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
512           ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
513           ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
514           ast::ExprInlineAsm(..) | ast::ExprBox(..) |
515           ast::ExprForLoop(..) => {
516             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
517           }
518         }
519     }
520
521     pub fn cat_def(&self,
522                    id: ast::NodeId,
523                    span: Span,
524                    expr_ty: ty::t,
525                    def: def::Def)
526                    -> McResult<cmt> {
527         debug!("cat_def: id={} expr={} def={:?}",
528                id, expr_ty.repr(self.tcx()), def);
529
530         match def {
531           def::DefStruct(..) | def::DefVariant(..) | def::DefFn(..) |
532           def::DefStaticMethod(..) => {
533                 Ok(self.cat_rvalue_node(id, span, expr_ty))
534           }
535           def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
536           def::DefTrait(_) | def::DefTy(..) | def::DefPrimTy(_) |
537           def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
538           def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) |
539           def::DefAssociatedTy(..) => {
540               Ok(Rc::new(cmt_ {
541                   id:id,
542                   span:span,
543                   cat:cat_static_item,
544                   mutbl: McImmutable,
545                   ty:expr_ty
546               }))
547           }
548
549           def::DefStatic(_, _) => {
550               Ok(Rc::new(cmt_ {
551                   id:id,
552                   span:span,
553                   cat:cat_static_item,
554                   mutbl: MutabilityCategory::from_def(&def),
555                   ty:expr_ty
556               }))
557           }
558
559           def::DefArg(vid, _) => {
560             // Idea: make this could be rewritten to model by-ref
561             // stuff as `&const` and `&mut`?
562
563             Ok(Rc::new(cmt_ {
564                 id: id,
565                 span: span,
566                 cat: cat_arg(vid),
567                 mutbl: MutabilityCategory::from_def(&def),
568                 ty:expr_ty
569             }))
570           }
571
572           def::DefUpvar(var_id, _, fn_node_id, _) => {
573               let ty = if_ok!(self.node_ty(fn_node_id));
574               match ty::get(ty).sty {
575                   ty::ty_closure(ref closure_ty) => {
576                       // Decide whether to use implicit reference or by copy/move
577                       // capture for the upvar. This, combined with the onceness,
578                       // determines whether the closure can move out of it.
579                       let var_is_refd = match (closure_ty.store, closure_ty.onceness) {
580                           // Many-shot stack closures can never move out.
581                           (ty::RegionTraitStore(..), ast::Many) => true,
582                           // 1-shot stack closures can move out.
583                           (ty::RegionTraitStore(..), ast::Once) => false,
584                           // Heap closures always capture by copy/move, and can
585                           // move out if they are once.
586                           (ty::UniqTraitStore, _) => false,
587
588                       };
589                       if var_is_refd {
590                           self.cat_upvar(id, span, var_id, fn_node_id)
591                       } else {
592                           Ok(Rc::new(cmt_ {
593                               id:id,
594                               span:span,
595                               cat:cat_copied_upvar(CopiedUpvar {
596                                   upvar_id: var_id,
597                                   onceness: closure_ty.onceness,
598                                   capturing_proc: fn_node_id,
599                               }),
600                               mutbl: MutabilityCategory::from_def(&def),
601                               ty:expr_ty
602                           }))
603                       }
604                   }
605                   ty::ty_unboxed_closure(closure_id, _) => {
606                       let unboxed_closures = self.typer
607                                                  .unboxed_closures()
608                                                  .borrow();
609                       let kind = unboxed_closures.get(&closure_id).kind;
610                       let onceness = match kind {
611                           ty::FnUnboxedClosureKind |
612                           ty::FnMutUnboxedClosureKind => ast::Many,
613                           ty::FnOnceUnboxedClosureKind => ast::Once,
614                       };
615                       Ok(Rc::new(cmt_ {
616                           id: id,
617                           span: span,
618                           cat: cat_copied_upvar(CopiedUpvar {
619                               upvar_id: var_id,
620                               onceness: onceness,
621                               capturing_proc: fn_node_id,
622                           }),
623                           mutbl: MutabilityCategory::from_def(&def),
624                           ty: expr_ty
625                       }))
626                   }
627                   _ => {
628                       self.tcx().sess.span_bug(
629                           span,
630                           format!("Upvar of non-closure {} - {}",
631                                   fn_node_id,
632                                   ty.repr(self.tcx())).as_slice());
633                   }
634               }
635           }
636
637           def::DefLocal(vid, _) |
638           def::DefBinding(vid, _) => {
639             // by-value/by-ref bindings are local variables
640             Ok(Rc::new(cmt_ {
641                 id: id,
642                 span: span,
643                 cat: cat_local(vid),
644                 mutbl: MutabilityCategory::from_def(&def),
645                 ty: expr_ty
646             }))
647           }
648         }
649     }
650
651     fn cat_upvar(&self,
652                  id: ast::NodeId,
653                  span: Span,
654                  var_id: ast::NodeId,
655                  fn_node_id: ast::NodeId)
656                  -> McResult<cmt> {
657         /*!
658          * Upvars through a closure are in fact indirect
659          * references. That is, when a closure refers to a
660          * variable from a parent stack frame like `x = 10`,
661          * that is equivalent to `*x_ = 10` where `x_` is a
662          * borrowed pointer (`&mut x`) created when the closure
663          * was created and store in the environment. This
664          * equivalence is expose in the mem-categorization.
665          */
666
667         let upvar_id = ty::UpvarId { var_id: var_id,
668                                      closure_expr_id: fn_node_id };
669
670         let upvar_borrow = self.typer.upvar_borrow(upvar_id);
671
672         let var_ty = if_ok!(self.node_ty(var_id));
673
674         // We can't actually represent the types of all upvars
675         // as user-describable types, since upvars support const
676         // and unique-imm borrows! Therefore, we cheat, and just
677         // give err type. Nobody should be inspecting this type anyhow.
678         let upvar_ty = ty::mk_err();
679
680         let base_cmt = Rc::new(cmt_ {
681             id:id,
682             span:span,
683             cat:cat_upvar(upvar_id, upvar_borrow),
684             mutbl:McImmutable,
685             ty:upvar_ty,
686         });
687
688         let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
689
690         let deref_cmt = Rc::new(cmt_ {
691             id:id,
692             span:span,
693             cat:cat_deref(base_cmt, 0, ptr),
694             mutbl:MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
695             ty:var_ty,
696         });
697
698         Ok(deref_cmt)
699     }
700
701     pub fn cat_rvalue_node(&self,
702                            id: ast::NodeId,
703                            span: Span,
704                            expr_ty: ty::t)
705                            -> cmt {
706         match self.typer.temporary_scope(id) {
707             Some(scope) => {
708                 match ty::get(expr_ty).sty {
709                     ty::ty_vec(_, Some(0)) => self.cat_rvalue(id, span, ty::ReStatic, expr_ty),
710                     _ => self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
711                 }
712             }
713             None => {
714                 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
715             }
716         }
717     }
718
719     pub fn cat_rvalue(&self,
720                       cmt_id: ast::NodeId,
721                       span: Span,
722                       temp_scope: ty::Region,
723                       expr_ty: ty::t) -> cmt {
724         Rc::new(cmt_ {
725             id:cmt_id,
726             span:span,
727             cat:cat_rvalue(temp_scope),
728             mutbl:McDeclared,
729             ty:expr_ty
730         })
731     }
732
733     pub fn cat_field<N:ast_node>(&self,
734                                  node: &N,
735                                  base_cmt: cmt,
736                                  f_name: ast::Ident,
737                                  f_ty: ty::t)
738                                  -> cmt {
739         Rc::new(cmt_ {
740             id: node.id(),
741             span: node.span(),
742             mutbl: base_cmt.mutbl.inherit(),
743             cat: cat_interior(base_cmt, InteriorField(NamedField(f_name.name))),
744             ty: f_ty
745         })
746     }
747
748     pub fn cat_tup_field<N:ast_node>(&self,
749                                      node: &N,
750                                      base_cmt: cmt,
751                                      f_idx: uint,
752                                      f_ty: ty::t)
753                                      -> cmt {
754         Rc::new(cmt_ {
755             id: node.id(),
756             span: node.span(),
757             mutbl: base_cmt.mutbl.inherit(),
758             cat: cat_interior(base_cmt, InteriorField(PositionalField(f_idx))),
759             ty: f_ty
760         })
761     }
762
763     pub fn cat_deref_obj<N:ast_node>(&self, node: &N, base_cmt: cmt) -> cmt {
764         self.cat_deref_common(node, base_cmt, 0, ty::mk_nil(), false)
765     }
766
767     fn cat_deref<N:ast_node>(&self,
768                              node: &N,
769                              base_cmt: cmt,
770                              deref_cnt: uint,
771                              implicit: bool)
772                              -> cmt {
773         let adjustment = match self.typer.adjustments().borrow().find(&node.id()) {
774             Some(adj) if ty::adjust_is_object(adj) => typeck::AutoObject,
775             _ if deref_cnt != 0 => typeck::AutoDeref(deref_cnt),
776             _ => typeck::NoAdjustment
777         };
778
779         let method_call = typeck::MethodCall {
780             expr_id: node.id(),
781             adjustment: adjustment
782         };
783         let method_ty = self.typer.node_method_ty(method_call);
784
785         debug!("cat_deref: method_call={:?} method_ty={}",
786             method_call, method_ty.map(|ty| ty.repr(self.tcx())));
787
788         let base_cmt = match method_ty {
789             Some(method_ty) => {
790                 let ref_ty = ty::ty_fn_ret(method_ty);
791                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
792             }
793             None => base_cmt
794         };
795         match ty::deref(base_cmt.ty, true) {
796             Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, implicit),
797             None => {
798                 self.tcx().sess.span_bug(
799                     node.span(),
800                     format!("Explicit deref of non-derefable type: {}",
801                             base_cmt.ty.repr(self.tcx())).as_slice());
802             }
803         }
804     }
805
806     fn cat_deref_common<N:ast_node>(&self,
807                                     node: &N,
808                                     base_cmt: cmt,
809                                     deref_cnt: uint,
810                                     deref_ty: ty::t,
811                                     implicit: bool)
812                                     -> cmt {
813         let (m, cat) = match deref_kind(self.tcx(), base_cmt.ty) {
814             deref_ptr(ptr) => {
815                 let ptr = if implicit {
816                     match ptr {
817                         BorrowedPtr(bk, r) => Implicit(bk, r),
818                         _ => self.tcx().sess.span_bug(node.span(),
819                             "Implicit deref of non-borrowed pointer")
820                     }
821                 } else {
822                     ptr
823                 };
824                 // for unique ptrs, we inherit mutability from the
825                 // owning reference.
826                 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
827                  cat_deref(base_cmt, deref_cnt, ptr))
828             }
829             deref_interior(interior) => {
830                 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
831             }
832         };
833         Rc::new(cmt_ {
834             id: node.id(),
835             span: node.span(),
836             cat: cat,
837             mutbl: m,
838             ty: deref_ty
839         })
840     }
841
842     pub fn cat_index<N:ast_node>(&self,
843                                  elt: &N,
844                                  mut base_cmt: cmt)
845                                  -> cmt {
846         //! Creates a cmt for an indexing operation (`[]`).
847         //!
848         //! One subtle aspect of indexing that may not be
849         //! immediately obvious: for anything other than a fixed-length
850         //! vector, an operation like `x[y]` actually consists of two
851         //! disjoint (from the point of view of borrowck) operations.
852         //! The first is a deref of `x` to create a pointer `p` that points
853         //! at the first element in the array. The second operation is
854         //! an index which adds `y*sizeof(T)` to `p` to obtain the
855         //! pointer to `x[y]`. `cat_index` will produce a resulting
856         //! cmt containing both this deref and the indexing,
857         //! presuming that `base_cmt` is not of fixed-length type.
858         //!
859         //! # Parameters
860         //! - `elt`: the AST node being indexed
861         //! - `base_cmt`: the cmt of `elt`
862
863         let method_call = typeck::MethodCall::expr(elt.id());
864         let method_ty = self.typer.node_method_ty(method_call);
865
866         let element_ty = match method_ty {
867             Some(method_ty) => {
868                 let ref_ty = ty::ty_fn_ret(method_ty);
869                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
870                 *ty::ty_fn_args(method_ty).get(0)
871             }
872             None => {
873                 match ty::array_element_ty(base_cmt.ty) {
874                     Some(ty) => ty,
875                     None => {
876                         self.tcx().sess.span_bug(
877                             elt.span(),
878                             format!("Explicit index of non-index type `{}`",
879                                     base_cmt.ty.repr(self.tcx())).as_slice());
880                     }
881                 }
882             }
883         };
884
885         let m = base_cmt.mutbl.inherit();
886         return interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty);
887
888         fn interior<N: ast_node>(elt: &N,
889                                  of_cmt: cmt,
890                                  vec_ty: ty::t,
891                                  mutbl: MutabilityCategory,
892                                  element_ty: ty::t) -> cmt
893         {
894             Rc::new(cmt_ {
895                 id:elt.id(),
896                 span:elt.span(),
897                 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
898                 mutbl:mutbl,
899                 ty:element_ty
900             })
901         }
902     }
903
904     // Takes either a vec or a reference to a vec and returns the cmt for the
905     // underlying vec.
906     fn deref_vec<N:ast_node>(&self,
907                              elt: &N,
908                              base_cmt: cmt)
909                              -> cmt {
910         match deref_kind(self.tcx(), base_cmt.ty) {
911             deref_ptr(ptr) => {
912                 // for unique ptrs, we inherit mutability from the
913                 // owning reference.
914                 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
915
916                 // the deref is explicit in the resulting cmt
917                 Rc::new(cmt_ {
918                     id:elt.id(),
919                     span:elt.span(),
920                     cat:cat_deref(base_cmt.clone(), 0, ptr),
921                     mutbl:m,
922                     ty: match ty::deref(base_cmt.ty, false) {
923                         Some(mt) => mt.ty,
924                         None => self.tcx().sess.bug("Found non-derefable type")
925                     }
926                 })
927             }
928
929             deref_interior(_) => {
930                 base_cmt
931             }
932         }
933     }
934
935     pub fn cat_slice_pattern(&self,
936                              vec_cmt: cmt,
937                              slice_pat: &ast::Pat)
938                              -> McResult<(cmt, ast::Mutability, ty::Region)> {
939         /*!
940          * Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is
941          * the cmt for `P`, `slice_pat` is the pattern `Q`, returns:
942          * - a cmt for `Q`
943          * - the mutability and region of the slice `Q`
944          *
945          * These last two bits of info happen to be things that
946          * borrowck needs.
947          */
948
949         let slice_ty = if_ok!(self.node_ty(slice_pat.id));
950         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
951                                                     slice_pat,
952                                                     slice_ty);
953         let cmt_slice = self.cat_index(slice_pat, self.deref_vec(slice_pat, vec_cmt));
954         return Ok((cmt_slice, slice_mutbl, slice_r));
955
956         fn vec_slice_info(tcx: &ty::ctxt,
957                           pat: &ast::Pat,
958                           slice_ty: ty::t)
959                           -> (ast::Mutability, ty::Region) {
960             /*!
961              * In a pattern like [a, b, ..c], normally `c` has slice type,
962              * but if you have [a, b, ..ref c], then the type of `ref c`
963              * will be `&&[]`, so to extract the slice details we have
964              * to recurse through rptrs.
965              */
966
967             match ty::get(slice_ty).sty {
968                 ty::ty_rptr(r, ref mt) => match ty::get(mt.ty).sty {
969                     ty::ty_vec(_, None) => (mt.mutbl, r),
970                     _ => vec_slice_info(tcx, pat, mt.ty),
971                 },
972
973                 _ => {
974                     tcx.sess.span_bug(pat.span,
975                                       "type of slice pattern is not a slice");
976                 }
977             }
978         }
979     }
980
981     pub fn cat_imm_interior<N:ast_node>(&self,
982                                         node: &N,
983                                         base_cmt: cmt,
984                                         interior_ty: ty::t,
985                                         interior: InteriorKind)
986                                         -> cmt {
987         Rc::new(cmt_ {
988             id: node.id(),
989             span: node.span(),
990             mutbl: base_cmt.mutbl.inherit(),
991             cat: cat_interior(base_cmt, interior),
992             ty: interior_ty
993         })
994     }
995
996     pub fn cat_downcast<N:ast_node>(&self,
997                                     node: &N,
998                                     base_cmt: cmt,
999                                     downcast_ty: ty::t)
1000                                     -> cmt {
1001         Rc::new(cmt_ {
1002             id: node.id(),
1003             span: node.span(),
1004             mutbl: base_cmt.mutbl.inherit(),
1005             cat: cat_downcast(base_cmt),
1006             ty: downcast_ty
1007         })
1008     }
1009
1010     pub fn cat_pattern(&self,
1011                        cmt: cmt,
1012                        pat: &ast::Pat,
1013                        op: |&MemCategorizationContext<TYPER>,
1014                             cmt,
1015                             &ast::Pat|)
1016                        -> McResult<()> {
1017         // Here, `cmt` is the categorization for the value being
1018         // matched and pat is the pattern it is being matched against.
1019         //
1020         // In general, the way that this works is that we walk down
1021         // the pattern, constructing a cmt that represents the path
1022         // that will be taken to reach the value being matched.
1023         //
1024         // When we encounter named bindings, we take the cmt that has
1025         // been built up and pass it off to guarantee_valid() so that
1026         // we can be sure that the binding will remain valid for the
1027         // duration of the arm.
1028         //
1029         // (*2) There is subtlety concerning the correspondence between
1030         // pattern ids and types as compared to *expression* ids and
1031         // types. This is explained briefly. on the definition of the
1032         // type `cmt`, so go off and read what it says there, then
1033         // come back and I'll dive into a bit more detail here. :) OK,
1034         // back?
1035         //
1036         // In general, the id of the cmt should be the node that
1037         // "produces" the value---patterns aren't executable code
1038         // exactly, but I consider them to "execute" when they match a
1039         // value, and I consider them to produce the value that was
1040         // matched. So if you have something like:
1041         //
1042         //     let x = @@3;
1043         //     match x {
1044         //       @@y { ... }
1045         //     }
1046         //
1047         // In this case, the cmt and the relevant ids would be:
1048         //
1049         //     CMT             Id                  Type of Id Type of cmt
1050         //
1051         //     local(x)->@->@
1052         //     ^~~~~~~^        `x` from discr      @@int      @@int
1053         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1054         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1055         //
1056         // You can see that the types of the id and the cmt are in
1057         // sync in the first line, because that id is actually the id
1058         // of an expression. But once we get to pattern ids, the types
1059         // step out of sync again. So you'll see below that we always
1060         // get the type of the *subpattern* and use that.
1061
1062         debug!("cat_pattern: id={} pat={} cmt={}",
1063                pat.id, pprust::pat_to_string(pat),
1064                cmt.repr(self.tcx()));
1065
1066         op(self, cmt.clone(), pat);
1067
1068         match pat.node {
1069           ast::PatWild(_) => {
1070             // _
1071           }
1072
1073           ast::PatEnum(_, None) => {
1074             // variant(..)
1075           }
1076           ast::PatEnum(_, Some(ref subpats)) => {
1077             match self.tcx().def_map.borrow().find(&pat.id) {
1078                 Some(&def::DefVariant(enum_did, _, _)) => {
1079                     // variant(x, y, z)
1080
1081                     let downcast_cmt = {
1082                         if ty::enum_is_univariant(self.tcx(), enum_did) {
1083                             cmt // univariant, no downcast needed
1084                         } else {
1085                             self.cat_downcast(pat, cmt.clone(), cmt.ty)
1086                         }
1087                     };
1088
1089                     for (i, subpat) in subpats.iter().enumerate() {
1090                         let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1091
1092                         let subcmt =
1093                             self.cat_imm_interior(
1094                                 pat, downcast_cmt.clone(), subpat_ty,
1095                                 InteriorField(PositionalField(i)));
1096
1097                         if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1098                     }
1099                 }
1100                 Some(&def::DefFn(..)) |
1101                 Some(&def::DefStruct(..)) => {
1102                     for (i, subpat) in subpats.iter().enumerate() {
1103                         let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1104                         let cmt_field =
1105                             self.cat_imm_interior(
1106                                 pat, cmt.clone(), subpat_ty,
1107                                 InteriorField(PositionalField(i)));
1108                         if_ok!(self.cat_pattern(cmt_field, &**subpat,
1109                                                 |x,y,z| op(x,y,z)));
1110                     }
1111                 }
1112                 Some(&def::DefStatic(..)) => {
1113                     for subpat in subpats.iter() {
1114                         if_ok!(self.cat_pattern(cmt.clone(), &**subpat, |x,y,z| op(x,y,z)));
1115                     }
1116                 }
1117                 _ => {
1118                     self.tcx().sess.span_bug(
1119                         pat.span,
1120                         "enum pattern didn't resolve to enum or struct");
1121                 }
1122             }
1123           }
1124
1125           ast::PatIdent(_, _, Some(ref subpat)) => {
1126               if_ok!(self.cat_pattern(cmt, &**subpat, op));
1127           }
1128
1129           ast::PatIdent(_, _, None) => {
1130               // nullary variant or identifier: ignore
1131           }
1132
1133           ast::PatStruct(_, ref field_pats, _) => {
1134             // {f1: p1, ..., fN: pN}
1135             for fp in field_pats.iter() {
1136                 let field_ty = if_ok!(self.pat_ty(&*fp.pat)); // see (*2)
1137                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.ident, field_ty);
1138                 if_ok!(self.cat_pattern(cmt_field, &*fp.pat, |x,y,z| op(x,y,z)));
1139             }
1140           }
1141
1142           ast::PatTup(ref subpats) => {
1143             // (p1, ..., pN)
1144             for (i, subpat) in subpats.iter().enumerate() {
1145                 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1146                 let subcmt =
1147                     self.cat_imm_interior(
1148                         pat, cmt.clone(), subpat_ty,
1149                         InteriorField(PositionalField(i)));
1150                 if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1151             }
1152           }
1153
1154           ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
1155             // @p1, ~p1, ref p1
1156             let subcmt = self.cat_deref(pat, cmt, 0, false);
1157             if_ok!(self.cat_pattern(subcmt, &**subpat, op));
1158           }
1159
1160           ast::PatVec(ref before, ref slice, ref after) => {
1161               let elt_cmt = self.cat_index(pat, self.deref_vec(pat, cmt));
1162               for before_pat in before.iter() {
1163                   if_ok!(self.cat_pattern(elt_cmt.clone(), &**before_pat,
1164                                           |x,y,z| op(x,y,z)));
1165               }
1166               for slice_pat in slice.iter() {
1167                   let slice_ty = if_ok!(self.pat_ty(&**slice_pat));
1168                   let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1169                   if_ok!(self.cat_pattern(slice_cmt, &**slice_pat, |x,y,z| op(x,y,z)));
1170               }
1171               for after_pat in after.iter() {
1172                   if_ok!(self.cat_pattern(elt_cmt.clone(), &**after_pat, |x,y,z| op(x,y,z)));
1173               }
1174           }
1175
1176           ast::PatLit(_) | ast::PatRange(_, _) => {
1177               /*always ok*/
1178           }
1179
1180           ast::PatMac(_) => {
1181               self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1182           }
1183         }
1184
1185         Ok(())
1186     }
1187
1188     pub fn cmt_to_string(&self, cmt: &cmt_) -> String {
1189         match cmt.cat {
1190           cat_static_item => {
1191               "static item".to_string()
1192           }
1193           cat_copied_upvar(_) => {
1194               "captured outer variable in a proc".to_string()
1195           }
1196           cat_rvalue(..) => {
1197               "non-lvalue".to_string()
1198           }
1199           cat_local(_) => {
1200               "local variable".to_string()
1201           }
1202           cat_arg(..) => {
1203               "argument".to_string()
1204           }
1205           cat_deref(ref base, _, pk) => {
1206               match base.cat {
1207                   cat_upvar(..) => {
1208                       "captured outer variable".to_string()
1209                   }
1210                   _ => {
1211                       match pk {
1212                           Implicit(..) => {
1213                             "dereference (dereference is implicit, due to indexing)".to_string()
1214                           }
1215                           OwnedPtr | GcPtr => format!("dereference of `{}`", ptr_sigil(pk)),
1216                           _ => format!("dereference of `{}`-pointer", ptr_sigil(pk))
1217                       }
1218                   }
1219               }
1220           }
1221           cat_interior(_, InteriorField(NamedField(_))) => {
1222               "field".to_string()
1223           }
1224           cat_interior(_, InteriorField(PositionalField(_))) => {
1225               "anonymous field".to_string()
1226           }
1227           cat_interior(_, InteriorElement(VecElement)) => {
1228               "vec content".to_string()
1229           }
1230           cat_interior(_, InteriorElement(OtherElement)) => {
1231               "indexed content".to_string()
1232           }
1233           cat_upvar(..) => {
1234               "captured outer variable".to_string()
1235           }
1236           cat_discr(ref cmt, _) => {
1237             self.cmt_to_string(&**cmt)
1238           }
1239           cat_downcast(ref cmt) => {
1240             self.cmt_to_string(&**cmt)
1241           }
1242         }
1243     }
1244 }
1245
1246 pub enum InteriorSafety {
1247     InteriorUnsafe,
1248     InteriorSafe
1249 }
1250
1251 pub enum AliasableReason {
1252     AliasableManaged,
1253     AliasableBorrowed,
1254     AliasableOther,
1255     AliasableStatic(InteriorSafety),
1256     AliasableStaticMut(InteriorSafety),
1257 }
1258
1259 impl cmt_ {
1260     pub fn guarantor(&self) -> cmt {
1261         //! Returns `self` after stripping away any owned pointer derefs or
1262         //! interior content. The return value is basically the `cmt` which
1263         //! determines how long the value in `self` remains live.
1264
1265         match self.cat {
1266             cat_rvalue(..) |
1267             cat_static_item |
1268             cat_copied_upvar(..) |
1269             cat_local(..) |
1270             cat_arg(..) |
1271             cat_deref(_, _, UnsafePtr(..)) |
1272             cat_deref(_, _, GcPtr(..)) |
1273             cat_deref(_, _, BorrowedPtr(..)) |
1274             cat_deref(_, _, Implicit(..)) |
1275             cat_upvar(..) => {
1276                 Rc::new((*self).clone())
1277             }
1278             cat_downcast(ref b) |
1279             cat_discr(ref b, _) |
1280             cat_interior(ref b, _) |
1281             cat_deref(ref b, _, OwnedPtr) => {
1282                 b.guarantor()
1283             }
1284         }
1285     }
1286
1287     pub fn freely_aliasable(&self, ctxt: &ty::ctxt) -> Option<AliasableReason> {
1288         /*!
1289          * Returns `Some(_)` if this lvalue represents a freely aliasable
1290          * pointer type.
1291          */
1292
1293         // Maybe non-obvious: copied upvars can only be considered
1294         // non-aliasable in once closures, since any other kind can be
1295         // aliased and eventually recused.
1296
1297         match self.cat {
1298             cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1299             cat_deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1300             cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1301             cat_deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1302             cat_downcast(ref b) |
1303             cat_deref(ref b, _, OwnedPtr) |
1304             cat_interior(ref b, _) |
1305             cat_discr(ref b, _) => {
1306                 // Aliasability depends on base cmt
1307                 b.freely_aliasable(ctxt)
1308             }
1309
1310             cat_copied_upvar(CopiedUpvar {onceness: ast::Once, ..}) |
1311             cat_rvalue(..) |
1312             cat_local(..) |
1313             cat_upvar(..) |
1314             cat_arg(_) |
1315             cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1316                 None
1317             }
1318
1319             cat_copied_upvar(CopiedUpvar {onceness: ast::Many, ..}) => {
1320                 Some(AliasableOther)
1321             }
1322
1323             cat_static_item(..) => {
1324                 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1325                     InteriorUnsafe
1326                 } else {
1327                     InteriorSafe
1328                 };
1329
1330                 if self.mutbl.is_mutable() {
1331                     Some(AliasableStaticMut(int_safe))
1332                 } else {
1333                     Some(AliasableStatic(int_safe))
1334                 }
1335             }
1336
1337             cat_deref(_, _, GcPtr) => {
1338                 Some(AliasableManaged)
1339             }
1340
1341             cat_deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) |
1342             cat_deref(_, _, Implicit(ty::ImmBorrow, _)) => {
1343                 Some(AliasableBorrowed)
1344             }
1345         }
1346     }
1347 }
1348
1349 impl Repr for cmt_ {
1350     fn repr(&self, tcx: &ty::ctxt) -> String {
1351         format!("{{{} id:{} m:{:?} ty:{}}}",
1352                 self.cat.repr(tcx),
1353                 self.id,
1354                 self.mutbl,
1355                 self.ty.repr(tcx))
1356     }
1357 }
1358
1359 impl Repr for categorization {
1360     fn repr(&self, tcx: &ty::ctxt) -> String {
1361         match *self {
1362             cat_static_item |
1363             cat_rvalue(..) |
1364             cat_copied_upvar(..) |
1365             cat_local(..) |
1366             cat_upvar(..) |
1367             cat_arg(..) => {
1368                 format!("{:?}", *self)
1369             }
1370             cat_deref(ref cmt, derefs, ptr) => {
1371                 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
1372             }
1373             cat_interior(ref cmt, interior) => {
1374                 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1375             }
1376             cat_downcast(ref cmt) => {
1377                 format!("{}->(enum)", cmt.cat.repr(tcx))
1378             }
1379             cat_discr(ref cmt, _) => {
1380                 cmt.cat.repr(tcx)
1381             }
1382         }
1383     }
1384 }
1385
1386 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1387     match ptr {
1388         OwnedPtr => "Box",
1389         GcPtr => "Gc",
1390         BorrowedPtr(ty::ImmBorrow, _) |
1391         Implicit(ty::ImmBorrow, _) => "&",
1392         BorrowedPtr(ty::MutBorrow, _) |
1393         Implicit(ty::MutBorrow, _) => "&mut",
1394         BorrowedPtr(ty::UniqueImmBorrow, _) |
1395         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1396         UnsafePtr(_) => "*"
1397     }
1398 }
1399
1400 impl Repr for InteriorKind {
1401     fn repr(&self, _tcx: &ty::ctxt) -> String {
1402         match *self {
1403             InteriorField(NamedField(fld)) => {
1404                 token::get_name(fld).get().to_string()
1405             }
1406             InteriorField(PositionalField(i)) => format!("#{:?}", i),
1407             InteriorElement(_) => "[]".to_string(),
1408         }
1409     }
1410 }
1411
1412 fn element_kind(t: ty::t) -> ElementKind {
1413     match ty::get(t).sty {
1414         ty::ty_rptr(_, ty::mt{ty:ty, ..}) |
1415         ty::ty_uniq(ty) => match ty::get(ty).sty {
1416             ty::ty_vec(_, None) => VecElement,
1417             _ => OtherElement
1418         },
1419         ty::ty_vec(..) => VecElement,
1420         _ => OtherElement
1421     }
1422 }