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