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