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