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