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