]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/mem_categorization.rs
auto merge of #12490 : zslayton/rust/doc-fix-12386, r=alexcrichton
[rust.git] / src / librustc / middle / mem_categorization.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
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 util::ppaux::{ty_to_str, region_ptr_to_str, Repr};
67
68 use syntax::ast::{MutImmutable, MutMutable};
69 use syntax::ast;
70 use syntax::codemap::Span;
71 use syntax::print::pprust;
72 use syntax::parse::token;
73
74 #[deriving(Eq)]
75 pub enum categorization {
76     cat_rvalue(ty::Region),            // temporary val, argument is its scope
77     cat_static_item,
78     cat_copied_upvar(CopiedUpvar),     // upvar copied into @fn or ~fn env
79     cat_upvar(ty::UpvarId, ty::UpvarBorrow), // by ref upvar from stack closure
80     cat_local(ast::NodeId),            // local variable
81     cat_arg(ast::NodeId),              // formal argument
82     cat_deref(cmt, uint, PointerKind), // deref of a ptr
83     cat_interior(cmt, InteriorKind),   // something interior: field, tuple, etc
84     cat_downcast(cmt),                 // selects a particular enum variant (*1)
85     cat_discr(cmt, ast::NodeId),       // match discriminant (see preserve())
86
87     // (*1) downcast is only required if the enum has more than one variant
88 }
89
90 #[deriving(Eq)]
91 pub struct CopiedUpvar {
92     upvar_id: ast::NodeId,
93     onceness: ast::Onceness,
94 }
95
96 // different kinds of pointers:
97 #[deriving(Eq, Hash)]
98 pub enum PointerKind {
99     OwnedPtr,
100     GcPtr,
101     BorrowedPtr(ty::BorrowKind, ty::Region),
102     UnsafePtr(ast::Mutability),
103 }
104
105 // We use the term "interior" to mean "something reachable from the
106 // base without a pointer dereference", e.g. a field
107 #[deriving(Eq, Hash)]
108 pub enum InteriorKind {
109     InteriorField(FieldName),
110     InteriorElement(ElementKind),
111 }
112
113 #[deriving(Eq, Hash)]
114 pub enum FieldName {
115     NamedField(ast::Name),
116     PositionalField(uint)
117 }
118
119 #[deriving(Eq, Hash)]
120 pub enum ElementKind {
121     VecElement,
122     StrElement,
123     OtherElement,
124 }
125
126 #[deriving(Eq, Hash, Show)]
127 pub enum MutabilityCategory {
128     McImmutable, // Immutable.
129     McDeclared,  // Directly declared as mutable.
130     McInherited, // Inherited from the fact that owner is mutable.
131 }
132
133 // `cmt`: "Category, Mutability, and Type".
134 //
135 // a complete categorization of a value indicating where it originated
136 // and how it is located, as well as the mutability of the memory in
137 // which the value is stored.
138 //
139 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
140 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
141 // always the `id` of the node producing the type; in an expression
142 // like `*x`, the type of this deref node is the deref'd type (`T`),
143 // but in a pattern like `@x`, the `@x` pattern is again a
144 // dereference, but its type is the type *before* the dereference
145 // (`@T`). So use `cmt.type` to find the type of the value in a consistent
146 // fashion. For more details, see the method `cat_pattern`
147 #[deriving(Eq)]
148 pub struct cmt_ {
149     id: ast::NodeId,          // id of expr/pat producing this value
150     span: Span,                // span of same expr/pat
151     cat: categorization,       // categorization of expr
152     mutbl: MutabilityCategory, // mutability of expr as lvalue
153     ty: ty::t                  // type of the expr (*see WARNING above*)
154 }
155
156 pub type cmt = @cmt_;
157
158 // We pun on *T to mean both actual deref of a ptr as well
159 // as accessing of components:
160 pub enum deref_kind {
161     deref_ptr(PointerKind),
162     deref_interior(InteriorKind),
163 }
164
165 // Categorizes a derefable type.  Note that we include vectors and strings as
166 // derefable (we model an index as the combination of a deref and then a
167 // pointer adjustment).
168 pub fn opt_deref_kind(t: ty::t) -> Option<deref_kind> {
169     match ty::get(t).sty {
170         ty::ty_uniq(_) |
171         ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
172         ty::ty_vec(_, ty::vstore_uniq) |
173         ty::ty_str(ty::vstore_uniq) |
174         ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
175             Some(deref_ptr(OwnedPtr))
176         }
177
178         ty::ty_rptr(r, mt) |
179         ty::ty_vec(mt, ty::vstore_slice(r)) => {
180             let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
181             Some(deref_ptr(BorrowedPtr(kind, r)))
182         }
183
184         ty::ty_trait(_, _, ty::RegionTraitStore(r), m, _) => {
185             let kind = ty::BorrowKind::from_mutbl(m);
186             Some(deref_ptr(BorrowedPtr(kind, r)))
187         }
188
189         ty::ty_str(ty::vstore_slice(r)) |
190         ty::ty_closure(ty::ClosureTy {sigil: ast::BorrowedSigil,
191                                       region: r, ..}) => {
192             Some(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
193         }
194
195         ty::ty_box(..) => {
196             Some(deref_ptr(GcPtr))
197         }
198
199         ty::ty_ptr(ref mt) => {
200             Some(deref_ptr(UnsafePtr(mt.mutbl)))
201         }
202
203         ty::ty_enum(..) |
204         ty::ty_struct(..) => { // newtype
205             Some(deref_interior(InteriorField(PositionalField(0))))
206         }
207
208         ty::ty_vec(_, ty::vstore_fixed(_)) |
209         ty::ty_str(ty::vstore_fixed(_)) => {
210             Some(deref_interior(InteriorElement(element_kind(t))))
211         }
212
213         _ => None
214     }
215 }
216
217 pub fn deref_kind(tcx: ty::ctxt, t: ty::t) -> deref_kind {
218     match opt_deref_kind(t) {
219       Some(k) => k,
220       None => {
221         tcx.sess.bug(
222             format!("deref_cat() invoked on non-derefable type {}",
223                  ty_to_str(tcx, t)));
224       }
225     }
226 }
227
228 trait ast_node {
229     fn id(&self) -> ast::NodeId;
230     fn span(&self) -> Span;
231 }
232
233 impl ast_node for ast::Expr {
234     fn id(&self) -> ast::NodeId { self.id }
235     fn span(&self) -> Span { self.span }
236 }
237
238 impl ast_node for ast::Pat {
239     fn id(&self) -> ast::NodeId { self.id }
240     fn span(&self) -> Span { self.span }
241 }
242
243 pub struct MemCategorizationContext<TYPER> {
244     typer: TYPER
245 }
246
247 pub type McResult<T> = Result<T, ()>;
248
249 /**
250  * The `Typer` trait provides the interface for the mem-categorization
251  * module to the results of the type check. It can be used to query
252  * the type assigned to an expression node, to inquire after adjustments,
253  * and so on.
254  *
255  * This interface is needed because mem-categorization is used from
256  * two places: `regionck` and `borrowck`. `regionck` executes before
257  * type inference is complete, and hence derives types and so on from
258  * intermediate tables.  This also implies that type errors can occur,
259  * and hence `node_ty()` and friends return a `Result` type -- any
260  * error will propagate back up through the mem-categorization
261  * routines.
262  *
263  * In the borrow checker, in contrast, type checking is complete and we
264  * know that no errors have occurred, so we simply consult the tcx and we
265  * can be sure that only `Ok` results will occur.
266  */
267 pub trait Typer {
268     fn tcx(&self) -> ty::ctxt;
269     fn node_ty(&mut self, id: ast::NodeId) -> McResult<ty::t>;
270     fn adjustment(&mut self, node_id: ast::NodeId) -> Option<@ty::AutoAdjustment>;
271     fn is_method_call(&mut self, id: ast::NodeId) -> bool;
272     fn temporary_scope(&mut self, rvalue_id: ast::NodeId) -> Option<ast::NodeId>;
273     fn upvar_borrow(&mut self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow;
274 }
275
276 impl MutabilityCategory {
277     pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
278         match m {
279             MutImmutable => McImmutable,
280             MutMutable => McDeclared
281         }
282     }
283
284     pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
285         match borrow_kind {
286             ty::ImmBorrow => McImmutable,
287             ty::UniqueImmBorrow => McImmutable,
288             ty::MutBorrow => McDeclared,
289         }
290     }
291
292     pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
293                              ptr: PointerKind) -> MutabilityCategory {
294         match ptr {
295             OwnedPtr => {
296                 base_mutbl.inherit()
297             }
298             BorrowedPtr(borrow_kind, _) => {
299                 MutabilityCategory::from_borrow_kind(borrow_kind)
300             }
301             GcPtr => {
302                 McImmutable
303             }
304             UnsafePtr(m) => {
305                 MutabilityCategory::from_mutbl(m)
306             }
307         }
308     }
309
310     pub fn inherit(&self) -> MutabilityCategory {
311         match *self {
312             McImmutable => McImmutable,
313             McDeclared => McInherited,
314             McInherited => McInherited,
315         }
316     }
317
318     pub fn is_mutable(&self) -> bool {
319         match *self {
320             McImmutable => false,
321             McInherited => true,
322             McDeclared => true,
323         }
324     }
325
326     pub fn is_immutable(&self) -> bool {
327         match *self {
328             McImmutable => true,
329             McDeclared | McInherited => false
330         }
331     }
332
333     pub fn to_user_str(&self) -> &'static str {
334         match *self {
335             McDeclared | McInherited => "mutable",
336             McImmutable => "immutable",
337         }
338     }
339 }
340
341 macro_rules! if_ok(
342     ($inp: expr) => (
343         match $inp {
344             Ok(v) => { v }
345             Err(e) => { return Err(e); }
346         }
347     )
348 )
349
350 impl<TYPER:Typer> MemCategorizationContext<TYPER> {
351     fn tcx(&self) -> ty::ctxt {
352         self.typer.tcx()
353     }
354
355     fn adjustment(&mut self, id: ast::NodeId) -> Option<@ty::AutoAdjustment> {
356         self.typer.adjustment(id)
357     }
358
359     fn expr_ty(&mut self, expr: &ast::Expr) -> McResult<ty::t> {
360         self.typer.node_ty(expr.id)
361     }
362
363     fn expr_ty_adjusted(&mut self, expr: &ast::Expr) -> McResult<ty::t> {
364         let unadjusted_ty = if_ok!(self.expr_ty(expr));
365         let adjustment = self.adjustment(expr.id);
366         Ok(ty::adjust_ty(self.tcx(), expr.span, unadjusted_ty, adjustment))
367     }
368
369     fn node_ty(&mut self, id: ast::NodeId) -> McResult<ty::t> {
370         self.typer.node_ty(id)
371     }
372
373     fn pat_ty(&mut self, pat: @ast::Pat) -> McResult<ty::t> {
374         self.typer.node_ty(pat.id)
375     }
376
377     pub fn cat_expr(&mut self, expr: &ast::Expr) -> McResult<cmt> {
378         match self.adjustment(expr.id) {
379             None => {
380                 // No adjustments.
381                 self.cat_expr_unadjusted(expr)
382             }
383
384             Some(adjustment) => {
385                 match *adjustment {
386                     ty::AutoObject(..) => {
387                         // Implicity casts a concrete object to trait object
388                         // so just patch up the type
389                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
390                         let expr_cmt = if_ok!(self.cat_expr_unadjusted(expr));
391                         Ok(@cmt_ {ty: expr_ty, ..*expr_cmt})
392                     }
393
394                     ty::AutoAddEnv(..) => {
395                         // Convert a bare fn to a closure by adding NULL env.
396                         // Result is an rvalue.
397                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
398                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
399                     }
400
401                     ty::AutoDerefRef(
402                         ty::AutoDerefRef {
403                             autoref: Some(_), ..}) => {
404                         // Equivalent to &*expr or something similar.
405                         // Result is an rvalue.
406                         let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
407                         Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
408                     }
409
410                     ty::AutoDerefRef(
411                         ty::AutoDerefRef {
412                             autoref: None, autoderefs: autoderefs}) => {
413                         // Equivalent to *expr or something similar.
414                         self.cat_expr_autoderefd(expr, autoderefs)
415                     }
416                 }
417             }
418         }
419     }
420
421     pub fn cat_expr_autoderefd(&mut self, expr: &ast::Expr, autoderefs: uint)
422                                -> McResult<cmt> {
423         let mut cmt = if_ok!(self.cat_expr_unadjusted(expr));
424         for deref in range(1u, autoderefs + 1) {
425             cmt = self.cat_deref(expr, cmt, deref);
426         }
427         return Ok(cmt);
428     }
429
430     pub fn cat_expr_unadjusted(&mut self, expr: &ast::Expr) -> McResult<cmt> {
431         debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
432
433         let expr_ty = if_ok!(self.expr_ty(expr));
434         match expr.node {
435           ast::ExprUnary(ast::UnDeref, e_base) => {
436             if self.typer.is_method_call(expr.id) {
437                 return Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty));
438             }
439
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             // Method calls are now a special syntactic form,
446             // so `a.b` should always be a field.
447             assert!(!self.typer.is_method_call(expr.id));
448
449             let base_cmt = if_ok!(self.cat_expr(base));
450             Ok(self.cat_field(expr, base_cmt, f_name, expr_ty))
451           }
452
453           ast::ExprIndex(base, _) => {
454             if self.typer.is_method_call(expr.id) {
455                 return Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty));
456             }
457
458             let base_cmt = if_ok!(self.cat_expr(base));
459             Ok(self.cat_index(expr, base_cmt, 0))
460           }
461
462           ast::ExprPath(_) => {
463             let def_map = self.tcx().def_map.borrow();
464             let def = def_map.get().get_copy(&expr.id);
465             self.cat_def(expr.id, expr.span, expr_ty, def)
466           }
467
468           ast::ExprParen(e) => self.cat_expr_unadjusted(e),
469
470           ast::ExprAddrOf(..) | ast::ExprCall(..) |
471           ast::ExprAssign(..) | ast::ExprAssignOp(..) |
472           ast::ExprFnBlock(..) | ast::ExprProc(..) | ast::ExprRet(..) |
473           ast::ExprUnary(..) |
474           ast::ExprMethodCall(..) | ast::ExprCast(..) | ast::ExprVstore(..) |
475           ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
476           ast::ExprLogLevel | ast::ExprBinary(..) | ast::ExprWhile(..) |
477           ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
478           ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
479           ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
480           ast::ExprInlineAsm(..) | ast::ExprBox(..) => {
481             Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
482           }
483
484           ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop")
485         }
486     }
487
488     pub fn cat_def(&mut self,
489                    id: ast::NodeId,
490                    span: Span,
491                    expr_ty: ty::t,
492                    def: ast::Def)
493                    -> McResult<cmt> {
494         debug!("cat_def: id={} expr={}",
495                id, expr_ty.repr(self.tcx()));
496
497         match def {
498           ast::DefStruct(..) | ast::DefVariant(..) => {
499                 Ok(self.cat_rvalue_node(id, span, expr_ty))
500           }
501           ast::DefFn(..) | ast::DefStaticMethod(..) | ast::DefMod(_) |
502           ast::DefForeignMod(_) | ast::DefStatic(_, false) |
503           ast::DefUse(_) | ast::DefTrait(_) | ast::DefTy(_) | ast::DefPrimTy(_) |
504           ast::DefTyParam(..) | ast::DefTyParamBinder(..) | ast::DefRegion(_) |
505           ast::DefLabel(_) | ast::DefSelfTy(..) | ast::DefMethod(..) => {
506               Ok(@cmt_ {
507                   id:id,
508                   span:span,
509                   cat:cat_static_item,
510                   mutbl: McImmutable,
511                   ty:expr_ty
512               })
513           }
514
515           ast::DefStatic(_, true) => {
516               Ok(@cmt_ {
517                   id:id,
518                   span:span,
519                   cat:cat_static_item,
520                   mutbl: McDeclared,
521                   ty:expr_ty
522               })
523           }
524
525           ast::DefArg(vid, binding_mode) => {
526             // Idea: make this could be rewritten to model by-ref
527             // stuff as `&const` and `&mut`?
528
529             // m: mutability of the argument
530             let m = match binding_mode {
531                 ast::BindByValue(ast::MutMutable) => McDeclared,
532                 _ => McImmutable
533             };
534             Ok(@cmt_ {
535                 id: id,
536                 span: span,
537                 cat: cat_arg(vid),
538                 mutbl: m,
539                 ty:expr_ty
540             })
541           }
542
543           ast::DefUpvar(var_id, _, fn_node_id, _) => {
544               let ty = if_ok!(self.node_ty(fn_node_id));
545               match ty::get(ty).sty {
546                   ty::ty_closure(ref closure_ty) => {
547                       // Decide whether to use implicit reference or by copy/move
548                       // capture for the upvar. This, combined with the onceness,
549                       // determines whether the closure can move out of it.
550                       let var_is_refd = match (closure_ty.sigil, closure_ty.onceness) {
551                           // Many-shot stack closures can never move out.
552                           (ast::BorrowedSigil, ast::Many) => true,
553                           // 1-shot stack closures can move out.
554                           (ast::BorrowedSigil, ast::Once) => false,
555                           // Heap closures always capture by copy/move, and can
556                           // move out if they are once.
557                           (ast::OwnedSigil, _) |
558                           (ast::ManagedSigil, _) => false,
559
560                       };
561                       if var_is_refd {
562                           self.cat_upvar(id, span, var_id, fn_node_id)
563                       } else {
564                           // FIXME #2152 allow mutation of moved upvars
565                           Ok(@cmt_ {
566                               id:id,
567                               span:span,
568                               cat:cat_copied_upvar(CopiedUpvar {
569                                   upvar_id: var_id,
570                                   onceness: closure_ty.onceness}),
571                               mutbl:McImmutable,
572                               ty:expr_ty
573                           })
574                       }
575                   }
576                   _ => {
577                       self.tcx().sess.span_bug(
578                           span,
579                           format!("Upvar of non-closure {} - {}",
580                                   fn_node_id, ty.repr(self.tcx())));
581                   }
582               }
583           }
584
585           ast::DefLocal(vid, binding_mode) |
586           ast::DefBinding(vid, binding_mode) => {
587             // by-value/by-ref bindings are local variables
588             let m = match binding_mode {
589                 ast::BindByValue(ast::MutMutable) => McDeclared,
590                 _ => McImmutable
591             };
592
593             Ok(@cmt_ {
594                 id: id,
595                 span: span,
596                 cat: cat_local(vid),
597                 mutbl: m,
598                 ty: expr_ty
599             })
600           }
601         }
602     }
603
604     fn cat_upvar(&mut self,
605                  id: ast::NodeId,
606                  span: Span,
607                  var_id: ast::NodeId,
608                  fn_node_id: ast::NodeId)
609                  -> McResult<cmt> {
610         /*!
611          * Upvars through a closure are in fact indirect
612          * references. That is, when a closure refers to a
613          * variable from a parent stack frame like `x = 10`,
614          * that is equivalent to `*x_ = 10` where `x_` is a
615          * borrowed pointer (`&mut x`) created when the closure
616          * was created and store in the environment. This
617          * equivalence is expose in the mem-categorization.
618          */
619
620         let upvar_id = ty::UpvarId { var_id: var_id,
621                                      closure_expr_id: fn_node_id };
622
623         let upvar_borrow = self.typer.upvar_borrow(upvar_id);
624
625         let var_ty = if_ok!(self.node_ty(var_id));
626
627         // We can't actually represent the types of all upvars
628         // as user-describable types, since upvars support const
629         // and unique-imm borrows! Therefore, we cheat, and just
630         // give err type. Nobody should be inspecting this type anyhow.
631         let upvar_ty = ty::mk_err();
632
633         let base_cmt = @cmt_ {
634             id:id,
635             span:span,
636             cat:cat_upvar(upvar_id, upvar_borrow),
637             mutbl:McImmutable,
638             ty:upvar_ty,
639         };
640
641         let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
642
643         let deref_cmt = @cmt_ {
644             id:id,
645             span:span,
646             cat:cat_deref(base_cmt, 0, ptr),
647             mutbl:MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
648             ty:var_ty,
649         };
650
651         Ok(deref_cmt)
652     }
653
654     pub fn cat_rvalue_node(&mut self,
655                            id: ast::NodeId,
656                            span: Span,
657                            expr_ty: ty::t)
658                            -> cmt {
659         match self.typer.temporary_scope(id) {
660             Some(scope) => {
661                 self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
662             }
663             None => {
664                 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
665             }
666         }
667     }
668
669     pub fn cat_rvalue(&mut self,
670                       cmt_id: ast::NodeId,
671                       span: Span,
672                       temp_scope: ty::Region,
673                       expr_ty: ty::t) -> cmt {
674         @cmt_ {
675             id:cmt_id,
676             span:span,
677             cat:cat_rvalue(temp_scope),
678             mutbl:McDeclared,
679             ty:expr_ty
680         }
681     }
682
683     /// inherited mutability: used in cases where the mutability of a
684     /// component is inherited from the base it is a part of. For
685     /// example, a record field is mutable if it is declared mutable
686     /// or if the container is mutable.
687     pub fn inherited_mutability(&mut self,
688                                 base_m: MutabilityCategory,
689                                 interior_m: ast::Mutability)
690                                 -> MutabilityCategory {
691         match interior_m {
692             MutImmutable => base_m.inherit(),
693             MutMutable => McDeclared
694         }
695     }
696
697     pub fn cat_field<N:ast_node>(&mut self,
698                                  node: &N,
699                                  base_cmt: cmt,
700                                  f_name: ast::Ident,
701                                  f_ty: ty::t)
702                                  -> cmt {
703         @cmt_ {
704             id: node.id(),
705             span: node.span(),
706             cat: cat_interior(base_cmt, InteriorField(NamedField(f_name.name))),
707             mutbl: base_cmt.mutbl.inherit(),
708             ty: f_ty
709         }
710     }
711
712     pub fn cat_deref_fn_or_obj<N:ast_node>(&mut self,
713                                            node: &N,
714                                            base_cmt: cmt,
715                                            deref_cnt: uint)
716                                            -> cmt {
717         // Bit of a hack: the "dereference" of a function pointer like
718         // `@fn()` is a mere logical concept. We interpret it as
719         // dereferencing the environment pointer; of course, we don't
720         // know what type lies at the other end, so we just call it
721         // `()` (the empty tuple).
722
723         let opaque_ty = ty::mk_tup(self.tcx(), ~[]);
724         return self.cat_deref_common(node, base_cmt, deref_cnt, opaque_ty);
725     }
726
727     pub fn cat_deref<N:ast_node>(&mut self,
728                                  node: &N,
729                                  base_cmt: cmt,
730                                  deref_cnt: uint)
731                                  -> cmt {
732         let mt = match ty::deref(base_cmt.ty, true) {
733             Some(mt) => mt,
734             None => {
735                 self.tcx().sess.span_bug(
736                     node.span(),
737                     format!("Explicit deref of non-derefable type: {}",
738                             base_cmt.ty.repr(self.tcx())));
739             }
740         };
741
742         return self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty);
743     }
744
745     pub fn cat_deref_common<N:ast_node>(&mut self,
746                                         node: &N,
747                                         base_cmt: cmt,
748                                         deref_cnt: uint,
749                                         deref_ty: ty::t)
750                                         -> cmt {
751         match deref_kind(self.tcx(), base_cmt.ty) {
752             deref_ptr(ptr) => {
753                 // for unique ptrs, we inherit mutability from the
754                 // owning reference.
755                 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl,
756                                                               ptr);
757
758                 @cmt_ {
759                     id:node.id(),
760                     span:node.span(),
761                     cat:cat_deref(base_cmt, deref_cnt, ptr),
762                     mutbl:m,
763                     ty:deref_ty
764                 }
765             }
766
767             deref_interior(interior) => {
768                 let m = base_cmt.mutbl.inherit();
769                 @cmt_ {
770                     id:node.id(),
771                     span:node.span(),
772                     cat:cat_interior(base_cmt, interior),
773                     mutbl:m,
774                     ty:deref_ty
775                 }
776             }
777         }
778     }
779
780     pub fn cat_index<N:ast_node>(&mut self,
781                                  elt: &N,
782                                  base_cmt: cmt,
783                                  derefs: uint)
784                                  -> cmt {
785         //! Creates a cmt for an indexing operation (`[]`); this
786         //! indexing operation may occurs as part of an
787         //! AutoBorrowVec, which when converting a `~[]` to an `&[]`
788         //! effectively takes the address of the 0th element.
789         //!
790         //! One subtle aspect of indexing that may not be
791         //! immediately obvious: for anything other than a fixed-length
792         //! vector, an operation like `x[y]` actually consists of two
793         //! disjoint (from the point of view of borrowck) operations.
794         //! The first is a deref of `x` to create a pointer `p` that points
795         //! at the first element in the array. The second operation is
796         //! an index which adds `y*sizeof(T)` to `p` to obtain the
797         //! pointer to `x[y]`. `cat_index` will produce a resulting
798         //! cmt containing both this deref and the indexing,
799         //! presuming that `base_cmt` is not of fixed-length type.
800         //!
801         //! In the event that a deref is needed, the "deref count"
802         //! is taken from the parameter `derefs`. See the comment
803         //! on the def'n of `root_map_key` in borrowck/mod.rs
804         //! for more details about deref counts; the summary is
805         //! that `derefs` should be 0 for an explicit indexing
806         //! operation and N+1 for an indexing that is part of
807         //! an auto-adjustment, where N is the number of autoderefs
808         //! in that adjustment.
809         //!
810         //! # Parameters
811         //! - `elt`: the AST node being indexed
812         //! - `base_cmt`: the cmt of `elt`
813         //! - `derefs`: the deref number to be used for
814         //!   the implicit index deref, if any (see above)
815
816         let element_ty = match ty::index(base_cmt.ty) {
817           Some(ref mt) => mt.ty,
818           None => {
819             self.tcx().sess.span_bug(
820                 elt.span(),
821                 format!("Explicit index of non-index type `{}`",
822                      base_cmt.ty.repr(self.tcx())));
823           }
824         };
825
826         return match deref_kind(self.tcx(), base_cmt.ty) {
827           deref_ptr(ptr) => {
828             // for unique ptrs, we inherit mutability from the
829             // owning reference.
830             let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
831
832             // the deref is explicit in the resulting cmt
833             let deref_cmt = @cmt_ {
834                 id:elt.id(),
835                 span:elt.span(),
836                 cat:cat_deref(base_cmt, derefs, ptr),
837                 mutbl:m,
838                 ty:element_ty
839             };
840
841             interior(elt, deref_cmt, base_cmt.ty, m.inherit(), element_ty)
842           }
843
844           deref_interior(_) => {
845             // fixed-length vectors have no deref
846             let m = base_cmt.mutbl.inherit();
847             interior(elt, base_cmt, base_cmt.ty, m, element_ty)
848           }
849         };
850
851         fn interior<N: ast_node>(elt: &N,
852                                  of_cmt: cmt,
853                                  vec_ty: ty::t,
854                                  mutbl: MutabilityCategory,
855                                  element_ty: ty::t) -> cmt
856         {
857             @cmt_ {
858                 id:elt.id(),
859                 span:elt.span(),
860                 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
861                 mutbl:mutbl,
862                 ty:element_ty
863             }
864         }
865     }
866
867     pub fn cat_slice_pattern(&mut self,
868                              vec_cmt: cmt,
869                              slice_pat: @ast::Pat)
870                              -> McResult<(cmt, ast::Mutability, ty::Region)> {
871         /*!
872          * Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is
873          * the cmt for `P`, `slice_pat` is the pattern `Q`, returns:
874          * - a cmt for `Q`
875          * - the mutability and region of the slice `Q`
876          *
877          * These last two bits of info happen to be things that
878          * borrowck needs.
879          */
880
881         let slice_ty = if_ok!(self.node_ty(slice_pat.id));
882         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
883                                                     slice_pat,
884                                                     slice_ty);
885         let cmt_slice = self.cat_index(slice_pat, vec_cmt, 0);
886         return Ok((cmt_slice, slice_mutbl, slice_r));
887
888         fn vec_slice_info(tcx: ty::ctxt,
889                           pat: @ast::Pat,
890                           slice_ty: ty::t)
891                           -> (ast::Mutability, ty::Region) {
892             /*!
893              * In a pattern like [a, b, ..c], normally `c` has slice type,
894              * but if you have [a, b, ..ref c], then the type of `ref c`
895              * will be `&&[]`, so to extract the slice details we have
896              * to recurse through rptrs.
897              */
898
899             match ty::get(slice_ty).sty {
900                 ty::ty_vec(slice_mt, ty::vstore_slice(slice_r)) => {
901                     (slice_mt.mutbl, slice_r)
902                 }
903
904                 ty::ty_rptr(_, ref mt) => {
905                     vec_slice_info(tcx, pat, mt.ty)
906                 }
907
908                 _ => {
909                     tcx.sess.span_bug(
910                         pat.span,
911                         format!("Type of slice pattern is not a slice"));
912                 }
913             }
914         }
915     }
916
917     pub fn cat_imm_interior<N:ast_node>(&mut self,
918                                         node: &N,
919                                         base_cmt: cmt,
920                                         interior_ty: ty::t,
921                                         interior: InteriorKind)
922                                         -> cmt {
923         @cmt_ {
924             id: node.id(),
925             span: node.span(),
926             cat: cat_interior(base_cmt, interior),
927             mutbl: base_cmt.mutbl.inherit(),
928             ty: interior_ty
929         }
930     }
931
932     pub fn cat_downcast<N:ast_node>(&mut self,
933                                     node: &N,
934                                     base_cmt: cmt,
935                                     downcast_ty: ty::t)
936                                     -> cmt {
937         @cmt_ {
938             id: node.id(),
939             span: node.span(),
940             cat: cat_downcast(base_cmt),
941             mutbl: base_cmt.mutbl.inherit(),
942             ty: downcast_ty
943         }
944     }
945
946     pub fn cat_pattern(&mut self,
947                        cmt: cmt,
948                        pat: @ast::Pat,
949                        op: |&mut MemCategorizationContext<TYPER>,
950                             cmt,
951                             @ast::Pat|)
952                        -> McResult<()> {
953         // Here, `cmt` is the categorization for the value being
954         // matched and pat is the pattern it is being matched against.
955         //
956         // In general, the way that this works is that we walk down
957         // the pattern, constructing a cmt that represents the path
958         // that will be taken to reach the value being matched.
959         //
960         // When we encounter named bindings, we take the cmt that has
961         // been built up and pass it off to guarantee_valid() so that
962         // we can be sure that the binding will remain valid for the
963         // duration of the arm.
964         //
965         // (*2) There is subtlety concerning the correspondence between
966         // pattern ids and types as compared to *expression* ids and
967         // types. This is explained briefly. on the definition of the
968         // type `cmt`, so go off and read what it says there, then
969         // come back and I'll dive into a bit more detail here. :) OK,
970         // back?
971         //
972         // In general, the id of the cmt should be the node that
973         // "produces" the value---patterns aren't executable code
974         // exactly, but I consider them to "execute" when they match a
975         // value, and I consider them to produce the value that was
976         // matched. So if you have something like:
977         //
978         //     let x = @@3;
979         //     match x {
980         //       @@y { ... }
981         //     }
982         //
983         // In this case, the cmt and the relevant ids would be:
984         //
985         //     CMT             Id                  Type of Id Type of cmt
986         //
987         //     local(x)->@->@
988         //     ^~~~~~~^        `x` from discr      @@int      @@int
989         //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
990         //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
991         //
992         // You can see that the types of the id and the cmt are in
993         // sync in the first line, because that id is actually the id
994         // of an expression. But once we get to pattern ids, the types
995         // step out of sync again. So you'll see below that we always
996         // get the type of the *subpattern* and use that.
997
998         let tcx = self.tcx();
999         debug!("cat_pattern: id={} pat={} cmt={}",
1000                pat.id, pprust::pat_to_str(pat),
1001                cmt.repr(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 }