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