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