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