]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty.rs
rollup merge of #17297 : treeman/net-unix
[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(_, Some(_)) => "array".to_string(),
3793         ty_vec(_, None) => "unsized array".to_string(),
3794         ty_ptr(_) => "*-ptr".to_string(),
3795         ty_rptr(_, _) => "&-ptr".to_string(),
3796         ty_bare_fn(_) => "extern fn".to_string(),
3797         ty_closure(_) => "fn".to_string(),
3798         ty_trait(ref inner) => {
3799             format!("trait {}", item_path_str(cx, inner.def_id))
3800         }
3801         ty_struct(id, _) => {
3802             format!("struct {}", item_path_str(cx, id))
3803         }
3804         ty_unboxed_closure(..) => "closure".to_string(),
3805         ty_tup(_) => "tuple".to_string(),
3806         ty_infer(TyVar(_)) => "inferred type".to_string(),
3807         ty_infer(IntVar(_)) => "integral variable".to_string(),
3808         ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
3809         ty_infer(SkolemizedTy(_)) => "skolemized type".to_string(),
3810         ty_infer(SkolemizedIntTy(_)) => "skolemized integral type".to_string(),
3811         ty_param(ref p) => {
3812             if p.space == subst::SelfSpace {
3813                 "Self".to_string()
3814             } else {
3815                 "type parameter".to_string()
3816             }
3817         }
3818         ty_err => "type error".to_string(),
3819         ty_open(_) => "opened DST".to_string(),
3820     }
3821 }
3822
3823 pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
3824     /*!
3825      *
3826      * Explains the source of a type err in a short,
3827      * human readable way.  This is meant to be placed in
3828      * parentheses after some larger message.  You should
3829      * also invoke `note_and_explain_type_err()` afterwards
3830      * to present additional details, particularly when
3831      * it comes to lifetime-related errors. */
3832
3833     fn tstore_to_closure(s: &TraitStore) -> String {
3834         match s {
3835             &UniqTraitStore => "proc".to_string(),
3836             &RegionTraitStore(..) => "closure".to_string()
3837         }
3838     }
3839
3840     match *err {
3841         terr_cyclic_ty => "cyclic type of infinite size".to_string(),
3842         terr_mismatch => "types differ".to_string(),
3843         terr_fn_style_mismatch(values) => {
3844             format!("expected {} fn, found {} fn",
3845                     values.expected.to_string(),
3846                     values.found.to_string())
3847         }
3848         terr_abi_mismatch(values) => {
3849             format!("expected {} fn, found {} fn",
3850                     values.expected.to_string(),
3851                     values.found.to_string())
3852         }
3853         terr_onceness_mismatch(values) => {
3854             format!("expected {} fn, found {} fn",
3855                     values.expected.to_string(),
3856                     values.found.to_string())
3857         }
3858         terr_sigil_mismatch(values) => {
3859             format!("expected {}, found {}",
3860                     tstore_to_closure(&values.expected),
3861                     tstore_to_closure(&values.found))
3862         }
3863         terr_mutability => "values differ in mutability".to_string(),
3864         terr_box_mutability => {
3865             "boxed values differ in mutability".to_string()
3866         }
3867         terr_vec_mutability => "vectors differ in mutability".to_string(),
3868         terr_ptr_mutability => "pointers differ in mutability".to_string(),
3869         terr_ref_mutability => "references differ in mutability".to_string(),
3870         terr_ty_param_size(values) => {
3871             format!("expected a type with {} type params, \
3872                      found one with {} type params",
3873                     values.expected,
3874                     values.found)
3875         }
3876         terr_tuple_size(values) => {
3877             format!("expected a tuple with {} elements, \
3878                      found one with {} elements",
3879                     values.expected,
3880                     values.found)
3881         }
3882         terr_record_size(values) => {
3883             format!("expected a record with {} fields, \
3884                      found one with {} fields",
3885                     values.expected,
3886                     values.found)
3887         }
3888         terr_record_mutability => {
3889             "record elements differ in mutability".to_string()
3890         }
3891         terr_record_fields(values) => {
3892             format!("expected a record with field `{}`, found one \
3893                      with field `{}`",
3894                     token::get_ident(values.expected),
3895                     token::get_ident(values.found))
3896         }
3897         terr_arg_count => {
3898             "incorrect number of function parameters".to_string()
3899         }
3900         terr_regions_does_not_outlive(..) => {
3901             "lifetime mismatch".to_string()
3902         }
3903         terr_regions_not_same(..) => {
3904             "lifetimes are not the same".to_string()
3905         }
3906         terr_regions_no_overlap(..) => {
3907             "lifetimes do not intersect".to_string()
3908         }
3909         terr_regions_insufficiently_polymorphic(br, _) => {
3910             format!("expected bound lifetime parameter {}, \
3911                      found concrete lifetime",
3912                     bound_region_ptr_to_string(cx, br))
3913         }
3914         terr_regions_overly_polymorphic(br, _) => {
3915             format!("expected concrete lifetime, \
3916                      found bound lifetime parameter {}",
3917                     bound_region_ptr_to_string(cx, br))
3918         }
3919         terr_trait_stores_differ(_, ref values) => {
3920             format!("trait storage differs: expected `{}`, found `{}`",
3921                     trait_store_to_string(cx, (*values).expected),
3922                     trait_store_to_string(cx, (*values).found))
3923         }
3924         terr_sorts(values) => {
3925             format!("expected {}, found {}",
3926                     ty_sort_string(cx, values.expected),
3927                     ty_sort_string(cx, values.found))
3928         }
3929         terr_traits(values) => {
3930             format!("expected trait `{}`, found trait `{}`",
3931                     item_path_str(cx, values.expected),
3932                     item_path_str(cx, values.found))
3933         }
3934         terr_builtin_bounds(values) => {
3935             if values.expected.is_empty() {
3936                 format!("expected no bounds, found `{}`",
3937                         values.found.user_string(cx))
3938             } else if values.found.is_empty() {
3939                 format!("expected bounds `{}`, found no bounds",
3940                         values.expected.user_string(cx))
3941             } else {
3942                 format!("expected bounds `{}`, found bounds `{}`",
3943                         values.expected.user_string(cx),
3944                         values.found.user_string(cx))
3945             }
3946         }
3947         terr_integer_as_char => {
3948             "expected an integral type, found `char`".to_string()
3949         }
3950         terr_int_mismatch(ref values) => {
3951             format!("expected `{}`, found `{}`",
3952                     values.expected.to_string(),
3953                     values.found.to_string())
3954         }
3955         terr_float_mismatch(ref values) => {
3956             format!("expected `{}`, found `{}`",
3957                     values.expected.to_string(),
3958                     values.found.to_string())
3959         }
3960         terr_variadic_mismatch(ref values) => {
3961             format!("expected {} fn, found {} function",
3962                     if values.expected { "variadic" } else { "non-variadic" },
3963                     if values.found { "variadic" } else { "non-variadic" })
3964         }
3965     }
3966 }
3967
3968 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
3969     match *err {
3970         terr_regions_does_not_outlive(subregion, superregion) => {
3971             note_and_explain_region(cx, "", subregion, "...");
3972             note_and_explain_region(cx, "...does not necessarily outlive ",
3973                                     superregion, "");
3974         }
3975         terr_regions_not_same(region1, region2) => {
3976             note_and_explain_region(cx, "", region1, "...");
3977             note_and_explain_region(cx, "...is not the same lifetime as ",
3978                                     region2, "");
3979         }
3980         terr_regions_no_overlap(region1, region2) => {
3981             note_and_explain_region(cx, "", region1, "...");
3982             note_and_explain_region(cx, "...does not overlap ",
3983                                     region2, "");
3984         }
3985         terr_regions_insufficiently_polymorphic(_, conc_region) => {
3986             note_and_explain_region(cx,
3987                                     "concrete lifetime that was found is ",
3988                                     conc_region, "");
3989         }
3990         terr_regions_overly_polymorphic(_, conc_region) => {
3991             note_and_explain_region(cx,
3992                                     "expected concrete lifetime is ",
3993                                     conc_region, "");
3994         }
3995         _ => {}
3996     }
3997 }
3998
3999 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
4000     cx.provided_method_sources.borrow().find(&id).map(|x| *x)
4001 }
4002
4003 pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
4004     if is_local(id) {
4005         match cx.map.find(id.node) {
4006             Some(ast_map::NodeItem(item)) => {
4007                 match item.node {
4008                     ItemTrait(_, _, _, ref ms) => {
4009                         ms.iter().filter_map(|m| match *m {
4010                             ast::RequiredMethod(_) => None,
4011                             ast::ProvidedMethod(ref m) => {
4012                                 match impl_or_trait_item(cx,
4013                                         ast_util::local_def(m.id)) {
4014                                     MethodTraitItem(m) => Some(m),
4015                                 }
4016                             }
4017                          }).collect()
4018                     }
4019                     _ => {
4020                         cx.sess.bug(format!("provided_trait_methods: `{}` is \
4021                                              not a trait",
4022                                             id).as_slice())
4023                     }
4024                 }
4025             }
4026             _ => {
4027                 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
4028                                      trait",
4029                                     id).as_slice())
4030             }
4031         }
4032     } else {
4033         csearch::get_provided_trait_methods(cx, id)
4034     }
4035 }
4036
4037 fn lookup_locally_or_in_crate_store<V:Clone>(
4038                                     descr: &str,
4039                                     def_id: ast::DefId,
4040                                     map: &mut DefIdMap<V>,
4041                                     load_external: || -> V) -> V {
4042     /*!
4043      * Helper for looking things up in the various maps
4044      * that are populated during typeck::collect (e.g.,
4045      * `cx.impl_or_trait_items`, `cx.tcache`, etc).  All of these share
4046      * the pattern that if the id is local, it should have
4047      * been loaded into the map by the `typeck::collect` phase.
4048      * If the def-id is external, then we have to go consult
4049      * the crate loading code (and cache the result for the future).
4050      */
4051
4052     match map.find_copy(&def_id) {
4053         Some(v) => { return v; }
4054         None => { }
4055     }
4056
4057     if def_id.krate == ast::LOCAL_CRATE {
4058         fail!("No def'n found for {:?} in tcx.{}", def_id, descr);
4059     }
4060     let v = load_external();
4061     map.insert(def_id, v.clone());
4062     v
4063 }
4064
4065 pub fn trait_item(cx: &ctxt, trait_did: ast::DefId, idx: uint)
4066                   -> ImplOrTraitItem {
4067     let method_def_id = ty::trait_item_def_ids(cx, trait_did).get(idx)
4068                                                              .def_id();
4069     impl_or_trait_item(cx, method_def_id)
4070 }
4071
4072 pub fn trait_items(cx: &ctxt, trait_did: ast::DefId)
4073                    -> Rc<Vec<ImplOrTraitItem>> {
4074     let mut trait_items = cx.trait_items_cache.borrow_mut();
4075     match trait_items.find_copy(&trait_did) {
4076         Some(trait_items) => trait_items,
4077         None => {
4078             let def_ids = ty::trait_item_def_ids(cx, trait_did);
4079             let items: Rc<Vec<ImplOrTraitItem>> =
4080                 Rc::new(def_ids.iter()
4081                                .map(|d| impl_or_trait_item(cx, d.def_id()))
4082                                .collect());
4083             trait_items.insert(trait_did, items.clone());
4084             items
4085         }
4086     }
4087 }
4088
4089 pub fn impl_or_trait_item(cx: &ctxt, id: ast::DefId) -> ImplOrTraitItem {
4090     lookup_locally_or_in_crate_store("impl_or_trait_items",
4091                                      id,
4092                                      &mut *cx.impl_or_trait_items
4093                                              .borrow_mut(),
4094                                      || {
4095         csearch::get_impl_or_trait_item(cx, id)
4096     })
4097 }
4098
4099 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
4100                           -> Rc<Vec<ImplOrTraitItemId>> {
4101     lookup_locally_or_in_crate_store("trait_item_def_ids",
4102                                      id,
4103                                      &mut *cx.trait_item_def_ids.borrow_mut(),
4104                                      || {
4105         Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
4106     })
4107 }
4108
4109 pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<Rc<TraitRef>> {
4110     match cx.impl_trait_cache.borrow().find(&id) {
4111         Some(ret) => { return ret.clone(); }
4112         None => {}
4113     }
4114
4115     let ret = if id.krate == ast::LOCAL_CRATE {
4116         debug!("(impl_trait_ref) searching for trait impl {:?}", id);
4117         match cx.map.find(id.node) {
4118             Some(ast_map::NodeItem(item)) => {
4119                 match item.node {
4120                     ast::ItemImpl(_, ref opt_trait, _, _) => {
4121                         match opt_trait {
4122                             &Some(ref t) => {
4123                                 Some(ty::node_id_to_trait_ref(cx, t.ref_id))
4124                             }
4125                             &None => None
4126                         }
4127                     }
4128                     _ => None
4129                 }
4130             }
4131             _ => None
4132         }
4133     } else {
4134         csearch::get_impl_trait(cx, id)
4135     };
4136
4137     cx.impl_trait_cache.borrow_mut().insert(id, ret.clone());
4138     ret
4139 }
4140
4141 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
4142     let def = *tcx.def_map.borrow()
4143                      .find(&tr.ref_id)
4144                      .expect("no def-map entry for trait");
4145     def.def_id()
4146 }
4147
4148 pub fn try_add_builtin_trait(
4149     tcx: &ctxt,
4150     trait_def_id: ast::DefId,
4151     builtin_bounds: &mut EnumSet<BuiltinBound>)
4152     -> bool
4153 {
4154     //! Checks whether `trait_ref` refers to one of the builtin
4155     //! traits, like `Send`, and adds the corresponding
4156     //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
4157     //! is a builtin trait.
4158
4159     match tcx.lang_items.to_builtin_kind(trait_def_id) {
4160         Some(bound) => { builtin_bounds.add(bound); true }
4161         None => false
4162     }
4163 }
4164
4165 pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
4166     match get(ty).sty {
4167         ty_trait(box TyTrait { def_id: id, .. }) |
4168         ty_struct(id, _) |
4169         ty_enum(id, _) |
4170         ty_unboxed_closure(id, _) => Some(id),
4171         _ => None
4172     }
4173 }
4174
4175 // Enum information
4176 #[deriving(Clone)]
4177 pub struct VariantInfo {
4178     pub args: Vec<t>,
4179     pub arg_names: Option<Vec<ast::Ident> >,
4180     pub ctor_ty: t,
4181     pub name: ast::Ident,
4182     pub id: ast::DefId,
4183     pub disr_val: Disr,
4184     pub vis: Visibility
4185 }
4186
4187 impl VariantInfo {
4188
4189     /// Creates a new VariantInfo from the corresponding ast representation.
4190     ///
4191     /// Does not do any caching of the value in the type context.
4192     pub fn from_ast_variant(cx: &ctxt,
4193                             ast_variant: &ast::Variant,
4194                             discriminant: Disr) -> VariantInfo {
4195         let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
4196
4197         match ast_variant.node.kind {
4198             ast::TupleVariantKind(ref args) => {
4199                 let arg_tys = if args.len() > 0 {
4200                     ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
4201                 } else {
4202                     Vec::new()
4203                 };
4204
4205                 return VariantInfo {
4206                     args: arg_tys,
4207                     arg_names: None,
4208                     ctor_ty: ctor_ty,
4209                     name: ast_variant.node.name,
4210                     id: ast_util::local_def(ast_variant.node.id),
4211                     disr_val: discriminant,
4212                     vis: ast_variant.node.vis
4213                 };
4214             },
4215             ast::StructVariantKind(ref struct_def) => {
4216
4217                 let fields: &[StructField] = struct_def.fields.as_slice();
4218
4219                 assert!(fields.len() > 0);
4220
4221                 let arg_tys = ty_fn_args(ctor_ty).iter().map(|a| *a).collect();
4222                 let arg_names = fields.iter().map(|field| {
4223                     match field.node.kind {
4224                         NamedField(ident, _) => ident,
4225                         UnnamedField(..) => cx.sess.bug(
4226                             "enum_variants: all fields in struct must have a name")
4227                     }
4228                 }).collect();
4229
4230                 return VariantInfo {
4231                     args: arg_tys,
4232                     arg_names: Some(arg_names),
4233                     ctor_ty: ctor_ty,
4234                     name: ast_variant.node.name,
4235                     id: ast_util::local_def(ast_variant.node.id),
4236                     disr_val: discriminant,
4237                     vis: ast_variant.node.vis
4238                 };
4239             }
4240         }
4241     }
4242 }
4243
4244 pub fn substd_enum_variants(cx: &ctxt,
4245                             id: ast::DefId,
4246                             substs: &Substs)
4247                          -> Vec<Rc<VariantInfo>> {
4248     enum_variants(cx, id).iter().map(|variant_info| {
4249         let substd_args = variant_info.args.iter()
4250             .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
4251
4252         let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
4253
4254         Rc::new(VariantInfo {
4255             args: substd_args,
4256             ctor_ty: substd_ctor_ty,
4257             ..(**variant_info).clone()
4258         })
4259     }).collect()
4260 }
4261
4262 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
4263     with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
4264 }
4265
4266 pub enum DtorKind {
4267     NoDtor,
4268     TraitDtor(DefId, bool)
4269 }
4270
4271 impl DtorKind {
4272     pub fn is_present(&self) -> bool {
4273         match *self {
4274             TraitDtor(..) => true,
4275             _ => false
4276         }
4277     }
4278
4279     pub fn has_drop_flag(&self) -> bool {
4280         match self {
4281             &NoDtor => false,
4282             &TraitDtor(_, flag) => flag
4283         }
4284     }
4285 }
4286
4287 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
4288    Otherwise return none. */
4289 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
4290     match cx.destructor_for_type.borrow().find(&struct_id) {
4291         Some(&method_def_id) => {
4292             let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
4293
4294             TraitDtor(method_def_id, flag)
4295         }
4296         None => NoDtor,
4297     }
4298 }
4299
4300 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
4301     ty_dtor(cx, struct_id).is_present()
4302 }
4303
4304 pub fn with_path<T>(cx: &ctxt, id: ast::DefId, f: |ast_map::PathElems| -> T) -> T {
4305     if id.krate == ast::LOCAL_CRATE {
4306         cx.map.with_path(id.node, f)
4307     } else {
4308         f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
4309     }
4310 }
4311
4312 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
4313     enum_variants(cx, id).len() == 1
4314 }
4315
4316 pub fn type_is_empty(cx: &ctxt, t: t) -> bool {
4317     match ty::get(t).sty {
4318        ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
4319        _ => false
4320      }
4321 }
4322
4323 pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
4324     match cx.enum_var_cache.borrow().find(&id) {
4325         Some(variants) => return variants.clone(),
4326         _ => { /* fallthrough */ }
4327     }
4328
4329     let result = if ast::LOCAL_CRATE != id.krate {
4330         Rc::new(csearch::get_enum_variants(cx, id))
4331     } else {
4332         /*
4333           Although both this code and check_enum_variants in typeck/check
4334           call eval_const_expr, it should never get called twice for the same
4335           expr, since check_enum_variants also updates the enum_var_cache
4336          */
4337         match cx.map.get(id.node) {
4338             ast_map::NodeItem(ref item) => {
4339                 match item.node {
4340                     ast::ItemEnum(ref enum_definition, _) => {
4341                         let mut last_discriminant: Option<Disr> = None;
4342                         Rc::new(enum_definition.variants.iter().map(|variant| {
4343
4344                             let mut discriminant = match last_discriminant {
4345                                 Some(val) => val + 1,
4346                                 None => INITIAL_DISCRIMINANT_VALUE
4347                             };
4348
4349                             match variant.node.disr_expr {
4350                                 Some(ref e) => match const_eval::eval_const_expr_partial(cx, &**e) {
4351                                     Ok(const_eval::const_int(val)) => {
4352                                         discriminant = val as Disr
4353                                     }
4354                                     Ok(const_eval::const_uint(val)) => {
4355                                         discriminant = val as Disr
4356                                     }
4357                                     Ok(_) => {
4358                                         cx.sess
4359                                           .span_err(e.span,
4360                                                     "expected signed integer constant");
4361                                     }
4362                                     Err(ref err) => {
4363                                         cx.sess
4364                                           .span_err(e.span,
4365                                                     format!("expected constant: {}",
4366                                                             *err).as_slice());
4367                                     }
4368                                 },
4369                                 None => {}
4370                             };
4371
4372                             last_discriminant = Some(discriminant);
4373                             Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
4374                                                                   discriminant))
4375                         }).collect())
4376                     }
4377                     _ => {
4378                         cx.sess.bug("enum_variants: id not bound to an enum")
4379                     }
4380                 }
4381             }
4382             _ => cx.sess.bug("enum_variants: id not bound to an enum")
4383         }
4384     };
4385
4386     cx.enum_var_cache.borrow_mut().insert(id, result.clone());
4387     result
4388 }
4389
4390
4391 // Returns information about the enum variant with the given ID:
4392 pub fn enum_variant_with_id(cx: &ctxt,
4393                             enum_id: ast::DefId,
4394                             variant_id: ast::DefId)
4395                          -> Rc<VariantInfo> {
4396     enum_variants(cx, enum_id).iter()
4397                               .find(|variant| variant.id == variant_id)
4398                               .expect("enum_variant_with_id(): no variant exists with that ID")
4399                               .clone()
4400 }
4401
4402
4403 // If the given item is in an external crate, looks up its type and adds it to
4404 // the type cache. Returns the type parameters and type.
4405 pub fn lookup_item_type(cx: &ctxt,
4406                         did: ast::DefId)
4407                      -> Polytype {
4408     lookup_locally_or_in_crate_store(
4409         "tcache", did, &mut *cx.tcache.borrow_mut(),
4410         || csearch::get_type(cx, did))
4411 }
4412
4413 /// Given the did of a trait, returns its canonical trait ref.
4414 pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> Rc<ty::TraitDef> {
4415     let mut trait_defs = cx.trait_defs.borrow_mut();
4416     match trait_defs.find_copy(&did) {
4417         Some(trait_def) => {
4418             // The item is in this crate. The caller should have added it to the
4419             // type cache already
4420             trait_def
4421         }
4422         None => {
4423             assert!(did.krate != ast::LOCAL_CRATE);
4424             let trait_def = Rc::new(csearch::get_trait_def(cx, did));
4425             trait_defs.insert(did, trait_def.clone());
4426             trait_def
4427         }
4428     }
4429 }
4430
4431 /// Given a reference to a trait, returns the bounds declared on the
4432 /// trait, with appropriate substitutions applied.
4433 pub fn bounds_for_trait_ref(tcx: &ctxt,
4434                             trait_ref: &TraitRef)
4435                             -> ty::ParamBounds
4436 {
4437     let trait_def = lookup_trait_def(tcx, trait_ref.def_id);
4438     debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})",
4439            trait_def.repr(tcx), trait_ref.repr(tcx));
4440     trait_def.bounds.subst(tcx, &trait_ref.substs)
4441 }
4442
4443 /// Iterate over attributes of a definition.
4444 // (This should really be an iterator, but that would require csearch and
4445 // decoder to use iterators instead of higher-order functions.)
4446 pub fn each_attr(tcx: &ctxt, did: DefId, f: |&ast::Attribute| -> bool) -> bool {
4447     if is_local(did) {
4448         let item = tcx.map.expect_item(did.node);
4449         item.attrs.iter().all(|attr| f(attr))
4450     } else {
4451         info!("getting foreign attrs");
4452         let mut cont = true;
4453         csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
4454             if cont {
4455                 cont = attrs.iter().all(|attr| f(attr));
4456             }
4457         });
4458         info!("done");
4459         cont
4460     }
4461 }
4462
4463 /// Determine whether an item is annotated with an attribute
4464 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
4465     let mut found = false;
4466     each_attr(tcx, did, |item| {
4467         if item.check_name(attr) {
4468             found = true;
4469             false
4470         } else {
4471             true
4472         }
4473     });
4474     found
4475 }
4476
4477 /// Determine whether an item is annotated with `#[repr(packed)]`
4478 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
4479     lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
4480 }
4481
4482 /// Determine whether an item is annotated with `#[simd]`
4483 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
4484     has_attr(tcx, did, "simd")
4485 }
4486
4487 /// Obtain the representation annotation for a struct definition.
4488 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Vec<attr::ReprAttr> {
4489     let mut acc = Vec::new();
4490
4491     ty::each_attr(tcx, did, |meta| {
4492         acc.extend(attr::find_repr_attrs(tcx.sess.diagnostic(), meta).into_iter());
4493         true
4494     });
4495
4496     acc
4497 }
4498
4499 // Look up a field ID, whether or not it's local
4500 // Takes a list of type substs in case the struct is generic
4501 pub fn lookup_field_type(tcx: &ctxt,
4502                          struct_id: DefId,
4503                          id: DefId,
4504                          substs: &Substs)
4505                       -> ty::t {
4506     let t = if id.krate == ast::LOCAL_CRATE {
4507         node_id_to_type(tcx, id.node)
4508     } else {
4509         let mut tcache = tcx.tcache.borrow_mut();
4510         let pty = tcache.find_or_insert_with(id, |_| {
4511             csearch::get_field_type(tcx, struct_id, id)
4512         });
4513         pty.ty
4514     };
4515     t.subst(tcx, substs)
4516 }
4517
4518 // Lookup all ancestor structs of a struct indicated by did. That is the reflexive,
4519 // transitive closure of doing a single lookup in cx.superstructs.
4520 fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
4521     let superstructs = cx.superstructs.borrow();
4522
4523     loop {
4524         f(did);
4525         match superstructs.find(&did) {
4526             Some(&Some(def_id)) => {
4527                 did = def_id;
4528             },
4529             Some(&None) => break,
4530             None => {
4531                 cx.sess.bug(
4532                     format!("ID not mapped to super-struct: {}",
4533                             cx.map.node_to_string(did.node)).as_slice());
4534             }
4535         }
4536     }
4537 }
4538
4539 // Look up the list of field names and IDs for a given struct.
4540 // Fails if the id is not bound to a struct.
4541 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
4542     if did.krate == ast::LOCAL_CRATE {
4543         // We store the fields which are syntactically in each struct in cx. So
4544         // we have to walk the inheritance chain of the struct to get all the
4545         // structs (explicit and inherited) for a struct. If this is expensive
4546         // we could cache the whole list of fields here.
4547         let struct_fields = cx.struct_fields.borrow();
4548         let mut results: SmallVector<&[field_ty]> = SmallVector::zero();
4549         each_super_struct(cx, did, |s| {
4550             match struct_fields.find(&s) {
4551                 Some(fields) => results.push(fields.as_slice()),
4552                 _ => {
4553                     cx.sess.bug(
4554                         format!("ID not mapped to struct fields: {}",
4555                                 cx.map.node_to_string(did.node)).as_slice());
4556                 }
4557             }
4558         });
4559
4560         let len = results.as_slice().iter().map(|x| x.len()).sum();
4561         let mut result: Vec<field_ty> = Vec::with_capacity(len);
4562         result.extend(results.as_slice().iter().flat_map(|rs| rs.iter().map(|f| f.clone())));
4563         assert!(result.len() == len);
4564         result
4565     } else {
4566         csearch::get_struct_fields(&cx.sess.cstore, did)
4567     }
4568 }
4569
4570 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
4571     let fields = lookup_struct_fields(cx, did);
4572     !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
4573 }
4574
4575 pub fn lookup_struct_field(cx: &ctxt,
4576                            parent: ast::DefId,
4577                            field_id: ast::DefId)
4578                         -> field_ty {
4579     let r = lookup_struct_fields(cx, parent);
4580     match r.iter().find(|f| f.id.node == field_id.node) {
4581         Some(t) => t.clone(),
4582         None => cx.sess.bug("struct ID not found in parent's fields")
4583     }
4584 }
4585
4586 // Returns a list of fields corresponding to the struct's items. trans uses
4587 // this. Takes a list of substs with which to instantiate field types.
4588 pub fn struct_fields(cx: &ctxt, did: ast::DefId, substs: &Substs)
4589                      -> Vec<field> {
4590     lookup_struct_fields(cx, did).iter().map(|f| {
4591        field {
4592             // FIXME #6993: change type of field to Name and get rid of new()
4593             ident: ast::Ident::new(f.name),
4594             mt: mt {
4595                 ty: lookup_field_type(cx, did, f.id, substs),
4596                 mutbl: MutImmutable
4597             }
4598         }
4599     }).collect()
4600 }
4601
4602 // Returns a list of fields corresponding to the tuple's items. trans uses
4603 // this.
4604 pub fn tup_fields(v: &[t]) -> Vec<field> {
4605     v.iter().enumerate().map(|(i, &f)| {
4606        field {
4607             // FIXME #6993: change type of field to Name and get rid of new()
4608             ident: ast::Ident::new(token::intern(i.to_string().as_slice())),
4609             mt: mt {
4610                 ty: f,
4611                 mutbl: MutImmutable
4612             }
4613         }
4614     }).collect()
4615 }
4616
4617 pub struct UnboxedClosureUpvar {
4618     pub def: def::Def,
4619     pub span: Span,
4620     pub ty: t,
4621 }
4622
4623 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
4624 pub fn unboxed_closure_upvars(tcx: &ctxt, closure_id: ast::DefId)
4625                               -> Vec<UnboxedClosureUpvar> {
4626     if closure_id.krate == ast::LOCAL_CRATE {
4627         match tcx.freevars.borrow().find(&closure_id.node) {
4628             None => tcx.sess.bug("no freevars for unboxed closure?!"),
4629             Some(ref freevars) => {
4630                 freevars.iter().map(|freevar| {
4631                     let freevar_def_id = freevar.def.def_id();
4632                     UnboxedClosureUpvar {
4633                         def: freevar.def,
4634                         span: freevar.span,
4635                         ty: node_id_to_type(tcx, freevar_def_id.node),
4636                     }
4637                 }).collect()
4638             }
4639         }
4640     } else {
4641         tcx.sess.bug("unimplemented cross-crate closure upvars")
4642     }
4643 }
4644
4645 pub fn is_binopable(cx: &ctxt, ty: t, op: ast::BinOp) -> bool {
4646     static tycat_other: int = 0;
4647     static tycat_bool: int = 1;
4648     static tycat_char: int = 2;
4649     static tycat_int: int = 3;
4650     static tycat_float: int = 4;
4651     static tycat_bot: int = 5;
4652     static tycat_raw_ptr: int = 6;
4653
4654     static opcat_add: int = 0;
4655     static opcat_sub: int = 1;
4656     static opcat_mult: int = 2;
4657     static opcat_shift: int = 3;
4658     static opcat_rel: int = 4;
4659     static opcat_eq: int = 5;
4660     static opcat_bit: int = 6;
4661     static opcat_logic: int = 7;
4662     static opcat_mod: int = 8;
4663
4664     fn opcat(op: ast::BinOp) -> int {
4665         match op {
4666           ast::BiAdd => opcat_add,
4667           ast::BiSub => opcat_sub,
4668           ast::BiMul => opcat_mult,
4669           ast::BiDiv => opcat_mult,
4670           ast::BiRem => opcat_mod,
4671           ast::BiAnd => opcat_logic,
4672           ast::BiOr => opcat_logic,
4673           ast::BiBitXor => opcat_bit,
4674           ast::BiBitAnd => opcat_bit,
4675           ast::BiBitOr => opcat_bit,
4676           ast::BiShl => opcat_shift,
4677           ast::BiShr => opcat_shift,
4678           ast::BiEq => opcat_eq,
4679           ast::BiNe => opcat_eq,
4680           ast::BiLt => opcat_rel,
4681           ast::BiLe => opcat_rel,
4682           ast::BiGe => opcat_rel,
4683           ast::BiGt => opcat_rel
4684         }
4685     }
4686
4687     fn tycat(cx: &ctxt, ty: t) -> int {
4688         if type_is_simd(cx, ty) {
4689             return tycat(cx, simd_type(cx, ty))
4690         }
4691         match get(ty).sty {
4692           ty_char => tycat_char,
4693           ty_bool => tycat_bool,
4694           ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4695           ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4696           ty_bot => tycat_bot,
4697           ty_ptr(_) => tycat_raw_ptr,
4698           _ => tycat_other
4699         }
4700     }
4701
4702     static t: bool = true;
4703     static f: bool = false;
4704
4705     let tbl = [
4706     //           +, -, *, shift, rel, ==, bit, logic, mod
4707     /*other*/   [f, f, f, f,     f,   f,  f,   f,     f],
4708     /*bool*/    [f, f, f, f,     t,   t,  t,   t,     f],
4709     /*char*/    [f, f, f, f,     t,   t,  f,   f,     f],
4710     /*int*/     [t, t, t, t,     t,   t,  t,   f,     t],
4711     /*float*/   [t, t, t, f,     t,   t,  f,   f,     f],
4712     /*bot*/     [t, t, t, t,     t,   t,  t,   t,     t],
4713     /*raw ptr*/ [f, f, f, f,     t,   t,  f,   f,     f]];
4714
4715     return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
4716 }
4717
4718 /// Returns an equivalent type with all the typedefs and self regions removed.
4719 pub fn normalize_ty(cx: &ctxt, t: t) -> t {
4720     let u = TypeNormalizer(cx).fold_ty(t);
4721     return u;
4722
4723     struct TypeNormalizer<'a, 'tcx: 'a>(&'a ctxt<'tcx>);
4724
4725     impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> {
4726         fn tcx(&self) -> &ctxt<'tcx> { let TypeNormalizer(c) = *self; c }
4727
4728         fn fold_ty(&mut self, t: ty::t) -> ty::t {
4729             match self.tcx().normalized_cache.borrow().find_copy(&t) {
4730                 None => {}
4731                 Some(u) => return u
4732             }
4733
4734             let t_norm = ty_fold::super_fold_ty(self, t);
4735             self.tcx().normalized_cache.borrow_mut().insert(t, t_norm);
4736             return t_norm;
4737         }
4738
4739         fn fold_region(&mut self, _: ty::Region) -> ty::Region {
4740             ty::ReStatic
4741         }
4742
4743         fn fold_substs(&mut self,
4744                        substs: &subst::Substs)
4745                        -> subst::Substs {
4746             subst::Substs { regions: subst::ErasedRegions,
4747                             types: substs.types.fold_with(self) }
4748         }
4749
4750         fn fold_sig(&mut self,
4751                     sig: &ty::FnSig)
4752                     -> ty::FnSig {
4753             // The binder-id is only relevant to bound regions, which
4754             // are erased at trans time.
4755             ty::FnSig {
4756                 binder_id: ast::DUMMY_NODE_ID,
4757                 inputs: sig.inputs.fold_with(self),
4758                 output: sig.output.fold_with(self),
4759                 variadic: sig.variadic,
4760             }
4761         }
4762     }
4763 }
4764
4765 // Returns the repeat count for a repeating vector expression.
4766 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
4767     match const_eval::eval_const_expr_partial(tcx, count_expr) {
4768       Ok(ref const_val) => match *const_val {
4769         const_eval::const_int(count) => if count < 0 {
4770             tcx.sess.span_err(count_expr.span,
4771                               "expected positive integer for \
4772                                repeat count, found negative integer");
4773             0
4774         } else {
4775             count as uint
4776         },
4777         const_eval::const_uint(count) => count as uint,
4778         const_eval::const_float(count) => {
4779             tcx.sess.span_err(count_expr.span,
4780                               "expected positive integer for \
4781                                repeat count, found float");
4782             count as uint
4783         }
4784         const_eval::const_str(_) => {
4785             tcx.sess.span_err(count_expr.span,
4786                               "expected positive integer for \
4787                                repeat count, found string");
4788             0
4789         }
4790         const_eval::const_bool(_) => {
4791             tcx.sess.span_err(count_expr.span,
4792                               "expected positive integer for \
4793                                repeat count, found boolean");
4794             0
4795         }
4796         const_eval::const_binary(_) => {
4797             tcx.sess.span_err(count_expr.span,
4798                               "expected positive integer for \
4799                                repeat count, found binary array");
4800             0
4801         }
4802         const_eval::const_nil => {
4803             tcx.sess.span_err(count_expr.span,
4804                               "expected positive integer for \
4805                                repeat count, found ()");
4806             0
4807         }
4808       },
4809       Err(..) => {
4810         tcx.sess.span_err(count_expr.span,
4811                           "expected constant integer for repeat count, \
4812                            found variable");
4813         0
4814       }
4815     }
4816 }
4817
4818 // Iterate over a type parameter's bounded traits and any supertraits
4819 // of those traits, ignoring kinds.
4820 // Here, the supertraits are the transitive closure of the supertrait
4821 // relation on the supertraits from each bounded trait's constraint
4822 // list.
4823 pub fn each_bound_trait_and_supertraits(tcx: &ctxt,
4824                                         bounds: &[Rc<TraitRef>],
4825                                         f: |Rc<TraitRef>| -> bool)
4826                                         -> bool
4827 {
4828     for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
4829         if !f(bound_trait_ref) {
4830             return false;
4831         }
4832     }
4833     return true;
4834 }
4835
4836 pub fn required_region_bounds(tcx: &ctxt,
4837                               region_bounds: &[ty::Region],
4838                               builtin_bounds: BuiltinBounds,
4839                               trait_bounds: &[Rc<TraitRef>])
4840                               -> Vec<ty::Region>
4841 {
4842     /*!
4843      * Given a type which must meet the builtin bounds and trait
4844      * bounds, returns a set of lifetimes which the type must outlive.
4845      *
4846      * Requires that trait definitions have been processed.
4847      */
4848
4849     let mut all_bounds = Vec::new();
4850
4851     debug!("required_region_bounds(builtin_bounds={}, trait_bounds={})",
4852            builtin_bounds.repr(tcx),
4853            trait_bounds.repr(tcx));
4854
4855     all_bounds.push_all(region_bounds);
4856
4857     push_region_bounds([],
4858                        builtin_bounds,
4859                        &mut all_bounds);
4860
4861     debug!("from builtin bounds: all_bounds={}", all_bounds.repr(tcx));
4862
4863     each_bound_trait_and_supertraits(
4864         tcx,
4865         trait_bounds,
4866         |trait_ref| {
4867             let bounds = ty::bounds_for_trait_ref(tcx, &*trait_ref);
4868             push_region_bounds(bounds.opt_region_bound.as_slice(),
4869                                bounds.builtin_bounds,
4870                                &mut all_bounds);
4871             debug!("from {}: bounds={} all_bounds={}",
4872                    trait_ref.repr(tcx),
4873                    bounds.repr(tcx),
4874                    all_bounds.repr(tcx));
4875             true
4876         });
4877
4878     return all_bounds;
4879
4880     fn push_region_bounds(region_bounds: &[ty::Region],
4881                           builtin_bounds: ty::BuiltinBounds,
4882                           all_bounds: &mut Vec<ty::Region>) {
4883         all_bounds.push_all(region_bounds.as_slice());
4884
4885         if builtin_bounds.contains_elem(ty::BoundSend) {
4886             all_bounds.push(ty::ReStatic);
4887         }
4888     }
4889 }
4890
4891 pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
4892     tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
4893         tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
4894             .expect("Failed to resolve TyDesc")
4895     })
4896 }
4897
4898 pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
4899     tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
4900         tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
4901             .expect("Failed to resolve Opaque")
4902     })
4903 }
4904
4905 pub fn visitor_object_ty(tcx: &ctxt,
4906                          ptr_region: ty::Region,
4907                          trait_region: ty::Region)
4908                          -> Result<(Rc<TraitRef>, t), String>
4909 {
4910     let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
4911         Ok(id) => id,
4912         Err(s) => { return Err(s); }
4913     };
4914     let substs = Substs::empty();
4915     let trait_ref = Rc::new(TraitRef { def_id: trait_lang_item, substs: substs });
4916     Ok((trait_ref.clone(),
4917         mk_rptr(tcx, ptr_region,
4918                 mt {mutbl: ast::MutMutable,
4919                     ty: mk_trait(tcx,
4920                                  trait_ref.def_id,
4921                                  trait_ref.substs.clone(),
4922                                  ty::region_existential_bound(trait_region))})))
4923 }
4924
4925 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
4926     lookup_locally_or_in_crate_store(
4927         "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
4928         || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
4929 }
4930
4931 /// Records a trait-to-implementation mapping.
4932 pub fn record_trait_implementation(tcx: &ctxt,
4933                                    trait_def_id: DefId,
4934                                    impl_def_id: DefId) {
4935     match tcx.trait_impls.borrow().find(&trait_def_id) {
4936         Some(impls_for_trait) => {
4937             impls_for_trait.borrow_mut().push(impl_def_id);
4938             return;
4939         }
4940         None => {}
4941     }
4942     tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
4943 }
4944
4945 /// Populates the type context with all the implementations for the given type
4946 /// if necessary.
4947 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
4948                                                       type_id: ast::DefId) {
4949     if type_id.krate == LOCAL_CRATE {
4950         return
4951     }
4952     if tcx.populated_external_types.borrow().contains(&type_id) {
4953         return
4954     }
4955
4956     let mut inherent_impls = Vec::new();
4957     csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
4958             |impl_def_id| {
4959         let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
4960                                                  impl_def_id);
4961
4962         // Record the trait->implementation mappings, if applicable.
4963         let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
4964         for trait_ref in associated_traits.iter() {
4965             record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
4966         }
4967
4968         // For any methods that use a default implementation, add them to
4969         // the map. This is a bit unfortunate.
4970         for impl_item_def_id in impl_items.iter() {
4971             let method_def_id = impl_item_def_id.def_id();
4972             match impl_or_trait_item(tcx, method_def_id) {
4973                 MethodTraitItem(method) => {
4974                     for &source in method.provided_source.iter() {
4975                         tcx.provided_method_sources
4976                            .borrow_mut()
4977                            .insert(method_def_id, source);
4978                     }
4979                 }
4980             }
4981         }
4982
4983         // Store the implementation info.
4984         tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
4985
4986         // If this is an inherent implementation, record it.
4987         if associated_traits.is_none() {
4988             inherent_impls.push(impl_def_id);
4989         }
4990     });
4991
4992     tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
4993     tcx.populated_external_types.borrow_mut().insert(type_id);
4994 }
4995
4996 /// Populates the type context with all the implementations for the given
4997 /// trait if necessary.
4998 pub fn populate_implementations_for_trait_if_necessary(
4999         tcx: &ctxt,
5000         trait_id: ast::DefId) {
5001     if trait_id.krate == LOCAL_CRATE {
5002         return
5003     }
5004     if tcx.populated_external_traits.borrow().contains(&trait_id) {
5005         return
5006     }
5007
5008     csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
5009             |implementation_def_id| {
5010         let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
5011
5012         // Record the trait->implementation mapping.
5013         record_trait_implementation(tcx, trait_id, implementation_def_id);
5014
5015         // For any methods that use a default implementation, add them to
5016         // the map. This is a bit unfortunate.
5017         for impl_item_def_id in impl_items.iter() {
5018             let method_def_id = impl_item_def_id.def_id();
5019             match impl_or_trait_item(tcx, method_def_id) {
5020                 MethodTraitItem(method) => {
5021                     for &source in method.provided_source.iter() {
5022                         tcx.provided_method_sources
5023                            .borrow_mut()
5024                            .insert(method_def_id, source);
5025                     }
5026                 }
5027             }
5028         }
5029
5030         // Store the implementation info.
5031         tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
5032     });
5033
5034     tcx.populated_external_traits.borrow_mut().insert(trait_id);
5035 }
5036
5037 /// Given the def_id of an impl, return the def_id of the trait it implements.
5038 /// If it implements no trait, return `None`.
5039 pub fn trait_id_of_impl(tcx: &ctxt,
5040                         def_id: ast::DefId) -> Option<ast::DefId> {
5041     let node = match tcx.map.find(def_id.node) {
5042         Some(node) => node,
5043         None => return None
5044     };
5045     match node {
5046         ast_map::NodeItem(item) => {
5047             match item.node {
5048                 ast::ItemImpl(_, Some(ref trait_ref), _, _) => {
5049                     Some(node_id_to_trait_ref(tcx, trait_ref.ref_id).def_id)
5050                 }
5051                 _ => None
5052             }
5053         }
5054         _ => None
5055     }
5056 }
5057
5058 /// If the given def ID describes a method belonging to an impl, return the
5059 /// ID of the impl that the method belongs to. Otherwise, return `None`.
5060 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
5061                        -> Option<ast::DefId> {
5062     if def_id.krate != LOCAL_CRATE {
5063         return match csearch::get_impl_or_trait_item(tcx,
5064                                                      def_id).container() {
5065             TraitContainer(_) => None,
5066             ImplContainer(def_id) => Some(def_id),
5067         };
5068     }
5069     match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5070         Some(trait_item) => {
5071             match trait_item.container() {
5072                 TraitContainer(_) => None,
5073                 ImplContainer(def_id) => Some(def_id),
5074             }
5075         }
5076         None => None
5077     }
5078 }
5079
5080 /// If the given def ID describes an item belonging to a trait (either a
5081 /// default method or an implementation of a trait method), return the ID of
5082 /// the trait that the method belongs to. Otherwise, return `None`.
5083 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
5084     if def_id.krate != LOCAL_CRATE {
5085         return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
5086     }
5087     match tcx.impl_or_trait_items.borrow().find_copy(&def_id) {
5088         Some(impl_or_trait_item) => {
5089             match impl_or_trait_item.container() {
5090                 TraitContainer(def_id) => Some(def_id),
5091                 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
5092             }
5093         }
5094         None => None
5095     }
5096 }
5097
5098 /// If the given def ID describes an item belonging to a trait, (either a
5099 /// default method or an implementation of a trait method), return the ID of
5100 /// the method inside trait definition (this means that if the given def ID
5101 /// is already that of the original trait method, then the return value is
5102 /// the same).
5103 /// Otherwise, return `None`.
5104 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
5105                           -> Option<ImplOrTraitItemId> {
5106     let impl_item = match tcx.impl_or_trait_items.borrow().find(&def_id) {
5107         Some(m) => m.clone(),
5108         None => return None,
5109     };
5110     let name = match impl_item {
5111         MethodTraitItem(method) => method.ident.name,
5112     };
5113     match trait_of_item(tcx, def_id) {
5114         Some(trait_did) => {
5115             let trait_items = ty::trait_items(tcx, trait_did);
5116             trait_items.iter()
5117                 .position(|m| m.ident().name == name)
5118                 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
5119         }
5120         None => None
5121     }
5122 }
5123
5124 /// Creates a hash of the type `t` which will be the same no matter what crate
5125 /// context it's calculated within. This is used by the `type_id` intrinsic.
5126 pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 {
5127     let mut state = sip::SipState::new();
5128     macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } );
5129     macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } );
5130
5131     let region = |_state: &mut sip::SipState, r: Region| {
5132         match r {
5133             ReStatic => {}
5134
5135             ReEmpty |
5136             ReEarlyBound(..) |
5137             ReLateBound(..) |
5138             ReFree(..) |
5139             ReScope(..) |
5140             ReInfer(..) => {
5141                 tcx.sess.bug("non-static region found when hashing a type")
5142             }
5143         }
5144     };
5145     let did = |state: &mut sip::SipState, did: DefId| {
5146         let h = if ast_util::is_local(did) {
5147             svh.clone()
5148         } else {
5149             tcx.sess.cstore.get_crate_hash(did.krate)
5150         };
5151         h.as_str().hash(state);
5152         did.node.hash(state);
5153     };
5154     let mt = |state: &mut sip::SipState, mt: mt| {
5155         mt.mutbl.hash(state);
5156     };
5157     ty::walk_ty(t, |t| {
5158         match ty::get(t).sty {
5159             ty_nil => byte!(0),
5160             ty_bot => byte!(1),
5161             ty_bool => byte!(2),
5162             ty_char => byte!(3),
5163             ty_int(i) => {
5164                 byte!(4);
5165                 hash!(i);
5166             }
5167             ty_uint(u) => {
5168                 byte!(5);
5169                 hash!(u);
5170             }
5171             ty_float(f) => {
5172                 byte!(6);
5173                 hash!(f);
5174             }
5175             ty_str => {
5176                 byte!(7);
5177             }
5178             ty_enum(d, _) => {
5179                 byte!(8);
5180                 did(&mut state, d);
5181             }
5182             ty_box(_) => {
5183                 byte!(9);
5184             }
5185             ty_uniq(_) => {
5186                 byte!(10);
5187             }
5188             ty_vec(_, Some(n)) => {
5189                 byte!(11);
5190                 n.hash(&mut state);
5191             }
5192             ty_vec(_, None) => {
5193                 byte!(11);
5194                 0u8.hash(&mut state);
5195             }
5196             ty_ptr(m) => {
5197                 byte!(12);
5198                 mt(&mut state, m);
5199             }
5200             ty_rptr(r, m) => {
5201                 byte!(13);
5202                 region(&mut state, r);
5203                 mt(&mut state, m);
5204             }
5205             ty_bare_fn(ref b) => {
5206                 byte!(14);
5207                 hash!(b.fn_style);
5208                 hash!(b.abi);
5209             }
5210             ty_closure(ref c) => {
5211                 byte!(15);
5212                 hash!(c.fn_style);
5213                 hash!(c.onceness);
5214                 hash!(c.bounds);
5215                 match c.store {
5216                     UniqTraitStore => byte!(0),
5217                     RegionTraitStore(r, m) => {
5218                         byte!(1)
5219                         region(&mut state, r);
5220                         assert_eq!(m, ast::MutMutable);
5221                     }
5222                 }
5223             }
5224             ty_trait(box TyTrait { def_id: d, bounds, .. }) => {
5225                 byte!(17);
5226                 did(&mut state, d);
5227                 hash!(bounds);
5228             }
5229             ty_struct(d, _) => {
5230                 byte!(18);
5231                 did(&mut state, d);
5232             }
5233             ty_tup(ref inner) => {
5234                 byte!(19);
5235                 hash!(inner.len());
5236             }
5237             ty_param(p) => {
5238                 byte!(20);
5239                 hash!(p.idx);
5240                 did(&mut state, p.def_id);
5241             }
5242             ty_open(_) => byte!(22),
5243             ty_infer(_) => unreachable!(),
5244             ty_err => byte!(23),
5245             ty_unboxed_closure(d, r) => {
5246                 byte!(24);
5247                 did(&mut state, d);
5248                 region(&mut state, r);
5249             }
5250         }
5251     });
5252
5253     state.result()
5254 }
5255
5256 impl Variance {
5257     pub fn to_string(self) -> &'static str {
5258         match self {
5259             Covariant => "+",
5260             Contravariant => "-",
5261             Invariant => "o",
5262             Bivariant => "*",
5263         }
5264     }
5265 }
5266
5267 pub fn empty_parameter_environment() -> ParameterEnvironment {
5268     /*!
5269      * Construct a parameter environment suitable for static contexts
5270      * or other contexts where there are no free type/lifetime
5271      * parameters in scope.
5272      */
5273
5274     ty::ParameterEnvironment { free_substs: Substs::empty(),
5275                                bounds: VecPerParamSpace::empty(),
5276                                caller_obligations: VecPerParamSpace::empty(),
5277                                implicit_region_bound: ty::ReEmpty }
5278 }
5279
5280 pub fn construct_parameter_environment(
5281     tcx: &ctxt,
5282     span: Span,
5283     generics: &ty::Generics,
5284     free_id: ast::NodeId)
5285     -> ParameterEnvironment
5286 {
5287     /*! See `ParameterEnvironment` struct def'n for details */
5288
5289     //
5290     // Construct the free substs.
5291     //
5292
5293     // map T => T
5294     let mut types = VecPerParamSpace::empty();
5295     for &space in subst::ParamSpace::all().iter() {
5296         push_types_from_defs(tcx, &mut types, space,
5297                              generics.types.get_slice(space));
5298     }
5299
5300     // map bound 'a => free 'a
5301     let mut regions = VecPerParamSpace::empty();
5302     for &space in subst::ParamSpace::all().iter() {
5303         push_region_params(&mut regions, space, free_id,
5304                            generics.regions.get_slice(space));
5305     }
5306
5307     let free_substs = Substs {
5308         types: types,
5309         regions: subst::NonerasedRegions(regions)
5310     };
5311
5312     //
5313     // Compute the bounds on Self and the type parameters.
5314     //
5315
5316     let mut bounds = VecPerParamSpace::empty();
5317     for &space in subst::ParamSpace::all().iter() {
5318         push_bounds_from_defs(tcx, &mut bounds, space, &free_substs,
5319                               generics.types.get_slice(space));
5320     }
5321
5322     //
5323     // Compute region bounds. For now, these relations are stored in a
5324     // global table on the tcx, so just enter them there. I'm not
5325     // crazy about this scheme, but it's convenient, at least.
5326     //
5327
5328     for &space in subst::ParamSpace::all().iter() {
5329         record_region_bounds_from_defs(tcx, space, &free_substs,
5330                                        generics.regions.get_slice(space));
5331     }
5332
5333
5334     debug!("construct_parameter_environment: free_id={} \
5335            free_subst={} \
5336            bounds={}",
5337            free_id,
5338            free_substs.repr(tcx),
5339            bounds.repr(tcx));
5340
5341     let obligations = traits::obligations_for_generics(tcx, traits::ObligationCause::misc(span),
5342                                                        generics, &free_substs);
5343
5344     return ty::ParameterEnvironment {
5345         free_substs: free_substs,
5346         bounds: bounds,
5347         implicit_region_bound: ty::ReScope(free_id),
5348         caller_obligations: obligations,
5349     };
5350
5351     fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
5352                           space: subst::ParamSpace,
5353                           free_id: ast::NodeId,
5354                           region_params: &[RegionParameterDef])
5355     {
5356         for r in region_params.iter() {
5357             regions.push(space, ty::free_region_from_def(free_id, r));
5358         }
5359     }
5360
5361     fn push_types_from_defs(tcx: &ty::ctxt,
5362                             types: &mut subst::VecPerParamSpace<ty::t>,
5363                             space: subst::ParamSpace,
5364                             defs: &[TypeParameterDef]) {
5365         for (i, def) in defs.iter().enumerate() {
5366             let ty = ty::mk_param(tcx, space, i, def.def_id);
5367             types.push(space, ty);
5368         }
5369     }
5370
5371     fn push_bounds_from_defs(tcx: &ty::ctxt,
5372                              bounds: &mut subst::VecPerParamSpace<ParamBounds>,
5373                              space: subst::ParamSpace,
5374                              free_substs: &subst::Substs,
5375                              defs: &[TypeParameterDef]) {
5376         for def in defs.iter() {
5377             let b = def.bounds.subst(tcx, free_substs);
5378             bounds.push(space, b);
5379         }
5380     }
5381
5382     fn record_region_bounds_from_defs(tcx: &ty::ctxt,
5383                                       space: subst::ParamSpace,
5384                                       free_substs: &subst::Substs,
5385                                       defs: &[RegionParameterDef]) {
5386         for (subst_region, def) in
5387             free_substs.regions().get_slice(space).iter().zip(
5388                 defs.iter())
5389         {
5390             // For each region parameter 'subst...
5391             let bounds = def.bounds.subst(tcx, free_substs);
5392             for bound_region in bounds.iter() {
5393                 // Which is declared with a bound like 'subst:'bound...
5394                 match (subst_region, bound_region) {
5395                     (&ty::ReFree(subst_fr), &ty::ReFree(bound_fr)) => {
5396                         // Record that 'subst outlives 'bound. Or, put
5397                         // another way, 'bound <= 'subst.
5398                         tcx.region_maps.relate_free_regions(bound_fr, subst_fr);
5399                     },
5400                     _ => {
5401                         // All named regions are instantiated with free regions.
5402                         tcx.sess.bug(
5403                             format!("push_region_bounds_from_defs: \
5404                                      non free region: {} / {}",
5405                                     subst_region.repr(tcx),
5406                                     bound_region.repr(tcx)).as_slice());
5407                     }
5408                 }
5409             }
5410         }
5411     }
5412 }
5413
5414 impl BorrowKind {
5415     pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
5416         match m {
5417             ast::MutMutable => MutBorrow,
5418             ast::MutImmutable => ImmBorrow,
5419         }
5420     }
5421
5422     pub fn to_mutbl_lossy(self) -> ast::Mutability {
5423         /*!
5424          * Returns a mutability `m` such that an `&m T` pointer could
5425          * be used to obtain this borrow kind. Because borrow kinds
5426          * are richer than mutabilities, we sometimes have to pick a
5427          * mutability that is stronger than necessary so that it at
5428          * least *would permit* the borrow in question.
5429          */
5430
5431         match self {
5432             MutBorrow => ast::MutMutable,
5433             ImmBorrow => ast::MutImmutable,
5434
5435             // We have no type correponding to a unique imm borrow, so
5436             // use `&mut`. It gives all the capabilities of an `&uniq`
5437             // and hence is a safe "over approximation".
5438             UniqueImmBorrow => ast::MutMutable,
5439         }
5440     }
5441
5442     pub fn to_user_str(&self) -> &'static str {
5443         match *self {
5444             MutBorrow => "mutable",
5445             ImmBorrow => "immutable",
5446             UniqueImmBorrow => "uniquely immutable",
5447         }
5448     }
5449 }
5450
5451 impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> {
5452     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
5453         self
5454     }
5455
5456     fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
5457         Ok(ty::node_id_to_type(self, id))
5458     }
5459
5460     fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
5461         self.method_map.borrow().find(&method_call).map(|method| method.ty)
5462     }
5463
5464     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
5465         &self.adjustments
5466     }
5467
5468     fn is_method_call(&self, id: ast::NodeId) -> bool {
5469         self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
5470     }
5471
5472     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
5473         self.region_maps.temporary_scope(rvalue_id)
5474     }
5475
5476     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
5477         self.upvar_borrow_map.borrow().get_copy(&upvar_id)
5478     }
5479
5480     fn capture_mode(&self, closure_expr_id: ast::NodeId)
5481                     -> freevars::CaptureMode {
5482         self.capture_modes.borrow().get_copy(&closure_expr_id)
5483     }
5484
5485     fn unboxed_closures<'a>(&'a self)
5486                         -> &'a RefCell<DefIdMap<UnboxedClosure>> {
5487         &self.unboxed_closures
5488     }
5489 }
5490
5491 /// The category of explicit self.
5492 #[deriving(Clone, Eq, PartialEq)]
5493 pub enum ExplicitSelfCategory {
5494     StaticExplicitSelfCategory,
5495     ByValueExplicitSelfCategory,
5496     ByReferenceExplicitSelfCategory(Region, ast::Mutability),
5497     ByBoxExplicitSelfCategory,
5498 }
5499
5500 /// Pushes all the lifetimes in the given type onto the given list. A
5501 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
5502 /// in a list of type substitutions. This does *not* traverse into nominal
5503 /// types, nor does it resolve fictitious types.
5504 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
5505                                     typ: t) {
5506     walk_ty(typ, |typ| {
5507         match get(typ).sty {
5508             ty_rptr(region, _) => accumulator.push(region),
5509             ty_enum(_, ref substs) |
5510             ty_trait(box TyTrait {
5511                 substs: ref substs,
5512                 ..
5513             }) |
5514             ty_struct(_, ref substs) => {
5515                 match substs.regions {
5516                     subst::ErasedRegions => {}
5517                     subst::NonerasedRegions(ref regions) => {
5518                         for region in regions.iter() {
5519                             accumulator.push(*region)
5520                         }
5521                     }
5522                 }
5523             }
5524             ty_closure(ref closure_ty) => {
5525                 match closure_ty.store {
5526                     RegionTraitStore(region, _) => accumulator.push(region),
5527                     UniqTraitStore => {}
5528                 }
5529             }
5530             ty_unboxed_closure(_, ref region) => accumulator.push(*region),
5531             ty_nil |
5532             ty_bot |
5533             ty_bool |
5534             ty_char |
5535             ty_int(_) |
5536             ty_uint(_) |
5537             ty_float(_) |
5538             ty_box(_) |
5539             ty_uniq(_) |
5540             ty_str |
5541             ty_vec(_, _) |
5542             ty_ptr(_) |
5543             ty_bare_fn(_) |
5544             ty_tup(_) |
5545             ty_param(_) |
5546             ty_infer(_) |
5547             ty_open(_) |
5548             ty_err => {}
5549         }
5550     })
5551 }