]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/mod.rs
Auto merge of #42332 - michaelwoerister:no-more-retracing, r=nikomatsakis
[rust.git] / src / librustc / ty / mod.rs
1 // Copyright 2012-2015 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 pub use self::Variance::*;
12 pub use self::AssociatedItemContainer::*;
13 pub use self::BorrowKind::*;
14 pub use self::IntVarValue::*;
15 pub use self::LvaluePreference::*;
16 pub use self::fold::TypeFoldable;
17
18 use dep_graph::DepNode;
19 use hir::{map as hir_map, FreevarMap, TraitMap};
20 use hir::def::{Def, CtorKind, ExportMap};
21 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
22 use ich::StableHashingContext;
23 use middle::const_val::ConstVal;
24 use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
25 use middle::privacy::AccessLevels;
26 use middle::resolve_lifetime::ObjectLifetimeDefault;
27 use middle::region::CodeExtent;
28 use mir::Mir;
29 use traits;
30 use ty;
31 use ty::subst::{Subst, Substs};
32 use ty::util::IntTypeExt;
33 use ty::walk::TypeWalker;
34 use util::common::ErrorReported;
35 use util::nodemap::{NodeSet, DefIdMap, FxHashMap, FxHashSet};
36
37 use serialize::{self, Encodable, Encoder};
38 use std::collections::BTreeMap;
39 use std::cmp;
40 use std::fmt;
41 use std::hash::{Hash, Hasher};
42 use std::iter::FromIterator;
43 use std::ops::Deref;
44 use std::rc::Rc;
45 use std::slice;
46 use std::vec::IntoIter;
47 use std::mem;
48 use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
49 use syntax::attr;
50 use syntax::ext::hygiene::{Mark, SyntaxContext};
51 use syntax::symbol::{Symbol, InternedString};
52 use syntax_pos::{DUMMY_SP, Span};
53 use rustc_const_math::ConstInt;
54
55 use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
56 use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
57                                            HashStable};
58 use rustc_data_structures::transitive_relation::TransitiveRelation;
59
60 use hir;
61
62 pub use self::sty::{Binder, DebruijnIndex};
63 pub use self::sty::{FnSig, PolyFnSig};
64 pub use self::sty::{InferTy, ParamTy, ProjectionTy, ExistentialPredicate};
65 pub use self::sty::{ClosureSubsts, TypeAndMut};
66 pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
67 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
68 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
69 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
70 pub use self::sty::RegionKind;
71 pub use self::sty::Issue32330;
72 pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
73 pub use self::sty::BoundRegion::*;
74 pub use self::sty::InferTy::*;
75 pub use self::sty::RegionKind::*;
76 pub use self::sty::TypeVariants::*;
77
78 pub use self::context::{TyCtxt, GlobalArenas, tls};
79 pub use self::context::{Lift, TypeckTables};
80
81 pub use self::instance::{Instance, InstanceDef};
82
83 pub use self::trait_def::TraitDef;
84
85 pub use self::maps::queries;
86
87 pub mod adjustment;
88 pub mod cast;
89 pub mod error;
90 pub mod fast_reject;
91 pub mod fold;
92 pub mod inhabitedness;
93 pub mod item_path;
94 pub mod layout;
95 pub mod _match;
96 pub mod maps;
97 pub mod outlives;
98 pub mod relate;
99 pub mod steal;
100 pub mod subst;
101 pub mod trait_def;
102 pub mod walk;
103 pub mod wf;
104 pub mod util;
105
106 mod context;
107 mod flags;
108 mod instance;
109 mod structural_impls;
110 mod sty;
111
112 // Data types
113
114 /// The complete set of all analyses described in this module. This is
115 /// produced by the driver and fed to trans and later passes.
116 ///
117 /// NB: These contents are being migrated into queries using the
118 /// *on-demand* infrastructure.
119 #[derive(Clone)]
120 pub struct CrateAnalysis {
121     pub access_levels: Rc<AccessLevels>,
122     pub reachable: Rc<NodeSet>,
123     pub name: String,
124     pub glob_map: Option<hir::GlobMap>,
125 }
126
127 #[derive(Clone)]
128 pub struct Resolutions {
129     pub freevars: FreevarMap,
130     pub trait_map: TraitMap,
131     pub maybe_unused_trait_imports: NodeSet,
132     pub export_map: ExportMap,
133 }
134
135 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
136 pub enum AssociatedItemContainer {
137     TraitContainer(DefId),
138     ImplContainer(DefId),
139 }
140
141 impl AssociatedItemContainer {
142     pub fn id(&self) -> DefId {
143         match *self {
144             TraitContainer(id) => id,
145             ImplContainer(id) => id,
146         }
147     }
148 }
149
150 /// The "header" of an impl is everything outside the body: a Self type, a trait
151 /// ref (in the case of a trait impl), and a set of predicates (from the
152 /// bounds/where clauses).
153 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
154 pub struct ImplHeader<'tcx> {
155     pub impl_def_id: DefId,
156     pub self_ty: Ty<'tcx>,
157     pub trait_ref: Option<TraitRef<'tcx>>,
158     pub predicates: Vec<Predicate<'tcx>>,
159 }
160
161 #[derive(Copy, Clone, Debug)]
162 pub struct AssociatedItem {
163     pub def_id: DefId,
164     pub name: Name,
165     pub kind: AssociatedKind,
166     pub vis: Visibility,
167     pub defaultness: hir::Defaultness,
168     pub container: AssociatedItemContainer,
169
170     /// Whether this is a method with an explicit self
171     /// as its first argument, allowing method calls.
172     pub method_has_self_argument: bool,
173 }
174
175 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
176 pub enum AssociatedKind {
177     Const,
178     Method,
179     Type
180 }
181
182 impl AssociatedItem {
183     pub fn def(&self) -> Def {
184         match self.kind {
185             AssociatedKind::Const => Def::AssociatedConst(self.def_id),
186             AssociatedKind::Method => Def::Method(self.def_id),
187             AssociatedKind::Type => Def::AssociatedTy(self.def_id),
188         }
189     }
190
191     /// Tests whether the associated item admits a non-trivial implementation
192     /// for !
193     pub fn relevant_for_never<'tcx>(&self) -> bool {
194         match self.kind {
195             AssociatedKind::Const => true,
196             AssociatedKind::Type => true,
197             // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited.
198             AssociatedKind::Method => !self.method_has_self_argument,
199         }
200     }
201 }
202
203 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
204 pub enum Visibility {
205     /// Visible everywhere (including in other crates).
206     Public,
207     /// Visible only in the given crate-local module.
208     Restricted(DefId),
209     /// Not visible anywhere in the local crate. This is the visibility of private external items.
210     Invisible,
211 }
212
213 pub trait DefIdTree: Copy {
214     fn parent(self, id: DefId) -> Option<DefId>;
215
216     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
217         if descendant.krate != ancestor.krate {
218             return false;
219         }
220
221         while descendant != ancestor {
222             match self.parent(descendant) {
223                 Some(parent) => descendant = parent,
224                 None => return false,
225             }
226         }
227         true
228     }
229 }
230
231 impl<'a, 'gcx, 'tcx> DefIdTree for TyCtxt<'a, 'gcx, 'tcx> {
232     fn parent(self, id: DefId) -> Option<DefId> {
233         self.def_key(id).parent.map(|index| DefId { index: index, ..id })
234     }
235 }
236
237 impl Visibility {
238     pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
239         match *visibility {
240             hir::Public => Visibility::Public,
241             hir::Visibility::Crate => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
242             hir::Visibility::Restricted { ref path, .. } => match path.def {
243                 // If there is no resolution, `resolve` will have already reported an error, so
244                 // assume that the visibility is public to avoid reporting more privacy errors.
245                 Def::Err => Visibility::Public,
246                 def => Visibility::Restricted(def.def_id()),
247             },
248             hir::Inherited => {
249                 Visibility::Restricted(tcx.hir.get_module_parent(id))
250             }
251         }
252     }
253
254     /// Returns true if an item with this visibility is accessible from the given block.
255     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
256         let restriction = match self {
257             // Public items are visible everywhere.
258             Visibility::Public => return true,
259             // Private items from other crates are visible nowhere.
260             Visibility::Invisible => return false,
261             // Restricted items are visible in an arbitrary local module.
262             Visibility::Restricted(other) if other.krate != module.krate => return false,
263             Visibility::Restricted(module) => module,
264         };
265
266         tree.is_descendant_of(module, restriction)
267     }
268
269     /// Returns true if this visibility is at least as accessible as the given visibility
270     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
271         let vis_restriction = match vis {
272             Visibility::Public => return self == Visibility::Public,
273             Visibility::Invisible => return true,
274             Visibility::Restricted(module) => module,
275         };
276
277         self.is_accessible_from(vis_restriction, tree)
278     }
279 }
280
281 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
282 pub enum Variance {
283     Covariant,      // T<A> <: T<B> iff A <: B -- e.g., function return type
284     Invariant,      // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
285     Contravariant,  // T<A> <: T<B> iff B <: A -- e.g., function param type
286     Bivariant,      // T<A> <: T<B>            -- e.g., unused type parameter
287 }
288
289 /// The crate variances map is computed during typeck and contains the
290 /// variance of every item in the local crate. You should not use it
291 /// directly, because to do so will make your pass dependent on the
292 /// HIR of every item in the local crate. Instead, use
293 /// `tcx.variances_of()` to get the variance for a *particular*
294 /// item.
295 pub struct CrateVariancesMap {
296     /// This relation tracks the dependencies between the variance of
297     /// various items. In particular, if `a < b`, then the variance of
298     /// `a` depends on the sources of `b`.
299     pub dependencies: TransitiveRelation<DefId>,
300
301     /// For each item with generics, maps to a vector of the variance
302     /// of its generics.  If an item has no generics, it will have no
303     /// entry.
304     pub variances: FxHashMap<DefId, Rc<Vec<ty::Variance>>>,
305
306     /// An empty vector, useful for cloning.
307     pub empty_variance: Rc<Vec<ty::Variance>>,
308 }
309
310 impl Variance {
311     /// `a.xform(b)` combines the variance of a context with the
312     /// variance of a type with the following meaning.  If we are in a
313     /// context with variance `a`, and we encounter a type argument in
314     /// a position with variance `b`, then `a.xform(b)` is the new
315     /// variance with which the argument appears.
316     ///
317     /// Example 1:
318     ///
319     ///     *mut Vec<i32>
320     ///
321     /// Here, the "ambient" variance starts as covariant. `*mut T` is
322     /// invariant with respect to `T`, so the variance in which the
323     /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
324     /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
325     /// respect to its type argument `T`, and hence the variance of
326     /// the `i32` here is `Invariant.xform(Covariant)`, which results
327     /// (again) in `Invariant`.
328     ///
329     /// Example 2:
330     ///
331     ///     fn(*const Vec<i32>, *mut Vec<i32)
332     ///
333     /// The ambient variance is covariant. A `fn` type is
334     /// contravariant with respect to its parameters, so the variance
335     /// within which both pointer types appear is
336     /// `Covariant.xform(Contravariant)`, or `Contravariant`.  `*const
337     /// T` is covariant with respect to `T`, so the variance within
338     /// which the first `Vec<i32>` appears is
339     /// `Contravariant.xform(Covariant)` or `Contravariant`.  The same
340     /// is true for its `i32` argument. In the `*mut T` case, the
341     /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
342     /// and hence the outermost type is `Invariant` with respect to
343     /// `Vec<i32>` (and its `i32` argument).
344     ///
345     /// Source: Figure 1 of "Taming the Wildcards:
346     /// Combining Definition- and Use-Site Variance" published in PLDI'11.
347     pub fn xform(self, v: ty::Variance) -> ty::Variance {
348         match (self, v) {
349             // Figure 1, column 1.
350             (ty::Covariant, ty::Covariant) => ty::Covariant,
351             (ty::Covariant, ty::Contravariant) => ty::Contravariant,
352             (ty::Covariant, ty::Invariant) => ty::Invariant,
353             (ty::Covariant, ty::Bivariant) => ty::Bivariant,
354
355             // Figure 1, column 2.
356             (ty::Contravariant, ty::Covariant) => ty::Contravariant,
357             (ty::Contravariant, ty::Contravariant) => ty::Covariant,
358             (ty::Contravariant, ty::Invariant) => ty::Invariant,
359             (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
360
361             // Figure 1, column 3.
362             (ty::Invariant, _) => ty::Invariant,
363
364             // Figure 1, column 4.
365             (ty::Bivariant, _) => ty::Bivariant,
366         }
367     }
368 }
369
370 // Contains information needed to resolve types and (in the future) look up
371 // the types of AST nodes.
372 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
373 pub struct CReaderCacheKey {
374     pub cnum: CrateNum,
375     pub pos: usize,
376 }
377
378 // Flags that we track on types. These flags are propagated upwards
379 // through the type during type construction, so that we can quickly
380 // check whether the type has various kinds of types in it without
381 // recursing over the type itself.
382 bitflags! {
383     flags TypeFlags: u32 {
384         const HAS_PARAMS         = 1 << 0,
385         const HAS_SELF           = 1 << 1,
386         const HAS_TY_INFER       = 1 << 2,
387         const HAS_RE_INFER       = 1 << 3,
388         const HAS_RE_SKOL        = 1 << 4,
389         const HAS_RE_EARLY_BOUND = 1 << 5,
390         const HAS_FREE_REGIONS   = 1 << 6,
391         const HAS_TY_ERR         = 1 << 7,
392         const HAS_PROJECTION     = 1 << 8,
393         const HAS_TY_CLOSURE     = 1 << 9,
394
395         // true if there are "names" of types and regions and so forth
396         // that are local to a particular fn
397         const HAS_LOCAL_NAMES    = 1 << 10,
398
399         // Present if the type belongs in a local type context.
400         // Only set for TyInfer other than Fresh.
401         const KEEP_IN_LOCAL_TCX  = 1 << 11,
402
403         // Is there a projection that does not involve a bound region?
404         // Currently we can't normalize projections w/ bound regions.
405         const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
406
407         const NEEDS_SUBST        = TypeFlags::HAS_PARAMS.bits |
408                                    TypeFlags::HAS_SELF.bits |
409                                    TypeFlags::HAS_RE_EARLY_BOUND.bits,
410
411         // Flags representing the nominal content of a type,
412         // computed by FlagsComputation. If you add a new nominal
413         // flag, it should be added here too.
414         const NOMINAL_FLAGS     = TypeFlags::HAS_PARAMS.bits |
415                                   TypeFlags::HAS_SELF.bits |
416                                   TypeFlags::HAS_TY_INFER.bits |
417                                   TypeFlags::HAS_RE_INFER.bits |
418                                   TypeFlags::HAS_RE_SKOL.bits |
419                                   TypeFlags::HAS_RE_EARLY_BOUND.bits |
420                                   TypeFlags::HAS_FREE_REGIONS.bits |
421                                   TypeFlags::HAS_TY_ERR.bits |
422                                   TypeFlags::HAS_PROJECTION.bits |
423                                   TypeFlags::HAS_TY_CLOSURE.bits |
424                                   TypeFlags::HAS_LOCAL_NAMES.bits |
425                                   TypeFlags::KEEP_IN_LOCAL_TCX.bits,
426     }
427 }
428
429 pub struct TyS<'tcx> {
430     pub sty: TypeVariants<'tcx>,
431     pub flags: TypeFlags,
432
433     // the maximal depth of any bound regions appearing in this type.
434     region_depth: u32,
435 }
436
437 impl<'tcx> PartialEq for TyS<'tcx> {
438     #[inline]
439     fn eq(&self, other: &TyS<'tcx>) -> bool {
440         // (self as *const _) == (other as *const _)
441         (self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
442     }
443 }
444 impl<'tcx> Eq for TyS<'tcx> {}
445
446 impl<'tcx> Hash for TyS<'tcx> {
447     fn hash<H: Hasher>(&self, s: &mut H) {
448         (self as *const TyS).hash(s)
449     }
450 }
451
452 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::TyS<'tcx> {
453     fn hash_stable<W: StableHasherResult>(&self,
454                                           hcx: &mut StableHashingContext<'a, 'tcx>,
455                                           hasher: &mut StableHasher<W>) {
456         let ty::TyS {
457             ref sty,
458
459             // The other fields just provide fast access to information that is
460             // also contained in `sty`, so no need to hash them.
461             flags: _,
462             region_depth: _,
463         } = *self;
464
465         sty.hash_stable(hcx, hasher);
466     }
467 }
468
469 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
470
471 impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
472 impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
473
474 /// A wrapper for slices with the additional invariant
475 /// that the slice is interned and no other slice with
476 /// the same contents can exist in the same context.
477 /// This means we can use pointer + length for both
478 /// equality comparisons and hashing.
479 #[derive(Debug, RustcEncodable)]
480 pub struct Slice<T>([T]);
481
482 impl<T> PartialEq for Slice<T> {
483     #[inline]
484     fn eq(&self, other: &Slice<T>) -> bool {
485         (&self.0 as *const [T]) == (&other.0 as *const [T])
486     }
487 }
488 impl<T> Eq for Slice<T> {}
489
490 impl<T> Hash for Slice<T> {
491     fn hash<H: Hasher>(&self, s: &mut H) {
492         (self.as_ptr(), self.len()).hash(s)
493     }
494 }
495
496 impl<T> Deref for Slice<T> {
497     type Target = [T];
498     fn deref(&self) -> &[T] {
499         &self.0
500     }
501 }
502
503 impl<'a, T> IntoIterator for &'a Slice<T> {
504     type Item = &'a T;
505     type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
506     fn into_iter(self) -> Self::IntoIter {
507         self[..].iter()
508     }
509 }
510
511 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
512
513 impl<T> Slice<T> {
514     pub fn empty<'a>() -> &'a Slice<T> {
515         unsafe {
516             mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
517         }
518     }
519 }
520
521 /// Upvars do not get their own node-id. Instead, we use the pair of
522 /// the original var id (that is, the root variable that is referenced
523 /// by the upvar) and the id of the closure expression.
524 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
525 pub struct UpvarId {
526     pub var_id: NodeId,
527     pub closure_expr_id: NodeId,
528 }
529
530 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
531 pub enum BorrowKind {
532     /// Data must be immutable and is aliasable.
533     ImmBorrow,
534
535     /// Data must be immutable but not aliasable.  This kind of borrow
536     /// cannot currently be expressed by the user and is used only in
537     /// implicit closure bindings. It is needed when the closure
538     /// is borrowing or mutating a mutable referent, e.g.:
539     ///
540     ///    let x: &mut isize = ...;
541     ///    let y = || *x += 5;
542     ///
543     /// If we were to try to translate this closure into a more explicit
544     /// form, we'd encounter an error with the code as written:
545     ///
546     ///    struct Env { x: & &mut isize }
547     ///    let x: &mut isize = ...;
548     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
549     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
550     ///
551     /// This is then illegal because you cannot mutate a `&mut` found
552     /// in an aliasable location. To solve, you'd have to translate with
553     /// an `&mut` borrow:
554     ///
555     ///    struct Env { x: & &mut isize }
556     ///    let x: &mut isize = ...;
557     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
558     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
559     ///
560     /// Now the assignment to `**env.x` is legal, but creating a
561     /// mutable pointer to `x` is not because `x` is not mutable. We
562     /// could fix this by declaring `x` as `let mut x`. This is ok in
563     /// user code, if awkward, but extra weird for closures, since the
564     /// borrow is hidden.
565     ///
566     /// So we introduce a "unique imm" borrow -- the referent is
567     /// immutable, but not aliasable. This solves the problem. For
568     /// simplicity, we don't give users the way to express this
569     /// borrow, it's just used when translating closures.
570     UniqueImmBorrow,
571
572     /// Data is mutable and not aliasable.
573     MutBorrow
574 }
575
576 /// Information describing the capture of an upvar. This is computed
577 /// during `typeck`, specifically by `regionck`.
578 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
579 pub enum UpvarCapture<'tcx> {
580     /// Upvar is captured by value. This is always true when the
581     /// closure is labeled `move`, but can also be true in other cases
582     /// depending on inference.
583     ByValue,
584
585     /// Upvar is captured by reference.
586     ByRef(UpvarBorrow<'tcx>),
587 }
588
589 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
590 pub struct UpvarBorrow<'tcx> {
591     /// The kind of borrow: by-ref upvars have access to shared
592     /// immutable borrows, which are not part of the normal language
593     /// syntax.
594     pub kind: BorrowKind,
595
596     /// Region of the resulting reference.
597     pub region: ty::Region<'tcx>,
598 }
599
600 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
601
602 #[derive(Copy, Clone)]
603 pub struct ClosureUpvar<'tcx> {
604     pub def: Def,
605     pub span: Span,
606     pub ty: Ty<'tcx>,
607 }
608
609 #[derive(Clone, Copy, PartialEq)]
610 pub enum IntVarValue {
611     IntType(ast::IntTy),
612     UintType(ast::UintTy),
613 }
614
615 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
616 pub struct TypeParameterDef {
617     pub name: Name,
618     pub def_id: DefId,
619     pub index: u32,
620     pub has_default: bool,
621     pub object_lifetime_default: ObjectLifetimeDefault,
622
623     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
624     /// on generic parameter `T`, asserts data behind the parameter
625     /// `T` won't be accessed during the parent type's `Drop` impl.
626     pub pure_wrt_drop: bool,
627 }
628
629 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
630 pub struct RegionParameterDef {
631     pub name: Name,
632     pub def_id: DefId,
633     pub index: u32,
634     pub issue_32330: Option<ty::Issue32330>,
635
636     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
637     /// on generic parameter `'a`, asserts data of lifetime `'a`
638     /// won't be accessed during the parent type's `Drop` impl.
639     pub pure_wrt_drop: bool,
640 }
641
642 impl RegionParameterDef {
643     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
644         ty::EarlyBoundRegion {
645             def_id: self.def_id,
646             index: self.index,
647             name: self.name,
648         }
649     }
650
651     pub fn to_bound_region(&self) -> ty::BoundRegion {
652         self.to_early_bound_region_data().to_bound_region()
653     }
654 }
655
656 impl ty::EarlyBoundRegion {
657     pub fn to_bound_region(&self) -> ty::BoundRegion {
658         ty::BoundRegion::BrNamed(self.def_id, self.name)
659     }
660 }
661
662 /// Information about the formal type/lifetime parameters associated
663 /// with an item or method. Analogous to hir::Generics.
664 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
665 pub struct Generics {
666     pub parent: Option<DefId>,
667     pub parent_regions: u32,
668     pub parent_types: u32,
669     pub regions: Vec<RegionParameterDef>,
670     pub types: Vec<TypeParameterDef>,
671
672     /// Reverse map to each `TypeParameterDef`'s `index` field, from
673     /// `def_id.index` (`def_id.krate` is the same as the item's).
674     pub type_param_to_index: BTreeMap<DefIndex, u32>,
675
676     pub has_self: bool,
677 }
678
679 impl Generics {
680     pub fn parent_count(&self) -> usize {
681         self.parent_regions as usize + self.parent_types as usize
682     }
683
684     pub fn own_count(&self) -> usize {
685         self.regions.len() + self.types.len()
686     }
687
688     pub fn count(&self) -> usize {
689         self.parent_count() + self.own_count()
690     }
691
692     pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef {
693         assert_eq!(self.parent_count(), 0);
694         &self.regions[param.index as usize - self.has_self as usize]
695     }
696
697     pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef {
698         assert_eq!(self.parent_count(), 0);
699         &self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
700     }
701 }
702
703 /// Bounds on generics.
704 #[derive(Clone, Default)]
705 pub struct GenericPredicates<'tcx> {
706     pub parent: Option<DefId>,
707     pub predicates: Vec<Predicate<'tcx>>,
708 }
709
710 impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
711 impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
712
713 impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
714     pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
715                        -> InstantiatedPredicates<'tcx> {
716         let mut instantiated = InstantiatedPredicates::empty();
717         self.instantiate_into(tcx, &mut instantiated, substs);
718         instantiated
719     }
720     pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
721                            -> InstantiatedPredicates<'tcx> {
722         InstantiatedPredicates {
723             predicates: self.predicates.subst(tcx, substs)
724         }
725     }
726
727     fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
728                         instantiated: &mut InstantiatedPredicates<'tcx>,
729                         substs: &Substs<'tcx>) {
730         if let Some(def_id) = self.parent {
731             tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
732         }
733         instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
734     }
735
736     pub fn instantiate_identity(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
737                                 -> InstantiatedPredicates<'tcx> {
738         let mut instantiated = InstantiatedPredicates::empty();
739         self.instantiate_identity_into(tcx, &mut instantiated);
740         instantiated
741     }
742
743     fn instantiate_identity_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
744                                  instantiated: &mut InstantiatedPredicates<'tcx>) {
745         if let Some(def_id) = self.parent {
746             tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
747         }
748         instantiated.predicates.extend(&self.predicates)
749     }
750
751     pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
752                                   poly_trait_ref: &ty::PolyTraitRef<'tcx>)
753                                   -> InstantiatedPredicates<'tcx>
754     {
755         assert_eq!(self.parent, None);
756         InstantiatedPredicates {
757             predicates: self.predicates.iter().map(|pred| {
758                 pred.subst_supertrait(tcx, poly_trait_ref)
759             }).collect()
760         }
761     }
762 }
763
764 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
765 pub enum Predicate<'tcx> {
766     /// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
767     /// the `Self` type of the trait reference and `A`, `B`, and `C`
768     /// would be the type parameters.
769     Trait(PolyTraitPredicate<'tcx>),
770
771     /// where `T1 == T2`.
772     Equate(PolyEquatePredicate<'tcx>),
773
774     /// where 'a : 'b
775     RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
776
777     /// where T : 'a
778     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
779
780     /// where <T as TraitRef>::Name == X, approximately.
781     /// See `ProjectionPredicate` struct for details.
782     Projection(PolyProjectionPredicate<'tcx>),
783
784     /// no syntax: T WF
785     WellFormed(Ty<'tcx>),
786
787     /// trait must be object-safe
788     ObjectSafe(DefId),
789
790     /// No direct syntax. May be thought of as `where T : FnFoo<...>`
791     /// for some substitutions `...` and T being a closure type.
792     /// Satisfied (or refuted) once we know the closure's kind.
793     ClosureKind(DefId, ClosureKind),
794
795     /// `T1 <: T2`
796     Subtype(PolySubtypePredicate<'tcx>),
797 }
798
799 impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
800     /// Performs a substitution suitable for going from a
801     /// poly-trait-ref to supertraits that must hold if that
802     /// poly-trait-ref holds. This is slightly different from a normal
803     /// substitution in terms of what happens with bound regions.  See
804     /// lengthy comment below for details.
805     pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
806                             trait_ref: &ty::PolyTraitRef<'tcx>)
807                             -> ty::Predicate<'tcx>
808     {
809         // The interaction between HRTB and supertraits is not entirely
810         // obvious. Let me walk you (and myself) through an example.
811         //
812         // Let's start with an easy case. Consider two traits:
813         //
814         //     trait Foo<'a> : Bar<'a,'a> { }
815         //     trait Bar<'b,'c> { }
816         //
817         // Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
818         // we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
819         // knew that `Foo<'x>` (for any 'x) then we also know that
820         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
821         // normal substitution.
822         //
823         // In terms of why this is sound, the idea is that whenever there
824         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
825         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
826         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
827         // `'a`.
828         //
829         // Another example to be careful of is this:
830         //
831         //     trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
832         //     trait Bar1<'b,'c> { }
833         //
834         // Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
835         // The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
836         // reason is similar to the previous example: any impl of
837         // `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`.  So
838         // basically we would want to collapse the bound lifetimes from
839         // the input (`trait_ref`) and the supertraits.
840         //
841         // To achieve this in practice is fairly straightforward. Let's
842         // consider the more complicated scenario:
843         //
844         // - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
845         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
846         //   where both `'x` and `'b` would have a DB index of 1.
847         //   The substitution from the input trait-ref is therefore going to be
848         //   `'a => 'x` (where `'x` has a DB index of 1).
849         // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
850         //   early-bound parameter and `'b' is a late-bound parameter with a
851         //   DB index of 1.
852         // - If we replace `'a` with `'x` from the input, it too will have
853         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
854         //   just as we wanted.
855         //
856         // There is only one catch. If we just apply the substitution `'a
857         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
858         // adjust the DB index because we substituting into a binder (it
859         // tries to be so smart...) resulting in `for<'x> for<'b>
860         // Bar1<'x,'b>` (we have no syntax for this, so use your
861         // imagination). Basically the 'x will have DB index of 2 and 'b
862         // will have DB index of 1. Not quite what we want. So we apply
863         // the substitution to the *contents* of the trait reference,
864         // rather than the trait reference itself (put another way, the
865         // substitution code expects equal binding levels in the values
866         // from the substitution and the value being substituted into, and
867         // this trick achieves that).
868
869         let substs = &trait_ref.0.substs;
870         match *self {
871             Predicate::Trait(ty::Binder(ref data)) =>
872                 Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
873             Predicate::Equate(ty::Binder(ref data)) =>
874                 Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
875             Predicate::Subtype(ty::Binder(ref data)) =>
876                 Predicate::Subtype(ty::Binder(data.subst(tcx, substs))),
877             Predicate::RegionOutlives(ty::Binder(ref data)) =>
878                 Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
879             Predicate::TypeOutlives(ty::Binder(ref data)) =>
880                 Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
881             Predicate::Projection(ty::Binder(ref data)) =>
882                 Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
883             Predicate::WellFormed(data) =>
884                 Predicate::WellFormed(data.subst(tcx, substs)),
885             Predicate::ObjectSafe(trait_def_id) =>
886                 Predicate::ObjectSafe(trait_def_id),
887             Predicate::ClosureKind(closure_def_id, kind) =>
888                 Predicate::ClosureKind(closure_def_id, kind),
889         }
890     }
891 }
892
893 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
894 pub struct TraitPredicate<'tcx> {
895     pub trait_ref: TraitRef<'tcx>
896 }
897 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
898
899 impl<'tcx> TraitPredicate<'tcx> {
900     pub fn def_id(&self) -> DefId {
901         self.trait_ref.def_id
902     }
903
904     /// Creates the dep-node for selecting/evaluating this trait reference.
905     fn dep_node(&self) -> DepNode<DefId> {
906         // Extact the trait-def and first def-id from inputs.  See the
907         // docs for `DepNode::TraitSelect` for more information.
908         let trait_def_id = self.def_id();
909         let input_def_id =
910             self.input_types()
911                 .flat_map(|t| t.walk())
912                 .filter_map(|t| match t.sty {
913                     ty::TyAdt(adt_def, _) => Some(adt_def.did),
914                     _ => None
915                 })
916                 .next()
917                 .unwrap_or(trait_def_id);
918         DepNode::TraitSelect {
919             trait_def_id: trait_def_id,
920             input_def_id: input_def_id
921         }
922     }
923
924     pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
925         self.trait_ref.input_types()
926     }
927
928     pub fn self_ty(&self) -> Ty<'tcx> {
929         self.trait_ref.self_ty()
930     }
931 }
932
933 impl<'tcx> PolyTraitPredicate<'tcx> {
934     pub fn def_id(&self) -> DefId {
935         // ok to skip binder since trait def-id does not care about regions
936         self.0.def_id()
937     }
938
939     pub fn dep_node(&self) -> DepNode<DefId> {
940         // ok to skip binder since depnode does not care about regions
941         self.0.dep_node()
942     }
943 }
944
945 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
946 pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
947 pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
948
949 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
950 pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
951 pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
952 pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<ty::Region<'tcx>,
953                                                                    ty::Region<'tcx>>;
954 pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
955
956 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
957 pub struct SubtypePredicate<'tcx> {
958     pub a_is_expected: bool,
959     pub a: Ty<'tcx>,
960     pub b: Ty<'tcx>
961 }
962 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
963
964 /// This kind of predicate has no *direct* correspondent in the
965 /// syntax, but it roughly corresponds to the syntactic forms:
966 ///
967 /// 1. `T : TraitRef<..., Item=Type>`
968 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
969 ///
970 /// In particular, form #1 is "desugared" to the combination of a
971 /// normal trait predicate (`T : TraitRef<...>`) and one of these
972 /// predicates. Form #2 is a broader form in that it also permits
973 /// equality between arbitrary types. Processing an instance of Form
974 /// #2 eventually yields one of these `ProjectionPredicate`
975 /// instances to normalize the LHS.
976 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
977 pub struct ProjectionPredicate<'tcx> {
978     pub projection_ty: ProjectionTy<'tcx>,
979     pub ty: Ty<'tcx>,
980 }
981
982 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
983
984 impl<'tcx> PolyProjectionPredicate<'tcx> {
985     pub fn item_name(&self, tcx: TyCtxt) -> Name {
986         self.0.projection_ty.item_name(tcx) // safe to skip the binder to access a name
987     }
988 }
989
990 pub trait ToPolyTraitRef<'tcx> {
991     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
992 }
993
994 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
995     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
996         assert!(!self.has_escaping_regions());
997         ty::Binder(self.clone())
998     }
999 }
1000
1001 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1002     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1003         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1004     }
1005 }
1006
1007 impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
1008     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1009         // Note: unlike with TraitRef::to_poly_trait_ref(),
1010         // self.0.trait_ref is permitted to have escaping regions.
1011         // This is because here `self` has a `Binder` and so does our
1012         // return value, so we are preserving the number of binding
1013         // levels.
1014         ty::Binder(self.0.projection_ty.trait_ref)
1015     }
1016 }
1017
1018 pub trait ToPredicate<'tcx> {
1019     fn to_predicate(&self) -> Predicate<'tcx>;
1020 }
1021
1022 impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
1023     fn to_predicate(&self) -> Predicate<'tcx> {
1024         // we're about to add a binder, so let's check that we don't
1025         // accidentally capture anything, or else that might be some
1026         // weird debruijn accounting.
1027         assert!(!self.has_escaping_regions());
1028
1029         ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
1030             trait_ref: self.clone()
1031         }))
1032     }
1033 }
1034
1035 impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
1036     fn to_predicate(&self) -> Predicate<'tcx> {
1037         ty::Predicate::Trait(self.to_poly_trait_predicate())
1038     }
1039 }
1040
1041 impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
1042     fn to_predicate(&self) -> Predicate<'tcx> {
1043         Predicate::Equate(self.clone())
1044     }
1045 }
1046
1047 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1048     fn to_predicate(&self) -> Predicate<'tcx> {
1049         Predicate::RegionOutlives(self.clone())
1050     }
1051 }
1052
1053 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1054     fn to_predicate(&self) -> Predicate<'tcx> {
1055         Predicate::TypeOutlives(self.clone())
1056     }
1057 }
1058
1059 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1060     fn to_predicate(&self) -> Predicate<'tcx> {
1061         Predicate::Projection(self.clone())
1062     }
1063 }
1064
1065 impl<'tcx> Predicate<'tcx> {
1066     /// Iterates over the types in this predicate. Note that in all
1067     /// cases this is skipping over a binder, so late-bound regions
1068     /// with depth 0 are bound by the predicate.
1069     pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
1070         let vec: Vec<_> = match *self {
1071             ty::Predicate::Trait(ref data) => {
1072                 data.skip_binder().input_types().collect()
1073             }
1074             ty::Predicate::Equate(ty::Binder(ref data)) => {
1075                 vec![data.0, data.1]
1076             }
1077             ty::Predicate::Subtype(ty::Binder(SubtypePredicate { a, b, a_is_expected: _ })) => {
1078                 vec![a, b]
1079             }
1080             ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
1081                 vec![data.0]
1082             }
1083             ty::Predicate::RegionOutlives(..) => {
1084                 vec![]
1085             }
1086             ty::Predicate::Projection(ref data) => {
1087                 let trait_inputs = data.0.projection_ty.trait_ref.input_types();
1088                 trait_inputs.chain(Some(data.0.ty)).collect()
1089             }
1090             ty::Predicate::WellFormed(data) => {
1091                 vec![data]
1092             }
1093             ty::Predicate::ObjectSafe(_trait_def_id) => {
1094                 vec![]
1095             }
1096             ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
1097                 vec![]
1098             }
1099         };
1100
1101         // The only reason to collect into a vector here is that I was
1102         // too lazy to make the full (somewhat complicated) iterator
1103         // type that would be needed here. But I wanted this fn to
1104         // return an iterator conceptually, rather than a `Vec`, so as
1105         // to be closer to `Ty::walk`.
1106         vec.into_iter()
1107     }
1108
1109     pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
1110         match *self {
1111             Predicate::Trait(ref t) => {
1112                 Some(t.to_poly_trait_ref())
1113             }
1114             Predicate::Projection(..) |
1115             Predicate::Equate(..) |
1116             Predicate::Subtype(..) |
1117             Predicate::RegionOutlives(..) |
1118             Predicate::WellFormed(..) |
1119             Predicate::ObjectSafe(..) |
1120             Predicate::ClosureKind(..) |
1121             Predicate::TypeOutlives(..) => {
1122                 None
1123             }
1124         }
1125     }
1126 }
1127
1128 /// Represents the bounds declared on a particular set of type
1129 /// parameters.  Should eventually be generalized into a flag list of
1130 /// where clauses.  You can obtain a `InstantiatedPredicates` list from a
1131 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1132 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1133 /// the `GenericPredicates` are expressed in terms of the bound type
1134 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1135 /// represented a set of bounds for some particular instantiation,
1136 /// meaning that the generic parameters have been substituted with
1137 /// their values.
1138 ///
1139 /// Example:
1140 ///
1141 ///     struct Foo<T,U:Bar<T>> { ... }
1142 ///
1143 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1144 /// `[[], [U:Bar<T>]]`.  Now if there were some particular reference
1145 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1146 /// [usize:Bar<isize>]]`.
1147 #[derive(Clone)]
1148 pub struct InstantiatedPredicates<'tcx> {
1149     pub predicates: Vec<Predicate<'tcx>>,
1150 }
1151
1152 impl<'tcx> InstantiatedPredicates<'tcx> {
1153     pub fn empty() -> InstantiatedPredicates<'tcx> {
1154         InstantiatedPredicates { predicates: vec![] }
1155     }
1156
1157     pub fn is_empty(&self) -> bool {
1158         self.predicates.is_empty()
1159     }
1160 }
1161
1162 /// When type checking, we use the `ParamEnv` to track
1163 /// details about the set of where-clauses that are in scope at this
1164 /// particular point.
1165 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1166 pub struct ParamEnv<'tcx> {
1167     /// Obligations that the caller must satisfy. This is basically
1168     /// the set of bounds on the in-scope type parameters, translated
1169     /// into Obligations, and elaborated and normalized.
1170     pub caller_bounds: &'tcx Slice<ty::Predicate<'tcx>>,
1171
1172     /// Typically, this is `Reveal::UserFacing`, but during trans we
1173     /// want `Reveal::All` -- note that this is always paired with an
1174     /// empty environment. To get that, use `ParamEnv::reveal()`.
1175     pub reveal: traits::Reveal,
1176 }
1177
1178 impl<'tcx> ParamEnv<'tcx> {
1179     /// Creates a suitable environment in which to perform trait
1180     /// queries on the given value. This will either be `self` *or*
1181     /// the empty environment, depending on whether `value` references
1182     /// type parameters that are in scope. (If it doesn't, then any
1183     /// judgements should be completely independent of the context,
1184     /// and hence we can safely use the empty environment so as to
1185     /// enable more sharing across functions.)
1186     ///
1187     /// NB: This is a mildly dubious thing to do, in that a function
1188     /// (or other environment) might have wacky where-clauses like
1189     /// `where Box<u32>: Copy`, which are clearly never
1190     /// satisfiable. The code will at present ignore these,
1191     /// effectively, when type-checking the body of said
1192     /// function. This preserves existing behavior in any
1193     /// case. --nmatsakis
1194     pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1195         assert!(!value.needs_infer());
1196         if value.has_param_types() || value.has_self_ty() {
1197             ParamEnvAnd {
1198                 param_env: self,
1199                 value: value,
1200             }
1201         } else {
1202             ParamEnvAnd {
1203                 param_env: ParamEnv::empty(self.reveal),
1204                 value: value,
1205             }
1206         }
1207     }
1208 }
1209
1210 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1211 pub struct ParamEnvAnd<'tcx, T> {
1212     pub param_env: ParamEnv<'tcx>,
1213     pub value: T,
1214 }
1215
1216 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1217     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1218         (self.param_env, self.value)
1219     }
1220 }
1221
1222 #[derive(Copy, Clone, Debug)]
1223 pub struct Destructor {
1224     /// The def-id of the destructor method
1225     pub did: DefId,
1226 }
1227
1228 bitflags! {
1229     flags AdtFlags: u32 {
1230         const NO_ADT_FLAGS        = 0,
1231         const IS_ENUM             = 1 << 0,
1232         const IS_PHANTOM_DATA     = 1 << 1,
1233         const IS_FUNDAMENTAL      = 1 << 2,
1234         const IS_UNION            = 1 << 3,
1235         const IS_BOX              = 1 << 4,
1236     }
1237 }
1238
1239 #[derive(Debug)]
1240 pub struct VariantDef {
1241     /// The variant's DefId. If this is a tuple-like struct,
1242     /// this is the DefId of the struct's ctor.
1243     pub did: DefId,
1244     pub name: Name, // struct's name if this is a struct
1245     pub discr: VariantDiscr,
1246     pub fields: Vec<FieldDef>,
1247     pub ctor_kind: CtorKind,
1248 }
1249
1250 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1251 pub enum VariantDiscr {
1252     /// Explicit value for this variant, i.e. `X = 123`.
1253     /// The `DefId` corresponds to the embedded constant.
1254     Explicit(DefId),
1255
1256     /// The previous variant's discriminant plus one.
1257     /// For efficiency reasons, the distance from the
1258     /// last `Explicit` discriminant is being stored,
1259     /// or `0` for the first variant, if it has none.
1260     Relative(usize),
1261 }
1262
1263 #[derive(Debug)]
1264 pub struct FieldDef {
1265     pub did: DefId,
1266     pub name: Name,
1267     pub vis: Visibility,
1268 }
1269
1270 /// The definition of an abstract data type - a struct or enum.
1271 ///
1272 /// These are all interned (by intern_adt_def) into the adt_defs
1273 /// table.
1274 pub struct AdtDef {
1275     pub did: DefId,
1276     pub variants: Vec<VariantDef>,
1277     flags: AdtFlags,
1278     pub repr: ReprOptions,
1279 }
1280
1281 impl PartialEq for AdtDef {
1282     // AdtDef are always interned and this is part of TyS equality
1283     #[inline]
1284     fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
1285 }
1286
1287 impl Eq for AdtDef {}
1288
1289 impl Hash for AdtDef {
1290     #[inline]
1291     fn hash<H: Hasher>(&self, s: &mut H) {
1292         (self as *const AdtDef).hash(s)
1293     }
1294 }
1295
1296 impl<'tcx> serialize::UseSpecializedEncodable for &'tcx AdtDef {
1297     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1298         self.did.encode(s)
1299     }
1300 }
1301
1302 impl<'tcx> serialize::UseSpecializedDecodable for &'tcx AdtDef {}
1303
1304
1305 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for AdtDef {
1306     fn hash_stable<W: StableHasherResult>(&self,
1307                                           hcx: &mut StableHashingContext<'a, 'tcx>,
1308                                           hasher: &mut StableHasher<W>) {
1309         let ty::AdtDef {
1310             did,
1311             ref variants,
1312             ref flags,
1313             ref repr,
1314         } = *self;
1315
1316         did.hash_stable(hcx, hasher);
1317         variants.hash_stable(hcx, hasher);
1318         flags.hash_stable(hcx, hasher);
1319         repr.hash_stable(hcx, hasher);
1320     }
1321 }
1322
1323 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1324 pub enum AdtKind { Struct, Union, Enum }
1325
1326 bitflags! {
1327     #[derive(RustcEncodable, RustcDecodable, Default)]
1328     flags ReprFlags: u8 {
1329         const IS_C               = 1 << 0,
1330         const IS_PACKED          = 1 << 1,
1331         const IS_SIMD            = 1 << 2,
1332         // Internal only for now. If true, don't reorder fields.
1333         const IS_LINEAR          = 1 << 3,
1334
1335         // Any of these flags being set prevent field reordering optimisation.
1336         const IS_UNOPTIMISABLE   = ReprFlags::IS_C.bits |
1337                                    ReprFlags::IS_PACKED.bits |
1338                                    ReprFlags::IS_SIMD.bits |
1339                                    ReprFlags::IS_LINEAR.bits,
1340     }
1341 }
1342
1343 impl_stable_hash_for!(struct ReprFlags {
1344     bits
1345 });
1346
1347
1348
1349 /// Represents the repr options provided by the user,
1350 #[derive(Copy, Clone, Eq, PartialEq, RustcEncodable, RustcDecodable, Default)]
1351 pub struct ReprOptions {
1352     pub int: Option<attr::IntType>,
1353     pub align: u16,
1354     pub flags: ReprFlags,
1355 }
1356
1357 impl_stable_hash_for!(struct ReprOptions {
1358     align,
1359     int,
1360     flags
1361 });
1362
1363 impl ReprOptions {
1364     pub fn new(tcx: TyCtxt, did: DefId) -> ReprOptions {
1365         let mut flags = ReprFlags::empty();
1366         let mut size = None;
1367         let mut max_align = 0;
1368         for attr in tcx.get_attrs(did).iter() {
1369             for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) {
1370                 flags.insert(match r {
1371                     attr::ReprExtern => ReprFlags::IS_C,
1372                     attr::ReprPacked => ReprFlags::IS_PACKED,
1373                     attr::ReprSimd => ReprFlags::IS_SIMD,
1374                     attr::ReprInt(i) => {
1375                         size = Some(i);
1376                         ReprFlags::empty()
1377                     },
1378                     attr::ReprAlign(align) => {
1379                         max_align = cmp::max(align, max_align);
1380                         ReprFlags::empty()
1381                     },
1382                 });
1383             }
1384         }
1385
1386         // FIXME(eddyb) This is deprecated and should be removed.
1387         if tcx.has_attr(did, "simd") {
1388             flags.insert(ReprFlags::IS_SIMD);
1389         }
1390
1391         // This is here instead of layout because the choice must make it into metadata.
1392         if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.item_path_str(did))) {
1393             flags.insert(ReprFlags::IS_LINEAR);
1394         }
1395         ReprOptions { int: size, align: max_align, flags: flags }
1396     }
1397
1398     #[inline]
1399     pub fn simd(&self) -> bool { self.flags.contains(ReprFlags::IS_SIMD) }
1400     #[inline]
1401     pub fn c(&self) -> bool { self.flags.contains(ReprFlags::IS_C) }
1402     #[inline]
1403     pub fn packed(&self) -> bool { self.flags.contains(ReprFlags::IS_PACKED) }
1404     #[inline]
1405     pub fn linear(&self) -> bool { self.flags.contains(ReprFlags::IS_LINEAR) }
1406
1407     pub fn discr_type(&self) -> attr::IntType {
1408         self.int.unwrap_or(attr::SignedInt(ast::IntTy::Is))
1409     }
1410
1411     /// Returns true if this `#[repr()]` should inhabit "smart enum
1412     /// layout" optimizations, such as representing `Foo<&T>` as a
1413     /// single pointer.
1414     pub fn inhibit_enum_layout_opt(&self) -> bool {
1415         self.c() || self.int.is_some()
1416     }
1417 }
1418
1419 impl<'a, 'gcx, 'tcx> AdtDef {
1420     fn new(tcx: TyCtxt,
1421            did: DefId,
1422            kind: AdtKind,
1423            variants: Vec<VariantDef>,
1424            repr: ReprOptions) -> Self {
1425         let mut flags = AdtFlags::NO_ADT_FLAGS;
1426         let attrs = tcx.get_attrs(did);
1427         if attr::contains_name(&attrs, "fundamental") {
1428             flags = flags | AdtFlags::IS_FUNDAMENTAL;
1429         }
1430         if Some(did) == tcx.lang_items.phantom_data() {
1431             flags = flags | AdtFlags::IS_PHANTOM_DATA;
1432         }
1433         if Some(did) == tcx.lang_items.owned_box() {
1434             flags = flags | AdtFlags::IS_BOX;
1435         }
1436         match kind {
1437             AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
1438             AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
1439             AdtKind::Struct => {}
1440         }
1441         AdtDef {
1442             did: did,
1443             variants: variants,
1444             flags: flags,
1445             repr: repr,
1446         }
1447     }
1448
1449     #[inline]
1450     pub fn is_struct(&self) -> bool {
1451         !self.is_union() && !self.is_enum()
1452     }
1453
1454     #[inline]
1455     pub fn is_union(&self) -> bool {
1456         self.flags.intersects(AdtFlags::IS_UNION)
1457     }
1458
1459     #[inline]
1460     pub fn is_enum(&self) -> bool {
1461         self.flags.intersects(AdtFlags::IS_ENUM)
1462     }
1463
1464     /// Returns the kind of the ADT - Struct or Enum.
1465     #[inline]
1466     pub fn adt_kind(&self) -> AdtKind {
1467         if self.is_enum() {
1468             AdtKind::Enum
1469         } else if self.is_union() {
1470             AdtKind::Union
1471         } else {
1472             AdtKind::Struct
1473         }
1474     }
1475
1476     pub fn descr(&self) -> &'static str {
1477         match self.adt_kind() {
1478             AdtKind::Struct => "struct",
1479             AdtKind::Union => "union",
1480             AdtKind::Enum => "enum",
1481         }
1482     }
1483
1484     pub fn variant_descr(&self) -> &'static str {
1485         match self.adt_kind() {
1486             AdtKind::Struct => "struct",
1487             AdtKind::Union => "union",
1488             AdtKind::Enum => "variant",
1489         }
1490     }
1491
1492     /// Returns whether this type is #[fundamental] for the purposes
1493     /// of coherence checking.
1494     #[inline]
1495     pub fn is_fundamental(&self) -> bool {
1496         self.flags.intersects(AdtFlags::IS_FUNDAMENTAL)
1497     }
1498
1499     /// Returns true if this is PhantomData<T>.
1500     #[inline]
1501     pub fn is_phantom_data(&self) -> bool {
1502         self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
1503     }
1504
1505     /// Returns true if this is Box<T>.
1506     #[inline]
1507     pub fn is_box(&self) -> bool {
1508         self.flags.intersects(AdtFlags::IS_BOX)
1509     }
1510
1511     /// Returns whether this type has a destructor.
1512     pub fn has_dtor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> bool {
1513         self.destructor(tcx).is_some()
1514     }
1515
1516     /// Asserts this is a struct and returns the struct's unique
1517     /// variant.
1518     pub fn struct_variant(&self) -> &VariantDef {
1519         assert!(!self.is_enum());
1520         &self.variants[0]
1521     }
1522
1523     #[inline]
1524     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
1525         tcx.predicates_of(self.did)
1526     }
1527
1528     /// Returns an iterator over all fields contained
1529     /// by this ADT.
1530     #[inline]
1531     pub fn all_fields<'s>(&'s self) -> impl Iterator<Item = &'s FieldDef> {
1532         self.variants.iter().flat_map(|v| v.fields.iter())
1533     }
1534
1535     #[inline]
1536     pub fn is_univariant(&self) -> bool {
1537         self.variants.len() == 1
1538     }
1539
1540     pub fn is_payloadfree(&self) -> bool {
1541         !self.variants.is_empty() &&
1542             self.variants.iter().all(|v| v.fields.is_empty())
1543     }
1544
1545     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
1546         self.variants
1547             .iter()
1548             .find(|v| v.did == vid)
1549             .expect("variant_with_id: unknown variant")
1550     }
1551
1552     pub fn variant_index_with_id(&self, vid: DefId) -> usize {
1553         self.variants
1554             .iter()
1555             .position(|v| v.did == vid)
1556             .expect("variant_index_with_id: unknown variant")
1557     }
1558
1559     pub fn variant_of_def(&self, def: Def) -> &VariantDef {
1560         match def {
1561             Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
1562             Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1563             Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
1564             _ => bug!("unexpected def {:?} in variant_of_def", def)
1565         }
1566     }
1567
1568     #[inline]
1569     pub fn discriminants(&'a self, tcx: TyCtxt<'a, 'gcx, 'tcx>)
1570                          -> impl Iterator<Item=ConstInt> + 'a {
1571         let repr_type = self.repr.discr_type();
1572         let initial = repr_type.initial_discriminant(tcx.global_tcx());
1573         let mut prev_discr = None::<ConstInt>;
1574         self.variants.iter().map(move |v| {
1575             let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr());
1576             if let VariantDiscr::Explicit(expr_did) = v.discr {
1577                 let substs = Substs::empty();
1578                 match tcx.const_eval((expr_did, substs)) {
1579                     Ok(ConstVal::Integral(v)) => {
1580                         discr = v;
1581                     }
1582                     err => {
1583                         if !expr_did.is_local() {
1584                             span_bug!(tcx.def_span(expr_did),
1585                                 "variant discriminant evaluation succeeded \
1586                                  in its crate but failed locally: {:?}", err);
1587                         }
1588                     }
1589                 }
1590             }
1591             prev_discr = Some(discr);
1592
1593             discr
1594         })
1595     }
1596
1597     /// Compute the discriminant value used by a specific variant.
1598     /// Unlike `discriminants`, this is (amortized) constant-time,
1599     /// only doing at most one query for evaluating an explicit
1600     /// discriminant (the last one before the requested variant),
1601     /// assuming there are no constant-evaluation errors there.
1602     pub fn discriminant_for_variant(&self,
1603                                     tcx: TyCtxt<'a, 'gcx, 'tcx>,
1604                                     variant_index: usize)
1605                                     -> ConstInt {
1606         let repr_type = self.repr.discr_type();
1607         let mut explicit_value = repr_type.initial_discriminant(tcx.global_tcx());
1608         let mut explicit_index = variant_index;
1609         loop {
1610             match self.variants[explicit_index].discr {
1611                 ty::VariantDiscr::Relative(0) => break,
1612                 ty::VariantDiscr::Relative(distance) => {
1613                     explicit_index -= distance;
1614                 }
1615                 ty::VariantDiscr::Explicit(expr_did) => {
1616                     let substs = Substs::empty();
1617                     match tcx.const_eval((expr_did, substs)) {
1618                         Ok(ConstVal::Integral(v)) => {
1619                             explicit_value = v;
1620                             break;
1621                         }
1622                         err => {
1623                             if !expr_did.is_local() {
1624                                 span_bug!(tcx.def_span(expr_did),
1625                                     "variant discriminant evaluation succeeded \
1626                                      in its crate but failed locally: {:?}", err);
1627                             }
1628                             if explicit_index == 0 {
1629                                 break;
1630                             }
1631                             explicit_index -= 1;
1632                         }
1633                     }
1634                 }
1635             }
1636         }
1637         let discr = explicit_value.to_u128_unchecked()
1638             .wrapping_add((variant_index - explicit_index) as u128);
1639         match repr_type {
1640             attr::UnsignedInt(ty) => {
1641                 ConstInt::new_unsigned_truncating(discr, ty,
1642                                                   tcx.sess.target.uint_type)
1643             }
1644             attr::SignedInt(ty) => {
1645                 ConstInt::new_signed_truncating(discr as i128, ty,
1646                                                 tcx.sess.target.int_type)
1647             }
1648         }
1649     }
1650
1651     pub fn destructor(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option<Destructor> {
1652         tcx.adt_destructor(self.did)
1653     }
1654
1655     /// Returns a list of types such that `Self: Sized` if and only
1656     /// if that type is Sized, or `TyErr` if this type is recursive.
1657     ///
1658     /// Oddly enough, checking that the sized-constraint is Sized is
1659     /// actually more expressive than checking all members:
1660     /// the Sized trait is inductive, so an associated type that references
1661     /// Self would prevent its containing ADT from being Sized.
1662     ///
1663     /// Due to normalization being eager, this applies even if
1664     /// the associated type is behind a pointer, e.g. issue #31299.
1665     pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] {
1666         match queries::adt_sized_constraint::try_get(tcx, DUMMY_SP, self.did) {
1667             Ok(tys) => tys,
1668             Err(_) => {
1669                 debug!("adt_sized_constraint: {:?} is recursive", self);
1670                 // This should be reported as an error by `check_representable`.
1671                 //
1672                 // Consider the type as Sized in the meanwhile to avoid
1673                 // further errors.
1674                 tcx.intern_type_list(&[tcx.types.err])
1675             }
1676         }
1677     }
1678
1679     fn sized_constraint_for_ty(&self,
1680                                tcx: TyCtxt<'a, 'tcx, 'tcx>,
1681                                ty: Ty<'tcx>)
1682                                -> Vec<Ty<'tcx>> {
1683         let result = match ty.sty {
1684             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
1685             TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
1686             TyArray(..) | TyClosure(..) | TyNever => {
1687                 vec![]
1688             }
1689
1690             TyStr | TyDynamic(..) | TySlice(_) | TyError => {
1691                 // these are never sized - return the target type
1692                 vec![ty]
1693             }
1694
1695             TyTuple(ref tys, _) => {
1696                 match tys.last() {
1697                     None => vec![],
1698                     Some(ty) => self.sized_constraint_for_ty(tcx, ty)
1699                 }
1700             }
1701
1702             TyAdt(adt, substs) => {
1703                 // recursive case
1704                 let adt_tys = adt.sized_constraint(tcx);
1705                 debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
1706                        ty, adt_tys);
1707                 adt_tys.iter()
1708                     .map(|ty| ty.subst(tcx, substs))
1709                     .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
1710                     .collect()
1711             }
1712
1713             TyProjection(..) | TyAnon(..) => {
1714                 // must calculate explicitly.
1715                 // FIXME: consider special-casing always-Sized projections
1716                 vec![ty]
1717             }
1718
1719             TyParam(..) => {
1720                 // perf hack: if there is a `T: Sized` bound, then
1721                 // we know that `T` is Sized and do not need to check
1722                 // it on the impl.
1723
1724                 let sized_trait = match tcx.lang_items.sized_trait() {
1725                     Some(x) => x,
1726                     _ => return vec![ty]
1727                 };
1728                 let sized_predicate = Binder(TraitRef {
1729                     def_id: sized_trait,
1730                     substs: tcx.mk_substs_trait(ty, &[])
1731                 }).to_predicate();
1732                 let predicates = tcx.predicates_of(self.did).predicates;
1733                 if predicates.into_iter().any(|p| p == sized_predicate) {
1734                     vec![]
1735                 } else {
1736                     vec![ty]
1737                 }
1738             }
1739
1740             TyInfer(..) => {
1741                 bug!("unexpected type `{:?}` in sized_constraint_for_ty",
1742                      ty)
1743             }
1744         };
1745         debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
1746         result
1747     }
1748 }
1749
1750 impl<'a, 'gcx, 'tcx> VariantDef {
1751     #[inline]
1752     pub fn find_field_named(&self, name: ast::Name) -> Option<&FieldDef> {
1753         self.index_of_field_named(name).map(|index| &self.fields[index])
1754     }
1755
1756     pub fn index_of_field_named(&self, name: ast::Name) -> Option<usize> {
1757         if let Some(index) = self.fields.iter().position(|f| f.name == name) {
1758             return Some(index);
1759         }
1760         let mut ident = name.to_ident();
1761         while ident.ctxt != SyntaxContext::empty() {
1762             ident.ctxt.remove_mark();
1763             if let Some(field) = self.fields.iter().position(|f| f.name.to_ident() == ident) {
1764                 return Some(field);
1765             }
1766         }
1767         None
1768     }
1769
1770     #[inline]
1771     pub fn field_named(&self, name: ast::Name) -> &FieldDef {
1772         self.find_field_named(name).unwrap()
1773     }
1774 }
1775
1776 impl<'a, 'gcx, 'tcx> FieldDef {
1777     pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
1778         tcx.type_of(self.did).subst(tcx, subst)
1779     }
1780 }
1781
1782 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1783 pub enum ClosureKind {
1784     // Warning: Ordering is significant here! The ordering is chosen
1785     // because the trait Fn is a subtrait of FnMut and so in turn, and
1786     // hence we order it so that Fn < FnMut < FnOnce.
1787     Fn,
1788     FnMut,
1789     FnOnce,
1790 }
1791
1792 impl<'a, 'tcx> ClosureKind {
1793     pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
1794         match *self {
1795             ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem),
1796             ClosureKind::FnMut => {
1797                 tcx.require_lang_item(FnMutTraitLangItem)
1798             }
1799             ClosureKind::FnOnce => {
1800                 tcx.require_lang_item(FnOnceTraitLangItem)
1801             }
1802         }
1803     }
1804
1805     /// True if this a type that impls this closure kind
1806     /// must also implement `other`.
1807     pub fn extends(self, other: ty::ClosureKind) -> bool {
1808         match (self, other) {
1809             (ClosureKind::Fn, ClosureKind::Fn) => true,
1810             (ClosureKind::Fn, ClosureKind::FnMut) => true,
1811             (ClosureKind::Fn, ClosureKind::FnOnce) => true,
1812             (ClosureKind::FnMut, ClosureKind::FnMut) => true,
1813             (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
1814             (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
1815             _ => false,
1816         }
1817     }
1818 }
1819
1820 impl<'tcx> TyS<'tcx> {
1821     /// Iterator that walks `self` and any types reachable from
1822     /// `self`, in depth-first order. Note that just walks the types
1823     /// that appear in `self`, it does not descend into the fields of
1824     /// structs or variants. For example:
1825     ///
1826     /// ```notrust
1827     /// isize => { isize }
1828     /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
1829     /// [isize] => { [isize], isize }
1830     /// ```
1831     pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
1832         TypeWalker::new(self)
1833     }
1834
1835     /// Iterator that walks the immediate children of `self`.  Hence
1836     /// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
1837     /// (but not `i32`, like `walk`).
1838     pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
1839         walk::walk_shallow(self)
1840     }
1841
1842     /// Walks `ty` and any types appearing within `ty`, invoking the
1843     /// callback `f` on each type. If the callback returns false, then the
1844     /// children of the current type are ignored.
1845     ///
1846     /// Note: prefer `ty.walk()` where possible.
1847     pub fn maybe_walk<F>(&'tcx self, mut f: F)
1848         where F : FnMut(Ty<'tcx>) -> bool
1849     {
1850         let mut walker = self.walk();
1851         while let Some(ty) = walker.next() {
1852             if !f(ty) {
1853                 walker.skip_current_subtree();
1854             }
1855         }
1856     }
1857 }
1858
1859 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1860 pub enum LvaluePreference {
1861     PreferMutLvalue,
1862     NoPreference
1863 }
1864
1865 impl LvaluePreference {
1866     pub fn from_mutbl(m: hir::Mutability) -> Self {
1867         match m {
1868             hir::MutMutable => PreferMutLvalue,
1869             hir::MutImmutable => NoPreference,
1870         }
1871     }
1872 }
1873
1874 impl BorrowKind {
1875     pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
1876         match m {
1877             hir::MutMutable => MutBorrow,
1878             hir::MutImmutable => ImmBorrow,
1879         }
1880     }
1881
1882     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
1883     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
1884     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
1885     /// question.
1886     pub fn to_mutbl_lossy(self) -> hir::Mutability {
1887         match self {
1888             MutBorrow => hir::MutMutable,
1889             ImmBorrow => hir::MutImmutable,
1890
1891             // We have no type corresponding to a unique imm borrow, so
1892             // use `&mut`. It gives all the capabilities of an `&uniq`
1893             // and hence is a safe "over approximation".
1894             UniqueImmBorrow => hir::MutMutable,
1895         }
1896     }
1897
1898     pub fn to_user_str(&self) -> &'static str {
1899         match *self {
1900             MutBorrow => "mutable",
1901             ImmBorrow => "immutable",
1902             UniqueImmBorrow => "uniquely immutable",
1903         }
1904     }
1905 }
1906
1907 #[derive(Debug, Clone)]
1908 pub enum Attributes<'gcx> {
1909     Owned(Rc<[ast::Attribute]>),
1910     Borrowed(&'gcx [ast::Attribute])
1911 }
1912
1913 impl<'gcx> ::std::ops::Deref for Attributes<'gcx> {
1914     type Target = [ast::Attribute];
1915
1916     fn deref(&self) -> &[ast::Attribute] {
1917         match self {
1918             &Attributes::Owned(ref data) => &data,
1919             &Attributes::Borrowed(data) => data
1920         }
1921     }
1922 }
1923
1924 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1925     pub fn body_tables(self, body: hir::BodyId) -> &'gcx TypeckTables<'gcx> {
1926         self.typeck_tables_of(self.hir.body_owner_def_id(body))
1927     }
1928
1929     /// Returns an iterator of the def-ids for all body-owners in this
1930     /// crate. If you would prefer to iterate over the bodies
1931     /// themselves, you can do `self.hir.krate().body_ids.iter()`.
1932     pub fn body_owners(self) -> impl Iterator<Item = DefId> + 'a {
1933         self.hir.krate()
1934                 .body_ids
1935                 .iter()
1936                 .map(move |&body_id| self.hir.body_owner_def_id(body_id))
1937     }
1938
1939     pub fn expr_span(self, id: NodeId) -> Span {
1940         match self.hir.find(id) {
1941             Some(hir_map::NodeExpr(e)) => {
1942                 e.span
1943             }
1944             Some(f) => {
1945                 bug!("Node id {} is not an expr: {:?}", id, f);
1946             }
1947             None => {
1948                 bug!("Node id {} is not present in the node map", id);
1949             }
1950         }
1951     }
1952
1953     pub fn local_var_name_str(self, id: NodeId) -> InternedString {
1954         match self.hir.find(id) {
1955             Some(hir_map::NodeLocal(pat)) => {
1956                 match pat.node {
1957                     hir::PatKind::Binding(_, _, ref path1, _) => path1.node.as_str(),
1958                     _ => {
1959                         bug!("Variable id {} maps to {:?}, not local", id, pat);
1960                     },
1961                 }
1962             },
1963             r => bug!("Variable id {} maps to {:?}, not local", id, r),
1964         }
1965     }
1966
1967     pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
1968          match expr.node {
1969             hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
1970                 match path.def {
1971                     Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
1972                     _ => false,
1973                 }
1974             }
1975
1976             hir::ExprType(ref e, _) => {
1977                 self.expr_is_lval(e)
1978             }
1979
1980             hir::ExprUnary(hir::UnDeref, _) |
1981             hir::ExprField(..) |
1982             hir::ExprTupField(..) |
1983             hir::ExprIndex(..) => {
1984                 true
1985             }
1986
1987             // Partially qualified paths in expressions can only legally
1988             // refer to associated items which are always rvalues.
1989             hir::ExprPath(hir::QPath::TypeRelative(..)) |
1990
1991             hir::ExprCall(..) |
1992             hir::ExprMethodCall(..) |
1993             hir::ExprStruct(..) |
1994             hir::ExprTup(..) |
1995             hir::ExprIf(..) |
1996             hir::ExprMatch(..) |
1997             hir::ExprClosure(..) |
1998             hir::ExprBlock(..) |
1999             hir::ExprRepeat(..) |
2000             hir::ExprArray(..) |
2001             hir::ExprBreak(..) |
2002             hir::ExprAgain(..) |
2003             hir::ExprRet(..) |
2004             hir::ExprWhile(..) |
2005             hir::ExprLoop(..) |
2006             hir::ExprAssign(..) |
2007             hir::ExprInlineAsm(..) |
2008             hir::ExprAssignOp(..) |
2009             hir::ExprLit(_) |
2010             hir::ExprUnary(..) |
2011             hir::ExprBox(..) |
2012             hir::ExprAddrOf(..) |
2013             hir::ExprBinary(..) |
2014             hir::ExprCast(..) => {
2015                 false
2016             }
2017         }
2018     }
2019
2020     pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
2021         self.associated_items(id)
2022             .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
2023             .collect()
2024     }
2025
2026     pub fn trait_relevant_for_never(self, did: DefId) -> bool {
2027         self.associated_items(did).any(|item| {
2028             item.relevant_for_never()
2029         })
2030     }
2031
2032     pub fn opt_associated_item(self, def_id: DefId) -> Option<AssociatedItem> {
2033         let is_associated_item = if let Some(node_id) = self.hir.as_local_node_id(def_id) {
2034             match self.hir.get(node_id) {
2035                 hir_map::NodeTraitItem(_) | hir_map::NodeImplItem(_) => true,
2036                 _ => false,
2037             }
2038         } else {
2039             match self.describe_def(def_id).expect("no def for def-id") {
2040                 Def::AssociatedConst(_) | Def::Method(_) | Def::AssociatedTy(_) => true,
2041                 _ => false,
2042             }
2043         };
2044
2045         if is_associated_item {
2046             Some(self.associated_item(def_id))
2047         } else {
2048             None
2049         }
2050     }
2051
2052     fn associated_item_from_trait_item_ref(self,
2053                                            parent_def_id: DefId,
2054                                            parent_vis: &hir::Visibility,
2055                                            trait_item_ref: &hir::TraitItemRef)
2056                                            -> AssociatedItem {
2057         let def_id = self.hir.local_def_id(trait_item_ref.id.node_id);
2058         let (kind, has_self) = match trait_item_ref.kind {
2059             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2060             hir::AssociatedItemKind::Method { has_self } => {
2061                 (ty::AssociatedKind::Method, has_self)
2062             }
2063             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2064         };
2065
2066         AssociatedItem {
2067             name: trait_item_ref.name,
2068             kind: kind,
2069             // Visibility of trait items is inherited from their traits.
2070             vis: Visibility::from_hir(parent_vis, trait_item_ref.id.node_id, self),
2071             defaultness: trait_item_ref.defaultness,
2072             def_id: def_id,
2073             container: TraitContainer(parent_def_id),
2074             method_has_self_argument: has_self
2075         }
2076     }
2077
2078     fn associated_item_from_impl_item_ref(self,
2079                                           parent_def_id: DefId,
2080                                           impl_item_ref: &hir::ImplItemRef)
2081                                           -> AssociatedItem {
2082         let def_id = self.hir.local_def_id(impl_item_ref.id.node_id);
2083         let (kind, has_self) = match impl_item_ref.kind {
2084             hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
2085             hir::AssociatedItemKind::Method { has_self } => {
2086                 (ty::AssociatedKind::Method, has_self)
2087             }
2088             hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
2089         };
2090
2091         ty::AssociatedItem {
2092             name: impl_item_ref.name,
2093             kind: kind,
2094             // Visibility of trait impl items doesn't matter.
2095             vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.node_id, self),
2096             defaultness: impl_item_ref.defaultness,
2097             def_id: def_id,
2098             container: ImplContainer(parent_def_id),
2099             method_has_self_argument: has_self
2100         }
2101     }
2102
2103     #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
2104     pub fn associated_items(self, def_id: DefId)
2105                             -> impl Iterator<Item = ty::AssociatedItem> + 'a {
2106         let def_ids = self.associated_item_def_ids(def_id);
2107         (0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
2108     }
2109
2110     /// Returns true if the impls are the same polarity and are implementing
2111     /// a trait which contains no items
2112     pub fn impls_are_allowed_to_overlap(self, def_id1: DefId, def_id2: DefId) -> bool {
2113         if !self.sess.features.borrow().overlapping_marker_traits {
2114             return false;
2115         }
2116         let trait1_is_empty = self.impl_trait_ref(def_id1)
2117             .map_or(false, |trait_ref| {
2118                 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2119             });
2120         let trait2_is_empty = self.impl_trait_ref(def_id2)
2121             .map_or(false, |trait_ref| {
2122                 self.associated_item_def_ids(trait_ref.def_id).is_empty()
2123             });
2124         self.impl_polarity(def_id1) == self.impl_polarity(def_id2)
2125             && trait1_is_empty
2126             && trait2_is_empty
2127     }
2128
2129     // Returns `ty::VariantDef` if `def` refers to a struct,
2130     // or variant or their constructors, panics otherwise.
2131     pub fn expect_variant_def(self, def: Def) -> &'tcx VariantDef {
2132         match def {
2133             Def::Variant(did) | Def::VariantCtor(did, ..) => {
2134                 let enum_did = self.parent_def_id(did).unwrap();
2135                 self.adt_def(enum_did).variant_with_id(did)
2136             }
2137             Def::Struct(did) | Def::Union(did) => {
2138                 self.adt_def(did).struct_variant()
2139             }
2140             Def::StructCtor(ctor_did, ..) => {
2141                 let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
2142                 self.adt_def(did).struct_variant()
2143             }
2144             _ => bug!("expect_variant_def used with unexpected def {:?}", def)
2145         }
2146     }
2147
2148     pub fn def_key(self, id: DefId) -> hir_map::DefKey {
2149         if id.is_local() {
2150             self.hir.def_key(id)
2151         } else {
2152             self.sess.cstore.def_key(id)
2153         }
2154     }
2155
2156     /// Convert a `DefId` into its fully expanded `DefPath` (every
2157     /// `DefId` is really just an interned def-path).
2158     ///
2159     /// Note that if `id` is not local to this crate, the result will
2160     ///  be a non-local `DefPath`.
2161     pub fn def_path(self, id: DefId) -> hir_map::DefPath {
2162         if id.is_local() {
2163             self.hir.def_path(id)
2164         } else {
2165             self.sess.cstore.def_path(id)
2166         }
2167     }
2168
2169     #[inline]
2170     pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
2171         if def_id.is_local() {
2172             self.hir.definitions().def_path_hash(def_id.index)
2173         } else {
2174             self.sess.cstore.def_path_hash(def_id)
2175         }
2176     }
2177
2178     pub fn item_name(self, id: DefId) -> ast::Name {
2179         if let Some(id) = self.hir.as_local_node_id(id) {
2180             self.hir.name(id)
2181         } else if id.index == CRATE_DEF_INDEX {
2182             self.sess.cstore.original_crate_name(id.krate)
2183         } else {
2184             let def_key = self.sess.cstore.def_key(id);
2185             // The name of a StructCtor is that of its struct parent.
2186             if let hir_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
2187                 self.item_name(DefId {
2188                     krate: id.krate,
2189                     index: def_key.parent.unwrap()
2190                 })
2191             } else {
2192                 def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
2193                     bug!("item_name: no name for {:?}", self.def_path(id));
2194                 })
2195             }
2196         }
2197     }
2198
2199     /// Return the possibly-auto-generated MIR of a (DefId, Subst) pair.
2200     pub fn instance_mir(self, instance: ty::InstanceDef<'gcx>)
2201                         -> &'gcx Mir<'gcx>
2202     {
2203         match instance {
2204             ty::InstanceDef::Item(did) => {
2205                 self.optimized_mir(did)
2206             }
2207             ty::InstanceDef::Intrinsic(..) |
2208             ty::InstanceDef::FnPtrShim(..) |
2209             ty::InstanceDef::Virtual(..) |
2210             ty::InstanceDef::ClosureOnceShim { .. } |
2211             ty::InstanceDef::DropGlue(..) => {
2212                 self.mir_shims(instance)
2213             }
2214         }
2215     }
2216
2217     /// Given the DefId of an item, returns its MIR, borrowed immutably.
2218     /// Returns None if there is no MIR for the DefId
2219     pub fn maybe_optimized_mir(self, did: DefId) -> Option<&'gcx Mir<'gcx>> {
2220         if self.is_mir_available(did) {
2221             Some(self.optimized_mir(did))
2222         } else {
2223             None
2224         }
2225     }
2226
2227     /// Get the attributes of a definition.
2228     pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
2229         if let Some(id) = self.hir.as_local_node_id(did) {
2230             Attributes::Borrowed(self.hir.attrs(id))
2231         } else {
2232             Attributes::Owned(self.item_attrs(did))
2233         }
2234     }
2235
2236     /// Determine whether an item is annotated with an attribute
2237     pub fn has_attr(self, did: DefId, attr: &str) -> bool {
2238         self.get_attrs(did).iter().any(|item| item.check_name(attr))
2239     }
2240
2241     pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
2242         self.trait_def(trait_def_id).has_default_impl
2243     }
2244
2245     /// Given the def_id of an impl, return the def_id of the trait it implements.
2246     /// If it implements no trait, return `None`.
2247     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2248         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2249     }
2250
2251     /// If the given def ID describes a method belonging to an impl, return the
2252     /// ID of the impl that the method belongs to. Otherwise, return `None`.
2253     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2254         let item = if def_id.krate != LOCAL_CRATE {
2255             if let Some(Def::Method(_)) = self.describe_def(def_id) {
2256                 Some(self.associated_item(def_id))
2257             } else {
2258                 None
2259             }
2260         } else {
2261             self.opt_associated_item(def_id)
2262         };
2263
2264         match item {
2265             Some(trait_item) => {
2266                 match trait_item.container {
2267                     TraitContainer(_) => None,
2268                     ImplContainer(def_id) => Some(def_id),
2269                 }
2270             }
2271             None => None
2272         }
2273     }
2274
2275     pub fn node_scope_region(self, id: NodeId) -> Region<'tcx> {
2276         self.mk_region(ty::ReScope(CodeExtent::Misc(id)))
2277     }
2278
2279     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2280     /// with the name of the crate containing the impl.
2281     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2282         if impl_did.is_local() {
2283             let node_id = self.hir.as_local_node_id(impl_did).unwrap();
2284             Ok(self.hir.span(node_id))
2285         } else {
2286             Err(self.sess.cstore.crate_name(impl_did.krate))
2287         }
2288     }
2289
2290     pub fn adjust(self, name: Name, scope: DefId, block: NodeId) -> (Ident, DefId) {
2291         self.adjust_ident(name.to_ident(), scope, block)
2292     }
2293
2294     pub fn adjust_ident(self, mut ident: Ident, scope: DefId, block: NodeId) -> (Ident, DefId) {
2295         let expansion = match scope.krate {
2296             LOCAL_CRATE => self.hir.definitions().expansion(scope.index),
2297             _ => Mark::root(),
2298         };
2299         let scope = match ident.ctxt.adjust(expansion) {
2300             Some(macro_def) => self.hir.definitions().macro_def_scope(macro_def),
2301             None => self.hir.get_module_parent(block),
2302         };
2303         (ident, scope)
2304     }
2305 }
2306
2307 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
2308     pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
2309         F: FnOnce(&[hir::Freevar]) -> T,
2310     {
2311         match self.freevars.borrow().get(&fid) {
2312             None => f(&[]),
2313             Some(d) => f(&d[..])
2314         }
2315     }
2316 }
2317
2318 fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
2319     -> AssociatedItem
2320 {
2321     let id = tcx.hir.as_local_node_id(def_id).unwrap();
2322     let parent_id = tcx.hir.get_parent(id);
2323     let parent_def_id = tcx.hir.local_def_id(parent_id);
2324     let parent_item = tcx.hir.expect_item(parent_id);
2325     match parent_item.node {
2326         hir::ItemImpl(.., ref impl_item_refs) => {
2327             if let Some(impl_item_ref) = impl_item_refs.iter().find(|i| i.id.node_id == id) {
2328                 let assoc_item = tcx.associated_item_from_impl_item_ref(parent_def_id,
2329                                                                         impl_item_ref);
2330                 debug_assert_eq!(assoc_item.def_id, def_id);
2331                 return assoc_item;
2332             }
2333         }
2334
2335         hir::ItemTrait(.., ref trait_item_refs) => {
2336             if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.node_id == id) {
2337                 let assoc_item = tcx.associated_item_from_trait_item_ref(parent_def_id,
2338                                                                          &parent_item.vis,
2339                                                                          trait_item_ref);
2340                 debug_assert_eq!(assoc_item.def_id, def_id);
2341                 return assoc_item;
2342             }
2343         }
2344
2345         _ => { }
2346     }
2347
2348     span_bug!(parent_item.span,
2349               "unexpected parent of trait or impl item or item not found: {:?}",
2350               parent_item.node)
2351 }
2352
2353 /// Calculates the Sized-constraint.
2354 ///
2355 /// In fact, there are only a few options for the types in the constraint:
2356 ///     - an obviously-unsized type
2357 ///     - a type parameter or projection whose Sizedness can't be known
2358 ///     - a tuple of type parameters or projections, if there are multiple
2359 ///       such.
2360 ///     - a TyError, if a type contained itself. The representability
2361 ///       check should catch this case.
2362 fn adt_sized_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2363                                   def_id: DefId)
2364                                   -> &'tcx [Ty<'tcx>] {
2365     let def = tcx.adt_def(def_id);
2366
2367     let result = tcx.intern_type_list(&def.variants.iter().flat_map(|v| {
2368         v.fields.last()
2369     }).flat_map(|f| {
2370         def.sized_constraint_for_ty(tcx, tcx.type_of(f.did))
2371     }).collect::<Vec<_>>());
2372
2373     debug!("adt_sized_constraint: {:?} => {:?}", def, result);
2374
2375     result
2376 }
2377
2378 /// Calculates the dtorck constraint for a type.
2379 fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2380                                    def_id: DefId)
2381                                    -> DtorckConstraint<'tcx> {
2382     let def = tcx.adt_def(def_id);
2383     let span = tcx.def_span(def_id);
2384     debug!("dtorck_constraint: {:?}", def);
2385
2386     if def.is_phantom_data() {
2387         let result = DtorckConstraint {
2388             outlives: vec![],
2389             dtorck_types: vec![
2390                 tcx.mk_param_from_def(&tcx.generics_of(def_id).types[0])
2391            ]
2392         };
2393         debug!("dtorck_constraint: {:?} => {:?}", def, result);
2394         return result;
2395     }
2396
2397     let mut result = def.all_fields()
2398         .map(|field| tcx.type_of(field.did))
2399         .map(|fty| tcx.dtorck_constraint_for_ty(span, fty, 0, fty))
2400         .collect::<Result<DtorckConstraint, ErrorReported>>()
2401         .unwrap_or(DtorckConstraint::empty());
2402     result.outlives.extend(tcx.destructor_constraints(def));
2403     result.dedup();
2404
2405     debug!("dtorck_constraint: {:?} => {:?}", def, result);
2406
2407     result
2408 }
2409
2410 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2411                                      def_id: DefId)
2412                                      -> Rc<Vec<DefId>> {
2413     let id = tcx.hir.as_local_node_id(def_id).unwrap();
2414     let item = tcx.hir.expect_item(id);
2415     let vec: Vec<_> = match item.node {
2416         hir::ItemTrait(.., ref trait_item_refs) => {
2417             trait_item_refs.iter()
2418                            .map(|trait_item_ref| trait_item_ref.id)
2419                            .map(|id| tcx.hir.local_def_id(id.node_id))
2420                            .collect()
2421         }
2422         hir::ItemImpl(.., ref impl_item_refs) => {
2423             impl_item_refs.iter()
2424                           .map(|impl_item_ref| impl_item_ref.id)
2425                           .map(|id| tcx.hir.local_def_id(id.node_id))
2426                           .collect()
2427         }
2428         _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
2429     };
2430     Rc::new(vec)
2431 }
2432
2433 fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span {
2434     tcx.hir.span_if_local(def_id).unwrap()
2435 }
2436
2437 /// If the given def ID describes an item belonging to a trait,
2438 /// return the ID of the trait that the trait item belongs to.
2439 /// Otherwise, return `None`.
2440 fn trait_of_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
2441     tcx.opt_associated_item(def_id)
2442         .and_then(|associated_item| {
2443             match associated_item.container {
2444                 TraitContainer(def_id) => Some(def_id),
2445                 ImplContainer(_) => None
2446             }
2447         })
2448 }
2449
2450 /// See `ParamEnv` struct def'n for details.
2451 fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2452                        def_id: DefId)
2453                        -> ParamEnv<'tcx> {
2454     // Compute the bounds on Self and the type parameters.
2455
2456     let bounds = tcx.predicates_of(def_id).instantiate_identity(tcx);
2457     let predicates = bounds.predicates;
2458
2459     // Finally, we have to normalize the bounds in the environment, in
2460     // case they contain any associated type projections. This process
2461     // can yield errors if the put in illegal associated types, like
2462     // `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
2463     // report these errors right here; this doesn't actually feel
2464     // right to me, because constructing the environment feels like a
2465     // kind of a "idempotent" action, but I'm not sure where would be
2466     // a better place. In practice, we construct environments for
2467     // every fn once during type checking, and we'll abort if there
2468     // are any errors at that point, so after type checking you can be
2469     // sure that this will succeed without errors anyway.
2470
2471     let unnormalized_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
2472                                              traits::Reveal::UserFacing);
2473
2474     let body_id = tcx.hir.as_local_node_id(def_id).map_or(DUMMY_NODE_ID, |id| {
2475         tcx.hir.maybe_body_owned_by(id).map_or(id, |body| body.node_id)
2476     });
2477     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
2478     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
2479 }
2480
2481 pub fn provide(providers: &mut ty::maps::Providers) {
2482     util::provide(providers);
2483     *providers = ty::maps::Providers {
2484         associated_item,
2485         associated_item_def_ids,
2486         adt_sized_constraint,
2487         adt_dtorck_constraint,
2488         def_span,
2489         param_env,
2490         trait_of_item,
2491         trait_impls_of: trait_def::trait_impls_of_provider,
2492         relevant_trait_impls_for: trait_def::relevant_trait_impls_provider,
2493         ..*providers
2494     };
2495 }
2496
2497 pub fn provide_extern(providers: &mut ty::maps::Providers) {
2498     *providers = ty::maps::Providers {
2499         adt_sized_constraint,
2500         adt_dtorck_constraint,
2501         trait_impls_of: trait_def::trait_impls_of_provider,
2502         relevant_trait_impls_for: trait_def::relevant_trait_impls_provider,
2503         param_env,
2504         ..*providers
2505     };
2506 }
2507
2508
2509 /// A map for the local crate mapping each type to a vector of its
2510 /// inherent impls. This is not meant to be used outside of coherence;
2511 /// rather, you should request the vector for a specific type via
2512 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2513 /// (constructing this map requires touching the entire crate).
2514 #[derive(Clone, Debug)]
2515 pub struct CrateInherentImpls {
2516     pub inherent_impls: DefIdMap<Rc<Vec<DefId>>>,
2517 }
2518
2519 /// A set of constraints that need to be satisfied in order for
2520 /// a type to be valid for destruction.
2521 #[derive(Clone, Debug)]
2522 pub struct DtorckConstraint<'tcx> {
2523     /// Types that are required to be alive in order for this
2524     /// type to be valid for destruction.
2525     pub outlives: Vec<ty::subst::Kind<'tcx>>,
2526     /// Types that could not be resolved: projections and params.
2527     pub dtorck_types: Vec<Ty<'tcx>>,
2528 }
2529
2530 impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx>
2531 {
2532     fn from_iter<I: IntoIterator<Item=DtorckConstraint<'tcx>>>(iter: I) -> Self {
2533         let mut result = Self::empty();
2534
2535         for constraint in iter {
2536             result.outlives.extend(constraint.outlives);
2537             result.dtorck_types.extend(constraint.dtorck_types);
2538         }
2539
2540         result
2541     }
2542 }
2543
2544
2545 impl<'tcx> DtorckConstraint<'tcx> {
2546     fn empty() -> DtorckConstraint<'tcx> {
2547         DtorckConstraint {
2548             outlives: vec![],
2549             dtorck_types: vec![]
2550         }
2551     }
2552
2553     fn dedup<'a>(&mut self) {
2554         let mut outlives = FxHashSet();
2555         let mut dtorck_types = FxHashSet();
2556
2557         self.outlives.retain(|&val| outlives.replace(val).is_none());
2558         self.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
2559     }
2560 }
2561
2562 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
2563 pub struct SymbolName {
2564     // FIXME: we don't rely on interning or equality here - better have
2565     // this be a `&'tcx str`.
2566     pub name: InternedString
2567 }
2568
2569 impl Deref for SymbolName {
2570     type Target = str;
2571
2572     fn deref(&self) -> &str { &self.name }
2573 }
2574
2575 impl fmt::Display for SymbolName {
2576     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2577         fmt::Display::fmt(&self.name, fmt)
2578     }
2579 }