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