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