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