]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
auto merge of #13316 : eddyb/rust/ast-ptr, 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(..) => fail!("no MutabilityCategory for def: {}", *def),
323
324             def::DefStatic(_, false) => McImmutable,
325             def::DefStatic(_, true) => McDeclared,
326
327             def::DefArg(_, binding_mode) |
328             def::DefBinding(_, binding_mode) |
329             def::DefLocal(_, binding_mode)  => match binding_mode {
330                 ast::BindByValue(ast::MutMutable) => McDeclared,
331                 _ => McImmutable
332             },
333
334             def::DefUpvar(_, def, _, _) => MutabilityCategory::from_def(&*def)
335         }
336     }
337
338     pub fn inherit(&self) -> MutabilityCategory {
339         match *self {
340             McImmutable => McImmutable,
341             McDeclared => McInherited,
342             McInherited => McInherited,
343         }
344     }
345
346     pub fn is_mutable(&self) -> bool {
347         match *self {
348             McImmutable => false,
349             McInherited => true,
350             McDeclared => true,
351         }
352     }
353
354     pub fn is_immutable(&self) -> bool {
355         match *self {
356             McImmutable => true,
357             McDeclared | McInherited => false
358         }
359     }
360
361     pub fn to_user_str(&self) -> &'static str {
362         match *self {
363             McDeclared | McInherited => "mutable",
364             McImmutable => "immutable",
365         }
366     }
367 }
368
369 macro_rules! if_ok(
370     ($inp: expr) => (
371         match $inp {
372             Ok(v) => { v }
373             Err(e) => { return Err(e); }
374         }
375     )
376 )
377
378 impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
379     pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
380         MemCategorizationContext { typer: typer }
381     }
382
383     fn tcx(&self) -> &'t ty::ctxt<'tcx> {
384         self.typer.tcx()
385     }
386
387     fn expr_ty(&self, expr: &ast::Expr) -> McResult<ty::t> {
388         self.typer.node_ty(expr.id)
389     }
390
391     fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<ty::t> {
392         let unadjusted_ty = if_ok!(self.expr_ty(expr));
393         Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
394                          self.typer.adjustments().borrow().find(&expr.id),
395                          |method_call| self.typer.node_method_ty(method_call)))
396     }
397
398     fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t> {
399         self.typer.node_ty(id)
400     }
401
402     fn pat_ty(&self, pat: &ast::Pat) -> McResult<ty::t> {
403         self.typer.node_ty(pat.id)
404     }
405
406     pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt> {
407         match self.typer.adjustments().borrow().find(&expr.id) {
408             None => {
409                 // No adjustments.
410                 self.cat_expr_unadjusted(expr)
411             }
412
413             Some(adjustment) => {
414                 match *adjustment {
415                     ty::AutoAddEnv(..) => {
416                         // Convert a bare fn to a closure by adding NULL env.
417                         // Result is an rvalue.
418                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
419                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
420                     }
421
422                     ty::AutoDerefRef(
423                         ty::AutoDerefRef {
424                             autoref: Some(_), ..}) => {
425                         // Equivalent to &*expr or something similar.
426                         // Result is an rvalue.
427                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
428                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
429                     }
430
431                     ty::AutoDerefRef(
432                         ty::AutoDerefRef {
433                             autoref: None, autoderefs: autoderefs}) => {
434                         // Equivalent to *expr or something similar.
435                         self.cat_expr_autoderefd(expr, autoderefs)
436                     }
437                 }
438             }
439         }
440     }
441
442     pub fn cat_expr_autoderefd(&self,
443                                expr: &ast::Expr,
444                                autoderefs: uint)
445                                -> McResult<cmt> {
446         let mut cmt = if_ok!(self.cat_expr_unadjusted(expr));
447         for deref in range(1u, autoderefs + 1) {
448             cmt = self.cat_deref(expr, cmt, deref, false);
449         }
450         return Ok(cmt);
451     }
452
453     pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt> {
454         debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
455
456         let expr_ty = if_ok!(self.expr_ty(expr));
457         match expr.node {
458           ast::ExprUnary(ast::UnDeref, ref e_base) => {
459             let base_cmt = if_ok!(self.cat_expr(&**e_base));
460             Ok(self.cat_deref(expr, base_cmt, 0, false))
461           }
462
463           ast::ExprField(ref base, f_name, _) => {
464             let base_cmt = if_ok!(self.cat_expr(&**base));
465             Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
466           }
467
468           ast::ExprTupField(ref base, idx, _) => {
469             let base_cmt = if_ok!(self.cat_expr(&**base));
470             Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
471           }
472
473           ast::ExprIndex(ref base, _) => {
474             let method_call = typeck::MethodCall::expr(expr.id());
475             match self.typer.node_method_ty(method_call) {
476                 Some(method_ty) => {
477                     // If this is an index implemented by a method call, then it will
478                     // include an implicit deref of the result.
479                     let ret_ty = ty::ty_fn_ret(method_ty);
480                     Ok(self.cat_deref(expr,
481                                       self.cat_rvalue_node(expr.id(),
482                                                            expr.span(),
483                                                            ret_ty), 1, true))
484                 }
485                 None => {
486                     let base_cmt = if_ok!(self.cat_expr(&**base));
487                     Ok(self.cat_index(expr, base_cmt))
488                 }
489             }
490           }
491
492           ast::ExprPath(_) => {
493             let def = *self.tcx().def_map.borrow().get(&expr.id);
494             self.cat_def(expr.id, expr.span, expr_ty, def)
495           }
496
497           ast::ExprParen(ref e) => {
498             self.cat_expr(&**e)
499           }
500
501           ast::ExprAddrOf(..) | ast::ExprCall(..) |
502           ast::ExprAssign(..) | ast::ExprAssignOp(..) |
503           ast::ExprFnBlock(..) | ast::ExprProc(..) |
504           ast::ExprUnboxedFn(..) | ast::ExprRet(..) |
505           ast::ExprUnary(..) |
506           ast::ExprMethodCall(..) | ast::ExprCast(..) |
507           ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
508           ast::ExprBinary(..) | ast::ExprWhile(..) |
509           ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
510           ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
511           ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
512           ast::ExprInlineAsm(..) | ast::ExprBox(..) |
513           ast::ExprForLoop(..) => {
514             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
515           }
516         }
517     }
518
519     pub fn cat_def(&self,
520                    id: ast::NodeId,
521                    span: Span,
522                    expr_ty: ty::t,
523                    def: def::Def)
524                    -> McResult<cmt> {
525         debug!("cat_def: id={} expr={} def={:?}",
526                id, expr_ty.repr(self.tcx()), def);
527
528         match def {
529           def::DefStruct(..) | def::DefVariant(..) | def::DefFn(..) |
530           def::DefStaticMethod(..) => {
531                 Ok(self.cat_rvalue_node(id, span, expr_ty))
532           }
533           def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
534           def::DefTrait(_) | def::DefTy(_) | def::DefPrimTy(_) |
535           def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
536           def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) => {
537               Ok(Rc::new(cmt_ {
538                   id:id,
539                   span:span,
540                   cat:cat_static_item,
541                   mutbl: McImmutable,
542                   ty:expr_ty
543               }))
544           }
545
546           def::DefStatic(_, _) => {
547               Ok(Rc::new(cmt_ {
548                   id:id,
549                   span:span,
550                   cat:cat_static_item,
551                   mutbl: MutabilityCategory::from_def(&def),
552                   ty:expr_ty
553               }))
554           }
555
556           def::DefArg(vid, _) => {
557             // Idea: make this could be rewritten to model by-ref
558             // stuff as `&const` and `&mut`?
559
560             Ok(Rc::new(cmt_ {
561                 id: id,
562                 span: span,
563                 cat: cat_arg(vid),
564                 mutbl: MutabilityCategory::from_def(&def),
565                 ty:expr_ty
566             }))
567           }
568
569           def::DefUpvar(var_id, _, fn_node_id, _) => {
570               let ty = if_ok!(self.node_ty(fn_node_id));
571               match ty::get(ty).sty {
572                   ty::ty_closure(ref closure_ty) => {
573                       // Decide whether to use implicit reference or by copy/move
574                       // capture for the upvar. This, combined with the onceness,
575                       // determines whether the closure can move out of it.
576                       let var_is_refd = match (closure_ty.store, closure_ty.onceness) {
577                           // Many-shot stack closures can never move out.
578                           (ty::RegionTraitStore(..), ast::Many) => true,
579                           // 1-shot stack closures can move out.
580                           (ty::RegionTraitStore(..), ast::Once) => false,
581                           // Heap closures always capture by copy/move, and can
582                           // move out if they are once.
583                           (ty::UniqTraitStore, _) => false,
584
585                       };
586                       if var_is_refd {
587                           self.cat_upvar(id, span, var_id, fn_node_id)
588                       } else {
589                           Ok(Rc::new(cmt_ {
590                               id:id,
591                               span:span,
592                               cat:cat_copied_upvar(CopiedUpvar {
593                                   upvar_id: var_id,
594                                   onceness: closure_ty.onceness,
595                                   capturing_proc: fn_node_id,
596                               }),
597                               mutbl: MutabilityCategory::from_def(&def),
598                               ty:expr_ty
599                           }))
600                       }
601                   }
602                   ty::ty_unboxed_closure(closure_id, _) => {
603                       let unboxed_closures = self.typer
604                                                  .unboxed_closures()
605                                                  .borrow();
606                       let kind = unboxed_closures.get(&closure_id).kind;
607                       let onceness = match kind {
608                           ty::FnUnboxedClosureKind |
609                           ty::FnMutUnboxedClosureKind => ast::Many,
610                           ty::FnOnceUnboxedClosureKind => ast::Once,
611                       };
612                       Ok(Rc::new(cmt_ {
613                           id: id,
614                           span: span,
615                           cat: cat_copied_upvar(CopiedUpvar {
616                               upvar_id: var_id,
617                               onceness: onceness,
618                               capturing_proc: fn_node_id,
619                           }),
620                           mutbl: MutabilityCategory::from_def(&def),
621                           ty: expr_ty
622                       }))
623                   }
624                   _ => {
625                       self.tcx().sess.span_bug(
626                           span,
627                           format!("Upvar of non-closure {} - {}",
628                                   fn_node_id,
629                                   ty.repr(self.tcx())).as_slice());
630                   }
631               }
632           }
633
634           def::DefLocal(vid, _) |
635           def::DefBinding(vid, _) => {
636             // by-value/by-ref bindings are local variables
637             Ok(Rc::new(cmt_ {
638                 id: id,
639                 span: span,
640                 cat: cat_local(vid),
641                 mutbl: MutabilityCategory::from_def(&def),
642                 ty: expr_ty
643             }))
644           }
645         }
646     }
647
648     fn cat_upvar(&self,
649                  id: ast::NodeId,
650                  span: Span,
651                  var_id: ast::NodeId,
652                  fn_node_id: ast::NodeId)
653                  -> McResult<cmt> {
654         /*!
655          * Upvars through a closure are in fact indirect
656          * references. That is, when a closure refers to a
657          * variable from a parent stack frame like `x = 10`,
658          * that is equivalent to `*x_ = 10` where `x_` is a
659          * borrowed pointer (`&mut x`) created when the closure
660          * was created and store in the environment. This
661          * equivalence is expose in the mem-categorization.
662          */
663
664         let upvar_id = ty::UpvarId { var_id: var_id,
665                                      closure_expr_id: fn_node_id };
666
667         let upvar_borrow = self.typer.upvar_borrow(upvar_id);
668
669         let var_ty = if_ok!(self.node_ty(var_id));
670
671         // We can't actually represent the types of all upvars
672         // as user-describable types, since upvars support const
673         // and unique-imm borrows! Therefore, we cheat, and just
674         // give err type. Nobody should be inspecting this type anyhow.
675         let upvar_ty = ty::mk_err();
676
677         let base_cmt = Rc::new(cmt_ {
678             id:id,
679             span:span,
680             cat:cat_upvar(upvar_id, upvar_borrow),
681             mutbl:McImmutable,
682             ty:upvar_ty,
683         });
684
685         let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
686
687         let deref_cmt = Rc::new(cmt_ {
688             id:id,
689             span:span,
690             cat:cat_deref(base_cmt, 0, ptr),
691             mutbl:MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
692             ty:var_ty,
693         });
694
695         Ok(deref_cmt)
696     }
697
698     pub fn cat_rvalue_node(&self,
699                            id: ast::NodeId,
700                            span: Span,
701                            expr_ty: ty::t)
702                            -> cmt {
703         match self.typer.temporary_scope(id) {
704             Some(scope) => {
705                 match ty::get(expr_ty).sty {
706                     ty::ty_vec(_, Some(0)) => self.cat_rvalue(id, span, ty::ReStatic, expr_ty),
707                     _ => self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
708                 }
709             }
710             None => {
711                 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
712             }
713         }
714     }
715
716     pub fn cat_rvalue(&self,
717                       cmt_id: ast::NodeId,
718                       span: Span,
719                       temp_scope: ty::Region,
720                       expr_ty: ty::t) -> cmt {
721         Rc::new(cmt_ {
722             id:cmt_id,
723             span:span,
724             cat:cat_rvalue(temp_scope),
725             mutbl:McDeclared,
726             ty:expr_ty
727         })
728     }
729
730     pub fn cat_field<N:ast_node>(&self,
731                                  node: &N,
732                                  base_cmt: cmt,
733                                  f_name: ast::Ident,
734                                  f_ty: ty::t)
735                                  -> cmt {
736         Rc::new(cmt_ {
737             id: node.id(),
738             span: node.span(),
739             mutbl: base_cmt.mutbl.inherit(),
740             cat: cat_interior(base_cmt, InteriorField(NamedField(f_name.name))),
741             ty: f_ty
742         })
743     }
744
745     pub fn cat_tup_field<N:ast_node>(&self,
746                                      node: &N,
747                                      base_cmt: cmt,
748                                      f_idx: uint,
749                                      f_ty: ty::t)
750                                      -> cmt {
751         Rc::new(cmt_ {
752             id: node.id(),
753             span: node.span(),
754             mutbl: base_cmt.mutbl.inherit(),
755             cat: cat_interior(base_cmt, InteriorField(PositionalField(f_idx))),
756             ty: f_ty
757         })
758     }
759
760     pub fn cat_deref_obj<N:ast_node>(&self, node: &N, base_cmt: cmt) -> cmt {
761         self.cat_deref_common(node, base_cmt, 0, ty::mk_nil(), false)
762     }
763
764     fn cat_deref<N:ast_node>(&self,
765                              node: &N,
766                              base_cmt: cmt,
767                              deref_cnt: uint,
768                              implicit: bool)
769                              -> cmt {
770         let adjustment = match self.typer.adjustments().borrow().find(&node.id()) {
771             Some(adj) if ty::adjust_is_object(adj) => typeck::AutoObject,
772             _ if deref_cnt != 0 => typeck::AutoDeref(deref_cnt),
773             _ => typeck::NoAdjustment
774         };
775
776         let method_call = typeck::MethodCall {
777             expr_id: node.id(),
778             adjustment: adjustment
779         };
780         let method_ty = self.typer.node_method_ty(method_call);
781
782         debug!("cat_deref: method_call={:?} method_ty={}",
783             method_call, method_ty.map(|ty| ty.repr(self.tcx())));
784
785         let base_cmt = match method_ty {
786             Some(method_ty) => {
787                 let ref_ty = ty::ty_fn_ret(method_ty);
788                 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
789             }
790             None => base_cmt
791         };
792         match ty::deref(base_cmt.ty, true) {
793             Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, implicit),
794             None => {
795                 self.tcx().sess.span_bug(
796                     node.span(),
797                     format!("Explicit deref of non-derefable type: {}",
798                             base_cmt.ty.repr(self.tcx())).as_slice());
799             }
800         }
801     }
802
803     fn cat_deref_common<N:ast_node>(&self,
804                                     node: &N,
805                                     base_cmt: cmt,
806                                     deref_cnt: uint,
807                                     deref_ty: ty::t,
808                                     implicit: bool)
809                                     -> cmt {
810         let (m, cat) = match deref_kind(self.tcx(), base_cmt.ty) {
811             deref_ptr(ptr) => {
812                 let ptr = if implicit {
813                     match ptr {
814                         BorrowedPtr(bk, r) => Implicit(bk, r),
815                         _ => self.tcx().sess.span_bug(node.span(),
816                             "Implicit deref of non-borrowed pointer")
817                     }
818                 } else {
819                     ptr
820                 };
821                 // for unique ptrs, we inherit mutability from the
822                 // owning reference.
823                 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
824                  cat_deref(base_cmt, deref_cnt, ptr))
825             }
826             deref_interior(interior) => {
827                 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
828             }
829         };
830         Rc::new(cmt_ {
831             id: node.id(),
832             span: node.span(),
833             cat: cat,
834             mutbl: m,
835             ty: deref_ty
836         })
837     }
838
839     pub fn cat_index<N:ast_node>(&self,
840                                  elt: &N,
841                                  mut base_cmt: cmt)
842                                  -> cmt {
843         //! Creates a cmt for an indexing operation (`[]`).
844         //!
845         //! One subtle aspect of indexing that may not be
846         //! immediately obvious: for anything other than a fixed-length
847         //! vector, an operation like `x[y]` actually consists of two
848         //! disjoint (from the point of view of borrowck) operations.
849         //! The first is a deref of `x` to create a pointer `p` that points
850         //! at the first element in the array. The second operation is
851         //! an index which adds `y*sizeof(T)` to `p` to obtain the
852         //! pointer to `x[y]`. `cat_index` will produce a resulting
853         //! cmt containing both this deref and the indexing,
854         //! presuming that `base_cmt` is not of fixed-length type.
855         //!
856         //! # Parameters
857         //! - `elt`: the AST node being indexed
858         //! - `base_cmt`: the cmt of `elt`
859
860         let method_call = typeck::MethodCall::expr(elt.id());
861         let method_ty = self.typer.node_method_ty(method_call);
862
863         let element_ty = match method_ty {
864             Some(method_ty) => {
865                 let ref_ty = ty::ty_fn_ret(method_ty);
866                 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
867                 *ty::ty_fn_args(method_ty).get(0)
868             }
869             None => {
870                 match ty::array_element_ty(base_cmt.ty) {
871                     Some(ty) => ty,
872                     None => {
873                         self.tcx().sess.span_bug(
874                             elt.span(),
875                             format!("Explicit index of non-index type `{}`",
876                                     base_cmt.ty.repr(self.tcx())).as_slice());
877                     }
878                 }
879             }
880         };
881
882         let m = base_cmt.mutbl.inherit();
883         return interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty);
884
885         fn interior<N: ast_node>(elt: &N,
886                                  of_cmt: cmt,
887                                  vec_ty: ty::t,
888                                  mutbl: MutabilityCategory,
889                                  element_ty: ty::t) -> cmt
890         {
891             Rc::new(cmt_ {
892                 id:elt.id(),
893                 span:elt.span(),
894                 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
895                 mutbl:mutbl,
896                 ty:element_ty
897             })
898         }
899     }
900
901     // Takes either a vec or a reference to a vec and returns the cmt for the
902     // underlying vec.
903     fn deref_vec<N:ast_node>(&self,
904                              elt: &N,
905                              base_cmt: cmt)
906                              -> cmt {
907         match deref_kind(self.tcx(), base_cmt.ty) {
908             deref_ptr(ptr) => {
909                 // for unique ptrs, we inherit mutability from the
910                 // owning reference.
911                 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
912
913                 // the deref is explicit in the resulting cmt
914                 Rc::new(cmt_ {
915                     id:elt.id(),
916                     span:elt.span(),
917                     cat:cat_deref(base_cmt.clone(), 0, ptr),
918                     mutbl:m,
919                     ty: match ty::deref(base_cmt.ty, false) {
920                         Some(mt) => mt.ty,
921                         None => self.tcx().sess.bug("Found non-derefable type")
922                     }
923                 })
924             }
925
926             deref_interior(_) => {
927                 base_cmt
928             }
929         }
930     }
931
932     pub fn cat_slice_pattern(&self,
933                              vec_cmt: cmt,
934                              slice_pat: &ast::Pat)
935                              -> McResult<(cmt, ast::Mutability, ty::Region)> {
936         /*!
937          * Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is
938          * the cmt for `P`, `slice_pat` is the pattern `Q`, returns:
939          * - a cmt for `Q`
940          * - the mutability and region of the slice `Q`
941          *
942          * These last two bits of info happen to be things that
943          * borrowck needs.
944          */
945
946         let slice_ty = if_ok!(self.node_ty(slice_pat.id));
947         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
948                                                     slice_pat,
949                                                     slice_ty);
950         let cmt_slice = self.cat_index(slice_pat, self.deref_vec(slice_pat, vec_cmt));
951         return Ok((cmt_slice, slice_mutbl, slice_r));
952
953         fn vec_slice_info(tcx: &ty::ctxt,
954                           pat: &ast::Pat,
955                           slice_ty: ty::t)
956                           -> (ast::Mutability, ty::Region) {
957             /*!
958              * In a pattern like [a, b, ..c], normally `c` has slice type,
959              * but if you have [a, b, ..ref c], then the type of `ref c`
960              * will be `&&[]`, so to extract the slice details we have
961              * to recurse through rptrs.
962              */
963
964             match ty::get(slice_ty).sty {
965                 ty::ty_rptr(r, ref mt) => match ty::get(mt.ty).sty {
966                     ty::ty_vec(_, None) => (mt.mutbl, r),
967                     _ => vec_slice_info(tcx, pat, mt.ty),
968                 },
969
970                 _ => {
971                     tcx.sess.span_bug(pat.span,
972                                       "type of slice pattern is not a slice");
973                 }
974             }
975         }
976     }
977
978     pub fn cat_imm_interior<N:ast_node>(&self,
979                                         node: &N,
980                                         base_cmt: cmt,
981                                         interior_ty: ty::t,
982                                         interior: InteriorKind)
983                                         -> cmt {
984         Rc::new(cmt_ {
985             id: node.id(),
986             span: node.span(),
987             mutbl: base_cmt.mutbl.inherit(),
988             cat: cat_interior(base_cmt, interior),
989             ty: interior_ty
990         })
991     }
992
993     pub fn cat_downcast<N:ast_node>(&self,
994                                     node: &N,
995                                     base_cmt: cmt,
996                                     downcast_ty: ty::t)
997                                     -> cmt {
998         Rc::new(cmt_ {
999             id: node.id(),
1000             span: node.span(),
1001             mutbl: base_cmt.mutbl.inherit(),
1002             cat: cat_downcast(base_cmt),
1003             ty: downcast_ty
1004         })
1005     }
1006
1007     pub fn cat_pattern(&self,
1008                        cmt: cmt,
1009                        pat: &ast::Pat,
1010                        op: |&MemCategorizationContext<TYPER>,
1011                             cmt,
1012                             &ast::Pat|)
1013                        -> McResult<()> {
1014         // Here, `cmt` is the categorization for the value being
1015         // matched and pat is the pattern it is being matched against.
1016         //
1017         // In general, the way that this works is that we walk down
1018         // the pattern, constructing a cmt that represents the path
1019         // that will be taken to reach the value being matched.
1020         //
1021         // When we encounter named bindings, we take the cmt that has
1022         // been built up and pass it off to guarantee_valid() so that
1023         // we can be sure that the binding will remain valid for the
1024         // duration of the arm.
1025         //
1026         // (*2) There is subtlety concerning the correspondence between
1027         // pattern ids and types as compared to *expression* ids and
1028         // types. This is explained briefly. on the definition of the
1029         // type `cmt`, so go off and read what it says there, then
1030         // come back and I'll dive into a bit more detail here. :) OK,
1031         // back?
1032         //
1033         // In general, the id of the cmt should be the node that
1034         // "produces" the value---patterns aren't executable code
1035         // exactly, but I consider them to "execute" when they match a
1036         // value, and I consider them to produce the value that was
1037         // matched. So if you have something like:
1038         //
1039         //     let x = @@3;
1040         //     match x {
1041         //       @@y { ... }
1042         //     }
1043         //
1044         // In this case, the cmt and the relevant ids would be:
1045         //
1046         //     CMT             Id                  Type of Id Type of cmt
1047         //
1048         //     local(x)->@->@
1049         //     ^~~~~~~^        `x` from discr      @@int      @@int
1050         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
1051         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
1052         //
1053         // You can see that the types of the id and the cmt are in
1054         // sync in the first line, because that id is actually the id
1055         // of an expression. But once we get to pattern ids, the types
1056         // step out of sync again. So you'll see below that we always
1057         // get the type of the *subpattern* and use that.
1058
1059         debug!("cat_pattern: id={} pat={} cmt={}",
1060                pat.id, pprust::pat_to_string(pat),
1061                cmt.repr(self.tcx()));
1062
1063         op(self, cmt.clone(), pat);
1064
1065         match pat.node {
1066           ast::PatWild(_) => {
1067             // _
1068           }
1069
1070           ast::PatEnum(_, None) => {
1071             // variant(..)
1072           }
1073           ast::PatEnum(_, Some(ref subpats)) => {
1074             match self.tcx().def_map.borrow().find(&pat.id) {
1075                 Some(&def::DefVariant(enum_did, _, _)) => {
1076                     // variant(x, y, z)
1077
1078                     let downcast_cmt = {
1079                         if ty::enum_is_univariant(self.tcx(), enum_did) {
1080                             cmt // univariant, no downcast needed
1081                         } else {
1082                             self.cat_downcast(pat, cmt.clone(), cmt.ty)
1083                         }
1084                     };
1085
1086                     for (i, subpat) in subpats.iter().enumerate() {
1087                         let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1088
1089                         let subcmt =
1090                             self.cat_imm_interior(
1091                                 pat, downcast_cmt.clone(), subpat_ty,
1092                                 InteriorField(PositionalField(i)));
1093
1094                         if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1095                     }
1096                 }
1097                 Some(&def::DefFn(..)) |
1098                 Some(&def::DefStruct(..)) => {
1099                     for (i, subpat) in subpats.iter().enumerate() {
1100                         let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1101                         let cmt_field =
1102                             self.cat_imm_interior(
1103                                 pat, cmt.clone(), subpat_ty,
1104                                 InteriorField(PositionalField(i)));
1105                         if_ok!(self.cat_pattern(cmt_field, &**subpat,
1106                                                 |x,y,z| op(x,y,z)));
1107                     }
1108                 }
1109                 Some(&def::DefStatic(..)) => {
1110                     for subpat in subpats.iter() {
1111                         if_ok!(self.cat_pattern(cmt.clone(), &**subpat, |x,y,z| op(x,y,z)));
1112                     }
1113                 }
1114                 _ => {
1115                     self.tcx().sess.span_bug(
1116                         pat.span,
1117                         "enum pattern didn't resolve to enum or struct");
1118                 }
1119             }
1120           }
1121
1122           ast::PatIdent(_, _, Some(ref subpat)) => {
1123               if_ok!(self.cat_pattern(cmt, &**subpat, op));
1124           }
1125
1126           ast::PatIdent(_, _, None) => {
1127               // nullary variant or identifier: ignore
1128           }
1129
1130           ast::PatStruct(_, ref field_pats, _) => {
1131             // {f1: p1, ..., fN: pN}
1132             for fp in field_pats.iter() {
1133                 let field_ty = if_ok!(self.pat_ty(&*fp.pat)); // see (*2)
1134                 let cmt_field = self.cat_field(pat, cmt.clone(), fp.ident, field_ty);
1135                 if_ok!(self.cat_pattern(cmt_field, &*fp.pat, |x,y,z| op(x,y,z)));
1136             }
1137           }
1138
1139           ast::PatTup(ref subpats) => {
1140             // (p1, ..., pN)
1141             for (i, subpat) in subpats.iter().enumerate() {
1142                 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1143                 let subcmt =
1144                     self.cat_imm_interior(
1145                         pat, cmt.clone(), subpat_ty,
1146                         InteriorField(PositionalField(i)));
1147                 if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1148             }
1149           }
1150
1151           ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
1152             // @p1, ~p1, ref p1
1153             let subcmt = self.cat_deref(pat, cmt, 0, false);
1154             if_ok!(self.cat_pattern(subcmt, &**subpat, op));
1155           }
1156
1157           ast::PatVec(ref before, ref slice, ref after) => {
1158               let elt_cmt = self.cat_index(pat, self.deref_vec(pat, cmt));
1159               for before_pat in before.iter() {
1160                   if_ok!(self.cat_pattern(elt_cmt.clone(), &**before_pat,
1161                                           |x,y,z| op(x,y,z)));
1162               }
1163               for slice_pat in slice.iter() {
1164                   let slice_ty = if_ok!(self.pat_ty(&**slice_pat));
1165                   let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1166                   if_ok!(self.cat_pattern(slice_cmt, &**slice_pat, |x,y,z| op(x,y,z)));
1167               }
1168               for after_pat in after.iter() {
1169                   if_ok!(self.cat_pattern(elt_cmt.clone(), &**after_pat, |x,y,z| op(x,y,z)));
1170               }
1171           }
1172
1173           ast::PatLit(_) | ast::PatRange(_, _) => {
1174               /*always ok*/
1175           }
1176
1177           ast::PatMac(_) => {
1178               self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1179           }
1180         }
1181
1182         Ok(())
1183     }
1184
1185     pub fn cmt_to_string(&self, cmt: &cmt_) -> String {
1186         match cmt.cat {
1187           cat_static_item => {
1188               "static item".to_string()
1189           }
1190           cat_copied_upvar(_) => {
1191               "captured outer variable in a proc".to_string()
1192           }
1193           cat_rvalue(..) => {
1194               "non-lvalue".to_string()
1195           }
1196           cat_local(_) => {
1197               "local variable".to_string()
1198           }
1199           cat_arg(..) => {
1200               "argument".to_string()
1201           }
1202           cat_deref(ref base, _, pk) => {
1203               match base.cat {
1204                   cat_upvar(..) => {
1205                       "captured outer variable".to_string()
1206                   }
1207                   _ => {
1208                       match pk {
1209                           Implicit(..) => {
1210                             "dereference (dereference is implicit, due to indexing)".to_string()
1211                           }
1212                           OwnedPtr | GcPtr => format!("dereference of `{}`", ptr_sigil(pk)),
1213                           _ => format!("dereference of `{}`-pointer", ptr_sigil(pk))
1214                       }
1215                   }
1216               }
1217           }
1218           cat_interior(_, InteriorField(NamedField(_))) => {
1219               "field".to_string()
1220           }
1221           cat_interior(_, InteriorField(PositionalField(_))) => {
1222               "anonymous field".to_string()
1223           }
1224           cat_interior(_, InteriorElement(VecElement)) => {
1225               "vec content".to_string()
1226           }
1227           cat_interior(_, InteriorElement(OtherElement)) => {
1228               "indexed content".to_string()
1229           }
1230           cat_upvar(..) => {
1231               "captured outer variable".to_string()
1232           }
1233           cat_discr(ref cmt, _) => {
1234             self.cmt_to_string(&**cmt)
1235           }
1236           cat_downcast(ref cmt) => {
1237             self.cmt_to_string(&**cmt)
1238           }
1239         }
1240     }
1241 }
1242
1243 pub enum InteriorSafety {
1244     InteriorUnsafe,
1245     InteriorSafe
1246 }
1247
1248 pub enum AliasableReason {
1249     AliasableManaged,
1250     AliasableBorrowed,
1251     AliasableOther,
1252     AliasableStatic(InteriorSafety),
1253     AliasableStaticMut(InteriorSafety),
1254 }
1255
1256 impl cmt_ {
1257     pub fn guarantor(&self) -> cmt {
1258         //! Returns `self` after stripping away any owned pointer derefs or
1259         //! interior content. The return value is basically the `cmt` which
1260         //! determines how long the value in `self` remains live.
1261
1262         match self.cat {
1263             cat_rvalue(..) |
1264             cat_static_item |
1265             cat_copied_upvar(..) |
1266             cat_local(..) |
1267             cat_arg(..) |
1268             cat_deref(_, _, UnsafePtr(..)) |
1269             cat_deref(_, _, GcPtr(..)) |
1270             cat_deref(_, _, BorrowedPtr(..)) |
1271             cat_deref(_, _, Implicit(..)) |
1272             cat_upvar(..) => {
1273                 Rc::new((*self).clone())
1274             }
1275             cat_downcast(ref b) |
1276             cat_discr(ref b, _) |
1277             cat_interior(ref b, _) |
1278             cat_deref(ref b, _, OwnedPtr) => {
1279                 b.guarantor()
1280             }
1281         }
1282     }
1283
1284     pub fn freely_aliasable(&self, ctxt: &ty::ctxt) -> Option<AliasableReason> {
1285         /*!
1286          * Returns `Some(_)` if this lvalue represents a freely aliasable
1287          * pointer type.
1288          */
1289
1290         // Maybe non-obvious: copied upvars can only be considered
1291         // non-aliasable in once closures, since any other kind can be
1292         // aliased and eventually recused.
1293
1294         match self.cat {
1295             cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1296             cat_deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1297             cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1298             cat_deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1299             cat_downcast(ref b) |
1300             cat_deref(ref b, _, OwnedPtr) |
1301             cat_interior(ref b, _) |
1302             cat_discr(ref b, _) => {
1303                 // Aliasability depends on base cmt
1304                 b.freely_aliasable(ctxt)
1305             }
1306
1307             cat_copied_upvar(CopiedUpvar {onceness: ast::Once, ..}) |
1308             cat_rvalue(..) |
1309             cat_local(..) |
1310             cat_upvar(..) |
1311             cat_arg(_) |
1312             cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1313                 None
1314             }
1315
1316             cat_copied_upvar(CopiedUpvar {onceness: ast::Many, ..}) => {
1317                 Some(AliasableOther)
1318             }
1319
1320             cat_static_item(..) => {
1321                 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1322                     InteriorUnsafe
1323                 } else {
1324                     InteriorSafe
1325                 };
1326
1327                 if self.mutbl.is_mutable() {
1328                     Some(AliasableStaticMut(int_safe))
1329                 } else {
1330                     Some(AliasableStatic(int_safe))
1331                 }
1332             }
1333
1334             cat_deref(_, _, GcPtr) => {
1335                 Some(AliasableManaged)
1336             }
1337
1338             cat_deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) |
1339             cat_deref(_, _, Implicit(ty::ImmBorrow, _)) => {
1340                 Some(AliasableBorrowed)
1341             }
1342         }
1343     }
1344 }
1345
1346 impl Repr for cmt_ {
1347     fn repr(&self, tcx: &ty::ctxt) -> String {
1348         format!("{{{} id:{} m:{:?} ty:{}}}",
1349                 self.cat.repr(tcx),
1350                 self.id,
1351                 self.mutbl,
1352                 self.ty.repr(tcx))
1353     }
1354 }
1355
1356 impl Repr for categorization {
1357     fn repr(&self, tcx: &ty::ctxt) -> String {
1358         match *self {
1359             cat_static_item |
1360             cat_rvalue(..) |
1361             cat_copied_upvar(..) |
1362             cat_local(..) |
1363             cat_upvar(..) |
1364             cat_arg(..) => {
1365                 format!("{:?}", *self)
1366             }
1367             cat_deref(ref cmt, derefs, ptr) => {
1368                 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
1369             }
1370             cat_interior(ref cmt, interior) => {
1371                 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1372             }
1373             cat_downcast(ref cmt) => {
1374                 format!("{}->(enum)", cmt.cat.repr(tcx))
1375             }
1376             cat_discr(ref cmt, _) => {
1377                 cmt.cat.repr(tcx)
1378             }
1379         }
1380     }
1381 }
1382
1383 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1384     match ptr {
1385         OwnedPtr => "Box",
1386         GcPtr => "Gc",
1387         BorrowedPtr(ty::ImmBorrow, _) |
1388         Implicit(ty::ImmBorrow, _) => "&",
1389         BorrowedPtr(ty::MutBorrow, _) |
1390         Implicit(ty::MutBorrow, _) => "&mut",
1391         BorrowedPtr(ty::UniqueImmBorrow, _) |
1392         Implicit(ty::UniqueImmBorrow, _) => "&unique",
1393         UnsafePtr(_) => "*"
1394     }
1395 }
1396
1397 impl Repr for InteriorKind {
1398     fn repr(&self, _tcx: &ty::ctxt) -> String {
1399         match *self {
1400             InteriorField(NamedField(fld)) => {
1401                 token::get_name(fld).get().to_string()
1402             }
1403             InteriorField(PositionalField(i)) => format!("#{:?}", i),
1404             InteriorElement(_) => "[]".to_string(),
1405         }
1406     }
1407 }
1408
1409 fn element_kind(t: ty::t) -> ElementKind {
1410     match ty::get(t).sty {
1411         ty::ty_rptr(_, ty::mt{ty:ty, ..}) |
1412         ty::ty_uniq(ty) => match ty::get(ty).sty {
1413             ty::ty_vec(_, None) => VecElement,
1414             _ => OtherElement
1415         },
1416         ty::ty_vec(..) => VecElement,
1417         _ => OtherElement
1418     }
1419 }