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