]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty.rs
588ae76ba3bd4c1989427a3953fbfbfa888dc02f
[rust.git] / src / librustc / middle / ty.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 #![allow(non_camel_case_types)]
12
13 use back::svh::Svh;
14 use driver::session::Session;
15 use metadata::csearch;
16 use mc = middle::mem_categorization;
17 use middle::lint;
18 use middle::const_eval;
19 use middle::def;
20 use middle::dependency_format;
21 use middle::lang_items::OpaqueStructLangItem;
22 use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
23 use middle::freevars;
24 use middle::resolve;
25 use middle::resolve_lifetime;
26 use middle::subst;
27 use middle::subst::{Subst, Substs, VecPerParamSpace};
28 use middle::stability;
29 use middle::ty;
30 use middle::typeck;
31 use middle::typeck::MethodCall;
32 use middle::ty_fold;
33 use middle::ty_fold::{TypeFoldable,TypeFolder};
34 use middle;
35 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
36 use util::ppaux::{trait_store_to_str, ty_to_str};
37 use util::ppaux::{Repr, UserString};
38 use util::common::{indenter};
39 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
40
41 use std::cell::{Cell, RefCell};
42 use std::cmp;
43 use std::fmt::Show;
44 use std::fmt;
45 use std::hash::{Hash, sip, Writer};
46 use std::gc::Gc;
47 use std::iter::AdditiveIterator;
48 use std::mem;
49 use std::ops;
50 use std::rc::Rc;
51 use std::collections::{HashMap, HashSet};
52 use syntax::abi;
53 use syntax::ast::*;
54 use syntax::ast_util::{is_local, lit_is_str};
55 use syntax::ast_util;
56 use syntax::attr;
57 use syntax::attr::AttrMetaMethods;
58 use syntax::codemap::Span;
59 use syntax::parse::token;
60 use syntax::parse::token::InternedString;
61 use syntax::{ast, ast_map};
62 use syntax::util::small_vector::SmallVector;
63 use std::collections::enum_set::{EnumSet, CLike};
64
65 pub type Disr = u64;
66
67 pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
68
69 // Data types
70
71 #[deriving(PartialEq, Eq, Hash)]
72 pub struct field {
73     pub ident: ast::Ident,
74     pub mt: mt
75 }
76
77 #[deriving(Clone)]
78 pub enum MethodContainer {
79     TraitContainer(ast::DefId),
80     ImplContainer(ast::DefId),
81 }
82
83 #[deriving(Clone)]
84 pub struct Method {
85     pub ident: ast::Ident,
86     pub generics: ty::Generics,
87     pub fty: BareFnTy,
88     pub explicit_self: ast::ExplicitSelf_,
89     pub vis: ast::Visibility,
90     pub def_id: ast::DefId,
91     pub container: MethodContainer,
92
93     // If this method is provided, we need to know where it came from
94     pub provided_source: Option<ast::DefId>
95 }
96
97 impl Method {
98     pub fn new(ident: ast::Ident,
99                generics: ty::Generics,
100                fty: BareFnTy,
101                explicit_self: ast::ExplicitSelf_,
102                vis: ast::Visibility,
103                def_id: ast::DefId,
104                container: MethodContainer,
105                provided_source: Option<ast::DefId>)
106                -> Method {
107        Method {
108             ident: ident,
109             generics: generics,
110             fty: fty,
111             explicit_self: explicit_self,
112             vis: vis,
113             def_id: def_id,
114             container: container,
115             provided_source: provided_source
116         }
117     }
118
119     pub fn container_id(&self) -> ast::DefId {
120         match self.container {
121             TraitContainer(id) => id,
122             ImplContainer(id) => id,
123         }
124     }
125 }
126
127 #[deriving(Clone, PartialEq, Eq, Hash)]
128 pub struct mt {
129     pub ty: t,
130     pub mutbl: ast::Mutability,
131 }
132
133 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
134 pub enum TraitStore {
135     /// Box<Trait>
136     UniqTraitStore,
137     /// &Trait and &mut Trait
138     RegionTraitStore(Region, ast::Mutability),
139 }
140
141 #[deriving(Clone)]
142 pub struct field_ty {
143     pub name: Name,
144     pub id: DefId,
145     pub vis: ast::Visibility,
146     pub origin: ast::DefId,  // The DefId of the struct in which the field is declared.
147 }
148
149 // Contains information needed to resolve types and (in the future) look up
150 // the types of AST nodes.
151 #[deriving(PartialEq, Eq, Hash)]
152 pub struct creader_cache_key {
153     pub cnum: CrateNum,
154     pub pos: uint,
155     pub len: uint
156 }
157
158 pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
159
160 pub struct intern_key {
161     sty: *sty,
162 }
163
164 // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
165 // implementation will not recurse through sty and you will get stack
166 // exhaustion.
167 impl cmp::PartialEq for intern_key {
168     fn eq(&self, other: &intern_key) -> bool {
169         unsafe {
170             *self.sty == *other.sty
171         }
172     }
173     fn ne(&self, other: &intern_key) -> bool {
174         !self.eq(other)
175     }
176 }
177
178 impl Eq for intern_key {}
179
180 impl<W:Writer> Hash<W> for intern_key {
181     fn hash(&self, s: &mut W) {
182         unsafe { (*self.sty).hash(s) }
183     }
184 }
185
186 pub enum ast_ty_to_ty_cache_entry {
187     atttce_unresolved,  /* not resolved yet */
188     atttce_resolved(t)  /* resolved to a type, irrespective of region */
189 }
190
191 #[deriving(Clone, PartialEq, Decodable, Encodable)]
192 pub struct ItemVariances {
193     pub types: VecPerParamSpace<Variance>,
194     pub regions: VecPerParamSpace<Variance>,
195 }
196
197 #[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
198 pub enum Variance {
199     Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
200     Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
201     Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
202     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
203 }
204
205 #[deriving(Clone)]
206 pub enum AutoAdjustment {
207     AutoAddEnv(ty::TraitStore),
208     AutoDerefRef(AutoDerefRef),
209     AutoObject(ty::TraitStore,
210                ty::BuiltinBounds,
211                ast::DefId, /* Trait ID */
212                subst::Substs /* Trait substitutions */)
213 }
214
215 #[deriving(Clone, Decodable, Encodable)]
216 pub struct AutoDerefRef {
217     pub autoderefs: uint,
218     pub autoref: Option<AutoRef>
219 }
220
221 #[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
222 pub enum AutoRef {
223     /// Convert from T to &T
224     AutoPtr(Region, ast::Mutability),
225
226     /// Convert from ~[]/&[] to &[] or str
227     AutoBorrowVec(Region, ast::Mutability),
228
229     /// Convert from ~[]/&[] to &&[] or str
230     AutoBorrowVecRef(Region, ast::Mutability),
231
232     /// Convert from T to *T
233     AutoUnsafe(ast::Mutability),
234
235     /// Convert from Box<Trait>/&Trait to &Trait
236     AutoBorrowObj(Region, ast::Mutability),
237 }
238
239 /// A restriction that certain types must be the same size. The use of
240 /// `transmute` gives rise to these restrictions.
241 pub struct TransmuteRestriction {
242     /// The span from whence the restriction comes.
243     pub span: Span,
244     /// The type being transmuted from.
245     pub from: t,
246     /// The type being transmuted to.
247     pub to: t,
248 }
249
250 /// The data structure to keep track of all the information that typechecker
251 /// generates so that so that it can be reused and doesn't have to be redone
252 /// later on.
253 pub struct ctxt {
254     /// Specifically use a speedy hash algorithm for this hash map, it's used
255     /// quite often.
256     pub interner: RefCell<FnvHashMap<intern_key, Box<t_box_>>>,
257     pub next_id: Cell<uint>,
258     pub sess: Session,
259     pub def_map: resolve::DefMap,
260
261     pub named_region_map: resolve_lifetime::NamedRegionMap,
262
263     pub region_maps: middle::region::RegionMaps,
264
265     /// Stores the types for various nodes in the AST.  Note that this table
266     /// is not guaranteed to be populated until after typeck.  See
267     /// typeck::check::fn_ctxt for details.
268     pub node_types: node_type_table,
269
270     /// Stores the type parameters which were substituted to obtain the type
271     /// of this node.  This only applies to nodes that refer to entities
272     /// param<eterized by type parameters, such as generic fns, types, or
273     /// other items.
274     pub item_substs: RefCell<NodeMap<ItemSubsts>>,
275
276     /// Maps from a method to the method "descriptor"
277     pub methods: RefCell<DefIdMap<Rc<Method>>>,
278
279     /// Maps from a trait def-id to a list of the def-ids of its methods
280     pub trait_method_def_ids: RefCell<DefIdMap<Rc<Vec<DefId>>>>,
281
282     /// A cache for the trait_methods() routine
283     pub trait_methods_cache: RefCell<DefIdMap<Rc<Vec<Rc<Method>>>>>,
284
285     pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
286
287     pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
288     pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
289
290     pub map: ast_map::Map,
291     pub intrinsic_defs: RefCell<DefIdMap<t>>,
292     pub freevars: RefCell<freevars::freevar_map>,
293     pub tcache: type_cache,
294     pub rcache: creader_cache,
295     pub short_names_cache: RefCell<HashMap<t, String>>,
296     pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
297     pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
298     pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
299     pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
300     pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
301     pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
302     pub normalized_cache: RefCell<HashMap<t, t>>,
303     pub lang_items: middle::lang_items::LanguageItems,
304     /// A mapping of fake provided method def_ids to the default implementation
305     pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
306     pub supertraits: RefCell<DefIdMap<Rc<Vec<Rc<TraitRef>>>>>,
307     pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
308     pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
309
310     /// Maps from def-id of a type or region parameter to its
311     /// (inferred) variance.
312     pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
313
314     /// A mapping from the def ID of an enum or struct type to the def ID
315     /// of the method that implements its destructor. If the type is not
316     /// present in this map, it does not have a destructor. This map is
317     /// populated during the coherence phase of typechecking.
318     pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
319
320     /// A method will be in this list if and only if it is a destructor.
321     pub destructors: RefCell<DefIdSet>,
322
323     /// Maps a trait onto a list of impls of that trait.
324     pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
325
326     /// Maps a DefId of a type to a list of its inherent impls.
327     /// Contains implementations of methods that are inherent to a type.
328     /// Methods in these implementations don't need to be exported.
329     pub inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
330
331     /// Maps a DefId of an impl to a list of its methods.
332     /// Note that this contains all of the impls that we know about,
333     /// including ones in other crates. It's not clear that this is the best
334     /// way to do it.
335     pub impl_methods: RefCell<DefIdMap<Vec<ast::DefId>>>,
336
337     /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
338     /// present in this set can be warned about.
339     pub used_unsafe: RefCell<NodeSet>,
340
341     /// Set of nodes which mark locals as mutable which end up getting used at
342     /// some point. Local variable definitions not in this set can be warned
343     /// about.
344     pub used_mut_nodes: RefCell<NodeSet>,
345
346     /// vtable resolution information for impl declarations
347     pub impl_vtables: typeck::impl_vtable_map,
348
349     /// The set of external nominal types whose implementations have been read.
350     /// This is used for lazy resolution of methods.
351     pub populated_external_types: RefCell<DefIdSet>,
352
353     /// The set of external traits whose implementations have been read. This
354     /// is used for lazy resolution of traits.
355     pub populated_external_traits: RefCell<DefIdSet>,
356
357     /// Borrows
358     pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
359
360     /// These two caches are used by const_eval when decoding external statics
361     /// and variants that are found.
362     pub extern_const_statics: RefCell<DefIdMap<Option<Gc<ast::Expr>>>>,
363     pub extern_const_variants: RefCell<DefIdMap<Option<Gc<ast::Expr>>>>,
364
365     pub method_map: typeck::MethodMap,
366     pub vtable_map: typeck::vtable_map,
367
368     pub dependency_formats: RefCell<dependency_format::Dependencies>,
369
370     pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::Lint),
371                                           (lint::Level, lint::LintSource)>>,
372
373     /// The types that must be asserted to be the same size for `transmute`
374     /// to be valid. We gather up these restrictions in the intrinsicck pass
375     /// and check them in trans.
376     pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
377
378     /// Maps any item's def-id to its stability index.
379     pub stability: RefCell<stability::Index>,
380 }
381
382 pub enum tbox_flag {
383     has_params = 1,
384     has_self = 2,
385     needs_infer = 4,
386     has_regions = 8,
387     has_ty_err = 16,
388     has_ty_bot = 32,
389
390     // a meta-pub flag: subst may be required if the type has parameters, a self
391     // type, or references bound regions
392     needs_subst = 1 | 2 | 8
393 }
394
395 pub type t_box = &'static t_box_;
396
397 pub struct t_box_ {
398     pub sty: sty,
399     pub id: uint,
400     pub flags: uint,
401 }
402
403 // To reduce refcounting cost, we're representing types as unsafe pointers
404 // throughout the compiler. These are simply casted t_box values. Use ty::get
405 // to cast them back to a box. (Without the cast, compiler performance suffers
406 // ~15%.) This does mean that a t value relies on the ctxt to keep its box
407 // alive, and using ty::get is unsafe when the ctxt is no longer alive.
408 enum t_opaque {}
409
410 #[allow(raw_pointer_deriving)]
411 #[deriving(Clone, PartialEq, Eq, Hash)]
412 pub struct t { inner: *t_opaque }
413
414 impl fmt::Show for t {
415     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
416         "*t_opaque".fmt(f)
417     }
418 }
419
420 pub fn get(t: t) -> t_box {
421     unsafe {
422         let t2: t_box = mem::transmute(t);
423         t2
424     }
425 }
426
427 pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
428     (tb.flags & (flag as uint)) != 0u
429 }
430 pub fn type_has_params(t: t) -> bool {
431     tbox_has_flag(get(t), has_params)
432 }
433 pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
434 pub fn type_needs_infer(t: t) -> bool {
435     tbox_has_flag(get(t), needs_infer)
436 }
437 pub fn type_id(t: t) -> uint { get(t).id }
438
439 #[deriving(Clone, PartialEq, Eq, Hash)]
440 pub struct BareFnTy {
441     pub fn_style: ast::FnStyle,
442     pub abi: abi::Abi,
443     pub sig: FnSig,
444 }
445
446 #[deriving(Clone, PartialEq, Eq, Hash)]
447 pub struct ClosureTy {
448     pub fn_style: ast::FnStyle,
449     pub onceness: ast::Onceness,
450     pub store: TraitStore,
451     pub bounds: BuiltinBounds,
452     pub sig: FnSig,
453 }
454
455 /**
456  * Signature of a function type, which I have arbitrarily
457  * decided to use to refer to the input/output types.
458  *
459  * - `binder_id` is the node id where this fn type appeared;
460  *   it is used to identify all the bound regions appearing
461  *   in the input/output types that are bound by this fn type
462  *   (vs some enclosing or enclosed fn type)
463  * - `inputs` is the list of arguments and their modes.
464  * - `output` is the return type.
465  * - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
466  */
467 #[deriving(Clone, PartialEq, Eq, Hash)]
468 pub struct FnSig {
469     pub binder_id: ast::NodeId,
470     pub inputs: Vec<t>,
471     pub output: t,
472     pub variadic: bool
473 }
474
475 #[deriving(Clone, PartialEq, Eq, Hash)]
476 pub struct ParamTy {
477     pub space: subst::ParamSpace,
478     pub idx: uint,
479     pub def_id: DefId
480 }
481
482 /// Representation of regions:
483 #[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
484 pub enum Region {
485     // Region bound in a type or fn declaration which will be
486     // substituted 'early' -- that is, at the same time when type
487     // parameters are substituted.
488     ReEarlyBound(/* param id */ ast::NodeId,
489                  subst::ParamSpace,
490                  /*index*/ uint,
491                  ast::Name),
492
493     // Region bound in a function scope, which will be substituted when the
494     // function is called. The first argument must be the `binder_id` of
495     // some enclosing function signature.
496     ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
497
498     /// When checking a function body, the types of all arguments and so forth
499     /// that refer to bound region parameters are modified to refer to free
500     /// region parameters.
501     ReFree(FreeRegion),
502
503     /// A concrete region naming some expression within the current function.
504     ReScope(NodeId),
505
506     /// Static data that has an "infinite" lifetime. Top in the region lattice.
507     ReStatic,
508
509     /// A region variable.  Should not exist after typeck.
510     ReInfer(InferRegion),
511
512     /// Empty lifetime is for data that is never accessed.
513     /// Bottom in the region lattice. We treat ReEmpty somewhat
514     /// specially; at least right now, we do not generate instances of
515     /// it during the GLB computations, but rather
516     /// generate an error instead. This is to improve error messages.
517     /// The only way to get an instance of ReEmpty is to have a region
518     /// variable with no constraints.
519     ReEmpty,
520 }
521
522 /**
523  * Upvars do not get their own node-id. Instead, we use the pair of
524  * the original var id (that is, the root variable that is referenced
525  * by the upvar) and the id of the closure expression.
526  */
527 #[deriving(Clone, PartialEq, Eq, Hash)]
528 pub struct UpvarId {
529     pub var_id: ast::NodeId,
530     pub closure_expr_id: ast::NodeId,
531 }
532
533 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
534 pub enum BorrowKind {
535     /// Data must be immutable and is aliasable.
536     ImmBorrow,
537
538     /// Data must be immutable but not aliasable.  This kind of borrow
539     /// cannot currently be expressed by the user and is used only in
540     /// implicit closure bindings. It is needed when you the closure
541     /// is borrowing or mutating a mutable referent, e.g.:
542     ///
543     ///    let x: &mut int = ...;
544     ///    let y = || *x += 5;
545     ///
546     /// If we were to try to translate this closure into a more explicit
547     /// form, we'd encounter an error with the code as written:
548     ///
549     ///    struct Env { x: & &mut int }
550     ///    let x: &mut int = ...;
551     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
552     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
553     ///
554     /// This is then illegal because you cannot mutate a `&mut` found
555     /// in an aliasable location. To solve, you'd have to translate with
556     /// an `&mut` borrow:
557     ///
558     ///    struct Env { x: & &mut int }
559     ///    let x: &mut int = ...;
560     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
561     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
562     ///
563     /// Now the assignment to `**env.x` is legal, but creating a
564     /// mutable pointer to `x` is not because `x` is not mutable. We
565     /// could fix this by declaring `x` as `let mut x`. This is ok in
566     /// user code, if awkward, but extra weird for closures, since the
567     /// borrow is hidden.
568     ///
569     /// So we introduce a "unique imm" borrow -- the referent is
570     /// immutable, but not aliasable. This solves the problem. For
571     /// simplicity, we don't give users the way to express this
572     /// borrow, it's just used when translating closures.
573     UniqueImmBorrow,
574
575     /// Data is mutable and not aliasable.
576     MutBorrow
577 }
578
579 /**
580  * Information describing the borrowing of an upvar. This is computed
581  * during `typeck`, specifically by `regionck`. The general idea is
582  * that the compiler analyses treat closures like:
583  *
584  *     let closure: &'e fn() = || {
585  *        x = 1;   // upvar x is assigned to
586  *        use(y);  // upvar y is read
587  *        foo(&z); // upvar z is borrowed immutably
588  *     };
589  *
590  * as if they were "desugared" to something loosely like:
591  *
592  *     struct Vars<'x,'y,'z> { x: &'x mut int,
593  *                             y: &'y const int,
594  *                             z: &'z int }
595  *     let closure: &'e fn() = {
596  *         fn f(env: &Vars) {
597  *             *env.x = 1;
598  *             use(*env.y);
599  *             foo(env.z);
600  *         }
601  *         let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
602  *                                                       y: &'y const y,
603  *                                                       z: &'z z };
604  *         (env, f)
605  *     };
606  *
607  * This is basically what happens at runtime. The closure is basically
608  * an existentially quantified version of the `(env, f)` pair.
609  *
610  * This data structure indicates the region and mutability of a single
611  * one of the `x...z` borrows.
612  *
613  * It may not be obvious why each borrowed variable gets its own
614  * lifetime (in the desugared version of the example, these are indicated
615  * by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
616  * Each such lifetime must encompass the lifetime `'e` of the closure itself,
617  * but need not be identical to it. The reason that this makes sense:
618  *
619  * - Callers are only permitted to invoke the closure, and hence to
620  *   use the pointers, within the lifetime `'e`, so clearly `'e` must
621  *   be a sublifetime of `'x...'z`.
622  * - The closure creator knows which upvars were borrowed by the closure
623  *   and thus `x...z` will be reserved for `'x...'z` respectively.
624  * - Through mutation, the borrowed upvars can actually escape
625  *   the closure, so sometimes it is necessary for them to be larger
626  *   than the closure lifetime itself.
627  */
628 #[deriving(PartialEq, Clone)]
629 pub struct UpvarBorrow {
630     pub kind: BorrowKind,
631     pub region: ty::Region,
632 }
633
634 pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
635
636 impl Region {
637     pub fn is_bound(&self) -> bool {
638         match self {
639             &ty::ReEarlyBound(..) => true,
640             &ty::ReLateBound(..) => true,
641             _ => false
642         }
643     }
644 }
645
646 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
647 pub struct FreeRegion {
648     pub scope_id: NodeId,
649     pub bound_region: BoundRegion
650 }
651
652 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
653 pub enum BoundRegion {
654     /// An anonymous region parameter for a given fn (&T)
655     BrAnon(uint),
656
657     /// Named region parameters for functions (a in &'a T)
658     ///
659     /// The def-id is needed to distinguish free regions in
660     /// the event of shadowing.
661     BrNamed(ast::DefId, ast::Name),
662
663     /// Fresh bound identifiers created during GLB computations.
664     BrFresh(uint),
665 }
666
667 mod primitives {
668     use super::t_box_;
669
670     use syntax::ast;
671
672     macro_rules! def_prim_ty(
673         ($name:ident, $sty:expr, $id:expr) => (
674             pub static $name: t_box_ = t_box_ {
675                 sty: $sty,
676                 id: $id,
677                 flags: 0,
678             };
679         )
680     )
681
682     def_prim_ty!(TY_NIL,    super::ty_nil,                  0)
683     def_prim_ty!(TY_BOOL,   super::ty_bool,                 1)
684     def_prim_ty!(TY_CHAR,   super::ty_char,                 2)
685     def_prim_ty!(TY_INT,    super::ty_int(ast::TyI),        3)
686     def_prim_ty!(TY_I8,     super::ty_int(ast::TyI8),       4)
687     def_prim_ty!(TY_I16,    super::ty_int(ast::TyI16),      5)
688     def_prim_ty!(TY_I32,    super::ty_int(ast::TyI32),      6)
689     def_prim_ty!(TY_I64,    super::ty_int(ast::TyI64),      7)
690     def_prim_ty!(TY_UINT,   super::ty_uint(ast::TyU),       8)
691     def_prim_ty!(TY_U8,     super::ty_uint(ast::TyU8),      9)
692     def_prim_ty!(TY_U16,    super::ty_uint(ast::TyU16),     10)
693     def_prim_ty!(TY_U32,    super::ty_uint(ast::TyU32),     11)
694     def_prim_ty!(TY_U64,    super::ty_uint(ast::TyU64),     12)
695     def_prim_ty!(TY_F32,    super::ty_float(ast::TyF32),    14)
696     def_prim_ty!(TY_F64,    super::ty_float(ast::TyF64),    15)
697     def_prim_ty!(TY_F128,   super::ty_float(ast::TyF128),   16)
698
699     pub static TY_BOT: t_box_ = t_box_ {
700         sty: super::ty_bot,
701         id: 16,
702         flags: super::has_ty_bot as uint,
703     };
704
705     pub static TY_ERR: t_box_ = t_box_ {
706         sty: super::ty_err,
707         id: 17,
708         flags: super::has_ty_err as uint,
709     };
710
711     pub static LAST_PRIMITIVE_ID: uint = 18;
712 }
713
714 // NB: If you change this, you'll probably want to change the corresponding
715 // AST structure in libsyntax/ast.rs as well.
716 #[deriving(Clone, PartialEq, Eq, Hash)]
717 pub enum sty {
718     ty_nil,
719     ty_bot,
720     ty_bool,
721     ty_char,
722     ty_int(ast::IntTy),
723     ty_uint(ast::UintTy),
724     ty_float(ast::FloatTy),
725     ty_enum(DefId, Substs),
726     ty_box(t),
727     ty_uniq(t),
728     ty_str,
729     ty_vec(mt, Option<uint>),  // Second field is length.
730     ty_ptr(mt),
731     ty_rptr(Region, mt),
732     ty_bare_fn(BareFnTy),
733     ty_closure(Box<ClosureTy>),
734     ty_trait(Box<TyTrait>),
735     ty_struct(DefId, Substs),
736     ty_tup(Vec<t>),
737
738     ty_param(ParamTy), // type parameter
739     ty_infer(InferTy), // something used only during inference/typeck
740     ty_err, // Also only used during inference/typeck, to represent
741             // the type of an erroneous expression (helps cut down
742             // on non-useful type error messages)
743 }
744
745 #[deriving(Clone, PartialEq, Eq, Hash)]
746 pub struct TyTrait {
747     pub def_id: DefId,
748     pub substs: Substs,
749     pub bounds: BuiltinBounds
750 }
751
752 #[deriving(PartialEq, Eq, Hash)]
753 pub struct TraitRef {
754     pub def_id: DefId,
755     pub substs: Substs,
756 }
757
758 #[deriving(Clone, PartialEq)]
759 pub enum IntVarValue {
760     IntType(ast::IntTy),
761     UintType(ast::UintTy),
762 }
763
764 #[deriving(Clone, Show)]
765 pub enum terr_vstore_kind {
766     terr_vec,
767     terr_str,
768     terr_fn,
769     terr_trait
770 }
771
772 #[deriving(Clone, Show)]
773 pub struct expected_found<T> {
774     pub expected: T,
775     pub found: T
776 }
777
778 // Data structures used in type unification
779 #[deriving(Clone, Show)]
780 pub enum type_err {
781     terr_mismatch,
782     terr_fn_style_mismatch(expected_found<FnStyle>),
783     terr_onceness_mismatch(expected_found<Onceness>),
784     terr_abi_mismatch(expected_found<abi::Abi>),
785     terr_mutability,
786     terr_sigil_mismatch(expected_found<TraitStore>),
787     terr_box_mutability,
788     terr_ptr_mutability,
789     terr_ref_mutability,
790     terr_vec_mutability,
791     terr_tuple_size(expected_found<uint>),
792     terr_ty_param_size(expected_found<uint>),
793     terr_record_size(expected_found<uint>),
794     terr_record_mutability,
795     terr_record_fields(expected_found<Ident>),
796     terr_arg_count,
797     terr_regions_does_not_outlive(Region, Region),
798     terr_regions_not_same(Region, Region),
799     terr_regions_no_overlap(Region, Region),
800     terr_regions_insufficiently_polymorphic(BoundRegion, Region),
801     terr_regions_overly_polymorphic(BoundRegion, Region),
802     terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
803     terr_sorts(expected_found<t>),
804     terr_integer_as_char,
805     terr_int_mismatch(expected_found<IntVarValue>),
806     terr_float_mismatch(expected_found<ast::FloatTy>),
807     terr_traits(expected_found<ast::DefId>),
808     terr_builtin_bounds(expected_found<BuiltinBounds>),
809     terr_variadic_mismatch(expected_found<bool>)
810 }
811
812 #[deriving(PartialEq, Eq, Hash)]
813 pub struct ParamBounds {
814     pub builtin_bounds: BuiltinBounds,
815     pub trait_bounds: Vec<Rc<TraitRef>>
816 }
817
818 pub type BuiltinBounds = EnumSet<BuiltinBound>;
819
820 #[deriving(Clone, Encodable, PartialEq, Eq, Decodable, Hash, Show)]
821 #[repr(uint)]
822 pub enum BuiltinBound {
823     BoundStatic,
824     BoundSend,
825     BoundSized,
826     BoundCopy,
827     BoundShare,
828 }
829
830 pub fn empty_builtin_bounds() -> BuiltinBounds {
831     EnumSet::empty()
832 }
833
834 pub fn all_builtin_bounds() -> BuiltinBounds {
835     let mut set = EnumSet::empty();
836     set.add(BoundStatic);
837     set.add(BoundSend);
838     set.add(BoundSized);
839     set.add(BoundShare);
840     set
841 }
842
843 impl CLike for BuiltinBound {
844     fn to_uint(&self) -> uint {
845         *self as uint
846     }
847     fn from_uint(v: uint) -> BuiltinBound {
848         unsafe { mem::transmute(v) }
849     }
850 }
851
852 #[deriving(Clone, PartialEq, Eq, Hash)]
853 pub struct TyVid(pub uint);
854
855 #[deriving(Clone, PartialEq, Eq, Hash)]
856 pub struct IntVid(pub uint);
857
858 #[deriving(Clone, PartialEq, Eq, Hash)]
859 pub struct FloatVid(pub uint);
860
861 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]
862 pub struct RegionVid {
863     pub id: uint
864 }
865
866 #[deriving(Clone, PartialEq, Eq, Hash)]
867 pub enum InferTy {
868     TyVar(TyVid),
869     IntVar(IntVid),
870     FloatVar(FloatVid)
871 }
872
873 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
874 pub enum InferRegion {
875     ReVar(RegionVid),
876     ReSkolemized(uint, BoundRegion)
877 }
878
879 impl cmp::PartialEq for InferRegion {
880     fn eq(&self, other: &InferRegion) -> bool {
881         match ((*self), *other) {
882             (ReVar(rva), ReVar(rvb)) => {
883                 rva == rvb
884             }
885             (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
886                 rva == rvb
887             }
888             _ => false
889         }
890     }
891     fn ne(&self, other: &InferRegion) -> bool {
892         !((*self) == (*other))
893     }
894 }
895
896 pub trait Vid {
897     fn to_uint(&self) -> uint;
898 }
899
900 impl Vid for TyVid {
901     fn to_uint(&self) -> uint { let TyVid(v) = *self; v }
902 }
903
904 impl fmt::Show for TyVid {
905     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
906         write!(f, "<generic #{}>", self.to_uint())
907     }
908 }
909
910 impl Vid for IntVid {
911     fn to_uint(&self) -> uint { let IntVid(v) = *self; v }
912 }
913
914 impl fmt::Show for IntVid {
915     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
916         write!(f, "<generic integer #{}>", self.to_uint())
917     }
918 }
919
920 impl Vid for FloatVid {
921     fn to_uint(&self) -> uint { let FloatVid(v) = *self; v }
922 }
923
924 impl fmt::Show for FloatVid {
925     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926         write!(f, "<generic float #{}>", self.to_uint())
927     }
928 }
929
930 impl Vid for RegionVid {
931     fn to_uint(&self) -> uint { self.id }
932 }
933
934 impl fmt::Show for RegionVid {
935     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
936         self.id.fmt(f)
937     }
938 }
939
940 impl fmt::Show for FnSig {
941     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
942         // grr, without tcx not much we can do.
943         write!(f, "(...)")
944     }
945 }
946
947 impl fmt::Show for InferTy {
948     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
949         match *self {
950             TyVar(ref v) => v.fmt(f),
951             IntVar(ref v) => v.fmt(f),
952             FloatVar(ref v) => v.fmt(f),
953         }
954     }
955 }
956
957 impl fmt::Show for IntVarValue {
958     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
959         match *self {
960             IntType(ref v) => v.fmt(f),
961             UintType(ref v) => v.fmt(f),
962         }
963     }
964 }
965
966 #[deriving(Clone)]
967 pub struct TypeParameterDef {
968     pub ident: ast::Ident,
969     pub def_id: ast::DefId,
970     pub space: subst::ParamSpace,
971     pub index: uint,
972     pub bounds: Rc<ParamBounds>,
973     pub default: Option<ty::t>
974 }
975
976 #[deriving(Encodable, Decodable, Clone)]
977 pub struct RegionParameterDef {
978     pub name: ast::Name,
979     pub def_id: ast::DefId,
980     pub space: subst::ParamSpace,
981     pub index: uint,
982 }
983
984 /// Information about the type/lifetime parameters associated with an
985 /// item or method. Analogous to ast::Generics.
986 #[deriving(Clone)]
987 pub struct Generics {
988     pub types: VecPerParamSpace<TypeParameterDef>,
989     pub regions: VecPerParamSpace<RegionParameterDef>,
990 }
991
992 impl Generics {
993     pub fn empty() -> Generics {
994         Generics { types: VecPerParamSpace::empty(),
995                    regions: VecPerParamSpace::empty() }
996     }
997
998     pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
999         !self.types.get_vec(space).is_empty()
1000     }
1001 }
1002
1003 /// When type checking, we use the `ParameterEnvironment` to track
1004 /// details about the type/lifetime parameters that are in scope.
1005 /// It primarily stores the bounds information.
1006 ///
1007 /// Note: This information might seem to be redundant with the data in
1008 /// `tcx.ty_param_defs`, but it is not. That table contains the
1009 /// parameter definitions from an "outside" perspective, but this
1010 /// struct will contain the bounds for a parameter as seen from inside
1011 /// the function body. Currently the only real distinction is that
1012 /// bound lifetime parameters are replaced with free ones, but in the
1013 /// future I hope to refine the representation of types so as to make
1014 /// more distinctions clearer.
1015 pub struct ParameterEnvironment {
1016     /// A substitution that can be applied to move from
1017     /// the "outer" view of a type or method to the "inner" view.
1018     /// In general, this means converting from bound parameters to
1019     /// free parameters. Since we currently represent bound/free type
1020     /// parameters in the same way, this only has an affect on regions.
1021     pub free_substs: Substs,
1022
1023     /// Bounds on the various type parameters
1024     pub bounds: VecPerParamSpace<ParamBounds>,
1025 }
1026
1027 /// A polytype.
1028 ///
1029 /// - `bounds`: The list of bounds for each type parameter.  The length of the
1030 ///   list also tells you how many type parameters there are.
1031 ///
1032 /// - `rp`: true if the type is region-parameterized.  Types can have at
1033 ///   most one region parameter, always called `&self`.
1034 ///
1035 /// - `ty`: the base type.  May have reference to the (unsubstituted) bound
1036 ///   region `&self` or to (unsubstituted) ty_param types
1037 #[deriving(Clone)]
1038 pub struct ty_param_bounds_and_ty {
1039     pub generics: Generics,
1040     pub ty: t
1041 }
1042
1043 /// As `ty_param_bounds_and_ty` but for a trait ref.
1044 pub struct TraitDef {
1045     pub generics: Generics,
1046     pub bounds: BuiltinBounds,
1047     pub trait_ref: Rc<ty::TraitRef>,
1048 }
1049
1050 /// Records the substitutions used to translate the polytype for an
1051 /// item into the monotype of an item reference.
1052 #[deriving(Clone)]
1053 pub struct ItemSubsts {
1054     pub substs: Substs,
1055 }
1056
1057 pub type type_cache = RefCell<DefIdMap<ty_param_bounds_and_ty>>;
1058
1059 pub type node_type_table = RefCell<HashMap<uint,t>>;
1060
1061 pub fn mk_ctxt(s: Session,
1062                dm: resolve::DefMap,
1063                named_region_map: resolve_lifetime::NamedRegionMap,
1064                map: ast_map::Map,
1065                freevars: freevars::freevar_map,
1066                region_maps: middle::region::RegionMaps,
1067                lang_items: middle::lang_items::LanguageItems,
1068                stability: stability::Index)
1069             -> ctxt {
1070     ctxt {
1071         named_region_map: named_region_map,
1072         item_variance_map: RefCell::new(DefIdMap::new()),
1073         interner: RefCell::new(FnvHashMap::new()),
1074         next_id: Cell::new(primitives::LAST_PRIMITIVE_ID),
1075         sess: s,
1076         def_map: dm,
1077         region_maps: region_maps,
1078         node_types: RefCell::new(HashMap::new()),
1079         item_substs: RefCell::new(NodeMap::new()),
1080         trait_refs: RefCell::new(NodeMap::new()),
1081         trait_defs: RefCell::new(DefIdMap::new()),
1082         map: map,
1083         intrinsic_defs: RefCell::new(DefIdMap::new()),
1084         freevars: RefCell::new(freevars),
1085         tcache: RefCell::new(DefIdMap::new()),
1086         rcache: RefCell::new(HashMap::new()),
1087         short_names_cache: RefCell::new(HashMap::new()),
1088         needs_unwind_cleanup_cache: RefCell::new(HashMap::new()),
1089         tc_cache: RefCell::new(HashMap::new()),
1090         ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
1091         enum_var_cache: RefCell::new(DefIdMap::new()),
1092         methods: RefCell::new(DefIdMap::new()),
1093         trait_method_def_ids: RefCell::new(DefIdMap::new()),
1094         trait_methods_cache: RefCell::new(DefIdMap::new()),
1095         impl_trait_cache: RefCell::new(DefIdMap::new()),
1096         ty_param_defs: RefCell::new(NodeMap::new()),
1097         adjustments: RefCell::new(NodeMap::new()),
1098         normalized_cache: RefCell::new(HashMap::new()),
1099         lang_items: lang_items,
1100         provided_method_sources: RefCell::new(DefIdMap::new()),
1101         supertraits: RefCell::new(DefIdMap::new()),
1102         superstructs: RefCell::new(DefIdMap::new()),
1103         struct_fields: RefCell::new(DefIdMap::new()),
1104         destructor_for_type: RefCell::new(DefIdMap::new()),
1105         destructors: RefCell::new(DefIdSet::new()),
1106         trait_impls: RefCell::new(DefIdMap::new()),
1107         inherent_impls: RefCell::new(DefIdMap::new()),
1108         impl_methods: RefCell::new(DefIdMap::new()),
1109         used_unsafe: RefCell::new(NodeSet::new()),
1110         used_mut_nodes: RefCell::new(NodeSet::new()),
1111         impl_vtables: RefCell::new(DefIdMap::new()),
1112         populated_external_types: RefCell::new(DefIdSet::new()),
1113         populated_external_traits: RefCell::new(DefIdSet::new()),
1114         upvar_borrow_map: RefCell::new(HashMap::new()),
1115         extern_const_statics: RefCell::new(DefIdMap::new()),
1116         extern_const_variants: RefCell::new(DefIdMap::new()),
1117         method_map: RefCell::new(FnvHashMap::new()),
1118         vtable_map: RefCell::new(FnvHashMap::new()),
1119         dependency_formats: RefCell::new(HashMap::new()),
1120         node_lint_levels: RefCell::new(HashMap::new()),
1121         transmute_restrictions: RefCell::new(Vec::new()),
1122         stability: RefCell::new(stability)
1123     }
1124 }
1125
1126 // Type constructors
1127
1128 // Interns a type/name combination, stores the resulting box in cx.interner,
1129 // and returns the box as cast to an unsafe ptr (see comments for t above).
1130 pub fn mk_t(cx: &ctxt, st: sty) -> t {
1131     // Check for primitive types.
1132     match st {
1133         ty_nil => return mk_nil(),
1134         ty_err => return mk_err(),
1135         ty_bool => return mk_bool(),
1136         ty_int(i) => return mk_mach_int(i),
1137         ty_uint(u) => return mk_mach_uint(u),
1138         ty_float(f) => return mk_mach_float(f),
1139         ty_char => return mk_char(),
1140         ty_bot => return mk_bot(),
1141         _ => {}
1142     };
1143
1144     let key = intern_key { sty: &st };
1145
1146     match cx.interner.borrow().find(&key) {
1147         Some(t) => unsafe { return mem::transmute(&t.sty); },
1148         _ => ()
1149     }
1150
1151     let mut flags = 0u;
1152     fn rflags(r: Region) -> uint {
1153         (has_regions as uint) | {
1154             match r {
1155               ty::ReInfer(_) => needs_infer as uint,
1156               _ => 0u
1157             }
1158         }
1159     }
1160     fn sflags(substs: &Substs) -> uint {
1161         let mut f = 0u;
1162         let mut i = substs.types.iter();
1163         for tt in i {
1164             f |= get(*tt).flags;
1165         }
1166         match substs.regions {
1167             subst::ErasedRegions => {}
1168             subst::NonerasedRegions(ref regions) => {
1169                 for r in regions.iter() {
1170                     f |= rflags(*r)
1171                 }
1172             }
1173         }
1174         return f;
1175     }
1176     match &st {
1177       &ty_nil | &ty_bool | &ty_char | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1178       &ty_str => {}
1179       // You might think that we could just return ty_err for
1180       // any type containing ty_err as a component, and get
1181       // rid of the has_ty_err flag -- likewise for ty_bot (with
1182       // the exception of function types that return bot).
1183       // But doing so caused sporadic memory corruption, and
1184       // neither I (tjc) nor nmatsakis could figure out why,
1185       // so we're doing it this way.
1186       &ty_bot => flags |= has_ty_bot as uint,
1187       &ty_err => flags |= has_ty_err as uint,
1188       &ty_param(ref p) => {
1189           if p.space == subst::SelfSpace {
1190               flags |= has_self as uint;
1191           } else {
1192               flags |= has_params as uint;
1193           }
1194       }
1195       &ty_infer(_) => flags |= needs_infer as uint,
1196       &ty_enum(_, ref substs) | &ty_struct(_, ref substs) => {
1197           flags |= sflags(substs);
1198       }
1199       &ty_trait(box ty::TyTrait { ref substs, .. }) => {
1200           flags |= sflags(substs);
1201       }
1202       &ty_box(tt) | &ty_uniq(tt) => {
1203         flags |= get(tt).flags
1204       }
1205       &ty_ptr(ref m) | &ty_vec(ref m, _) => {
1206         flags |= get(m.ty).flags;
1207       }
1208       &ty_rptr(r, ref m) => {
1209         flags |= rflags(r);
1210         flags |= get(m.ty).flags;
1211       }
1212       &ty_tup(ref ts) => for tt in ts.iter() { flags |= get(*tt).flags; },
1213       &ty_bare_fn(ref f) => {
1214         for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1215         flags |= get(f.sig.output).flags;
1216         // T -> _|_ is *not* _|_ !
1217         flags &= !(has_ty_bot as uint);
1218       }
1219       &ty_closure(ref f) => {
1220         match f.store {
1221             RegionTraitStore(r, _) => {
1222                 flags |= rflags(r);
1223             }
1224             _ => {}
1225         }
1226         for a in f.sig.inputs.iter() { flags |= get(*a).flags; }
1227         flags |= get(f.sig.output).flags;
1228         // T -> _|_ is *not* _|_ !
1229         flags &= !(has_ty_bot as uint);
1230       }
1231     }
1232
1233     let t = box t_box_ {
1234         sty: st,
1235         id: cx.next_id.get(),
1236         flags: flags,
1237     };
1238
1239     let sty_ptr = &t.sty as *sty;
1240
1241     let key = intern_key {
1242         sty: sty_ptr,
1243     };
1244
1245     cx.interner.borrow_mut().insert(key, t);
1246
1247     cx.next_id.set(cx.next_id.get() + 1);
1248
1249     unsafe {
1250         mem::transmute::<*sty, t>(sty_ptr)
1251     }
1252 }
1253
1254 #[inline]
1255 pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1256     unsafe {
1257         mem::transmute::<&'static t_box_, t>(primitive)
1258     }
1259 }
1260
1261 #[inline]
1262 pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1263
1264 #[inline]
1265 pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1266
1267 #[inline]
1268 pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1269
1270 #[inline]
1271 pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1272
1273 #[inline]
1274 pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1275
1276 #[inline]
1277 pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1278
1279 #[inline]
1280 pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1281
1282 #[inline]
1283 pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1284
1285 #[inline]
1286 pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1287
1288 #[inline]
1289 pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1290
1291 #[inline]
1292 pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1293
1294 #[inline]
1295 pub fn mk_f128() -> t { mk_prim_t(&primitives::TY_F128) }
1296
1297 #[inline]
1298 pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1299
1300 #[inline]
1301 pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1302
1303 #[inline]
1304 pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1305
1306 #[inline]
1307 pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1308
1309 #[inline]
1310 pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1311
1312 pub fn mk_mach_int(tm: ast::IntTy) -> t {
1313     match tm {
1314         ast::TyI    => mk_int(),
1315         ast::TyI8   => mk_i8(),
1316         ast::TyI16  => mk_i16(),
1317         ast::TyI32  => mk_i32(),
1318         ast::TyI64  => mk_i64(),
1319     }
1320 }
1321
1322 pub fn mk_mach_uint(tm: ast::UintTy) -> t {
1323     match tm {
1324         ast::TyU    => mk_uint(),
1325         ast::TyU8   => mk_u8(),
1326         ast::TyU16  => mk_u16(),
1327         ast::TyU32  => mk_u32(),
1328         ast::TyU64  => mk_u64(),
1329     }
1330 }
1331
1332 pub fn mk_mach_float(tm: ast::FloatTy) -> t {
1333     match tm {
1334         ast::TyF32  => mk_f32(),
1335         ast::TyF64  => mk_f64(),
1336         ast::TyF128 => mk_f128()
1337     }
1338 }
1339
1340 #[inline]
1341 pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1342
1343 pub fn mk_str(cx: &ctxt) -> t {
1344     mk_t(cx, ty_str)
1345 }
1346
1347 pub fn mk_str_slice(cx: &ctxt, r: Region, m: ast::Mutability) -> t {
1348     mk_rptr(cx, r,
1349             mt {
1350                 ty: mk_t(cx, ty_str),
1351                 mutbl: m
1352             })
1353 }
1354
1355 pub fn mk_enum(cx: &ctxt, did: ast::DefId, substs: Substs) -> t {
1356     // take a copy of substs so that we own the vectors inside
1357     mk_t(cx, ty_enum(did, substs))
1358 }
1359
1360 pub fn mk_box(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_box(ty)) }
1361
1362 pub fn mk_uniq(cx: &ctxt, ty: t) -> t { mk_t(cx, ty_uniq(ty)) }
1363
1364 pub fn mk_ptr(cx: &ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1365
1366 pub fn mk_rptr(cx: &ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1367
1368 pub fn mk_mut_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1369     mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
1370 }
1371 pub fn mk_imm_rptr(cx: &ctxt, r: Region, ty: t) -> t {
1372     mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
1373 }
1374
1375 pub fn mk_mut_ptr(cx: &ctxt, ty: t) -> t {
1376     mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
1377 }
1378
1379 pub fn mk_imm_ptr(cx: &ctxt, ty: t) -> t {
1380     mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
1381 }
1382
1383 pub fn mk_nil_ptr(cx: &ctxt) -> t {
1384     mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::MutImmutable})
1385 }
1386
1387 pub fn mk_vec(cx: &ctxt, tm: mt, sz: Option<uint>) -> t {
1388     mk_t(cx, ty_vec(tm, sz))
1389 }
1390
1391 pub fn mk_slice(cx: &ctxt, r: Region, tm: mt) -> t {
1392     mk_rptr(cx, r,
1393             mt {
1394                 ty: mk_vec(cx, tm, None),
1395                 mutbl: tm.mutbl
1396             })
1397 }
1398
1399 pub fn mk_tup(cx: &ctxt, ts: Vec<t>) -> t { mk_t(cx, ty_tup(ts)) }
1400
1401 pub fn mk_closure(cx: &ctxt, fty: ClosureTy) -> t {
1402     mk_t(cx, ty_closure(box fty))
1403 }
1404
1405 pub fn mk_bare_fn(cx: &ctxt, fty: BareFnTy) -> t {
1406     mk_t(cx, ty_bare_fn(fty))
1407 }
1408
1409 pub fn mk_ctor_fn(cx: &ctxt,
1410                   binder_id: ast::NodeId,
1411                   input_tys: &[ty::t],
1412                   output: ty::t) -> t {
1413     let input_args = input_tys.iter().map(|t| *t).collect();
1414     mk_bare_fn(cx,
1415                BareFnTy {
1416                    fn_style: ast::NormalFn,
1417                    abi: abi::Rust,
1418                    sig: FnSig {
1419                     binder_id: binder_id,
1420                     inputs: input_args,
1421                     output: output,
1422                     variadic: false
1423                    }
1424                 })
1425 }
1426
1427
1428 pub fn mk_trait(cx: &ctxt,
1429                 did: ast::DefId,
1430                 substs: Substs,
1431                 bounds: BuiltinBounds)
1432              -> t {
1433     // take a copy of substs so that we own the vectors inside
1434     let inner = box TyTrait {
1435         def_id: did,
1436         substs: substs,
1437         bounds: bounds
1438     };
1439     mk_t(cx, ty_trait(inner))
1440 }
1441
1442 pub fn mk_struct(cx: &ctxt, struct_id: ast::DefId, substs: Substs) -> t {
1443     // take a copy of substs so that we own the vectors inside
1444     mk_t(cx, ty_struct(struct_id, substs))
1445 }
1446
1447 pub fn mk_var(cx: &ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1448
1449 pub fn mk_int_var(cx: &ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1450
1451 pub fn mk_float_var(cx: &ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1452
1453 pub fn mk_infer(cx: &ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1454
1455 pub fn mk_param(cx: &ctxt, space: subst::ParamSpace, n: uint, k: DefId) -> t {
1456     mk_t(cx, ty_param(ParamTy { space: space, idx: n, def_id: k }))
1457 }
1458
1459 pub fn mk_self_type(cx: &ctxt, did: ast::DefId) -> t {
1460     mk_param(cx, subst::SelfSpace, 0, did)
1461 }
1462
1463 pub fn mk_param_from_def(cx: &ctxt, def: &TypeParameterDef) -> t {
1464     mk_param(cx, def.space, def.index, def.def_id)
1465 }
1466
1467 pub fn walk_ty(ty: t, f: |t|) {
1468     maybe_walk_ty(ty, |t| { f(t); true });
1469 }
1470
1471 pub fn maybe_walk_ty(ty: t, f: |t| -> bool) {
1472     if !f(ty) {
1473         return;
1474     }
1475     match get(ty).sty {
1476         ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) |
1477         ty_str | ty_infer(_) | ty_param(_) | ty_err => {
1478         }
1479         ty_box(ty) | ty_uniq(ty) => maybe_walk_ty(ty, f),
1480         ty_ptr(ref tm) | ty_rptr(_, ref tm) | ty_vec(ref tm, _) => {
1481             maybe_walk_ty(tm.ty, f);
1482         }
1483         ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1484         ty_trait(box TyTrait { ref substs, .. }) => {
1485             for subty in (*substs).types.iter() {
1486                 maybe_walk_ty(*subty, |x| f(x));
1487             }
1488         }
1489         ty_tup(ref ts) => { for tt in ts.iter() { maybe_walk_ty(*tt, |x| f(x)); } }
1490         ty_bare_fn(ref ft) => {
1491             for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1492             maybe_walk_ty(ft.sig.output, f);
1493         }
1494         ty_closure(ref ft) => {
1495             for a in ft.sig.inputs.iter() { maybe_walk_ty(*a, |x| f(x)); }
1496             maybe_walk_ty(ft.sig.output, f);
1497         }
1498     }
1499 }
1500
1501 // Folds types from the bottom up.
1502 pub fn fold_ty(cx: &ctxt, t0: t, fldop: |t| -> t) -> t {
1503     let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
1504     f.fold_ty(t0)
1505 }
1506
1507 pub fn walk_regions_and_ty(cx: &ctxt, ty: t, fldr: |r: Region|, fldt: |t: t|)
1508                            -> t {
1509     ty_fold::RegionFolder::general(cx,
1510                                    |r| { fldr(r); r },
1511                                    |t| { fldt(t); t }).fold_ty(ty)
1512 }
1513
1514 impl ItemSubsts {
1515     pub fn empty() -> ItemSubsts {
1516         ItemSubsts { substs: Substs::empty() }
1517     }
1518
1519     pub fn is_noop(&self) -> bool {
1520         self.substs.is_noop()
1521     }
1522 }
1523
1524 // Type utilities
1525
1526 pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1527
1528 pub fn type_is_bot(ty: t) -> bool {
1529     (get(ty).flags & (has_ty_bot as uint)) != 0
1530 }
1531
1532 pub fn type_is_error(ty: t) -> bool {
1533     (get(ty).flags & (has_ty_err as uint)) != 0
1534 }
1535
1536 pub fn type_needs_subst(ty: t) -> bool {
1537     tbox_has_flag(get(ty), needs_subst)
1538 }
1539
1540 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1541     tref.substs.types.any(|&t| type_is_error(t))
1542 }
1543
1544 pub fn type_is_ty_var(ty: t) -> bool {
1545     match get(ty).sty {
1546       ty_infer(TyVar(_)) => true,
1547       _ => false
1548     }
1549 }
1550
1551 pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1552
1553 pub fn type_is_self(ty: t) -> bool {
1554     match get(ty).sty {
1555         ty_param(ref p) => p.space == subst::SelfSpace,
1556         _ => false
1557     }
1558 }
1559
1560 fn type_is_slice(ty:t) -> bool {
1561     match get(ty).sty {
1562         ty_rptr(_, mt) => match get(mt.ty).sty {
1563             ty_vec(_, None) | ty_str => true,
1564             _ => false,
1565         },
1566         _ => false
1567     }
1568 }
1569
1570 pub fn type_is_structural(ty: t) -> bool {
1571     match get(ty).sty {
1572       ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
1573       ty_vec(_, Some(_)) => true,
1574       _ => type_is_slice(ty) | type_is_trait(ty)
1575     }
1576 }
1577
1578 pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
1579     match get(ty).sty {
1580         ty_struct(did, _) => lookup_simd(cx, did),
1581         _ => false
1582     }
1583 }
1584
1585 pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
1586     match get(ty).sty {
1587         ty_vec(mt, Some(_)) => mt.ty,
1588         ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
1589         ty_box(t) | ty_uniq(t) => match get(t).sty {
1590             ty_vec(mt, None) => mt.ty,
1591             ty_str => mk_mach_uint(ast::TyU8),
1592             _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1593         },
1594         _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1595     }
1596 }
1597
1598 pub fn simd_type(cx: &ctxt, ty: t) -> t {
1599     match get(ty).sty {
1600         ty_struct(did, ref substs) => {
1601             let fields = lookup_struct_fields(cx, did);
1602             lookup_field_type(cx, did, fields.get(0).id, substs)
1603         }
1604         _ => fail!("simd_type called on invalid type")
1605     }
1606 }
1607
1608 pub fn simd_size(cx: &ctxt, ty: t) -> uint {
1609     match get(ty).sty {
1610         ty_struct(did, _) => {
1611             let fields = lookup_struct_fields(cx, did);
1612             fields.len()
1613         }
1614         _ => fail!("simd_size called on invalid type")
1615     }
1616 }
1617
1618 pub fn type_is_boxed(ty: t) -> bool {
1619     match get(ty).sty {
1620       ty_box(_) => true,
1621       _ => false
1622     }
1623 }
1624
1625 pub fn type_is_region_ptr(ty: t) -> bool {
1626     match get(ty).sty {
1627         ty_rptr(_, mt) => match get(mt.ty).sty {
1628             // FIXME(nrc, DST) slices weren't regarded as rptrs, so we preserve this
1629             // odd behaviour for now. (But ~[] were unique. I have no idea why).
1630             ty_vec(_, None) | ty_str | ty_trait(..) => false,
1631             _ => true
1632         },
1633         _ => false
1634     }
1635 }
1636
1637 pub fn type_is_unsafe_ptr(ty: t) -> bool {
1638     match get(ty).sty {
1639       ty_ptr(_) => return true,
1640       _ => return false
1641     }
1642 }
1643
1644 pub fn type_is_unique(ty: t) -> bool {
1645     match get(ty).sty {
1646         ty_uniq(_) => match get(ty).sty {
1647             ty_trait(..) => false,
1648             _ => true
1649         },
1650         _ => false
1651     }
1652 }
1653
1654 /*
1655  A scalar type is one that denotes an atomic datum, with no sub-components.
1656  (A ty_ptr is scalar because it represents a non-managed pointer, so its
1657  contents are abstract to rustc.)
1658 */
1659 pub fn type_is_scalar(ty: t) -> bool {
1660     match get(ty).sty {
1661       ty_nil | ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
1662       ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
1663       ty_bare_fn(..) | ty_ptr(_) => true,
1664       _ => false
1665     }
1666 }
1667
1668 /// Returns true if this type is a floating point type and false otherwise.
1669 pub fn type_is_floating_point(ty: t) -> bool {
1670     match get(ty).sty {
1671         ty_float(_) => true,
1672         _ => false,
1673     }
1674 }
1675
1676 pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool {
1677     type_contents(cx, ty).needs_drop(cx)
1678 }
1679
1680 // Some things don't need cleanups during unwinding because the
1681 // task can free them all at once later. Currently only things
1682 // that only contain scalars and shared boxes can avoid unwind
1683 // cleanups.
1684 pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool {
1685     match cx.needs_unwind_cleanup_cache.borrow().find(&ty) {
1686         Some(&result) => return result,
1687         None => ()
1688     }
1689
1690     let mut tycache = HashSet::new();
1691     let needs_unwind_cleanup =
1692         type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1693     cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup);
1694     return needs_unwind_cleanup;
1695 }
1696
1697 fn type_needs_unwind_cleanup_(cx: &ctxt, ty: t,
1698                               tycache: &mut HashSet<t>,
1699                               encountered_box: bool) -> bool {
1700
1701     // Prevent infinite recursion
1702     if !tycache.insert(ty) {
1703         return false;
1704     }
1705
1706     let mut encountered_box = encountered_box;
1707     let mut needs_unwind_cleanup = false;
1708     maybe_walk_ty(ty, |ty| {
1709         let old_encountered_box = encountered_box;
1710         let result = match get(ty).sty {
1711           ty_box(_) => {
1712             encountered_box = true;
1713             true
1714           }
1715           ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1716           ty_tup(_) | ty_ptr(_) => {
1717             true
1718           }
1719           ty_enum(did, ref substs) => {
1720             for v in (*enum_variants(cx, did)).iter() {
1721                 for aty in v.args.iter() {
1722                     let t = aty.subst(cx, substs);
1723                     needs_unwind_cleanup |=
1724                         type_needs_unwind_cleanup_(cx, t, tycache,
1725                                                    encountered_box);
1726                 }
1727             }
1728             !needs_unwind_cleanup
1729           }
1730           ty_uniq(_) => {
1731             // Once we're inside a box, the annihilator will find
1732             // it and destroy it.
1733             if !encountered_box {
1734                 needs_unwind_cleanup = true;
1735                 false
1736             } else {
1737                 true
1738             }
1739           }
1740           _ => {
1741             needs_unwind_cleanup = true;
1742             false
1743           }
1744         };
1745
1746         encountered_box = old_encountered_box;
1747         result
1748     });
1749
1750     return needs_unwind_cleanup;
1751 }
1752
1753 /**
1754  * Type contents is how the type checker reasons about kinds.
1755  * They track what kinds of things are found within a type.  You can
1756  * think of them as kind of an "anti-kind".  They track the kinds of values
1757  * and thinks that are contained in types.  Having a larger contents for
1758  * a type tends to rule that type *out* from various kinds.  For example,
1759  * a type that contains a reference is not sendable.
1760  *
1761  * The reason we compute type contents and not kinds is that it is
1762  * easier for me (nmatsakis) to think about what is contained within
1763  * a type than to think about what is *not* contained within a type.
1764  */
1765 pub struct TypeContents {
1766     pub bits: u64
1767 }
1768
1769 macro_rules! def_type_content_sets(
1770     (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
1771         mod $mname {
1772             use middle::ty::TypeContents;
1773             $(pub static $name: TypeContents = TypeContents { bits: $bits };)+
1774         }
1775     }
1776 )
1777
1778 def_type_content_sets!(
1779     mod TC {
1780         None                                = 0b0000_0000__0000_0000__0000,
1781
1782         // Things that are interior to the value (first nibble):
1783         InteriorUnsized                     = 0b0000_0000__0000_0000__0001,
1784         InteriorUnsafe                      = 0b0000_0000__0000_0000__0010,
1785         // InteriorAll                         = 0b00000000__00000000__1111,
1786
1787         // Things that are owned by the value (second and third nibbles):
1788         OwnsOwned                           = 0b0000_0000__0000_0001__0000,
1789         OwnsDtor                            = 0b0000_0000__0000_0010__0000,
1790         OwnsManaged /* see [1] below */     = 0b0000_0000__0000_0100__0000,
1791         OwnsAffine                          = 0b0000_0000__0000_1000__0000,
1792         OwnsAll                             = 0b0000_0000__1111_1111__0000,
1793
1794         // Things that are reachable by the value in any way (fourth nibble):
1795         ReachesNonsendAnnot                 = 0b0000_0001__0000_0000__0000,
1796         ReachesBorrowed                     = 0b0000_0010__0000_0000__0000,
1797         // ReachesManaged /* see [1] below */  = 0b0000_0100__0000_0000__0000,
1798         ReachesMutable                      = 0b0000_1000__0000_0000__0000,
1799         ReachesNoShare                      = 0b0001_0000__0000_0000__0000,
1800         ReachesAll                          = 0b0001_1111__0000_0000__0000,
1801
1802         // Things that cause values to *move* rather than *copy*
1803         Moves                               = 0b0000_0000__0000_1011__0000,
1804
1805         // Things that mean drop glue is necessary
1806         NeedsDrop                           = 0b0000_0000__0000_0111__0000,
1807
1808         // Things that prevent values from being sent
1809         //
1810         // Note: For checking whether something is sendable, it'd
1811         //       be sufficient to have ReachesManaged. However, we include
1812         //       both ReachesManaged and OwnsManaged so that when
1813         //       a parameter has a bound T:Send, we are able to deduce
1814         //       that it neither reaches nor owns a managed pointer.
1815         Nonsendable                         = 0b0000_0111__0000_0100__0000,
1816
1817         // Things that prevent values from being considered 'static
1818         Nonstatic                           = 0b0000_0010__0000_0000__0000,
1819
1820         // Things that prevent values from being considered sized
1821         Nonsized                            = 0b0000_0000__0000_0000__0001,
1822
1823         // Things that prevent values from being shared
1824         Nonsharable                         = 0b0001_0000__0000_0000__0000,
1825
1826         // Things that make values considered not POD (would be same
1827         // as `Moves`, but for the fact that managed data `@` is
1828         // not considered POD)
1829         Noncopy                              = 0b0000_0000__0000_1111__0000,
1830
1831         // Bits to set when a managed value is encountered
1832         //
1833         // [1] Do not set the bits TC::OwnsManaged or
1834         //     TC::ReachesManaged directly, instead reference
1835         //     TC::Managed to set them both at once.
1836         Managed                             = 0b0000_0100__0000_0100__0000,
1837
1838         // All bits
1839         All                                 = 0b1111_1111__1111_1111__1111
1840     }
1841 )
1842
1843 impl TypeContents {
1844     pub fn meets_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
1845         match bb {
1846             BoundStatic => self.is_static(cx),
1847             BoundSend => self.is_sendable(cx),
1848             BoundSized => self.is_sized(cx),
1849             BoundCopy => self.is_copy(cx),
1850             BoundShare => self.is_sharable(cx),
1851         }
1852     }
1853
1854     pub fn when(&self, cond: bool) -> TypeContents {
1855         if cond {*self} else {TC::None}
1856     }
1857
1858     pub fn intersects(&self, tc: TypeContents) -> bool {
1859         (self.bits & tc.bits) != 0
1860     }
1861
1862     pub fn is_static(&self, _: &ctxt) -> bool {
1863         !self.intersects(TC::Nonstatic)
1864     }
1865
1866     pub fn is_sendable(&self, _: &ctxt) -> bool {
1867         !self.intersects(TC::Nonsendable)
1868     }
1869
1870     pub fn is_sharable(&self, _: &ctxt) -> bool {
1871         !self.intersects(TC::Nonsharable)
1872     }
1873
1874     pub fn owns_managed(&self) -> bool {
1875         self.intersects(TC::OwnsManaged)
1876     }
1877
1878     pub fn owns_owned(&self) -> bool {
1879         self.intersects(TC::OwnsOwned)
1880     }
1881
1882     pub fn is_sized(&self, _: &ctxt) -> bool {
1883         !self.intersects(TC::Nonsized)
1884     }
1885
1886     pub fn is_copy(&self, _: &ctxt) -> bool {
1887         !self.intersects(TC::Noncopy)
1888     }
1889
1890     pub fn interior_unsafe(&self) -> bool {
1891         self.intersects(TC::InteriorUnsafe)
1892     }
1893
1894     pub fn interior_unsized(&self) -> bool {
1895         self.intersects(TC::InteriorUnsized)
1896     }
1897
1898     pub fn moves_by_default(&self, _: &ctxt) -> bool {
1899         self.intersects(TC::Moves)
1900     }
1901
1902     pub fn needs_drop(&self, _: &ctxt) -> bool {
1903         self.intersects(TC::NeedsDrop)
1904     }
1905
1906     pub fn owned_pointer(&self) -> TypeContents {
1907         /*!
1908          * Includes only those bits that still apply
1909          * when indirected through a `Box` pointer
1910          */
1911         TC::OwnsOwned | (
1912             *self & (TC::OwnsAll | TC::ReachesAll))
1913     }
1914
1915     pub fn reference(&self, bits: TypeContents) -> TypeContents {
1916         /*!
1917          * Includes only those bits that still apply
1918          * when indirected through a reference (`&`)
1919          */
1920         bits | (
1921             *self & TC::ReachesAll)
1922     }
1923
1924     pub fn managed_pointer(&self) -> TypeContents {
1925         /*!
1926          * Includes only those bits that still apply
1927          * when indirected through a managed pointer (`@`)
1928          */
1929         TC::Managed | (
1930             *self & TC::ReachesAll)
1931     }
1932
1933     pub fn unsafe_pointer(&self) -> TypeContents {
1934         /*!
1935          * Includes only those bits that still apply
1936          * when indirected through an unsafe pointer (`*`)
1937          */
1938         *self & TC::ReachesAll
1939     }
1940
1941     pub fn union<T>(v: &[T], f: |&T| -> TypeContents) -> TypeContents {
1942         v.iter().fold(TC::None, |tc, t| tc | f(t))
1943     }
1944
1945     pub fn has_dtor(&self) -> bool {
1946         self.intersects(TC::OwnsDtor)
1947     }
1948 }
1949
1950 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
1951     fn bitor(&self, other: &TypeContents) -> TypeContents {
1952         TypeContents {bits: self.bits | other.bits}
1953     }
1954 }
1955
1956 impl ops::BitAnd<TypeContents,TypeContents> for TypeContents {
1957     fn bitand(&self, other: &TypeContents) -> TypeContents {
1958         TypeContents {bits: self.bits & other.bits}
1959     }
1960 }
1961
1962 impl ops::Sub<TypeContents,TypeContents> for TypeContents {
1963     fn sub(&self, other: &TypeContents) -> TypeContents {
1964         TypeContents {bits: self.bits & !other.bits}
1965     }
1966 }
1967
1968 impl fmt::Show for TypeContents {
1969     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1970         write!(f, "TypeContents({:t})", self.bits)
1971     }
1972 }
1973
1974 pub fn type_is_static(cx: &ctxt, t: ty::t) -> bool {
1975     type_contents(cx, t).is_static(cx)
1976 }
1977
1978 pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool {
1979     type_contents(cx, t).is_sendable(cx)
1980 }
1981
1982 pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool {
1983     type_contents(cx, t).interior_unsafe()
1984 }
1985
1986 pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents {
1987     let ty_id = type_id(ty);
1988
1989     match cx.tc_cache.borrow().find(&ty_id) {
1990         Some(tc) => { return *tc; }
1991         None => {}
1992     }
1993
1994     let mut cache = HashMap::new();
1995     let result = tc_ty(cx, ty, &mut cache);
1996
1997     cx.tc_cache.borrow_mut().insert(ty_id, result);
1998     return result;
1999
2000     fn tc_ty(cx: &ctxt,
2001              ty: t,
2002              cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2003     {
2004         // Subtle: Note that we are *not* using cx.tc_cache here but rather a
2005         // private cache for this walk.  This is needed in the case of cyclic
2006         // types like:
2007         //
2008         //     struct List { next: Box<Option<List>>, ... }
2009         //
2010         // When computing the type contents of such a type, we wind up deeply
2011         // recursing as we go.  So when we encounter the recursive reference
2012         // to List, we temporarily use TC::None as its contents.  Later we'll
2013         // patch up the cache with the correct value, once we've computed it
2014         // (this is basically a co-inductive process, if that helps).  So in
2015         // the end we'll compute TC::OwnsOwned, in this case.
2016         //
2017         // The problem is, as we are doing the computation, we will also
2018         // compute an *intermediate* contents for, e.g., Option<List> of
2019         // TC::None.  This is ok during the computation of List itself, but if
2020         // we stored this intermediate value into cx.tc_cache, then later
2021         // requests for the contents of Option<List> would also yield TC::None
2022         // which is incorrect.  This value was computed based on the crutch
2023         // value for the type contents of list.  The correct value is
2024         // TC::OwnsOwned.  This manifested as issue #4821.
2025         let ty_id = type_id(ty);
2026         match cache.find(&ty_id) {
2027             Some(tc) => { return *tc; }
2028             None => {}
2029         }
2030         match cx.tc_cache.borrow().find(&ty_id) {    // Must check both caches!
2031             Some(tc) => { return *tc; }
2032             None => {}
2033         }
2034         cache.insert(ty_id, TC::None);
2035
2036         let result = match get(ty).sty {
2037             // Scalar and unique types are sendable, and durable
2038             ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
2039             ty_bare_fn(_) | ty::ty_char | ty_str => {
2040                 TC::None
2041             }
2042
2043             ty_closure(ref c) => {
2044                 closure_contents(cx, *c)
2045             }
2046
2047             ty_box(typ) => {
2048                 tc_ty(cx, typ, cache).managed_pointer()
2049             }
2050
2051             ty_uniq(typ) => {
2052                 match get(typ).sty {
2053                     ty_str => TC::OwnsOwned,
2054                     _ => tc_ty(cx, typ, cache).owned_pointer(),
2055                 }
2056             }
2057
2058             ty_trait(box ty::TyTrait { bounds, .. }) => {
2059                 object_contents(cx, bounds)
2060             }
2061
2062             ty_ptr(ref mt) => {
2063                 tc_ty(cx, mt.ty, cache).unsafe_pointer()
2064             }
2065
2066             ty_rptr(r, ref mt) => {
2067                 match get(mt.ty).sty {
2068                     ty_str => borrowed_contents(r, ast::MutImmutable),
2069                     _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(r, mt.mutbl)),
2070                 }
2071             }
2072
2073             ty_vec(mt, _) => {
2074                 tc_mt(cx, mt, cache)
2075             }
2076
2077             ty_struct(did, ref substs) => {
2078                 let flds = struct_fields(cx, did, substs);
2079                 let mut res =
2080                     TypeContents::union(flds.as_slice(),
2081                                         |f| tc_mt(cx, f.mt, cache));
2082                 if ty::has_dtor(cx, did) {
2083                     res = res | TC::OwnsDtor;
2084                 }
2085                 apply_lang_items(cx, did, res)
2086             }
2087
2088             ty_tup(ref tys) => {
2089                 TypeContents::union(tys.as_slice(),
2090                                     |ty| tc_ty(cx, *ty, cache))
2091             }
2092
2093             ty_enum(did, ref substs) => {
2094                 let variants = substd_enum_variants(cx, did, substs);
2095                 let res =
2096                     TypeContents::union(variants.as_slice(), |variant| {
2097                         TypeContents::union(variant.args.as_slice(),
2098                                             |arg_ty| {
2099                             tc_ty(cx, *arg_ty, cache)
2100                         })
2101                     });
2102                 apply_lang_items(cx, did, res)
2103             }
2104
2105             ty_param(p) => {
2106                 // We only ever ask for the kind of types that are defined in
2107                 // the current crate; therefore, the only type parameters that
2108                 // could be in scope are those defined in the current crate.
2109                 // If this assertion failures, it is likely because of a
2110                 // failure in the cross-crate inlining code to translate a
2111                 // def-id.
2112                 assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
2113
2114                 let ty_param_defs = cx.ty_param_defs.borrow();
2115                 let tp_def = ty_param_defs.get(&p.def_id.node);
2116                 kind_bounds_to_contents(cx,
2117                                         tp_def.bounds.builtin_bounds,
2118                                         tp_def.bounds.trait_bounds.as_slice())
2119             }
2120
2121             ty_infer(_) => {
2122                 // This occurs during coherence, but shouldn't occur at other
2123                 // times.
2124                 TC::All
2125             }
2126
2127             ty_err => {
2128                 cx.sess.bug("asked to compute contents of error type");
2129             }
2130         };
2131
2132         cache.insert(ty_id, result);
2133         return result;
2134     }
2135
2136     fn tc_mt(cx: &ctxt,
2137              mt: mt,
2138              cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2139     {
2140         let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
2141         mc | tc_ty(cx, mt.ty, cache)
2142     }
2143
2144     fn apply_lang_items(cx: &ctxt,
2145                         did: ast::DefId,
2146                         tc: TypeContents)
2147                         -> TypeContents {
2148         if Some(did) == cx.lang_items.no_send_bound() {
2149             tc | TC::ReachesNonsendAnnot
2150         } else if Some(did) == cx.lang_items.managed_bound() {
2151             tc | TC::Managed
2152         } else if Some(did) == cx.lang_items.no_copy_bound() {
2153             tc | TC::OwnsAffine
2154         } else if Some(did) == cx.lang_items.no_share_bound() {
2155             tc | TC::ReachesNoShare
2156         } else if Some(did) == cx.lang_items.unsafe_type() {
2157             // FIXME(#13231): This shouldn't be needed after
2158             // opt-in built-in bounds are implemented.
2159             (tc | TC::InteriorUnsafe) - TC::Nonsharable
2160         } else {
2161             tc
2162         }
2163     }
2164
2165     fn borrowed_contents(region: ty::Region,
2166                          mutbl: ast::Mutability)
2167                          -> TypeContents {
2168         /*!
2169          * Type contents due to containing a reference
2170          * with the region `region` and borrow kind `bk`
2171          */
2172
2173         let b = match mutbl {
2174             ast::MutMutable => TC::ReachesMutable | TC::OwnsAffine,
2175             ast::MutImmutable => TC::None,
2176         };
2177         b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
2178     }
2179
2180     fn closure_contents(cx: &ctxt, cty: &ClosureTy) -> TypeContents {
2181         // Closure contents are just like trait contents, but with potentially
2182         // even more stuff.
2183         let st = object_contents(cx, cty.bounds);
2184
2185         let st = match cty.store {
2186             UniqTraitStore => {
2187                 st.owned_pointer()
2188             }
2189             RegionTraitStore(r, mutbl) => {
2190                 st.reference(borrowed_contents(r, mutbl))
2191             }
2192         };
2193
2194         // This also prohibits "@once fn" from being copied, which allows it to
2195         // be called. Neither way really makes much sense.
2196         let ot = match cty.onceness {
2197             ast::Once => TC::OwnsAffine,
2198             ast::Many => TC::None,
2199         };
2200
2201         st | ot
2202     }
2203
2204     fn object_contents(cx: &ctxt,
2205                        bounds: BuiltinBounds)
2206                        -> TypeContents {
2207         // These are the type contents of the (opaque) interior
2208         kind_bounds_to_contents(cx, bounds, [])
2209     }
2210
2211     fn kind_bounds_to_contents(cx: &ctxt,
2212                                bounds: BuiltinBounds,
2213                                traits: &[Rc<TraitRef>])
2214                                -> TypeContents {
2215         let _i = indenter();
2216         let mut tc = TC::All;
2217         each_inherited_builtin_bound(cx, bounds, traits, |bound| {
2218             tc = tc - match bound {
2219                 BoundStatic => TC::Nonstatic,
2220                 BoundSend => TC::Nonsendable,
2221                 BoundSized => TC::Nonsized,
2222                 BoundCopy => TC::Noncopy,
2223                 BoundShare => TC::Nonsharable,
2224             };
2225         });
2226         return tc;
2227
2228         // Iterates over all builtin bounds on the type parameter def, including
2229         // those inherited from traits with builtin-kind-supertraits.
2230         fn each_inherited_builtin_bound(cx: &ctxt,
2231                                         bounds: BuiltinBounds,
2232                                         traits: &[Rc<TraitRef>],
2233                                         f: |BuiltinBound|) {
2234             for bound in bounds.iter() {
2235                 f(bound);
2236             }
2237
2238             each_bound_trait_and_supertraits(cx, traits, |trait_ref| {
2239                 let trait_def = lookup_trait_def(cx, trait_ref.def_id);
2240                 for bound in trait_def.bounds.iter() {
2241                     f(bound);
2242                 }
2243                 true
2244             });
2245         }
2246     }
2247 }
2248
2249 pub fn type_moves_by_default(cx: &ctxt, ty: t) -> bool {
2250     type_contents(cx, ty).moves_by_default(cx)
2251 }
2252
2253 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2254 pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool {
2255     fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>,
2256                      r_ty: t, ty: t) -> bool {
2257         debug!("type_requires({}, {})?",
2258                ::util::ppaux::ty_to_str(cx, r_ty),
2259                ::util::ppaux::ty_to_str(cx, ty));
2260
2261         let r = {
2262             get(r_ty).sty == get(ty).sty ||
2263                 subtypes_require(cx, seen, r_ty, ty)
2264         };
2265
2266         debug!("type_requires({}, {})? {}",
2267                ::util::ppaux::ty_to_str(cx, r_ty),
2268                ::util::ppaux::ty_to_str(cx, ty),
2269                r);
2270         return r;
2271     }
2272
2273     fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>,
2274                         r_ty: t, ty: t) -> bool {
2275         debug!("subtypes_require({}, {})?",
2276                ::util::ppaux::ty_to_str(cx, r_ty),
2277                ::util::ppaux::ty_to_str(cx, ty));
2278
2279         let r = match get(ty).sty {
2280             // fixed length vectors need special treatment compared to
2281             // normal vectors, since they don't necessarily have the
2282             // possibility to have length zero.
2283             ty_vec(_, Some(0)) => false, // don't need no contents
2284             ty_vec(mt, Some(_)) => type_requires(cx, seen, r_ty, mt.ty),
2285
2286             ty_nil |
2287             ty_bot |
2288             ty_bool |
2289             ty_char |
2290             ty_int(_) |
2291             ty_uint(_) |
2292             ty_float(_) |
2293             ty_str |
2294             ty_bare_fn(_) |
2295             ty_closure(_) |
2296             ty_infer(_) |
2297             ty_err |
2298             ty_param(_) |
2299             ty_vec(_, None) => {
2300                 false
2301             }
2302             ty_box(typ) | ty_uniq(typ) => {
2303                 type_requires(cx, seen, r_ty, typ)
2304             }
2305             ty_rptr(_, ref mt) => {
2306                 type_requires(cx, seen, r_ty, mt.ty)
2307             }
2308
2309             ty_ptr(..) => {
2310                 false           // unsafe ptrs can always be NULL
2311             }
2312
2313             ty_trait(..) => {
2314                 false
2315             }
2316
2317             ty_struct(ref did, _) if seen.contains(did) => {
2318                 false
2319             }
2320
2321             ty_struct(did, ref substs) => {
2322                 seen.push(did);
2323                 let fields = struct_fields(cx, did, substs);
2324                 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2325                 seen.pop().unwrap();
2326                 r
2327             }
2328
2329             ty_tup(ref ts) => {
2330                 ts.iter().any(|t| type_requires(cx, seen, r_ty, *t))
2331             }
2332
2333             ty_enum(ref did, _) if seen.contains(did) => {
2334                 false
2335             }
2336
2337             ty_enum(did, ref substs) => {
2338                 seen.push(did);
2339                 let vs = enum_variants(cx, did);
2340                 let r = !vs.is_empty() && vs.iter().all(|variant| {
2341                     variant.args.iter().any(|aty| {
2342                         let sty = aty.subst(cx, substs);
2343                         type_requires(cx, seen, r_ty, sty)
2344                     })
2345                 });
2346                 seen.pop().unwrap();
2347                 r
2348             }
2349         };
2350
2351         debug!("subtypes_require({}, {})? {}",
2352                ::util::ppaux::ty_to_str(cx, r_ty),
2353                ::util::ppaux::ty_to_str(cx, ty),
2354                r);
2355
2356         return r;
2357     }
2358
2359     let mut seen = Vec::new();
2360     !subtypes_require(cx, &mut seen, r_ty, r_ty)
2361 }
2362
2363 /// Describes whether a type is representable. For types that are not
2364 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
2365 /// distinguish between types that are recursive with themselves and types that
2366 /// contain a different recursive type. These cases can therefore be treated
2367 /// differently when reporting errors.
2368 #[deriving(PartialEq)]
2369 pub enum Representability {
2370     Representable,
2371     SelfRecursive,
2372     ContainsRecursive,
2373 }
2374
2375 /// Check whether a type is representable. This means it cannot contain unboxed
2376 /// structural recursion. This check is needed for structs and enums.
2377 pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability {
2378
2379     // Iterate until something non-representable is found
2380     fn find_nonrepresentable<It: Iterator<t>>(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2381                                               mut iter: It) -> Representability {
2382         for ty in iter {
2383             let r = type_structurally_recursive(cx, sp, seen, ty);
2384             if r != Representable {
2385                  return r
2386             }
2387         }
2388         Representable
2389     }
2390
2391     // Does the type `ty` directly (without indirection through a pointer)
2392     // contain any types on stack `seen`?
2393     fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>,
2394                                    ty: t) -> Representability {
2395         debug!("type_structurally_recursive: {}",
2396                ::util::ppaux::ty_to_str(cx, ty));
2397
2398         // Compare current type to previously seen types
2399         match get(ty).sty {
2400             ty_struct(did, _) |
2401             ty_enum(did, _) => {
2402                 for (i, &seen_did) in seen.iter().enumerate() {
2403                     if did == seen_did {
2404                         return if i == 0 { SelfRecursive }
2405                                else { ContainsRecursive }
2406                     }
2407                 }
2408             }
2409             _ => (),
2410         }
2411
2412         // Check inner types
2413         match get(ty).sty {
2414             // Tuples
2415             ty_tup(ref ts) => {
2416                 find_nonrepresentable(cx, sp, seen, ts.iter().map(|t| *t))
2417             }
2418             // Fixed-length vectors.
2419             // FIXME(#11924) Behavior undecided for zero-length vectors.
2420             ty_vec(mt, Some(_)) => {
2421                 type_structurally_recursive(cx, sp, seen, mt.ty)
2422             }
2423
2424             // Push struct and enum def-ids onto `seen` before recursing.
2425             ty_struct(did, ref substs) => {
2426                 seen.push(did);
2427                 let fields = struct_fields(cx, did, substs);
2428                 let r = find_nonrepresentable(cx, sp, seen,
2429                                               fields.iter().map(|f| f.mt.ty));
2430                 seen.pop();
2431                 r
2432             }
2433             ty_enum(did, ref substs) => {
2434                 seen.push(did);
2435                 let vs = enum_variants(cx, did);
2436
2437                 let mut r = Representable;
2438                 for variant in vs.iter() {
2439                     let iter = variant.args.iter().map(|aty| {
2440                         aty.subst_spanned(cx, substs, Some(sp))
2441                     });
2442                     r = find_nonrepresentable(cx, sp, seen, iter);
2443
2444                     if r != Representable { break }
2445                 }
2446
2447                 seen.pop();
2448                 r
2449             }
2450
2451             _ => Representable,
2452         }
2453     }
2454
2455     debug!("is_type_representable: {}",
2456            ::util::ppaux::ty_to_str(cx, ty));
2457
2458     // To avoid a stack overflow when checking an enum variant or struct that
2459     // contains a different, structurally recursive type, maintain a stack
2460     // of seen types and check recursion for each of them (issues #3008, #3779).
2461     let mut seen: Vec<DefId> = Vec::new();
2462     type_structurally_recursive(cx, sp, &mut seen, ty)
2463 }
2464
2465 pub fn type_is_trait(ty: t) -> bool {
2466     match get(ty).sty {
2467         ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) => match get(ty).sty {
2468             ty_trait(..) => true,
2469             _ => false
2470         },
2471         ty_trait(..) => true,
2472         _ => false
2473     }
2474 }
2475
2476 pub fn type_is_integral(ty: t) -> bool {
2477     match get(ty).sty {
2478       ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
2479       _ => false
2480     }
2481 }
2482
2483 pub fn type_is_uint(ty: t) -> bool {
2484     match get(ty).sty {
2485       ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
2486       _ => false
2487     }
2488 }
2489
2490 pub fn type_is_char(ty: t) -> bool {
2491     match get(ty).sty {
2492         ty_char => true,
2493         _ => false
2494     }
2495 }
2496
2497 pub fn type_is_bare_fn(ty: t) -> bool {
2498     match get(ty).sty {
2499         ty_bare_fn(..) => true,
2500         _ => false
2501     }
2502 }
2503
2504 pub fn type_is_fp(ty: t) -> bool {
2505     match get(ty).sty {
2506       ty_infer(FloatVar(_)) | ty_float(_) => true,
2507       _ => false
2508     }
2509 }
2510
2511 pub fn type_is_numeric(ty: t) -> bool {
2512     return type_is_integral(ty) || type_is_fp(ty);
2513 }
2514
2515 pub fn type_is_signed(ty: t) -> bool {
2516     match get(ty).sty {
2517       ty_int(_) => true,
2518       _ => false
2519     }
2520 }
2521
2522 pub fn type_is_machine(ty: t) -> bool {
2523     match get(ty).sty {
2524         ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
2525         ty_int(..) | ty_uint(..) | ty_float(..) => true,
2526         _ => false
2527     }
2528 }
2529
2530 // Is the type's representation size known at compile time?
2531 #[allow(dead_code)] // leaving in for DST
2532 pub fn type_is_sized(cx: &ctxt, ty: ty::t) -> bool {
2533     type_contents(cx, ty).is_sized(cx)
2534 }
2535
2536 // Whether a type is enum like, that is an enum type with only nullary
2537 // constructors
2538 pub fn type_is_c_like_enum(cx: &ctxt, ty: t) -> bool {
2539     match get(ty).sty {
2540         ty_enum(did, _) => {
2541             let variants = enum_variants(cx, did);
2542             if variants.len() == 0 {
2543                 false
2544             } else {
2545                 variants.iter().all(|v| v.args.len() == 0)
2546             }
2547         }
2548         _ => false
2549     }
2550 }
2551
2552 // Returns the type and mutability of *t.
2553 //
2554 // The parameter `explicit` indicates if this is an *explicit* dereference.
2555 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2556 pub fn deref(t: t, explicit: bool) -> Option<mt> {
2557     match get(t).sty {
2558         ty_box(typ) | ty_uniq(typ) => match get(typ).sty {
2559             // Don't deref ~[] etc., might need to generalise this to all DST.
2560             ty_vec(_, None) | ty_str | ty_trait(..) => None,
2561             _ => Some(mt {
2562                 ty: typ,
2563                 mutbl: ast::MutImmutable,
2564             }),
2565         },
2566         ty_rptr(_, mt) => match get(mt.ty).sty {
2567             // Don't deref &[], might need to generalise this to all DST.
2568             ty_vec(_, None) | ty_str | ty_trait(..) => None,
2569             _ => Some(mt),
2570         },
2571         ty_ptr(mt) if explicit => Some(mt),
2572         _ => None
2573     }
2574 }
2575
2576 // Returns the type of t[i]
2577 pub fn index(t: t) -> Option<mt> {
2578     match get(t).sty {
2579         ty_vec(mt, Some(_)) => Some(mt),
2580         ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) |
2581         ty_box(t) | ty_uniq(t) => match get(t).sty {
2582             ty_vec(mt, None) => Some(mt),
2583             ty_str => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}),
2584             _ => None,
2585         },
2586         _ => None
2587     }
2588 }
2589
2590 pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
2591     match cx.trait_refs.borrow().find(&id) {
2592         Some(t) => t.clone(),
2593         None => cx.sess.bug(
2594             format!("node_id_to_trait_ref: no trait ref for node `{}`",
2595                     cx.map.node_to_str(id)).as_slice())
2596     }
2597 }
2598
2599 pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2600     cx.node_types.borrow().find_copy(&(id as uint))
2601 }
2602
2603 pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
2604     match try_node_id_to_type(cx, id) {
2605        Some(t) => t,
2606        None => cx.sess.bug(
2607            format!("node_id_to_type: no type for node `{}`",
2608                    cx.map.node_to_str(id)).as_slice())
2609     }
2610 }
2611
2612 pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
2613     match cx.node_types.borrow().find(&(id as uint)) {
2614        Some(&t) => Some(t),
2615        None => None
2616     }
2617 }
2618
2619 pub fn node_id_item_substs(cx: &ctxt, id: ast::NodeId) -> ItemSubsts {
2620     match cx.item_substs.borrow().find(&id) {
2621       None => ItemSubsts::empty(),
2622       Some(ts) => ts.clone(),
2623     }
2624 }
2625
2626 pub fn fn_is_variadic(fty: t) -> bool {
2627     match get(fty).sty {
2628         ty_bare_fn(ref f) => f.sig.variadic,
2629         ty_closure(ref f) => f.sig.variadic,
2630         ref s => {
2631             fail!("fn_is_variadic() called on non-fn type: {:?}", s)
2632         }
2633     }
2634 }
2635
2636 pub fn ty_fn_sig(fty: t) -> FnSig {
2637     match get(fty).sty {
2638         ty_bare_fn(ref f) => f.sig.clone(),
2639         ty_closure(ref f) => f.sig.clone(),
2640         ref s => {
2641             fail!("ty_fn_sig() called on non-fn type: {:?}", s)
2642         }
2643     }
2644 }
2645
2646 // Type accessors for substructures of types
2647 pub fn ty_fn_args(fty: t) -> Vec<t> {
2648     match get(fty).sty {
2649         ty_bare_fn(ref f) => f.sig.inputs.clone(),
2650         ty_closure(ref f) => f.sig.inputs.clone(),
2651         ref s => {
2652             fail!("ty_fn_args() called on non-fn type: {:?}", s)
2653         }
2654     }
2655 }
2656
2657 pub fn ty_closure_store(fty: t) -> TraitStore {
2658     match get(fty).sty {
2659         ty_closure(ref f) => f.store,
2660         ref s => {
2661             fail!("ty_closure_store() called on non-closure type: {:?}", s)
2662         }
2663     }
2664 }
2665
2666 pub fn ty_fn_ret(fty: t) -> t {
2667     match get(fty).sty {
2668         ty_bare_fn(ref f) => f.sig.output,
2669         ty_closure(ref f) => f.sig.output,
2670         ref s => {
2671             fail!("ty_fn_ret() called on non-fn type: {:?}", s)
2672         }
2673     }
2674 }
2675
2676 pub fn is_fn_ty(fty: t) -> bool {
2677     match get(fty).sty {
2678         ty_bare_fn(_) => true,
2679         ty_closure(_) => true,
2680         _ => false
2681     }
2682 }
2683
2684 pub fn ty_region(tcx: &ctxt,
2685                  span: Span,
2686                  ty: t) -> Region {
2687     match get(ty).sty {
2688         ty_rptr(r, _) => r,
2689         ref s => {
2690             tcx.sess.span_bug(
2691                 span,
2692                 format!("ty_region() invoked on in appropriate ty: {:?}",
2693                         s).as_slice());
2694         }
2695     }
2696 }
2697
2698 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
2699     -> ty::Region
2700 {
2701     ty::ReFree(ty::FreeRegion { scope_id: free_id,
2702                                 bound_region: ty::BrNamed(def.def_id,
2703                                                           def.name) })
2704 }
2705
2706 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
2707 // doesn't provide type parameter substitutions.
2708 pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
2709     return node_id_to_type(cx, pat.id);
2710 }
2711
2712
2713 // Returns the type of an expression as a monotype.
2714 //
2715 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
2716 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
2717 // auto-ref.  The type returned by this function does not consider such
2718 // adjustments.  See `expr_ty_adjusted()` instead.
2719 //
2720 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
2721 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
2722 // instead of "fn(t) -> T with T = int".
2723 pub fn expr_ty(cx: &ctxt, expr: &ast::Expr) -> t {
2724     return node_id_to_type(cx, expr.id);
2725 }
2726
2727 pub fn expr_ty_opt(cx: &ctxt, expr: &ast::Expr) -> Option<t> {
2728     return node_id_to_type_opt(cx, expr.id);
2729 }
2730
2731 pub fn expr_ty_adjusted(cx: &ctxt, expr: &ast::Expr) -> t {
2732     /*!
2733      *
2734      * Returns the type of `expr`, considering any `AutoAdjustment`
2735      * entry recorded for that expression.
2736      *
2737      * It would almost certainly be better to store the adjusted ty in with
2738      * the `AutoAdjustment`, but I opted not to do this because it would
2739      * require serializing and deserializing the type and, although that's not
2740      * hard to do, I just hate that code so much I didn't want to touch it
2741      * unless it was to fix it properly, which seemed a distraction from the
2742      * task at hand! -nmatsakis
2743      */
2744
2745     adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
2746               cx.adjustments.borrow().find(&expr.id),
2747               |method_call| cx.method_map.borrow().find(&method_call).map(|method| method.ty))
2748 }
2749
2750 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
2751     match cx.map.find(id) {
2752         Some(ast_map::NodeExpr(e)) => {
2753             e.span
2754         }
2755         Some(f) => {
2756             cx.sess.bug(format!("Node id {} is not an expr: {:?}",
2757                                 id,
2758                                 f).as_slice());
2759         }
2760         None => {
2761             cx.sess.bug(format!("Node id {} is not present \
2762                                 in the node map", id).as_slice());
2763         }
2764     }
2765 }
2766
2767 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
2768     match cx.map.find(id) {
2769         Some(ast_map::NodeLocal(pat)) => {
2770             match pat.node {
2771                 ast::PatIdent(_, ref path, _) => {
2772                     token::get_ident(ast_util::path_to_ident(path))
2773                 }
2774                 _ => {
2775                     cx.sess.bug(
2776                         format!("Variable id {} maps to {:?}, not local",
2777                                 id,
2778                                 pat).as_slice());
2779                 }
2780             }
2781         }
2782         r => {
2783             cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
2784                                 id,
2785                                 r).as_slice());
2786         }
2787     }
2788 }
2789
2790 pub fn adjust_ty(cx: &ctxt,
2791                  span: Span,
2792                  expr_id: ast::NodeId,
2793                  unadjusted_ty: ty::t,
2794                  adjustment: Option<&AutoAdjustment>,
2795                  method_type: |typeck::MethodCall| -> Option<ty::t>)
2796                  -> ty::t {
2797     /*! See `expr_ty_adjusted` */
2798
2799     return match adjustment {
2800         Some(adjustment) => {
2801             match *adjustment {
2802                 AutoAddEnv(store) => {
2803                     match ty::get(unadjusted_ty).sty {
2804                         ty::ty_bare_fn(ref b) => {
2805                             ty::mk_closure(
2806                                 cx,
2807                                 ty::ClosureTy {fn_style: b.fn_style,
2808                                                onceness: ast::Many,
2809                                                store: store,
2810                                                bounds: ty::all_builtin_bounds(),
2811                                                sig: b.sig.clone()})
2812                         }
2813                         ref b => {
2814                             cx.sess.bug(
2815                                 format!("add_env adjustment on non-bare-fn: \
2816                                          {:?}",
2817                                         b).as_slice());
2818                         }
2819                     }
2820                 }
2821
2822                 AutoDerefRef(ref adj) => {
2823                     let mut adjusted_ty = unadjusted_ty;
2824
2825                     if !ty::type_is_error(adjusted_ty) {
2826                         for i in range(0, adj.autoderefs) {
2827                             let method_call = typeck::MethodCall::autoderef(expr_id, i);
2828                             match method_type(method_call) {
2829                                 Some(method_ty) => {
2830                                     adjusted_ty = ty_fn_ret(method_ty);
2831                                 }
2832                                 None => {}
2833                             }
2834                             match deref(adjusted_ty, true) {
2835                                 Some(mt) => { adjusted_ty = mt.ty; }
2836                                 None => {
2837                                     cx.sess.span_bug(
2838                                         span,
2839                                         format!("the {}th autoderef failed: \
2840                                                 {}",
2841                                                 i,
2842                                                 ty_to_str(cx, adjusted_ty))
2843                                                           .as_slice());
2844                                 }
2845                             }
2846                         }
2847                     }
2848
2849                     match adj.autoref {
2850                         None => adjusted_ty,
2851                         Some(ref autoref) => {
2852                             match *autoref {
2853                                 AutoPtr(r, m) => {
2854                                     mk_rptr(cx, r, mt {
2855                                         ty: adjusted_ty,
2856                                         mutbl: m
2857                                     })
2858                                 }
2859
2860                                 AutoBorrowVec(r, m) => {
2861                                     borrow_vec(cx, span, r, m, adjusted_ty)
2862                                 }
2863
2864                                 AutoBorrowVecRef(r, m) => {
2865                                     adjusted_ty = borrow_vec(cx,
2866                                                              span,
2867                                                              r,
2868                                                              m,
2869                                                              adjusted_ty);
2870                                     mk_rptr(cx, r, mt {
2871                                         ty: adjusted_ty,
2872                                         mutbl: ast::MutImmutable
2873                                     })
2874                                 }
2875
2876                                 AutoUnsafe(m) => {
2877                                     mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
2878                                 }
2879
2880                                 AutoBorrowObj(r, m) => {
2881                                     borrow_obj(cx, span, r, m, adjusted_ty)
2882                                 }
2883                             }
2884                         }
2885                     }
2886                 }
2887
2888                 AutoObject(store, bounds, def_id, ref substs) => {
2889
2890                     let tr = mk_trait(cx, def_id, substs.clone(), bounds);
2891                     match store {
2892                         UniqTraitStore => {
2893                             mk_uniq(cx, tr)
2894                         }
2895                         RegionTraitStore(r, m) => {
2896                             mk_rptr(cx, r, mt {
2897                                 ty: tr,
2898                                 mutbl: m
2899                             })
2900                         }
2901                     }
2902                 }
2903             }
2904         }
2905         None => unadjusted_ty
2906     };
2907
2908     fn borrow_vec(cx: &ctxt,
2909                   span: Span,
2910                   r: Region,
2911                   m: ast::Mutability,
2912                   ty: ty::t) -> ty::t {
2913         match get(ty).sty {
2914             ty_uniq(t) | ty_ptr(mt{ty: t, ..}) |
2915             ty_rptr(_, mt{ty: t, ..}) => match get(t).sty {
2916                 ty::ty_vec(mt, None) => ty::mk_slice(cx, r, ty::mt {ty: mt.ty, mutbl: m}),
2917                 ty::ty_str => ty::mk_str_slice(cx, r, m),
2918                 _ => {
2919                     cx.sess.span_bug(
2920                         span,
2921                         format!("borrow-vec associated with bad sty: {:?}",
2922                                 get(ty).sty).as_slice());
2923                 }
2924             },
2925             ty_vec(mt, Some(_)) => ty::mk_slice(cx, r, ty::mt {ty: mt.ty, mutbl: m}),
2926
2927             ref s => {
2928                 cx.sess.span_bug(
2929                     span,
2930                     format!("borrow-vec associated with bad sty: {:?}",
2931                             s).as_slice());
2932             }
2933         }
2934     }
2935
2936     fn borrow_obj(cx: &ctxt, span: Span, r: Region,
2937                   m: ast::Mutability, ty: ty::t) -> ty::t {
2938         match get(ty).sty {
2939             ty_uniq(t) | ty_rptr(_, mt{ty: t, ..}) => match get(t).sty {
2940                 ty_trait(box ty::TyTrait {def_id, ref substs, bounds, .. }) => {
2941                     mk_rptr(cx, r, mt {
2942                         ty: ty::mk_trait(cx, def_id, substs.clone(), bounds),
2943                         mutbl: m
2944                     })
2945                 }
2946                 _ => {
2947                     cx.sess.span_bug(
2948                         span,
2949                         format!("borrow-trait-obj associated with bad sty: {:?}",
2950                                 get(ty).sty).as_slice());
2951                 }
2952             },
2953             ref s => {
2954                 cx.sess.span_bug(
2955                     span,
2956                     format!("borrow-trait-obj associated with bad sty: {:?}",
2957                             s).as_slice());
2958             }
2959         }
2960     }
2961 }
2962
2963 impl AutoRef {
2964     pub fn map_region(&self, f: |Region| -> Region) -> AutoRef {
2965         match *self {
2966             ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
2967             ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
2968             ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
2969             ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
2970             ty::AutoBorrowObj(r, m) => ty::AutoBorrowObj(f(r), m),
2971         }
2972     }
2973 }
2974
2975 pub fn method_call_type_param_defs(tcx: &ctxt, origin: typeck::MethodOrigin)
2976                                    -> VecPerParamSpace<TypeParameterDef> {
2977     match origin {
2978         typeck::MethodStatic(did) => {
2979             ty::lookup_item_type(tcx, did).generics.types.clone()
2980         }
2981         typeck::MethodParam(typeck::MethodParam{trait_id: trt_id,
2982                                                 method_num: n_mth, ..}) |
2983         typeck::MethodObject(typeck::MethodObject{trait_id: trt_id,
2984                                                   method_num: n_mth, ..}) => {
2985             ty::trait_method(tcx, trt_id, n_mth).generics.types.clone()
2986         }
2987     }
2988 }
2989
2990 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
2991     match tcx.def_map.borrow().find(&expr.id) {
2992         Some(&def) => def,
2993         None => {
2994             tcx.sess.span_bug(expr.span, format!(
2995                 "no def-map entry for expr {:?}", expr.id).as_slice());
2996         }
2997     }
2998 }
2999
3000 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
3001     match expr_kind(tcx, e) {
3002         LvalueExpr => true,
3003         RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
3004     }
3005 }
3006
3007 /// We categorize expressions into three kinds.  The distinction between
3008 /// lvalue/rvalue is fundamental to the language.  The distinction between the
3009 /// two kinds of rvalues is an artifact of trans which reflects how we will
3010 /// generate code for that kind of expression.  See trans/expr.rs for more
3011 /// information.
3012 pub enum ExprKind {
3013     LvalueExpr,
3014     RvalueDpsExpr,
3015     RvalueDatumExpr,
3016     RvalueStmtExpr
3017 }
3018
3019 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
3020     if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) {
3021         // Overloaded operations are generally calls, and hence they are
3022         // generated via DPS, but there are two exceptions:
3023         return match expr.node {
3024             // `a += b` has a unit result.
3025             ast::ExprAssignOp(..) => RvalueStmtExpr,
3026
3027             // the deref method invoked for `*a` always yields an `&T`
3028             ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
3029
3030             // in the general case, result could be any type, use DPS
3031             _ => RvalueDpsExpr
3032         };
3033     }
3034
3035     match expr.node {
3036         ast::ExprPath(..) => {
3037             match resolve_expr(tcx, expr) {
3038                 def::DefVariant(tid, vid, _) => {
3039                     let variant_info = enum_variant_with_id(tcx, tid, vid);
3040                     if variant_info.args.len() > 0u {
3041                         // N-ary variant.
3042                         RvalueDatumExpr
3043                     } else {
3044                         // Nullary variant.
3045                         RvalueDpsExpr
3046                     }
3047                 }
3048
3049                 def::DefStruct(_) => {
3050                     match get(expr_ty(tcx, expr)).sty {
3051                         ty_bare_fn(..) => RvalueDatumExpr,
3052                         _ => RvalueDpsExpr
3053                     }
3054                 }
3055
3056                 // Fn pointers are just scalar values.
3057                 def::DefFn(..) | def::DefStaticMethod(..) => RvalueDatumExpr,
3058
3059                 // Note: there is actually a good case to be made that
3060                 // DefArg's, particularly those of immediate type, ought to
3061                 // considered rvalues.
3062                 def::DefStatic(..) |
3063                 def::DefBinding(..) |
3064                 def::DefUpvar(..) |
3065                 def::DefArg(..) |
3066                 def::DefLocal(..) => LvalueExpr,
3067
3068                 def => {
3069                     tcx.sess.span_bug(
3070                         expr.span,
3071                         format!("uncategorized def for expr {:?}: {:?}",
3072                                 expr.id,
3073                                 def).as_slice());
3074                 }
3075             }
3076         }
3077
3078         ast::ExprUnary(ast::UnDeref, _) |
3079         ast::ExprField(..) |
3080         ast::ExprIndex(..) => {
3081             LvalueExpr
3082         }
3083
3084         ast::ExprCall(..) |
3085         ast::ExprMethodCall(..) |
3086         ast::ExprStruct(..) |
3087         ast::ExprTup(..) |
3088         ast::ExprIf(..) |
3089         ast::ExprMatch(..) |
3090         ast::ExprFnBlock(..) |
3091         ast::ExprProc(..) |
3092         ast::ExprBlock(..) |
3093         ast::ExprRepeat(..) |
3094         ast::ExprVstore(_, ast::ExprVstoreSlice) |
3095         ast::ExprVstore(_, ast::ExprVstoreMutSlice) |
3096         ast::ExprVec(..) => {
3097             RvalueDpsExpr
3098         }
3099
3100         ast::ExprLit(lit) if lit_is_str(lit) => {
3101             RvalueDpsExpr
3102         }
3103
3104         ast::ExprCast(..) => {
3105             match tcx.node_types.borrow().find(&(expr.id as uint)) {
3106                 Some(&t) => {
3107                     if type_is_trait(t) {
3108                         RvalueDpsExpr
3109                     } else {
3110                         RvalueDatumExpr
3111                     }
3112                 }
3113                 None => {
3114                     // Technically, it should not happen that the expr is not
3115                     // present within the table.  However, it DOES happen
3116                     // during type check, because the final types from the
3117                     // expressions are not yet recorded in the tcx.  At that
3118                     // time, though, we are only interested in knowing lvalue
3119                     // vs rvalue.  It would be better to base this decision on
3120                     // the AST type in cast node---but (at the time of this
3121                     // writing) it's not easy to distinguish casts to traits
3122                     // from other casts based on the AST.  This should be
3123                     // easier in the future, when casts to traits
3124                     // would like @Foo, Box<Foo>, or &Foo.
3125                     RvalueDatumExpr
3126                 }
3127             }
3128         }
3129
3130         ast::ExprBreak(..) |
3131         ast::ExprAgain(..) |
3132         ast::ExprRet(..) |
3133         ast::ExprWhile(..) |
3134         ast::ExprLoop(..) |
3135         ast::ExprAssign(..) |
3136         ast::ExprInlineAsm(..) |
3137         ast::ExprAssignOp(..) => {
3138             RvalueStmtExpr
3139         }
3140
3141         ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
3142
3143         ast::ExprLit(_) | // Note: LitStr is carved out above
3144         ast::ExprUnary(..) |
3145         ast::ExprAddrOf(..) |
3146         ast::ExprBinary(..) |
3147         ast::ExprVstore(_, ast::ExprVstoreUniq) => {
3148             RvalueDatumExpr
3149         }
3150
3151         ast::ExprBox(place, _) => {
3152             // Special case `Box<T>`/`Gc<T>` for now:
3153             let definition = match tcx.def_map.borrow().find(&place.id) {
3154                 Some(&def) => def,
3155                 None => fail!("no def for place"),
3156             };
3157             let def_id = definition.def_id();
3158             if tcx.lang_items.exchange_heap() == Some(def_id) ||
3159                tcx.lang_items.managed_heap() == Some(def_id) {
3160                 RvalueDatumExpr
3161             } else {
3162                 RvalueDpsExpr
3163             }
3164         }
3165
3166         ast::ExprParen(ref e) => expr_kind(tcx, &**e),
3167
3168         ast::ExprMac(..) => {
3169             tcx.sess.span_bug(
3170                 expr.span,
3171                 "macro expression remains after expansion");
3172         }
3173     }
3174 }
3175
3176 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
3177     match s.node {
3178       ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
3179         return id;
3180       }
3181       ast::StmtMac(..) => fail!("unexpanded macro in trans")
3182     }
3183 }
3184
3185 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
3186                      -> uint {
3187     let mut i = 0u;
3188     for f in fields.iter() { if f.ident.name == name { return i; } i += 1u; }
3189     tcx.sess.bug(format!(
3190         "no field named `{}` found in the list of fields `{:?}`",
3191         token::get_name(name),
3192         fields.iter()
3193               .map(|f| token::get_ident(f.ident).get().to_string())
3194               .collect::<Vec<String>>()).as_slice());
3195 }
3196
3197 pub fn method_idx(id: ast::Ident, meths: &[Rc<Method>]) -> Option<uint> {
3198     meths.iter().position(|m| m.ident == id)
3199 }
3200
3201 /// Returns a vector containing the indices of all type parameters that appear
3202 /// in `ty`.  The vector may contain duplicates.  Probably should be converted
3203 /// to a bitset or some other representation.
3204 pub fn param_tys_in_type(ty: t) -> Vec<ParamTy> {
3205     let mut rslt = Vec::new();
3206     walk_ty(ty, |ty| {
3207         match get(ty).sty {
3208           ty_param(p) => {
3209             rslt.push(p);
3210           }
3211           _ => ()
3212         }
3213     });
3214     rslt
3215 }
3216
3217 pub fn ty_sort_str(cx: &ctxt, t: t) -> String {
3218     match get(t).sty {
3219         ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
3220         ty_uint(_) | ty_float(_) | ty_str => {
3221             ::util::ppaux::ty_to_str(cx, t)
3222         }
3223
3224         ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
3225         ty_box(_) => "Gc-ptr".to_string(),
3226         ty_uniq(_) => "box".to_string(),
3227         ty_vec(_, _) => "vector".to_string(),
3228         ty_ptr(_) => "*-ptr".to_string(),
3229         ty_rptr(_, _) => "&-ptr".to_string(),
3230         ty_bare_fn(_) => "extern fn".to_string(),
3231         ty_closure(_) => "fn".to_string(),
3232         ty_trait(ref inner) => {
3233             format!("trait {}", item_path_str(cx, inner.def_id))
3234         }
3235         ty_struct(id, _) => {
3236             format!("struct {}", item_path_str(cx, id))
3237         }
3238         ty_tup(_) => "tuple".to_string(),
3239         ty_infer(TyVar(_)) => "inferred type".to_string(),
3240         ty_infer(IntVar(_)) => "integral variable".to_string(),
3241         ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3242         ty_param(ref p) => {
3243             if p.space == subst::SelfSpace {
3244                 "Self".to_string()
3245             } else {
3246                 "type parameter".to_string()
3247             }
3248         }
3249         ty_err => "type error".to_string(),
3250     }
3251 }
3252
3253 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3254     /*!
3255      *
3256      * Explains the source of a type err in a short,
3257      * human readable way.  This is meant to be placed in
3258      * parentheses after some larger message.  You should
3259      * also invoke `note_and_explain_type_err()` afterwards
3260      * to present additional details, particularly when
3261      * it comes to lifetime-related errors. */
3262
3263     fn tstore_to_closure(s: &TraitStore) -> String {
3264         match s {
3265             &UniqTraitStore => "proc".to_string(),
3266             &RegionTraitStore(..) => "closure".to_string()
3267         }
3268     }
3269
3270     match *err {
3271         terr_mismatch => "types differ".to_string(),
3272         terr_fn_style_mismatch(values) => {
3273             format!("expected {} fn but found {} fn",
3274                     values.expected.to_str(),
3275                     values.found.to_str())
3276         }
3277         terr_abi_mismatch(values) => {
3278             format!("expected {} fn but found {} fn",
3279                     values.expected.to_str(),
3280                     values.found.to_str())
3281         }
3282         terr_onceness_mismatch(values) => {
3283             format!("expected {} fn but found {} fn",
3284                     values.expected.to_str(),
3285                     values.found.to_str())
3286         }
3287         terr_sigil_mismatch(values) => {
3288             format!("expected {}, found {}",
3289                     tstore_to_closure(&values.expected),
3290                     tstore_to_closure(&values.found))
3291         }
3292         terr_mutability => "values differ in mutability".to_string(),
3293         terr_box_mutability => {
3294             "boxed values differ in mutability".to_string()
3295         }
3296         terr_vec_mutability => "vectors differ in mutability".to_string(),
3297         terr_ptr_mutability => "pointers differ in mutability".to_string(),
3298         terr_ref_mutability => "references differ in mutability".to_string(),
3299         terr_ty_param_size(values) => {
3300             format!("expected a type with {} type params \
3301                      but found one with {} type params",
3302                     values.expected,
3303                     values.found)
3304         }
3305         terr_tuple_size(values) => {
3306             format!("expected a tuple with {} elements \
3307                      but found one with {} elements",
3308                     values.expected,
3309                     values.found)
3310         }
3311         terr_record_size(values) => {
3312             format!("expected a record with {} fields \
3313                      but found one with {} fields",
3314                     values.expected,
3315                     values.found)
3316         }
3317         terr_record_mutability => {
3318             "record elements differ in mutability".to_string()
3319         }
3320         terr_record_fields(values) => {
3321             format!("expected a record with field `{}` but found one \
3322                      with field `{}`",
3323                     token::get_ident(values.expected),
3324                     token::get_ident(values.found))
3325         }
3326         terr_arg_count => {
3327             "incorrect number of function parameters".to_string()
3328         }
3329         terr_regions_does_not_outlive(..) => {
3330             "lifetime mismatch".to_string()
3331         }
3332         terr_regions_not_same(..) => {
3333             "lifetimes are not the same".to_string()
3334         }
3335         terr_regions_no_overlap(..) => {
3336             "lifetimes do not intersect".to_string()
3337         }
3338         terr_regions_insufficiently_polymorphic(br, _) => {
3339             format!("expected bound lifetime parameter {}, \
3340                      but found concrete lifetime",
3341                     bound_region_ptr_to_str(cx, br))
3342         }
3343         terr_regions_overly_polymorphic(br, _) => {
3344             format!("expected concrete lifetime, \
3345                      but found bound lifetime parameter {}",
3346                     bound_region_ptr_to_str(cx, br))
3347         }
3348         terr_trait_stores_differ(_, ref values) => {
3349             format!("trait storage differs: expected `{}` but found `{}`",
3350                     trait_store_to_str(cx, (*values).expected),
3351                     trait_store_to_str(cx, (*values).found))
3352         }
3353         terr_sorts(values) => {
3354             format!("expected {} but found {}",
3355                     ty_sort_str(cx, values.expected),
3356                     ty_sort_str(cx, values.found))
3357         }
3358         terr_traits(values) => {
3359             format!("expected trait `{}` but found trait `{}`",
3360                     item_path_str(cx, values.expected),
3361                     item_path_str(cx, values.found))
3362         }
3363         terr_builtin_bounds(values) => {
3364             if values.expected.is_empty() {
3365                 format!("expected no bounds but found `{}`",
3366                         values.found.user_string(cx))
3367             } else if values.found.is_empty() {
3368                 format!("expected bounds `{}` but found no bounds",
3369                         values.expected.user_string(cx))
3370             } else {
3371                 format!("expected bounds `{}` but found bounds `{}`",
3372                         values.expected.user_string(cx),
3373                         values.found.user_string(cx))
3374             }
3375         }
3376         terr_integer_as_char => {
3377             "expected an integral type but found `char`".to_string()
3378         }
3379         terr_int_mismatch(ref values) => {
3380             format!("expected `{}` but found `{}`",
3381                     values.expected.to_str(),
3382                     values.found.to_str())
3383         }
3384         terr_float_mismatch(ref values) => {
3385             format!("expected `{}` but found `{}`",
3386                     values.expected.to_str(),
3387                     values.found.to_str())
3388         }
3389         terr_variadic_mismatch(ref values) => {
3390             format!("expected {} fn but found {} function",
3391                     if values.expected { "variadic" } else { "non-variadic" },
3392                     if values.found { "variadic" } else { "non-variadic" })
3393         }
3394     }
3395 }
3396
3397 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3398     match *err {
3399         terr_regions_does_not_outlive(subregion, superregion) => {
3400             note_and_explain_region(cx, "", subregion, "...");
3401             note_and_explain_region(cx, "...does not necessarily outlive ",
3402                                     superregion, "");
3403         }
3404         terr_regions_not_same(region1, region2) => {
3405             note_and_explain_region(cx, "", region1, "...");
3406             note_and_explain_region(cx, "...is not the same lifetime as ",
3407                                     region2, "");
3408         }
3409         terr_regions_no_overlap(region1, region2) => {
3410             note_and_explain_region(cx, "", region1, "...");
3411             note_and_explain_region(cx, "...does not overlap ",
3412                                     region2, "");
3413         }
3414         terr_regions_insufficiently_polymorphic(_, conc_region) => {
3415             note_and_explain_region(cx,
3416                                     "concrete lifetime that was found is ",
3417                                     conc_region, "");
3418         }
3419         terr_regions_overly_polymorphic(_, conc_region) => {
3420             note_and_explain_region(cx,
3421                                     "expected concrete lifetime is ",
3422                                     conc_region, "");
3423         }
3424         _ => {}
3425     }
3426 }
3427
3428 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
3429     cx.provided_method_sources.borrow().find(&id).map(|x| *x)
3430 }
3431
3432 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
3433     if is_local(id) {
3434         match cx.map.find(id.node) {
3435             Some(ast_map::NodeItem(item)) => {
3436                 match item.node {
3437                     ItemTrait(_, _, _, ref ms) => {
3438                         let (_, p) = ast_util::split_trait_methods(ms.as_slice());
3439                         p.iter().map(|m| method(cx, ast_util::local_def(m.id))).collect()
3440                     }
3441                     _ => {
3442                         cx.sess.bug(format!("provided_trait_methods: `{}` is \
3443                                              not a trait",
3444                                             id).as_slice())
3445                     }
3446                 }
3447             }
3448             _ => {
3449                 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
3450                                      trait",
3451                                     id).as_slice())
3452             }
3453         }
3454     } else {
3455         csearch::get_provided_trait_methods(cx, id)
3456     }
3457 }
3458
3459 pub fn trait_supertraits(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<TraitRef>>> {
3460     // Check the cache.
3461     match cx.supertraits.borrow().find(&id) {
3462         Some(trait_refs) => { return trait_refs.clone(); }
3463         None => {}  // Continue.
3464     }
3465
3466     // Not in the cache. It had better be in the metadata, which means it
3467     // shouldn't be local.
3468     assert!(!is_local(id));
3469
3470     // Get the supertraits out of the metadata and create the
3471     // TraitRef for each.
3472     let result = Rc::new(csearch::get_supertraits(cx, id));
3473     cx.supertraits.borrow_mut().insert(id, result.clone());
3474     result
3475 }
3476
3477 pub fn trait_ref_supertraits(cx: &ctxt, trait_ref: &ty::TraitRef) -> Vec<Rc<TraitRef>> {
3478     let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
3479     supertrait_refs.iter().map(
3480         |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs)).collect()
3481 }
3482
3483 fn lookup_locally_or_in_crate_store<V:Clone>(
3484                                     descr: &str,
3485                                     def_id: ast::DefId,
3486                                     map: &mut DefIdMap<V>,
3487                                     load_external: || -> V) -> V {
3488     /*!
3489      * Helper for looking things up in the various maps
3490      * that are populated during typeck::collect (e.g.,
3491      * `cx.methods`, `cx.tcache`, etc).  All of these share
3492      * the pattern that if the id is local, it should have
3493      * been loaded into the map by the `typeck::collect` phase.
3494      * If the def-id is external, then we have to go consult
3495      * the crate loading code (and cache the result for the future).
3496      */
3497
3498     match map.find_copy(&def_id) {
3499         Some(v) => { return v; }
3500         None => { }
3501     }
3502
3503     if def_id.krate == ast::LOCAL_CRATE {
3504         fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
3505     }
3506     let v = load_external();
3507     map.insert(def_id, v.clone());
3508     v
3509 }
3510
3511 pub fn trait_method(cx: &ctxt, trait_did: ast::DefId, idx: uint) -> Rc<Method> {
3512     let method_def_id = *ty::trait_method_def_ids(cx, trait_did).get(idx);
3513     ty::method(cx, method_def_id)
3514 }
3515
3516
3517 pub fn trait_methods(cx: &ctxt, trait_did: ast::DefId) -> Rc<Vec<Rc<Method>>> {
3518     let mut trait_methods = cx.trait_methods_cache.borrow_mut();
3519     match trait_methods.find_copy(&trait_did) {
3520         Some(methods) => methods,
3521         None => {
3522             let def_ids = ty::trait_method_def_ids(cx, trait_did);
3523             let methods: Rc<Vec<Rc<Method>>> = Rc::new(def_ids.iter().map(|d| {
3524                 ty::method(cx, *d)
3525             }).collect());
3526             trait_methods.insert(trait_did, methods.clone());
3527             methods
3528         }
3529     }
3530 }
3531
3532 pub fn method(cx: &ctxt, id: ast::DefId) -> Rc<Method> {
3533     lookup_locally_or_in_crate_store("methods", id,
3534                                      &mut *cx.methods.borrow_mut(), || {
3535         Rc::new(csearch::get_method(cx, id))
3536     })
3537 }
3538
3539 pub fn trait_method_def_ids(cx: &ctxt, id: ast::DefId) -> Rc<Vec<DefId>> {
3540     lookup_locally_or_in_crate_store("trait_method_def_ids",
3541                                      id,
3542                                      &mut *cx.trait_method_def_ids.borrow_mut(),
3543                                      || {
3544         Rc::new(csearch::get_trait_method_def_ids(&cx.sess.cstore, id))
3545     })
3546 }
3547
3548 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
3549     match cx.impl_trait_cache.borrow().find(&id) {
3550         Some(ret) => { return ret.clone(); }
3551         None => {}
3552     }
3553
3554     let ret = if id.krate == ast::LOCAL_CRATE {
3555         debug!("(impl_trait_ref) searching for trait impl {:?}", id);
3556         match cx.map.find(id.node) {
3557             Some(ast_map::NodeItem(item)) => {
3558                 match item.node {
3559                     ast::ItemImpl(_, ref opt_trait, _, _) => {
3560                         match opt_trait {
3561                             &Some(ref t) => {
3562                                 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
3563                             }
3564                             &None => None
3565                         }
3566                     }
3567                     _ => None
3568                 }
3569             }
3570             _ => None
3571         }
3572     } else {
3573         csearch::get_impl_trait(cx, id)
3574     };
3575
3576     cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
3577     ret
3578 }
3579
3580 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
3581     let def = *tcx.def_map.borrow()
3582                      .find(&tr.ref_id)
3583                      .expect("no def-map entry for trait");
3584     def.def_id()
3585 }
3586
3587 pub fn try_add_builtin_trait(tcx: &ctxt,
3588                              trait_def_id: ast::DefId,
3589                              builtin_bounds: &mut BuiltinBounds) -> bool {
3590     //! Checks whether `trait_ref` refers to one of the builtin
3591     //! traits, like `Send`, and adds the corresponding
3592     //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
3593     //! is a builtin trait.
3594
3595     match tcx.lang_items.to_builtin_kind(trait_def_id) {
3596         Some(bound) => { builtin_bounds.add(bound); true }
3597         None => false
3598     }
3599 }
3600
3601 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
3602     match get(ty).sty {
3603         ty_trait(box TyTrait { def_id: id, .. }) |
3604         ty_struct(id, _) |
3605         ty_enum(id, _) => Some(id),
3606         _ => None
3607     }
3608 }
3609
3610 // Enum information
3611 #[deriving(Clone)]
3612 pub struct VariantInfo {
3613     pub args: Vec<t>,
3614     pub arg_names: Option<Vec<ast::Ident> >,
3615     pub ctor_ty: t,
3616     pub name: ast::Ident,
3617     pub id: ast::DefId,
3618     pub disr_val: Disr,
3619     pub vis: Visibility
3620 }
3621
3622 impl VariantInfo {
3623
3624     /// Creates a new VariantInfo from the corresponding ast representation.
3625     ///
3626     /// Does not do any caching of the value in the type context.
3627     pub fn from_ast_variant(cx: &ctxt,
3628                             ast_variant: &ast::Variant,
3629                             discriminant: Disr) -> VariantInfo {
3630         let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
3631
3632         match ast_variant.node.kind {
3633             ast::TupleVariantKind(ref args) => {
3634                 let arg_tys = if args.len() > 0 {
3635                     ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
3636                 } else {
3637                     Vec::new()
3638                 };
3639
3640                 return VariantInfo {
3641                     args: arg_tys,
3642                     arg_names: None,
3643                     ctor_ty: ctor_ty,
3644                     name: ast_variant.node.name,
3645                     id: ast_util::local_def(ast_variant.node.id),
3646                     disr_val: discriminant,
3647                     vis: ast_variant.node.vis
3648                 };
3649             },
3650             ast::StructVariantKind(ref struct_def) => {
3651
3652                 let fields: &[StructField] = struct_def.fields.as_slice();
3653
3654                 assert!(fields.len() > 0);
3655
3656                 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
3657                 let arg_names = fields.iter().map(|field| {
3658                     match field.node.kind {
3659                         NamedField(ident, _) => ident,
3660                         UnnamedField(..) => cx.sess.bug(
3661                             "enum_variants: all fields in struct must have a name")
3662                     }
3663                 }).collect();
3664
3665                 return VariantInfo {
3666                     args: arg_tys,
3667                     arg_names: Some(arg_names),
3668                     ctor_ty: ctor_ty,
3669                     name: ast_variant.node.name,
3670                     id: ast_util::local_def(ast_variant.node.id),
3671                     disr_val: discriminant,
3672                     vis: ast_variant.node.vis
3673                 };
3674             }
3675         }
3676     }
3677 }
3678
3679 pub fn substd_enum_variants(cx: &ctxt,
3680                             id: ast::DefId,
3681                             substs: &Substs)
3682                          -> Vec<Rc<VariantInfo>> {
3683     enum_variants(cx, id).iter().map(|variant_info| {
3684         let substd_args = variant_info.args.iter()
3685             .map(|aty| aty.subst(cx, substs)).collect();
3686
3687         let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
3688
3689         Rc::new(VariantInfo {
3690             args: substd_args,
3691             ctor_ty: substd_ctor_ty,
3692             ..(**variant_info).clone()
3693         })
3694     }).collect()
3695 }
3696
3697 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
3698     with_path(cx, id, |path| ast_map::path_to_str(path)).to_string()
3699 }
3700
3701 pub enum DtorKind {
3702     NoDtor,
3703     TraitDtor(DefId, bool)
3704 }
3705
3706 impl DtorKind {
3707     pub fn is_not_present(&self) -> bool {
3708         match *self {
3709             NoDtor => true,
3710             _ => false
3711         }
3712     }
3713
3714     pub fn is_present(&self) -> bool {
3715         !self.is_not_present()
3716     }
3717
3718     pub fn has_drop_flag(&self) -> bool {
3719         match self {
3720             &NoDtor => false,
3721             &TraitDtor(_, flag) => flag
3722         }
3723     }
3724 }
3725
3726 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
3727    Otherwise return none. */
3728 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
3729     match cx.destructor_for_type.borrow().find(&struct_id) {
3730         Some(&method_def_id) => {
3731             let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
3732
3733             TraitDtor(method_def_id, flag)
3734         }
3735         None => NoDtor,
3736     }
3737 }
3738
3739 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
3740     ty_dtor(cx, struct_id).is_present()
3741 }
3742
3743 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
3744     if id.krate == ast::LOCAL_CRATE {
3745         cx.map.with_path(id.node, f)
3746     } else {
3747         f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
3748     }
3749 }
3750
3751 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
3752     enum_variants(cx, id).len() == 1
3753 }
3754
3755 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
3756     match ty::get(t).sty {
3757        ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
3758        _ => false
3759      }
3760 }
3761
3762 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
3763     match cx.enum_var_cache.borrow().find(&id) {
3764         Some(variants) => return variants.clone(),
3765         _ => { /* fallthrough */ }
3766     }
3767
3768     let result = if ast::LOCAL_CRATE != id.krate {
3769         Rc::new(csearch::get_enum_variants(cx, id))
3770     } else {
3771         /*
3772           Although both this code and check_enum_variants in typeck/check
3773           call eval_const_expr, it should never get called twice for the same
3774           expr, since check_enum_variants also updates the enum_var_cache
3775          */
3776         match cx.map.get(id.node) {
3777             ast_map::NodeItem(item) => {
3778                 match item.node {
3779                     ast::ItemEnum(ref enum_definition, _) => {
3780                         let mut last_discriminant: Option<Disr> = None;
3781                         Rc::new(enum_definition.variants.iter().map(|&variant| {
3782
3783                             let mut discriminant = match last_discriminant {
3784                                 Some(val) => val + 1,
3785                                 None => INITIAL_DISCRIMINANT_VALUE
3786                             };
3787
3788                             match variant.node.disr_expr {
3789                                 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
3790                                     Ok(const_eval::const_int(val)) => {
3791                                         discriminant = val as Disr
3792                                     }
3793                                     Ok(const_eval::const_uint(val)) => {
3794                                         discriminant = val as Disr
3795                                     }
3796                                     Ok(_) => {
3797                                         cx.sess
3798                                           .span_err(e.span,
3799                                                     "expected signed integer constant");
3800                                     }
3801                                     Err(ref err) => {
3802                                         cx.sess
3803                                           .span_err(e.span,
3804                                                     format!("expected constant: {}",
3805                                                             *err).as_slice());
3806                                     }
3807                                 },
3808                                 None => {}
3809                             };
3810
3811                             last_discriminant = Some(discriminant);
3812                             Rc::new(VariantInfo::from_ast_variant(cx, &*variant,
3813                                                                   discriminant))
3814                         }).collect())
3815                     }
3816                     _ => {
3817                         cx.sess.bug("enum_variants: id not bound to an enum")
3818                     }
3819                 }
3820             }
3821             _ => cx.sess.bug("enum_variants: id not bound to an enum")
3822         }
3823     };
3824
3825     cx.enum_var_cache.borrow_mut().insert(id, result.clone());
3826     result
3827 }
3828
3829
3830 // Returns information about the enum variant with the given ID:
3831 pub fn enum_variant_with_id(cx: &ctxt,
3832                             enum_id: ast::DefId,
3833                             variant_id: ast::DefId)
3834                          -> Rc<VariantInfo> {
3835     enum_variants(cx, enum_id).iter()
3836                               .find(|variant| variant.id == variant_id)
3837                               .expect("enum_variant_with_id(): no variant exists with that ID")
3838                               .clone()
3839 }
3840
3841
3842 // If the given item is in an external crate, looks up its type and adds it to
3843 // the type cache. Returns the type parameters and type.
3844 pub fn lookup_item_type(cx: &ctxt,
3845                         did: ast::DefId)
3846                      -> ty_param_bounds_and_ty {
3847     lookup_locally_or_in_crate_store(
3848         "tcache", did, &mut *cx.tcache.borrow_mut(),
3849         || csearch::get_type(cx, did))
3850 }
3851
3852 pub fn lookup_impl_vtables(cx: &ctxt,
3853                            did: ast::DefId)
3854                            -> typeck::vtable_res {
3855     lookup_locally_or_in_crate_store(
3856         "impl_vtables", did, &mut *cx.impl_vtables.borrow_mut(),
3857         || csearch::get_impl_vtables(cx, did) )
3858 }
3859
3860 /// Given the did of a trait, returns its canonical trait ref.
3861 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
3862     let mut trait_defs = cx.trait_defs.borrow_mut();
3863     match trait_defs.find_copy(&did) {
3864         Some(trait_def) => {
3865             // The item is in this crate. The caller should have added it to the
3866             // type cache already
3867             trait_def
3868         }
3869         None => {
3870             assert!(did.krate != ast::LOCAL_CRATE);
3871             let trait_def = Rc::new(csearch::get_trait_def(cx, did));
3872             trait_defs.insert(did, trait_def.clone());
3873             trait_def
3874         }
3875     }
3876 }
3877
3878 /// Iterate over attributes of a definition.
3879 // (This should really be an iterator, but that would require csearch and
3880 // decoder to use iterators instead of higher-order functions.)
3881 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
3882     if is_local(did) {
3883         let item = tcx.map.expect_item(did.node);
3884         item.attrs.iter().advance(|attr| f(attr))
3885     } else {
3886         info!("getting foreign attrs");
3887         let mut cont = true;
3888         csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
3889             if cont {
3890                 cont = attrs.iter().advance(|attr| f(attr));
3891             }
3892         });
3893         info!("done");
3894         cont
3895     }
3896 }
3897
3898 /// Determine whether an item is annotated with an attribute
3899 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
3900     let mut found = false;
3901     each_attr(tcx, did, |item| {
3902         if item.check_name(attr) {
3903             found = true;
3904             false
3905         } else {
3906             true
3907         }
3908     });
3909     found
3910 }
3911
3912 /// Determine whether an item is annotated with `#[packed]`
3913 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
3914     has_attr(tcx, did, "packed")
3915 }
3916
3917 /// Determine whether an item is annotated with `#[simd]`
3918 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
3919     has_attr(tcx, did, "simd")
3920 }
3921
3922 // Obtain the representation annotation for a definition.
3923 pub fn lookup_repr_hint(tcx: &ctxt, did: DefId) -> attr::ReprAttr {
3924     let mut acc = attr::ReprAny;
3925     ty::each_attr(tcx, did, |meta| {
3926         acc = attr::find_repr_attr(tcx.sess.diagnostic(), meta, acc);
3927         true
3928     });
3929     return acc;
3930 }
3931
3932 // Look up a field ID, whether or not it's local
3933 // Takes a list of type substs in case the struct is generic
3934 pub fn lookup_field_type(tcx: &ctxt,
3935                          struct_id: DefId,
3936                          id: DefId,
3937                          substs: &Substs)
3938                       -> ty::t {
3939     let t = if id.krate == ast::LOCAL_CRATE {
3940         node_id_to_type(tcx, id.node)
3941     } else {
3942         let mut tcache = tcx.tcache.borrow_mut();
3943         match tcache.find(&id) {
3944            Some(&ty_param_bounds_and_ty {ty, ..}) => ty,
3945            None => {
3946                let tpt = csearch::get_field_type(tcx, struct_id, id);
3947                tcache.insert(id, tpt.clone());
3948                tpt.ty
3949            }
3950         }
3951     };
3952     t.subst(tcx, substs)
3953 }
3954
3955 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
3956 // transitive closure of doing a single lookup in cx.superstructs.
3957 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
3958     let superstructs = cx.superstructs.borrow();
3959
3960     loop {
3961         f(did);
3962         match superstructs.find(&did) {
3963             Some(&Some(def_id)) => {
3964                 did = def_id;
3965             },
3966             Some(&None) => break,
3967             None => {
3968                 cx.sess.bug(
3969                     format!("ID not mapped to super-struct: {}",
3970                             cx.map.node_to_str(did.node)).as_slice());
3971             }
3972         }
3973     }
3974 }
3975
3976 // Look up the list of field names and IDs for a given struct.
3977 // Fails if the id is not bound to a struct.
3978 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
3979     if did.krate == ast::LOCAL_CRATE {
3980         // We store the fields which are syntactically in each struct in cx. So
3981         // we have to walk the inheritance chain of the struct to get all the
3982         // structs (explicit and inherited) for a struct. If this is expensive
3983         // we could cache the whole list of fields here.
3984         let struct_fields = cx.struct_fields.borrow();
3985         let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
3986         each_super_struct(cx, did, |s| {
3987             match struct_fields.find(&s) {
3988                 Some(fields) => results.push(fields.as_slice()),
3989                 _ => {
3990                     cx.sess.bug(
3991                         format!("ID not mapped to struct fields: {}",
3992                                 cx.map.node_to_str(did.node)).as_slice());
3993                 }
3994             }
3995         });
3996
3997         let len = results.as_slice().iter().map(|x| x.len()).sum();
3998         let mut result: Vec<field_ty> = Vec::with_capacity(len);
3999         result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|&f| f)));
4000         assert!(result.len() == len);
4001         result
4002     } else {
4003         csearch::get_struct_fields(&cx.sess.cstore, did)
4004     }
4005 }
4006
4007 pub fn lookup_struct_field(cx: &ctxt,
4008                            parent: ast::DefId,
4009                            field_id: ast::DefId)
4010                         -> field_ty {
4011     let r = lookup_struct_fields(cx, parent);
4012     match r.iter().find(|f| f.id.node == field_id.node) {
4013         Some(t) => *t,
4014         None => cx.sess.bug("struct ID not found in parent's fields")
4015     }
4016 }
4017
4018 // Returns a list of fields corresponding to the struct's items. trans uses
4019 // this. Takes a list of substs with which to instantiate field types.
4020 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4021                      -> Vec<field> {
4022     lookup_struct_fields(cx, did).iter().map(|f| {
4023        field {
4024             // FIXME #6993: change type of field to Name and get rid of new()
4025             ident: ast::Ident::new(f.name),
4026             mt: mt {
4027                 ty: lookup_field_type(cx, did, f.id, substs),
4028                 mutbl: MutImmutable
4029             }
4030         }
4031     }).collect()
4032 }
4033
4034 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4035     static tycat_other: int = 0;
4036     static tycat_bool: int = 1;
4037     static tycat_char: int = 2;
4038     static tycat_int: int = 3;
4039     static tycat_float: int = 4;
4040     static tycat_bot: int = 5;
4041     static tycat_raw_ptr: int = 6;
4042
4043     static opcat_add: int = 0;
4044     static opcat_sub: int = 1;
4045     static opcat_mult: int = 2;
4046     static opcat_shift: int = 3;
4047     static opcat_rel: int = 4;
4048     static opcat_eq: int = 5;
4049     static opcat_bit: int = 6;
4050     static opcat_logic: int = 7;
4051     static opcat_mod: int = 8;
4052
4053     fn opcat(op: ast::BinOp) -> int {
4054         match op {
4055           ast::BiAdd => opcat_add,
4056           ast::BiSub => opcat_sub,
4057           ast::BiMul => opcat_mult,
4058           ast::BiDiv => opcat_mult,
4059           ast::BiRem => opcat_mod,
4060           ast::BiAnd => opcat_logic,
4061           ast::BiOr => opcat_logic,
4062           ast::BiBitXor => opcat_bit,
4063           ast::BiBitAnd => opcat_bit,
4064           ast::BiBitOr => opcat_bit,
4065           ast::BiShl => opcat_shift,
4066           ast::BiShr => opcat_shift,
4067           ast::BiEq => opcat_eq,
4068           ast::BiNe => opcat_eq,
4069           ast::BiLt => opcat_rel,
4070           ast::BiLe => opcat_rel,
4071           ast::BiGe => opcat_rel,
4072           ast::BiGt => opcat_rel
4073         }
4074     }
4075
4076     fn tycat(cx: &ctxt, ty: t) -> int {
4077         if type_is_simd(cx, ty) {
4078             return tycat(cx, simd_type(cx, ty))
4079         }
4080         match get(ty).sty {
4081           ty_char => tycat_char,
4082           ty_bool => tycat_bool,
4083           ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4084           ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4085           ty_bot => tycat_bot,
4086           ty_ptr(_) => tycat_raw_ptr,
4087           _ => tycat_other
4088         }
4089     }
4090
4091     static t: bool = true;
4092     static f: bool = false;
4093
4094     let tbl = [
4095     //           +, -, *, shift, rel, ==, bit, logic, mod
4096     /*other*/   [f, f, f, f,     f,   f,  f,   f,     f],
4097     /*bool*/    [f, f, f, f,     t,   t,  t,   t,     f],
4098     /*char*/    [f, f, f, f,     t,   t,  f,   f,     f],
4099     /*int*/     [t, t, t, t,     t,   t,  t,   f,     t],
4100     /*float*/   [t, t, t, f,     t,   t,  f,   f,     f],
4101     /*bot*/     [t, t, t, t,     t,   t,  t,   t,     t],
4102     /*raw ptr*/ [f, f, f, f,     t,   t,  f,   f,     f]];
4103
4104     return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4105 }
4106
4107 /// Returns an equivalent type with all the typedefs and self regions removed.
4108 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4109     let u = TypeNormalizer(cx).fold_ty(t);
4110     return u;
4111
4112     struct TypeNormalizer<'a>(&'a ctxt);
4113
4114     impl<'a> TypeFolder for TypeNormalizer<'a> {
4115         fn tcx<'a>(&'a self) -> &'a ctxt { let TypeNormalizer(c) = *self; c }
4116
4117         fn fold_ty(&mut self, t: ty::t) -> ty::t {
4118             match self.tcx().normalized_cache.borrow().find_copy(&t) {
4119                 None => {}
4120                 Some(u) => return u
4121             }
4122
4123             let t_norm = ty_fold::super_fold_ty(self, t);
4124             self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4125             return t_norm;
4126         }
4127
4128         fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4129             ty::ReStatic
4130         }
4131
4132         fn fold_substs(&mut self,
4133                        substs: &subst::Substs)
4134                        -> subst::Substs {
4135             subst::Substs { regions: subst::ErasedRegions,
4136                             types: substs.types.fold_with(self) }
4137         }
4138
4139         fn fold_sig(&mut self,
4140                     sig: &ty::FnSig)
4141                     -> ty::FnSig {
4142             // The binder-id is only relevant to bound regions, which
4143             // are erased at trans time.
4144             ty::FnSig {
4145                 binder_id: ast::DUMMY_NODE_ID,
4146                 inputs: sig.inputs.fold_with(self),
4147                 output: sig.output.fold_with(self),
4148                 variadic: sig.variadic,
4149             }
4150         }
4151     }
4152 }
4153
4154 pub trait ExprTyProvider {
4155     fn expr_ty(&self, ex: &ast::Expr) -> t;
4156     fn ty_ctxt<'a>(&'a self) -> &'a ctxt;
4157 }
4158
4159 impl ExprTyProvider for ctxt {
4160     fn expr_ty(&self, ex: &ast::Expr) -> t {
4161         expr_ty(self, ex)
4162     }
4163
4164     fn ty_ctxt<'a>(&'a self) -> &'a ctxt {
4165         self
4166     }
4167 }
4168
4169 // Returns the repeat count for a repeating vector expression.
4170 pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) -> uint {
4171     match const_eval::eval_const_expr_partial(tcx, count_expr) {
4172       Ok(ref const_val) => match *const_val {
4173         const_eval::const_int(count) => if count < 0 {
4174             tcx.ty_ctxt().sess.span_err(count_expr.span,
4175                                         "expected positive integer for \
4176                                          repeat count but found negative integer");
4177             return 0;
4178         } else {
4179             return count as uint
4180         },
4181         const_eval::const_uint(count) => return count as uint,
4182         const_eval::const_float(count) => {
4183             tcx.ty_ctxt().sess.span_err(count_expr.span,
4184                                         "expected positive integer for \
4185                                          repeat count but found float");
4186             return count as uint;
4187         }
4188         const_eval::const_str(_) => {
4189             tcx.ty_ctxt().sess.span_err(count_expr.span,
4190                                         "expected positive integer for \
4191                                          repeat count but found string");
4192             return 0;
4193         }
4194         const_eval::const_bool(_) => {
4195             tcx.ty_ctxt().sess.span_err(count_expr.span,
4196                                         "expected positive integer for \
4197                                          repeat count but found boolean");
4198             return 0;
4199         }
4200         const_eval::const_binary(_) => {
4201             tcx.ty_ctxt().sess.span_err(count_expr.span,
4202                                         "expected positive integer for \
4203                                          repeat count but found binary array");
4204             return 0;
4205         }
4206       },
4207       Err(..) => {
4208         tcx.ty_ctxt().sess.span_err(count_expr.span,
4209                                     "expected constant integer for repeat count \
4210                                      but found variable");
4211         return 0;
4212       }
4213     }
4214 }
4215
4216 // Iterate over a type parameter's bounded traits and any supertraits
4217 // of those traits, ignoring kinds.
4218 // Here, the supertraits are the transitive closure of the supertrait
4219 // relation on the supertraits from each bounded trait's constraint
4220 // list.
4221 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4222                                         bounds: &[Rc<TraitRef>],
4223                                         f: |Rc<TraitRef>| -> bool)
4224                                         -> bool {
4225     for bound_trait_ref in bounds.iter() {
4226         let mut supertrait_set = HashMap::new();
4227         let mut trait_refs = Vec::new();
4228         let mut i = 0;
4229
4230         // Seed the worklist with the trait from the bound
4231         supertrait_set.insert(bound_trait_ref.def_id, ());
4232         trait_refs.push(bound_trait_ref.clone());
4233
4234         // Add the given trait ty to the hash map
4235         while i < trait_refs.len() {
4236             debug!("each_bound_trait_and_supertraits(i={:?}, trait_ref={})",
4237                    i, trait_refs.get(i).repr(tcx));
4238
4239             if !f(trait_refs.get(i).clone()) {
4240                 return false;
4241             }
4242
4243             // Add supertraits to supertrait_set
4244             let supertrait_refs = trait_ref_supertraits(tcx,
4245                                                         &**trait_refs.get(i));
4246             for supertrait_ref in supertrait_refs.iter() {
4247                 debug!("each_bound_trait_and_supertraits(supertrait_ref={})",
4248                        supertrait_ref.repr(tcx));
4249
4250                 let d_id = supertrait_ref.def_id;
4251                 if !supertrait_set.contains_key(&d_id) {
4252                     // FIXME(#5527) Could have same trait multiple times
4253                     supertrait_set.insert(d_id, ());
4254                     trait_refs.push(supertrait_ref.clone());
4255                 }
4256             }
4257
4258             i += 1;
4259         }
4260     }
4261     return true;
4262 }
4263
4264 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
4265     tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4266         tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4267             .expect("Failed to resolve TyDesc")
4268     })
4269 }
4270
4271 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
4272     tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4273         tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4274             .expect("Failed to resolve Opaque")
4275     })
4276 }
4277
4278 pub fn visitor_object_ty(tcx: &ctxt,
4279                          region: ty::Region) -> Result<(Rc<TraitRef>, t), String> {
4280     let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4281         Ok(id) => id,
4282         Err(s) => { return Err(s); }
4283     };
4284     let substs = Substs::empty();
4285     let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
4286     Ok((trait_ref.clone(),
4287         mk_rptr(tcx, region, mt {mutbl: ast::MutMutable,
4288                                  ty: mk_trait(tcx,
4289                                               trait_ref.def_id,
4290                                               trait_ref.substs.clone(),
4291                                               empty_builtin_bounds()) })))
4292 }
4293
4294 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
4295     lookup_locally_or_in_crate_store(
4296         "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4297         || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
4298 }
4299
4300 /// Records a trait-to-implementation mapping.
4301 pub fn record_trait_implementation(tcx: &ctxt,
4302                                    trait_def_id: DefId,
4303                                    impl_def_id: DefId) {
4304     match tcx.trait_impls.borrow().find(&trait_def_id) {
4305         Some(impls_for_trait) => {
4306             impls_for_trait.borrow_mut().push(impl_def_id);
4307             return;
4308         }
4309         None => {}
4310     }
4311     tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
4312 }
4313
4314 /// Populates the type context with all the implementations for the given type
4315 /// if necessary.
4316 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4317                                                       type_id: ast::DefId) {
4318     if type_id.krate == LOCAL_CRATE {
4319         return
4320     }
4321     if tcx.populated_external_types.borrow().contains(&type_id) {
4322         return
4323     }
4324
4325     csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4326             |impl_def_id| {
4327         let methods = csearch::get_impl_methods(&tcx.sess.cstore, impl_def_id);
4328
4329         // Record the trait->implementation mappings, if applicable.
4330         let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
4331         for trait_ref in associated_traits.iter() {
4332             record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
4333         }
4334
4335         // For any methods that use a default implementation, add them to
4336         // the map. This is a bit unfortunate.
4337         for &method_def_id in methods.iter() {
4338             for &source in ty::method(tcx, method_def_id).provided_source.iter() {
4339                 tcx.provided_method_sources.borrow_mut().insert(method_def_id, source);
4340             }
4341         }
4342
4343         // Store the implementation info.
4344         tcx.impl_methods.borrow_mut().insert(impl_def_id, methods);
4345
4346         // If this is an inherent implementation, record it.
4347         if associated_traits.is_none() {
4348             match tcx.inherent_impls.borrow().find(&type_id) {
4349                 Some(implementation_list) => {
4350                     implementation_list.borrow_mut().push(impl_def_id);
4351                     return;
4352                 }
4353                 None => {}
4354             }
4355             tcx.inherent_impls.borrow_mut().insert(type_id,
4356                                                    Rc::new(RefCell::new(vec!(impl_def_id))));
4357         }
4358     });
4359
4360     tcx.populated_external_types.borrow_mut().insert(type_id);
4361 }
4362
4363 /// Populates the type context with all the implementations for the given
4364 /// trait if necessary.
4365 pub fn populate_implementations_for_trait_if_necessary(
4366         tcx: &ctxt,
4367         trait_id: ast::DefId) {
4368     if trait_id.krate == LOCAL_CRATE {
4369         return
4370     }
4371     if tcx.populated_external_traits.borrow().contains(&trait_id) {
4372         return
4373     }
4374
4375     csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
4376             |implementation_def_id| {
4377         let methods = csearch::get_impl_methods(&tcx.sess.cstore, implementation_def_id);
4378
4379         // Record the trait->implementation mapping.
4380         record_trait_implementation(tcx, trait_id, implementation_def_id);
4381
4382         // For any methods that use a default implementation, add them to
4383         // the map. This is a bit unfortunate.
4384         for &method_def_id in methods.iter() {
4385             for &source in ty::method(tcx, method_def_id).provided_source.iter() {
4386                 tcx.provided_method_sources.borrow_mut().insert(method_def_id, source);
4387             }
4388         }
4389
4390         // Store the implementation info.
4391         tcx.impl_methods.borrow_mut().insert(implementation_def_id, methods);
4392     });
4393
4394     tcx.populated_external_traits.borrow_mut().insert(trait_id);
4395 }
4396
4397 /// Given the def_id of an impl, return the def_id of the trait it implements.
4398 /// If it implements no trait, return `None`.
4399 pub fn trait_id_of_impl(tcx: &ctxt,
4400                         def_id: ast::DefId) -> Option<ast::DefId> {
4401     let node = match tcx.map.find(def_id.node) {
4402         Some(node) => node,
4403         None => return None
4404     };
4405     match node {
4406         ast_map::NodeItem(item) => {
4407             match item.node {
4408                 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
4409                     Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
4410                 }
4411                 _ => None
4412             }
4413         }
4414         _ => None
4415     }
4416 }
4417
4418 /// If the given def ID describes a method belonging to an impl, return the
4419 /// ID of the impl that the method belongs to. Otherwise, return `None`.
4420 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
4421                        -> Option<ast::DefId> {
4422     if def_id.krate != LOCAL_CRATE {
4423         return match csearch::get_method(tcx, def_id).container {
4424             TraitContainer(_) => None,
4425             ImplContainer(def_id) => Some(def_id),
4426         };
4427     }
4428     match tcx.methods.borrow().find_copy(&def_id) {
4429         Some(method) => {
4430             match method.container {
4431                 TraitContainer(_) => None,
4432                 ImplContainer(def_id) => Some(def_id),
4433             }
4434         }
4435         None => None
4436     }
4437 }
4438
4439 /// If the given def ID describes a method belonging to a trait (either a
4440 /// default method or an implementation of a trait method), return the ID of
4441 /// the trait that the method belongs to. Otherwise, return `None`.
4442 pub fn trait_of_method(tcx: &ctxt, def_id: ast::DefId)
4443                        -> Option<ast::DefId> {
4444     if def_id.krate != LOCAL_CRATE {
4445         return csearch::get_trait_of_method(&tcx.sess.cstore, def_id, tcx);
4446     }
4447     match tcx.methods.borrow().find_copy(&def_id) {
4448         Some(method) => {
4449             match method.container {
4450                 TraitContainer(def_id) => Some(def_id),
4451                 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
4452             }
4453         }
4454         None => None
4455     }
4456 }
4457
4458 /// If the given def ID describes a method belonging to a trait, (either a
4459 /// default method or an implementation of a trait method), return the ID of
4460 /// the method inside trait definition (this means that if the given def ID
4461 /// is already that of the original trait method, then the return value is
4462 /// the same).
4463 /// Otherwise, return `None`.
4464 pub fn trait_method_of_method(tcx: &ctxt,
4465                               def_id: ast::DefId) -> Option<ast::DefId> {
4466     let method = match tcx.methods.borrow().find(&def_id) {
4467         Some(m) => m.clone(),
4468         None => return None,
4469     };
4470     let name = method.ident.name;
4471     match trait_of_method(tcx, def_id) {
4472         Some(trait_did) => {
4473             let trait_methods = ty::trait_methods(tcx, trait_did);
4474             trait_methods.iter()
4475                 .position(|m| m.ident.name == name)
4476                 .map(|idx| ty::trait_method(tcx, trait_did, idx).def_id)
4477         }
4478         None => None
4479     }
4480 }
4481
4482 /// Creates a hash of the type `t` which will be the same no matter what crate
4483 /// context it's calculated within. This is used by the `type_id` intrinsic.
4484 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
4485     let mut state = sip::SipState::new();
4486     macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
4487     macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
4488
4489     let region = |_state: &mut sip::SipState, r: Region| {
4490         match r {
4491             ReStatic => {}
4492
4493             ReEmpty |
4494             ReEarlyBound(..) |
4495             ReLateBound(..) |
4496             ReFree(..) |
4497             ReScope(..) |
4498             ReInfer(..) => {
4499                 tcx.sess.bug("non-static region found when hashing a type")
4500             }
4501         }
4502     };
4503     let did = |state: &mut sip::SipState, did: DefId| {
4504         let h = if ast_util::is_local(did) {
4505             svh.clone()
4506         } else {
4507             tcx.sess.cstore.get_crate_hash(did.krate)
4508         };
4509         h.as_str().hash(state);
4510         did.node.hash(state);
4511     };
4512     let mt = |state: &mut sip::SipState, mt: mt| {
4513         mt.mutbl.hash(state);
4514     };
4515     ty::walk_ty(t, |t| {
4516         match ty::get(t).sty {
4517             ty_nil => byte!(0),
4518             ty_bot => byte!(1),
4519             ty_bool => byte!(2),
4520             ty_char => byte!(3),
4521             ty_int(i) => {
4522                 byte!(4);
4523                 hash!(i);
4524             }
4525             ty_uint(u) => {
4526                 byte!(5);
4527                 hash!(u);
4528             }
4529             ty_float(f) => {
4530                 byte!(6);
4531                 hash!(f);
4532             }
4533             ty_str => {
4534                 byte!(7);
4535             }
4536             ty_enum(d, _) => {
4537                 byte!(8);
4538                 did(&mut state, d);
4539             }
4540             ty_box(_) => {
4541                 byte!(9);
4542             }
4543             ty_uniq(_) => {
4544                 byte!(10);
4545             }
4546             ty_vec(m, Some(n)) => {
4547                 byte!(11);
4548                 mt(&mut state, m);
4549                 n.hash(&mut state);
4550                 1u8.hash(&mut state);
4551             }
4552             ty_vec(m, None) => {
4553                 byte!(11);
4554                 mt(&mut state, m);
4555                 0u8.hash(&mut state);
4556             }
4557             ty_ptr(m) => {
4558                 byte!(12);
4559                 mt(&mut state, m);
4560             }
4561             ty_rptr(r, m) => {
4562                 byte!(13);
4563                 region(&mut state, r);
4564                 mt(&mut state, m);
4565             }
4566             ty_bare_fn(ref b) => {
4567                 byte!(14);
4568                 hash!(b.fn_style);
4569                 hash!(b.abi);
4570             }
4571             ty_closure(ref c) => {
4572                 byte!(15);
4573                 hash!(c.fn_style);
4574                 hash!(c.onceness);
4575                 hash!(c.bounds);
4576                 match c.store {
4577                     UniqTraitStore => byte!(0),
4578                     RegionTraitStore(r, m) => {
4579                         byte!(1)
4580                         region(&mut state, r);
4581                         assert_eq!(m, ast::MutMutable);
4582                     }
4583                 }
4584             }
4585             ty_trait(box ty::TyTrait { def_id: d, bounds, .. }) => {
4586                 byte!(17);
4587                 did(&mut state, d);
4588                 hash!(bounds);
4589             }
4590             ty_struct(d, _) => {
4591                 byte!(18);
4592                 did(&mut state, d);
4593             }
4594             ty_tup(ref inner) => {
4595                 byte!(19);
4596                 hash!(inner.len());
4597             }
4598             ty_param(p) => {
4599                 byte!(20);
4600                 hash!(p.idx);
4601                 did(&mut state, p.def_id);
4602             }
4603             ty_infer(_) => unreachable!(),
4604             ty_err => byte!(23),
4605         }
4606     });
4607
4608     state.result()
4609 }
4610
4611 impl Variance {
4612     pub fn to_str(self) -> &'static str {
4613         match self {
4614             Covariant => "+",
4615             Contravariant => "-",
4616             Invariant => "o",
4617             Bivariant => "*",
4618         }
4619     }
4620 }
4621
4622 pub fn construct_parameter_environment(
4623     tcx: &ctxt,
4624     generics: &ty::Generics,
4625     free_id: ast::NodeId)
4626     -> ParameterEnvironment
4627 {
4628     /*! See `ParameterEnvironment` struct def'n for details */
4629
4630     //
4631     // Construct the free substs.
4632     //
4633
4634     // map T => T
4635     let mut types = VecPerParamSpace::empty();
4636     for &space in subst::ParamSpace::all().iter() {
4637         push_types_from_defs(tcx, &mut types, space,
4638                              generics.types.get_vec(space));
4639     }
4640
4641     // map bound 'a => free 'a
4642     let mut regions = VecPerParamSpace::empty();
4643     for &space in subst::ParamSpace::all().iter() {
4644         push_region_params(&mut regions, space, free_id,
4645                            generics.regions.get_vec(space));
4646     }
4647
4648     let free_substs = Substs {
4649         types: types,
4650         regions: subst::NonerasedRegions(regions)
4651     };
4652
4653     //
4654     // Compute the bounds on Self and the type parameters.
4655     //
4656
4657     let mut bounds = VecPerParamSpace::empty();
4658     for &space in subst::ParamSpace::all().iter() {
4659         push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
4660                               generics.types.get_vec(space));
4661     }
4662
4663     debug!("construct_parameter_environment: free_id={} \
4664            free_subst={} \
4665            bounds={}",
4666            free_id,
4667            free_substs.repr(tcx),
4668            bounds.repr(tcx));
4669
4670     return ty::ParameterEnvironment {
4671         free_substs: free_substs,
4672         bounds: bounds
4673     };
4674
4675     fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
4676                           space: subst::ParamSpace,
4677                           free_id: ast::NodeId,
4678                           region_params: &Vec<RegionParameterDef>)
4679     {
4680         for r in region_params.iter() {
4681             regions.push(space, ty::free_region_from_def(free_id, r));
4682         }
4683     }
4684
4685     fn push_types_from_defs(tcx: &ty::ctxt,
4686                             types: &mut subst::VecPerParamSpace<ty::t>,
4687                             space: subst::ParamSpace,
4688                             defs: &Vec<TypeParameterDef>) {
4689         for (i, def) in defs.iter().enumerate() {
4690             let ty = ty::mk_param(tcx, space, i, def.def_id);
4691             types.push(space, ty);
4692         }
4693     }
4694
4695     fn push_bounds_from_defs(tcx: &ty::ctxt,
4696                              bounds: &mut subst::VecPerParamSpace<ParamBounds>,
4697                              space: subst::ParamSpace,
4698                              free_substs: &subst::Substs,
4699                              defs: &Vec<TypeParameterDef>) {
4700         for def in defs.iter() {
4701             let b = (*def.bounds).subst(tcx, free_substs);
4702             bounds.push(space, b);
4703         }
4704     }
4705 }
4706
4707 impl BorrowKind {
4708     pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
4709         match m {
4710             ast::MutMutable => MutBorrow,
4711             ast::MutImmutable => ImmBorrow,
4712         }
4713     }
4714
4715     pub fn to_user_str(&self) -> &'static str {
4716         match *self {
4717             MutBorrow => "mutable",
4718             ImmBorrow => "immutable",
4719             UniqueImmBorrow => "uniquely immutable",
4720         }
4721     }
4722 }
4723
4724 impl mc::Typer for ty::ctxt {
4725     fn tcx<'a>(&'a self) -> &'a ty::ctxt {
4726         self
4727     }
4728
4729     fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
4730         Ok(ty::node_id_to_type(self, id))
4731     }
4732
4733     fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
4734         self.method_map.borrow().find(&method_call).map(|method| method.ty)
4735     }
4736
4737     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
4738         &self.adjustments
4739     }
4740
4741     fn is_method_call(&self, id: ast::NodeId) -> bool {
4742         self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
4743     }
4744
4745     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
4746         self.region_maps.temporary_scope(rvalue_id)
4747     }
4748
4749     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
4750         self.upvar_borrow_map.borrow().get_copy(&upvar_id)
4751     }
4752 }