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