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