]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty.rs
rustc: fix fallout
[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 pub use self::terr_vstore_kind::*;
14 pub use self::type_err::*;
15 pub use self::BuiltinBound::*;
16 pub use self::InferTy::*;
17 pub use self::InferRegion::*;
18 pub use self::ImplOrTraitItemId::*;
19 pub use self::UnboxedClosureKind::*;
20 pub use self::TraitStore::*;
21 pub use self::ast_ty_to_ty_cache_entry::*;
22 pub use self::Variance::*;
23 pub use self::AutoAdjustment::*;
24 pub use self::Representability::*;
25 pub use self::UnsizeKind::*;
26 pub use self::AutoRef::*;
27 pub use self::ExprKind::*;
28 pub use self::DtorKind::*;
29 pub use self::ExplicitSelfCategory::*;
30 pub use self::FnOutput::*;
31 pub use self::Region::*;
32 pub use self::ImplOrTraitItemContainer::*;
33 pub use self::BorrowKind::*;
34 pub use self::ImplOrTraitItem::*;
35 pub use self::BoundRegion::*;
36 pub use self::sty::*;
37 pub use self::IntVarValue::*;
38 pub use self::ExprAdjustment::*;
39 pub use self::vtable_origin::*;
40 pub use self::MethodOrigin::*;
41 pub use self::CopyImplementationError::*;
42
43 use back::svh::Svh;
44 use session::Session;
45 use lint;
46 use metadata::csearch;
47 use middle;
48 use middle::const_eval;
49 use middle::def::{mod, DefMap, ExportMap};
50 use middle::dependency_format;
51 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
52 use middle::lang_items::{FnOnceTraitLangItem, TyDescStructLangItem};
53 use middle::mem_categorization as mc;
54 use middle::region;
55 use middle::resolve_lifetime;
56 use middle::infer;
57 use middle::stability;
58 use middle::subst::{mod, Subst, Substs, VecPerParamSpace};
59 use middle::traits;
60 use middle::ty;
61 use middle::ty_fold::{mod, TypeFoldable, TypeFolder};
62 use middle::ty_walk::TypeWalker;
63 use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
64 use util::ppaux::{trait_store_to_string, ty_to_string};
65 use util::ppaux::{Repr, UserString};
66 use util::common::{memoized, ErrorReported};
67 use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet};
68 use util::nodemap::{FnvHashMap};
69
70 use arena::TypedArena;
71 use std::borrow::BorrowFrom;
72 use std::cell::{Cell, RefCell};
73 use std::cmp::{mod, Ordering};
74 use std::fmt::{mod, Show};
75 use std::hash::{Hash, sip, Writer};
76 use std::mem;
77 use std::ops;
78 use std::rc::Rc;
79 use collections::enum_set::{EnumSet, CLike};
80 use std::collections::{HashMap, HashSet};
81 use std::collections::hash_map::Entry::{Occupied, Vacant};
82 use syntax::abi;
83 use syntax::ast::{CrateNum, DefId, Ident, ItemTrait, LOCAL_CRATE};
84 use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
85 use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
86 use syntax::ast::{Visibility};
87 use syntax::ast_util::{mod, is_local, lit_is_str, local_def, PostExpansionMethod};
88 use syntax::attr::{mod, AttrMetaMethods};
89 use syntax::codemap::Span;
90 use syntax::parse::token::{mod, InternedString, special_idents};
91 use syntax::{ast, ast_map};
92
93 pub type Disr = u64;
94
95 pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0;
96
97 // Data types
98
99 /// The complete set of all analyses described in this module. This is
100 /// produced by the driver and fed to trans and later passes.
101 pub struct CrateAnalysis<'tcx> {
102     pub export_map: ExportMap,
103     pub exported_items: middle::privacy::ExportedItems,
104     pub public_items: middle::privacy::PublicItems,
105     pub ty_cx: ty::ctxt<'tcx>,
106     pub reachable: NodeSet,
107     pub name: String,
108     pub glob_map: Option<GlobMap>,
109 }
110
111 #[deriving(Copy, PartialEq, Eq, Hash)]
112 pub struct field<'tcx> {
113     pub name: ast::Name,
114     pub mt: mt<'tcx>
115 }
116
117 #[deriving(Clone, Copy, Show)]
118 pub enum ImplOrTraitItemContainer {
119     TraitContainer(ast::DefId),
120     ImplContainer(ast::DefId),
121 }
122
123 impl ImplOrTraitItemContainer {
124     pub fn id(&self) -> ast::DefId {
125         match *self {
126             TraitContainer(id) => id,
127             ImplContainer(id) => id,
128         }
129     }
130 }
131
132 #[deriving(Clone, Show)]
133 pub enum ImplOrTraitItem<'tcx> {
134     MethodTraitItem(Rc<Method<'tcx>>),
135     TypeTraitItem(Rc<AssociatedType>),
136 }
137
138 impl<'tcx> ImplOrTraitItem<'tcx> {
139     fn id(&self) -> ImplOrTraitItemId {
140         match *self {
141             MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
142             TypeTraitItem(ref associated_type) => {
143                 TypeTraitItemId(associated_type.def_id)
144             }
145         }
146     }
147
148     pub fn def_id(&self) -> ast::DefId {
149         match *self {
150             MethodTraitItem(ref method) => method.def_id,
151             TypeTraitItem(ref associated_type) => associated_type.def_id,
152         }
153     }
154
155     pub fn name(&self) -> ast::Name {
156         match *self {
157             MethodTraitItem(ref method) => method.name,
158             TypeTraitItem(ref associated_type) => associated_type.name,
159         }
160     }
161
162     pub fn container(&self) -> ImplOrTraitItemContainer {
163         match *self {
164             MethodTraitItem(ref method) => method.container,
165             TypeTraitItem(ref associated_type) => associated_type.container,
166         }
167     }
168
169     pub fn as_opt_method(&self) -> Option<Rc<Method<'tcx>>> {
170         match *self {
171             MethodTraitItem(ref m) => Some((*m).clone()),
172             TypeTraitItem(_) => None
173         }
174     }
175 }
176
177 #[deriving(Clone, Copy, Show)]
178 pub enum ImplOrTraitItemId {
179     MethodTraitItemId(ast::DefId),
180     TypeTraitItemId(ast::DefId),
181 }
182
183 impl ImplOrTraitItemId {
184     pub fn def_id(&self) -> ast::DefId {
185         match *self {
186             MethodTraitItemId(def_id) => def_id,
187             TypeTraitItemId(def_id) => def_id,
188         }
189     }
190 }
191
192 #[deriving(Clone, Show)]
193 pub struct Method<'tcx> {
194     pub name: ast::Name,
195     pub generics: ty::Generics<'tcx>,
196     pub fty: BareFnTy<'tcx>,
197     pub explicit_self: ExplicitSelfCategory,
198     pub vis: ast::Visibility,
199     pub def_id: ast::DefId,
200     pub container: ImplOrTraitItemContainer,
201
202     // If this method is provided, we need to know where it came from
203     pub provided_source: Option<ast::DefId>
204 }
205
206 impl<'tcx> Method<'tcx> {
207     pub fn new(name: ast::Name,
208                generics: ty::Generics<'tcx>,
209                fty: BareFnTy<'tcx>,
210                explicit_self: ExplicitSelfCategory,
211                vis: ast::Visibility,
212                def_id: ast::DefId,
213                container: ImplOrTraitItemContainer,
214                provided_source: Option<ast::DefId>)
215                -> Method<'tcx> {
216        Method {
217             name: name,
218             generics: generics,
219             fty: fty,
220             explicit_self: explicit_self,
221             vis: vis,
222             def_id: def_id,
223             container: container,
224             provided_source: provided_source
225         }
226     }
227
228     pub fn container_id(&self) -> ast::DefId {
229         match self.container {
230             TraitContainer(id) => id,
231             ImplContainer(id) => id,
232         }
233     }
234 }
235
236 #[deriving(Clone, Copy, Show)]
237 pub struct AssociatedType {
238     pub name: ast::Name,
239     pub vis: ast::Visibility,
240     pub def_id: ast::DefId,
241     pub container: ImplOrTraitItemContainer,
242 }
243
244 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
245 pub struct mt<'tcx> {
246     pub ty: Ty<'tcx>,
247     pub mutbl: ast::Mutability,
248 }
249
250 #[deriving(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show)]
251 pub enum TraitStore {
252     /// Box<Trait>
253     UniqTraitStore,
254     /// &Trait and &mut Trait
255     RegionTraitStore(Region, ast::Mutability),
256 }
257
258 #[deriving(Clone, Copy, Show)]
259 pub struct field_ty {
260     pub name: Name,
261     pub id: DefId,
262     pub vis: ast::Visibility,
263     pub origin: ast::DefId,  // The DefId of the struct in which the field is declared.
264 }
265
266 // Contains information needed to resolve types and (in the future) look up
267 // the types of AST nodes.
268 #[deriving(Copy, PartialEq, Eq, Hash)]
269 pub struct creader_cache_key {
270     pub cnum: CrateNum,
271     pub pos: uint,
272     pub len: uint
273 }
274
275 #[deriving(Copy)]
276 pub enum ast_ty_to_ty_cache_entry<'tcx> {
277     atttce_unresolved,  /* not resolved yet */
278     atttce_resolved(Ty<'tcx>)  /* resolved to a type, irrespective of region */
279 }
280
281 #[deriving(Clone, PartialEq, RustcDecodable, RustcEncodable)]
282 pub struct ItemVariances {
283     pub types: VecPerParamSpace<Variance>,
284     pub regions: VecPerParamSpace<Variance>,
285 }
286
287 #[deriving(Clone, PartialEq, RustcDecodable, RustcEncodable, Show, Copy)]
288 pub enum Variance {
289     Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
290     Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
291     Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
292     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
293 }
294
295 #[deriving(Clone, Show)]
296 pub enum AutoAdjustment<'tcx> {
297     AdjustAddEnv(ast::DefId, ty::TraitStore),
298     AdjustReifyFnPointer(ast::DefId), // go from a fn-item type to a fn-pointer type
299     AdjustDerefRef(AutoDerefRef<'tcx>)
300 }
301
302 #[deriving(Clone, PartialEq, Show)]
303 pub enum UnsizeKind<'tcx> {
304     // [T, ..n] -> [T], the uint field is n.
305     UnsizeLength(uint),
306     // An unsize coercion applied to the tail field of a struct.
307     // The uint is the index of the type parameter which is unsized.
308     UnsizeStruct(Box<UnsizeKind<'tcx>>, uint),
309     UnsizeVtable(TyTrait<'tcx>, /* the self type of the trait */ Ty<'tcx>)
310 }
311
312 #[deriving(Clone, Show)]
313 pub struct AutoDerefRef<'tcx> {
314     pub autoderefs: uint,
315     pub autoref: Option<AutoRef<'tcx>>
316 }
317
318 #[deriving(Clone, PartialEq, Show)]
319 pub enum AutoRef<'tcx> {
320     /// Convert from T to &T
321     /// The third field allows us to wrap other AutoRef adjustments.
322     AutoPtr(Region, ast::Mutability, Option<Box<AutoRef<'tcx>>>),
323
324     /// Convert [T, ..n] to [T] (or similar, depending on the kind)
325     AutoUnsize(UnsizeKind<'tcx>),
326
327     /// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
328     /// With DST and Box a library type, this should be replaced by UnsizeStruct.
329     AutoUnsizeUniq(UnsizeKind<'tcx>),
330
331     /// Convert from T to *T
332     /// Value to thin pointer
333     /// The second field allows us to wrap other AutoRef adjustments.
334     AutoUnsafe(ast::Mutability, Option<Box<AutoRef<'tcx>>>),
335 }
336
337 // Ugly little helper function. The first bool in the returned tuple is true if
338 // there is an 'unsize to trait object' adjustment at the bottom of the
339 // adjustment. If that is surrounded by an AutoPtr, then we also return the
340 // region of the AutoPtr (in the third argument). The second bool is true if the
341 // adjustment is unique.
342 fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
343     fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
344         match k {
345             &UnsizeVtable(..) => true,
346             &UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
347             _ => false
348         }
349     }
350
351     match autoref {
352         &AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
353         &AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
354         &AutoPtr(adj_r, _, Some(box ref autoref)) => {
355             let (b, u, r) = autoref_object_region(autoref);
356             if r.is_some() || u {
357                 (b, u, r)
358             } else {
359                 (b, u, Some(adj_r))
360             }
361         }
362         &AutoUnsafe(_, Some(box ref autoref)) => autoref_object_region(autoref),
363         _ => (false, false, None)
364     }
365 }
366
367 // If the adjustment introduces a borrowed reference to a trait object, then
368 // returns the region of the borrowed reference.
369 pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
370     match adj {
371         &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
372             let (b, _, r) = autoref_object_region(autoref);
373             if b {
374                 r
375             } else {
376                 None
377             }
378         }
379         _ => None
380     }
381 }
382
383 // Returns true if there is a trait cast at the bottom of the adjustment.
384 pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
385     match adj {
386         &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
387             let (b, _, _) = autoref_object_region(autoref);
388             b
389         }
390         _ => false
391     }
392 }
393
394 // If possible, returns the type expected from the given adjustment. This is not
395 // possible if the adjustment depends on the type of the adjusted expression.
396 pub fn type_of_adjust<'tcx>(cx: &ctxt<'tcx>, adj: &AutoAdjustment<'tcx>) -> Option<Ty<'tcx>> {
397     fn type_of_autoref<'tcx>(cx: &ctxt<'tcx>, autoref: &AutoRef<'tcx>) -> Option<Ty<'tcx>> {
398         match autoref {
399             &AutoUnsize(ref k) => match k {
400                 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
401                     Some(mk_trait(cx, principal.clone(), bounds.clone()))
402                 }
403                 _ => None
404             },
405             &AutoUnsizeUniq(ref k) => match k {
406                 &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
407                     Some(mk_uniq(cx, mk_trait(cx, principal.clone(), bounds.clone())))
408                 }
409                 _ => None
410             },
411             &AutoPtr(r, m, Some(box ref autoref)) => {
412                 match type_of_autoref(cx, autoref) {
413                     Some(ty) => Some(mk_rptr(cx, cx.mk_region(r), mt {mutbl: m, ty: ty})),
414                     None => None
415                 }
416             }
417             &AutoUnsafe(m, Some(box ref autoref)) => {
418                 match type_of_autoref(cx, autoref) {
419                     Some(ty) => Some(mk_ptr(cx, mt {mutbl: m, ty: ty})),
420                     None => None
421                 }
422             }
423             _ => None
424         }
425     }
426
427     match adj {
428         &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
429             type_of_autoref(cx, autoref)
430         }
431         _ => None
432     }
433 }
434
435 #[deriving(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Show)]
436 pub struct param_index {
437     pub space: subst::ParamSpace,
438     pub index: uint
439 }
440
441 #[deriving(Clone, Show)]
442 pub enum MethodOrigin<'tcx> {
443     // fully statically resolved method
444     MethodStatic(ast::DefId),
445
446     // fully statically resolved unboxed closure invocation
447     MethodStaticUnboxedClosure(ast::DefId),
448
449     // method invoked on a type parameter with a bounded trait
450     MethodTypeParam(MethodParam<'tcx>),
451
452     // method invoked on a trait instance
453     MethodTraitObject(MethodObject<'tcx>),
454
455 }
456
457 // details for a method invoked with a receiver whose type is a type parameter
458 // with a bounded trait.
459 #[deriving(Clone, Show)]
460 pub struct MethodParam<'tcx> {
461     // the precise trait reference that occurs as a bound -- this may
462     // be a supertrait of what the user actually typed. Note that it
463     // never contains bound regions; those regions should have been
464     // instantiated with fresh variables at this point.
465     pub trait_ref: Rc<ty::TraitRef<'tcx>>,
466
467     // index of uint in the list of methods for the trait
468     pub method_num: uint,
469 }
470
471 // details for a method invoked with a receiver whose type is an object
472 #[deriving(Clone, Show)]
473 pub struct MethodObject<'tcx> {
474     // the (super)trait containing the method to be invoked
475     pub trait_ref: Rc<ty::TraitRef<'tcx>>,
476
477     // the actual base trait id of the object
478     pub object_trait_id: ast::DefId,
479
480     // index of the method to be invoked amongst the trait's methods
481     pub method_num: uint,
482
483     // index into the actual runtime vtable.
484     // the vtable is formed by concatenating together the method lists of
485     // the base object trait and all supertraits;  this is the index into
486     // that vtable
487     pub real_index: uint,
488 }
489
490 #[deriving(Clone)]
491 pub struct MethodCallee<'tcx> {
492     pub origin: MethodOrigin<'tcx>,
493     pub ty: Ty<'tcx>,
494     pub substs: subst::Substs<'tcx>
495 }
496
497 /// With method calls, we store some extra information in
498 /// side tables (i.e method_map). We use
499 /// MethodCall as a key to index into these tables instead of
500 /// just directly using the expression's NodeId. The reason
501 /// for this being that we may apply adjustments (coercions)
502 /// with the resulting expression also needing to use the
503 /// side tables. The problem with this is that we don't
504 /// assign a separate NodeId to this new expression
505 /// and so it would clash with the base expression if both
506 /// needed to add to the side tables. Thus to disambiguate
507 /// we also keep track of whether there's an adjustment in
508 /// our key.
509 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
510 pub struct MethodCall {
511     pub expr_id: ast::NodeId,
512     pub adjustment: ExprAdjustment
513 }
514
515 #[deriving(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
516 pub enum ExprAdjustment {
517     NoAdjustment,
518     AutoDeref(uint),
519     AutoObject
520 }
521
522 impl MethodCall {
523     pub fn expr(id: ast::NodeId) -> MethodCall {
524         MethodCall {
525             expr_id: id,
526             adjustment: NoAdjustment
527         }
528     }
529
530     pub fn autoobject(id: ast::NodeId) -> MethodCall {
531         MethodCall {
532             expr_id: id,
533             adjustment: AutoObject
534         }
535     }
536
537     pub fn autoderef(expr_id: ast::NodeId, autoderef: uint) -> MethodCall {
538         MethodCall {
539             expr_id: expr_id,
540             adjustment: AutoDeref(1 + autoderef)
541         }
542     }
543 }
544
545 // maps from an expression id that corresponds to a method call to the details
546 // of the method to be invoked
547 pub type MethodMap<'tcx> = RefCell<FnvHashMap<MethodCall, MethodCallee<'tcx>>>;
548
549 pub type vtable_param_res<'tcx> = Vec<vtable_origin<'tcx>>;
550
551 // Resolutions for bounds of all parameters, left to right, for a given path.
552 pub type vtable_res<'tcx> = VecPerParamSpace<vtable_param_res<'tcx>>;
553
554 #[deriving(Clone)]
555 pub enum vtable_origin<'tcx> {
556     /*
557       Statically known vtable. def_id gives the impl item
558       from whence comes the vtable, and tys are the type substs.
559       vtable_res is the vtable itself.
560      */
561     vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>),
562
563     /*
564       Dynamic vtable, comes from a parameter that has a bound on it:
565       fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a
566       vtable_param origin
567
568       The first argument is the param index (identifying T in the example),
569       and the second is the bound number (identifying baz)
570      */
571     vtable_param(param_index, uint),
572
573     /*
574       Vtable automatically generated for an unboxed closure. The def ID is the
575       ID of the closure expression.
576      */
577     vtable_unboxed_closure(ast::DefId),
578
579     /*
580       Asked to determine the vtable for ty_err. This is the value used
581       for the vtables of `Self` in a virtual call like `foo.bar()`
582       where `foo` is of object type. The same value is also used when
583       type errors occur.
584      */
585     vtable_error,
586 }
587
588
589 // For every explicit cast into an object type, maps from the cast
590 // expr to the associated trait ref.
591 pub type ObjectCastMap<'tcx> = RefCell<NodeMap<ty::PolyTraitRef<'tcx>>>;
592
593 /// A restriction that certain types must be the same size. The use of
594 /// `transmute` gives rise to these restrictions. These generally
595 /// cannot be checked until trans; therefore, each call to `transmute`
596 /// will push one or more such restriction into the
597 /// `transmute_restrictions` vector during `intrinsicck`. They are
598 /// then checked during `trans` by the fn `check_intrinsics`.
599 #[deriving(Copy)]
600 pub struct TransmuteRestriction<'tcx> {
601     /// The span whence the restriction comes.
602     pub span: Span,
603
604     /// The type being transmuted from.
605     pub original_from: Ty<'tcx>,
606
607     /// The type being transmuted to.
608     pub original_to: Ty<'tcx>,
609
610     /// The type being transmuted from, with all type parameters
611     /// substituted for an arbitrary representative. Not to be shown
612     /// to the end user.
613     pub substituted_from: Ty<'tcx>,
614
615     /// The type being transmuted to, with all type parameters
616     /// substituted for an arbitrary representative. Not to be shown
617     /// to the end user.
618     pub substituted_to: Ty<'tcx>,
619
620     /// NodeId of the transmute intrinsic.
621     pub id: ast::NodeId,
622 }
623
624 /// Internal storage
625 pub struct CtxtArenas<'tcx> {
626     type_: TypedArena<TyS<'tcx>>,
627     substs: TypedArena<Substs<'tcx>>,
628     bare_fn: TypedArena<BareFnTy<'tcx>>,
629     region: TypedArena<Region>,
630 }
631
632 impl<'tcx> CtxtArenas<'tcx> {
633     pub fn new() -> CtxtArenas<'tcx> {
634         CtxtArenas {
635             type_: TypedArena::new(),
636             substs: TypedArena::new(),
637             bare_fn: TypedArena::new(),
638             region: TypedArena::new(),
639         }
640     }
641 }
642
643 pub struct CommonTypes<'tcx> {
644     pub bool: Ty<'tcx>,
645     pub char: Ty<'tcx>,
646     pub int: Ty<'tcx>,
647     pub i8: Ty<'tcx>,
648     pub i16: Ty<'tcx>,
649     pub i32: Ty<'tcx>,
650     pub i64: Ty<'tcx>,
651     pub uint: Ty<'tcx>,
652     pub u8: Ty<'tcx>,
653     pub u16: Ty<'tcx>,
654     pub u32: Ty<'tcx>,
655     pub u64: Ty<'tcx>,
656     pub f32: Ty<'tcx>,
657     pub f64: Ty<'tcx>,
658     pub err: Ty<'tcx>,
659 }
660
661 /// The data structure to keep track of all the information that typechecker
662 /// generates so that so that it can be reused and doesn't have to be redone
663 /// later on.
664 pub struct ctxt<'tcx> {
665     /// The arenas that types etc are allocated from.
666     arenas: &'tcx CtxtArenas<'tcx>,
667
668     /// Specifically use a speedy hash algorithm for this hash map, it's used
669     /// quite often.
670     // FIXME(eddyb) use a FnvHashSet<InternedTy<'tcx>> when equivalent keys can
671     // queried from a HashSet.
672     interner: RefCell<FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>>,
673
674     // FIXME as above, use a hashset if equivalent elements can be queried.
675     substs_interner: RefCell<FnvHashMap<&'tcx Substs<'tcx>, &'tcx Substs<'tcx>>>,
676     bare_fn_interner: RefCell<FnvHashMap<&'tcx BareFnTy<'tcx>, &'tcx BareFnTy<'tcx>>>,
677     region_interner: RefCell<FnvHashMap<&'tcx Region, &'tcx Region>>,
678
679     /// Common types, pre-interned for your convenience.
680     pub types: CommonTypes<'tcx>,
681
682     pub sess: Session,
683     pub def_map: DefMap,
684
685     pub named_region_map: resolve_lifetime::NamedRegionMap,
686
687     pub region_maps: middle::region::RegionMaps,
688
689     /// Stores the types for various nodes in the AST.  Note that this table
690     /// is not guaranteed to be populated until after typeck.  See
691     /// typeck::check::fn_ctxt for details.
692     pub node_types: RefCell<NodeMap<Ty<'tcx>>>,
693
694     /// Stores the type parameters which were substituted to obtain the type
695     /// of this node.  This only applies to nodes that refer to entities
696     /// parameterized by type parameters, such as generic fns, types, or
697     /// other items.
698     pub item_substs: RefCell<NodeMap<ItemSubsts<'tcx>>>,
699
700     /// Maps from a trait item to the trait item "descriptor"
701     pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem<'tcx>>>,
702
703     /// Maps from a trait def-id to a list of the def-ids of its trait items
704     pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
705
706     /// A cache for the trait_items() routine
707     pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem<'tcx>>>>>,
708
709     pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef<'tcx>>>>>,
710
711     pub trait_refs: RefCell<NodeMap<Rc<TraitRef<'tcx>>>>,
712     pub trait_defs: RefCell<DefIdMap<Rc<TraitDef<'tcx>>>>,
713
714     /// Maps from node-id of a trait object cast (like `foo as
715     /// Box<Trait>`) to the trait reference.
716     pub object_cast_map: ObjectCastMap<'tcx>,
717
718     pub map: ast_map::Map<'tcx>,
719     pub intrinsic_defs: RefCell<DefIdMap<Ty<'tcx>>>,
720     pub freevars: RefCell<FreevarMap>,
721     pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
722     pub rcache: RefCell<FnvHashMap<creader_cache_key, Ty<'tcx>>>,
723     pub short_names_cache: RefCell<FnvHashMap<Ty<'tcx>, String>>,
724     pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
725     pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry<'tcx>>>,
726     pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo<'tcx>>>>>>,
727     pub ty_param_defs: RefCell<NodeMap<TypeParameterDef<'tcx>>>,
728     pub adjustments: RefCell<NodeMap<AutoAdjustment<'tcx>>>,
729     pub normalized_cache: RefCell<FnvHashMap<Ty<'tcx>, Ty<'tcx>>>,
730     pub lang_items: middle::lang_items::LanguageItems,
731     /// A mapping of fake provided method def_ids to the default implementation
732     pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
733     pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
734
735     /// Maps from def-id of a type or region parameter to its
736     /// (inferred) variance.
737     pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
738
739     /// True if the variance has been computed yet; false otherwise.
740     pub variance_computed: Cell<bool>,
741
742     /// A mapping from the def ID of an enum or struct type to the def ID
743     /// of the method that implements its destructor. If the type is not
744     /// present in this map, it does not have a destructor. This map is
745     /// populated during the coherence phase of typechecking.
746     pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
747
748     /// A method will be in this list if and only if it is a destructor.
749     pub destructors: RefCell<DefIdSet>,
750
751     /// Maps a trait onto a list of impls of that trait.
752     pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
753
754     /// Maps a DefId of a type to a list of its inherent impls.
755     /// Contains implementations of methods that are inherent to a type.
756     /// Methods in these implementations don't need to be exported.
757     pub inherent_impls: RefCell<DefIdMap<Rc<Vec<ast::DefId>>>>,
758
759     /// Maps a DefId of an impl to a list of its items.
760     /// Note that this contains all of the impls that we know about,
761     /// including ones in other crates. It's not clear that this is the best
762     /// way to do it.
763     pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
764
765     /// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
766     /// present in this set can be warned about.
767     pub used_unsafe: RefCell<NodeSet>,
768
769     /// Set of nodes which mark locals as mutable which end up getting used at
770     /// some point. Local variable definitions not in this set can be warned
771     /// about.
772     pub used_mut_nodes: RefCell<NodeSet>,
773
774     /// The set of external nominal types whose implementations have been read.
775     /// This is used for lazy resolution of methods.
776     pub populated_external_types: RefCell<DefIdSet>,
777
778     /// The set of external traits whose implementations have been read. This
779     /// is used for lazy resolution of traits.
780     pub populated_external_traits: RefCell<DefIdSet>,
781
782     /// Borrows
783     pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
784
785     /// These two caches are used by const_eval when decoding external statics
786     /// and variants that are found.
787     pub extern_const_statics: RefCell<DefIdMap<ast::NodeId>>,
788     pub extern_const_variants: RefCell<DefIdMap<ast::NodeId>>,
789
790     pub method_map: MethodMap<'tcx>,
791
792     pub dependency_formats: RefCell<dependency_format::Dependencies>,
793
794     /// Records the type of each unboxed closure. The def ID is the ID of the
795     /// expression defining the unboxed closure.
796     pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure<'tcx>>>,
797
798     pub node_lint_levels: RefCell<FnvHashMap<(ast::NodeId, lint::LintId),
799                                               lint::LevelSource>>,
800
801     /// The types that must be asserted to be the same size for `transmute`
802     /// to be valid. We gather up these restrictions in the intrinsicck pass
803     /// and check them in trans.
804     pub transmute_restrictions: RefCell<Vec<TransmuteRestriction<'tcx>>>,
805
806     /// Maps any item's def-id to its stability index.
807     pub stability: RefCell<stability::Index>,
808
809     /// Maps closures to their capture clauses.
810     pub capture_modes: RefCell<CaptureModeMap>,
811
812     /// Maps def IDs to true if and only if they're associated types.
813     pub associated_types: RefCell<DefIdMap<bool>>,
814
815     /// Caches the results of trait selection. This cache is used
816     /// for things that do not have to do with the parameters in scope.
817     pub selection_cache: traits::SelectionCache<'tcx>,
818
819     /// Caches the representation hints for struct definitions.
820     pub repr_hint_cache: RefCell<DefIdMap<Rc<Vec<attr::ReprAttr>>>>,
821
822     /// Caches whether types are known to impl Copy. Note that type
823     /// parameters are never placed into this cache, because their
824     /// results are dependent on the parameter environment.
825     pub type_impls_copy_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
826
827     /// Caches whether types are known to impl Sized. Note that type
828     /// parameters are never placed into this cache, because their
829     /// results are dependent on the parameter environment.
830     pub type_impls_sized_cache: RefCell<HashMap<Ty<'tcx>,bool>>,
831
832     /// Caches whether traits are object safe
833     pub object_safety_cache: RefCell<DefIdMap<bool>>,
834 }
835
836 // Flags that we track on types. These flags are propagated upwards
837 // through the type during type construction, so that we can quickly
838 // check whether the type has various kinds of types in it without
839 // recursing over the type itself.
840 bitflags! {
841     flags TypeFlags: u32 {
842         const NO_TYPE_FLAGS       = 0b0,
843         const HAS_PARAMS          = 0b1,
844         const HAS_SELF            = 0b10,
845         const HAS_TY_INFER        = 0b100,
846         const HAS_RE_INFER        = 0b1000,
847         const HAS_RE_LATE_BOUND   = 0b10000,
848         const HAS_REGIONS         = 0b100000,
849         const HAS_TY_ERR          = 0b1000000,
850         const HAS_PROJECTION      = 0b10000000,
851         const NEEDS_SUBST   = HAS_PARAMS.bits | HAS_SELF.bits | HAS_REGIONS.bits,
852     }
853 }
854
855 macro_rules! sty_debug_print {
856     ($ctxt: expr, $($variant: ident),*) => {{
857         // curious inner module to allow variant names to be used as
858         // variable names.
859         mod inner {
860             use middle::ty;
861             #[deriving(Copy)]
862             struct DebugStat {
863                 total: uint,
864                 region_infer: uint,
865                 ty_infer: uint,
866                 both_infer: uint,
867             }
868
869             pub fn go(tcx: &ty::ctxt) {
870                 let mut total = DebugStat {
871                     total: 0,
872                     region_infer: 0, ty_infer: 0, both_infer: 0,
873                 };
874                 $(let mut $variant = total;)*
875
876
877                 for (_, t) in tcx.interner.borrow().iter() {
878                     let variant = match t.sty {
879                         ty::ty_bool | ty::ty_char | ty::ty_int(..) | ty::ty_uint(..) |
880                             ty::ty_float(..) | ty::ty_str => continue,
881                         ty::ty_err => /* unimportant */ continue,
882                         $(ty::$variant(..) => &mut $variant,)*
883                     };
884                     let region = t.flags.intersects(ty::HAS_RE_INFER);
885                     let ty = t.flags.intersects(ty::HAS_TY_INFER);
886
887                     variant.total += 1;
888                     total.total += 1;
889                     if region { total.region_infer += 1; variant.region_infer += 1 }
890                     if ty { total.ty_infer += 1; variant.ty_infer += 1 }
891                     if region && ty { total.both_infer += 1; variant.both_infer += 1 }
892                 }
893                 println!("Ty interner             total           ty region  both");
894                 $(println!("    {:18}: {uses:6} {usespc:4.1}%, \
895 {ty:4.1}% {region:5.1}% {both:4.1}%",
896                            stringify!($variant),
897                            uses = $variant.total,
898                            usespc = $variant.total as f64 * 100.0 / total.total as f64,
899                            ty = $variant.ty_infer as f64 * 100.0  / total.total as f64,
900                            region = $variant.region_infer as f64 * 100.0  / total.total as f64,
901                            both = $variant.both_infer as f64 * 100.0  / total.total as f64);
902                   )*
903                 println!("                  total {uses:6}        \
904 {ty:4.1}% {region:5.1}% {both:4.1}%",
905                          uses = total.total,
906                          ty = total.ty_infer as f64 * 100.0  / total.total as f64,
907                          region = total.region_infer as f64 * 100.0  / total.total as f64,
908                          both = total.both_infer as f64 * 100.0  / total.total as f64)
909             }
910         }
911
912         inner::go($ctxt)
913     }}
914 }
915
916 impl<'tcx> ctxt<'tcx> {
917     pub fn print_debug_stats(&self) {
918         sty_debug_print!(
919             self,
920             ty_enum, ty_uniq, ty_vec, ty_ptr, ty_rptr, ty_bare_fn, ty_closure, ty_trait,
921             ty_struct, ty_unboxed_closure, ty_tup, ty_param, ty_open, ty_infer, ty_projection);
922
923         println!("Substs interner: #{}", self.substs_interner.borrow().len());
924         println!("BareFnTy interner: #{}", self.bare_fn_interner.borrow().len());
925         println!("Region interner: #{}", self.region_interner.borrow().len());
926     }
927 }
928
929 #[deriving(Show)]
930 pub struct TyS<'tcx> {
931     pub sty: sty<'tcx>,
932     pub flags: TypeFlags,
933
934     // the maximal depth of any bound regions appearing in this type.
935     region_depth: u32,
936 }
937
938 impl fmt::Show for TypeFlags {
939     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
940         write!(f, "{}", self.bits)
941     }
942 }
943
944 impl<'tcx> PartialEq for TyS<'tcx> {
945     fn eq(&self, other: &TyS<'tcx>) -> bool {
946         (self as *const _) == (other as *const _)
947     }
948 }
949 impl<'tcx> Eq for TyS<'tcx> {}
950
951 impl<'tcx, S: Writer> Hash<S> for TyS<'tcx> {
952     fn hash(&self, s: &mut S) {
953         (self as *const _).hash(s)
954     }
955 }
956
957 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
958
959 /// An entry in the type interner.
960 pub struct InternedTy<'tcx> {
961     ty: Ty<'tcx>
962 }
963
964 // NB: An InternedTy compares and hashes as a sty.
965 impl<'tcx> PartialEq for InternedTy<'tcx> {
966     fn eq(&self, other: &InternedTy<'tcx>) -> bool {
967         self.ty.sty == other.ty.sty
968     }
969 }
970
971 impl<'tcx> Eq for InternedTy<'tcx> {}
972
973 impl<'tcx, S: Writer> Hash<S> for InternedTy<'tcx> {
974     fn hash(&self, s: &mut S) {
975         self.ty.sty.hash(s)
976     }
977 }
978
979 impl<'tcx> BorrowFrom<InternedTy<'tcx>> for sty<'tcx> {
980     fn borrow_from<'a>(ty: &'a InternedTy<'tcx>) -> &'a sty<'tcx> {
981         &ty.ty.sty
982     }
983 }
984
985 pub fn type_has_params(ty: Ty) -> bool {
986     ty.flags.intersects(HAS_PARAMS)
987 }
988 pub fn type_has_self(ty: Ty) -> bool {
989     ty.flags.intersects(HAS_SELF)
990 }
991 pub fn type_has_ty_infer(ty: Ty) -> bool {
992     ty.flags.intersects(HAS_TY_INFER)
993 }
994 pub fn type_needs_infer(ty: Ty) -> bool {
995     ty.flags.intersects(HAS_TY_INFER | HAS_RE_INFER)
996 }
997 pub fn type_has_projection(ty: Ty) -> bool {
998     ty.flags.intersects(HAS_PROJECTION)
999 }
1000
1001 pub fn type_has_late_bound_regions(ty: Ty) -> bool {
1002     ty.flags.intersects(HAS_RE_LATE_BOUND)
1003 }
1004
1005 /// An "escaping region" is a bound region whose binder is not part of `t`.
1006 ///
1007 /// So, for example, consider a type like the following, which has two binders:
1008 ///
1009 ///    for<'a> fn(x: for<'b> fn(&'a int, &'b int))
1010 ///    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ outer scope
1011 ///                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~  inner scope
1012 ///
1013 /// This type has *bound regions* (`'a`, `'b`), but it does not have escaping regions, because the
1014 /// binders of both `'a` and `'b` are part of the type itself. However, if we consider the *inner
1015 /// fn type*, that type has an escaping region: `'a`.
1016 ///
1017 /// Note that what I'm calling an "escaping region" is often just called a "free region". However,
1018 /// we already use the term "free region". It refers to the regions that we use to represent bound
1019 /// regions on a fn definition while we are typechecking its body.
1020 ///
1021 /// To clarify, conceptually there is no particular difference between an "escaping" region and a
1022 /// "free" region. However, there is a big difference in practice. Basically, when "entering" a
1023 /// binding level, one is generally required to do some sort of processing to a bound region, such
1024 /// as replacing it with a fresh/skolemized region, or making an entry in the environment to
1025 /// represent the scope to which it is attached, etc. An escaping region represents a bound region
1026 /// for which this processing has not yet been done.
1027 pub fn type_has_escaping_regions(ty: Ty) -> bool {
1028     type_escapes_depth(ty, 0)
1029 }
1030
1031 pub fn type_escapes_depth(ty: Ty, depth: u32) -> bool {
1032     ty.region_depth > depth
1033 }
1034
1035 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1036 pub struct BareFnTy<'tcx> {
1037     pub unsafety: ast::Unsafety,
1038     pub abi: abi::Abi,
1039     pub sig: PolyFnSig<'tcx>,
1040 }
1041
1042 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1043 pub struct ClosureTy<'tcx> {
1044     pub unsafety: ast::Unsafety,
1045     pub onceness: ast::Onceness,
1046     pub store: TraitStore,
1047     pub bounds: ExistentialBounds<'tcx>,
1048     pub sig: PolyFnSig<'tcx>,
1049     pub abi: abi::Abi,
1050 }
1051
1052 #[deriving(Clone, Copy, PartialEq, Eq, Hash)]
1053 pub enum FnOutput<'tcx> {
1054     FnConverging(Ty<'tcx>),
1055     FnDiverging
1056 }
1057
1058 impl<'tcx> FnOutput<'tcx> {
1059     pub fn unwrap(self) -> Ty<'tcx> {
1060         match self {
1061             ty::FnConverging(t) => t,
1062             ty::FnDiverging => unreachable!()
1063         }
1064     }
1065 }
1066
1067 /// Signature of a function type, which I have arbitrarily
1068 /// decided to use to refer to the input/output types.
1069 ///
1070 /// - `inputs` is the list of arguments and their modes.
1071 /// - `output` is the return type.
1072 /// - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
1073 #[deriving(Clone, PartialEq, Eq, Hash)]
1074 pub struct FnSig<'tcx> {
1075     pub inputs: Vec<Ty<'tcx>>,
1076     pub output: FnOutput<'tcx>,
1077     pub variadic: bool
1078 }
1079
1080 pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
1081
1082 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
1083 pub struct ParamTy {
1084     pub space: subst::ParamSpace,
1085     pub idx: u32,
1086     pub name: ast::Name,
1087 }
1088
1089 /// A [De Bruijn index][dbi] is a standard means of representing
1090 /// regions (and perhaps later types) in a higher-ranked setting. In
1091 /// particular, imagine a type like this:
1092 ///
1093 ///     for<'a> fn(for<'b> fn(&'b int, &'a int), &'a char)
1094 ///     ^          ^            |        |         |
1095 ///     |          |            |        |         |
1096 ///     |          +------------+ 1      |         |
1097 ///     |                                |         |
1098 ///     +--------------------------------+ 2       |
1099 ///     |                                          |
1100 ///     +------------------------------------------+ 1
1101 ///
1102 /// In this type, there are two binders (the outer fn and the inner
1103 /// fn). We need to be able to determine, for any given region, which
1104 /// fn type it is bound by, the inner or the outer one. There are
1105 /// various ways you can do this, but a De Bruijn index is one of the
1106 /// more convenient and has some nice properties. The basic idea is to
1107 /// count the number of binders, inside out. Some examples should help
1108 /// clarify what I mean.
1109 ///
1110 /// Let's start with the reference type `&'b int` that is the first
1111 /// argument to the inner function. This region `'b` is assigned a De
1112 /// Bruijn index of 1, meaning "the innermost binder" (in this case, a
1113 /// fn). The region `'a` that appears in the second argument type (`&'a
1114 /// int`) would then be assigned a De Bruijn index of 2, meaning "the
1115 /// second-innermost binder". (These indices are written on the arrays
1116 /// in the diagram).
1117 ///
1118 /// What is interesting is that De Bruijn index attached to a particular
1119 /// variable will vary depending on where it appears. For example,
1120 /// the final type `&'a char` also refers to the region `'a` declared on
1121 /// the outermost fn. But this time, this reference is not nested within
1122 /// any other binders (i.e., it is not an argument to the inner fn, but
1123 /// rather the outer one). Therefore, in this case, it is assigned a
1124 /// De Bruijn index of 1, because the innermost binder in that location
1125 /// is the outer fn.
1126 ///
1127 /// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
1128 #[deriving(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
1129 pub struct DebruijnIndex {
1130     // We maintain the invariant that this is never 0. So 1 indicates
1131     // the innermost binder. To ensure this, create with `DebruijnIndex::new`.
1132     pub depth: u32,
1133 }
1134
1135 /// Representation of regions:
1136 #[deriving(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
1137 pub enum Region {
1138     // Region bound in a type or fn declaration which will be
1139     // substituted 'early' -- that is, at the same time when type
1140     // parameters are substituted.
1141     ReEarlyBound(/* param id */ ast::NodeId,
1142                  subst::ParamSpace,
1143                  /*index*/ u32,
1144                  ast::Name),
1145
1146     // Region bound in a function scope, which will be substituted when the
1147     // function is called.
1148     ReLateBound(DebruijnIndex, BoundRegion),
1149
1150     /// When checking a function body, the types of all arguments and so forth
1151     /// that refer to bound region parameters are modified to refer to free
1152     /// region parameters.
1153     ReFree(FreeRegion),
1154
1155     /// A concrete region naming some expression within the current function.
1156     ReScope(region::CodeExtent),
1157
1158     /// Static data that has an "infinite" lifetime. Top in the region lattice.
1159     ReStatic,
1160
1161     /// A region variable.  Should not exist after typeck.
1162     ReInfer(InferRegion),
1163
1164     /// Empty lifetime is for data that is never accessed.
1165     /// Bottom in the region lattice. We treat ReEmpty somewhat
1166     /// specially; at least right now, we do not generate instances of
1167     /// it during the GLB computations, but rather
1168     /// generate an error instead. This is to improve error messages.
1169     /// The only way to get an instance of ReEmpty is to have a region
1170     /// variable with no constraints.
1171     ReEmpty,
1172 }
1173
1174 /// Upvars do not get their own node-id. Instead, we use the pair of
1175 /// the original var id (that is, the root variable that is referenced
1176 /// by the upvar) and the id of the closure expression.
1177 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
1178 pub struct UpvarId {
1179     pub var_id: ast::NodeId,
1180     pub closure_expr_id: ast::NodeId,
1181 }
1182
1183 #[deriving(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
1184 pub enum BorrowKind {
1185     /// Data must be immutable and is aliasable.
1186     ImmBorrow,
1187
1188     /// Data must be immutable but not aliasable.  This kind of borrow
1189     /// cannot currently be expressed by the user and is used only in
1190     /// implicit closure bindings. It is needed when you the closure
1191     /// is borrowing or mutating a mutable referent, e.g.:
1192     ///
1193     ///    let x: &mut int = ...;
1194     ///    let y = || *x += 5;
1195     ///
1196     /// If we were to try to translate this closure into a more explicit
1197     /// form, we'd encounter an error with the code as written:
1198     ///
1199     ///    struct Env { x: & &mut int }
1200     ///    let x: &mut int = ...;
1201     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
1202     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
1203     ///
1204     /// This is then illegal because you cannot mutate a `&mut` found
1205     /// in an aliasable location. To solve, you'd have to translate with
1206     /// an `&mut` borrow:
1207     ///
1208     ///    struct Env { x: & &mut int }
1209     ///    let x: &mut int = ...;
1210     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
1211     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
1212     ///
1213     /// Now the assignment to `**env.x` is legal, but creating a
1214     /// mutable pointer to `x` is not because `x` is not mutable. We
1215     /// could fix this by declaring `x` as `let mut x`. This is ok in
1216     /// user code, if awkward, but extra weird for closures, since the
1217     /// borrow is hidden.
1218     ///
1219     /// So we introduce a "unique imm" borrow -- the referent is
1220     /// immutable, but not aliasable. This solves the problem. For
1221     /// simplicity, we don't give users the way to express this
1222     /// borrow, it's just used when translating closures.
1223     UniqueImmBorrow,
1224
1225     /// Data is mutable and not aliasable.
1226     MutBorrow
1227 }
1228
1229 /// Information describing the borrowing of an upvar. This is computed
1230 /// during `typeck`, specifically by `regionck`. The general idea is
1231 /// that the compiler analyses treat closures like:
1232 ///
1233 ///     let closure: &'e fn() = || {
1234 ///        x = 1;   // upvar x is assigned to
1235 ///        use(y);  // upvar y is read
1236 ///        foo(&z); // upvar z is borrowed immutably
1237 ///     };
1238 ///
1239 /// as if they were "desugared" to something loosely like:
1240 ///
1241 ///     struct Vars<'x,'y,'z> { x: &'x mut int,
1242 ///                             y: &'y const int,
1243 ///                             z: &'z int }
1244 ///     let closure: &'e fn() = {
1245 ///         fn f(env: &Vars) {
1246 ///             *env.x = 1;
1247 ///             use(*env.y);
1248 ///             foo(env.z);
1249 ///         }
1250 ///         let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
1251 ///                                                       y: &'y const y,
1252 ///                                                       z: &'z z };
1253 ///         (env, f)
1254 ///     };
1255 ///
1256 /// This is basically what happens at runtime. The closure is basically
1257 /// an existentially quantified version of the `(env, f)` pair.
1258 ///
1259 /// This data structure indicates the region and mutability of a single
1260 /// one of the `x...z` borrows.
1261 ///
1262 /// It may not be obvious why each borrowed variable gets its own
1263 /// lifetime (in the desugared version of the example, these are indicated
1264 /// by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
1265 /// Each such lifetime must encompass the lifetime `'e` of the closure itself,
1266 /// but need not be identical to it. The reason that this makes sense:
1267 ///
1268 /// - Callers are only permitted to invoke the closure, and hence to
1269 ///   use the pointers, within the lifetime `'e`, so clearly `'e` must
1270 ///   be a sublifetime of `'x...'z`.
1271 /// - The closure creator knows which upvars were borrowed by the closure
1272 ///   and thus `x...z` will be reserved for `'x...'z` respectively.
1273 /// - Through mutation, the borrowed upvars can actually escape
1274 ///   the closure, so sometimes it is necessary for them to be larger
1275 ///   than the closure lifetime itself.
1276 #[deriving(PartialEq, Clone, RustcEncodable, RustcDecodable, Show, Copy)]
1277 pub struct UpvarBorrow {
1278     pub kind: BorrowKind,
1279     pub region: ty::Region,
1280 }
1281
1282 pub type UpvarBorrowMap = FnvHashMap<UpvarId, UpvarBorrow>;
1283
1284 impl Region {
1285     pub fn is_bound(&self) -> bool {
1286         match *self {
1287             ty::ReEarlyBound(..) => true,
1288             ty::ReLateBound(..) => true,
1289             _ => false
1290         }
1291     }
1292
1293     pub fn escapes_depth(&self, depth: u32) -> bool {
1294         match *self {
1295             ty::ReLateBound(debruijn, _) => debruijn.depth > depth,
1296             _ => false,
1297         }
1298     }
1299 }
1300
1301 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1302            RustcEncodable, RustcDecodable, Show, Copy)]
1303 /// A "free" region `fr` can be interpreted as "some region
1304 /// at least as big as the scope `fr.scope`".
1305 pub struct FreeRegion {
1306     pub scope: region::CodeExtent,
1307     pub bound_region: BoundRegion
1308 }
1309
1310 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
1311            RustcEncodable, RustcDecodable, Show, Copy)]
1312 pub enum BoundRegion {
1313     /// An anonymous region parameter for a given fn (&T)
1314     BrAnon(u32),
1315
1316     /// Named region parameters for functions (a in &'a T)
1317     ///
1318     /// The def-id is needed to distinguish free regions in
1319     /// the event of shadowing.
1320     BrNamed(ast::DefId, ast::Name),
1321
1322     /// Fresh bound identifiers created during GLB computations.
1323     BrFresh(u32),
1324
1325     // Anonymous region for the implicit env pointer parameter
1326     // to a closure
1327     BrEnv
1328 }
1329
1330 // NB: If you change this, you'll probably want to change the corresponding
1331 // AST structure in libsyntax/ast.rs as well.
1332 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1333 pub enum sty<'tcx> {
1334     ty_bool,
1335     ty_char,
1336     ty_int(ast::IntTy),
1337     ty_uint(ast::UintTy),
1338     ty_float(ast::FloatTy),
1339     /// Substs here, possibly against intuition, *may* contain `ty_param`s.
1340     /// That is, even after substitution it is possible that there are type
1341     /// variables. This happens when the `ty_enum` corresponds to an enum
1342     /// definition and not a concrete use of it. To get the correct `ty_enum`
1343     /// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
1344     /// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
1345     /// well.`
1346     ty_enum(DefId, &'tcx Substs<'tcx>),
1347     ty_uniq(Ty<'tcx>),
1348     ty_str,
1349     ty_vec(Ty<'tcx>, Option<uint>), // Second field is length.
1350     ty_ptr(mt<'tcx>),
1351     ty_rptr(&'tcx Region, mt<'tcx>),
1352
1353     // If the def-id is Some(_), then this is the type of a specific
1354     // fn item. Otherwise, if None(_), it a fn pointer type.
1355     ty_bare_fn(Option<DefId>, &'tcx BareFnTy<'tcx>),
1356
1357     ty_closure(Box<ClosureTy<'tcx>>),
1358     ty_trait(Box<TyTrait<'tcx>>),
1359     ty_struct(DefId, &'tcx Substs<'tcx>),
1360
1361     ty_unboxed_closure(DefId, &'tcx Region, &'tcx Substs<'tcx>),
1362
1363     ty_tup(Vec<Ty<'tcx>>),
1364
1365     ty_projection(ProjectionTy<'tcx>),
1366     ty_param(ParamTy), // type parameter
1367
1368     ty_open(Ty<'tcx>), // A deref'ed fat pointer, i.e., a dynamically sized value
1369                        // and its size. Only ever used in trans. It is not necessary
1370                        // earlier since we don't need to distinguish a DST with its
1371                        // size (e.g., in a deref) vs a DST with the size elsewhere (
1372                        // e.g., in a field).
1373
1374     ty_infer(InferTy), // something used only during inference/typeck
1375     ty_err, // Also only used during inference/typeck, to represent
1376             // the type of an erroneous expression (helps cut down
1377             // on non-useful type error messages)
1378 }
1379
1380 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1381 pub struct TyTrait<'tcx> {
1382     pub principal: ty::PolyTraitRef<'tcx>,
1383     pub bounds: ExistentialBounds<'tcx>,
1384 }
1385
1386 impl<'tcx> TyTrait<'tcx> {
1387     pub fn principal_def_id(&self) -> ast::DefId {
1388         self.principal.0.def_id
1389     }
1390
1391     /// Object types don't have a self-type specified. Therefore, when
1392     /// we convert the principal trait-ref into a normal trait-ref,
1393     /// you must give *some* self-type. A common choice is `mk_err()`
1394     /// or some skolemized type.
1395     pub fn principal_trait_ref_with_self_ty(&self,
1396                                             tcx: &ctxt<'tcx>,
1397                                             self_ty: Ty<'tcx>)
1398                                             -> ty::PolyTraitRef<'tcx>
1399     {
1400         // otherwise the escaping regions would be captured by the binder
1401         assert!(!self_ty.has_escaping_regions());
1402
1403         ty::Binder(Rc::new(ty::TraitRef {
1404             def_id: self.principal.0.def_id,
1405             substs: tcx.mk_substs(self.principal.0.substs.with_self_ty(self_ty)),
1406         }))
1407     }
1408
1409     pub fn projection_bounds_with_self_ty(&self,
1410                                           tcx: &ctxt<'tcx>,
1411                                           self_ty: Ty<'tcx>)
1412                                           -> Vec<ty::PolyProjectionPredicate<'tcx>>
1413     {
1414         // otherwise the escaping regions would be captured by the binders
1415         assert!(!self_ty.has_escaping_regions());
1416
1417         self.bounds.projection_bounds.iter()
1418             .map(|in_poly_projection_predicate| {
1419                 let in_projection_ty = &in_poly_projection_predicate.0.projection_ty;
1420                 let substs = tcx.mk_substs(in_projection_ty.trait_ref.substs.with_self_ty(self_ty));
1421                 let trait_ref =
1422                     Rc::new(ty::TraitRef::new(in_projection_ty.trait_ref.def_id,
1423                                               substs));
1424                 let projection_ty = ty::ProjectionTy {
1425                     trait_ref: trait_ref,
1426                     item_name: in_projection_ty.item_name
1427                 };
1428                 ty::Binder(ty::ProjectionPredicate {
1429                     projection_ty: projection_ty,
1430                     ty: in_poly_projection_predicate.0.ty
1431                 })
1432             })
1433             .collect()
1434     }
1435 }
1436
1437 /// A complete reference to a trait. These take numerous guises in syntax,
1438 /// but perhaps the most recognizable form is in a where clause:
1439 ///
1440 ///     T : Foo<U>
1441 ///
1442 /// This would be represented by a trait-reference where the def-id is the
1443 /// def-id for the trait `Foo` and the substs defines `T` as parameter 0 in the
1444 /// `SelfSpace` and `U` as parameter 0 in the `TypeSpace`.
1445 ///
1446 /// Trait references also appear in object types like `Foo<U>`, but in
1447 /// that case the `Self` parameter is absent from the substitutions.
1448 ///
1449 /// Note that a `TraitRef` introduces a level of region binding, to
1450 /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
1451 /// U>` or higher-ranked object types.
1452 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1453 pub struct TraitRef<'tcx> {
1454     pub def_id: DefId,
1455     pub substs: &'tcx Substs<'tcx>,
1456 }
1457
1458 pub type PolyTraitRef<'tcx> = Binder<Rc<TraitRef<'tcx>>>;
1459
1460 impl<'tcx> PolyTraitRef<'tcx> {
1461     pub fn self_ty(&self) -> Ty<'tcx> {
1462         self.0.self_ty()
1463     }
1464
1465     pub fn def_id(&self) -> ast::DefId {
1466         self.0.def_id
1467     }
1468
1469     pub fn substs(&self) -> &'tcx Substs<'tcx> {
1470         self.0.substs
1471     }
1472
1473     pub fn input_types(&self) -> &[Ty<'tcx>] {
1474         self.0.input_types()
1475     }
1476
1477     pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
1478         // Note that we preserve binding levels
1479         Binder(TraitPredicate { trait_ref: self.0.clone() })
1480     }
1481 }
1482
1483 /// Binder is a binder for higher-ranked lifetimes. It is part of the
1484 /// compiler's representation for things like `for<'a> Fn(&'a int)`
1485 /// (which would be represented by the type `PolyTraitRef ==
1486 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
1487 /// erase, or otherwise "discharge" these bound reons, we change the
1488 /// type from `Binder<T>` to just `T` (see
1489 /// e.g. `liberate_late_bound_regions`).
1490 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1491 pub struct Binder<T>(pub T);
1492
1493 #[deriving(Clone, Copy, PartialEq)]
1494 pub enum IntVarValue {
1495     IntType(ast::IntTy),
1496     UintType(ast::UintTy),
1497 }
1498
1499 #[deriving(Clone, Copy, Show)]
1500 pub enum terr_vstore_kind {
1501     terr_vec,
1502     terr_str,
1503     terr_fn,
1504     terr_trait
1505 }
1506
1507 #[deriving(Clone, Copy, Show)]
1508 pub struct expected_found<T> {
1509     pub expected: T,
1510     pub found: T
1511 }
1512
1513 // Data structures used in type unification
1514 #[deriving(Clone, Copy, Show)]
1515 pub enum type_err<'tcx> {
1516     terr_mismatch,
1517     terr_unsafety_mismatch(expected_found<ast::Unsafety>),
1518     terr_onceness_mismatch(expected_found<Onceness>),
1519     terr_abi_mismatch(expected_found<abi::Abi>),
1520     terr_mutability,
1521     terr_sigil_mismatch(expected_found<TraitStore>),
1522     terr_box_mutability,
1523     terr_ptr_mutability,
1524     terr_ref_mutability,
1525     terr_vec_mutability,
1526     terr_tuple_size(expected_found<uint>),
1527     terr_fixed_array_size(expected_found<uint>),
1528     terr_ty_param_size(expected_found<uint>),
1529     terr_arg_count,
1530     terr_regions_does_not_outlive(Region, Region),
1531     terr_regions_not_same(Region, Region),
1532     terr_regions_no_overlap(Region, Region),
1533     terr_regions_insufficiently_polymorphic(BoundRegion, Region),
1534     terr_regions_overly_polymorphic(BoundRegion, Region),
1535     terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
1536     terr_sorts(expected_found<Ty<'tcx>>),
1537     terr_integer_as_char,
1538     terr_int_mismatch(expected_found<IntVarValue>),
1539     terr_float_mismatch(expected_found<ast::FloatTy>),
1540     terr_traits(expected_found<ast::DefId>),
1541     terr_builtin_bounds(expected_found<BuiltinBounds>),
1542     terr_variadic_mismatch(expected_found<bool>),
1543     terr_cyclic_ty,
1544     terr_convergence_mismatch(expected_found<bool>),
1545     terr_projection_name_mismatched(expected_found<ast::Name>),
1546     terr_projection_bounds_length(expected_found<uint>),
1547 }
1548
1549 /// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
1550 /// as well as the existential type parameter in an object type.
1551 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1552 pub struct ParamBounds<'tcx> {
1553     pub region_bounds: Vec<ty::Region>,
1554     pub builtin_bounds: BuiltinBounds,
1555     pub trait_bounds: Vec<PolyTraitRef<'tcx>>,
1556     pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1557 }
1558
1559 /// Bounds suitable for an existentially quantified type parameter
1560 /// such as those that appear in object types or closure types. The
1561 /// major difference between this case and `ParamBounds` is that
1562 /// general purpose trait bounds are omitted and there must be
1563 /// *exactly one* region.
1564 #[deriving(PartialEq, Eq, Hash, Clone, Show)]
1565 pub struct ExistentialBounds<'tcx> {
1566     pub region_bound: ty::Region,
1567     pub builtin_bounds: BuiltinBounds,
1568     pub projection_bounds: Vec<PolyProjectionPredicate<'tcx>>,
1569 }
1570
1571 pub type BuiltinBounds = EnumSet<BuiltinBound>;
1572
1573 #[deriving(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
1574            Show, Copy)]
1575 #[repr(uint)]
1576 pub enum BuiltinBound {
1577     BoundSend,
1578     BoundSized,
1579     BoundCopy,
1580     BoundSync,
1581 }
1582
1583 pub fn empty_builtin_bounds() -> BuiltinBounds {
1584     EnumSet::new()
1585 }
1586
1587 pub fn all_builtin_bounds() -> BuiltinBounds {
1588     let mut set = EnumSet::new();
1589     set.insert(BoundSend);
1590     set.insert(BoundSized);
1591     set.insert(BoundSync);
1592     set
1593 }
1594
1595 /// An existential bound that does not implement any traits.
1596 pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx> {
1597     ty::ExistentialBounds { region_bound: r,
1598                             builtin_bounds: empty_builtin_bounds(),
1599                             projection_bounds: Vec::new() }
1600 }
1601
1602 impl CLike for BuiltinBound {
1603     fn to_uint(&self) -> uint {
1604         *self as uint
1605     }
1606     fn from_uint(v: uint) -> BuiltinBound {
1607         unsafe { mem::transmute(v) }
1608     }
1609 }
1610
1611 #[deriving(Clone, Copy, PartialEq, Eq, Hash)]
1612 pub struct TyVid {
1613     pub index: u32
1614 }
1615
1616 #[deriving(Clone, Copy, PartialEq, Eq, Hash)]
1617 pub struct IntVid {
1618     pub index: u32
1619 }
1620
1621 #[deriving(Clone, Copy, PartialEq, Eq, Hash)]
1622 pub struct FloatVid {
1623     pub index: u32
1624 }
1625
1626 #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1627 pub struct RegionVid {
1628     pub index: u32
1629 }
1630
1631 #[deriving(Clone, Copy, PartialEq, Eq, Hash)]
1632 pub enum InferTy {
1633     TyVar(TyVid),
1634     IntVar(IntVid),
1635     FloatVar(FloatVid),
1636
1637     /// A `FreshTy` is one that is generated as a replacement for an
1638     /// unbound type variable. This is convenient for caching etc. See
1639     /// `middle::infer::freshen` for more details.
1640     FreshTy(u32),
1641
1642     // FIXME -- once integral fallback is impl'd, we should remove
1643     // this type. It's only needed to prevent spurious errors for
1644     // integers whose type winds up never being constrained.
1645     FreshIntTy(u32),
1646 }
1647
1648 #[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
1649 pub enum UnconstrainedNumeric {
1650     UnconstrainedFloat,
1651     UnconstrainedInt,
1652     Neither,
1653 }
1654
1655
1656 #[deriving(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Show, Copy)]
1657 pub enum InferRegion {
1658     ReVar(RegionVid),
1659     ReSkolemized(u32, BoundRegion)
1660 }
1661
1662 impl cmp::PartialEq for InferRegion {
1663     fn eq(&self, other: &InferRegion) -> bool {
1664         match ((*self), *other) {
1665             (ReVar(rva), ReVar(rvb)) => {
1666                 rva == rvb
1667             }
1668             (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
1669                 rva == rvb
1670             }
1671             _ => false
1672         }
1673     }
1674     fn ne(&self, other: &InferRegion) -> bool {
1675         !((*self) == (*other))
1676     }
1677 }
1678
1679 impl fmt::Show for TyVid {
1680     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
1681         write!(f, "_#{}t", self.index)
1682     }
1683 }
1684
1685 impl fmt::Show for IntVid {
1686     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1687         write!(f, "_#{}i", self.index)
1688     }
1689 }
1690
1691 impl fmt::Show for FloatVid {
1692     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1693         write!(f, "_#{}f", self.index)
1694     }
1695 }
1696
1697 impl fmt::Show for RegionVid {
1698     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1699         write!(f, "'_#{}r", self.index)
1700     }
1701 }
1702
1703 impl<'tcx> fmt::Show for FnSig<'tcx> {
1704     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1705         // grr, without tcx not much we can do.
1706         write!(f, "(...)")
1707     }
1708 }
1709
1710 impl fmt::Show for InferTy {
1711     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1712         match *self {
1713             TyVar(ref v) => v.fmt(f),
1714             IntVar(ref v) => v.fmt(f),
1715             FloatVar(ref v) => v.fmt(f),
1716             FreshTy(v) => write!(f, "FreshTy({})", v),
1717             FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
1718         }
1719     }
1720 }
1721
1722 impl fmt::Show for IntVarValue {
1723     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1724         match *self {
1725             IntType(ref v) => v.fmt(f),
1726             UintType(ref v) => v.fmt(f),
1727         }
1728     }
1729 }
1730
1731 #[deriving(Clone, Show)]
1732 pub struct TypeParameterDef<'tcx> {
1733     pub name: ast::Name,
1734     pub def_id: ast::DefId,
1735     pub space: subst::ParamSpace,
1736     pub index: u32,
1737     pub bounds: ParamBounds<'tcx>,
1738     pub default: Option<Ty<'tcx>>,
1739 }
1740
1741 #[deriving(RustcEncodable, RustcDecodable, Clone, Show)]
1742 pub struct RegionParameterDef {
1743     pub name: ast::Name,
1744     pub def_id: ast::DefId,
1745     pub space: subst::ParamSpace,
1746     pub index: u32,
1747     pub bounds: Vec<ty::Region>,
1748 }
1749
1750 impl RegionParameterDef {
1751     pub fn to_early_bound_region(&self) -> ty::Region {
1752         ty::ReEarlyBound(self.def_id.node, self.space, self.index, self.name)
1753     }
1754 }
1755
1756 /// Information about the formal type/lifetime parameters associated
1757 /// with an item or method. Analogous to ast::Generics.
1758 #[deriving(Clone, Show)]
1759 pub struct Generics<'tcx> {
1760     pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
1761     pub regions: VecPerParamSpace<RegionParameterDef>,
1762     pub predicates: VecPerParamSpace<Predicate<'tcx>>,
1763 }
1764
1765 impl<'tcx> Generics<'tcx> {
1766     pub fn empty() -> Generics<'tcx> {
1767         Generics {
1768             types: VecPerParamSpace::empty(),
1769             regions: VecPerParamSpace::empty(),
1770             predicates: VecPerParamSpace::empty(),
1771         }
1772     }
1773
1774     pub fn has_type_params(&self, space: subst::ParamSpace) -> bool {
1775         !self.types.is_empty_in(space)
1776     }
1777
1778     pub fn has_region_params(&self, space: subst::ParamSpace) -> bool {
1779         !self.regions.is_empty_in(space)
1780     }
1781
1782     pub fn to_bounds(&self, tcx: &ty::ctxt<'tcx>, substs: &Substs<'tcx>)
1783                      -> GenericBounds<'tcx> {
1784         GenericBounds {
1785             predicates: self.predicates.subst(tcx, substs),
1786         }
1787     }
1788 }
1789
1790 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1791 pub enum Predicate<'tcx> {
1792     /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
1793     /// the `Self` type of the trait reference and `A`, `B`, and `C`
1794     /// would be the parameters in the `TypeSpace`.
1795     Trait(PolyTraitPredicate<'tcx>),
1796
1797     /// where `T1 == T2`.
1798     Equate(PolyEquatePredicate<'tcx>),
1799
1800     /// where 'a : 'b
1801     RegionOutlives(PolyRegionOutlivesPredicate),
1802
1803     /// where T : 'a
1804     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1805
1806     /// where <T as TraitRef>::Name == X, approximately.
1807     /// See `ProjectionPredicate` struct for details.
1808     Projection(PolyProjectionPredicate<'tcx>),
1809 }
1810
1811 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1812 pub struct TraitPredicate<'tcx> {
1813     pub trait_ref: Rc<TraitRef<'tcx>>
1814 }
1815 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1816
1817 impl<'tcx> TraitPredicate<'tcx> {
1818     pub fn def_id(&self) -> ast::DefId {
1819         self.trait_ref.def_id
1820     }
1821
1822     pub fn input_types(&self) -> &[Ty<'tcx>] {
1823         self.trait_ref.substs.types.as_slice()
1824     }
1825
1826     pub fn self_ty(&self) -> Ty<'tcx> {
1827         self.trait_ref.self_ty()
1828     }
1829 }
1830
1831 impl<'tcx> PolyTraitPredicate<'tcx> {
1832     pub fn def_id(&self) -> ast::DefId {
1833         self.0.def_id()
1834     }
1835 }
1836
1837 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1838 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
1839 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
1840
1841 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1842 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
1843 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
1844 pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
1845 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region>;
1846
1847 /// This kind of predicate has no *direct* correspondent in the
1848 /// syntax, but it roughly corresponds to the syntactic forms:
1849 ///
1850 /// 1. `T : TraitRef<..., Item=Type>`
1851 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1852 ///
1853 /// In particular, form #1 is "desugared" to the combination of a
1854 /// normal trait predicate (`T : TraitRef<...>`) and one of these
1855 /// predicates. Form #2 is a broader form in that it also permits
1856 /// equality between arbitrary types. Processing an instance of Form
1857 /// #2 eventually yields one of these `ProjectionPredicate`
1858 /// instances to normalize the LHS.
1859 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1860 pub struct ProjectionPredicate<'tcx> {
1861     pub projection_ty: ProjectionTy<'tcx>,
1862     pub ty: Ty<'tcx>,
1863 }
1864
1865 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1866
1867 impl<'tcx> PolyProjectionPredicate<'tcx> {
1868     pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
1869         self.0.projection_ty.sort_key()
1870     }
1871 }
1872
1873 /// Represents the projection of an associated type. In explicit UFCS
1874 /// form this would be written `<T as Trait<..>>::N`.
1875 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
1876 pub struct ProjectionTy<'tcx> {
1877     /// The trait reference `T as Trait<..>`.
1878     pub trait_ref: Rc<ty::TraitRef<'tcx>>,
1879
1880     /// The name `N` of the associated type.
1881     pub item_name: ast::Name,
1882 }
1883
1884 impl<'tcx> ProjectionTy<'tcx> {
1885     pub fn sort_key(&self) -> (ast::DefId, ast::Name) {
1886         (self.trait_ref.def_id, self.item_name)
1887     }
1888 }
1889
1890 pub trait ToPolyTraitRef<'tcx> {
1891     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1892 }
1893
1894 impl<'tcx> ToPolyTraitRef<'tcx> for Rc<TraitRef<'tcx>> {
1895     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1896         assert!(!self.has_escaping_regions());
1897         ty::Binder(self.clone())
1898     }
1899 }
1900
1901 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1902     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1903         // We are just preserving the binder levels here
1904         ty::Binder(self.0.trait_ref.clone())
1905     }
1906 }
1907
1908 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1909     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1910         // Note: unlike with TraitRef::to_poly_trait_ref(),
1911         // self.0.trait_ref is permitted to have escaping regions.
1912         // This is because here `self` has a `Binder` and so does our
1913         // return value, so we are preserving the number of binding
1914         // levels.
1915         ty::Binder(self.0.projection_ty.trait_ref.clone())
1916     }
1917 }
1918
1919 pub trait AsPredicate<'tcx> {
1920     fn as_predicate(&self) -> Predicate<'tcx>;
1921 }
1922
1923 impl<'tcx> AsPredicate<'tcx> for Rc<TraitRef<'tcx>> {
1924     fn as_predicate(&self) -> Predicate<'tcx> {
1925         // we're about to add a binder, so let's check that we don't
1926         // accidentally capture anything, or else that might be some
1927         // weird debruijn accounting.
1928         assert!(!self.has_escaping_regions());
1929
1930         ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1931             trait_ref: self.clone()
1932         }))
1933     }
1934 }
1935
1936 impl<'tcx> AsPredicate<'tcx> for PolyTraitRef<'tcx> {
1937     fn as_predicate(&self) -> Predicate<'tcx> {
1938         ty::Predicate::Trait(self.to_poly_trait_predicate())
1939     }
1940 }
1941
1942 impl<'tcx> AsPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1943     fn as_predicate(&self) -> Predicate<'tcx> {
1944         Predicate::Equate(self.clone())
1945     }
1946 }
1947
1948 impl<'tcx> AsPredicate<'tcx> for PolyRegionOutlivesPredicate {
1949     fn as_predicate(&self) -> Predicate<'tcx> {
1950         Predicate::RegionOutlives(self.clone())
1951     }
1952 }
1953
1954 impl<'tcx> AsPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1955     fn as_predicate(&self) -> Predicate<'tcx> {
1956         Predicate::TypeOutlives(self.clone())
1957     }
1958 }
1959
1960 impl<'tcx> AsPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1961     fn as_predicate(&self) -> Predicate<'tcx> {
1962         Predicate::Projection(self.clone())
1963     }
1964 }
1965
1966 impl<'tcx> Predicate<'tcx> {
1967     pub fn has_escaping_regions(&self) -> bool {
1968         match *self {
1969             Predicate::Trait(ref trait_ref) => trait_ref.has_escaping_regions(),
1970             Predicate::Equate(ref p) => p.has_escaping_regions(),
1971             Predicate::RegionOutlives(ref p) => p.has_escaping_regions(),
1972             Predicate::TypeOutlives(ref p) => p.has_escaping_regions(),
1973             Predicate::Projection(ref p) => p.has_escaping_regions(),
1974         }
1975     }
1976
1977     pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1978         match *self {
1979             Predicate::Trait(ref t) => {
1980                 Some(t.to_poly_trait_ref())
1981             }
1982             Predicate::Projection(..) |
1983             Predicate::Equate(..) |
1984             Predicate::RegionOutlives(..) |
1985             Predicate::TypeOutlives(..) => {
1986                 None
1987             }
1988         }
1989     }
1990 }
1991
1992 /// Represents the bounds declared on a particular set of type
1993 /// parameters.  Should eventually be generalized into a flag list of
1994 /// where clauses.  You can obtain a `GenericBounds` list from a
1995 /// `Generics` by using the `to_bounds` method. Note that this method
1996 /// reflects an important semantic invariant of `GenericBounds`: while
1997 /// the bounds in a `Generics` are expressed in terms of the bound type
1998 /// parameters of the impl/trait/whatever, a `GenericBounds` instance
1999 /// represented a set of bounds for some particular instantiation,
2000 /// meaning that the generic parameters have been substituted with
2001 /// their values.
2002 ///
2003 /// Example:
2004 ///
2005 ///     struct Foo<T,U:Bar<T>> { ... }
2006 ///
2007 /// Here, the `Generics` for `Foo` would contain a list of bounds like
2008 /// `[[], [U:Bar<T>]]`.  Now if there were some particular reference
2009 /// like `Foo<int,uint>`, then the `GenericBounds` would be `[[],
2010 /// [uint:Bar<int>]]`.
2011 #[deriving(Clone, Show)]
2012 pub struct GenericBounds<'tcx> {
2013     pub predicates: VecPerParamSpace<Predicate<'tcx>>,
2014 }
2015
2016 impl<'tcx> GenericBounds<'tcx> {
2017     pub fn empty() -> GenericBounds<'tcx> {
2018         GenericBounds { predicates: VecPerParamSpace::empty() }
2019     }
2020
2021     pub fn has_escaping_regions(&self) -> bool {
2022         self.predicates.any(|p| p.has_escaping_regions())
2023     }
2024
2025     pub fn is_empty(&self) -> bool {
2026         self.predicates.is_empty()
2027     }
2028 }
2029
2030 impl<'tcx> TraitRef<'tcx> {
2031     pub fn new(def_id: ast::DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
2032         TraitRef { def_id: def_id, substs: substs }
2033     }
2034
2035     pub fn self_ty(&self) -> Ty<'tcx> {
2036         self.substs.self_ty().unwrap()
2037     }
2038
2039     pub fn input_types(&self) -> &[Ty<'tcx>] {
2040         // Select only the "input types" from a trait-reference. For
2041         // now this is all the types that appear in the
2042         // trait-reference, but it should eventually exclude
2043         // associated types.
2044         self.substs.types.as_slice()
2045     }
2046 }
2047
2048 /// When type checking, we use the `ParameterEnvironment` to track
2049 /// details about the type/lifetime parameters that are in scope.
2050 /// It primarily stores the bounds information.
2051 ///
2052 /// Note: This information might seem to be redundant with the data in
2053 /// `tcx.ty_param_defs`, but it is not. That table contains the
2054 /// parameter definitions from an "outside" perspective, but this
2055 /// struct will contain the bounds for a parameter as seen from inside
2056 /// the function body. Currently the only real distinction is that
2057 /// bound lifetime parameters are replaced with free ones, but in the
2058 /// future I hope to refine the representation of types so as to make
2059 /// more distinctions clearer.
2060 #[deriving(Clone)]
2061 pub struct ParameterEnvironment<'tcx> {
2062     /// A substitution that can be applied to move from
2063     /// the "outer" view of a type or method to the "inner" view.
2064     /// In general, this means converting from bound parameters to
2065     /// free parameters. Since we currently represent bound/free type
2066     /// parameters in the same way, this only has an effect on regions.
2067     pub free_substs: Substs<'tcx>,
2068
2069     /// Each type parameter has an implicit region bound that
2070     /// indicates it must outlive at least the function body (the user
2071     /// may specify stronger requirements). This field indicates the
2072     /// region of the callee.
2073     pub implicit_region_bound: ty::Region,
2074
2075     /// Obligations that the caller must satisfy. This is basically
2076     /// the set of bounds on the in-scope type parameters, translated
2077     /// into Obligations.
2078     pub caller_bounds: ty::GenericBounds<'tcx>,
2079
2080     /// Caches the results of trait selection. This cache is used
2081     /// for things that have to do with the parameters in scope.
2082     pub selection_cache: traits::SelectionCache<'tcx>,
2083 }
2084
2085 impl<'tcx> ParameterEnvironment<'tcx> {
2086     pub fn for_item(cx: &ctxt<'tcx>, id: NodeId) -> ParameterEnvironment<'tcx> {
2087         match cx.map.find(id) {
2088             Some(ast_map::NodeImplItem(ref impl_item)) => {
2089                 match **impl_item {
2090                     ast::MethodImplItem(ref method) => {
2091                         let method_def_id = ast_util::local_def(id);
2092                         match ty::impl_or_trait_item(cx, method_def_id) {
2093                             MethodTraitItem(ref method_ty) => {
2094                                 let method_generics = &method_ty.generics;
2095                                 construct_parameter_environment(
2096                                     cx,
2097                                     method_generics,
2098                                     method.pe_body().id)
2099                             }
2100                             TypeTraitItem(_) => {
2101                                 cx.sess
2102                                   .bug("ParameterEnvironment::for_item(): \
2103                                         can't create a parameter environment \
2104                                         for type trait items")
2105                             }
2106                         }
2107                     }
2108                     ast::TypeImplItem(_) => {
2109                         cx.sess.bug("ParameterEnvironment::for_item(): \
2110                                      can't create a parameter environment \
2111                                      for type impl items")
2112                     }
2113                 }
2114             }
2115             Some(ast_map::NodeTraitItem(trait_method)) => {
2116                 match *trait_method {
2117                     ast::RequiredMethod(ref required) => {
2118                         cx.sess.span_bug(required.span,
2119                                          "ParameterEnvironment::for_item():
2120                                           can't create a parameter \
2121                                           environment for required trait \
2122                                           methods")
2123                     }
2124                     ast::ProvidedMethod(ref method) => {
2125                         let method_def_id = ast_util::local_def(id);
2126                         match ty::impl_or_trait_item(cx, method_def_id) {
2127                             MethodTraitItem(ref method_ty) => {
2128                                 let method_generics = &method_ty.generics;
2129                                 construct_parameter_environment(
2130                                     cx,
2131                                     method_generics,
2132                                     method.pe_body().id)
2133                             }
2134                             TypeTraitItem(_) => {
2135                                 cx.sess
2136                                   .bug("ParameterEnvironment::for_item(): \
2137                                         can't create a parameter environment \
2138                                         for type trait items")
2139                             }
2140                         }
2141                     }
2142                     ast::TypeTraitItem(_) => {
2143                         cx.sess.bug("ParameterEnvironment::from_item(): \
2144                                      can't create a parameter environment \
2145                                      for type trait items")
2146                     }
2147                 }
2148             }
2149             Some(ast_map::NodeItem(item)) => {
2150                 match item.node {
2151                     ast::ItemFn(_, _, _, _, ref body) => {
2152                         // We assume this is a function.
2153                         let fn_def_id = ast_util::local_def(id);
2154                         let fn_pty = ty::lookup_item_type(cx, fn_def_id);
2155
2156                         construct_parameter_environment(cx,
2157                                                         &fn_pty.generics,
2158                                                         body.id)
2159                     }
2160                     ast::ItemEnum(..) |
2161                     ast::ItemStruct(..) |
2162                     ast::ItemImpl(..) |
2163                     ast::ItemConst(..) |
2164                     ast::ItemStatic(..) => {
2165                         let def_id = ast_util::local_def(id);
2166                         let pty = ty::lookup_item_type(cx, def_id);
2167                         construct_parameter_environment(cx, &pty.generics, id)
2168                     }
2169                     _ => {
2170                         cx.sess.span_bug(item.span,
2171                                          "ParameterEnvironment::from_item():
2172                                           can't create a parameter \
2173                                           environment for this kind of item")
2174                     }
2175                 }
2176             }
2177             Some(ast_map::NodeExpr(..)) => {
2178                 // This is a convenience to allow closures to work.
2179                 ParameterEnvironment::for_item(cx, cx.map.get_parent(id))
2180             }
2181             _ => {
2182                 cx.sess.bug(format!("ParameterEnvironment::from_item(): \
2183                                      `{}` is not an item",
2184                                     cx.map.node_to_string(id))[])
2185             }
2186         }
2187     }
2188 }
2189
2190 /// A "type scheme", in ML terminology, is a type combined with some
2191 /// set of generic types that the type is, well, generic over. In Rust
2192 /// terms, it is the "type" of a fn item or struct -- this type will
2193 /// include various generic parameters that must be substituted when
2194 /// the item/struct is referenced. That is called converting the type
2195 /// scheme to a monotype.
2196 ///
2197 /// - `generics`: the set of type parameters and their bounds
2198 /// - `ty`: the base types, which may reference the parameters defined
2199 ///   in `generics`
2200 ///
2201 /// Note that TypeSchemes are also sometimes called "polytypes" (and
2202 /// in fact this struct used to carry that name, so you may find some
2203 /// stray references in a comment or something). We try to reserve the
2204 /// "poly" prefix to refer to higher-ranked things, as in
2205 /// `PolyTraitRef`.
2206 #[deriving(Clone, Show)]
2207 pub struct TypeScheme<'tcx> {
2208     pub generics: Generics<'tcx>,
2209     pub ty: Ty<'tcx>
2210 }
2211
2212 /// As `TypeScheme` but for a trait ref.
2213 pub struct TraitDef<'tcx> {
2214     pub unsafety: ast::Unsafety,
2215
2216     /// Generic type definitions. Note that `Self` is listed in here
2217     /// as having a single bound, the trait itself (e.g., in the trait
2218     /// `Eq`, there is a single bound `Self : Eq`). This is so that
2219     /// default methods get to assume that the `Self` parameters
2220     /// implements the trait.
2221     pub generics: Generics<'tcx>,
2222
2223     /// The "supertrait" bounds.
2224     pub bounds: ParamBounds<'tcx>,
2225
2226     pub trait_ref: Rc<ty::TraitRef<'tcx>>,
2227
2228     /// A list of the associated types defined in this trait. Useful
2229     /// for resolving `X::Foo` type markers.
2230     pub associated_type_names: Vec<ast::Name>,
2231 }
2232
2233 /// Records the substitutions used to translate the polytype for an
2234 /// item into the monotype of an item reference.
2235 #[deriving(Clone)]
2236 pub struct ItemSubsts<'tcx> {
2237     pub substs: Substs<'tcx>,
2238 }
2239
2240 /// Records information about each unboxed closure.
2241 #[deriving(Clone)]
2242 pub struct UnboxedClosure<'tcx> {
2243     /// The type of the unboxed closure.
2244     pub closure_type: ClosureTy<'tcx>,
2245     /// The kind of unboxed closure this is.
2246     pub kind: UnboxedClosureKind,
2247 }
2248
2249 #[deriving(Clone, Copy, PartialEq, Eq, Show)]
2250 pub enum UnboxedClosureKind {
2251     FnUnboxedClosureKind,
2252     FnMutUnboxedClosureKind,
2253     FnOnceUnboxedClosureKind,
2254 }
2255
2256 impl UnboxedClosureKind {
2257     pub fn trait_did(&self, cx: &ctxt) -> ast::DefId {
2258         let result = match *self {
2259             FnUnboxedClosureKind => cx.lang_items.require(FnTraitLangItem),
2260             FnMutUnboxedClosureKind => {
2261                 cx.lang_items.require(FnMutTraitLangItem)
2262             }
2263             FnOnceUnboxedClosureKind => {
2264                 cx.lang_items.require(FnOnceTraitLangItem)
2265             }
2266         };
2267         match result {
2268             Ok(trait_did) => trait_did,
2269             Err(err) => cx.sess.fatal(err[]),
2270         }
2271     }
2272 }
2273
2274 pub trait UnboxedClosureTyper<'tcx> {
2275     fn unboxed_closure_kind(&self,
2276                             def_id: ast::DefId)
2277                             -> ty::UnboxedClosureKind;
2278
2279     fn unboxed_closure_type(&self,
2280                             def_id: ast::DefId,
2281                             substs: &subst::Substs<'tcx>)
2282                             -> ty::ClosureTy<'tcx>;
2283
2284     // Returns `None` if the upvar types cannot yet be definitively determined.
2285     fn unboxed_closure_upvars(&self,
2286                               def_id: ast::DefId,
2287                               substs: &Substs<'tcx>)
2288                               -> Option<Vec<UnboxedClosureUpvar<'tcx>>>;
2289 }
2290
2291 impl<'tcx> CommonTypes<'tcx> {
2292     fn new(arena: &'tcx TypedArena<TyS<'tcx>>,
2293            interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>)
2294            -> CommonTypes<'tcx>
2295     {
2296         CommonTypes {
2297             bool: intern_ty(arena, interner, ty_bool),
2298             char: intern_ty(arena, interner, ty_char),
2299             err: intern_ty(arena, interner, ty_err),
2300             int: intern_ty(arena, interner, ty_int(ast::TyI)),
2301             i8: intern_ty(arena, interner, ty_int(ast::TyI8)),
2302             i16: intern_ty(arena, interner, ty_int(ast::TyI16)),
2303             i32: intern_ty(arena, interner, ty_int(ast::TyI32)),
2304             i64: intern_ty(arena, interner, ty_int(ast::TyI64)),
2305             uint: intern_ty(arena, interner, ty_uint(ast::TyU)),
2306             u8: intern_ty(arena, interner, ty_uint(ast::TyU8)),
2307             u16: intern_ty(arena, interner, ty_uint(ast::TyU16)),
2308             u32: intern_ty(arena, interner, ty_uint(ast::TyU32)),
2309             u64: intern_ty(arena, interner, ty_uint(ast::TyU64)),
2310             f32: intern_ty(arena, interner, ty_float(ast::TyF32)),
2311             f64: intern_ty(arena, interner, ty_float(ast::TyF64)),
2312         }
2313     }
2314 }
2315
2316 pub fn mk_ctxt<'tcx>(s: Session,
2317                      arenas: &'tcx CtxtArenas<'tcx>,
2318                      dm: DefMap,
2319                      named_region_map: resolve_lifetime::NamedRegionMap,
2320                      map: ast_map::Map<'tcx>,
2321                      freevars: RefCell<FreevarMap>,
2322                      capture_modes: RefCell<CaptureModeMap>,
2323                      region_maps: middle::region::RegionMaps,
2324                      lang_items: middle::lang_items::LanguageItems,
2325                      stability: stability::Index) -> ctxt<'tcx>
2326 {
2327     let mut interner = FnvHashMap::new();
2328     let common_types = CommonTypes::new(&arenas.type_, &mut interner);
2329
2330     ctxt {
2331         arenas: arenas,
2332         interner: RefCell::new(interner),
2333         substs_interner: RefCell::new(FnvHashMap::new()),
2334         bare_fn_interner: RefCell::new(FnvHashMap::new()),
2335         region_interner: RefCell::new(FnvHashMap::new()),
2336         types: common_types,
2337         named_region_map: named_region_map,
2338         item_variance_map: RefCell::new(DefIdMap::new()),
2339         variance_computed: Cell::new(false),
2340         sess: s,
2341         def_map: dm,
2342         region_maps: region_maps,
2343         node_types: RefCell::new(FnvHashMap::new()),
2344         item_substs: RefCell::new(NodeMap::new()),
2345         trait_refs: RefCell::new(NodeMap::new()),
2346         trait_defs: RefCell::new(DefIdMap::new()),
2347         object_cast_map: RefCell::new(NodeMap::new()),
2348         map: map,
2349         intrinsic_defs: RefCell::new(DefIdMap::new()),
2350         freevars: freevars,
2351         tcache: RefCell::new(DefIdMap::new()),
2352         rcache: RefCell::new(FnvHashMap::new()),
2353         short_names_cache: RefCell::new(FnvHashMap::new()),
2354         tc_cache: RefCell::new(FnvHashMap::new()),
2355         ast_ty_to_ty_cache: RefCell::new(NodeMap::new()),
2356         enum_var_cache: RefCell::new(DefIdMap::new()),
2357         impl_or_trait_items: RefCell::new(DefIdMap::new()),
2358         trait_item_def_ids: RefCell::new(DefIdMap::new()),
2359         trait_items_cache: RefCell::new(DefIdMap::new()),
2360         impl_trait_cache: RefCell::new(DefIdMap::new()),
2361         ty_param_defs: RefCell::new(NodeMap::new()),
2362         adjustments: RefCell::new(NodeMap::new()),
2363         normalized_cache: RefCell::new(FnvHashMap::new()),
2364         lang_items: lang_items,
2365         provided_method_sources: RefCell::new(DefIdMap::new()),
2366         struct_fields: RefCell::new(DefIdMap::new()),
2367         destructor_for_type: RefCell::new(DefIdMap::new()),
2368         destructors: RefCell::new(DefIdSet::new()),
2369         trait_impls: RefCell::new(DefIdMap::new()),
2370         inherent_impls: RefCell::new(DefIdMap::new()),
2371         impl_items: RefCell::new(DefIdMap::new()),
2372         used_unsafe: RefCell::new(NodeSet::new()),
2373         used_mut_nodes: RefCell::new(NodeSet::new()),
2374         populated_external_types: RefCell::new(DefIdSet::new()),
2375         populated_external_traits: RefCell::new(DefIdSet::new()),
2376         upvar_borrow_map: RefCell::new(FnvHashMap::new()),
2377         extern_const_statics: RefCell::new(DefIdMap::new()),
2378         extern_const_variants: RefCell::new(DefIdMap::new()),
2379         method_map: RefCell::new(FnvHashMap::new()),
2380         dependency_formats: RefCell::new(FnvHashMap::new()),
2381         unboxed_closures: RefCell::new(DefIdMap::new()),
2382         node_lint_levels: RefCell::new(FnvHashMap::new()),
2383         transmute_restrictions: RefCell::new(Vec::new()),
2384         stability: RefCell::new(stability),
2385         capture_modes: capture_modes,
2386         associated_types: RefCell::new(DefIdMap::new()),
2387         selection_cache: traits::SelectionCache::new(),
2388         repr_hint_cache: RefCell::new(DefIdMap::new()),
2389         type_impls_copy_cache: RefCell::new(HashMap::new()),
2390         type_impls_sized_cache: RefCell::new(HashMap::new()),
2391         object_safety_cache: RefCell::new(DefIdMap::new()),
2392    }
2393 }
2394
2395 // Type constructors
2396
2397 impl<'tcx> ctxt<'tcx> {
2398     pub fn mk_substs(&self, substs: Substs<'tcx>) -> &'tcx Substs<'tcx> {
2399         if let Some(substs) = self.substs_interner.borrow().get(&substs) {
2400             return *substs;
2401         }
2402
2403         let substs = self.arenas.substs.alloc(substs);
2404         self.substs_interner.borrow_mut().insert(substs, substs);
2405         substs
2406     }
2407
2408     pub fn mk_bare_fn(&self, bare_fn: BareFnTy<'tcx>) -> &'tcx BareFnTy<'tcx> {
2409         if let Some(bare_fn) = self.bare_fn_interner.borrow().get(&bare_fn) {
2410             return *bare_fn;
2411         }
2412
2413         let bare_fn = self.arenas.bare_fn.alloc(bare_fn);
2414         self.bare_fn_interner.borrow_mut().insert(bare_fn, bare_fn);
2415         bare_fn
2416     }
2417
2418     pub fn mk_region(&self, region: Region) -> &'tcx Region {
2419         if let Some(region) = self.region_interner.borrow().get(&region) {
2420             return *region;
2421         }
2422
2423         let region = self.arenas.region.alloc(region);
2424         self.region_interner.borrow_mut().insert(region, region);
2425         region
2426     }
2427 }
2428
2429 // Interns a type/name combination, stores the resulting box in cx.interner,
2430 // and returns the box as cast to an unsafe ptr (see comments for Ty above).
2431 pub fn mk_t<'tcx>(cx: &ctxt<'tcx>, st: sty<'tcx>) -> Ty<'tcx> {
2432     let mut interner = cx.interner.borrow_mut();
2433     intern_ty(&cx.arenas.type_, &mut *interner, st)
2434 }
2435
2436 fn intern_ty<'tcx>(type_arena: &'tcx TypedArena<TyS<'tcx>>,
2437                    interner: &mut FnvHashMap<InternedTy<'tcx>, Ty<'tcx>>,
2438                    st: sty<'tcx>)
2439                    -> Ty<'tcx>
2440 {
2441     match interner.get(&st) {
2442         Some(ty) => return *ty,
2443         _ => ()
2444     }
2445
2446     let flags = FlagComputation::for_sty(&st);
2447
2448     let ty = type_arena.alloc(TyS {
2449         sty: st,
2450         flags: flags.flags,
2451         region_depth: flags.depth,
2452     });
2453
2454     debug!("Interned type: {} Pointer: {}",
2455            ty, ty as *const _);
2456
2457     interner.insert(InternedTy { ty: ty }, ty);
2458
2459     ty
2460 }
2461
2462 struct FlagComputation {
2463     flags: TypeFlags,
2464
2465     // maximum depth of any bound region that we have seen thus far
2466     depth: u32,
2467 }
2468
2469 impl FlagComputation {
2470     fn new() -> FlagComputation {
2471         FlagComputation { flags: NO_TYPE_FLAGS, depth: 0 }
2472     }
2473
2474     fn for_sty(st: &sty) -> FlagComputation {
2475         let mut result = FlagComputation::new();
2476         result.add_sty(st);
2477         result
2478     }
2479
2480     fn add_flags(&mut self, flags: TypeFlags) {
2481         self.flags = self.flags | flags;
2482     }
2483
2484     fn add_depth(&mut self, depth: u32) {
2485         if depth > self.depth {
2486             self.depth = depth;
2487         }
2488     }
2489
2490     /// Adds the flags/depth from a set of types that appear within the current type, but within a
2491     /// region binder.
2492     fn add_bound_computation(&mut self, computation: &FlagComputation) {
2493         self.add_flags(computation.flags);
2494
2495         // The types that contributed to `computation` occured within
2496         // a region binder, so subtract one from the region depth
2497         // within when adding the depth to `self`.
2498         let depth = computation.depth;
2499         if depth > 0 {
2500             self.add_depth(depth - 1);
2501         }
2502     }
2503
2504     fn add_sty(&mut self, st: &sty) {
2505         match st {
2506             &ty_bool |
2507             &ty_char |
2508             &ty_int(_) |
2509             &ty_float(_) |
2510             &ty_uint(_) |
2511             &ty_str => {
2512             }
2513
2514             // You might think that we could just return ty_err for
2515             // any type containing ty_err as a component, and get
2516             // rid of the HAS_TY_ERR flag -- likewise for ty_bot (with
2517             // the exception of function types that return bot).
2518             // But doing so caused sporadic memory corruption, and
2519             // neither I (tjc) nor nmatsakis could figure out why,
2520             // so we're doing it this way.
2521             &ty_err => {
2522                 self.add_flags(HAS_TY_ERR)
2523             }
2524
2525             &ty_param(ref p) => {
2526                 if p.space == subst::SelfSpace {
2527                     self.add_flags(HAS_SELF);
2528                 } else {
2529                     self.add_flags(HAS_PARAMS);
2530                 }
2531             }
2532
2533             &ty_unboxed_closure(_, region, substs) => {
2534                 self.add_region(*region);
2535                 self.add_substs(substs);
2536             }
2537
2538             &ty_infer(_) => {
2539                 self.add_flags(HAS_TY_INFER)
2540             }
2541
2542             &ty_enum(_, substs) | &ty_struct(_, substs) => {
2543                 self.add_substs(substs);
2544             }
2545
2546             &ty_projection(ref data) => {
2547                 self.add_flags(HAS_PROJECTION);
2548                 self.add_substs(data.trait_ref.substs);
2549             }
2550
2551             &ty_trait(box TyTrait { ref principal, ref bounds }) => {
2552                 let mut computation = FlagComputation::new();
2553                 computation.add_substs(principal.0.substs);
2554                 self.add_bound_computation(&computation);
2555
2556                 self.add_bounds(bounds);
2557             }
2558
2559             &ty_uniq(tt) | &ty_vec(tt, _) | &ty_open(tt) => {
2560                 self.add_ty(tt)
2561             }
2562
2563             &ty_ptr(ref m) => {
2564                 self.add_ty(m.ty);
2565             }
2566
2567             &ty_rptr(r, ref m) => {
2568                 self.add_region(*r);
2569                 self.add_ty(m.ty);
2570             }
2571
2572             &ty_tup(ref ts) => {
2573                 self.add_tys(ts[]);
2574             }
2575
2576             &ty_bare_fn(_, ref f) => {
2577                 self.add_fn_sig(&f.sig);
2578             }
2579
2580             &ty_closure(ref f) => {
2581                 if let RegionTraitStore(r, _) = f.store {
2582                     self.add_region(r);
2583                 }
2584                 self.add_fn_sig(&f.sig);
2585                 self.add_bounds(&f.bounds);
2586             }
2587         }
2588     }
2589
2590     fn add_ty(&mut self, ty: Ty) {
2591         self.add_flags(ty.flags);
2592         self.add_depth(ty.region_depth);
2593     }
2594
2595     fn add_tys(&mut self, tys: &[Ty]) {
2596         for &ty in tys.iter() {
2597             self.add_ty(ty);
2598         }
2599     }
2600
2601     fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) {
2602         let mut computation = FlagComputation::new();
2603
2604         computation.add_tys(fn_sig.0.inputs[]);
2605
2606         if let ty::FnConverging(output) = fn_sig.0.output {
2607             computation.add_ty(output);
2608         }
2609
2610         self.add_bound_computation(&computation);
2611     }
2612
2613     fn add_region(&mut self, r: Region) {
2614         self.add_flags(HAS_REGIONS);
2615         match r {
2616             ty::ReInfer(_) => { self.add_flags(HAS_RE_INFER); }
2617             ty::ReLateBound(debruijn, _) => {
2618                 self.add_flags(HAS_RE_LATE_BOUND);
2619                 self.add_depth(debruijn.depth);
2620             }
2621             _ => { }
2622         }
2623     }
2624
2625     fn add_substs(&mut self, substs: &Substs) {
2626         self.add_tys(substs.types.as_slice());
2627         match substs.regions {
2628             subst::ErasedRegions => {}
2629             subst::NonerasedRegions(ref regions) => {
2630                 for &r in regions.iter() {
2631                     self.add_region(r);
2632                 }
2633             }
2634         }
2635     }
2636
2637     fn add_bounds(&mut self, bounds: &ExistentialBounds) {
2638         self.add_region(bounds.region_bound);
2639     }
2640 }
2641
2642 pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> {
2643     match tm {
2644         ast::TyI    => tcx.types.int,
2645         ast::TyI8   => tcx.types.i8,
2646         ast::TyI16  => tcx.types.i16,
2647         ast::TyI32  => tcx.types.i32,
2648         ast::TyI64  => tcx.types.i64,
2649     }
2650 }
2651
2652 pub fn mk_mach_uint<'tcx>(tcx: &ctxt<'tcx>, tm: ast::UintTy) -> Ty<'tcx> {
2653     match tm {
2654         ast::TyU    => tcx.types.uint,
2655         ast::TyU8   => tcx.types.u8,
2656         ast::TyU16  => tcx.types.u16,
2657         ast::TyU32  => tcx.types.u32,
2658         ast::TyU64  => tcx.types.u64,
2659     }
2660 }
2661
2662 pub fn mk_mach_float<'tcx>(tcx: &ctxt<'tcx>, tm: ast::FloatTy) -> Ty<'tcx> {
2663     match tm {
2664         ast::TyF32  => tcx.types.f32,
2665         ast::TyF64  => tcx.types.f64,
2666     }
2667 }
2668
2669 pub fn mk_str<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2670     mk_t(cx, ty_str)
2671 }
2672
2673 pub fn mk_str_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, m: ast::Mutability) -> Ty<'tcx> {
2674     mk_rptr(cx, r,
2675             mt {
2676                 ty: mk_t(cx, ty_str),
2677                 mutbl: m
2678             })
2679 }
2680
2681 pub fn mk_enum<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2682     // take a copy of substs so that we own the vectors inside
2683     mk_t(cx, ty_enum(did, substs))
2684 }
2685
2686 pub fn mk_uniq<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_uniq(ty)) }
2687
2688 pub fn mk_ptr<'tcx>(cx: &ctxt<'tcx>, tm: mt<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_ptr(tm)) }
2689
2690 pub fn mk_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2691     mk_t(cx, ty_rptr(r, tm))
2692 }
2693
2694 pub fn mk_mut_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2695     mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutMutable})
2696 }
2697 pub fn mk_imm_rptr<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
2698     mk_rptr(cx, r, mt {ty: ty, mutbl: ast::MutImmutable})
2699 }
2700
2701 pub fn mk_mut_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2702     mk_ptr(cx, mt {ty: ty, mutbl: ast::MutMutable})
2703 }
2704
2705 pub fn mk_imm_ptr<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
2706     mk_ptr(cx, mt {ty: ty, mutbl: ast::MutImmutable})
2707 }
2708
2709 pub fn mk_nil_ptr<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2710     mk_ptr(cx, mt {ty: mk_nil(cx), mutbl: ast::MutImmutable})
2711 }
2712
2713 pub fn mk_vec<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, sz: Option<uint>) -> Ty<'tcx> {
2714     mk_t(cx, ty_vec(ty, sz))
2715 }
2716
2717 pub fn mk_slice<'tcx>(cx: &ctxt<'tcx>, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
2718     mk_rptr(cx, r,
2719             mt {
2720                 ty: mk_vec(cx, tm.ty, None),
2721                 mutbl: tm.mutbl
2722             })
2723 }
2724
2725 pub fn mk_tup<'tcx>(cx: &ctxt<'tcx>, ts: Vec<Ty<'tcx>>) -> Ty<'tcx> {
2726     mk_t(cx, ty_tup(ts))
2727 }
2728
2729 pub fn mk_nil<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2730     mk_tup(cx, Vec::new())
2731 }
2732
2733 pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, fty: ClosureTy<'tcx>) -> Ty<'tcx> {
2734     mk_t(cx, ty_closure(box fty))
2735 }
2736
2737 pub fn mk_bare_fn<'tcx>(cx: &ctxt<'tcx>,
2738                         opt_def_id: Option<ast::DefId>,
2739                         fty: &'tcx BareFnTy<'tcx>) -> Ty<'tcx> {
2740     mk_t(cx, ty_bare_fn(opt_def_id, fty))
2741 }
2742
2743 pub fn mk_ctor_fn<'tcx>(cx: &ctxt<'tcx>,
2744                         def_id: ast::DefId,
2745                         input_tys: &[Ty<'tcx>],
2746                         output: Ty<'tcx>) -> Ty<'tcx> {
2747     let input_args = input_tys.iter().map(|ty| *ty).collect();
2748     mk_bare_fn(cx,
2749                Some(def_id),
2750                cx.mk_bare_fn(BareFnTy {
2751                    unsafety: ast::Unsafety::Normal,
2752                    abi: abi::Rust,
2753                    sig: ty::Binder(FnSig {
2754                     inputs: input_args,
2755                     output: ty::FnConverging(output),
2756                     variadic: false
2757                    })
2758                 }))
2759 }
2760
2761 pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>,
2762                       principal: ty::PolyTraitRef<'tcx>,
2763                       bounds: ExistentialBounds<'tcx>)
2764                       -> Ty<'tcx>
2765 {
2766     assert!(bound_list_is_sorted(bounds.projection_bounds.as_slice()));
2767
2768     let inner = box TyTrait {
2769         principal: principal,
2770         bounds: bounds
2771     };
2772     mk_t(cx, ty_trait(inner))
2773 }
2774
2775 fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool {
2776     bounds.len() == 0 ||
2777         bounds[1..].iter().enumerate().all(
2778             |(index, bound)| bounds[index].sort_key() <= bound.sort_key())
2779 }
2780
2781 pub fn sort_bounds_list(bounds: &mut [ty::PolyProjectionPredicate]) {
2782     bounds.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()))
2783 }
2784
2785 pub fn mk_projection<'tcx>(cx: &ctxt<'tcx>,
2786                            trait_ref: Rc<ty::TraitRef<'tcx>>,
2787                            item_name: ast::Name)
2788                            -> Ty<'tcx> {
2789     // take a copy of substs so that we own the vectors inside
2790     let inner = ProjectionTy { trait_ref: trait_ref, item_name: item_name };
2791     mk_t(cx, ty_projection(inner))
2792 }
2793
2794 pub fn mk_struct<'tcx>(cx: &ctxt<'tcx>, struct_id: ast::DefId,
2795                        substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
2796     // take a copy of substs so that we own the vectors inside
2797     mk_t(cx, ty_struct(struct_id, substs))
2798 }
2799
2800 pub fn mk_unboxed_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId,
2801                                 region: &'tcx Region, substs: &'tcx Substs<'tcx>)
2802                                 -> Ty<'tcx> {
2803     mk_t(cx, ty_unboxed_closure(closure_id, region, substs))
2804 }
2805
2806 pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
2807     mk_infer(cx, TyVar(v))
2808 }
2809
2810 pub fn mk_int_var<'tcx>(cx: &ctxt<'tcx>, v: IntVid) -> Ty<'tcx> {
2811     mk_infer(cx, IntVar(v))
2812 }
2813
2814 pub fn mk_float_var<'tcx>(cx: &ctxt<'tcx>, v: FloatVid) -> Ty<'tcx> {
2815     mk_infer(cx, FloatVar(v))
2816 }
2817
2818 pub fn mk_infer<'tcx>(cx: &ctxt<'tcx>, it: InferTy) -> Ty<'tcx> {
2819     mk_t(cx, ty_infer(it))
2820 }
2821
2822 pub fn mk_param<'tcx>(cx: &ctxt<'tcx>,
2823                       space: subst::ParamSpace,
2824                       index: u32,
2825                       name: ast::Name) -> Ty<'tcx> {
2826     mk_t(cx, ty_param(ParamTy { space: space, idx: index, name: name }))
2827 }
2828
2829 pub fn mk_self_type<'tcx>(cx: &ctxt<'tcx>) -> Ty<'tcx> {
2830     mk_param(cx, subst::SelfSpace, 0, special_idents::type_self.name)
2831 }
2832
2833 pub fn mk_param_from_def<'tcx>(cx: &ctxt<'tcx>, def: &TypeParameterDef) -> Ty<'tcx> {
2834     mk_param(cx, def.space, def.index, def.name)
2835 }
2836
2837 pub fn mk_open<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { mk_t(cx, ty_open(ty)) }
2838
2839 impl<'tcx> TyS<'tcx> {
2840     /// Iterator that walks `self` and any types reachable from
2841     /// `self`, in depth-first order. Note that just walks the types
2842     /// that appear in `self`, it does not descend into the fields of
2843     /// structs or variants. For example:
2844     ///
2845     /// ```notrust
2846     /// int => { int }
2847     /// Foo<Bar<int>> => { Foo<Bar<int>>, Bar<int>, int }
2848     /// [int] => { [int], int }
2849     /// ```
2850     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
2851         TypeWalker::new(self)
2852     }
2853
2854     /// Iterator that walks types reachable from `self`, in
2855     /// depth-first order. Note that this is a shallow walk. For
2856     /// example:
2857     ///
2858     /// ```notrust
2859     /// int => { }
2860     /// Foo<Bar<int>> => { Bar<int>, int }
2861     /// [int] => { int }
2862     /// ```
2863     pub fn walk_children(&'tcx self) -> TypeWalker<'tcx> {
2864         // Walks type reachable from `self` but not `self
2865         let mut walker = self.walk();
2866         let r = walker.next();
2867         assert_eq!(r, Some(self));
2868         walker
2869     }
2870 }
2871
2872 pub fn walk_ty<'tcx, F>(ty_root: Ty<'tcx>, mut f: F)
2873     where F: FnMut(Ty<'tcx>),
2874 {
2875     for ty in ty_root.walk() {
2876         f(ty);
2877     }
2878 }
2879
2880 /// Walks `ty` and any types appearing within `ty`, invoking the
2881 /// callback `f` on each type. If the callback returns false, then the
2882 /// children of the current type are ignored.
2883 ///
2884 /// Note: prefer `ty.walk()` where possible.
2885 pub fn maybe_walk_ty<'tcx,F>(ty_root: Ty<'tcx>, mut f: F)
2886     where F : FnMut(Ty<'tcx>) -> bool
2887 {
2888     let mut walker = ty_root.walk();
2889     while let Some(ty) = walker.next() {
2890         if !f(ty) {
2891             walker.skip_current_subtree();
2892         }
2893     }
2894 }
2895
2896 // Folds types from the bottom up.
2897 pub fn fold_ty<'tcx, F>(cx: &ctxt<'tcx>, t0: Ty<'tcx>,
2898                         fldop: F)
2899                         -> Ty<'tcx> where
2900     F: FnMut(Ty<'tcx>) -> Ty<'tcx>,
2901 {
2902     let mut f = ty_fold::BottomUpFolder {tcx: cx, fldop: fldop};
2903     f.fold_ty(t0)
2904 }
2905
2906 impl ParamTy {
2907     pub fn new(space: subst::ParamSpace,
2908                index: u32,
2909                name: ast::Name)
2910                -> ParamTy {
2911         ParamTy { space: space, idx: index, name: name }
2912     }
2913
2914     pub fn for_self() -> ParamTy {
2915         ParamTy::new(subst::SelfSpace, 0, special_idents::type_self.name)
2916     }
2917
2918     pub fn for_def(def: &TypeParameterDef) -> ParamTy {
2919         ParamTy::new(def.space, def.index, def.name)
2920     }
2921
2922     pub fn to_ty<'tcx>(self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
2923         ty::mk_param(tcx, self.space, self.idx, self.name)
2924     }
2925
2926     pub fn is_self(&self) -> bool {
2927         self.space == subst::SelfSpace && self.idx == 0
2928     }
2929 }
2930
2931 impl<'tcx> ItemSubsts<'tcx> {
2932     pub fn empty() -> ItemSubsts<'tcx> {
2933         ItemSubsts { substs: Substs::empty() }
2934     }
2935
2936     pub fn is_noop(&self) -> bool {
2937         self.substs.is_noop()
2938     }
2939 }
2940
2941 impl<'tcx> ParamBounds<'tcx> {
2942     pub fn empty() -> ParamBounds<'tcx> {
2943         ParamBounds {
2944             builtin_bounds: empty_builtin_bounds(),
2945             trait_bounds: Vec::new(),
2946             region_bounds: Vec::new(),
2947             projection_bounds: Vec::new(),
2948         }
2949     }
2950 }
2951
2952 // Type utilities
2953
2954 pub fn type_is_nil(ty: Ty) -> bool {
2955     match ty.sty {
2956         ty_tup(ref tys) => tys.is_empty(),
2957         _ => false
2958     }
2959 }
2960
2961 pub fn type_is_error(ty: Ty) -> bool {
2962     ty.flags.intersects(HAS_TY_ERR)
2963 }
2964
2965 pub fn type_needs_subst(ty: Ty) -> bool {
2966     ty.flags.intersects(NEEDS_SUBST)
2967 }
2968
2969 pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
2970     tref.substs.types.any(|&ty| type_is_error(ty))
2971 }
2972
2973 pub fn type_is_ty_var(ty: Ty) -> bool {
2974     match ty.sty {
2975         ty_infer(TyVar(_)) => true,
2976         _ => false
2977     }
2978 }
2979
2980 pub fn type_is_bool(ty: Ty) -> bool { ty.sty == ty_bool }
2981
2982 pub fn type_is_self(ty: Ty) -> bool {
2983     match ty.sty {
2984         ty_param(ref p) => p.space == subst::SelfSpace,
2985         _ => false
2986     }
2987 }
2988
2989 fn type_is_slice(ty: Ty) -> bool {
2990     match ty.sty {
2991         ty_ptr(mt) | ty_rptr(_, mt) => match mt.ty.sty {
2992             ty_vec(_, None) | ty_str => true,
2993             _ => false,
2994         },
2995         _ => false
2996     }
2997 }
2998
2999 pub fn type_is_vec(ty: Ty) -> bool {
3000     match ty.sty {
3001         ty_vec(..) => true,
3002         ty_ptr(mt{ty, ..}) | ty_rptr(_, mt{ty, ..}) |
3003         ty_uniq(ty) => match ty.sty {
3004             ty_vec(_, None) => true,
3005             _ => false
3006         },
3007         _ => false
3008     }
3009 }
3010
3011 pub fn type_is_structural(ty: Ty) -> bool {
3012     match ty.sty {
3013       ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) |
3014       ty_vec(_, Some(_)) | ty_unboxed_closure(..) => true,
3015       _ => type_is_slice(ty) | type_is_trait(ty)
3016     }
3017 }
3018
3019 pub fn type_is_simd(cx: &ctxt, ty: Ty) -> bool {
3020     match ty.sty {
3021         ty_struct(did, _) => lookup_simd(cx, did),
3022         _ => false
3023     }
3024 }
3025
3026 pub fn sequence_element_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3027     match ty.sty {
3028         ty_vec(ty, _) => ty,
3029         ty_str => mk_mach_uint(cx, ast::TyU8),
3030         ty_open(ty) => sequence_element_type(cx, ty),
3031         _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}",
3032                                  ty_to_string(cx, ty))[]),
3033     }
3034 }
3035
3036 pub fn simd_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3037     match ty.sty {
3038         ty_struct(did, substs) => {
3039             let fields = lookup_struct_fields(cx, did);
3040             lookup_field_type(cx, did, fields[0].id, substs)
3041         }
3042         _ => panic!("simd_type called on invalid type")
3043     }
3044 }
3045
3046 pub fn simd_size(cx: &ctxt, ty: Ty) -> uint {
3047     match ty.sty {
3048         ty_struct(did, _) => {
3049             let fields = lookup_struct_fields(cx, did);
3050             fields.len()
3051         }
3052         _ => panic!("simd_size called on invalid type")
3053     }
3054 }
3055
3056 pub fn type_is_region_ptr(ty: Ty) -> bool {
3057     match ty.sty {
3058         ty_rptr(..) => true,
3059         _ => false
3060     }
3061 }
3062
3063 pub fn type_is_unsafe_ptr(ty: Ty) -> bool {
3064     match ty.sty {
3065       ty_ptr(_) => return true,
3066       _ => return false
3067     }
3068 }
3069
3070 pub fn type_is_unique(ty: Ty) -> bool {
3071     match ty.sty {
3072         ty_uniq(_) => match ty.sty {
3073             ty_trait(..) => false,
3074             _ => true
3075         },
3076         _ => false
3077     }
3078 }
3079
3080 /*
3081  A scalar type is one that denotes an atomic datum, with no sub-components.
3082  (A ty_ptr is scalar because it represents a non-managed pointer, so its
3083  contents are abstract to rustc.)
3084 */
3085 pub fn type_is_scalar(ty: Ty) -> bool {
3086     match ty.sty {
3087       ty_bool | ty_char | ty_int(_) | ty_float(_) | ty_uint(_) |
3088       ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) |
3089       ty_bare_fn(..) | ty_ptr(_) => true,
3090       ty_tup(ref tys) if tys.is_empty() => true,
3091       _ => false
3092     }
3093 }
3094
3095 /// Returns true if this type is a floating point type and false otherwise.
3096 pub fn type_is_floating_point(ty: Ty) -> bool {
3097     match ty.sty {
3098         ty_float(_) => true,
3099         _ => false,
3100     }
3101 }
3102
3103 /// Type contents is how the type checker reasons about kinds.
3104 /// They track what kinds of things are found within a type.  You can
3105 /// think of them as kind of an "anti-kind".  They track the kinds of values
3106 /// and thinks that are contained in types.  Having a larger contents for
3107 /// a type tends to rule that type *out* from various kinds.  For example,
3108 /// a type that contains a reference is not sendable.
3109 ///
3110 /// The reason we compute type contents and not kinds is that it is
3111 /// easier for me (nmatsakis) to think about what is contained within
3112 /// a type than to think about what is *not* contained within a type.
3113 #[deriving(Clone, Copy)]
3114 pub struct TypeContents {
3115     pub bits: u64
3116 }
3117
3118 macro_rules! def_type_content_sets {
3119     (mod $mname:ident { $($name:ident = $bits:expr),+ }) => {
3120         #[allow(non_snake_case)]
3121         mod $mname {
3122             use middle::ty::TypeContents;
3123             $(
3124                 #[allow(non_upper_case_globals)]
3125                 pub const $name: TypeContents = TypeContents { bits: $bits };
3126              )+
3127         }
3128     }
3129 }
3130
3131 def_type_content_sets! {
3132     mod TC {
3133         None                                = 0b0000_0000__0000_0000__0000,
3134
3135         // Things that are interior to the value (first nibble):
3136         InteriorUnsized                     = 0b0000_0000__0000_0000__0001,
3137         InteriorUnsafe                      = 0b0000_0000__0000_0000__0010,
3138         InteriorParam                       = 0b0000_0000__0000_0000__0100,
3139         // InteriorAll                         = 0b00000000__00000000__1111,
3140
3141         // Things that are owned by the value (second and third nibbles):
3142         OwnsOwned                           = 0b0000_0000__0000_0001__0000,
3143         OwnsDtor                            = 0b0000_0000__0000_0010__0000,
3144         OwnsManaged /* see [1] below */     = 0b0000_0000__0000_0100__0000,
3145         OwnsAll                             = 0b0000_0000__1111_1111__0000,
3146
3147         // Things that are reachable by the value in any way (fourth nibble):
3148         ReachesBorrowed                     = 0b0000_0010__0000_0000__0000,
3149         // ReachesManaged /* see [1] below */  = 0b0000_0100__0000_0000__0000,
3150         ReachesMutable                      = 0b0000_1000__0000_0000__0000,
3151         ReachesFfiUnsafe                    = 0b0010_0000__0000_0000__0000,
3152         ReachesAll                          = 0b0011_1111__0000_0000__0000,
3153
3154         // Things that mean drop glue is necessary
3155         NeedsDrop                           = 0b0000_0000__0000_0111__0000,
3156
3157         // Things that prevent values from being considered sized
3158         Nonsized                            = 0b0000_0000__0000_0000__0001,
3159
3160         // Bits to set when a managed value is encountered
3161         //
3162         // [1] Do not set the bits TC::OwnsManaged or
3163         //     TC::ReachesManaged directly, instead reference
3164         //     TC::Managed to set them both at once.
3165         Managed                             = 0b0000_0100__0000_0100__0000,
3166
3167         // All bits
3168         All                                 = 0b1111_1111__1111_1111__1111
3169     }
3170 }
3171
3172 impl TypeContents {
3173     pub fn when(&self, cond: bool) -> TypeContents {
3174         if cond {*self} else {TC::None}
3175     }
3176
3177     pub fn intersects(&self, tc: TypeContents) -> bool {
3178         (self.bits & tc.bits) != 0
3179     }
3180
3181     pub fn owns_managed(&self) -> bool {
3182         self.intersects(TC::OwnsManaged)
3183     }
3184
3185     pub fn owns_owned(&self) -> bool {
3186         self.intersects(TC::OwnsOwned)
3187     }
3188
3189     pub fn is_sized(&self, _: &ctxt) -> bool {
3190         !self.intersects(TC::Nonsized)
3191     }
3192
3193     pub fn interior_param(&self) -> bool {
3194         self.intersects(TC::InteriorParam)
3195     }
3196
3197     pub fn interior_unsafe(&self) -> bool {
3198         self.intersects(TC::InteriorUnsafe)
3199     }
3200
3201     pub fn interior_unsized(&self) -> bool {
3202         self.intersects(TC::InteriorUnsized)
3203     }
3204
3205     pub fn needs_drop(&self, _: &ctxt) -> bool {
3206         self.intersects(TC::NeedsDrop)
3207     }
3208
3209     /// Includes only those bits that still apply when indirected through a `Box` pointer
3210     pub fn owned_pointer(&self) -> TypeContents {
3211         TC::OwnsOwned | (
3212             *self & (TC::OwnsAll | TC::ReachesAll))
3213     }
3214
3215     /// Includes only those bits that still apply when indirected through a reference (`&`)
3216     pub fn reference(&self, bits: TypeContents) -> TypeContents {
3217         bits | (
3218             *self & TC::ReachesAll)
3219     }
3220
3221     /// Includes only those bits that still apply when indirected through a managed pointer (`@`)
3222     pub fn managed_pointer(&self) -> TypeContents {
3223         TC::Managed | (
3224             *self & TC::ReachesAll)
3225     }
3226
3227     /// Includes only those bits that still apply when indirected through an unsafe pointer (`*`)
3228     pub fn unsafe_pointer(&self) -> TypeContents {
3229         *self & TC::ReachesAll
3230     }
3231
3232     pub fn union<T, F>(v: &[T], mut f: F) -> TypeContents where
3233         F: FnMut(&T) -> TypeContents,
3234     {
3235         v.iter().fold(TC::None, |tc, ty| tc | f(ty))
3236     }
3237
3238     pub fn has_dtor(&self) -> bool {
3239         self.intersects(TC::OwnsDtor)
3240     }
3241 }
3242
3243 impl ops::BitOr<TypeContents,TypeContents> for TypeContents {
3244     fn bitor(self, other: TypeContents) -> TypeContents {
3245         TypeContents {bits: self.bits | other.bits}
3246     }
3247 }
3248
3249 impl ops::BitAnd<TypeContents, TypeContents> for TypeContents {
3250     fn bitand(self, other: TypeContents) -> TypeContents {
3251         TypeContents {bits: self.bits & other.bits}
3252     }
3253 }
3254
3255 impl ops::Sub<TypeContents, TypeContents> for TypeContents {
3256     fn sub(self, other: TypeContents) -> TypeContents {
3257         TypeContents {bits: self.bits & !other.bits}
3258     }
3259 }
3260
3261 impl fmt::Show for TypeContents {
3262     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3263         write!(f, "TypeContents({:b})", self.bits)
3264     }
3265 }
3266
3267 pub fn type_interior_is_unsafe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3268     type_contents(cx, ty).interior_unsafe()
3269 }
3270
3271 pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents {
3272     return memoized(&cx.tc_cache, ty, |ty| {
3273         tc_ty(cx, ty, &mut FnvHashMap::new())
3274     });
3275
3276     fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
3277                    ty: Ty<'tcx>,
3278                    cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3279     {
3280         // Subtle: Note that we are *not* using cx.tc_cache here but rather a
3281         // private cache for this walk.  This is needed in the case of cyclic
3282         // types like:
3283         //
3284         //     struct List { next: Box<Option<List>>, ... }
3285         //
3286         // When computing the type contents of such a type, we wind up deeply
3287         // recursing as we go.  So when we encounter the recursive reference
3288         // to List, we temporarily use TC::None as its contents.  Later we'll
3289         // patch up the cache with the correct value, once we've computed it
3290         // (this is basically a co-inductive process, if that helps).  So in
3291         // the end we'll compute TC::OwnsOwned, in this case.
3292         //
3293         // The problem is, as we are doing the computation, we will also
3294         // compute an *intermediate* contents for, e.g., Option<List> of
3295         // TC::None.  This is ok during the computation of List itself, but if
3296         // we stored this intermediate value into cx.tc_cache, then later
3297         // requests for the contents of Option<List> would also yield TC::None
3298         // which is incorrect.  This value was computed based on the crutch
3299         // value for the type contents of list.  The correct value is
3300         // TC::OwnsOwned.  This manifested as issue #4821.
3301         match cache.get(&ty) {
3302             Some(tc) => { return *tc; }
3303             None => {}
3304         }
3305         match cx.tc_cache.borrow().get(&ty) {    // Must check both caches!
3306             Some(tc) => { return *tc; }
3307             None => {}
3308         }
3309         cache.insert(ty, TC::None);
3310
3311         let result = match ty.sty {
3312             // uint and int are ffi-unsafe
3313             ty_uint(ast::TyU) | ty_int(ast::TyI) => {
3314                 TC::ReachesFfiUnsafe
3315             }
3316
3317             // Scalar and unique types are sendable, and durable
3318             ty_infer(ty::FreshIntTy(_)) |
3319             ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
3320             ty_bare_fn(..) | ty::ty_char => {
3321                 TC::None
3322             }
3323
3324             ty_closure(ref c) => {
3325                 closure_contents(&**c) | TC::ReachesFfiUnsafe
3326             }
3327
3328             ty_uniq(typ) => {
3329                 TC::ReachesFfiUnsafe | match typ.sty {
3330                     ty_str => TC::OwnsOwned,
3331                     _ => tc_ty(cx, typ, cache).owned_pointer(),
3332                 }
3333             }
3334
3335             ty_trait(box TyTrait { ref bounds, .. }) => {
3336                 object_contents(bounds) | TC::ReachesFfiUnsafe | TC::Nonsized
3337             }
3338
3339             ty_ptr(ref mt) => {
3340                 tc_ty(cx, mt.ty, cache).unsafe_pointer()
3341             }
3342
3343             ty_rptr(r, ref mt) => {
3344                 TC::ReachesFfiUnsafe | match mt.ty.sty {
3345                     ty_str => borrowed_contents(*r, ast::MutImmutable),
3346                     ty_vec(..) => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r,
3347                                                                                       mt.mutbl)),
3348                     _ => tc_ty(cx, mt.ty, cache).reference(borrowed_contents(*r, mt.mutbl)),
3349                 }
3350             }
3351
3352             ty_vec(ty, Some(_)) => {
3353                 tc_ty(cx, ty, cache)
3354             }
3355
3356             ty_vec(ty, None) => {
3357                 tc_ty(cx, ty, cache) | TC::Nonsized
3358             }
3359             ty_str => TC::Nonsized,
3360
3361             ty_struct(did, substs) => {
3362                 let flds = struct_fields(cx, did, substs);
3363                 let mut res =
3364                     TypeContents::union(flds[],
3365                                         |f| tc_mt(cx, f.mt, cache));
3366
3367                 if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) {
3368                     res = res | TC::ReachesFfiUnsafe;
3369                 }
3370
3371                 if ty::has_dtor(cx, did) {
3372                     res = res | TC::OwnsDtor;
3373                 }
3374                 apply_lang_items(cx, did, res)
3375             }
3376
3377             ty_unboxed_closure(did, r, substs) => {
3378                 // FIXME(#14449): `borrowed_contents` below assumes `&mut`
3379                 // unboxed closure.
3380                 let upvars = unboxed_closure_upvars(cx, did, substs).unwrap();
3381                 TypeContents::union(upvars.as_slice(),
3382                                     |f| tc_ty(cx, f.ty, cache))
3383                     | borrowed_contents(*r, MutMutable)
3384             }
3385
3386             ty_tup(ref tys) => {
3387                 TypeContents::union(tys[],
3388                                     |ty| tc_ty(cx, *ty, cache))
3389             }
3390
3391             ty_enum(did, substs) => {
3392                 let variants = substd_enum_variants(cx, did, substs);
3393                 let mut res =
3394                     TypeContents::union(variants[], |variant| {
3395                         TypeContents::union(variant.args[],
3396                                             |arg_ty| {
3397                             tc_ty(cx, *arg_ty, cache)
3398                         })
3399                     });
3400
3401                 if ty::has_dtor(cx, did) {
3402                     res = res | TC::OwnsDtor;
3403                 }
3404
3405                 if variants.len() != 0 {
3406                     let repr_hints = lookup_repr_hints(cx, did);
3407                     if repr_hints.len() > 1 {
3408                         // this is an error later on, but this type isn't safe
3409                         res = res | TC::ReachesFfiUnsafe;
3410                     }
3411
3412                     match repr_hints.get(0) {
3413                         Some(h) => if !h.is_ffi_safe() {
3414                             res = res | TC::ReachesFfiUnsafe;
3415                         },
3416                         // ReprAny
3417                         None => {
3418                             res = res | TC::ReachesFfiUnsafe;
3419
3420                             // We allow ReprAny enums if they are eligible for
3421                             // the nullable pointer optimization and the
3422                             // contained type is an `extern fn`
3423
3424                             if variants.len() == 2 {
3425                                 let mut data_idx = 0;
3426
3427                                 if variants[0].args.len() == 0 {
3428                                     data_idx = 1;
3429                                 }
3430
3431                                 if variants[data_idx].args.len() == 1 {
3432                                     match variants[data_idx].args[0].sty {
3433                                         ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; }
3434                                         _ => { }
3435                                     }
3436                                 }
3437                             }
3438                         }
3439                     }
3440                 }
3441
3442
3443                 apply_lang_items(cx, did, res)
3444             }
3445
3446             ty_projection(..) |
3447             ty_param(_) => {
3448                 TC::All
3449             }
3450
3451             ty_open(ty) => {
3452                 let result = tc_ty(cx, ty, cache);
3453                 assert!(!result.is_sized(cx));
3454                 result.unsafe_pointer() | TC::Nonsized
3455             }
3456
3457             ty_infer(_) |
3458             ty_err => {
3459                 cx.sess.bug("asked to compute contents of error type");
3460             }
3461         };
3462
3463         cache.insert(ty, result);
3464         result
3465     }
3466
3467     fn tc_mt<'tcx>(cx: &ctxt<'tcx>,
3468                    mt: mt<'tcx>,
3469                    cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
3470     {
3471         let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
3472         mc | tc_ty(cx, mt.ty, cache)
3473     }
3474
3475     fn apply_lang_items(cx: &ctxt, did: ast::DefId, tc: TypeContents)
3476                         -> TypeContents {
3477         if Some(did) == cx.lang_items.managed_bound() {
3478             tc | TC::Managed
3479         } else if Some(did) == cx.lang_items.unsafe_type() {
3480             tc | TC::InteriorUnsafe
3481         } else {
3482             tc
3483         }
3484     }
3485
3486     /// Type contents due to containing a reference with the region `region` and borrow kind `bk`
3487     fn borrowed_contents(region: ty::Region,
3488                          mutbl: ast::Mutability)
3489                          -> TypeContents {
3490         let b = match mutbl {
3491             ast::MutMutable => TC::ReachesMutable,
3492             ast::MutImmutable => TC::None,
3493         };
3494         b | (TC::ReachesBorrowed).when(region != ty::ReStatic)
3495     }
3496
3497     fn closure_contents(cty: &ClosureTy) -> TypeContents {
3498         // Closure contents are just like trait contents, but with potentially
3499         // even more stuff.
3500         let st = object_contents(&cty.bounds);
3501
3502         let st = match cty.store {
3503             UniqTraitStore => {
3504                 st.owned_pointer()
3505             }
3506             RegionTraitStore(r, mutbl) => {
3507                 st.reference(borrowed_contents(r, mutbl))
3508             }
3509         };
3510
3511         st
3512     }
3513
3514     fn object_contents(bounds: &ExistentialBounds) -> TypeContents {
3515         // These are the type contents of the (opaque) interior. We
3516         // make no assumptions (other than that it cannot have an
3517         // in-scope type parameter within, which makes no sense).
3518         let mut tc = TC::All - TC::InteriorParam;
3519         for bound in bounds.builtin_bounds.iter() {
3520             tc = tc - match bound {
3521                 BoundSync | BoundSend | BoundCopy => TC::None,
3522                 BoundSized => TC::Nonsized,
3523             };
3524         }
3525         return tc;
3526     }
3527 }
3528
3529 fn type_impls_bound<'tcx>(cx: &ctxt<'tcx>,
3530                           cache: &RefCell<HashMap<Ty<'tcx>,bool>>,
3531                           param_env: &ParameterEnvironment<'tcx>,
3532                           ty: Ty<'tcx>,
3533                           bound: ty::BuiltinBound)
3534                           -> bool
3535 {
3536     assert!(!ty::type_needs_infer(ty));
3537
3538     if !type_has_params(ty) && !type_has_self(ty) {
3539         match cache.borrow().get(&ty) {
3540             None => {}
3541             Some(&result) => {
3542                 debug!("type_impls_bound({}, {}) = {} (cached)",
3543                        ty_to_string(cx, ty),
3544                        bound,
3545                        result);
3546                 return result
3547             }
3548         }
3549     }
3550
3551     let infcx = infer::new_infer_ctxt(cx);
3552     let is_impld = traits::type_known_to_meet_builtin_bound(&infcx, param_env, ty, bound);
3553
3554     debug!("type_impls_bound({}, {}) = {}",
3555            ty_to_string(cx, ty),
3556            bound,
3557            is_impld);
3558
3559     if !type_has_params(ty) && !type_has_self(ty) {
3560         let old_value = cache.borrow_mut().insert(ty, is_impld);
3561         assert!(old_value.is_none());
3562     }
3563
3564     is_impld
3565 }
3566
3567 pub fn type_moves_by_default<'tcx>(cx: &ctxt<'tcx>,
3568                                    ty: Ty<'tcx>,
3569                                    param_env: &ParameterEnvironment<'tcx>)
3570                                    -> bool
3571 {
3572     !type_impls_bound(cx, &cx.type_impls_copy_cache, param_env, ty, ty::BoundCopy)
3573 }
3574
3575 pub fn type_is_sized<'tcx>(cx: &ctxt<'tcx>,
3576                            ty: Ty<'tcx>,
3577                            param_env: &ParameterEnvironment<'tcx>)
3578                            -> bool
3579 {
3580     type_impls_bound(cx, &cx.type_impls_sized_cache, param_env, ty, ty::BoundSized)
3581 }
3582
3583 pub fn is_ffi_safe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
3584     !type_contents(cx, ty).intersects(TC::ReachesFfiUnsafe)
3585 }
3586
3587 // True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
3588 pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
3589     fn type_requires<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3590                            r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3591         debug!("type_requires({}, {})?",
3592                ::util::ppaux::ty_to_string(cx, r_ty),
3593                ::util::ppaux::ty_to_string(cx, ty));
3594
3595         let r = r_ty == ty || subtypes_require(cx, seen, r_ty, ty);
3596
3597         debug!("type_requires({}, {})? {}",
3598                ::util::ppaux::ty_to_string(cx, r_ty),
3599                ::util::ppaux::ty_to_string(cx, ty),
3600                r);
3601         return r;
3602     }
3603
3604     fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
3605                               r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool {
3606         debug!("subtypes_require({}, {})?",
3607                ::util::ppaux::ty_to_string(cx, r_ty),
3608                ::util::ppaux::ty_to_string(cx, ty));
3609
3610         let r = match ty.sty {
3611             // fixed length vectors need special treatment compared to
3612             // normal vectors, since they don't necessarily have the
3613             // possibility to have length zero.
3614             ty_vec(_, Some(0)) => false, // don't need no contents
3615             ty_vec(ty, Some(_)) => type_requires(cx, seen, r_ty, ty),
3616
3617             ty_bool |
3618             ty_char |
3619             ty_int(_) |
3620             ty_uint(_) |
3621             ty_float(_) |
3622             ty_str |
3623             ty_bare_fn(..) |
3624             ty_closure(_) |
3625             ty_infer(_) |
3626             ty_err |
3627             ty_param(_) |
3628             ty_projection(_) |
3629             ty_vec(_, None) => {
3630                 false
3631             }
3632             ty_uniq(typ) | ty_open(typ) => {
3633                 type_requires(cx, seen, r_ty, typ)
3634             }
3635             ty_rptr(_, ref mt) => {
3636                 type_requires(cx, seen, r_ty, mt.ty)
3637             }
3638
3639             ty_ptr(..) => {
3640                 false           // unsafe ptrs can always be NULL
3641             }
3642
3643             ty_trait(..) => {
3644                 false
3645             }
3646
3647             ty_struct(ref did, _) if seen.contains(did) => {
3648                 false
3649             }
3650
3651             ty_struct(did, substs) => {
3652                 seen.push(did);
3653                 let fields = struct_fields(cx, did, substs);
3654                 let r = fields.iter().any(|f| type_requires(cx, seen, r_ty, f.mt.ty));
3655                 seen.pop().unwrap();
3656                 r
3657             }
3658
3659             ty_unboxed_closure(did, _, substs) => {
3660                 let upvars = unboxed_closure_upvars(cx, did, substs).unwrap();
3661                 upvars.iter().any(|f| type_requires(cx, seen, r_ty, f.ty))
3662             }
3663
3664             ty_tup(ref ts) => {
3665                 ts.iter().any(|ty| type_requires(cx, seen, r_ty, *ty))
3666             }
3667
3668             ty_enum(ref did, _) if seen.contains(did) => {
3669                 false
3670             }
3671
3672             ty_enum(did, substs) => {
3673                 seen.push(did);
3674                 let vs = enum_variants(cx, did);
3675                 let r = !vs.is_empty() && vs.iter().all(|variant| {
3676                     variant.args.iter().any(|aty| {
3677                         let sty = aty.subst(cx, substs);
3678                         type_requires(cx, seen, r_ty, sty)
3679                     })
3680                 });
3681                 seen.pop().unwrap();
3682                 r
3683             }
3684         };
3685
3686         debug!("subtypes_require({}, {})? {}",
3687                ::util::ppaux::ty_to_string(cx, r_ty),
3688                ::util::ppaux::ty_to_string(cx, ty),
3689                r);
3690
3691         return r;
3692     }
3693
3694     let mut seen = Vec::new();
3695     !subtypes_require(cx, &mut seen, r_ty, r_ty)
3696 }
3697
3698 /// Describes whether a type is representable. For types that are not
3699 /// representable, 'SelfRecursive' and 'ContainsRecursive' are used to
3700 /// distinguish between types that are recursive with themselves and types that
3701 /// contain a different recursive type. These cases can therefore be treated
3702 /// differently when reporting errors.
3703 ///
3704 /// The ordering of the cases is significant. They are sorted so that cmp::max
3705 /// will keep the "more erroneous" of two values.
3706 #[deriving(Copy, PartialOrd, Ord, Eq, PartialEq, Show)]
3707 pub enum Representability {
3708     Representable,
3709     ContainsRecursive,
3710     SelfRecursive,
3711 }
3712
3713 /// Check whether a type is representable. This means it cannot contain unboxed
3714 /// structural recursion. This check is needed for structs and enums.
3715 pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>)
3716                                    -> Representability {
3717
3718     // Iterate until something non-representable is found
3719     fn find_nonrepresentable<'tcx, It: Iterator<Item=Ty<'tcx>>>(cx: &ctxt<'tcx>, sp: Span,
3720                                                                 seen: &mut Vec<Ty<'tcx>>,
3721                                                                 iter: It)
3722                                                                 -> Representability {
3723         iter.fold(Representable,
3724                   |r, ty| cmp::max(r, is_type_structurally_recursive(cx, sp, seen, ty)))
3725     }
3726
3727     fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3728                                        seen: &mut Vec<Ty<'tcx>>, ty: Ty<'tcx>)
3729                                        -> Representability {
3730         match ty.sty {
3731             ty_tup(ref ts) => {
3732                 find_nonrepresentable(cx, sp, seen, ts.iter().map(|ty| *ty))
3733             }
3734             // Fixed-length vectors.
3735             // FIXME(#11924) Behavior undecided for zero-length vectors.
3736             ty_vec(ty, Some(_)) => {
3737                 is_type_structurally_recursive(cx, sp, seen, ty)
3738             }
3739             ty_struct(did, substs) => {
3740                 let fields = struct_fields(cx, did, substs);
3741                 find_nonrepresentable(cx, sp, seen, fields.iter().map(|f| f.mt.ty))
3742             }
3743             ty_enum(did, substs) => {
3744                 let vs = enum_variants(cx, did);
3745                 let iter = vs.iter()
3746                     .flat_map(|variant| { variant.args.iter() })
3747                     .map(|aty| { aty.subst_spanned(cx, substs, Some(sp)) });
3748
3749                 find_nonrepresentable(cx, sp, seen, iter)
3750             }
3751             ty_unboxed_closure(did, _, substs) => {
3752                 let upvars = unboxed_closure_upvars(cx, did, substs).unwrap();
3753                 find_nonrepresentable(cx, sp, seen, upvars.iter().map(|f| f.ty))
3754             }
3755             _ => Representable,
3756         }
3757     }
3758
3759     fn same_struct_or_enum_def_id(ty: Ty, did: DefId) -> bool {
3760         match ty.sty {
3761             ty_struct(ty_did, _) | ty_enum(ty_did, _) => {
3762                  ty_did == did
3763             }
3764             _ => false
3765         }
3766     }
3767
3768     fn same_type<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
3769         match (&a.sty, &b.sty) {
3770             (&ty_struct(did_a, ref substs_a), &ty_struct(did_b, ref substs_b)) |
3771             (&ty_enum(did_a, ref substs_a), &ty_enum(did_b, ref substs_b)) => {
3772                 if did_a != did_b {
3773                     return false;
3774                 }
3775
3776                 let types_a = substs_a.types.get_slice(subst::TypeSpace);
3777                 let types_b = substs_b.types.get_slice(subst::TypeSpace);
3778
3779                 let pairs = types_a.iter().zip(types_b.iter());
3780
3781                 pairs.all(|(&a, &b)| same_type(a, b))
3782             }
3783             _ => {
3784                 a == b
3785             }
3786         }
3787     }
3788
3789     // Does the type `ty` directly (without indirection through a pointer)
3790     // contain any types on stack `seen`?
3791     fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
3792                                             seen: &mut Vec<Ty<'tcx>>,
3793                                             ty: Ty<'tcx>) -> Representability {
3794         debug!("is_type_structurally_recursive: {}",
3795                ::util::ppaux::ty_to_string(cx, ty));
3796
3797         match ty.sty {
3798             ty_struct(did, _) | ty_enum(did, _) => {
3799                 {
3800                     // Iterate through stack of previously seen types.
3801                     let mut iter = seen.iter();
3802
3803                     // The first item in `seen` is the type we are actually curious about.
3804                     // We want to return SelfRecursive if this type contains itself.
3805                     // It is important that we DON'T take generic parameters into account
3806                     // for this check, so that Bar<T> in this example counts as SelfRecursive:
3807                     //
3808                     // struct Foo;
3809                     // struct Bar<T> { x: Bar<Foo> }
3810
3811                     match iter.next() {
3812                         Some(&seen_type) => {
3813                             if same_struct_or_enum_def_id(seen_type, did) {
3814                                 debug!("SelfRecursive: {} contains {}",
3815                                        ::util::ppaux::ty_to_string(cx, seen_type),
3816                                        ::util::ppaux::ty_to_string(cx, ty));
3817                                 return SelfRecursive;
3818                             }
3819                         }
3820                         None => {}
3821                     }
3822
3823                     // We also need to know whether the first item contains other types that
3824                     // are structurally recursive. If we don't catch this case, we will recurse
3825                     // infinitely for some inputs.
3826                     //
3827                     // It is important that we DO take generic parameters into account here,
3828                     // so that code like this is considered SelfRecursive, not ContainsRecursive:
3829                     //
3830                     // struct Foo { Option<Option<Foo>> }
3831
3832                     for &seen_type in iter {
3833                         if same_type(ty, seen_type) {
3834                             debug!("ContainsRecursive: {} contains {}",
3835                                    ::util::ppaux::ty_to_string(cx, seen_type),
3836                                    ::util::ppaux::ty_to_string(cx, ty));
3837                             return ContainsRecursive;
3838                         }
3839                     }
3840                 }
3841
3842                 // For structs and enums, track all previously seen types by pushing them
3843                 // onto the 'seen' stack.
3844                 seen.push(ty);
3845                 let out = are_inner_types_recursive(cx, sp, seen, ty);
3846                 seen.pop();
3847                 out
3848             }
3849             _ => {
3850                 // No need to push in other cases.
3851                 are_inner_types_recursive(cx, sp, seen, ty)
3852             }
3853         }
3854     }
3855
3856     debug!("is_type_representable: {}",
3857            ::util::ppaux::ty_to_string(cx, ty));
3858
3859     // To avoid a stack overflow when checking an enum variant or struct that
3860     // contains a different, structurally recursive type, maintain a stack
3861     // of seen types and check recursion for each of them (issues #3008, #3779).
3862     let mut seen: Vec<Ty> = Vec::new();
3863     let r = is_type_structurally_recursive(cx, sp, &mut seen, ty);
3864     debug!("is_type_representable: {} is {}",
3865            ::util::ppaux::ty_to_string(cx, ty), r);
3866     r
3867 }
3868
3869 pub fn type_is_trait(ty: Ty) -> bool {
3870     type_trait_info(ty).is_some()
3871 }
3872
3873 pub fn type_trait_info<'tcx>(ty: Ty<'tcx>) -> Option<&'tcx TyTrait<'tcx>> {
3874     match ty.sty {
3875         ty_uniq(ty) | ty_rptr(_, mt { ty, ..}) | ty_ptr(mt { ty, ..}) => match ty.sty {
3876             ty_trait(ref t) => Some(&**t),
3877             _ => None
3878         },
3879         ty_trait(ref t) => Some(&**t),
3880         _ => None
3881     }
3882 }
3883
3884 pub fn type_is_integral(ty: Ty) -> bool {
3885     match ty.sty {
3886       ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
3887       _ => false
3888     }
3889 }
3890
3891 pub fn type_is_fresh(ty: Ty) -> bool {
3892     match ty.sty {
3893       ty_infer(FreshTy(_)) => true,
3894       ty_infer(FreshIntTy(_)) => true,
3895       _ => false
3896     }
3897 }
3898
3899 pub fn type_is_uint(ty: Ty) -> bool {
3900     match ty.sty {
3901       ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
3902       _ => false
3903     }
3904 }
3905
3906 pub fn type_is_char(ty: Ty) -> bool {
3907     match ty.sty {
3908         ty_char => true,
3909         _ => false
3910     }
3911 }
3912
3913 pub fn type_is_bare_fn(ty: Ty) -> bool {
3914     match ty.sty {
3915         ty_bare_fn(..) => true,
3916         _ => false
3917     }
3918 }
3919
3920 pub fn type_is_bare_fn_item(ty: Ty) -> bool {
3921     match ty.sty {
3922         ty_bare_fn(Some(_), _) => true,
3923         _ => false
3924     }
3925 }
3926
3927 pub fn type_is_fp(ty: Ty) -> bool {
3928     match ty.sty {
3929       ty_infer(FloatVar(_)) | ty_float(_) => true,
3930       _ => false
3931     }
3932 }
3933
3934 pub fn type_is_numeric(ty: Ty) -> bool {
3935     return type_is_integral(ty) || type_is_fp(ty);
3936 }
3937
3938 pub fn type_is_signed(ty: Ty) -> bool {
3939     match ty.sty {
3940       ty_int(_) => true,
3941       _ => false
3942     }
3943 }
3944
3945 pub fn type_is_machine(ty: Ty) -> bool {
3946     match ty.sty {
3947         ty_int(ast::TyI) | ty_uint(ast::TyU) => false,
3948         ty_int(..) | ty_uint(..) | ty_float(..) => true,
3949         _ => false
3950     }
3951 }
3952
3953 // Whether a type is enum like, that is an enum type with only nullary
3954 // constructors
3955 pub fn type_is_c_like_enum(cx: &ctxt, ty: Ty) -> bool {
3956     match ty.sty {
3957         ty_enum(did, _) => {
3958             let variants = enum_variants(cx, did);
3959             if variants.len() == 0 {
3960                 false
3961             } else {
3962                 variants.iter().all(|v| v.args.len() == 0)
3963             }
3964         }
3965         _ => false
3966     }
3967 }
3968
3969 // Returns the type and mutability of *ty.
3970 //
3971 // The parameter `explicit` indicates if this is an *explicit* dereference.
3972 // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
3973 pub fn deref<'tcx>(ty: Ty<'tcx>, explicit: bool) -> Option<mt<'tcx>> {
3974     match ty.sty {
3975         ty_uniq(ty) => {
3976             Some(mt {
3977                 ty: ty,
3978                 mutbl: ast::MutImmutable,
3979             })
3980         },
3981         ty_rptr(_, mt) => Some(mt),
3982         ty_ptr(mt) if explicit => Some(mt),
3983         _ => None
3984     }
3985 }
3986
3987 pub fn close_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
3988     match ty.sty {
3989         ty_open(ty) => mk_rptr(cx, cx.mk_region(ReStatic), mt {ty: ty, mutbl:ast::MutImmutable}),
3990         _ => cx.sess.bug(format!("Trying to close a non-open type {}",
3991                                  ty_to_string(cx, ty))[])
3992     }
3993 }
3994
3995 pub fn type_content<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
3996     match ty.sty {
3997         ty_uniq(ty) => ty,
3998         ty_rptr(_, mt) |ty_ptr(mt) => mt.ty,
3999         _ => ty
4000     }
4001 }
4002
4003 // Extract the unsized type in an open type (or just return ty if it is not open).
4004 pub fn unopen_type<'tcx>(ty: Ty<'tcx>) -> Ty<'tcx> {
4005     match ty.sty {
4006         ty_open(ty) => ty,
4007         _ => ty
4008     }
4009 }
4010
4011 // Returns the type of ty[i]
4012 pub fn index<'tcx>(ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4013     match ty.sty {
4014         ty_vec(ty, _) => Some(ty),
4015         _ => None
4016     }
4017 }
4018
4019 // Returns the type of elements contained within an 'array-like' type.
4020 // This is exactly the same as the above, except it supports strings,
4021 // which can't actually be indexed.
4022 pub fn array_element_ty<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
4023     match ty.sty {
4024         ty_vec(ty, _) => Some(ty),
4025         ty_str => Some(tcx.types.u8),
4026         _ => None
4027     }
4028 }
4029
4030 /// Returns the type of element at index `i` in tuple or tuple-like type `t`.
4031 /// For an enum `t`, `variant` is None only if `t` is a univariant enum.
4032 pub fn positional_element_ty<'tcx>(cx: &ctxt<'tcx>,
4033                                    ty: Ty<'tcx>,
4034                                    i: uint,
4035                                    variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4036
4037     match (&ty.sty, variant) {
4038         (&ty_tup(ref v), None) => v.get(i).map(|&t| t),
4039
4040
4041         (&ty_struct(def_id, substs), None) => lookup_struct_fields(cx, def_id)
4042             .get(i)
4043             .map(|&t|lookup_item_type(cx, t.id).ty.subst(cx, substs)),
4044
4045         (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4046             let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4047             variant_info.args.get(i).map(|t|t.subst(cx, substs))
4048         }
4049
4050         (&ty_enum(def_id, substs), None) => {
4051             assert!(enum_is_univariant(cx, def_id));
4052             let enum_variants = enum_variants(cx, def_id);
4053             let variant_info = &(*enum_variants)[0];
4054             variant_info.args.get(i).map(|t|t.subst(cx, substs))
4055         }
4056
4057         _ => None
4058     }
4059 }
4060
4061 /// Returns the type of element at field `n` in struct or struct-like type `t`.
4062 /// For an enum `t`, `variant` must be some def id.
4063 pub fn named_element_ty<'tcx>(cx: &ctxt<'tcx>,
4064                               ty: Ty<'tcx>,
4065                               n: ast::Name,
4066                               variant: Option<ast::DefId>) -> Option<Ty<'tcx>> {
4067
4068     match (&ty.sty, variant) {
4069         (&ty_struct(def_id, substs), None) => {
4070             let r = lookup_struct_fields(cx, def_id);
4071             r.iter().find(|f| f.name == n)
4072                 .map(|&f| lookup_field_type(cx, def_id, f.id, substs))
4073         }
4074         (&ty_enum(def_id, substs), Some(variant_def_id)) => {
4075             let variant_info = enum_variant_with_id(cx, def_id, variant_def_id);
4076             variant_info.arg_names.as_ref()
4077                 .expect("must have struct enum variant if accessing a named fields")
4078                 .iter().zip(variant_info.args.iter())
4079                 .find(|&(ident, _)| ident.name == n)
4080                 .map(|(_ident, arg_t)| arg_t.subst(cx, substs))
4081         }
4082         _ => None
4083     }
4084 }
4085
4086 pub fn node_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId)
4087                                   -> Rc<ty::TraitRef<'tcx>> {
4088     match cx.trait_refs.borrow().get(&id) {
4089         Some(ty) => ty.clone(),
4090         None => cx.sess.bug(
4091             format!("node_id_to_trait_ref: no trait ref for node `{}`",
4092                     cx.map.node_to_string(id))[])
4093     }
4094 }
4095
4096 pub fn try_node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Option<Ty<'tcx>> {
4097     cx.node_types.borrow().get(&id).cloned()
4098 }
4099
4100 pub fn node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Ty<'tcx> {
4101     match try_node_id_to_type(cx, id) {
4102        Some(ty) => ty,
4103        None => cx.sess.bug(
4104            format!("node_id_to_type: no type for node `{}`",
4105                    cx.map.node_to_string(id))[])
4106     }
4107 }
4108
4109 pub fn node_id_to_type_opt<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Option<Ty<'tcx>> {
4110     match cx.node_types.borrow().get(&id) {
4111        Some(&ty) => Some(ty),
4112        None => None
4113     }
4114 }
4115
4116 pub fn node_id_item_substs<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> ItemSubsts<'tcx> {
4117     match cx.item_substs.borrow().get(&id) {
4118       None => ItemSubsts::empty(),
4119       Some(ts) => ts.clone(),
4120     }
4121 }
4122
4123 pub fn fn_is_variadic(fty: Ty) -> bool {
4124     match fty.sty {
4125         ty_bare_fn(_, ref f) => f.sig.0.variadic,
4126         ty_closure(ref f) => f.sig.0.variadic,
4127         ref s => {
4128             panic!("fn_is_variadic() called on non-fn type: {}", s)
4129         }
4130     }
4131 }
4132
4133 pub fn ty_fn_sig<'tcx>(fty: Ty<'tcx>) -> &'tcx PolyFnSig<'tcx> {
4134     match fty.sty {
4135         ty_bare_fn(_, ref f) => &f.sig,
4136         ty_closure(ref f) => &f.sig,
4137         ref s => {
4138             panic!("ty_fn_sig() called on non-fn type: {}", s)
4139         }
4140     }
4141 }
4142
4143 /// Returns the ABI of the given function.
4144 pub fn ty_fn_abi(fty: Ty) -> abi::Abi {
4145     match fty.sty {
4146         ty_bare_fn(_, ref f) => f.abi,
4147         ty_closure(ref f) => f.abi,
4148         _ => panic!("ty_fn_abi() called on non-fn type"),
4149     }
4150 }
4151
4152 // Type accessors for substructures of types
4153 pub fn ty_fn_args<'tcx>(fty: Ty<'tcx>) -> &'tcx [Ty<'tcx>] {
4154     ty_fn_sig(fty).0.inputs.as_slice()
4155 }
4156
4157 pub fn ty_closure_store(fty: Ty) -> TraitStore {
4158     match fty.sty {
4159         ty_closure(ref f) => f.store,
4160         ty_unboxed_closure(..) => {
4161             // Close enough for the purposes of all the callers of this
4162             // function (which is soon to be deprecated anyhow).
4163             UniqTraitStore
4164         }
4165         ref s => {
4166             panic!("ty_closure_store() called on non-closure type: {}", s)
4167         }
4168     }
4169 }
4170
4171 pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> FnOutput<'tcx> {
4172     match fty.sty {
4173         ty_bare_fn(_, ref f) => f.sig.0.output,
4174         ty_closure(ref f) => f.sig.0.output,
4175         ref s => {
4176             panic!("ty_fn_ret() called on non-fn type: {}", s)
4177         }
4178     }
4179 }
4180
4181 pub fn is_fn_ty(fty: Ty) -> bool {
4182     match fty.sty {
4183         ty_bare_fn(..) => true,
4184         ty_closure(_) => true,
4185         _ => false
4186     }
4187 }
4188
4189 pub fn ty_region(tcx: &ctxt,
4190                  span: Span,
4191                  ty: Ty) -> Region {
4192     match ty.sty {
4193         ty_rptr(r, _) => *r,
4194         ref s => {
4195             tcx.sess.span_bug(
4196                 span,
4197                 format!("ty_region() invoked on an inappropriate ty: {}",
4198                         s)[]);
4199         }
4200     }
4201 }
4202
4203 pub fn free_region_from_def(free_id: ast::NodeId, def: &RegionParameterDef)
4204     -> ty::Region
4205 {
4206     ty::ReFree(ty::FreeRegion { scope: region::CodeExtent::from_node_id(free_id),
4207                                 bound_region: ty::BrNamed(def.def_id,
4208                                                           def.name) })
4209 }
4210
4211 // Returns the type of a pattern as a monotype. Like @expr_ty, this function
4212 // doesn't provide type parameter substitutions.
4213 pub fn pat_ty<'tcx>(cx: &ctxt<'tcx>, pat: &ast::Pat) -> Ty<'tcx> {
4214     return node_id_to_type(cx, pat.id);
4215 }
4216
4217
4218 // Returns the type of an expression as a monotype.
4219 //
4220 // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
4221 // some cases, we insert `AutoAdjustment` annotations such as auto-deref or
4222 // auto-ref.  The type returned by this function does not consider such
4223 // adjustments.  See `expr_ty_adjusted()` instead.
4224 //
4225 // NB (2): This type doesn't provide type parameter substitutions; e.g. if you
4226 // ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
4227 // instead of "fn(ty) -> T with T = int".
4228 pub fn expr_ty<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4229     return node_id_to_type(cx, expr.id);
4230 }
4231
4232 pub fn expr_ty_opt<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Option<Ty<'tcx>> {
4233     return node_id_to_type_opt(cx, expr.id);
4234 }
4235
4236 /// Returns the type of `expr`, considering any `AutoAdjustment`
4237 /// entry recorded for that expression.
4238 ///
4239 /// It would almost certainly be better to store the adjusted ty in with
4240 /// the `AutoAdjustment`, but I opted not to do this because it would
4241 /// require serializing and deserializing the type and, although that's not
4242 /// hard to do, I just hate that code so much I didn't want to touch it
4243 /// unless it was to fix it properly, which seemed a distraction from the
4244 /// task at hand! -nmatsakis
4245 pub fn expr_ty_adjusted<'tcx>(cx: &ctxt<'tcx>, expr: &ast::Expr) -> Ty<'tcx> {
4246     adjust_ty(cx, expr.span, expr.id, expr_ty(cx, expr),
4247               cx.adjustments.borrow().get(&expr.id),
4248               |method_call| cx.method_map.borrow().get(&method_call).map(|method| method.ty))
4249 }
4250
4251 pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
4252     match cx.map.find(id) {
4253         Some(ast_map::NodeExpr(e)) => {
4254             e.span
4255         }
4256         Some(f) => {
4257             cx.sess.bug(format!("Node id {} is not an expr: {}",
4258                                 id,
4259                                 f)[]);
4260         }
4261         None => {
4262             cx.sess.bug(format!("Node id {} is not present \
4263                                 in the node map", id)[]);
4264         }
4265     }
4266 }
4267
4268 pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
4269     match cx.map.find(id) {
4270         Some(ast_map::NodeLocal(pat)) => {
4271             match pat.node {
4272                 ast::PatIdent(_, ref path1, _) => {
4273                     token::get_ident(path1.node)
4274                 }
4275                 _ => {
4276                     cx.sess.bug(
4277                         format!("Variable id {} maps to {}, not local",
4278                                 id,
4279                                 pat)[]);
4280                 }
4281             }
4282         }
4283         r => {
4284             cx.sess.bug(format!("Variable id {} maps to {}, not local",
4285                                 id,
4286                                 r)[]);
4287         }
4288     }
4289 }
4290
4291 /// See `expr_ty_adjusted`
4292 pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>,
4293                           span: Span,
4294                           expr_id: ast::NodeId,
4295                           unadjusted_ty: Ty<'tcx>,
4296                           adjustment: Option<&AutoAdjustment<'tcx>>,
4297                           mut method_type: F)
4298                           -> Ty<'tcx> where
4299     F: FnMut(MethodCall) -> Option<Ty<'tcx>>,
4300 {
4301     if let ty_err = unadjusted_ty.sty {
4302         return unadjusted_ty;
4303     }
4304
4305     return match adjustment {
4306         Some(adjustment) => {
4307             match *adjustment {
4308                 AdjustAddEnv(_, store) => {
4309                     match unadjusted_ty.sty {
4310                         ty::ty_bare_fn(Some(_), ref b) => {
4311                             let bounds = ty::ExistentialBounds {
4312                                 region_bound: ReStatic,
4313                                 builtin_bounds: all_builtin_bounds(),
4314                                 projection_bounds: vec!(),
4315                             };
4316
4317                             ty::mk_closure(
4318                                 cx,
4319                                 ty::ClosureTy {unsafety: b.unsafety,
4320                                                onceness: ast::Many,
4321                                                store: store,
4322                                                bounds: bounds,
4323                                                sig: b.sig.clone(),
4324                                                abi: b.abi})
4325                         }
4326                         ref b => {
4327                             cx.sess.bug(
4328                                 format!("add_env adjustment on non-fn-item: \
4329                                          {}",
4330                                         b).as_slice());
4331                         }
4332                     }
4333                 }
4334
4335                 AdjustReifyFnPointer(_) => {
4336                     match unadjusted_ty.sty {
4337                         ty::ty_bare_fn(Some(_), b) => {
4338                             ty::mk_bare_fn(cx, None, b)
4339                         }
4340                         ref b => {
4341                             cx.sess.bug(
4342                                 format!("AdjustReifyFnPointer adjustment on non-fn-item: \
4343                                          {}",
4344                                         b)[]);
4345                         }
4346                     }
4347                 }
4348
4349                 AdjustDerefRef(ref adj) => {
4350                     let mut adjusted_ty = unadjusted_ty;
4351
4352                     if !ty::type_is_error(adjusted_ty) {
4353                         for i in range(0, adj.autoderefs) {
4354                             let method_call = MethodCall::autoderef(expr_id, i);
4355                             match method_type(method_call) {
4356                                 Some(method_ty) => {
4357                                     if let ty::FnConverging(result_type) = ty_fn_ret(method_ty) {
4358                                         adjusted_ty = result_type;
4359                                     }
4360                                 }
4361                                 None => {}
4362                             }
4363                             match deref(adjusted_ty, true) {
4364                                 Some(mt) => { adjusted_ty = mt.ty; }
4365                                 None => {
4366                                     cx.sess.span_bug(
4367                                         span,
4368                                         format!("the {}th autoderef failed: \
4369                                                 {}",
4370                                                 i,
4371                                                 ty_to_string(cx, adjusted_ty))
4372                                                           []);
4373                                 }
4374                             }
4375                         }
4376                     }
4377
4378                     adjust_ty_for_autoref(cx, span, adjusted_ty, adj.autoref.as_ref())
4379                 }
4380             }
4381         }
4382         None => unadjusted_ty
4383     };
4384 }
4385
4386 pub fn adjust_ty_for_autoref<'tcx>(cx: &ctxt<'tcx>,
4387                                    span: Span,
4388                                    ty: Ty<'tcx>,
4389                                    autoref: Option<&AutoRef<'tcx>>)
4390                                    -> Ty<'tcx>
4391 {
4392     match autoref {
4393         None => ty,
4394
4395         Some(&AutoPtr(r, m, ref a)) => {
4396             let adjusted_ty = match a {
4397                 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4398                 &None => ty
4399             };
4400             mk_rptr(cx, cx.mk_region(r), mt {
4401                 ty: adjusted_ty,
4402                 mutbl: m
4403             })
4404         }
4405
4406         Some(&AutoUnsafe(m, ref a)) => {
4407             let adjusted_ty = match a {
4408                 &Some(box ref a) => adjust_ty_for_autoref(cx, span, ty, Some(a)),
4409                 &None => ty
4410             };
4411             mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
4412         }
4413
4414         Some(&AutoUnsize(ref k)) => unsize_ty(cx, ty, k, span),
4415
4416         Some(&AutoUnsizeUniq(ref k)) => ty::mk_uniq(cx, unsize_ty(cx, ty, k, span)),
4417     }
4418 }
4419
4420 // Take a sized type and a sizing adjustment and produce an unsized version of
4421 // the type.
4422 pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>,
4423                        ty: Ty<'tcx>,
4424                        kind: &UnsizeKind<'tcx>,
4425                        span: Span)
4426                        -> Ty<'tcx> {
4427     match kind {
4428         &UnsizeLength(len) => match ty.sty {
4429             ty_vec(ty, Some(n)) => {
4430                 assert!(len == n);
4431                 mk_vec(cx, ty, None)
4432             }
4433             _ => cx.sess.span_bug(span,
4434                                   format!("UnsizeLength with bad sty: {}",
4435                                           ty_to_string(cx, ty))[])
4436         },
4437         &UnsizeStruct(box ref k, tp_index) => match ty.sty {
4438             ty_struct(did, substs) => {
4439                 let ty_substs = substs.types.get_slice(subst::TypeSpace);
4440                 let new_ty = unsize_ty(cx, ty_substs[tp_index], k, span);
4441                 let mut unsized_substs = substs.clone();
4442                 unsized_substs.types.get_mut_slice(subst::TypeSpace)[tp_index] = new_ty;
4443                 mk_struct(cx, did, cx.mk_substs(unsized_substs))
4444             }
4445             _ => cx.sess.span_bug(span,
4446                                   format!("UnsizeStruct with bad sty: {}",
4447                                           ty_to_string(cx, ty))[])
4448         },
4449         &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => {
4450             mk_trait(cx, principal.clone(), bounds.clone())
4451         }
4452     }
4453 }
4454
4455 pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def {
4456     match tcx.def_map.borrow().get(&expr.id) {
4457         Some(&def) => def,
4458         None => {
4459             tcx.sess.span_bug(expr.span, format!(
4460                 "no def-map entry for expr {}", expr.id)[]);
4461         }
4462     }
4463 }
4464
4465 pub fn expr_is_lval(tcx: &ctxt, e: &ast::Expr) -> bool {
4466     match expr_kind(tcx, e) {
4467         LvalueExpr => true,
4468         RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
4469     }
4470 }
4471
4472 /// We categorize expressions into three kinds.  The distinction between
4473 /// lvalue/rvalue is fundamental to the language.  The distinction between the
4474 /// two kinds of rvalues is an artifact of trans which reflects how we will
4475 /// generate code for that kind of expression.  See trans/expr.rs for more
4476 /// information.
4477 #[deriving(Copy)]
4478 pub enum ExprKind {
4479     LvalueExpr,
4480     RvalueDpsExpr,
4481     RvalueDatumExpr,
4482     RvalueStmtExpr
4483 }
4484
4485 pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
4486     if tcx.method_map.borrow().contains_key(&MethodCall::expr(expr.id)) {
4487         // Overloaded operations are generally calls, and hence they are
4488         // generated via DPS, but there are a few exceptions:
4489         return match expr.node {
4490             // `a += b` has a unit result.
4491             ast::ExprAssignOp(..) => RvalueStmtExpr,
4492
4493             // the deref method invoked for `*a` always yields an `&T`
4494             ast::ExprUnary(ast::UnDeref, _) => LvalueExpr,
4495
4496             // the index method invoked for `a[i]` always yields an `&T`
4497             ast::ExprIndex(..) => LvalueExpr,
4498
4499             // `for` loops are statements
4500             ast::ExprForLoop(..) => RvalueStmtExpr,
4501
4502             // in the general case, result could be any type, use DPS
4503             _ => RvalueDpsExpr
4504         };
4505     }
4506
4507     match expr.node {
4508         ast::ExprPath(..) => {
4509             match resolve_expr(tcx, expr) {
4510                 def::DefVariant(tid, vid, _) => {
4511                     let variant_info = enum_variant_with_id(tcx, tid, vid);
4512                     if variant_info.args.len() > 0u {
4513                         // N-ary variant.
4514                         RvalueDatumExpr
4515                     } else {
4516                         // Nullary variant.
4517                         RvalueDpsExpr
4518                     }
4519                 }
4520
4521                 def::DefStruct(_) => {
4522                     match tcx.node_types.borrow().get(&expr.id) {
4523                         Some(ty) => match ty.sty {
4524                             ty_bare_fn(..) => RvalueDatumExpr,
4525                             _ => RvalueDpsExpr
4526                         },
4527                         // See ExprCast below for why types might be missing.
4528                         None => RvalueDatumExpr
4529                      }
4530                 }
4531
4532                 // Special case: A unit like struct's constructor must be called without () at the
4533                 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
4534                 // of unit structs this is should not be interpreted as function pointer but as
4535                 // call to the constructor.
4536                 def::DefFn(_, true) => RvalueDpsExpr,
4537
4538                 // Fn pointers are just scalar values.
4539                 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => RvalueDatumExpr,
4540
4541                 // Note: there is actually a good case to be made that
4542                 // DefArg's, particularly those of immediate type, ought to
4543                 // considered rvalues.
4544                 def::DefStatic(..) |
4545                 def::DefUpvar(..) |
4546                 def::DefLocal(..) => LvalueExpr,
4547
4548                 def::DefConst(..) => RvalueDatumExpr,
4549
4550                 def => {
4551                     tcx.sess.span_bug(
4552                         expr.span,
4553                         format!("uncategorized def for expr {}: {}",
4554                                 expr.id,
4555                                 def)[]);
4556                 }
4557             }
4558         }
4559
4560         ast::ExprUnary(ast::UnDeref, _) |
4561         ast::ExprField(..) |
4562         ast::ExprTupField(..) |
4563         ast::ExprIndex(..) => {
4564             LvalueExpr
4565         }
4566
4567         ast::ExprCall(..) |
4568         ast::ExprMethodCall(..) |
4569         ast::ExprStruct(..) |
4570         ast::ExprRange(..) |
4571         ast::ExprTup(..) |
4572         ast::ExprIf(..) |
4573         ast::ExprMatch(..) |
4574         ast::ExprClosure(..) |
4575         ast::ExprBlock(..) |
4576         ast::ExprRepeat(..) |
4577         ast::ExprVec(..) => {
4578             RvalueDpsExpr
4579         }
4580
4581         ast::ExprIfLet(..) => {
4582             tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
4583         }
4584         ast::ExprWhileLet(..) => {
4585             tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
4586         }
4587
4588         ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
4589             RvalueDpsExpr
4590         }
4591
4592         ast::ExprCast(..) => {
4593             match tcx.node_types.borrow().get(&expr.id) {
4594                 Some(&ty) => {
4595                     if type_is_trait(ty) {
4596                         RvalueDpsExpr
4597                     } else {
4598                         RvalueDatumExpr
4599                     }
4600                 }
4601                 None => {
4602                     // Technically, it should not happen that the expr is not
4603                     // present within the table.  However, it DOES happen
4604                     // during type check, because the final types from the
4605                     // expressions are not yet recorded in the tcx.  At that
4606                     // time, though, we are only interested in knowing lvalue
4607                     // vs rvalue.  It would be better to base this decision on
4608                     // the AST type in cast node---but (at the time of this
4609                     // writing) it's not easy to distinguish casts to traits
4610                     // from other casts based on the AST.  This should be
4611                     // easier in the future, when casts to traits
4612                     // would like @Foo, Box<Foo>, or &Foo.
4613                     RvalueDatumExpr
4614                 }
4615             }
4616         }
4617
4618         ast::ExprBreak(..) |
4619         ast::ExprAgain(..) |
4620         ast::ExprRet(..) |
4621         ast::ExprWhile(..) |
4622         ast::ExprLoop(..) |
4623         ast::ExprAssign(..) |
4624         ast::ExprInlineAsm(..) |
4625         ast::ExprAssignOp(..) |
4626         ast::ExprForLoop(..) => {
4627             RvalueStmtExpr
4628         }
4629
4630         ast::ExprLit(_) | // Note: LitStr is carved out above
4631         ast::ExprUnary(..) |
4632         ast::ExprBox(None, _) |
4633         ast::ExprAddrOf(..) |
4634         ast::ExprBinary(..) => {
4635             RvalueDatumExpr
4636         }
4637
4638         ast::ExprBox(Some(ref place), _) => {
4639             // Special case `Box<T>` for now:
4640             let definition = match tcx.def_map.borrow().get(&place.id) {
4641                 Some(&def) => def,
4642                 None => panic!("no def for place"),
4643             };
4644             let def_id = definition.def_id();
4645             if tcx.lang_items.exchange_heap() == Some(def_id) {
4646                 RvalueDatumExpr
4647             } else {
4648                 RvalueDpsExpr
4649             }
4650         }
4651
4652         ast::ExprParen(ref e) => expr_kind(tcx, &**e),
4653
4654         ast::ExprMac(..) => {
4655             tcx.sess.span_bug(
4656                 expr.span,
4657                 "macro expression remains after expansion");
4658         }
4659     }
4660 }
4661
4662 pub fn stmt_node_id(s: &ast::Stmt) -> ast::NodeId {
4663     match s.node {
4664       ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
4665         return id;
4666       }
4667       ast::StmtMac(..) => panic!("unexpanded macro in trans")
4668     }
4669 }
4670
4671 pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
4672                      -> uint {
4673     let mut i = 0u;
4674     for f in fields.iter() { if f.name == name { return i; } i += 1u; }
4675     tcx.sess.bug(format!(
4676         "no field named `{}` found in the list of fields `{}`",
4677         token::get_name(name),
4678         fields.iter()
4679               .map(|f| token::get_name(f.name).get().to_string())
4680               .collect::<Vec<String>>())[]);
4681 }
4682
4683 pub fn impl_or_trait_item_idx(id: ast::Name, trait_items: &[ImplOrTraitItem])
4684                               -> Option<uint> {
4685     trait_items.iter().position(|m| m.name() == id)
4686 }
4687
4688 pub fn ty_sort_string<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> String {
4689     match ty.sty {
4690         ty_bool | ty_char | ty_int(_) |
4691         ty_uint(_) | ty_float(_) | ty_str => {
4692             ::util::ppaux::ty_to_string(cx, ty)
4693         }
4694         ty_tup(ref tys) if tys.is_empty() => ::util::ppaux::ty_to_string(cx, ty),
4695
4696         ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)),
4697         ty_uniq(_) => "box".to_string(),
4698         ty_vec(_, Some(n)) => format!("array of {} elements", n),
4699         ty_vec(_, None) => "slice".to_string(),
4700         ty_ptr(_) => "*-ptr".to_string(),
4701         ty_rptr(_, _) => "&-ptr".to_string(),
4702         ty_bare_fn(Some(_), _) => format!("fn item"),
4703         ty_bare_fn(None, _) => "fn pointer".to_string(),
4704         ty_closure(_) => "fn".to_string(),
4705         ty_trait(ref inner) => {
4706             format!("trait {}", item_path_str(cx, inner.principal_def_id()))
4707         }
4708         ty_struct(id, _) => {
4709             format!("struct {}", item_path_str(cx, id))
4710         }
4711         ty_unboxed_closure(..) => "closure".to_string(),
4712         ty_tup(_) => "tuple".to_string(),
4713         ty_infer(TyVar(_)) => "inferred type".to_string(),
4714         ty_infer(IntVar(_)) => "integral variable".to_string(),
4715         ty_infer(FloatVar(_)) => "floating-point variable".to_string(),
4716         ty_infer(FreshTy(_)) => "skolemized type".to_string(),
4717         ty_infer(FreshIntTy(_)) => "skolemized integral type".to_string(),
4718         ty_projection(_) => "associated type".to_string(),
4719         ty_param(ref p) => {
4720             if p.space == subst::SelfSpace {
4721                 "Self".to_string()
4722             } else {
4723                 "type parameter".to_string()
4724             }
4725         }
4726         ty_err => "type error".to_string(),
4727         ty_open(_) => "opened DST".to_string(),
4728     }
4729 }
4730
4731 impl<'tcx> Repr<'tcx> for ty::type_err<'tcx> {
4732     fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
4733         ty::type_err_to_str(tcx, self)
4734     }
4735 }
4736
4737 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
4738 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
4739 /// afterwards to present additional details, particularly when it comes to lifetime-related
4740 /// errors.
4741 pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String {
4742     fn tstore_to_closure(s: &TraitStore) -> String {
4743         match s {
4744             &UniqTraitStore => "proc".to_string(),
4745             &RegionTraitStore(..) => "closure".to_string()
4746         }
4747     }
4748
4749     match *err {
4750         terr_cyclic_ty => "cyclic type of infinite size".to_string(),
4751         terr_mismatch => "types differ".to_string(),
4752         terr_unsafety_mismatch(values) => {
4753             format!("expected {} fn, found {} fn",
4754                     values.expected.to_string(),
4755                     values.found.to_string())
4756         }
4757         terr_abi_mismatch(values) => {
4758             format!("expected {} fn, found {} fn",
4759                     values.expected.to_string(),
4760                     values.found.to_string())
4761         }
4762         terr_onceness_mismatch(values) => {
4763             format!("expected {} fn, found {} fn",
4764                     values.expected.to_string(),
4765                     values.found.to_string())
4766         }
4767         terr_sigil_mismatch(values) => {
4768             format!("expected {}, found {}",
4769                     tstore_to_closure(&values.expected),
4770                     tstore_to_closure(&values.found))
4771         }
4772         terr_mutability => "values differ in mutability".to_string(),
4773         terr_box_mutability => {
4774             "boxed values differ in mutability".to_string()
4775         }
4776         terr_vec_mutability => "vectors differ in mutability".to_string(),
4777         terr_ptr_mutability => "pointers differ in mutability".to_string(),
4778         terr_ref_mutability => "references differ in mutability".to_string(),
4779         terr_ty_param_size(values) => {
4780             format!("expected a type with {} type params, \
4781                      found one with {} type params",
4782                     values.expected,
4783                     values.found)
4784         }
4785         terr_fixed_array_size(values) => {
4786             format!("expected an array with a fixed size of {} elements, \
4787                      found one with {} elements",
4788                     values.expected,
4789                     values.found)
4790         }
4791         terr_tuple_size(values) => {
4792             format!("expected a tuple with {} elements, \
4793                      found one with {} elements",
4794                     values.expected,
4795                     values.found)
4796         }
4797         terr_arg_count => {
4798             "incorrect number of function parameters".to_string()
4799         }
4800         terr_regions_does_not_outlive(..) => {
4801             "lifetime mismatch".to_string()
4802         }
4803         terr_regions_not_same(..) => {
4804             "lifetimes are not the same".to_string()
4805         }
4806         terr_regions_no_overlap(..) => {
4807             "lifetimes do not intersect".to_string()
4808         }
4809         terr_regions_insufficiently_polymorphic(br, _) => {
4810             format!("expected bound lifetime parameter {}, \
4811                      found concrete lifetime",
4812                     bound_region_ptr_to_string(cx, br))
4813         }
4814         terr_regions_overly_polymorphic(br, _) => {
4815             format!("expected concrete lifetime, \
4816                      found bound lifetime parameter {}",
4817                     bound_region_ptr_to_string(cx, br))
4818         }
4819         terr_trait_stores_differ(_, ref values) => {
4820             format!("trait storage differs: expected `{}`, found `{}`",
4821                     trait_store_to_string(cx, (*values).expected),
4822                     trait_store_to_string(cx, (*values).found))
4823         }
4824         terr_sorts(values) => {
4825             // A naive approach to making sure that we're not reporting silly errors such as:
4826             // (expected closure, found closure).
4827             let expected_str = ty_sort_string(cx, values.expected);
4828             let found_str = ty_sort_string(cx, values.found);
4829             if expected_str == found_str {
4830                 format!("expected {}, found a different {}", expected_str, found_str)
4831             } else {
4832                 format!("expected {}, found {}", expected_str, found_str)
4833             }
4834         }
4835         terr_traits(values) => {
4836             format!("expected trait `{}`, found trait `{}`",
4837                     item_path_str(cx, values.expected),
4838                     item_path_str(cx, values.found))
4839         }
4840         terr_builtin_bounds(values) => {
4841             if values.expected.is_empty() {
4842                 format!("expected no bounds, found `{}`",
4843                         values.found.user_string(cx))
4844             } else if values.found.is_empty() {
4845                 format!("expected bounds `{}`, found no bounds",
4846                         values.expected.user_string(cx))
4847             } else {
4848                 format!("expected bounds `{}`, found bounds `{}`",
4849                         values.expected.user_string(cx),
4850                         values.found.user_string(cx))
4851             }
4852         }
4853         terr_integer_as_char => {
4854             "expected an integral type, found `char`".to_string()
4855         }
4856         terr_int_mismatch(ref values) => {
4857             format!("expected `{}`, found `{}`",
4858                     values.expected.to_string(),
4859                     values.found.to_string())
4860         }
4861         terr_float_mismatch(ref values) => {
4862             format!("expected `{}`, found `{}`",
4863                     values.expected.to_string(),
4864                     values.found.to_string())
4865         }
4866         terr_variadic_mismatch(ref values) => {
4867             format!("expected {} fn, found {} function",
4868                     if values.expected { "variadic" } else { "non-variadic" },
4869                     if values.found { "variadic" } else { "non-variadic" })
4870         }
4871         terr_convergence_mismatch(ref values) => {
4872             format!("expected {} fn, found {} function",
4873                     if values.expected { "converging" } else { "diverging" },
4874                     if values.found { "converging" } else { "diverging" })
4875         }
4876         terr_projection_name_mismatched(ref values) => {
4877             format!("expected {}, found {}",
4878                     token::get_name(values.expected),
4879                     token::get_name(values.found))
4880         }
4881         terr_projection_bounds_length(ref values) => {
4882             format!("expected {} associated type bindings, found {}",
4883                     values.expected,
4884                     values.found)
4885         }
4886     }
4887 }
4888
4889 pub fn note_and_explain_type_err(cx: &ctxt, err: &type_err) {
4890     match *err {
4891         terr_regions_does_not_outlive(subregion, superregion) => {
4892             note_and_explain_region(cx, "", subregion, "...");
4893             note_and_explain_region(cx, "...does not necessarily outlive ",
4894                                     superregion, "");
4895         }
4896         terr_regions_not_same(region1, region2) => {
4897             note_and_explain_region(cx, "", region1, "...");
4898             note_and_explain_region(cx, "...is not the same lifetime as ",
4899                                     region2, "");
4900         }
4901         terr_regions_no_overlap(region1, region2) => {
4902             note_and_explain_region(cx, "", region1, "...");
4903             note_and_explain_region(cx, "...does not overlap ",
4904                                     region2, "");
4905         }
4906         terr_regions_insufficiently_polymorphic(_, conc_region) => {
4907             note_and_explain_region(cx,
4908                                     "concrete lifetime that was found is ",
4909                                     conc_region, "");
4910         }
4911         terr_regions_overly_polymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
4912             // don't bother to print out the message below for
4913             // inference variables, it's not very illuminating.
4914         }
4915         terr_regions_overly_polymorphic(_, conc_region) => {
4916             note_and_explain_region(cx,
4917                                     "expected concrete lifetime is ",
4918                                     conc_region, "");
4919         }
4920         _ => {}
4921     }
4922 }
4923
4924 pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
4925     cx.provided_method_sources.borrow().get(&id).map(|x| *x)
4926 }
4927
4928 pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
4929                                     -> Vec<Rc<Method<'tcx>>> {
4930     if is_local(id) {
4931         match cx.map.find(id.node) {
4932             Some(ast_map::NodeItem(item)) => {
4933                 match item.node {
4934                     ItemTrait(_, _, _, ref ms) => {
4935                         let (_, p) =
4936                             ast_util::split_trait_methods(ms[]);
4937                         p.iter()
4938                          .map(|m| {
4939                             match impl_or_trait_item(
4940                                     cx,
4941                                     ast_util::local_def(m.id)) {
4942                                 MethodTraitItem(m) => m,
4943                                 TypeTraitItem(_) => {
4944                                     cx.sess.bug("provided_trait_methods(): \
4945                                                  split_trait_methods() put \
4946                                                  associated types in the \
4947                                                  provided method bucket?!")
4948                                 }
4949                             }
4950                          }).collect()
4951                     }
4952                     _ => {
4953                         cx.sess.bug(format!("provided_trait_methods: `{}` is \
4954                                              not a trait",
4955                                             id)[])
4956                     }
4957                 }
4958             }
4959             _ => {
4960                 cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
4961                                      trait",
4962                                     id)[])
4963             }
4964         }
4965     } else {
4966         csearch::get_provided_trait_methods(cx, id)
4967     }
4968 }
4969
4970 /// Helper for looking things up in the various maps that are populated during
4971 /// typeck::collect (e.g., `cx.impl_or_trait_items`, `cx.tcache`, etc).  All of
4972 /// these share the pattern that if the id is local, it should have been loaded
4973 /// into the map by the `typeck::collect` phase.  If the def-id is external,
4974 /// then we have to go consult the crate loading code (and cache the result for
4975 /// the future).
4976 fn lookup_locally_or_in_crate_store<V, F>(descr: &str,
4977                                           def_id: ast::DefId,
4978                                           map: &mut DefIdMap<V>,
4979                                           load_external: F) -> V where
4980     V: Clone,
4981     F: FnOnce() -> V,
4982 {
4983     match map.get(&def_id).cloned() {
4984         Some(v) => { return v; }
4985         None => { }
4986     }
4987
4988     if def_id.krate == ast::LOCAL_CRATE {
4989         panic!("No def'n found for {} in tcx.{}", def_id, descr);
4990     }
4991     let v = load_external();
4992     map.insert(def_id, v.clone());
4993     v
4994 }
4995
4996 pub fn trait_item<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId, idx: uint)
4997                         -> ImplOrTraitItem<'tcx> {
4998     let method_def_id = (*ty::trait_item_def_ids(cx, trait_did))[idx].def_id();
4999     impl_or_trait_item(cx, method_def_id)
5000 }
5001
5002 pub fn trait_items<'tcx>(cx: &ctxt<'tcx>, trait_did: ast::DefId)
5003                          -> Rc<Vec<ImplOrTraitItem<'tcx>>> {
5004     let mut trait_items = cx.trait_items_cache.borrow_mut();
5005     match trait_items.get(&trait_did).cloned() {
5006         Some(trait_items) => trait_items,
5007         None => {
5008             let def_ids = ty::trait_item_def_ids(cx, trait_did);
5009             let items: Rc<Vec<ImplOrTraitItem>> =
5010                 Rc::new(def_ids.iter()
5011                                .map(|d| impl_or_trait_item(cx, d.def_id()))
5012                                .collect());
5013             trait_items.insert(trait_did, items.clone());
5014             items
5015         }
5016     }
5017 }
5018
5019 pub fn impl_or_trait_item<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5020                                 -> ImplOrTraitItem<'tcx> {
5021     lookup_locally_or_in_crate_store("impl_or_trait_items",
5022                                      id,
5023                                      &mut *cx.impl_or_trait_items
5024                                              .borrow_mut(),
5025                                      || {
5026         csearch::get_impl_or_trait_item(cx, id)
5027     })
5028 }
5029
5030 /// Returns true if the given ID refers to an associated type and false if it
5031 /// refers to anything else.
5032 pub fn is_associated_type(cx: &ctxt, id: ast::DefId) -> bool {
5033     memoized(&cx.associated_types, id, |id: ast::DefId| {
5034         if id.krate == ast::LOCAL_CRATE {
5035             match cx.impl_or_trait_items.borrow().get(&id) {
5036                 Some(ref item) => {
5037                     match **item {
5038                         TypeTraitItem(_) => true,
5039                         MethodTraitItem(_) => false,
5040                     }
5041                 }
5042                 None => false,
5043             }
5044         } else {
5045             csearch::is_associated_type(&cx.sess.cstore, id)
5046         }
5047     })
5048 }
5049
5050 /// Returns the parameter index that the given associated type corresponds to.
5051 pub fn associated_type_parameter_index(cx: &ctxt,
5052                                        trait_def: &TraitDef,
5053                                        associated_type_id: ast::DefId)
5054                                        -> uint {
5055     for type_parameter_def in trait_def.generics.types.iter() {
5056         if type_parameter_def.def_id == associated_type_id {
5057             return type_parameter_def.index as uint
5058         }
5059     }
5060     cx.sess.bug("couldn't find associated type parameter index")
5061 }
5062
5063 #[deriving(Copy, PartialEq, Eq)]
5064 pub struct AssociatedTypeInfo {
5065     pub def_id: ast::DefId,
5066     pub index: uint,
5067     pub name: ast::Name,
5068 }
5069
5070 impl PartialOrd for AssociatedTypeInfo {
5071     fn partial_cmp(&self, other: &AssociatedTypeInfo) -> Option<Ordering> {
5072         Some(self.index.cmp(&other.index))
5073     }
5074 }
5075
5076 impl Ord for AssociatedTypeInfo {
5077     fn cmp(&self, other: &AssociatedTypeInfo) -> Ordering {
5078         self.index.cmp(&other.index)
5079     }
5080 }
5081
5082 pub fn trait_item_def_ids(cx: &ctxt, id: ast::DefId)
5083                           -> Rc<Vec<ImplOrTraitItemId>> {
5084     lookup_locally_or_in_crate_store("trait_item_def_ids",
5085                                      id,
5086                                      &mut *cx.trait_item_def_ids.borrow_mut(),
5087                                      || {
5088         Rc::new(csearch::get_trait_item_def_ids(&cx.sess.cstore, id))
5089     })
5090 }
5091
5092 pub fn impl_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5093                             -> Option<Rc<TraitRef<'tcx>>> {
5094     memoized(&cx.impl_trait_cache, id, |id: ast::DefId| {
5095         if id.krate == ast::LOCAL_CRATE {
5096             debug!("(impl_trait_ref) searching for trait impl {}", id);
5097             match cx.map.find(id.node) {
5098                 Some(ast_map::NodeItem(item)) => {
5099                     match item.node {
5100                         ast::ItemImpl(_, _, ref opt_trait, _, _) => {
5101                             match opt_trait {
5102                                 &Some(ref t) => {
5103                                     let trait_ref = ty::node_id_to_trait_ref(cx, t.ref_id);
5104                                     Some(trait_ref)
5105                                 }
5106                                 &None => None
5107                             }
5108                         }
5109                         _ => None
5110                     }
5111                 }
5112                 _ => None
5113             }
5114         } else {
5115             csearch::get_impl_trait(cx, id)
5116         }
5117     })
5118 }
5119
5120 pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId {
5121     let def = *tcx.def_map.borrow()
5122                      .get(&tr.ref_id)
5123                      .expect("no def-map entry for trait");
5124     def.def_id()
5125 }
5126
5127 pub fn try_add_builtin_trait(
5128     tcx: &ctxt,
5129     trait_def_id: ast::DefId,
5130     builtin_bounds: &mut EnumSet<BuiltinBound>)
5131     -> bool
5132 {
5133     //! Checks whether `trait_ref` refers to one of the builtin
5134     //! traits, like `Send`, and adds the corresponding
5135     //! bound to the set `builtin_bounds` if so. Returns true if `trait_ref`
5136     //! is a builtin trait.
5137
5138     match tcx.lang_items.to_builtin_kind(trait_def_id) {
5139         Some(bound) => { builtin_bounds.insert(bound); true }
5140         None => false
5141     }
5142 }
5143
5144 pub fn ty_to_def_id(ty: Ty) -> Option<ast::DefId> {
5145     match ty.sty {
5146         ty_trait(ref tt) =>
5147             Some(tt.principal_def_id()),
5148         ty_struct(id, _) |
5149         ty_enum(id, _) |
5150         ty_unboxed_closure(id, _, _) =>
5151             Some(id),
5152         _ =>
5153             None
5154     }
5155 }
5156
5157 // Enum information
5158 #[deriving(Clone)]
5159 pub struct VariantInfo<'tcx> {
5160     pub args: Vec<Ty<'tcx>>,
5161     pub arg_names: Option<Vec<ast::Ident>>,
5162     pub ctor_ty: Option<Ty<'tcx>>,
5163     pub name: ast::Name,
5164     pub id: ast::DefId,
5165     pub disr_val: Disr,
5166     pub vis: Visibility
5167 }
5168
5169 impl<'tcx> VariantInfo<'tcx> {
5170
5171     /// Creates a new VariantInfo from the corresponding ast representation.
5172     ///
5173     /// Does not do any caching of the value in the type context.
5174     pub fn from_ast_variant(cx: &ctxt<'tcx>,
5175                             ast_variant: &ast::Variant,
5176                             discriminant: Disr) -> VariantInfo<'tcx> {
5177         let ctor_ty = node_id_to_type(cx, ast_variant.node.id);
5178
5179         match ast_variant.node.kind {
5180             ast::TupleVariantKind(ref args) => {
5181                 let arg_tys = if args.len() > 0 {
5182                     ty_fn_args(ctor_ty).iter().map(|a| *a).collect()
5183                 } else {
5184                     Vec::new()
5185                 };
5186
5187                 return VariantInfo {
5188                     args: arg_tys,
5189                     arg_names: None,
5190                     ctor_ty: Some(ctor_ty),
5191                     name: ast_variant.node.name.name,
5192                     id: ast_util::local_def(ast_variant.node.id),
5193                     disr_val: discriminant,
5194                     vis: ast_variant.node.vis
5195                 };
5196             },
5197             ast::StructVariantKind(ref struct_def) => {
5198
5199                 let fields: &[StructField] = struct_def.fields[];
5200
5201                 assert!(fields.len() > 0);
5202
5203                 let arg_tys = struct_def.fields.iter()
5204                     .map(|field| node_id_to_type(cx, field.node.id)).collect();
5205                 let arg_names = fields.iter().map(|field| {
5206                     match field.node.kind {
5207                         NamedField(ident, _) => ident,
5208                         UnnamedField(..) => cx.sess.bug(
5209                             "enum_variants: all fields in struct must have a name")
5210                     }
5211                 }).collect();
5212
5213                 return VariantInfo {
5214                     args: arg_tys,
5215                     arg_names: Some(arg_names),
5216                     ctor_ty: None,
5217                     name: ast_variant.node.name.name,
5218                     id: ast_util::local_def(ast_variant.node.id),
5219                     disr_val: discriminant,
5220                     vis: ast_variant.node.vis
5221                 };
5222             }
5223         }
5224     }
5225 }
5226
5227 pub fn substd_enum_variants<'tcx>(cx: &ctxt<'tcx>,
5228                                   id: ast::DefId,
5229                                   substs: &Substs<'tcx>)
5230                                   -> Vec<Rc<VariantInfo<'tcx>>> {
5231     enum_variants(cx, id).iter().map(|variant_info| {
5232         let substd_args = variant_info.args.iter()
5233             .map(|aty| aty.subst(cx, substs)).collect::<Vec<_>>();
5234
5235         let substd_ctor_ty = variant_info.ctor_ty.subst(cx, substs);
5236
5237         Rc::new(VariantInfo {
5238             args: substd_args,
5239             ctor_ty: substd_ctor_ty,
5240             ..(**variant_info).clone()
5241         })
5242     }).collect()
5243 }
5244
5245 pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
5246     with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
5247 }
5248
5249 #[deriving(Copy)]
5250 pub enum DtorKind {
5251     NoDtor,
5252     TraitDtor(DefId, bool)
5253 }
5254
5255 impl DtorKind {
5256     pub fn is_present(&self) -> bool {
5257         match *self {
5258             TraitDtor(..) => true,
5259             _ => false
5260         }
5261     }
5262
5263     pub fn has_drop_flag(&self) -> bool {
5264         match self {
5265             &NoDtor => false,
5266             &TraitDtor(_, flag) => flag
5267         }
5268     }
5269 }
5270
5271 /* If struct_id names a struct with a dtor, return Some(the dtor's id).
5272    Otherwise return none. */
5273 pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind {
5274     match cx.destructor_for_type.borrow().get(&struct_id) {
5275         Some(&method_def_id) => {
5276             let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
5277
5278             TraitDtor(method_def_id, flag)
5279         }
5280         None => NoDtor,
5281     }
5282 }
5283
5284 pub fn has_dtor(cx: &ctxt, struct_id: DefId) -> bool {
5285     cx.destructor_for_type.borrow().contains_key(&struct_id)
5286 }
5287
5288 pub fn with_path<T, F>(cx: &ctxt, id: ast::DefId, f: F) -> T where
5289     F: FnOnce(ast_map::PathElems) -> T,
5290 {
5291     if id.krate == ast::LOCAL_CRATE {
5292         cx.map.with_path(id.node, f)
5293     } else {
5294         f(ast_map::Values(csearch::get_item_path(cx, id).iter()).chain(None))
5295     }
5296 }
5297
5298 pub fn enum_is_univariant(cx: &ctxt, id: ast::DefId) -> bool {
5299     enum_variants(cx, id).len() == 1
5300 }
5301
5302 pub fn type_is_empty(cx: &ctxt, ty: Ty) -> bool {
5303     match ty.sty {
5304        ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
5305        _ => false
5306      }
5307 }
5308
5309 pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId)
5310                            -> Rc<Vec<Rc<VariantInfo<'tcx>>>> {
5311     memoized(&cx.enum_var_cache, id, |id: ast::DefId| {
5312         if ast::LOCAL_CRATE != id.krate {
5313             Rc::new(csearch::get_enum_variants(cx, id))
5314         } else {
5315             /*
5316               Although both this code and check_enum_variants in typeck/check
5317               call eval_const_expr, it should never get called twice for the same
5318               expr, since check_enum_variants also updates the enum_var_cache
5319              */
5320             match cx.map.get(id.node) {
5321                 ast_map::NodeItem(ref item) => {
5322                     match item.node {
5323                         ast::ItemEnum(ref enum_definition, _) => {
5324                             let mut last_discriminant: Option<Disr> = None;
5325                             Rc::new(enum_definition.variants.iter().map(|variant| {
5326
5327                                 let mut discriminant = match last_discriminant {
5328                                     Some(val) => val + 1,
5329                                     None => INITIAL_DISCRIMINANT_VALUE
5330                                 };
5331
5332                                 match variant.node.disr_expr {
5333                                     Some(ref e) =>
5334                                         match const_eval::eval_const_expr_partial(cx, &**e) {
5335                                             Ok(const_eval::const_int(val)) => {
5336                                                 discriminant = val as Disr
5337                                             }
5338                                             Ok(const_eval::const_uint(val)) => {
5339                                                 discriminant = val as Disr
5340                                             }
5341                                             Ok(_) => {
5342                                                 cx.sess
5343                                                   .span_err(e.span,
5344                                                             "expected signed integer constant");
5345                                             }
5346                                             Err(ref err) => {
5347                                                 cx.sess
5348                                                   .span_err(e.span,
5349                                                             format!("expected constant: {}",
5350                                                                     *err)[]);
5351                                             }
5352                                         },
5353                                     None => {}
5354                                 };
5355
5356                                 last_discriminant = Some(discriminant);
5357                                 Rc::new(VariantInfo::from_ast_variant(cx, &**variant,
5358                                                                       discriminant))
5359                             }).collect())
5360                         }
5361                         _ => {
5362                             cx.sess.bug("enum_variants: id not bound to an enum")
5363                         }
5364                     }
5365                 }
5366                 _ => cx.sess.bug("enum_variants: id not bound to an enum")
5367             }
5368         }
5369     })
5370 }
5371
5372 // Returns information about the enum variant with the given ID:
5373 pub fn enum_variant_with_id<'tcx>(cx: &ctxt<'tcx>,
5374                                   enum_id: ast::DefId,
5375                                   variant_id: ast::DefId)
5376                                   -> Rc<VariantInfo<'tcx>> {
5377     enum_variants(cx, enum_id).iter()
5378                               .find(|variant| variant.id == variant_id)
5379                               .expect("enum_variant_with_id(): no variant exists with that ID")
5380                               .clone()
5381 }
5382
5383
5384 // If the given item is in an external crate, looks up its type and adds it to
5385 // the type cache. Returns the type parameters and type.
5386 pub fn lookup_item_type<'tcx>(cx: &ctxt<'tcx>,
5387                               did: ast::DefId)
5388                               -> TypeScheme<'tcx> {
5389     lookup_locally_or_in_crate_store(
5390         "tcache", did, &mut *cx.tcache.borrow_mut(),
5391         || csearch::get_type(cx, did))
5392 }
5393
5394 /// Given the did of a trait, returns its canonical trait ref.
5395 pub fn lookup_trait_def<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId)
5396                               -> Rc<ty::TraitDef<'tcx>> {
5397     memoized(&cx.trait_defs, did, |did: DefId| {
5398         assert!(did.krate != ast::LOCAL_CRATE);
5399         Rc::new(csearch::get_trait_def(cx, did))
5400     })
5401 }
5402
5403 /// Given a reference to a trait, returns the "superbounds" declared
5404 /// on the trait, with appropriate substitutions applied. Basically,
5405 /// this applies a filter to the where clauses on the trait, returning
5406 /// those that have the form:
5407 ///
5408 ///     Self : SuperTrait<...>
5409 ///     Self : 'region
5410 pub fn predicates_for_trait_ref<'tcx>(tcx: &ctxt<'tcx>,
5411                                       trait_ref: &PolyTraitRef<'tcx>)
5412                                       -> Vec<ty::Predicate<'tcx>>
5413 {
5414     let trait_def = lookup_trait_def(tcx, trait_ref.def_id());
5415
5416     debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})",
5417            trait_def.repr(tcx), trait_ref.repr(tcx));
5418
5419     // The interaction between HRTB and supertraits is not entirely
5420     // obvious. Let me walk you (and myself) through an example.
5421     //
5422     // Let's start with an easy case. Consider two traits:
5423     //
5424     //     trait Foo<'a> : Bar<'a,'a> { }
5425     //     trait Bar<'b,'c> { }
5426     //
5427     // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
5428     // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
5429     // knew that `Foo<'x>` (for any 'x) then we also know that
5430     // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
5431     // normal substitution.
5432     //
5433     // In terms of why this is sound, the idea is that whenever there
5434     // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
5435     // holds.  So if there is an impl of `T:Foo<'a>` that applies to
5436     // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
5437     // `'a`.
5438     //
5439     // Another example to be careful of is this:
5440     //
5441     //     trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
5442     //     trait Bar1<'b,'c> { }
5443     //
5444     // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
5445     // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
5446     // reason is similar to the previous example: any impl of
5447     // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`.  So
5448     // basically we would want to collapse the bound lifetimes from
5449     // the input (`trait_ref`) and the supertraits.
5450     //
5451     // To achieve this in practice is fairly straightforward. Let's
5452     // consider the more complicated scenario:
5453     //
5454     // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
5455     //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
5456     //   where both `'x` and `'b` would have a DB index of 1.
5457     //   The substitution from the input trait-ref is therefore going to be
5458     //   `'a => 'x` (where `'x` has a DB index of 1).
5459     // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
5460     //   early-bound parameter and `'b' is a late-bound parameter with a
5461     //   DB index of 1.
5462     // - If we replace `'a` with `'x` from the input, it too will have
5463     //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
5464     //   just as we wanted.
5465     //
5466     // There is only one catch. If we just apply the substitution `'a
5467     // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
5468     // adjust the DB index because we substituting into a binder (it
5469     // tries to be so smart...) resulting in `for<'x> for<'b>
5470     // Bar1<'x,'b>` (we have no syntax for this, so use your
5471     // imagination). Basically the 'x will have DB index of 2 and 'b
5472     // will have DB index of 1. Not quite what we want. So we apply
5473     // the substitution to the *contents* of the trait reference,
5474     // rather than the trait reference itself (put another way, the
5475     // substitution code expects equal binding levels in the values
5476     // from the substitution and the value being substituted into, and
5477     // this trick achieves that).
5478
5479     // Carefully avoid the binder introduced by each trait-ref by
5480     // substituting over the substs, not the trait-refs themselves,
5481     // thus achieving the "collapse" described in the big comment
5482     // above.
5483     let trait_bounds: Vec<_> =
5484         trait_def.bounds.trait_bounds
5485         .iter()
5486         .map(|poly_trait_ref| ty::Binder(poly_trait_ref.0.subst(tcx, trait_ref.substs())))
5487         .collect();
5488
5489     let projection_bounds: Vec<_> =
5490         trait_def.bounds.projection_bounds
5491         .iter()
5492         .map(|poly_proj| ty::Binder(poly_proj.0.subst(tcx, trait_ref.substs())))
5493         .collect();
5494
5495     debug!("bounds_for_trait_ref: trait_bounds={} projection_bounds={}",
5496            trait_bounds.repr(tcx),
5497            projection_bounds.repr(tcx));
5498
5499     // The region bounds and builtin bounds do not currently introduce
5500     // binders so we can just substitute in a straightforward way here.
5501     let region_bounds =
5502         trait_def.bounds.region_bounds.subst(tcx, trait_ref.substs());
5503     let builtin_bounds =
5504         trait_def.bounds.builtin_bounds.subst(tcx, trait_ref.substs());
5505
5506     let bounds = ty::ParamBounds {
5507         trait_bounds: trait_bounds,
5508         region_bounds: region_bounds,
5509         builtin_bounds: builtin_bounds,
5510         projection_bounds: projection_bounds,
5511     };
5512
5513     predicates(tcx, trait_ref.self_ty(), &bounds)
5514 }
5515
5516 pub fn predicates<'tcx>(
5517     tcx: &ctxt<'tcx>,
5518     param_ty: Ty<'tcx>,
5519     bounds: &ParamBounds<'tcx>)
5520     -> Vec<Predicate<'tcx>>
5521 {
5522     let mut vec = Vec::new();
5523
5524     for builtin_bound in bounds.builtin_bounds.iter() {
5525         match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
5526             Ok(trait_ref) => { vec.push(trait_ref.as_predicate()); }
5527             Err(ErrorReported) => { }
5528         }
5529     }
5530
5531     for &region_bound in bounds.region_bounds.iter() {
5532         // account for the binder being introduced below; no need to shift `param_ty`
5533         // because, at present at least, it can only refer to early-bound regions
5534         let region_bound = ty_fold::shift_region(region_bound, 1);
5535         vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).as_predicate());
5536     }
5537
5538     for bound_trait_ref in bounds.trait_bounds.iter() {
5539         vec.push(bound_trait_ref.as_predicate());
5540     }
5541
5542     for projection in bounds.projection_bounds.iter() {
5543         vec.push(projection.as_predicate());
5544     }
5545
5546     vec
5547 }
5548
5549 /// Iterate over attributes of a definition.
5550 // (This should really be an iterator, but that would require csearch and
5551 // decoder to use iterators instead of higher-order functions.)
5552 pub fn each_attr<F>(tcx: &ctxt, did: DefId, mut f: F) -> bool where
5553     F: FnMut(&ast::Attribute) -> bool,
5554 {
5555     if is_local(did) {
5556         let item = tcx.map.expect_item(did.node);
5557         item.attrs.iter().all(|attr| f(attr))
5558     } else {
5559         info!("getting foreign attrs");
5560         let mut cont = true;
5561         csearch::get_item_attrs(&tcx.sess.cstore, did, |attrs| {
5562             if cont {
5563                 cont = attrs.iter().all(|attr| f(attr));
5564             }
5565         });
5566         info!("done");
5567         cont
5568     }
5569 }
5570
5571 /// Determine whether an item is annotated with an attribute
5572 pub fn has_attr(tcx: &ctxt, did: DefId, attr: &str) -> bool {
5573     let mut found = false;
5574     each_attr(tcx, did, |item| {
5575         if item.check_name(attr) {
5576             found = true;
5577             false
5578         } else {
5579             true
5580         }
5581     });
5582     found
5583 }
5584
5585 /// Determine whether an item is annotated with `#[repr(packed)]`
5586 pub fn lookup_packed(tcx: &ctxt, did: DefId) -> bool {
5587     lookup_repr_hints(tcx, did).contains(&attr::ReprPacked)
5588 }
5589
5590 /// Determine whether an item is annotated with `#[simd]`
5591 pub fn lookup_simd(tcx: &ctxt, did: DefId) -> bool {
5592     has_attr(tcx, did, "simd")
5593 }
5594
5595 /// Obtain the representation annotation for a struct definition.
5596 pub fn lookup_repr_hints(tcx: &ctxt, did: DefId) -> Rc<Vec<attr::ReprAttr>> {
5597     memoized(&tcx.repr_hint_cache, did, |did: DefId| {
5598         Rc::new(if did.krate == LOCAL_CRATE {
5599             let mut acc = Vec::new();
5600             ty::each_attr(tcx, did, |meta| {
5601                 acc.extend(attr::find_repr_attrs(tcx.sess.diagnostic(),
5602                                                  meta).into_iter());
5603                 true
5604             });
5605             acc
5606         } else {
5607             csearch::get_repr_attrs(&tcx.sess.cstore, did)
5608         })
5609     })
5610 }
5611
5612 // Look up a field ID, whether or not it's local
5613 // Takes a list of type substs in case the struct is generic
5614 pub fn lookup_field_type<'tcx>(tcx: &ctxt<'tcx>,
5615                                struct_id: DefId,
5616                                id: DefId,
5617                                substs: &Substs<'tcx>)
5618                                -> Ty<'tcx> {
5619     let ty = if id.krate == ast::LOCAL_CRATE {
5620         node_id_to_type(tcx, id.node)
5621     } else {
5622         let mut tcache = tcx.tcache.borrow_mut();
5623         let pty = match tcache.entry(id) {
5624             Occupied(entry) => entry.into_mut(),
5625             Vacant(entry) => entry.set(csearch::get_field_type(tcx, struct_id, id)),
5626         };
5627         pty.ty
5628     };
5629     ty.subst(tcx, substs)
5630 }
5631
5632 // Look up the list of field names and IDs for a given struct.
5633 // Panics if the id is not bound to a struct.
5634 pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
5635     if did.krate == ast::LOCAL_CRATE {
5636         let struct_fields = cx.struct_fields.borrow();
5637         match struct_fields.get(&did) {
5638             Some(fields) => (**fields).clone(),
5639             _ => {
5640                 cx.sess.bug(
5641                     format!("ID not mapped to struct fields: {}",
5642                             cx.map.node_to_string(did.node))[]);
5643             }
5644         }
5645     } else {
5646         csearch::get_struct_fields(&cx.sess.cstore, did)
5647     }
5648 }
5649
5650 pub fn is_tuple_struct(cx: &ctxt, did: ast::DefId) -> bool {
5651     let fields = lookup_struct_fields(cx, did);
5652     !fields.is_empty() && fields.iter().all(|f| f.name == token::special_names::unnamed_field)
5653 }
5654
5655 // Returns a list of fields corresponding to the struct's items. trans uses
5656 // this. Takes a list of substs with which to instantiate field types.
5657 pub fn struct_fields<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &Substs<'tcx>)
5658                            -> Vec<field<'tcx>> {
5659     lookup_struct_fields(cx, did).iter().map(|f| {
5660        field {
5661             name: f.name,
5662             mt: mt {
5663                 ty: lookup_field_type(cx, did, f.id, substs),
5664                 mutbl: MutImmutable
5665             }
5666         }
5667     }).collect()
5668 }
5669
5670 // Returns a list of fields corresponding to the tuple's items. trans uses
5671 // this.
5672 pub fn tup_fields<'tcx>(v: &[Ty<'tcx>]) -> Vec<field<'tcx>> {
5673     v.iter().enumerate().map(|(i, &f)| {
5674        field {
5675             name: token::intern(i.to_string()[]),
5676             mt: mt {
5677                 ty: f,
5678                 mutbl: MutImmutable
5679             }
5680         }
5681     }).collect()
5682 }
5683
5684 #[deriving(Copy, Clone)]
5685 pub struct UnboxedClosureUpvar<'tcx> {
5686     pub def: def::Def,
5687     pub span: Span,
5688     pub ty: Ty<'tcx>,
5689 }
5690
5691 // Returns a list of `UnboxedClosureUpvar`s for each upvar.
5692 pub fn unboxed_closure_upvars<'tcx>(typer: &mc::Typer<'tcx>,
5693                                     closure_id: ast::DefId,
5694                                     substs: &Substs<'tcx>)
5695                                     -> Option<Vec<UnboxedClosureUpvar<'tcx>>>
5696 {
5697     // Presently an unboxed closure type cannot "escape" out of a
5698     // function, so we will only encounter ones that originated in the
5699     // local crate or were inlined into it along with some function.
5700     // This may change if abstract return types of some sort are
5701     // implemented.
5702     assert!(closure_id.krate == ast::LOCAL_CRATE);
5703     let tcx = typer.tcx();
5704     let capture_mode = tcx.capture_modes.borrow()[closure_id.node].clone();
5705     match tcx.freevars.borrow().get(&closure_id.node) {
5706         None => Some(vec![]),
5707         Some(ref freevars) => {
5708             freevars.iter()
5709                     .map(|freevar| {
5710                         let freevar_def_id = freevar.def.def_id();
5711                         let freevar_ty = typer.node_ty(freevar_def_id.node);
5712                         let freevar_ty = freevar_ty.subst(tcx, substs);
5713
5714                         match capture_mode {
5715                             ast::CaptureByValue => {
5716                                 Some(UnboxedClosureUpvar { def: freevar.def,
5717                                                            span: freevar.span,
5718                                                            ty: freevar_ty })
5719                             }
5720
5721                             ast::CaptureByRef => {
5722                                 let upvar_id = ty::UpvarId {
5723                                     var_id: freevar_def_id.node,
5724                                     closure_expr_id: closure_id.node
5725                                 };
5726
5727                                 // FIXME
5728                                 let freevar_ref_ty = match typer.upvar_borrow(upvar_id) {
5729                                     Some(borrow) => {
5730                                         mk_rptr(tcx,
5731                                                 tcx.mk_region(borrow.region),
5732                                                 ty::mt {
5733                                                     ty: freevar_ty,
5734                                                     mutbl: borrow.kind.to_mutbl_lossy(),
5735                                                 })
5736                                     }
5737                                     None => {
5738                                         // FIXME(#16640) we should really return None here;
5739                                         // but that requires better inference integration,
5740                                         // for now gin up something.
5741                                         freevar_ty
5742                                     }
5743                                 };
5744                                 Some(UnboxedClosureUpvar {
5745                                     def: freevar.def,
5746                                     span: freevar.span,
5747                                     ty: freevar_ref_ty,
5748                                 })
5749                             }
5750                         }
5751                     })
5752                     .collect()
5753         }
5754     }
5755 }
5756
5757 pub fn is_binopable<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, op: ast::BinOp) -> bool {
5758     #![allow(non_upper_case_globals)]
5759     static tycat_other: int = 0;
5760     static tycat_bool: int = 1;
5761     static tycat_char: int = 2;
5762     static tycat_int: int = 3;
5763     static tycat_float: int = 4;
5764     static tycat_raw_ptr: int = 6;
5765
5766     static opcat_add: int = 0;
5767     static opcat_sub: int = 1;
5768     static opcat_mult: int = 2;
5769     static opcat_shift: int = 3;
5770     static opcat_rel: int = 4;
5771     static opcat_eq: int = 5;
5772     static opcat_bit: int = 6;
5773     static opcat_logic: int = 7;
5774     static opcat_mod: int = 8;
5775
5776     fn opcat(op: ast::BinOp) -> int {
5777         match op {
5778           ast::BiAdd => opcat_add,
5779           ast::BiSub => opcat_sub,
5780           ast::BiMul => opcat_mult,
5781           ast::BiDiv => opcat_mult,
5782           ast::BiRem => opcat_mod,
5783           ast::BiAnd => opcat_logic,
5784           ast::BiOr => opcat_logic,
5785           ast::BiBitXor => opcat_bit,
5786           ast::BiBitAnd => opcat_bit,
5787           ast::BiBitOr => opcat_bit,
5788           ast::BiShl => opcat_shift,
5789           ast::BiShr => opcat_shift,
5790           ast::BiEq => opcat_eq,
5791           ast::BiNe => opcat_eq,
5792           ast::BiLt => opcat_rel,
5793           ast::BiLe => opcat_rel,
5794           ast::BiGe => opcat_rel,
5795           ast::BiGt => opcat_rel
5796         }
5797     }
5798
5799     fn tycat<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> int {
5800         if type_is_simd(cx, ty) {
5801             return tycat(cx, simd_type(cx, ty))
5802         }
5803         match ty.sty {
5804           ty_char => tycat_char,
5805           ty_bool => tycat_bool,
5806           ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
5807           ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
5808           ty_ptr(_) => tycat_raw_ptr,
5809           _ => tycat_other
5810         }
5811     }
5812
5813     static t: bool = true;
5814     static f: bool = false;
5815
5816     let tbl = [
5817     //           +, -, *, shift, rel, ==, bit, logic, mod
5818     /*other*/   [f, f, f, f,     f,   f,  f,   f,     f],
5819     /*bool*/    [f, f, f, f,     t,   t,  t,   t,     f],
5820     /*char*/    [f, f, f, f,     t,   t,  f,   f,     f],
5821     /*int*/     [t, t, t, t,     t,   t,  t,   f,     t],
5822     /*float*/   [t, t, t, f,     t,   t,  f,   f,     f],
5823     /*bot*/     [t, t, t, t,     t,   t,  t,   t,     t],
5824     /*raw ptr*/ [f, f, f, f,     t,   t,  f,   f,     f]];
5825
5826     return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
5827 }
5828
5829 /// Returns an equivalent type with all the typedefs and self regions removed.
5830 pub fn normalize_ty<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
5831     let u = TypeNormalizer(cx).fold_ty(ty);
5832     return u;
5833
5834     struct TypeNormalizer<'a, 'tcx: 'a>(&'a ctxt<'tcx>);
5835
5836     impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> {
5837         fn tcx(&self) -> &ctxt<'tcx> { let TypeNormalizer(c) = *self; c }
5838
5839         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
5840             match self.tcx().normalized_cache.borrow().get(&ty).cloned() {
5841                 None => {}
5842                 Some(u) => return u
5843             }
5844
5845             let t_norm = ty_fold::super_fold_ty(self, ty);
5846             self.tcx().normalized_cache.borrow_mut().insert(ty, t_norm);
5847             return t_norm;
5848         }
5849
5850         fn fold_region(&mut self, _: ty::Region) -> ty::Region {
5851             ty::ReStatic
5852         }
5853
5854         fn fold_substs(&mut self,
5855                        substs: &subst::Substs<'tcx>)
5856                        -> subst::Substs<'tcx> {
5857             subst::Substs { regions: subst::ErasedRegions,
5858                             types: substs.types.fold_with(self) }
5859         }
5860     }
5861 }
5862
5863 // Returns the repeat count for a repeating vector expression.
5864 pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint {
5865     match const_eval::eval_const_expr_partial(tcx, count_expr) {
5866         Ok(val) => {
5867             let found = match val {
5868                 const_eval::const_uint(count) => return count as uint,
5869                 const_eval::const_int(count) if count >= 0 => return count as uint,
5870                 const_eval::const_int(_) =>
5871                     "negative integer",
5872                 const_eval::const_float(_) =>
5873                     "float",
5874                 const_eval::const_str(_) =>
5875                     "string",
5876                 const_eval::const_bool(_) =>
5877                     "boolean",
5878                 const_eval::const_binary(_) =>
5879                     "binary array"
5880             };
5881             tcx.sess.span_err(count_expr.span, format!(
5882                 "expected positive integer for repeat count, found {}",
5883                 found)[]);
5884         }
5885         Err(_) => {
5886             let found = match count_expr.node {
5887                 ast::ExprPath(ast::Path {
5888                     global: false,
5889                     ref segments,
5890                     ..
5891                 }) if segments.len() == 1 =>
5892                     "variable",
5893                 _ =>
5894                     "non-constant expression"
5895             };
5896             tcx.sess.span_err(count_expr.span, format!(
5897                 "expected constant integer for repeat count, found {}",
5898                 found)[]);
5899         }
5900     }
5901     0
5902 }
5903
5904 // Iterate over a type parameter's bounded traits and any supertraits
5905 // of those traits, ignoring kinds.
5906 // Here, the supertraits are the transitive closure of the supertrait
5907 // relation on the supertraits from each bounded trait's constraint
5908 // list.
5909 pub fn each_bound_trait_and_supertraits<'tcx, F>(tcx: &ctxt<'tcx>,
5910                                                  bounds: &[PolyTraitRef<'tcx>],
5911                                                  mut f: F)
5912                                                  -> bool where
5913     F: FnMut(PolyTraitRef<'tcx>) -> bool,
5914 {
5915     for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
5916         if !f(bound_trait_ref) {
5917             return false;
5918         }
5919     }
5920     return true;
5921 }
5922
5923 pub fn object_region_bounds<'tcx>(
5924     tcx: &ctxt<'tcx>,
5925     opt_principal: Option<&PolyTraitRef<'tcx>>, // None for closures
5926     others: BuiltinBounds)
5927     -> Vec<ty::Region>
5928 {
5929     // Since we don't actually *know* the self type for an object,
5930     // this "open(err)" serves as a kind of dummy standin -- basically
5931     // a skolemized type.
5932     let open_ty = ty::mk_infer(tcx, FreshTy(0));
5933
5934     let opt_trait_ref = opt_principal.map_or(Vec::new(), |principal| {
5935         // Note that we preserve the overall binding levels here.
5936         assert!(!open_ty.has_escaping_regions());
5937         let substs = tcx.mk_substs(principal.0.substs.with_self_ty(open_ty));
5938         vec!(ty::Binder(Rc::new(ty::TraitRef::new(principal.0.def_id, substs))))
5939     });
5940
5941     let param_bounds = ty::ParamBounds {
5942         region_bounds: Vec::new(),
5943         builtin_bounds: others,
5944         trait_bounds: opt_trait_ref,
5945         projection_bounds: Vec::new(), // not relevant to computing region bounds
5946     };
5947
5948     let predicates = ty::predicates(tcx, open_ty, &param_bounds);
5949     ty::required_region_bounds(tcx, open_ty, predicates)
5950 }
5951
5952 /// Given a set of predicates that apply to an object type, returns
5953 /// the region bounds that the (erased) `Self` type must
5954 /// outlive. Precisely *because* the `Self` type is erased, the
5955 /// parameter `erased_self_ty` must be supplied to indicate what type
5956 /// has been used to represent `Self` in the predicates
5957 /// themselves. This should really be a unique type; `FreshTy(0)` is a
5958 /// popular choice (see `object_region_bounds` above).
5959 ///
5960 /// Requires that trait definitions have been processed so that we can
5961 /// elaborate predicates and walk supertraits.
5962 pub fn required_region_bounds<'tcx>(tcx: &ctxt<'tcx>,
5963                                     erased_self_ty: Ty<'tcx>,
5964                                     predicates: Vec<ty::Predicate<'tcx>>)
5965                                     -> Vec<ty::Region>
5966 {
5967     debug!("required_region_bounds(erased_self_ty={}, predicates={})",
5968            erased_self_ty.repr(tcx),
5969            predicates.repr(tcx));
5970
5971     assert!(!erased_self_ty.has_escaping_regions());
5972
5973     traits::elaborate_predicates(tcx, predicates)
5974         .filter_map(|predicate| {
5975             match predicate {
5976                 ty::Predicate::Projection(..) |
5977                 ty::Predicate::Trait(..) |
5978                 ty::Predicate::Equate(..) |
5979                 ty::Predicate::RegionOutlives(..) => {
5980                     None
5981                 }
5982                 ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(t, r))) => {
5983                     // Search for a bound of the form `erased_self_ty
5984                     // : 'a`, but be wary of something like `for<'a>
5985                     // erased_self_ty : 'a` (we interpret a
5986                     // higher-ranked bound like that as 'static,
5987                     // though at present the code in `fulfill.rs`
5988                     // considers such bounds to be unsatisfiable, so
5989                     // it's kind of a moot point since you could never
5990                     // construct such an object, but this seems
5991                     // correct even if that code changes).
5992                     if t == erased_self_ty && !r.has_escaping_regions() {
5993                         if r.has_escaping_regions() {
5994                             Some(ty::ReStatic)
5995                         } else {
5996                             Some(r)
5997                         }
5998                     } else {
5999                         None
6000                     }
6001                 }
6002             }
6003         })
6004         .collect()
6005 }
6006
6007 pub fn get_tydesc_ty<'tcx>(tcx: &ctxt<'tcx>) -> Result<Ty<'tcx>, String> {
6008     tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
6009         tcx.intrinsic_defs.borrow().get(&tydesc_lang_item).cloned()
6010             .expect("Failed to resolve TyDesc")
6011     })
6012 }
6013
6014 pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> Rc<ItemVariances> {
6015     lookup_locally_or_in_crate_store(
6016         "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(),
6017         || Rc::new(csearch::get_item_variances(&tcx.sess.cstore, item_id)))
6018 }
6019
6020 /// Records a trait-to-implementation mapping.
6021 pub fn record_trait_implementation(tcx: &ctxt,
6022                                    trait_def_id: DefId,
6023                                    impl_def_id: DefId) {
6024     match tcx.trait_impls.borrow().get(&trait_def_id) {
6025         Some(impls_for_trait) => {
6026             impls_for_trait.borrow_mut().push(impl_def_id);
6027             return;
6028         }
6029         None => {}
6030     }
6031     tcx.trait_impls.borrow_mut().insert(trait_def_id, Rc::new(RefCell::new(vec!(impl_def_id))));
6032 }
6033
6034 /// Populates the type context with all the implementations for the given type
6035 /// if necessary.
6036 pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt,
6037                                                       type_id: ast::DefId) {
6038     if type_id.krate == LOCAL_CRATE {
6039         return
6040     }
6041     if tcx.populated_external_types.borrow().contains(&type_id) {
6042         return
6043     }
6044
6045     debug!("populate_implementations_for_type_if_necessary: searching for {}", type_id);
6046
6047     let mut inherent_impls = Vec::new();
6048     csearch::each_implementation_for_type(&tcx.sess.cstore, type_id,
6049             |impl_def_id| {
6050         let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id);
6051
6052         // Record the trait->implementation mappings, if applicable.
6053         let associated_traits = csearch::get_impl_trait(tcx, impl_def_id);
6054         for trait_ref in associated_traits.iter() {
6055             record_trait_implementation(tcx, trait_ref.def_id, impl_def_id);
6056         }
6057
6058         // For any methods that use a default implementation, add them to
6059         // the map. This is a bit unfortunate.
6060         for impl_item_def_id in impl_items.iter() {
6061             let method_def_id = impl_item_def_id.def_id();
6062             match impl_or_trait_item(tcx, method_def_id) {
6063                 MethodTraitItem(method) => {
6064                     for &source in method.provided_source.iter() {
6065                         tcx.provided_method_sources
6066                            .borrow_mut()
6067                            .insert(method_def_id, source);
6068                     }
6069                 }
6070                 TypeTraitItem(_) => {}
6071             }
6072         }
6073
6074         // Store the implementation info.
6075         tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
6076
6077         // If this is an inherent implementation, record it.
6078         if associated_traits.is_none() {
6079             inherent_impls.push(impl_def_id);
6080         }
6081     });
6082
6083     tcx.inherent_impls.borrow_mut().insert(type_id, Rc::new(inherent_impls));
6084     tcx.populated_external_types.borrow_mut().insert(type_id);
6085 }
6086
6087 /// Populates the type context with all the implementations for the given
6088 /// trait if necessary.
6089 pub fn populate_implementations_for_trait_if_necessary(
6090         tcx: &ctxt,
6091         trait_id: ast::DefId) {
6092     if trait_id.krate == LOCAL_CRATE {
6093         return
6094     }
6095     if tcx.populated_external_traits.borrow().contains(&trait_id) {
6096         return
6097     }
6098
6099     csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id,
6100             |implementation_def_id| {
6101         let impl_items = csearch::get_impl_items(&tcx.sess.cstore, implementation_def_id);
6102
6103         // Record the trait->implementation mapping.
6104         record_trait_implementation(tcx, trait_id, implementation_def_id);
6105
6106         // For any methods that use a default implementation, add them to
6107         // the map. This is a bit unfortunate.
6108         for impl_item_def_id in impl_items.iter() {
6109             let method_def_id = impl_item_def_id.def_id();
6110             match impl_or_trait_item(tcx, method_def_id) {
6111                 MethodTraitItem(method) => {
6112                     for &source in method.provided_source.iter() {
6113                         tcx.provided_method_sources
6114                            .borrow_mut()
6115                            .insert(method_def_id, source);
6116                     }
6117                 }
6118                 TypeTraitItem(_) => {}
6119             }
6120         }
6121
6122         // Store the implementation info.
6123         tcx.impl_items.borrow_mut().insert(implementation_def_id, impl_items);
6124     });
6125
6126     tcx.populated_external_traits.borrow_mut().insert(trait_id);
6127 }
6128
6129 /// Given the def_id of an impl, return the def_id of the trait it implements.
6130 /// If it implements no trait, return `None`.
6131 pub fn trait_id_of_impl(tcx: &ctxt,
6132                         def_id: ast::DefId)
6133                         -> Option<ast::DefId> {
6134     ty::impl_trait_ref(tcx, def_id).map(|tr| tr.def_id)
6135 }
6136
6137 /// If the given def ID describes a method belonging to an impl, return the
6138 /// ID of the impl that the method belongs to. Otherwise, return `None`.
6139 pub fn impl_of_method(tcx: &ctxt, def_id: ast::DefId)
6140                        -> Option<ast::DefId> {
6141     if def_id.krate != LOCAL_CRATE {
6142         return match csearch::get_impl_or_trait_item(tcx,
6143                                                      def_id).container() {
6144             TraitContainer(_) => None,
6145             ImplContainer(def_id) => Some(def_id),
6146         };
6147     }
6148     match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6149         Some(trait_item) => {
6150             match trait_item.container() {
6151                 TraitContainer(_) => None,
6152                 ImplContainer(def_id) => Some(def_id),
6153             }
6154         }
6155         None => None
6156     }
6157 }
6158
6159 /// If the given def ID describes an item belonging to a trait (either a
6160 /// default method or an implementation of a trait method), return the ID of
6161 /// the trait that the method belongs to. Otherwise, return `None`.
6162 pub fn trait_of_item(tcx: &ctxt, def_id: ast::DefId) -> Option<ast::DefId> {
6163     if def_id.krate != LOCAL_CRATE {
6164         return csearch::get_trait_of_item(&tcx.sess.cstore, def_id, tcx);
6165     }
6166     match tcx.impl_or_trait_items.borrow().get(&def_id).cloned() {
6167         Some(impl_or_trait_item) => {
6168             match impl_or_trait_item.container() {
6169                 TraitContainer(def_id) => Some(def_id),
6170                 ImplContainer(def_id) => trait_id_of_impl(tcx, def_id),
6171             }
6172         }
6173         None => None
6174     }
6175 }
6176
6177 /// If the given def ID describes an item belonging to a trait, (either a
6178 /// default method or an implementation of a trait method), return the ID of
6179 /// the method inside trait definition (this means that if the given def ID
6180 /// is already that of the original trait method, then the return value is
6181 /// the same).
6182 /// Otherwise, return `None`.
6183 pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId)
6184                           -> Option<ImplOrTraitItemId> {
6185     let impl_item = match tcx.impl_or_trait_items.borrow().get(&def_id) {
6186         Some(m) => m.clone(),
6187         None => return None,
6188     };
6189     let name = impl_item.name();
6190     match trait_of_item(tcx, def_id) {
6191         Some(trait_did) => {
6192             let trait_items = ty::trait_items(tcx, trait_did);
6193             trait_items.iter()
6194                 .position(|m| m.name() == name)
6195                 .map(|idx| ty::trait_item(tcx, trait_did, idx).id())
6196         }
6197         None => None
6198     }
6199 }
6200
6201 /// Creates a hash of the type `Ty` which will be the same no matter what crate
6202 /// context it's calculated within. This is used by the `type_id` intrinsic.
6203 pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) -> u64 {
6204     let mut state = sip::SipState::new();
6205     helper(tcx, ty, svh, &mut state);
6206     return state.result();
6207
6208     fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh, state: &mut sip::SipState) {
6209         macro_rules! byte( ($b:expr) => { ($b as u8).hash(state) } );
6210         macro_rules! hash( ($e:expr) => { $e.hash(state) } );
6211
6212         let region = |&: state: &mut sip::SipState, r: Region| {
6213             match r {
6214                 ReStatic => {}
6215                 ReLateBound(db, BrAnon(i)) => {
6216                     db.hash(state);
6217                     i.hash(state);
6218                 }
6219                 ReEmpty |
6220                 ReEarlyBound(..) |
6221                 ReLateBound(..) |
6222                 ReFree(..) |
6223                 ReScope(..) |
6224                 ReInfer(..) => {
6225                     tcx.sess.bug("unexpected region found when hashing a type")
6226                 }
6227             }
6228         };
6229         let did = |&: state: &mut sip::SipState, did: DefId| {
6230             let h = if ast_util::is_local(did) {
6231                 svh.clone()
6232             } else {
6233                 tcx.sess.cstore.get_crate_hash(did.krate)
6234             };
6235             h.as_str().hash(state);
6236             did.node.hash(state);
6237         };
6238         let mt = |&: state: &mut sip::SipState, mt: mt| {
6239             mt.mutbl.hash(state);
6240         };
6241         let fn_sig = |&: state: &mut sip::SipState, sig: &Binder<FnSig<'tcx>>| {
6242             let sig = anonymize_late_bound_regions(tcx, sig);
6243             for a in sig.inputs.iter() { helper(tcx, *a, svh, state); }
6244             if let ty::FnConverging(output) = sig.output {
6245                 helper(tcx, output, svh, state);
6246             }
6247         };
6248         maybe_walk_ty(ty, |ty| {
6249             match ty.sty {
6250                 ty_bool => byte!(2),
6251                 ty_char => byte!(3),
6252                 ty_int(i) => {
6253                     byte!(4);
6254                     hash!(i);
6255                 }
6256                 ty_uint(u) => {
6257                     byte!(5);
6258                     hash!(u);
6259                 }
6260                 ty_float(f) => {
6261                     byte!(6);
6262                     hash!(f);
6263                 }
6264                 ty_str => {
6265                     byte!(7);
6266                 }
6267                 ty_enum(d, _) => {
6268                     byte!(8);
6269                     did(state, d);
6270                 }
6271                 ty_uniq(_) => {
6272                     byte!(9);
6273                 }
6274                 ty_vec(_, Some(n)) => {
6275                     byte!(10);
6276                     n.hash(state);
6277                 }
6278                 ty_vec(_, None) => {
6279                     byte!(11);
6280                 }
6281                 ty_ptr(m) => {
6282                     byte!(12);
6283                     mt(state, m);
6284                 }
6285                 ty_rptr(r, m) => {
6286                     byte!(13);
6287                     region(state, *r);
6288                     mt(state, m);
6289                 }
6290                 ty_bare_fn(opt_def_id, ref b) => {
6291                     byte!(14);
6292                     hash!(opt_def_id);
6293                     hash!(b.unsafety);
6294                     hash!(b.abi);
6295                     fn_sig(state, &b.sig);
6296                     return false;
6297                 }
6298                 ty_closure(ref c) => {
6299                     byte!(15);
6300                     hash!(c.unsafety);
6301                     hash!(c.onceness);
6302                     hash!(c.bounds);
6303                     match c.store {
6304                         UniqTraitStore => byte!(0),
6305                         RegionTraitStore(r, m) => {
6306                             byte!(1);
6307                             region(state, r);
6308                             assert_eq!(m, ast::MutMutable);
6309                         }
6310                     }
6311
6312                     fn_sig(state, &c.sig);
6313
6314                     return false;
6315                 }
6316                 ty_trait(ref data) => {
6317                     byte!(17);
6318                     did(state, data.principal_def_id());
6319                     hash!(data.bounds);
6320
6321                     let principal = anonymize_late_bound_regions(tcx, &data.principal);
6322                     for subty in principal.substs.types.iter() {
6323                         helper(tcx, *subty, svh, state);
6324                     }
6325
6326                     return false;
6327                 }
6328                 ty_struct(d, _) => {
6329                     byte!(18);
6330                     did(state, d);
6331                 }
6332                 ty_tup(ref inner) => {
6333                     byte!(19);
6334                     hash!(inner.len());
6335                 }
6336                 ty_param(p) => {
6337                     byte!(20);
6338                     hash!(p.space);
6339                     hash!(p.idx);
6340                     hash!(token::get_name(p.name));
6341                 }
6342                 ty_open(_) => byte!(22),
6343                 ty_infer(_) => unreachable!(),
6344                 ty_err => byte!(23),
6345                 ty_unboxed_closure(d, r, _) => {
6346                     byte!(24);
6347                     did(state, d);
6348                     region(state, *r);
6349                 }
6350                 ty_projection(ref data) => {
6351                     byte!(25);
6352                     did(state, data.trait_ref.def_id);
6353                     hash!(token::get_name(data.item_name));
6354                 }
6355             }
6356             true
6357         });
6358     }
6359 }
6360
6361 impl Variance {
6362     pub fn to_string(self) -> &'static str {
6363         match self {
6364             Covariant => "+",
6365             Contravariant => "-",
6366             Invariant => "o",
6367             Bivariant => "*",
6368         }
6369     }
6370 }
6371
6372 /// Construct a parameter environment suitable for static contexts or other contexts where there
6373 /// are no free type/lifetime parameters in scope.
6374 pub fn empty_parameter_environment<'tcx>() -> ParameterEnvironment<'tcx> {
6375     ty::ParameterEnvironment { free_substs: Substs::empty(),
6376                                caller_bounds: GenericBounds::empty(),
6377                                implicit_region_bound: ty::ReEmpty,
6378                                selection_cache: traits::SelectionCache::new(), }
6379 }
6380
6381 /// See `ParameterEnvironment` struct def'n for details
6382 pub fn construct_parameter_environment<'tcx>(
6383     tcx: &ctxt<'tcx>,
6384     generics: &ty::Generics<'tcx>,
6385     free_id: ast::NodeId)
6386     -> ParameterEnvironment<'tcx>
6387 {
6388
6389     //
6390     // Construct the free substs.
6391     //
6392
6393     // map T => T
6394     let mut types = VecPerParamSpace::empty();
6395     push_types_from_defs(tcx, &mut types, generics.types.as_slice());
6396
6397     // map bound 'a => free 'a
6398     let mut regions = VecPerParamSpace::empty();
6399     push_region_params(&mut regions, free_id, generics.regions.as_slice());
6400
6401     let free_substs = Substs {
6402         types: types,
6403         regions: subst::NonerasedRegions(regions)
6404     };
6405
6406     let free_id_scope = region::CodeExtent::from_node_id(free_id);
6407
6408     //
6409     // Compute the bounds on Self and the type parameters.
6410     //
6411
6412     let bounds = generics.to_bounds(tcx, &free_substs);
6413     let bounds = liberate_late_bound_regions(tcx, free_id_scope, &ty::Binder(bounds));
6414
6415     //
6416     // Compute region bounds. For now, these relations are stored in a
6417     // global table on the tcx, so just enter them there. I'm not
6418     // crazy about this scheme, but it's convenient, at least.
6419     //
6420
6421     record_region_bounds(tcx, &bounds);
6422
6423     debug!("construct_parameter_environment: free_id={} free_subst={} bounds={}",
6424            free_id,
6425            free_substs.repr(tcx),
6426            bounds.repr(tcx));
6427
6428     return ty::ParameterEnvironment {
6429         free_substs: free_substs,
6430         implicit_region_bound: ty::ReScope(free_id_scope),
6431         caller_bounds: bounds,
6432         selection_cache: traits::SelectionCache::new(),
6433     };
6434
6435     fn push_region_params(regions: &mut VecPerParamSpace<ty::Region>,
6436                           free_id: ast::NodeId,
6437                           region_params: &[RegionParameterDef])
6438     {
6439         for r in region_params.iter() {
6440             regions.push(r.space, ty::free_region_from_def(free_id, r));
6441         }
6442     }
6443
6444     fn push_types_from_defs<'tcx>(tcx: &ty::ctxt<'tcx>,
6445                                   types: &mut VecPerParamSpace<Ty<'tcx>>,
6446                                   defs: &[TypeParameterDef<'tcx>]) {
6447         for def in defs.iter() {
6448             debug!("construct_parameter_environment(): push_types_from_defs: def={}",
6449                    def.repr(tcx));
6450             let ty = ty::mk_param_from_def(tcx, def);
6451             types.push(def.space, ty);
6452         }
6453     }
6454
6455     fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, bounds: &GenericBounds<'tcx>) {
6456         debug!("record_region_bounds(bounds={})", bounds.repr(tcx));
6457
6458         for predicate in bounds.predicates.iter() {
6459             match *predicate {
6460                 Predicate::Projection(..) |
6461                 Predicate::Trait(..) |
6462                 Predicate::Equate(..) |
6463                 Predicate::TypeOutlives(..) => {
6464                     // No region bounds here
6465                 }
6466                 Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(r_a, r_b))) => {
6467                     match (r_a, r_b) {
6468                         (ty::ReFree(fr_a), ty::ReFree(fr_b)) => {
6469                             // Record that `'a:'b`. Or, put another way, `'b <= 'a`.
6470                             tcx.region_maps.relate_free_regions(fr_b, fr_a);
6471                         }
6472                         _ => {
6473                             // All named regions are instantiated with free regions.
6474                             tcx.sess.bug(
6475                                 format!("record_region_bounds: non free region: {} / {}",
6476                                         r_a.repr(tcx),
6477                                         r_b.repr(tcx)).as_slice());
6478                         }
6479                     }
6480                 }
6481             }
6482         }
6483     }
6484 }
6485
6486 impl BorrowKind {
6487     pub fn from_mutbl(m: ast::Mutability) -> BorrowKind {
6488         match m {
6489             ast::MutMutable => MutBorrow,
6490             ast::MutImmutable => ImmBorrow,
6491         }
6492     }
6493
6494     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
6495     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
6496     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
6497     /// question.
6498     pub fn to_mutbl_lossy(self) -> ast::Mutability {
6499         match self {
6500             MutBorrow => ast::MutMutable,
6501             ImmBorrow => ast::MutImmutable,
6502
6503             // We have no type corresponding to a unique imm borrow, so
6504             // use `&mut`. It gives all the capabilities of an `&uniq`
6505             // and hence is a safe "over approximation".
6506             UniqueImmBorrow => ast::MutMutable,
6507         }
6508     }
6509
6510     pub fn to_user_str(&self) -> &'static str {
6511         match *self {
6512             MutBorrow => "mutable",
6513             ImmBorrow => "immutable",
6514             UniqueImmBorrow => "uniquely immutable",
6515         }
6516     }
6517 }
6518
6519 impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> {
6520     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
6521         self
6522     }
6523
6524     fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
6525         ty::node_id_to_type(self, id)
6526     }
6527
6528     fn expr_ty_adjusted(&self, expr: &ast::Expr) -> Ty<'tcx> {
6529         ty::expr_ty_adjusted(self, expr)
6530     }
6531
6532     fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
6533         self.method_map.borrow().get(&method_call).map(|method| method.ty)
6534     }
6535
6536     fn node_method_origin(&self, method_call: ty::MethodCall)
6537                           -> Option<ty::MethodOrigin<'tcx>>
6538     {
6539         self.method_map.borrow().get(&method_call).map(|method| method.origin.clone())
6540     }
6541
6542     fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
6543         &self.adjustments
6544     }
6545
6546     fn is_method_call(&self, id: ast::NodeId) -> bool {
6547         self.method_map.borrow().contains_key(&MethodCall::expr(id))
6548     }
6549
6550     fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
6551         self.region_maps.temporary_scope(rvalue_id)
6552     }
6553
6554     fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> {
6555         Some(self.upvar_borrow_map.borrow()[upvar_id].clone())
6556     }
6557
6558     fn capture_mode(&self, closure_expr_id: ast::NodeId)
6559                     -> ast::CaptureClause {
6560         self.capture_modes.borrow()[closure_expr_id].clone()
6561     }
6562 }
6563
6564 impl<'tcx> UnboxedClosureTyper<'tcx> for ty::ctxt<'tcx> {
6565     fn unboxed_closure_kind(&self,
6566                             def_id: ast::DefId)
6567                             -> ty::UnboxedClosureKind
6568     {
6569         self.unboxed_closures.borrow()[def_id].kind
6570     }
6571
6572     fn unboxed_closure_type(&self,
6573                             def_id: ast::DefId,
6574                             substs: &subst::Substs<'tcx>)
6575                             -> ty::ClosureTy<'tcx>
6576     {
6577         self.unboxed_closures.borrow()[def_id].closure_type.subst(self, substs)
6578     }
6579
6580     fn unboxed_closure_upvars(&self,
6581                               def_id: ast::DefId,
6582                               substs: &Substs<'tcx>)
6583                               -> Option<Vec<UnboxedClosureUpvar<'tcx>>>
6584     {
6585         unboxed_closure_upvars(self, def_id, substs)
6586     }
6587 }
6588
6589
6590 /// The category of explicit self.
6591 #[deriving(Clone, Copy, Eq, PartialEq, Show)]
6592 pub enum ExplicitSelfCategory {
6593     StaticExplicitSelfCategory,
6594     ByValueExplicitSelfCategory,
6595     ByReferenceExplicitSelfCategory(Region, ast::Mutability),
6596     ByBoxExplicitSelfCategory,
6597 }
6598
6599 /// Pushes all the lifetimes in the given type onto the given list. A
6600 /// "lifetime in a type" is a lifetime specified by a reference or a lifetime
6601 /// in a list of type substitutions. This does *not* traverse into nominal
6602 /// types, nor does it resolve fictitious types.
6603 pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
6604                                     ty: Ty) {
6605     walk_ty(ty, |ty| {
6606         match ty.sty {
6607             ty_rptr(region, _) => {
6608                 accumulator.push(*region)
6609             }
6610             ty_trait(ref t) => {
6611                 accumulator.push_all(t.principal.0.substs.regions().as_slice());
6612             }
6613             ty_enum(_, substs) |
6614             ty_struct(_, substs) => {
6615                 accum_substs(accumulator, substs);
6616             }
6617             ty_closure(ref closure_ty) => {
6618                 match closure_ty.store {
6619                     RegionTraitStore(region, _) => accumulator.push(region),
6620                     UniqTraitStore => {}
6621                 }
6622             }
6623             ty_unboxed_closure(_, region, substs) => {
6624                 accumulator.push(*region);
6625                 accum_substs(accumulator, substs);
6626             }
6627             ty_bool |
6628             ty_char |
6629             ty_int(_) |
6630             ty_uint(_) |
6631             ty_float(_) |
6632             ty_uniq(_) |
6633             ty_str |
6634             ty_vec(_, _) |
6635             ty_ptr(_) |
6636             ty_bare_fn(..) |
6637             ty_tup(_) |
6638             ty_projection(_) |
6639             ty_param(_) |
6640             ty_infer(_) |
6641             ty_open(_) |
6642             ty_err => {
6643             }
6644         }
6645     });
6646
6647     fn accum_substs(accumulator: &mut Vec<Region>, substs: &Substs) {
6648         match substs.regions {
6649             subst::ErasedRegions => {}
6650             subst::NonerasedRegions(ref regions) => {
6651                 for region in regions.iter() {
6652                     accumulator.push(*region)
6653                 }
6654             }
6655         }
6656     }
6657 }
6658
6659 /// A free variable referred to in a function.
6660 #[deriving(Copy, RustcEncodable, RustcDecodable)]
6661 pub struct Freevar {
6662     /// The variable being accessed free.
6663     pub def: def::Def,
6664
6665     // First span where it is accessed (there can be multiple).
6666     pub span: Span
6667 }
6668
6669 pub type FreevarMap = NodeMap<Vec<Freevar>>;
6670
6671 pub type CaptureModeMap = NodeMap<ast::CaptureClause>;
6672
6673 // Trait method resolution
6674 pub type TraitMap = NodeMap<Vec<DefId>>;
6675
6676 // Map from the NodeId of a glob import to a list of items which are actually
6677 // imported.
6678 pub type GlobMap = HashMap<NodeId, HashSet<Name>>;
6679
6680 pub fn with_freevars<T, F>(tcx: &ty::ctxt, fid: ast::NodeId, f: F) -> T where
6681     F: FnOnce(&[Freevar]) -> T,
6682 {
6683     match tcx.freevars.borrow().get(&fid) {
6684         None => f(&[]),
6685         Some(d) => f(d[])
6686     }
6687 }
6688
6689 impl<'tcx> AutoAdjustment<'tcx> {
6690     pub fn is_identity(&self) -> bool {
6691         match *self {
6692             AdjustAddEnv(..) => false,
6693             AdjustReifyFnPointer(..) => false,
6694             AdjustDerefRef(ref r) => r.is_identity(),
6695         }
6696     }
6697 }
6698
6699 impl<'tcx> AutoDerefRef<'tcx> {
6700     pub fn is_identity(&self) -> bool {
6701         self.autoderefs == 0 && self.autoref.is_none()
6702     }
6703 }
6704
6705 /// Replace any late-bound regions bound in `value` with free variants attached to scope-id
6706 /// `scope_id`.
6707 pub fn liberate_late_bound_regions<'tcx, T>(
6708     tcx: &ty::ctxt<'tcx>,
6709     scope: region::CodeExtent,
6710     value: &Binder<T>)
6711     -> T
6712     where T : TypeFoldable<'tcx> + Repr<'tcx>
6713 {
6714     replace_late_bound_regions(
6715         tcx, value,
6716         |br, _| ty::ReFree(ty::FreeRegion{scope: scope, bound_region: br})).0
6717 }
6718
6719 pub fn count_late_bound_regions<'tcx, T>(
6720     tcx: &ty::ctxt<'tcx>,
6721     value: &Binder<T>)
6722     -> uint
6723     where T : TypeFoldable<'tcx> + Repr<'tcx>
6724 {
6725     let (_, skol_map) = replace_late_bound_regions(tcx, value, |_, _| ty::ReStatic);
6726     skol_map.len()
6727 }
6728
6729 pub fn binds_late_bound_regions<'tcx, T>(
6730     tcx: &ty::ctxt<'tcx>,
6731     value: &Binder<T>)
6732     -> bool
6733     where T : TypeFoldable<'tcx> + Repr<'tcx>
6734 {
6735     count_late_bound_regions(tcx, value) > 0
6736 }
6737
6738 /// Replace any late-bound regions bound in `value` with `'static`. Useful in trans but also
6739 /// method lookup and a few other places where precise region relationships are not required.
6740 pub fn erase_late_bound_regions<'tcx, T>(
6741     tcx: &ty::ctxt<'tcx>,
6742     value: &Binder<T>)
6743     -> T
6744     where T : TypeFoldable<'tcx> + Repr<'tcx>
6745 {
6746     replace_late_bound_regions(tcx, value, |_, _| ty::ReStatic).0
6747 }
6748
6749 /// Rewrite any late-bound regions so that they are anonymous.  Region numbers are
6750 /// assigned starting at 1 and increasing monotonically in the order traversed
6751 /// by the fold operation.
6752 ///
6753 /// The chief purpose of this function is to canonicalize regions so that two
6754 /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become
6755 /// structurally identical.  For example, `for<'a, 'b> fn(&'a int, &'b int)` and
6756 /// `for<'a, 'b> fn(&'b int, &'a int)` will become identical after anonymization.
6757 pub fn anonymize_late_bound_regions<'tcx, T>(
6758     tcx: &ctxt<'tcx>,
6759     sig: &Binder<T>)
6760     -> T
6761     where T : TypeFoldable<'tcx> + Repr<'tcx>,
6762 {
6763     let mut counter = 0;
6764     replace_late_bound_regions(tcx, sig, |_, db| {
6765         counter += 1;
6766         ReLateBound(db, BrAnon(counter))
6767     }).0
6768 }
6769
6770 /// Replaces the late-bound-regions in `value` that are bound by `value`.
6771 pub fn replace_late_bound_regions<'tcx, T, F>(
6772     tcx: &ty::ctxt<'tcx>,
6773     binder: &Binder<T>,
6774     mut mapf: F)
6775     -> (T, FnvHashMap<ty::BoundRegion,ty::Region>)
6776     where T : TypeFoldable<'tcx> + Repr<'tcx>,
6777           F : FnMut(BoundRegion, DebruijnIndex) -> ty::Region,
6778 {
6779     debug!("replace_late_bound_regions({})", binder.repr(tcx));
6780
6781     let mut map = FnvHashMap::new();
6782
6783     // Note: fold the field `0`, not the binder, so that late-bound
6784     // regions bound by `binder` are considered free.
6785     let value = ty_fold::fold_regions(tcx, &binder.0, |region, current_depth| {
6786         debug!("region={}", region.repr(tcx));
6787         match region {
6788             ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => {
6789                 * match map.entry(br) {
6790                     Vacant(entry) => entry.set(mapf(br, debruijn)),
6791                     Occupied(entry) => entry.into_mut(),
6792                 }
6793             }
6794             _ => {
6795                 region
6796             }
6797         }
6798     });
6799
6800     debug!("resulting map: {} value: {}", map, value.repr(tcx));
6801     (value, map)
6802 }
6803
6804 impl DebruijnIndex {
6805     pub fn new(depth: u32) -> DebruijnIndex {
6806         assert!(depth > 0);
6807         DebruijnIndex { depth: depth }
6808     }
6809
6810     pub fn shifted(&self, amount: u32) -> DebruijnIndex {
6811         DebruijnIndex { depth: self.depth + amount }
6812     }
6813 }
6814
6815 impl<'tcx> Repr<'tcx> for AutoAdjustment<'tcx> {
6816     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6817         match *self {
6818             AdjustAddEnv(def_id, ref trait_store) => {
6819                 format!("AdjustAddEnv({},{})", def_id.repr(tcx), trait_store)
6820             }
6821             AdjustReifyFnPointer(def_id) => {
6822                 format!("AdjustAddEnv({})", def_id.repr(tcx))
6823             }
6824             AdjustDerefRef(ref data) => {
6825                 data.repr(tcx)
6826             }
6827         }
6828     }
6829 }
6830
6831 impl<'tcx> Repr<'tcx> for UnsizeKind<'tcx> {
6832     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6833         match *self {
6834             UnsizeLength(n) => format!("UnsizeLength({})", n),
6835             UnsizeStruct(ref k, n) => format!("UnsizeStruct({},{})", k.repr(tcx), n),
6836             UnsizeVtable(ref a, ref b) => format!("UnsizeVtable({},{})", a.repr(tcx), b.repr(tcx)),
6837         }
6838     }
6839 }
6840
6841 impl<'tcx> Repr<'tcx> for AutoDerefRef<'tcx> {
6842     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6843         format!("AutoDerefRef({}, {})", self.autoderefs, self.autoref.repr(tcx))
6844     }
6845 }
6846
6847 impl<'tcx> Repr<'tcx> for AutoRef<'tcx> {
6848     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6849         match *self {
6850             AutoPtr(a, b, ref c) => {
6851                 format!("AutoPtr({},{},{})", a.repr(tcx), b, c.repr(tcx))
6852             }
6853             AutoUnsize(ref a) => {
6854                 format!("AutoUnsize({})", a.repr(tcx))
6855             }
6856             AutoUnsizeUniq(ref a) => {
6857                 format!("AutoUnsizeUniq({})", a.repr(tcx))
6858             }
6859             AutoUnsafe(ref a, ref b) => {
6860                 format!("AutoUnsafe({},{})", a, b.repr(tcx))
6861             }
6862         }
6863     }
6864 }
6865
6866 impl<'tcx> Repr<'tcx> for TyTrait<'tcx> {
6867     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6868         format!("TyTrait({},{})",
6869                 self.principal.repr(tcx),
6870                 self.bounds.repr(tcx))
6871     }
6872 }
6873
6874 impl<'tcx> Repr<'tcx> for ty::Predicate<'tcx> {
6875     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
6876         match *self {
6877             Predicate::Trait(ref a) => a.repr(tcx),
6878             Predicate::Equate(ref pair) => pair.repr(tcx),
6879             Predicate::RegionOutlives(ref pair) => pair.repr(tcx),
6880             Predicate::TypeOutlives(ref pair) => pair.repr(tcx),
6881             Predicate::Projection(ref pair) => pair.repr(tcx),
6882         }
6883     }
6884 }
6885
6886 impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> {
6887     fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
6888         match *self {
6889             vtable_static(def_id, ref tys, ref vtable_res) => {
6890                 format!("vtable_static({}:{}, {}, {})",
6891                         def_id,
6892                         ty::item_path_str(tcx, def_id),
6893                         tys.repr(tcx),
6894                         vtable_res.repr(tcx))
6895             }
6896
6897             vtable_param(x, y) => {
6898                 format!("vtable_param({}, {})", x, y)
6899             }
6900
6901             vtable_unboxed_closure(def_id) => {
6902                 format!("vtable_unboxed_closure({})", def_id)
6903             }
6904
6905             vtable_error => {
6906                 format!("vtable_error")
6907             }
6908         }
6909     }
6910 }
6911
6912 pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>,
6913                                             trait_ref: &ty::TraitRef<'tcx>,
6914                                             method: &ty::Method<'tcx>)
6915                                             -> subst::Substs<'tcx>
6916 {
6917     /*!
6918      * Substitutes the values for the receiver's type parameters
6919      * that are found in method, leaving the method's type parameters
6920      * intact.
6921      */
6922
6923     let meth_tps: Vec<Ty> =
6924         method.generics.types.get_slice(subst::FnSpace)
6925               .iter()
6926               .map(|def| ty::mk_param_from_def(tcx, def))
6927               .collect();
6928     let meth_regions: Vec<ty::Region> =
6929         method.generics.regions.get_slice(subst::FnSpace)
6930               .iter()
6931               .map(|def| ty::ReEarlyBound(def.def_id.node, def.space,
6932                                           def.index, def.name))
6933               .collect();
6934     trait_ref.substs.clone().with_method(meth_tps, meth_regions)
6935 }
6936
6937 #[deriving(Copy)]
6938 pub enum CopyImplementationError {
6939     FieldDoesNotImplementCopy(ast::Name),
6940     VariantDoesNotImplementCopy(ast::Name),
6941     TypeIsStructural,
6942 }
6943
6944 pub fn can_type_implement_copy<'tcx>(tcx: &ctxt<'tcx>,
6945                                      self_type: Ty<'tcx>,
6946                                      param_env: &ParameterEnvironment<'tcx>)
6947                                      -> Result<(),CopyImplementationError> {
6948     match self_type.sty {
6949         ty::ty_struct(struct_did, substs) => {
6950             let fields = ty::struct_fields(tcx, struct_did, substs);
6951             for field in fields.iter() {
6952                 if type_moves_by_default(tcx, field.mt.ty, param_env) {
6953                     return Err(FieldDoesNotImplementCopy(field.name))
6954                 }
6955             }
6956         }
6957         ty::ty_enum(enum_did, substs) => {
6958             let enum_variants = ty::enum_variants(tcx, enum_did);
6959             for variant in enum_variants.iter() {
6960                 for variant_arg_type in variant.args.iter() {
6961                     let substd_arg_type =
6962                         variant_arg_type.subst(tcx, substs);
6963                     if type_moves_by_default(tcx,
6964                                              substd_arg_type,
6965                                              param_env) {
6966                         return Err(VariantDoesNotImplementCopy(variant.name))
6967                     }
6968                 }
6969             }
6970         }
6971         _ => return Err(TypeIsStructural),
6972     }
6973
6974     Ok(())
6975 }
6976
6977 // FIXME(#20298) -- all of these types basically walk various
6978 // structures to test whether types/regions are reachable with various
6979 // properties. It should be possible to express them in terms of one
6980 // common "walker" trait or something.
6981
6982 pub trait RegionEscape {
6983     fn has_escaping_regions(&self) -> bool {
6984         self.has_regions_escaping_depth(0)
6985     }
6986
6987     fn has_regions_escaping_depth(&self, depth: u32) -> bool;
6988 }
6989
6990 impl<'tcx> RegionEscape for Ty<'tcx> {
6991     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6992         ty::type_escapes_depth(*self, depth)
6993     }
6994 }
6995
6996 impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> {
6997     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
6998         self.iter_enumerated().any(|(space, _, t)| {
6999             if space == subst::FnSpace {
7000                 t.has_regions_escaping_depth(depth+1)
7001             } else {
7002                 t.has_regions_escaping_depth(depth)
7003             }
7004         })
7005     }
7006 }
7007
7008 impl<'tcx> RegionEscape for TypeScheme<'tcx> {
7009     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7010         self.ty.has_regions_escaping_depth(depth) ||
7011             self.generics.has_regions_escaping_depth(depth)
7012     }
7013 }
7014
7015 impl RegionEscape for Region {
7016     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7017         self.escapes_depth(depth)
7018     }
7019 }
7020
7021 impl<'tcx> RegionEscape for Generics<'tcx> {
7022     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7023         self.predicates.has_regions_escaping_depth(depth)
7024     }
7025 }
7026
7027 impl<'tcx> RegionEscape for Predicate<'tcx> {
7028     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7029         match *self {
7030             Predicate::Trait(ref data) => data.has_regions_escaping_depth(depth),
7031             Predicate::Equate(ref data) => data.has_regions_escaping_depth(depth),
7032             Predicate::RegionOutlives(ref data) => data.has_regions_escaping_depth(depth),
7033             Predicate::TypeOutlives(ref data) => data.has_regions_escaping_depth(depth),
7034             Predicate::Projection(ref data) => data.has_regions_escaping_depth(depth),
7035         }
7036     }
7037 }
7038
7039 impl<'tcx> RegionEscape for TraitRef<'tcx> {
7040     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7041         self.substs.types.iter().any(|t| t.has_regions_escaping_depth(depth)) ||
7042             self.substs.regions.has_regions_escaping_depth(depth)
7043     }
7044 }
7045
7046 impl<'tcx> RegionEscape for subst::RegionSubsts {
7047     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7048         match *self {
7049             subst::ErasedRegions => false,
7050             subst::NonerasedRegions(ref r) => {
7051                 r.iter().any(|t| t.has_regions_escaping_depth(depth))
7052             }
7053         }
7054     }
7055 }
7056
7057 impl<'tcx,T:RegionEscape> RegionEscape for Binder<T> {
7058     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7059         self.0.has_regions_escaping_depth(depth + 1)
7060     }
7061 }
7062
7063 impl<'tcx> RegionEscape for EquatePredicate<'tcx> {
7064     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7065         self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7066     }
7067 }
7068
7069 impl<'tcx> RegionEscape for TraitPredicate<'tcx> {
7070     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7071         self.trait_ref.has_regions_escaping_depth(depth)
7072     }
7073 }
7074
7075 impl<T:RegionEscape,U:RegionEscape> RegionEscape for OutlivesPredicate<T,U> {
7076     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7077         self.0.has_regions_escaping_depth(depth) || self.1.has_regions_escaping_depth(depth)
7078     }
7079 }
7080
7081 impl<'tcx> RegionEscape for ProjectionPredicate<'tcx> {
7082     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7083         self.projection_ty.has_regions_escaping_depth(depth) ||
7084             self.ty.has_regions_escaping_depth(depth)
7085     }
7086 }
7087
7088 impl<'tcx> RegionEscape for ProjectionTy<'tcx> {
7089     fn has_regions_escaping_depth(&self, depth: u32) -> bool {
7090         self.trait_ref.has_regions_escaping_depth(depth)
7091     }
7092 }
7093
7094 impl<'tcx> Repr<'tcx> for ty::ProjectionPredicate<'tcx> {
7095     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7096         format!("ProjectionPredicate({}, {})",
7097                 self.projection_ty.repr(tcx),
7098                 self.ty.repr(tcx))
7099     }
7100 }
7101
7102 pub trait HasProjectionTypes {
7103     fn has_projection_types(&self) -> bool;
7104 }
7105
7106 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for Vec<T> {
7107     fn has_projection_types(&self) -> bool {
7108         self.iter().any(|p| p.has_projection_types())
7109     }
7110 }
7111
7112 impl<'tcx,T:HasProjectionTypes> HasProjectionTypes for VecPerParamSpace<T> {
7113     fn has_projection_types(&self) -> bool {
7114         self.iter().any(|p| p.has_projection_types())
7115     }
7116 }
7117
7118 impl<'tcx> HasProjectionTypes for ClosureTy<'tcx> {
7119     fn has_projection_types(&self) -> bool {
7120         self.sig.has_projection_types()
7121     }
7122 }
7123
7124 impl<'tcx> HasProjectionTypes for UnboxedClosureUpvar<'tcx> {
7125     fn has_projection_types(&self) -> bool {
7126         self.ty.has_projection_types()
7127     }
7128 }
7129
7130 impl<'tcx> HasProjectionTypes for ty::GenericBounds<'tcx> {
7131     fn has_projection_types(&self) -> bool {
7132         self.predicates.has_projection_types()
7133     }
7134 }
7135
7136 impl<'tcx> HasProjectionTypes for Predicate<'tcx> {
7137     fn has_projection_types(&self) -> bool {
7138         match *self {
7139             Predicate::Trait(ref data) => data.has_projection_types(),
7140             Predicate::Equate(ref data) => data.has_projection_types(),
7141             Predicate::RegionOutlives(ref data) => data.has_projection_types(),
7142             Predicate::TypeOutlives(ref data) => data.has_projection_types(),
7143             Predicate::Projection(ref data) => data.has_projection_types(),
7144         }
7145     }
7146 }
7147
7148 impl<'tcx> HasProjectionTypes for TraitPredicate<'tcx> {
7149     fn has_projection_types(&self) -> bool {
7150         self.trait_ref.has_projection_types()
7151     }
7152 }
7153
7154 impl<'tcx> HasProjectionTypes for EquatePredicate<'tcx> {
7155     fn has_projection_types(&self) -> bool {
7156         self.0.has_projection_types() || self.1.has_projection_types()
7157     }
7158 }
7159
7160 impl HasProjectionTypes for Region {
7161     fn has_projection_types(&self) -> bool {
7162         false
7163     }
7164 }
7165
7166 impl<T:HasProjectionTypes,U:HasProjectionTypes> HasProjectionTypes for OutlivesPredicate<T,U> {
7167     fn has_projection_types(&self) -> bool {
7168         self.0.has_projection_types() || self.1.has_projection_types()
7169     }
7170 }
7171
7172 impl<'tcx> HasProjectionTypes for ProjectionPredicate<'tcx> {
7173     fn has_projection_types(&self) -> bool {
7174         self.projection_ty.has_projection_types() || self.ty.has_projection_types()
7175     }
7176 }
7177
7178 impl<'tcx> HasProjectionTypes for ProjectionTy<'tcx> {
7179     fn has_projection_types(&self) -> bool {
7180         self.trait_ref.has_projection_types()
7181     }
7182 }
7183
7184 impl<'tcx> HasProjectionTypes for Ty<'tcx> {
7185     fn has_projection_types(&self) -> bool {
7186         ty::type_has_projection(*self)
7187     }
7188 }
7189
7190 impl<'tcx> HasProjectionTypes for TraitRef<'tcx> {
7191     fn has_projection_types(&self) -> bool {
7192         self.substs.has_projection_types()
7193     }
7194 }
7195
7196 impl<'tcx> HasProjectionTypes for subst::Substs<'tcx> {
7197     fn has_projection_types(&self) -> bool {
7198         self.types.iter().any(|t| t.has_projection_types())
7199     }
7200 }
7201
7202 impl<'tcx,T> HasProjectionTypes for Option<T>
7203     where T : HasProjectionTypes
7204 {
7205     fn has_projection_types(&self) -> bool {
7206         self.iter().any(|t| t.has_projection_types())
7207     }
7208 }
7209
7210 impl<'tcx,T> HasProjectionTypes for Rc<T>
7211     where T : HasProjectionTypes
7212 {
7213     fn has_projection_types(&self) -> bool {
7214         (**self).has_projection_types()
7215     }
7216 }
7217
7218 impl<'tcx,T> HasProjectionTypes for Box<T>
7219     where T : HasProjectionTypes
7220 {
7221     fn has_projection_types(&self) -> bool {
7222         (**self).has_projection_types()
7223     }
7224 }
7225
7226 impl<T> HasProjectionTypes for Binder<T>
7227     where T : HasProjectionTypes
7228 {
7229     fn has_projection_types(&self) -> bool {
7230         self.0.has_projection_types()
7231     }
7232 }
7233
7234 impl<'tcx> HasProjectionTypes for FnOutput<'tcx> {
7235     fn has_projection_types(&self) -> bool {
7236         match *self {
7237             FnConverging(t) => t.has_projection_types(),
7238             FnDiverging => false,
7239         }
7240     }
7241 }
7242
7243 impl<'tcx> HasProjectionTypes for FnSig<'tcx> {
7244     fn has_projection_types(&self) -> bool {
7245         self.inputs.iter().any(|t| t.has_projection_types()) ||
7246             self.output.has_projection_types()
7247     }
7248 }
7249
7250 impl<'tcx> HasProjectionTypes for BareFnTy<'tcx> {
7251     fn has_projection_types(&self) -> bool {
7252         self.sig.has_projection_types()
7253     }
7254 }
7255
7256 pub trait ReferencesError {
7257     fn references_error(&self) -> bool;
7258 }
7259
7260 impl<T:ReferencesError> ReferencesError for Binder<T> {
7261     fn references_error(&self) -> bool {
7262         self.0.references_error()
7263     }
7264 }
7265
7266 impl<T:ReferencesError> ReferencesError for Rc<T> {
7267     fn references_error(&self) -> bool {
7268         (&**self).references_error()
7269     }
7270 }
7271
7272 impl<'tcx> ReferencesError for TraitPredicate<'tcx> {
7273     fn references_error(&self) -> bool {
7274         self.trait_ref.references_error()
7275     }
7276 }
7277
7278 impl<'tcx> ReferencesError for ProjectionPredicate<'tcx> {
7279     fn references_error(&self) -> bool {
7280         self.projection_ty.trait_ref.references_error() || self.ty.references_error()
7281     }
7282 }
7283
7284 impl<'tcx> ReferencesError for TraitRef<'tcx> {
7285     fn references_error(&self) -> bool {
7286         self.input_types().iter().any(|t| t.references_error())
7287     }
7288 }
7289
7290 impl<'tcx> ReferencesError for Ty<'tcx> {
7291     fn references_error(&self) -> bool {
7292         type_is_error(*self)
7293     }
7294 }
7295
7296 impl<'tcx> ReferencesError for Predicate<'tcx> {
7297     fn references_error(&self) -> bool {
7298         match *self {
7299             Predicate::Trait(ref data) => data.references_error(),
7300             Predicate::Equate(ref data) => data.references_error(),
7301             Predicate::RegionOutlives(ref data) => data.references_error(),
7302             Predicate::TypeOutlives(ref data) => data.references_error(),
7303             Predicate::Projection(ref data) => data.references_error(),
7304         }
7305     }
7306 }
7307
7308 impl<A,B> ReferencesError for OutlivesPredicate<A,B>
7309     where A : ReferencesError, B : ReferencesError
7310 {
7311     fn references_error(&self) -> bool {
7312         self.0.references_error() || self.1.references_error()
7313     }
7314 }
7315
7316 impl<'tcx> ReferencesError for EquatePredicate<'tcx>
7317 {
7318     fn references_error(&self) -> bool {
7319         self.0.references_error() || self.1.references_error()
7320     }
7321 }
7322
7323 impl ReferencesError for Region
7324 {
7325     fn references_error(&self) -> bool {
7326         false
7327     }
7328 }
7329
7330 impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> {
7331     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7332         format!("ClosureTy({},{},{},{},{},{})",
7333                 self.unsafety,
7334                 self.onceness,
7335                 self.store,
7336                 self.bounds.repr(tcx),
7337                 self.sig.repr(tcx),
7338                 self.abi)
7339     }
7340 }
7341
7342 impl<'tcx> Repr<'tcx> for UnboxedClosureUpvar<'tcx> {
7343     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
7344         format!("UnboxedClosureUpvar({},{})",
7345                 self.def.repr(tcx),
7346                 self.ty.repr(tcx))
7347     }
7348 }