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