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