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