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