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