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