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