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