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