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