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