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