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