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