]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/ty/mod.rs
somewhat related cleanup
[rust.git] / src / librustc_middle / ty / mod.rs
1 // ignore-tidy-filelength
2 pub use self::fold::{TypeFoldable, TypeVisitor};
3 pub use self::AssocItemContainer::*;
4 pub use self::BorrowKind::*;
5 pub use self::IntVarValue::*;
6 pub use self::Variance::*;
7
8 use crate::hir::exports::ExportMap;
9 use crate::ich::StableHashingContext;
10 use crate::infer::canonical::Canonical;
11 use crate::middle::cstore::CrateStoreDyn;
12 use crate::middle::resolve_lifetime::ObjectLifetimeDefault;
13 use crate::mir::interpret::ErrorHandled;
14 use crate::mir::Body;
15 use crate::mir::GeneratorLayout;
16 use crate::traits::{self, Reveal};
17 use crate::ty;
18 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
19 use crate::ty::util::{Discr, IntTypeExt};
20 use rustc_ast::ast;
21 use rustc_attr as attr;
22 use rustc_data_structures::captures::Captures;
23 use rustc_data_structures::fingerprint::Fingerprint;
24 use rustc_data_structures::fx::FxHashMap;
25 use rustc_data_structures::fx::FxHashSet;
26 use rustc_data_structures::fx::FxIndexMap;
27 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::sync::{self, par_iter, ParallelIterator};
30 use rustc_errors::ErrorReported;
31 use rustc_hir as hir;
32 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
33 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
34 use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem};
35 use rustc_hir::{Constness, Node};
36 use rustc_index::vec::{Idx, IndexVec};
37 use rustc_macros::HashStable;
38 use rustc_serialize::{self, Encodable, Encoder};
39 use rustc_session::DataTypeKind;
40 use rustc_span::hygiene::ExpnId;
41 use rustc_span::symbol::{kw, sym, Ident, Symbol};
42 use rustc_span::Span;
43 use rustc_target::abi::{Align, VariantIdx};
44
45 use std::cell::RefCell;
46 use std::cmp::Ordering;
47 use std::fmt;
48 use std::hash::{Hash, Hasher};
49 use std::marker::PhantomData;
50 use std::ops::Range;
51 use std::ptr;
52 use std::str;
53
54 pub use self::sty::BoundRegion::*;
55 pub use self::sty::InferTy::*;
56 pub use self::sty::RegionKind;
57 pub use self::sty::RegionKind::*;
58 pub use self::sty::TyKind::*;
59 pub use self::sty::{Binder, BoundTy, BoundTyKind, BoundVar, DebruijnIndex, INNERMOST};
60 pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
61 pub use self::sty::{CanonicalPolyFnSig, FnSig, GenSig, PolyFnSig, PolyGenSig};
62 pub use self::sty::{ClosureSubsts, GeneratorSubsts, TypeAndMut, UpvarSubsts};
63 pub use self::sty::{ConstVid, FloatVid, IntVid, RegionVid, TyVid};
64 pub use self::sty::{ExistentialPredicate, InferTy, ParamConst, ParamTy, ProjectionTy};
65 pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
66 pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
67 pub use self::sty::{PolyTraitRef, TraitRef, TyKind};
68 pub use crate::ty::diagnostics::*;
69
70 pub use self::binding::BindingMode;
71 pub use self::binding::BindingMode::*;
72
73 pub use self::context::{tls, FreeRegionInfo, TyCtxt};
74 pub use self::context::{
75     CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,
76     UserType, UserTypeAnnotationIndex,
77 };
78 pub use self::context::{
79     CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckResults,
80 };
81
82 pub use self::instance::{Instance, InstanceDef};
83
84 pub use self::list::List;
85
86 pub use self::trait_def::TraitDef;
87
88 pub use self::query::queries;
89
90 pub use self::consts::{Const, ConstInt, ConstKind, InferConst};
91
92 pub mod adjustment;
93 pub mod binding;
94 pub mod cast;
95 #[macro_use]
96 pub mod codec;
97 pub mod _match;
98 mod erase_regions;
99 pub mod error;
100 pub mod fast_reject;
101 pub mod flags;
102 pub mod fold;
103 pub mod inhabitedness;
104 pub mod layout;
105 pub mod normalize_erasing_regions;
106 pub mod outlives;
107 pub mod print;
108 pub mod query;
109 pub mod relate;
110 pub mod steal;
111 pub mod subst;
112 pub mod trait_def;
113 pub mod util;
114 pub mod walk;
115
116 mod consts;
117 mod context;
118 mod diagnostics;
119 mod instance;
120 mod list;
121 mod structural_impls;
122 mod sty;
123
124 // Data types
125
126 pub struct ResolverOutputs {
127     pub definitions: rustc_hir::definitions::Definitions,
128     pub cstore: Box<CrateStoreDyn>,
129     pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
130     pub maybe_unused_trait_imports: FxHashSet<LocalDefId>,
131     pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
132     pub export_map: ExportMap<LocalDefId>,
133     pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
134     /// Extern prelude entries. The value is `true` if the entry was introduced
135     /// via `extern crate` item and not `--extern` option or compiler built-in.
136     pub extern_prelude: FxHashMap<Symbol, bool>,
137 }
138
139 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash)]
140 pub enum AssocItemContainer {
141     TraitContainer(DefId),
142     ImplContainer(DefId),
143 }
144
145 impl AssocItemContainer {
146     /// Asserts that this is the `DefId` of an associated item declared
147     /// in a trait, and returns the trait `DefId`.
148     pub fn assert_trait(&self) -> DefId {
149         match *self {
150             TraitContainer(id) => id,
151             _ => bug!("associated item has wrong container type: {:?}", self),
152         }
153     }
154
155     pub fn id(&self) -> DefId {
156         match *self {
157             TraitContainer(id) => id,
158             ImplContainer(id) => id,
159         }
160     }
161 }
162
163 /// The "header" of an impl is everything outside the body: a Self type, a trait
164 /// ref (in the case of a trait impl), and a set of predicates (from the
165 /// bounds / where-clauses).
166 #[derive(Clone, Debug, TypeFoldable)]
167 pub struct ImplHeader<'tcx> {
168     pub impl_def_id: DefId,
169     pub self_ty: Ty<'tcx>,
170     pub trait_ref: Option<TraitRef<'tcx>>,
171     pub predicates: Vec<Predicate<'tcx>>,
172 }
173
174 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
175 pub enum ImplPolarity {
176     /// `impl Trait for Type`
177     Positive,
178     /// `impl !Trait for Type`
179     Negative,
180     /// `#[rustc_reservation_impl] impl Trait for Type`
181     ///
182     /// This is a "stability hack", not a real Rust feature.
183     /// See #64631 for details.
184     Reservation,
185 }
186
187 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash)]
188 pub struct AssocItem {
189     pub def_id: DefId,
190     #[stable_hasher(project(name))]
191     pub ident: Ident,
192     pub kind: AssocKind,
193     pub vis: Visibility,
194     pub defaultness: hir::Defaultness,
195     pub container: AssocItemContainer,
196
197     /// Whether this is a method with an explicit self
198     /// as its first parameter, allowing method calls.
199     pub fn_has_self_parameter: bool,
200 }
201
202 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash)]
203 pub enum AssocKind {
204     Const,
205     Fn,
206     Type,
207 }
208
209 impl AssocKind {
210     pub fn namespace(&self) -> Namespace {
211         match *self {
212             ty::AssocKind::Type => Namespace::TypeNS,
213             ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
214         }
215     }
216
217     pub fn as_def_kind(&self) -> DefKind {
218         match self {
219             AssocKind::Const => DefKind::AssocConst,
220             AssocKind::Fn => DefKind::AssocFn,
221             AssocKind::Type => DefKind::AssocTy,
222         }
223     }
224 }
225
226 impl AssocItem {
227     pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
228         match self.kind {
229             ty::AssocKind::Fn => {
230                 // We skip the binder here because the binder would deanonymize all
231                 // late-bound regions, and we don't want method signatures to show up
232                 // `as for<'r> fn(&'r MyType)`.  Pretty-printing handles late-bound
233                 // regions just fine, showing `fn(&MyType)`.
234                 tcx.fn_sig(self.def_id).skip_binder().to_string()
235             }
236             ty::AssocKind::Type => format!("type {};", self.ident),
237             ty::AssocKind::Const => {
238                 format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id))
239             }
240         }
241     }
242 }
243
244 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
245 ///
246 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
247 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
248 /// done only on items with the same name.
249 #[derive(Debug, Clone, PartialEq, HashStable)]
250 pub struct AssociatedItems<'tcx> {
251     items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
252 }
253
254 impl<'tcx> AssociatedItems<'tcx> {
255     /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
256     pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
257         let items = items_in_def_order.into_iter().map(|item| (item.ident.name, item)).collect();
258         AssociatedItems { items }
259     }
260
261     /// Returns a slice of associated items in the order they were defined.
262     ///
263     /// New code should avoid relying on definition order. If you need a particular associated item
264     /// for a known trait, make that trait a lang item instead of indexing this array.
265     pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
266         self.items.iter().map(|(_, v)| *v)
267     }
268
269     /// Returns an iterator over all associated items with the given name, ignoring hygiene.
270     pub fn filter_by_name_unhygienic(
271         &self,
272         name: Symbol,
273     ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
274         self.items.get_by_key(&name).copied()
275     }
276
277     /// Returns an iterator over all associated items with the given name.
278     ///
279     /// Multiple items may have the same name if they are in different `Namespace`s. For example,
280     /// an associated type can have the same name as a method. Use one of the `find_by_name_and_*`
281     /// methods below if you know which item you are looking for.
282     pub fn filter_by_name(
283         &'a self,
284         tcx: TyCtxt<'a>,
285         ident: Ident,
286         parent_def_id: DefId,
287     ) -> impl 'a + Iterator<Item = &'a ty::AssocItem> {
288         self.filter_by_name_unhygienic(ident.name)
289             .filter(move |item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
290     }
291
292     /// Returns the associated item with the given name and `AssocKind`, if one exists.
293     pub fn find_by_name_and_kind(
294         &self,
295         tcx: TyCtxt<'_>,
296         ident: Ident,
297         kind: AssocKind,
298         parent_def_id: DefId,
299     ) -> Option<&ty::AssocItem> {
300         self.filter_by_name_unhygienic(ident.name)
301             .filter(|item| item.kind == kind)
302             .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
303     }
304
305     /// Returns the associated item with the given name in the given `Namespace`, if one exists.
306     pub fn find_by_name_and_namespace(
307         &self,
308         tcx: TyCtxt<'_>,
309         ident: Ident,
310         ns: Namespace,
311         parent_def_id: DefId,
312     ) -> Option<&ty::AssocItem> {
313         self.filter_by_name_unhygienic(ident.name)
314             .filter(|item| item.kind.namespace() == ns)
315             .find(|item| tcx.hygienic_eq(ident, item.ident, parent_def_id))
316     }
317 }
318
319 #[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable, HashStable, Hash)]
320 pub enum Visibility {
321     /// Visible everywhere (including in other crates).
322     Public,
323     /// Visible only in the given crate-local module.
324     Restricted(DefId),
325     /// Not visible anywhere in the local crate. This is the visibility of private external items.
326     Invisible,
327 }
328
329 pub trait DefIdTree: Copy {
330     fn parent(self, id: DefId) -> Option<DefId>;
331
332     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
333         if descendant.krate != ancestor.krate {
334             return false;
335         }
336
337         while descendant != ancestor {
338             match self.parent(descendant) {
339                 Some(parent) => descendant = parent,
340                 None => return false,
341             }
342         }
343         true
344     }
345 }
346
347 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
348     fn parent(self, id: DefId) -> Option<DefId> {
349         self.def_key(id).parent.map(|index| DefId { index, ..id })
350     }
351 }
352
353 impl Visibility {
354     pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self {
355         match visibility.node {
356             hir::VisibilityKind::Public => Visibility::Public,
357             hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)),
358             hir::VisibilityKind::Restricted { ref path, .. } => match path.res {
359                 // If there is no resolution, `resolve` will have already reported an error, so
360                 // assume that the visibility is public to avoid reporting more privacy errors.
361                 Res::Err => Visibility::Public,
362                 def => Visibility::Restricted(def.def_id()),
363             },
364             hir::VisibilityKind::Inherited => {
365                 Visibility::Restricted(tcx.parent_module(id).to_def_id())
366             }
367         }
368     }
369
370     /// Returns `true` if an item with this visibility is accessible from the given block.
371     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
372         let restriction = match self {
373             // Public items are visible everywhere.
374             Visibility::Public => return true,
375             // Private items from other crates are visible nowhere.
376             Visibility::Invisible => return false,
377             // Restricted items are visible in an arbitrary local module.
378             Visibility::Restricted(other) if other.krate != module.krate => return false,
379             Visibility::Restricted(module) => module,
380         };
381
382         tree.is_descendant_of(module, restriction)
383     }
384
385     /// Returns `true` if this visibility is at least as accessible as the given visibility
386     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
387         let vis_restriction = match vis {
388             Visibility::Public => return self == Visibility::Public,
389             Visibility::Invisible => return true,
390             Visibility::Restricted(module) => module,
391         };
392
393         self.is_accessible_from(vis_restriction, tree)
394     }
395
396     // Returns `true` if this item is visible anywhere in the local crate.
397     pub fn is_visible_locally(self) -> bool {
398         match self {
399             Visibility::Public => true,
400             Visibility::Restricted(def_id) => def_id.is_local(),
401             Visibility::Invisible => false,
402         }
403     }
404 }
405
406 #[derive(Copy, Clone, PartialEq, RustcDecodable, RustcEncodable, HashStable)]
407 pub enum Variance {
408     Covariant,     // T<A> <: T<B> iff A <: B -- e.g., function return type
409     Invariant,     // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
410     Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
411     Bivariant,     // T<A> <: T<B>            -- e.g., unused type parameter
412 }
413
414 /// The crate variances map is computed during typeck and contains the
415 /// variance of every item in the local crate. You should not use it
416 /// directly, because to do so will make your pass dependent on the
417 /// HIR of every item in the local crate. Instead, use
418 /// `tcx.variances_of()` to get the variance for a *particular*
419 /// item.
420 #[derive(HashStable)]
421 pub struct CrateVariancesMap<'tcx> {
422     /// For each item with generics, maps to a vector of the variance
423     /// of its generics. If an item has no generics, it will have no
424     /// entry.
425     pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
426 }
427
428 impl Variance {
429     /// `a.xform(b)` combines the variance of a context with the
430     /// variance of a type with the following meaning. If we are in a
431     /// context with variance `a`, and we encounter a type argument in
432     /// a position with variance `b`, then `a.xform(b)` is the new
433     /// variance with which the argument appears.
434     ///
435     /// Example 1:
436     ///
437     ///     *mut Vec<i32>
438     ///
439     /// Here, the "ambient" variance starts as covariant. `*mut T` is
440     /// invariant with respect to `T`, so the variance in which the
441     /// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
442     /// yields `Invariant`. Now, the type `Vec<T>` is covariant with
443     /// respect to its type argument `T`, and hence the variance of
444     /// the `i32` here is `Invariant.xform(Covariant)`, which results
445     /// (again) in `Invariant`.
446     ///
447     /// Example 2:
448     ///
449     ///     fn(*const Vec<i32>, *mut Vec<i32)
450     ///
451     /// The ambient variance is covariant. A `fn` type is
452     /// contravariant with respect to its parameters, so the variance
453     /// within which both pointer types appear is
454     /// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
455     /// T` is covariant with respect to `T`, so the variance within
456     /// which the first `Vec<i32>` appears is
457     /// `Contravariant.xform(Covariant)` or `Contravariant`. The same
458     /// is true for its `i32` argument. In the `*mut T` case, the
459     /// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
460     /// and hence the outermost type is `Invariant` with respect to
461     /// `Vec<i32>` (and its `i32` argument).
462     ///
463     /// Source: Figure 1 of "Taming the Wildcards:
464     /// Combining Definition- and Use-Site Variance" published in PLDI'11.
465     pub fn xform(self, v: ty::Variance) -> ty::Variance {
466         match (self, v) {
467             // Figure 1, column 1.
468             (ty::Covariant, ty::Covariant) => ty::Covariant,
469             (ty::Covariant, ty::Contravariant) => ty::Contravariant,
470             (ty::Covariant, ty::Invariant) => ty::Invariant,
471             (ty::Covariant, ty::Bivariant) => ty::Bivariant,
472
473             // Figure 1, column 2.
474             (ty::Contravariant, ty::Covariant) => ty::Contravariant,
475             (ty::Contravariant, ty::Contravariant) => ty::Covariant,
476             (ty::Contravariant, ty::Invariant) => ty::Invariant,
477             (ty::Contravariant, ty::Bivariant) => ty::Bivariant,
478
479             // Figure 1, column 3.
480             (ty::Invariant, _) => ty::Invariant,
481
482             // Figure 1, column 4.
483             (ty::Bivariant, _) => ty::Bivariant,
484         }
485     }
486 }
487
488 // Contains information needed to resolve types and (in the future) look up
489 // the types of AST nodes.
490 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
491 pub struct CReaderCacheKey {
492     pub cnum: CrateNum,
493     pub pos: usize,
494 }
495
496 bitflags! {
497     /// Flags that we track on types. These flags are propagated upwards
498     /// through the type during type construction, so that we can quickly check
499     /// whether the type has various kinds of types in it without recursing
500     /// over the type itself.
501     pub struct TypeFlags: u32 {
502         // Does this have parameters? Used to determine whether substitution is
503         // required.
504         /// Does this have [Param]?
505         const HAS_TY_PARAM                = 1 << 0;
506         /// Does this have [ReEarlyBound]?
507         const HAS_RE_PARAM                = 1 << 1;
508         /// Does this have [ConstKind::Param]?
509         const HAS_CT_PARAM                = 1 << 2;
510
511         const NEEDS_SUBST                 = TypeFlags::HAS_TY_PARAM.bits
512                                           | TypeFlags::HAS_RE_PARAM.bits
513                                           | TypeFlags::HAS_CT_PARAM.bits;
514
515         /// Does this have [Infer]?
516         const HAS_TY_INFER                = 1 << 3;
517         /// Does this have [ReVar]?
518         const HAS_RE_INFER                = 1 << 4;
519         /// Does this have [ConstKind::Infer]?
520         const HAS_CT_INFER                = 1 << 5;
521
522         /// Does this have inference variables? Used to determine whether
523         /// inference is required.
524         const NEEDS_INFER                 = TypeFlags::HAS_TY_INFER.bits
525                                           | TypeFlags::HAS_RE_INFER.bits
526                                           | TypeFlags::HAS_CT_INFER.bits;
527
528         /// Does this have [Placeholder]?
529         const HAS_TY_PLACEHOLDER          = 1 << 6;
530         /// Does this have [RePlaceholder]?
531         const HAS_RE_PLACEHOLDER          = 1 << 7;
532         /// Does this have [ConstKind::Placeholder]?
533         const HAS_CT_PLACEHOLDER          = 1 << 8;
534
535         /// `true` if there are "names" of regions and so forth
536         /// that are local to a particular fn/inferctxt
537         const HAS_FREE_LOCAL_REGIONS      = 1 << 9;
538
539         /// `true` if there are "names" of types and regions and so forth
540         /// that are local to a particular fn
541         const HAS_FREE_LOCAL_NAMES        = TypeFlags::HAS_TY_PARAM.bits
542                                           | TypeFlags::HAS_CT_PARAM.bits
543                                           | TypeFlags::HAS_TY_INFER.bits
544                                           | TypeFlags::HAS_CT_INFER.bits
545                                           | TypeFlags::HAS_TY_PLACEHOLDER.bits
546                                           | TypeFlags::HAS_CT_PLACEHOLDER.bits
547                                           | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
548
549         /// Does this have [Projection]?
550         const HAS_TY_PROJECTION           = 1 << 10;
551         /// Does this have [Opaque]?
552         const HAS_TY_OPAQUE               = 1 << 11;
553         /// Does this have [ConstKind::Unevaluated]?
554         const HAS_CT_PROJECTION           = 1 << 12;
555
556         /// Could this type be normalized further?
557         const HAS_PROJECTION              = TypeFlags::HAS_TY_PROJECTION.bits
558                                           | TypeFlags::HAS_TY_OPAQUE.bits
559                                           | TypeFlags::HAS_CT_PROJECTION.bits;
560
561         /// Is an error type/const reachable?
562         const HAS_ERROR                   = 1 << 13;
563
564         /// Does this have any region that "appears free" in the type?
565         /// Basically anything but [ReLateBound] and [ReErased].
566         const HAS_FREE_REGIONS            = 1 << 14;
567
568         /// Does this have any [ReLateBound] regions? Used to check
569         /// if a global bound is safe to evaluate.
570         const HAS_RE_LATE_BOUND           = 1 << 15;
571
572         /// Does this have any [ReErased] regions?
573         const HAS_RE_ERASED               = 1 << 16;
574
575         /// Does this value have parameters/placeholders/inference variables which could be
576         /// replaced later, in a way that would change the results of `impl` specialization?
577         const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
578     }
579 }
580
581 #[allow(rustc::usage_of_ty_tykind)]
582 pub struct TyS<'tcx> {
583     pub kind: TyKind<'tcx>,
584     pub flags: TypeFlags,
585
586     /// This is a kind of confusing thing: it stores the smallest
587     /// binder such that
588     ///
589     /// (a) the binder itself captures nothing but
590     /// (b) all the late-bound things within the type are captured
591     ///     by some sub-binder.
592     ///
593     /// So, for a type without any late-bound things, like `u32`, this
594     /// will be *innermost*, because that is the innermost binder that
595     /// captures nothing. But for a type `&'D u32`, where `'D` is a
596     /// late-bound region with De Bruijn index `D`, this would be `D + 1`
597     /// -- the binder itself does not capture `D`, but `D` is captured
598     /// by an inner binder.
599     ///
600     /// We call this concept an "exclusive" binder `D` because all
601     /// De Bruijn indices within the type are contained within `0..D`
602     /// (exclusive).
603     outer_exclusive_binder: ty::DebruijnIndex,
604 }
605
606 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
607 #[cfg(target_arch = "x86_64")]
608 static_assert_size!(TyS<'_>, 32);
609
610 impl<'tcx> Ord for TyS<'tcx> {
611     fn cmp(&self, other: &TyS<'tcx>) -> Ordering {
612         self.kind.cmp(&other.kind)
613     }
614 }
615
616 impl<'tcx> PartialOrd for TyS<'tcx> {
617     fn partial_cmp(&self, other: &TyS<'tcx>) -> Option<Ordering> {
618         Some(self.kind.cmp(&other.kind))
619     }
620 }
621
622 impl<'tcx> PartialEq for TyS<'tcx> {
623     #[inline]
624     fn eq(&self, other: &TyS<'tcx>) -> bool {
625         ptr::eq(self, other)
626     }
627 }
628 impl<'tcx> Eq for TyS<'tcx> {}
629
630 impl<'tcx> Hash for TyS<'tcx> {
631     fn hash<H: Hasher>(&self, s: &mut H) {
632         (self as *const TyS<'_>).hash(s)
633     }
634 }
635
636 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
637     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
638         let ty::TyS {
639             ref kind,
640
641             // The other fields just provide fast access to information that is
642             // also contained in `kind`, so no need to hash them.
643             flags: _,
644
645             outer_exclusive_binder: _,
646         } = *self;
647
648         kind.hash_stable(hcx, hasher);
649     }
650 }
651
652 #[rustc_diagnostic_item = "Ty"]
653 pub type Ty<'tcx> = &'tcx TyS<'tcx>;
654
655 impl<'tcx> rustc_serialize::UseSpecializedEncodable for Ty<'tcx> {}
656 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Ty<'tcx> {}
657 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx List<Ty<'tcx>> {}
658
659 pub type CanonicalTy<'tcx> = Canonical<'tcx, Ty<'tcx>>;
660
661 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
662 pub struct UpvarPath {
663     pub hir_id: hir::HirId,
664 }
665
666 /// Upvars do not get their own `NodeId`. Instead, we use the pair of
667 /// the original var ID (that is, the root variable that is referenced
668 /// by the upvar) and the ID of the closure expression.
669 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
670 pub struct UpvarId {
671     pub var_path: UpvarPath,
672     pub closure_expr_id: LocalDefId,
673 }
674
675 #[derive(Clone, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, HashStable)]
676 pub enum BorrowKind {
677     /// Data must be immutable and is aliasable.
678     ImmBorrow,
679
680     /// Data must be immutable but not aliasable. This kind of borrow
681     /// cannot currently be expressed by the user and is used only in
682     /// implicit closure bindings. It is needed when the closure
683     /// is borrowing or mutating a mutable referent, e.g.:
684     ///
685     ///    let x: &mut isize = ...;
686     ///    let y = || *x += 5;
687     ///
688     /// If we were to try to translate this closure into a more explicit
689     /// form, we'd encounter an error with the code as written:
690     ///
691     ///    struct Env { x: & &mut isize }
692     ///    let x: &mut isize = ...;
693     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
694     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
695     ///
696     /// This is then illegal because you cannot mutate a `&mut` found
697     /// in an aliasable location. To solve, you'd have to translate with
698     /// an `&mut` borrow:
699     ///
700     ///    struct Env { x: & &mut isize }
701     ///    let x: &mut isize = ...;
702     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
703     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
704     ///
705     /// Now the assignment to `**env.x` is legal, but creating a
706     /// mutable pointer to `x` is not because `x` is not mutable. We
707     /// could fix this by declaring `x` as `let mut x`. This is ok in
708     /// user code, if awkward, but extra weird for closures, since the
709     /// borrow is hidden.
710     ///
711     /// So we introduce a "unique imm" borrow -- the referent is
712     /// immutable, but not aliasable. This solves the problem. For
713     /// simplicity, we don't give users the way to express this
714     /// borrow, it's just used when translating closures.
715     UniqueImmBorrow,
716
717     /// Data is mutable and not aliasable.
718     MutBorrow,
719 }
720
721 /// Information describing the capture of an upvar. This is computed
722 /// during `typeck`, specifically by `regionck`.
723 #[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable, HashStable)]
724 pub enum UpvarCapture<'tcx> {
725     /// Upvar is captured by value. This is always true when the
726     /// closure is labeled `move`, but can also be true in other cases
727     /// depending on inference.
728     ByValue,
729
730     /// Upvar is captured by reference.
731     ByRef(UpvarBorrow<'tcx>),
732 }
733
734 #[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable, HashStable)]
735 pub struct UpvarBorrow<'tcx> {
736     /// The kind of borrow: by-ref upvars have access to shared
737     /// immutable borrows, which are not part of the normal language
738     /// syntax.
739     pub kind: BorrowKind,
740
741     /// Region of the resulting reference.
742     pub region: ty::Region<'tcx>,
743 }
744
745 pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>;
746 pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
747
748 #[derive(Clone, Copy, PartialEq, Eq)]
749 pub enum IntVarValue {
750     IntType(ast::IntTy),
751     UintType(ast::UintTy),
752 }
753
754 #[derive(Clone, Copy, PartialEq, Eq)]
755 pub struct FloatVarValue(pub ast::FloatTy);
756
757 impl ty::EarlyBoundRegion {
758     pub fn to_bound_region(&self) -> ty::BoundRegion {
759         ty::BoundRegion::BrNamed(self.def_id, self.name)
760     }
761
762     /// Does this early bound region have a name? Early bound regions normally
763     /// always have names except when using anonymous lifetimes (`'_`).
764     pub fn has_name(&self) -> bool {
765         self.name != kw::UnderscoreLifetime
766     }
767 }
768
769 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
770 pub enum GenericParamDefKind {
771     Lifetime,
772     Type {
773         has_default: bool,
774         object_lifetime_default: ObjectLifetimeDefault,
775         synthetic: Option<hir::SyntheticTyParamKind>,
776     },
777     Const,
778 }
779
780 impl GenericParamDefKind {
781     pub fn descr(&self) -> &'static str {
782         match self {
783             GenericParamDefKind::Lifetime => "lifetime",
784             GenericParamDefKind::Type { .. } => "type",
785             GenericParamDefKind::Const => "constant",
786         }
787     }
788 }
789
790 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
791 pub struct GenericParamDef {
792     pub name: Symbol,
793     pub def_id: DefId,
794     pub index: u32,
795
796     /// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
797     /// on generic parameter `'a`/`T`, asserts data behind the parameter
798     /// `'a`/`T` won't be accessed during the parent type's `Drop` impl.
799     pub pure_wrt_drop: bool,
800
801     pub kind: GenericParamDefKind,
802 }
803
804 impl GenericParamDef {
805     pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
806         if let GenericParamDefKind::Lifetime = self.kind {
807             ty::EarlyBoundRegion { def_id: self.def_id, index: self.index, name: self.name }
808         } else {
809             bug!("cannot convert a non-lifetime parameter def to an early bound region")
810         }
811     }
812
813     pub fn to_bound_region(&self) -> ty::BoundRegion {
814         if let GenericParamDefKind::Lifetime = self.kind {
815             self.to_early_bound_region_data().to_bound_region()
816         } else {
817             bug!("cannot convert a non-lifetime parameter def to an early bound region")
818         }
819     }
820 }
821
822 #[derive(Default)]
823 pub struct GenericParamCount {
824     pub lifetimes: usize,
825     pub types: usize,
826     pub consts: usize,
827 }
828
829 /// Information about the formal type/lifetime parameters associated
830 /// with an item or method. Analogous to `hir::Generics`.
831 ///
832 /// The ordering of parameters is the same as in `Subst` (excluding child generics):
833 /// `Self` (optionally), `Lifetime` params..., `Type` params...
834 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
835 pub struct Generics {
836     pub parent: Option<DefId>,
837     pub parent_count: usize,
838     pub params: Vec<GenericParamDef>,
839
840     /// Reverse map to the `index` field of each `GenericParamDef`.
841     #[stable_hasher(ignore)]
842     pub param_def_id_to_index: FxHashMap<DefId, u32>,
843
844     pub has_self: bool,
845     pub has_late_bound_regions: Option<Span>,
846 }
847
848 impl<'tcx> Generics {
849     pub fn count(&self) -> usize {
850         self.parent_count + self.params.len()
851     }
852
853     pub fn own_counts(&self) -> GenericParamCount {
854         // We could cache this as a property of `GenericParamCount`, but
855         // the aim is to refactor this away entirely eventually and the
856         // presence of this method will be a constant reminder.
857         let mut own_counts: GenericParamCount = Default::default();
858
859         for param in &self.params {
860             match param.kind {
861                 GenericParamDefKind::Lifetime => own_counts.lifetimes += 1,
862                 GenericParamDefKind::Type { .. } => own_counts.types += 1,
863                 GenericParamDefKind::Const => own_counts.consts += 1,
864             };
865         }
866
867         own_counts
868     }
869
870     pub fn requires_monomorphization(&self, tcx: TyCtxt<'tcx>) -> bool {
871         if self.own_requires_monomorphization() {
872             return true;
873         }
874
875         if let Some(parent_def_id) = self.parent {
876             let parent = tcx.generics_of(parent_def_id);
877             parent.requires_monomorphization(tcx)
878         } else {
879             false
880         }
881     }
882
883     pub fn own_requires_monomorphization(&self) -> bool {
884         for param in &self.params {
885             match param.kind {
886                 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => return true,
887                 GenericParamDefKind::Lifetime => {}
888             }
889         }
890         false
891     }
892
893     /// Returns the `GenericParamDef` with the given index.
894     pub fn param_at(&'tcx self, param_index: usize, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
895         if let Some(index) = param_index.checked_sub(self.parent_count) {
896             &self.params[index]
897         } else {
898             tcx.generics_of(self.parent.expect("parent_count > 0 but no parent?"))
899                 .param_at(param_index, tcx)
900         }
901     }
902
903     /// Returns the `GenericParamDef` associated with this `EarlyBoundRegion`.
904     pub fn region_param(
905         &'tcx self,
906         param: &EarlyBoundRegion,
907         tcx: TyCtxt<'tcx>,
908     ) -> &'tcx GenericParamDef {
909         let param = self.param_at(param.index as usize, tcx);
910         match param.kind {
911             GenericParamDefKind::Lifetime => param,
912             _ => bug!("expected lifetime parameter, but found another generic parameter"),
913         }
914     }
915
916     /// Returns the `GenericParamDef` associated with this `ParamTy`.
917     pub fn type_param(&'tcx self, param: &ParamTy, tcx: TyCtxt<'tcx>) -> &'tcx GenericParamDef {
918         let param = self.param_at(param.index as usize, tcx);
919         match param.kind {
920             GenericParamDefKind::Type { .. } => param,
921             _ => bug!("expected type parameter, but found another generic parameter"),
922         }
923     }
924
925     /// Returns the `GenericParamDef` associated with this `ParamConst`.
926     pub fn const_param(&'tcx self, param: &ParamConst, tcx: TyCtxt<'tcx>) -> &GenericParamDef {
927         let param = self.param_at(param.index as usize, tcx);
928         match param.kind {
929             GenericParamDefKind::Const => param,
930             _ => bug!("expected const parameter, but found another generic parameter"),
931         }
932     }
933 }
934
935 /// Bounds on generics.
936 #[derive(Copy, Clone, Default, Debug, RustcEncodable, RustcDecodable, HashStable)]
937 pub struct GenericPredicates<'tcx> {
938     pub parent: Option<DefId>,
939     pub predicates: &'tcx [(Predicate<'tcx>, Span)],
940 }
941
942 impl<'tcx> GenericPredicates<'tcx> {
943     pub fn instantiate(
944         &self,
945         tcx: TyCtxt<'tcx>,
946         substs: SubstsRef<'tcx>,
947     ) -> InstantiatedPredicates<'tcx> {
948         let mut instantiated = InstantiatedPredicates::empty();
949         self.instantiate_into(tcx, &mut instantiated, substs);
950         instantiated
951     }
952
953     pub fn instantiate_own(
954         &self,
955         tcx: TyCtxt<'tcx>,
956         substs: SubstsRef<'tcx>,
957     ) -> InstantiatedPredicates<'tcx> {
958         InstantiatedPredicates {
959             predicates: self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)).collect(),
960             spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
961         }
962     }
963
964     fn instantiate_into(
965         &self,
966         tcx: TyCtxt<'tcx>,
967         instantiated: &mut InstantiatedPredicates<'tcx>,
968         substs: SubstsRef<'tcx>,
969     ) {
970         if let Some(def_id) = self.parent {
971             tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs);
972         }
973         instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p.subst(tcx, substs)));
974         instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
975     }
976
977     pub fn instantiate_identity(&self, tcx: TyCtxt<'tcx>) -> InstantiatedPredicates<'tcx> {
978         let mut instantiated = InstantiatedPredicates::empty();
979         self.instantiate_identity_into(tcx, &mut instantiated);
980         instantiated
981     }
982
983     fn instantiate_identity_into(
984         &self,
985         tcx: TyCtxt<'tcx>,
986         instantiated: &mut InstantiatedPredicates<'tcx>,
987     ) {
988         if let Some(def_id) = self.parent {
989             tcx.predicates_of(def_id).instantiate_identity_into(tcx, instantiated);
990         }
991         instantiated.predicates.extend(self.predicates.iter().map(|(p, _)| p));
992         instantiated.spans.extend(self.predicates.iter().map(|(_, s)| s));
993     }
994
995     pub fn instantiate_supertrait(
996         &self,
997         tcx: TyCtxt<'tcx>,
998         poly_trait_ref: &ty::PolyTraitRef<'tcx>,
999     ) -> InstantiatedPredicates<'tcx> {
1000         assert_eq!(self.parent, None);
1001         InstantiatedPredicates {
1002             predicates: self
1003                 .predicates
1004                 .iter()
1005                 .map(|(pred, _)| pred.subst_supertrait(tcx, poly_trait_ref))
1006                 .collect(),
1007             spans: self.predicates.iter().map(|(_, sp)| *sp).collect(),
1008         }
1009     }
1010 }
1011
1012 #[derive(Debug)]
1013 crate struct PredicateInner<'tcx> {
1014     kind: PredicateKind<'tcx>,
1015     flags: TypeFlags,
1016     /// See the comment for the corresponding field of [TyS].
1017     outer_exclusive_binder: ty::DebruijnIndex,
1018 }
1019
1020 #[cfg(target_arch = "x86_64")]
1021 static_assert_size!(PredicateInner<'_>, 40);
1022
1023 #[derive(Clone, Copy, Lift)]
1024 pub struct Predicate<'tcx> {
1025     inner: &'tcx PredicateInner<'tcx>,
1026 }
1027
1028 impl rustc_serialize::UseSpecializedEncodable for Predicate<'_> {}
1029 impl rustc_serialize::UseSpecializedDecodable for Predicate<'_> {}
1030
1031 impl<'tcx> PartialEq for Predicate<'tcx> {
1032     fn eq(&self, other: &Self) -> bool {
1033         // `self.kind` is always interned.
1034         ptr::eq(self.inner, other.inner)
1035     }
1036 }
1037
1038 impl Hash for Predicate<'_> {
1039     fn hash<H: Hasher>(&self, s: &mut H) {
1040         (self.inner as *const PredicateInner<'_>).hash(s)
1041     }
1042 }
1043
1044 impl<'tcx> Eq for Predicate<'tcx> {}
1045
1046 impl<'tcx> Predicate<'tcx> {
1047     #[inline(always)]
1048     pub fn kind(self) -> &'tcx PredicateKind<'tcx> {
1049         &self.inner.kind
1050     }
1051 }
1052
1053 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
1054     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1055         let PredicateInner {
1056             ref kind,
1057
1058             // The other fields just provide fast access to information that is
1059             // also contained in `kind`, so no need to hash them.
1060             flags: _,
1061             outer_exclusive_binder: _,
1062         } = self.inner;
1063
1064         kind.hash_stable(hcx, hasher);
1065     }
1066 }
1067
1068 impl<'tcx> Predicate<'tcx> {
1069     pub fn kint(self, tcx: TyCtxt<'tcx>) -> &'tcx PredicateKint<'tcx> {
1070         // I am efficient
1071         tcx.intern_predicate_kint(match *self.kind() {
1072             PredicateKind::Trait(binder, data) => {
1073                 if let Some(simpl) = binder.no_bound_vars() {
1074                     PredicateKint::Trait(simpl, data)
1075                 } else {
1076                     let inner = tcx
1077                         .intern_predicate_kint(PredicateKint::Trait(*binder.skip_binder(), data));
1078                     PredicateKint::ForAll(Binder::bind(inner))
1079                 }
1080             }
1081             PredicateKind::RegionOutlives(binder) => {
1082                 if let Some(simpl) = binder.no_bound_vars() {
1083                     PredicateKint::RegionOutlives(simpl)
1084                 } else {
1085                     let inner = tcx.intern_predicate_kint(PredicateKint::RegionOutlives(
1086                         *binder.skip_binder(),
1087                     ));
1088                     PredicateKint::ForAll(Binder::bind(inner))
1089                 }
1090             }
1091             PredicateKind::TypeOutlives(binder) => {
1092                 if let Some(simpl) = binder.no_bound_vars() {
1093                     PredicateKint::TypeOutlives(simpl)
1094                 } else {
1095                     let inner = tcx
1096                         .intern_predicate_kint(PredicateKint::TypeOutlives(*binder.skip_binder()));
1097                     PredicateKint::ForAll(Binder::bind(inner))
1098                 }
1099             }
1100             PredicateKind::Projection(binder) => {
1101                 if let Some(simpl) = binder.no_bound_vars() {
1102                     PredicateKint::Projection(simpl)
1103                 } else {
1104                     let inner =
1105                         tcx.intern_predicate_kint(PredicateKint::Projection(*binder.skip_binder()));
1106                     PredicateKint::ForAll(Binder::bind(inner))
1107                 }
1108             }
1109             PredicateKind::WellFormed(arg) => PredicateKint::WellFormed(arg),
1110             PredicateKind::ObjectSafe(def_id) => PredicateKint::ObjectSafe(def_id),
1111             PredicateKind::ClosureKind(def_id, substs, kind) => {
1112                 PredicateKint::ClosureKind(def_id, substs, kind)
1113             }
1114             PredicateKind::Subtype(binder) => {
1115                 if let Some(simpl) = binder.no_bound_vars() {
1116                     PredicateKint::Subtype(simpl)
1117                 } else {
1118                     let inner =
1119                         tcx.intern_predicate_kint(PredicateKint::Subtype(*binder.skip_binder()));
1120                     PredicateKint::ForAll(Binder::bind(inner))
1121                 }
1122             }
1123             PredicateKind::ConstEvaluatable(def, substs) => {
1124                 PredicateKint::ConstEvaluatable(def, substs)
1125             }
1126             PredicateKind::ConstEquate(l, r) => PredicateKint::ConstEquate(l, r),
1127         })
1128     }
1129 }
1130
1131 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1132 #[derive(TypeFoldable)]
1133 pub enum PredicateKint<'tcx> {
1134     /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1135     /// the `Self` type of the trait reference and `A`, `B`, and `C`
1136     /// would be the type parameters.
1137     ///
1138     /// A trait predicate will have `Constness::Const` if it originates
1139     /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1140     /// `const fn foobar<Foo: Bar>() {}`).
1141     Trait(TraitPredicate<'tcx>, Constness),
1142
1143     /// `where 'a: 'b`
1144     RegionOutlives(RegionOutlivesPredicate<'tcx>),
1145
1146     /// `where T: 'a`
1147     TypeOutlives(TypeOutlivesPredicate<'tcx>),
1148
1149     /// `where <T as TraitRef>::Name == X`, approximately.
1150     /// See the `ProjectionPredicate` struct for details.
1151     Projection(ProjectionPredicate<'tcx>),
1152
1153     /// No syntax: `T` well-formed.
1154     WellFormed(GenericArg<'tcx>),
1155
1156     /// Trait must be object-safe.
1157     ObjectSafe(DefId),
1158
1159     /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1160     /// for some substitutions `...` and `T` being a closure type.
1161     /// Satisfied (or refuted) once we know the closure's kind.
1162     ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1163
1164     /// `T1 <: T2`
1165     Subtype(SubtypePredicate<'tcx>),
1166
1167     /// Constant initializer must evaluate successfully.
1168     ConstEvaluatable(DefId, SubstsRef<'tcx>),
1169
1170     /// Constants must be equal. The first component is the const that is expected.
1171     ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1172
1173     /// `for<'a>: ...`
1174     ForAll(Binder<&'tcx PredicateKint<'tcx>>),
1175 }
1176
1177 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1178 #[derive(HashStable, TypeFoldable)]
1179 pub enum PredicateKind<'tcx> {
1180     /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
1181     /// the `Self` type of the trait reference and `A`, `B`, and `C`
1182     /// would be the type parameters.
1183     ///
1184     /// A trait predicate will have `Constness::Const` if it originates
1185     /// from a bound on a `const fn` without the `?const` opt-out (e.g.,
1186     /// `const fn foobar<Foo: Bar>() {}`).
1187     Trait(PolyTraitPredicate<'tcx>, Constness),
1188
1189     /// `where 'a: 'b`
1190     RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
1191
1192     /// `where T: 'a`
1193     TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
1194
1195     /// `where <T as TraitRef>::Name == X`, approximately.
1196     /// See the `ProjectionPredicate` struct for details.
1197     Projection(PolyProjectionPredicate<'tcx>),
1198
1199     /// No syntax: `T` well-formed.
1200     WellFormed(GenericArg<'tcx>),
1201
1202     /// Trait must be object-safe.
1203     ObjectSafe(DefId),
1204
1205     /// No direct syntax. May be thought of as `where T: FnFoo<...>`
1206     /// for some substitutions `...` and `T` being a closure type.
1207     /// Satisfied (or refuted) once we know the closure's kind.
1208     ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
1209
1210     /// `T1 <: T2`
1211     Subtype(PolySubtypePredicate<'tcx>),
1212
1213     /// Constant initializer must evaluate successfully.
1214     ConstEvaluatable(ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
1215
1216     /// Constants must be equal. The first component is the const that is expected.
1217     ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>),
1218 }
1219
1220 /// The crate outlives map is computed during typeck and contains the
1221 /// outlives of every item in the local crate. You should not use it
1222 /// directly, because to do so will make your pass dependent on the
1223 /// HIR of every item in the local crate. Instead, use
1224 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
1225 /// item.
1226 #[derive(HashStable)]
1227 pub struct CratePredicatesMap<'tcx> {
1228     /// For each struct with outlive bounds, maps to a vector of the
1229     /// predicate of its outlive bounds. If an item has no outlives
1230     /// bounds, it will have no entry.
1231     pub predicates: FxHashMap<DefId, &'tcx [(ty::Predicate<'tcx>, Span)]>,
1232 }
1233
1234 impl<'tcx> Predicate<'tcx> {
1235     /// Performs a substitution suitable for going from a
1236     /// poly-trait-ref to supertraits that must hold if that
1237     /// poly-trait-ref holds. This is slightly different from a normal
1238     /// substitution in terms of what happens with bound regions. See
1239     /// lengthy comment below for details.
1240     pub fn subst_supertrait(
1241         self,
1242         tcx: TyCtxt<'tcx>,
1243         trait_ref: &ty::PolyTraitRef<'tcx>,
1244     ) -> ty::Predicate<'tcx> {
1245         // The interaction between HRTB and supertraits is not entirely
1246         // obvious. Let me walk you (and myself) through an example.
1247         //
1248         // Let's start with an easy case. Consider two traits:
1249         //
1250         //     trait Foo<'a>: Bar<'a,'a> { }
1251         //     trait Bar<'b,'c> { }
1252         //
1253         // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
1254         // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
1255         // knew that `Foo<'x>` (for any 'x) then we also know that
1256         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
1257         // normal substitution.
1258         //
1259         // In terms of why this is sound, the idea is that whenever there
1260         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
1261         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
1262         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
1263         // `'a`.
1264         //
1265         // Another example to be careful of is this:
1266         //
1267         //     trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
1268         //     trait Bar1<'b,'c> { }
1269         //
1270         // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
1271         // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
1272         // reason is similar to the previous example: any impl of
1273         // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`.  So
1274         // basically we would want to collapse the bound lifetimes from
1275         // the input (`trait_ref`) and the supertraits.
1276         //
1277         // To achieve this in practice is fairly straightforward. Let's
1278         // consider the more complicated scenario:
1279         //
1280         // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
1281         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
1282         //   where both `'x` and `'b` would have a DB index of 1.
1283         //   The substitution from the input trait-ref is therefore going to be
1284         //   `'a => 'x` (where `'x` has a DB index of 1).
1285         // - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
1286         //   early-bound parameter and `'b' is a late-bound parameter with a
1287         //   DB index of 1.
1288         // - If we replace `'a` with `'x` from the input, it too will have
1289         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
1290         //   just as we wanted.
1291         //
1292         // There is only one catch. If we just apply the substitution `'a
1293         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
1294         // adjust the DB index because we substituting into a binder (it
1295         // tries to be so smart...) resulting in `for<'x> for<'b>
1296         // Bar1<'x,'b>` (we have no syntax for this, so use your
1297         // imagination). Basically the 'x will have DB index of 2 and 'b
1298         // will have DB index of 1. Not quite what we want. So we apply
1299         // the substitution to the *contents* of the trait reference,
1300         // rather than the trait reference itself (put another way, the
1301         // substitution code expects equal binding levels in the values
1302         // from the substitution and the value being substituted into, and
1303         // this trick achieves that).
1304
1305         let substs = trait_ref.skip_binder().substs;
1306         let kind = self.kind();
1307         let new = match kind {
1308             &PredicateKind::Trait(ref binder, constness) => {
1309                 PredicateKind::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness)
1310             }
1311             PredicateKind::Subtype(binder) => {
1312                 PredicateKind::Subtype(binder.map_bound(|data| data.subst(tcx, substs)))
1313             }
1314             PredicateKind::RegionOutlives(binder) => {
1315                 PredicateKind::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1316             }
1317             PredicateKind::TypeOutlives(binder) => {
1318                 PredicateKind::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs)))
1319             }
1320             PredicateKind::Projection(binder) => {
1321                 PredicateKind::Projection(binder.map_bound(|data| data.subst(tcx, substs)))
1322             }
1323             &PredicateKind::WellFormed(data) => PredicateKind::WellFormed(data.subst(tcx, substs)),
1324             &PredicateKind::ObjectSafe(trait_def_id) => PredicateKind::ObjectSafe(trait_def_id),
1325             &PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
1326                 PredicateKind::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind)
1327             }
1328             &PredicateKind::ConstEvaluatable(def_id, const_substs) => {
1329                 PredicateKind::ConstEvaluatable(def_id, const_substs.subst(tcx, substs))
1330             }
1331             PredicateKind::ConstEquate(c1, c2) => {
1332                 PredicateKind::ConstEquate(c1.subst(tcx, substs), c2.subst(tcx, substs))
1333             }
1334         };
1335
1336         if new != *kind { new.to_predicate(tcx) } else { self }
1337     }
1338 }
1339
1340 #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1341 #[derive(HashStable, TypeFoldable)]
1342 pub struct TraitPredicate<'tcx> {
1343     pub trait_ref: TraitRef<'tcx>,
1344 }
1345
1346 pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
1347
1348 impl<'tcx> TraitPredicate<'tcx> {
1349     pub fn def_id(self) -> DefId {
1350         self.trait_ref.def_id
1351     }
1352
1353     pub fn self_ty(self) -> Ty<'tcx> {
1354         self.trait_ref.self_ty()
1355     }
1356 }
1357
1358 impl<'tcx> PolyTraitPredicate<'tcx> {
1359     pub fn def_id(self) -> DefId {
1360         // Ok to skip binder since trait `DefId` does not care about regions.
1361         self.skip_binder().def_id()
1362     }
1363 }
1364
1365 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
1366 #[derive(HashStable, TypeFoldable)]
1367 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
1368 pub type PolyOutlivesPredicate<A, B> = ty::Binder<OutlivesPredicate<A, B>>;
1369 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
1370 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
1371 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<RegionOutlivesPredicate<'tcx>>;
1372 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<TypeOutlivesPredicate<'tcx>>;
1373
1374 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
1375 #[derive(HashStable, TypeFoldable)]
1376 pub struct SubtypePredicate<'tcx> {
1377     pub a_is_expected: bool,
1378     pub a: Ty<'tcx>,
1379     pub b: Ty<'tcx>,
1380 }
1381 pub type PolySubtypePredicate<'tcx> = ty::Binder<SubtypePredicate<'tcx>>;
1382
1383 /// This kind of predicate has no *direct* correspondent in the
1384 /// syntax, but it roughly corresponds to the syntactic forms:
1385 ///
1386 /// 1. `T: TraitRef<..., Item = Type>`
1387 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
1388 ///
1389 /// In particular, form #1 is "desugared" to the combination of a
1390 /// normal trait predicate (`T: TraitRef<...>`) and one of these
1391 /// predicates. Form #2 is a broader form in that it also permits
1392 /// equality between arbitrary types. Processing an instance of
1393 /// Form #2 eventually yields one of these `ProjectionPredicate`
1394 /// instances to normalize the LHS.
1395 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1396 #[derive(HashStable, TypeFoldable)]
1397 pub struct ProjectionPredicate<'tcx> {
1398     pub projection_ty: ProjectionTy<'tcx>,
1399     pub ty: Ty<'tcx>,
1400 }
1401
1402 pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
1403
1404 impl<'tcx> PolyProjectionPredicate<'tcx> {
1405     /// Returns the `DefId` of the associated item being projected.
1406     pub fn item_def_id(&self) -> DefId {
1407         self.skip_binder().projection_ty.item_def_id
1408     }
1409
1410     #[inline]
1411     pub fn to_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
1412         // Note: unlike with `TraitRef::to_poly_trait_ref()`,
1413         // `self.0.trait_ref` is permitted to have escaping regions.
1414         // This is because here `self` has a `Binder` and so does our
1415         // return value, so we are preserving the number of binding
1416         // levels.
1417         self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
1418     }
1419
1420     pub fn ty(&self) -> Binder<Ty<'tcx>> {
1421         self.map_bound(|predicate| predicate.ty)
1422     }
1423
1424     /// The `DefId` of the `TraitItem` for the associated type.
1425     ///
1426     /// Note that this is not the `DefId` of the `TraitRef` containing this
1427     /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
1428     pub fn projection_def_id(&self) -> DefId {
1429         // Ok to skip binder since trait `DefId` does not care about regions.
1430         self.skip_binder().projection_ty.item_def_id
1431     }
1432 }
1433
1434 pub trait ToPolyTraitRef<'tcx> {
1435     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1436 }
1437
1438 impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
1439     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1440         ty::Binder::dummy(*self)
1441     }
1442 }
1443
1444 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1445     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1446         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1447     }
1448 }
1449
1450 pub trait ToPredicate<'tcx> {
1451     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1452 }
1453
1454 impl ToPredicate<'tcx> for PredicateKind<'tcx> {
1455     #[inline(always)]
1456     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1457         tcx.mk_predicate(self)
1458     }
1459 }
1460
1461 impl ToPredicate<'tcx> for PredicateKint<'tcx> {
1462     #[inline(always)]
1463     fn to_predicate(&self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1464         let (predicate, in_binder) = if let PredicateKint::ForAll(binder) = self {
1465             (*binder.skip_binder(), true)
1466         } else {
1467             (self, false)
1468         };
1469
1470         macro_rules! bind {
1471             ($expr:expr) => {
1472                 match $expr {
1473                     expr => {
1474                         if in_binder {
1475                             Binder::bind(expr)
1476                         } else {
1477                             Binder::dummy(expr)
1478                         }
1479                     }
1480                 }
1481             };
1482         }
1483
1484         match *predicate {
1485             PredicateKint::ForAll(_) => bug!("unexpected PredicateKint: {:?}", self),
1486             PredicateKint::Trait(data, ct) => PredicateKind::Trait(bind!(data), ct),
1487             PredicateKint::RegionOutlives(data) => PredicateKind::RegionOutlives(bind!(data)),
1488             PredicateKint::TypeOutlives(data) => PredicateKind::TypeOutlives(bind!(data)),
1489             PredicateKint::Projection(data) => PredicateKind::Projection(bind!(data)),
1490             PredicateKint::WellFormed(arg) => {
1491                 if in_binder {
1492                     bug!("unexpected ForAll: {:?}", self)
1493                 } else {
1494                     PredicateKind::WellFormed(arg)
1495                 }
1496             }
1497             PredicateKint::ObjectSafe(def_id) => {
1498                 if in_binder {
1499                     bug!("unexpected ForAll: {:?}", self)
1500                 } else {
1501                     PredicateKind::ObjectSafe(def_id)
1502                 }
1503             }
1504             PredicateKint::ClosureKind(def_id, substs, kind) => {
1505                 if in_binder {
1506                     bug!("unexpected ForAll: {:?}", self)
1507                 } else {
1508                     PredicateKind::ClosureKind(def_id, substs, kind)
1509                 }
1510             }
1511             PredicateKint::Subtype(data) => PredicateKind::Subtype(bind!(data)),
1512             PredicateKint::ConstEvaluatable(def_id, substs) => {
1513                 if in_binder {
1514                     bug!("unexpected ForAll: {:?}", self)
1515                 } else {
1516                     PredicateKind::ConstEvaluatable(def_id, substs)
1517                 }
1518             }
1519             PredicateKint::ConstEquate(l, r) => {
1520                 if in_binder {
1521                     bug!("unexpected ForAll: {:?}", self)
1522                 } else {
1523                     PredicateKind::ConstEquate(l, r)
1524                 }
1525             }
1526         }
1527         .to_predicate(tcx)
1528     }
1529 }
1530
1531 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<TraitRef<'tcx>> {
1532     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1533         ty::PredicateKind::Trait(
1534             ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }),
1535             self.constness,
1536         )
1537         .to_predicate(tcx)
1538     }
1539 }
1540
1541 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> {
1542     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1543         ty::PredicateKind::Trait(
1544             ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }),
1545             self.constness,
1546         )
1547         .to_predicate(tcx)
1548     }
1549 }
1550
1551 impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<PolyTraitRef<'tcx>> {
1552     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1553         ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness)
1554             .to_predicate(tcx)
1555     }
1556 }
1557
1558 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1559     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1560         PredicateKind::RegionOutlives(self).to_predicate(tcx)
1561     }
1562 }
1563
1564 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1565     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1566         PredicateKind::TypeOutlives(self).to_predicate(tcx)
1567     }
1568 }
1569
1570 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1571     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1572         PredicateKind::Projection(self).to_predicate(tcx)
1573     }
1574 }
1575
1576 impl<'tcx> Predicate<'tcx> {
1577     pub fn to_opt_poly_trait_ref(self) -> Option<PolyTraitRef<'tcx>> {
1578         match self.kind() {
1579             &PredicateKind::Trait(ref t, _) => Some(t.to_poly_trait_ref()),
1580             PredicateKind::Projection(..)
1581             | PredicateKind::Subtype(..)
1582             | PredicateKind::RegionOutlives(..)
1583             | PredicateKind::WellFormed(..)
1584             | PredicateKind::ObjectSafe(..)
1585             | PredicateKind::ClosureKind(..)
1586             | PredicateKind::TypeOutlives(..)
1587             | PredicateKind::ConstEvaluatable(..)
1588             | PredicateKind::ConstEquate(..) => None,
1589         }
1590     }
1591
1592     pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1593         match self.kind() {
1594             &PredicateKind::TypeOutlives(data) => Some(data),
1595             PredicateKind::Trait(..)
1596             | PredicateKind::Projection(..)
1597             | PredicateKind::Subtype(..)
1598             | PredicateKind::RegionOutlives(..)
1599             | PredicateKind::WellFormed(..)
1600             | PredicateKind::ObjectSafe(..)
1601             | PredicateKind::ClosureKind(..)
1602             | PredicateKind::ConstEvaluatable(..)
1603             | PredicateKind::ConstEquate(..) => None,
1604         }
1605     }
1606 }
1607
1608 /// Represents the bounds declared on a particular set of type
1609 /// parameters. Should eventually be generalized into a flag list of
1610 /// where-clauses. You can obtain a `InstantiatedPredicates` list from a
1611 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1612 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1613 /// the `GenericPredicates` are expressed in terms of the bound type
1614 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1615 /// represented a set of bounds for some particular instantiation,
1616 /// meaning that the generic parameters have been substituted with
1617 /// their values.
1618 ///
1619 /// Example:
1620 ///
1621 ///     struct Foo<T, U: Bar<T>> { ... }
1622 ///
1623 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1624 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1625 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1626 /// [usize:Bar<isize>]]`.
1627 #[derive(Clone, Debug, TypeFoldable)]
1628 pub struct InstantiatedPredicates<'tcx> {
1629     pub predicates: Vec<Predicate<'tcx>>,
1630     pub spans: Vec<Span>,
1631 }
1632
1633 impl<'tcx> InstantiatedPredicates<'tcx> {
1634     pub fn empty() -> InstantiatedPredicates<'tcx> {
1635         InstantiatedPredicates { predicates: vec![], spans: vec![] }
1636     }
1637
1638     pub fn is_empty(&self) -> bool {
1639         self.predicates.is_empty()
1640     }
1641 }
1642
1643 rustc_index::newtype_index! {
1644     /// "Universes" are used during type- and trait-checking in the
1645     /// presence of `for<..>` binders to control what sets of names are
1646     /// visible. Universes are arranged into a tree: the root universe
1647     /// contains names that are always visible. Each child then adds a new
1648     /// set of names that are visible, in addition to those of its parent.
1649     /// We say that the child universe "extends" the parent universe with
1650     /// new names.
1651     ///
1652     /// To make this more concrete, consider this program:
1653     ///
1654     /// ```
1655     /// struct Foo { }
1656     /// fn bar<T>(x: T) {
1657     ///   let y: for<'a> fn(&'a u8, Foo) = ...;
1658     /// }
1659     /// ```
1660     ///
1661     /// The struct name `Foo` is in the root universe U0. But the type
1662     /// parameter `T`, introduced on `bar`, is in an extended universe U1
1663     /// -- i.e., within `bar`, we can name both `T` and `Foo`, but outside
1664     /// of `bar`, we cannot name `T`. Then, within the type of `y`, the
1665     /// region `'a` is in a universe U2 that extends U1, because we can
1666     /// name it inside the fn type but not outside.
1667     ///
1668     /// Universes are used to do type- and trait-checking around these
1669     /// "forall" binders (also called **universal quantification**). The
1670     /// idea is that when, in the body of `bar`, we refer to `T` as a
1671     /// type, we aren't referring to any type in particular, but rather a
1672     /// kind of "fresh" type that is distinct from all other types we have
1673     /// actually declared. This is called a **placeholder** type, and we
1674     /// use universes to talk about this. In other words, a type name in
1675     /// universe 0 always corresponds to some "ground" type that the user
1676     /// declared, but a type name in a non-zero universe is a placeholder
1677     /// type -- an idealized representative of "types in general" that we
1678     /// use for checking generic functions.
1679     pub struct UniverseIndex {
1680         derive [HashStable]
1681         DEBUG_FORMAT = "U{}",
1682     }
1683 }
1684
1685 impl UniverseIndex {
1686     pub const ROOT: UniverseIndex = UniverseIndex::from_u32(0);
1687
1688     /// Returns the "next" universe index in order -- this new index
1689     /// is considered to extend all previous universes. This
1690     /// corresponds to entering a `forall` quantifier. So, for
1691     /// example, suppose we have this type in universe `U`:
1692     ///
1693     /// ```
1694     /// for<'a> fn(&'a u32)
1695     /// ```
1696     ///
1697     /// Once we "enter" into this `for<'a>` quantifier, we are in a
1698     /// new universe that extends `U` -- in this new universe, we can
1699     /// name the region `'a`, but that region was not nameable from
1700     /// `U` because it was not in scope there.
1701     pub fn next_universe(self) -> UniverseIndex {
1702         UniverseIndex::from_u32(self.private.checked_add(1).unwrap())
1703     }
1704
1705     /// Returns `true` if `self` can name a name from `other` -- in other words,
1706     /// if the set of names in `self` is a superset of those in
1707     /// `other` (`self >= other`).
1708     pub fn can_name(self, other: UniverseIndex) -> bool {
1709         self.private >= other.private
1710     }
1711
1712     /// Returns `true` if `self` cannot name some names from `other` -- in other
1713     /// words, if the set of names in `self` is a strict subset of
1714     /// those in `other` (`self < other`).
1715     pub fn cannot_name(self, other: UniverseIndex) -> bool {
1716         self.private < other.private
1717     }
1718 }
1719
1720 /// The "placeholder index" fully defines a placeholder region.
1721 /// Placeholder regions are identified by both a **universe** as well
1722 /// as a "bound-region" within that universe. The `bound_region` is
1723 /// basically a name -- distinct bound regions within the same
1724 /// universe are just two regions with an unknown relationship to one
1725 /// another.
1726 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
1727 pub struct Placeholder<T> {
1728     pub universe: UniverseIndex,
1729     pub name: T,
1730 }
1731
1732 impl<'a, T> HashStable<StableHashingContext<'a>> for Placeholder<T>
1733 where
1734     T: HashStable<StableHashingContext<'a>>,
1735 {
1736     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1737         self.universe.hash_stable(hcx, hasher);
1738         self.name.hash_stable(hcx, hasher);
1739     }
1740 }
1741
1742 pub type PlaceholderRegion = Placeholder<BoundRegion>;
1743
1744 pub type PlaceholderType = Placeholder<BoundVar>;
1745
1746 pub type PlaceholderConst = Placeholder<BoundVar>;
1747
1748 /// A `DefId` which is potentially bundled with its corresponding generic parameter
1749 /// in case `did` is a const argument.
1750 ///
1751 /// This is used to prevent cycle errors during typeck
1752 /// as `type_of(const_arg)` depends on `typeck(owning_body)`
1753 /// which once again requires the type of its generic arguments.
1754 ///
1755 /// Luckily we only need to deal with const arguments once we
1756 /// know their corresponding parameters. We (ab)use this by
1757 /// calling `type_of(param_did)` for these arguments.
1758 ///
1759 /// ```rust
1760 /// #![feature(const_generics)]
1761 ///
1762 /// struct A;
1763 /// impl A {
1764 ///     fn foo<const N: usize>(&self) -> usize { N }
1765 /// }
1766 /// struct B;
1767 /// impl B {
1768 ///     fn foo<const N: u8>(&self) -> usize { 42 }
1769 /// }
1770 ///
1771 /// fn main() {
1772 ///     let a = A;
1773 ///     a.foo::<7>();
1774 /// }
1775 /// ```
1776 #[derive(Copy, Clone, Debug, TypeFoldable, Lift, RustcEncodable, RustcDecodable)]
1777 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1778 #[derive(Hash, HashStable)]
1779 pub struct WithOptConstParam<T> {
1780     pub did: T,
1781     /// The `DefId` of the corresponding generic paramter in case `did` is
1782     /// a const argument.
1783     ///
1784     /// Note that even if `did` is a const argument, this may still be `None`.
1785     /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1786     /// to potentially update `param_did` in case it `None`.
1787     pub const_param_did: Option<DefId>,
1788 }
1789
1790 impl<T> WithOptConstParam<T> {
1791     /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1792     #[inline(always)]
1793     pub fn unknown(did: T) -> WithOptConstParam<T> {
1794         WithOptConstParam { did, const_param_did: None }
1795     }
1796 }
1797
1798 impl WithOptConstParam<LocalDefId> {
1799     /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1800     /// `None` otherwise.
1801     #[inline(always)]
1802     pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1803         tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1804     }
1805
1806     /// In case `self` is unknown but `self.did` is a const argument, this returns
1807     /// a `WithOptConstParam` with the correct `const_param_did`.
1808     #[inline(always)]
1809     pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1810         if self.const_param_did.is_none() {
1811             if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1812                 return Some(WithOptConstParam { did: self.did, const_param_did });
1813             }
1814         }
1815
1816         None
1817     }
1818
1819     pub fn to_global(self) -> WithOptConstParam<DefId> {
1820         WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1821     }
1822
1823     pub fn def_id_for_type_of(self) -> DefId {
1824         if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1825     }
1826 }
1827
1828 impl WithOptConstParam<DefId> {
1829     pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1830         self.did
1831             .as_local()
1832             .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1833     }
1834
1835     pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1836         if let Some(param_did) = self.const_param_did {
1837             if let Some(did) = self.did.as_local() {
1838                 return Some((did, param_did));
1839             }
1840         }
1841
1842         None
1843     }
1844
1845     pub fn expect_local(self) -> WithOptConstParam<LocalDefId> {
1846         self.as_local().unwrap()
1847     }
1848
1849     pub fn is_local(self) -> bool {
1850         self.did.is_local()
1851     }
1852
1853     pub fn def_id_for_type_of(self) -> DefId {
1854         self.const_param_did.unwrap_or(self.did)
1855     }
1856 }
1857
1858 /// When type checking, we use the `ParamEnv` to track
1859 /// details about the set of where-clauses that are in scope at this
1860 /// particular point.
1861 #[derive(Copy, Clone)]
1862 pub struct ParamEnv<'tcx> {
1863     // We pack the caller_bounds List pointer and a Reveal enum into this usize.
1864     // Specifically, the low bit represents Reveal, with 0 meaning `UserFacing`
1865     // and 1 meaning `All`. The rest is the pointer.
1866     //
1867     // This relies on the List<ty::Predicate<'tcx>> type having at least 2-byte
1868     // alignment. Lists start with a usize and are repr(C) so this should be
1869     // fine; there is a debug_assert in the constructor as well.
1870     //
1871     // Note that the choice of 0 for UserFacing is intentional -- since it is the
1872     // first variant in Reveal this means that joining the pointer is a simple `or`.
1873     packed_data: usize,
1874
1875     /// `Obligation`s that the caller must satisfy. This is basically
1876     /// the set of bounds on the in-scope type parameters, translated
1877     /// into `Obligation`s, and elaborated and normalized.
1878     ///
1879     /// Note: This is packed into the `packed_data` usize above, use the
1880     /// `caller_bounds()` method to access it.
1881     caller_bounds: PhantomData<&'tcx List<ty::Predicate<'tcx>>>,
1882
1883     /// Typically, this is `Reveal::UserFacing`, but during codegen we
1884     /// want `Reveal::All`.
1885     ///
1886     /// Note: This is packed into the caller_bounds usize above, use the reveal()
1887     /// method to access it.
1888     reveal: PhantomData<traits::Reveal>,
1889
1890     /// If this `ParamEnv` comes from a call to `tcx.param_env(def_id)`,
1891     /// register that `def_id` (useful for transitioning to the chalk trait
1892     /// solver).
1893     pub def_id: Option<DefId>,
1894 }
1895
1896 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1897     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1898         f.debug_struct("ParamEnv")
1899             .field("caller_bounds", &self.caller_bounds())
1900             .field("reveal", &self.reveal())
1901             .field("def_id", &self.def_id)
1902             .finish()
1903     }
1904 }
1905
1906 impl<'tcx> Hash for ParamEnv<'tcx> {
1907     fn hash<H: Hasher>(&self, state: &mut H) {
1908         // List hashes as the raw pointer, so we can skip splitting into the
1909         // pointer and the enum.
1910         self.packed_data.hash(state);
1911         self.def_id.hash(state);
1912     }
1913 }
1914
1915 impl<'tcx> PartialEq for ParamEnv<'tcx> {
1916     fn eq(&self, other: &Self) -> bool {
1917         self.caller_bounds() == other.caller_bounds()
1918             && self.reveal() == other.reveal()
1919             && self.def_id == other.def_id
1920     }
1921 }
1922 impl<'tcx> Eq for ParamEnv<'tcx> {}
1923
1924 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1925     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1926         self.caller_bounds().hash_stable(hcx, hasher);
1927         self.reveal().hash_stable(hcx, hasher);
1928         self.def_id.hash_stable(hcx, hasher);
1929     }
1930 }
1931
1932 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1933     fn super_fold_with<F: ty::fold::TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
1934         ParamEnv::new(
1935             self.caller_bounds().fold_with(folder),
1936             self.reveal().fold_with(folder),
1937             self.def_id.fold_with(folder),
1938         )
1939     }
1940
1941     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1942         self.caller_bounds().visit_with(visitor)
1943             || self.reveal().visit_with(visitor)
1944             || self.def_id.visit_with(visitor)
1945     }
1946 }
1947
1948 impl<'tcx> ParamEnv<'tcx> {
1949     /// Construct a trait environment suitable for contexts where
1950     /// there are no where-clauses in scope. Hidden types (like `impl
1951     /// Trait`) are left hidden, so this is suitable for ordinary
1952     /// type-checking.
1953     #[inline]
1954     pub fn empty() -> Self {
1955         Self::new(List::empty(), Reveal::UserFacing, None)
1956     }
1957
1958     #[inline]
1959     pub fn caller_bounds(self) -> &'tcx List<ty::Predicate<'tcx>> {
1960         // mask out bottom bit
1961         unsafe { &*((self.packed_data & (!1)) as *const _) }
1962     }
1963
1964     #[inline]
1965     pub fn reveal(self) -> traits::Reveal {
1966         if self.packed_data & 1 == 0 { traits::Reveal::UserFacing } else { traits::Reveal::All }
1967     }
1968
1969     /// Construct a trait environment with no where-clauses in scope
1970     /// where the values of all `impl Trait` and other hidden types
1971     /// are revealed. This is suitable for monomorphized, post-typeck
1972     /// environments like codegen or doing optimizations.
1973     ///
1974     /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1975     /// or invoke `param_env.with_reveal_all()`.
1976     #[inline]
1977     pub fn reveal_all() -> Self {
1978         Self::new(List::empty(), Reveal::All, None)
1979     }
1980
1981     /// Construct a trait environment with the given set of predicates.
1982     #[inline]
1983     pub fn new(
1984         caller_bounds: &'tcx List<ty::Predicate<'tcx>>,
1985         reveal: Reveal,
1986         def_id: Option<DefId>,
1987     ) -> Self {
1988         let packed_data = caller_bounds as *const _ as usize;
1989         // Check that we can pack the reveal data into the pointer.
1990         debug_assert!(packed_data & 1 == 0);
1991         ty::ParamEnv {
1992             packed_data: packed_data
1993                 | match reveal {
1994                     Reveal::UserFacing => 0,
1995                     Reveal::All => 1,
1996                 },
1997             caller_bounds: PhantomData,
1998             reveal: PhantomData,
1999             def_id,
2000         }
2001     }
2002
2003     pub fn with_user_facing(mut self) -> Self {
2004         // clear bottom bit
2005         self.packed_data &= !1;
2006         self
2007     }
2008
2009     /// Returns a new parameter environment with the same clauses, but
2010     /// which "reveals" the true results of projections in all cases
2011     /// (even for associated types that are specializable). This is
2012     /// the desired behavior during codegen and certain other special
2013     /// contexts; normally though we want to use `Reveal::UserFacing`,
2014     /// which is the default.
2015     pub fn with_reveal_all(mut self) -> Self {
2016         self.packed_data |= 1;
2017         self
2018     }
2019
2020     /// Returns this same environment but with no caller bounds.
2021     pub fn without_caller_bounds(self) -> Self {
2022         Self::new(List::empty(), self.reveal(), self.def_id)
2023     }
2024
2025     /// Creates a suitable environment in which to perform trait
2026     /// queries on the given value. When type-checking, this is simply
2027     /// the pair of the environment plus value. But when reveal is set to
2028     /// All, then if `value` does not reference any type parameters, we will
2029     /// pair it with the empty environment. This improves caching and is generally
2030     /// invisible.
2031     ///
2032     /// N.B., we preserve the environment when type-checking because it
2033     /// is possible for the user to have wacky where-clauses like
2034     /// `where Box<u32>: Copy`, which are clearly never
2035     /// satisfiable. We generally want to behave as if they were true,
2036     /// although the surrounding function is never reachable.
2037     pub fn and<T: TypeFoldable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
2038         match self.reveal() {
2039             Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
2040
2041             Reveal::All => {
2042                 if value.is_global() {
2043                     ParamEnvAnd { param_env: self.without_caller_bounds(), value }
2044                 } else {
2045                     ParamEnvAnd { param_env: self, value }
2046                 }
2047             }
2048         }
2049     }
2050 }
2051
2052 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
2053 pub struct ConstnessAnd<T> {
2054     pub constness: Constness,
2055     pub value: T,
2056 }
2057
2058 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
2059 // the constness of trait bounds is being propagated correctly.
2060 pub trait WithConstness: Sized {
2061     #[inline]
2062     fn with_constness(self, constness: Constness) -> ConstnessAnd<Self> {
2063         ConstnessAnd { constness, value: self }
2064     }
2065
2066     #[inline]
2067     fn with_const(self) -> ConstnessAnd<Self> {
2068         self.with_constness(Constness::Const)
2069     }
2070
2071     #[inline]
2072     fn without_const(self) -> ConstnessAnd<Self> {
2073         self.with_constness(Constness::NotConst)
2074     }
2075 }
2076
2077 impl<T> WithConstness for T {}
2078
2079 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)]
2080 pub struct ParamEnvAnd<'tcx, T> {
2081     pub param_env: ParamEnv<'tcx>,
2082     pub value: T,
2083 }
2084
2085 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
2086     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
2087         (self.param_env, self.value)
2088     }
2089 }
2090
2091 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a>> for ParamEnvAnd<'tcx, T>
2092 where
2093     T: HashStable<StableHashingContext<'a>>,
2094 {
2095     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2096         let ParamEnvAnd { ref param_env, ref value } = *self;
2097
2098         param_env.hash_stable(hcx, hasher);
2099         value.hash_stable(hcx, hasher);
2100     }
2101 }
2102
2103 #[derive(Copy, Clone, Debug, HashStable)]
2104 pub struct Destructor {
2105     /// The `DefId` of the destructor method
2106     pub did: DefId,
2107 }
2108
2109 bitflags! {
2110     #[derive(HashStable)]
2111     pub struct AdtFlags: u32 {
2112         const NO_ADT_FLAGS        = 0;
2113         /// Indicates whether the ADT is an enum.
2114         const IS_ENUM             = 1 << 0;
2115         /// Indicates whether the ADT is a union.
2116         const IS_UNION            = 1 << 1;
2117         /// Indicates whether the ADT is a struct.
2118         const IS_STRUCT           = 1 << 2;
2119         /// Indicates whether the ADT is a struct and has a constructor.
2120         const HAS_CTOR            = 1 << 3;
2121         /// Indicates whether the type is `PhantomData`.
2122         const IS_PHANTOM_DATA     = 1 << 4;
2123         /// Indicates whether the type has a `#[fundamental]` attribute.
2124         const IS_FUNDAMENTAL      = 1 << 5;
2125         /// Indicates whether the type is `Box`.
2126         const IS_BOX              = 1 << 6;
2127         /// Indicates whether the type is `ManuallyDrop`.
2128         const IS_MANUALLY_DROP    = 1 << 7;
2129         /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
2130         /// (i.e., this flag is never set unless this ADT is an enum).
2131         const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8;
2132     }
2133 }
2134
2135 bitflags! {
2136     #[derive(HashStable)]
2137     pub struct VariantFlags: u32 {
2138         const NO_VARIANT_FLAGS        = 0;
2139         /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
2140         const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
2141     }
2142 }
2143
2144 /// Definition of a variant -- a struct's fields or a enum variant.
2145 #[derive(Debug, HashStable)]
2146 pub struct VariantDef {
2147     /// `DefId` that identifies the variant itself.
2148     /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
2149     pub def_id: DefId,
2150     /// `DefId` that identifies the variant's constructor.
2151     /// If this variant is a struct variant, then this is `None`.
2152     pub ctor_def_id: Option<DefId>,
2153     /// Variant or struct name.
2154     #[stable_hasher(project(name))]
2155     pub ident: Ident,
2156     /// Discriminant of this variant.
2157     pub discr: VariantDiscr,
2158     /// Fields of this variant.
2159     pub fields: Vec<FieldDef>,
2160     /// Type of constructor of variant.
2161     pub ctor_kind: CtorKind,
2162     /// Flags of the variant (e.g. is field list non-exhaustive)?
2163     flags: VariantFlags,
2164     /// Variant is obtained as part of recovering from a syntactic error.
2165     /// May be incomplete or bogus.
2166     pub recovered: bool,
2167 }
2168
2169 impl<'tcx> VariantDef {
2170     /// Creates a new `VariantDef`.
2171     ///
2172     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
2173     /// represents an enum variant).
2174     ///
2175     /// `ctor_did` is the `DefId` that identifies the constructor of unit or
2176     /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
2177     ///
2178     /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
2179     /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
2180     /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
2181     /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
2182     /// built-in trait), and we do not want to load attributes twice.
2183     ///
2184     /// If someone speeds up attribute loading to not be a performance concern, they can
2185     /// remove this hack and use the constructor `DefId` everywhere.
2186     pub fn new(
2187         tcx: TyCtxt<'tcx>,
2188         ident: Ident,
2189         variant_did: Option<DefId>,
2190         ctor_def_id: Option<DefId>,
2191         discr: VariantDiscr,
2192         fields: Vec<FieldDef>,
2193         ctor_kind: CtorKind,
2194         adt_kind: AdtKind,
2195         parent_did: DefId,
2196         recovered: bool,
2197     ) -> Self {
2198         debug!(
2199             "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
2200              fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
2201             ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
2202         );
2203
2204         let mut flags = VariantFlags::NO_VARIANT_FLAGS;
2205         if adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive) {
2206             debug!("found non-exhaustive field list for {:?}", parent_did);
2207             flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2208         } else if let Some(variant_did) = variant_did {
2209             if tcx.has_attr(variant_did, sym::non_exhaustive) {
2210                 debug!("found non-exhaustive field list for {:?}", variant_did);
2211                 flags = flags | VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
2212             }
2213         }
2214
2215         VariantDef {
2216             def_id: variant_did.unwrap_or(parent_did),
2217             ctor_def_id,
2218             ident,
2219             discr,
2220             fields,
2221             ctor_kind,
2222             flags,
2223             recovered,
2224         }
2225     }
2226
2227     /// Is this field list non-exhaustive?
2228     #[inline]
2229     pub fn is_field_list_non_exhaustive(&self) -> bool {
2230         self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
2231     }
2232
2233     /// `repr(transparent)` structs can have a single non-ZST field, this function returns that
2234     /// field.
2235     pub fn transparent_newtype_field(&self, tcx: TyCtxt<'tcx>) -> Option<&FieldDef> {
2236         for field in &self.fields {
2237             let field_ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, self.def_id));
2238             if !field_ty.is_zst(tcx, self.def_id) {
2239                 return Some(field);
2240             }
2241         }
2242
2243         None
2244     }
2245 }
2246
2247 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2248 pub enum VariantDiscr {
2249     /// Explicit value for this variant, i.e., `X = 123`.
2250     /// The `DefId` corresponds to the embedded constant.
2251     Explicit(DefId),
2252
2253     /// The previous variant's discriminant plus one.
2254     /// For efficiency reasons, the distance from the
2255     /// last `Explicit` discriminant is being stored,
2256     /// or `0` for the first variant, if it has none.
2257     Relative(u32),
2258 }
2259
2260 #[derive(Debug, HashStable)]
2261 pub struct FieldDef {
2262     pub did: DefId,
2263     #[stable_hasher(project(name))]
2264     pub ident: Ident,
2265     pub vis: Visibility,
2266 }
2267
2268 /// The definition of a user-defined type, e.g., a `struct`, `enum`, or `union`.
2269 ///
2270 /// These are all interned (by `alloc_adt_def`) into the global arena.
2271 ///
2272 /// The initialism *ADT* stands for an [*algebraic data type (ADT)*][adt].
2273 /// This is slightly wrong because `union`s are not ADTs.
2274 /// Moreover, Rust only allows recursive data types through indirection.
2275 ///
2276 /// [adt]: https://en.wikipedia.org/wiki/Algebraic_data_type
2277 pub struct AdtDef {
2278     /// The `DefId` of the struct, enum or union item.
2279     pub did: DefId,
2280     /// Variants of the ADT. If this is a struct or union, then there will be a single variant.
2281     pub variants: IndexVec<VariantIdx, VariantDef>,
2282     /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?).
2283     flags: AdtFlags,
2284     /// Repr options provided by the user.
2285     pub repr: ReprOptions,
2286 }
2287
2288 impl PartialOrd for AdtDef {
2289     fn partial_cmp(&self, other: &AdtDef) -> Option<Ordering> {
2290         Some(self.cmp(&other))
2291     }
2292 }
2293
2294 /// There should be only one AdtDef for each `did`, therefore
2295 /// it is fine to implement `Ord` only based on `did`.
2296 impl Ord for AdtDef {
2297     fn cmp(&self, other: &AdtDef) -> Ordering {
2298         self.did.cmp(&other.did)
2299     }
2300 }
2301
2302 impl PartialEq for AdtDef {
2303     // `AdtDef`s are always interned, and this is part of `TyS` equality.
2304     #[inline]
2305     fn eq(&self, other: &Self) -> bool {
2306         ptr::eq(self, other)
2307     }
2308 }
2309
2310 impl Eq for AdtDef {}
2311
2312 impl Hash for AdtDef {
2313     #[inline]
2314     fn hash<H: Hasher>(&self, s: &mut H) {
2315         (self as *const AdtDef).hash(s)
2316     }
2317 }
2318
2319 impl<'tcx> rustc_serialize::UseSpecializedEncodable for &'tcx AdtDef {
2320     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2321         self.did.encode(s)
2322     }
2323 }
2324
2325 impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx AdtDef {}
2326
2327 impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
2328     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
2329         thread_local! {
2330             static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
2331         }
2332
2333         let hash: Fingerprint = CACHE.with(|cache| {
2334             let addr = self as *const AdtDef as usize;
2335             *cache.borrow_mut().entry(addr).or_insert_with(|| {
2336                 let ty::AdtDef { did, ref variants, ref flags, ref repr } = *self;
2337
2338                 let mut hasher = StableHasher::new();
2339                 did.hash_stable(hcx, &mut hasher);
2340                 variants.hash_stable(hcx, &mut hasher);
2341                 flags.hash_stable(hcx, &mut hasher);
2342                 repr.hash_stable(hcx, &mut hasher);
2343
2344                 hasher.finish()
2345             })
2346         });
2347
2348         hash.hash_stable(hcx, hasher);
2349     }
2350 }
2351
2352 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
2353 pub enum AdtKind {
2354     Struct,
2355     Union,
2356     Enum,
2357 }
2358
2359 impl Into<DataTypeKind> for AdtKind {
2360     fn into(self) -> DataTypeKind {
2361         match self {
2362             AdtKind::Struct => DataTypeKind::Struct,
2363             AdtKind::Union => DataTypeKind::Union,
2364             AdtKind::Enum => DataTypeKind::Enum,
2365         }
2366     }
2367 }
2368
2369 bitflags! {
2370     #[derive(RustcEncodable, RustcDecodable, Default, HashStable)]
2371     pub struct ReprFlags: u8 {
2372         const IS_C               = 1 << 0;
2373         const IS_SIMD            = 1 << 1;
2374         const IS_TRANSPARENT     = 1 << 2;
2375         // Internal only for now. If true, don't reorder fields.
2376         const IS_LINEAR          = 1 << 3;
2377         // If true, don't expose any niche to type's context.
2378         const HIDE_NICHE         = 1 << 4;
2379         // Any of these flags being set prevent field reordering optimisation.
2380         const IS_UNOPTIMISABLE   = ReprFlags::IS_C.bits |
2381                                    ReprFlags::IS_SIMD.bits |
2382                                    ReprFlags::IS_LINEAR.bits;
2383     }
2384 }
2385
2386 /// Represents the repr options provided by the user,
2387 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Default, HashStable)]
2388 pub struct ReprOptions {
2389     pub int: Option<attr::IntType>,
2390     pub align: Option<Align>,
2391     pub pack: Option<Align>,
2392     pub flags: ReprFlags,
2393 }
2394
2395 impl ReprOptions {
2396     pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
2397         let mut flags = ReprFlags::empty();
2398         let mut size = None;
2399         let mut max_align: Option<Align> = None;
2400         let mut min_pack: Option<Align> = None;
2401         for attr in tcx.get_attrs(did).iter() {
2402             for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) {
2403                 flags.insert(match r {
2404                     attr::ReprC => ReprFlags::IS_C,
2405                     attr::ReprPacked(pack) => {
2406                         let pack = Align::from_bytes(pack as u64).unwrap();
2407                         min_pack = Some(if let Some(min_pack) = min_pack {
2408                             min_pack.min(pack)
2409                         } else {
2410                             pack
2411                         });
2412                         ReprFlags::empty()
2413                     }
2414                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2415                     attr::ReprNoNiche => ReprFlags::HIDE_NICHE,
2416                     attr::ReprSimd => ReprFlags::IS_SIMD,
2417                     attr::ReprInt(i) => {
2418                         size = Some(i);
2419                         ReprFlags::empty()
2420                     }
2421                     attr::ReprAlign(align) => {
2422                         max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2423                         ReprFlags::empty()
2424                     }
2425                 });
2426             }
2427         }
2428
2429         // This is here instead of layout because the choice must make it into metadata.
2430         if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
2431             flags.insert(ReprFlags::IS_LINEAR);
2432         }
2433         ReprOptions { int: size, align: max_align, pack: min_pack, flags }
2434     }
2435
2436     #[inline]
2437     pub fn simd(&self) -> bool {
2438         self.flags.contains(ReprFlags::IS_SIMD)
2439     }
2440     #[inline]
2441     pub fn c(&self) -> bool {
2442         self.flags.contains(ReprFlags::IS_C)
2443     }
2444     #[inline]
2445     pub fn packed(&self) -> bool {
2446         self.pack.is_some()
2447     }
2448     #[inline]
2449     pub fn transparent(&self) -> bool {
2450         self.flags.contains(ReprFlags::IS_TRANSPARENT)
2451     }
2452     #[inline]
2453     pub fn linear(&self) -> bool {
2454         self.flags.contains(ReprFlags::IS_LINEAR)
2455     }
2456     #[inline]
2457     pub fn hide_niche(&self) -> bool {
2458         self.flags.contains(ReprFlags::HIDE_NICHE)
2459     }
2460
2461     /// Returns the discriminant type, given these `repr` options.
2462     /// This must only be called on enums!
2463     pub fn discr_type(&self) -> attr::IntType {
2464         self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
2465     }
2466
2467     /// Returns `true` if this `#[repr()]` should inhabit "smart enum
2468     /// layout" optimizations, such as representing `Foo<&T>` as a
2469     /// single pointer.
2470     pub fn inhibit_enum_layout_opt(&self) -> bool {
2471         self.c() || self.int.is_some()
2472     }
2473
2474     /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
2475     /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
2476     pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
2477         if let Some(pack) = self.pack {
2478             if pack.bytes() == 1 {
2479                 return true;
2480             }
2481         }
2482         self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
2483     }
2484
2485     /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
2486     pub fn inhibit_union_abi_opt(&self) -> bool {
2487         self.c()
2488     }
2489 }
2490
2491 impl<'tcx> AdtDef {
2492     /// Creates a new `AdtDef`.
2493     fn new(
2494         tcx: TyCtxt<'_>,
2495         did: DefId,
2496         kind: AdtKind,
2497         variants: IndexVec<VariantIdx, VariantDef>,
2498         repr: ReprOptions,
2499     ) -> Self {
2500         debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
2501         let mut flags = AdtFlags::NO_ADT_FLAGS;
2502
2503         if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
2504             debug!("found non-exhaustive variant list for {:?}", did);
2505             flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
2506         }
2507
2508         flags |= match kind {
2509             AdtKind::Enum => AdtFlags::IS_ENUM,
2510             AdtKind::Union => AdtFlags::IS_UNION,
2511             AdtKind::Struct => AdtFlags::IS_STRUCT,
2512         };
2513
2514         if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor_def_id.is_some() {
2515             flags |= AdtFlags::HAS_CTOR;
2516         }
2517
2518         let attrs = tcx.get_attrs(did);
2519         if attr::contains_name(&attrs, sym::fundamental) {
2520             flags |= AdtFlags::IS_FUNDAMENTAL;
2521         }
2522         if Some(did) == tcx.lang_items().phantom_data() {
2523             flags |= AdtFlags::IS_PHANTOM_DATA;
2524         }
2525         if Some(did) == tcx.lang_items().owned_box() {
2526             flags |= AdtFlags::IS_BOX;
2527         }
2528         if Some(did) == tcx.lang_items().manually_drop() {
2529             flags |= AdtFlags::IS_MANUALLY_DROP;
2530         }
2531
2532         AdtDef { did, variants, flags, repr }
2533     }
2534
2535     /// Returns `true` if this is a struct.
2536     #[inline]
2537     pub fn is_struct(&self) -> bool {
2538         self.flags.contains(AdtFlags::IS_STRUCT)
2539     }
2540
2541     /// Returns `true` if this is a union.
2542     #[inline]
2543     pub fn is_union(&self) -> bool {
2544         self.flags.contains(AdtFlags::IS_UNION)
2545     }
2546
2547     /// Returns `true` if this is a enum.
2548     #[inline]
2549     pub fn is_enum(&self) -> bool {
2550         self.flags.contains(AdtFlags::IS_ENUM)
2551     }
2552
2553     /// Returns `true` if the variant list of this ADT is `#[non_exhaustive]`.
2554     #[inline]
2555     pub fn is_variant_list_non_exhaustive(&self) -> bool {
2556         self.flags.contains(AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE)
2557     }
2558
2559     /// Returns the kind of the ADT.
2560     #[inline]
2561     pub fn adt_kind(&self) -> AdtKind {
2562         if self.is_enum() {
2563             AdtKind::Enum
2564         } else if self.is_union() {
2565             AdtKind::Union
2566         } else {
2567             AdtKind::Struct
2568         }
2569     }
2570
2571     /// Returns a description of this abstract data type.
2572     pub fn descr(&self) -> &'static str {
2573         match self.adt_kind() {
2574             AdtKind::Struct => "struct",
2575             AdtKind::Union => "union",
2576             AdtKind::Enum => "enum",
2577         }
2578     }
2579
2580     /// Returns a description of a variant of this abstract data type.
2581     #[inline]
2582     pub fn variant_descr(&self) -> &'static str {
2583         match self.adt_kind() {
2584             AdtKind::Struct => "struct",
2585             AdtKind::Union => "union",
2586             AdtKind::Enum => "variant",
2587         }
2588     }
2589
2590     /// If this function returns `true`, it implies that `is_struct` must return `true`.
2591     #[inline]
2592     pub fn has_ctor(&self) -> bool {
2593         self.flags.contains(AdtFlags::HAS_CTOR)
2594     }
2595
2596     /// Returns `true` if this type is `#[fundamental]` for the purposes
2597     /// of coherence checking.
2598     #[inline]
2599     pub fn is_fundamental(&self) -> bool {
2600         self.flags.contains(AdtFlags::IS_FUNDAMENTAL)
2601     }
2602
2603     /// Returns `true` if this is `PhantomData<T>`.
2604     #[inline]
2605     pub fn is_phantom_data(&self) -> bool {
2606         self.flags.contains(AdtFlags::IS_PHANTOM_DATA)
2607     }
2608
2609     /// Returns `true` if this is Box<T>.
2610     #[inline]
2611     pub fn is_box(&self) -> bool {
2612         self.flags.contains(AdtFlags::IS_BOX)
2613     }
2614
2615     /// Returns `true` if this is `ManuallyDrop<T>`.
2616     #[inline]
2617     pub fn is_manually_drop(&self) -> bool {
2618         self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
2619     }
2620
2621     /// Returns `true` if this type has a destructor.
2622     pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
2623         self.destructor(tcx).is_some()
2624     }
2625
2626     /// Asserts this is a struct or union and returns its unique variant.
2627     pub fn non_enum_variant(&self) -> &VariantDef {
2628         assert!(self.is_struct() || self.is_union());
2629         &self.variants[VariantIdx::new(0)]
2630     }
2631
2632     #[inline]
2633     pub fn predicates(&self, tcx: TyCtxt<'tcx>) -> GenericPredicates<'tcx> {
2634         tcx.predicates_of(self.did)
2635     }
2636
2637     /// Returns an iterator over all fields contained
2638     /// by this ADT.
2639     #[inline]
2640     pub fn all_fields(&self) -> impl Iterator<Item = &FieldDef> + Clone {
2641         self.variants.iter().flat_map(|v| v.fields.iter())
2642     }
2643
2644     pub fn is_payloadfree(&self) -> bool {
2645         !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty())
2646     }
2647
2648     /// Return a `VariantDef` given a variant id.
2649     pub fn variant_with_id(&self, vid: DefId) -> &VariantDef {
2650         self.variants.iter().find(|v| v.def_id == vid).expect("variant_with_id: unknown variant")
2651     }
2652
2653     /// Return a `VariantDef` given a constructor id.
2654     pub fn variant_with_ctor_id(&self, cid: DefId) -> &VariantDef {
2655         self.variants
2656             .iter()
2657             .find(|v| v.ctor_def_id == Some(cid))
2658             .expect("variant_with_ctor_id: unknown variant")
2659     }
2660
2661     /// Return the index of `VariantDef` given a variant id.
2662     pub fn variant_index_with_id(&self, vid: DefId) -> VariantIdx {
2663         self.variants
2664             .iter_enumerated()
2665             .find(|(_, v)| v.def_id == vid)
2666             .expect("variant_index_with_id: unknown variant")
2667             .0
2668     }
2669
2670     /// Return the index of `VariantDef` given a constructor id.
2671     pub fn variant_index_with_ctor_id(&self, cid: DefId) -> VariantIdx {
2672         self.variants
2673             .iter_enumerated()
2674             .find(|(_, v)| v.ctor_def_id == Some(cid))
2675             .expect("variant_index_with_ctor_id: unknown variant")
2676             .0
2677     }
2678
2679     pub fn variant_of_res(&self, res: Res) -> &VariantDef {
2680         match res {
2681             Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid),
2682             Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid),
2683             Res::Def(DefKind::Struct, _)
2684             | Res::Def(DefKind::Union, _)
2685             | Res::Def(DefKind::TyAlias, _)
2686             | Res::Def(DefKind::AssocTy, _)
2687             | Res::SelfTy(..)
2688             | Res::SelfCtor(..) => self.non_enum_variant(),
2689             _ => bug!("unexpected res {:?} in variant_of_res", res),
2690         }
2691     }
2692
2693     #[inline]
2694     pub fn eval_explicit_discr(&self, tcx: TyCtxt<'tcx>, expr_did: DefId) -> Option<Discr<'tcx>> {
2695         assert!(self.is_enum());
2696         let param_env = tcx.param_env(expr_did);
2697         let repr_type = self.repr.discr_type();
2698         match tcx.const_eval_poly(expr_did) {
2699             Ok(val) => {
2700                 let ty = repr_type.to_ty(tcx);
2701                 if let Some(b) = val.try_to_bits_for_ty(tcx, param_env, ty) {
2702                     trace!("discriminants: {} ({:?})", b, repr_type);
2703                     Some(Discr { val: b, ty })
2704                 } else {
2705                     info!("invalid enum discriminant: {:#?}", val);
2706                     crate::mir::interpret::struct_error(
2707                         tcx.at(tcx.def_span(expr_did)),
2708                         "constant evaluation of enum discriminant resulted in non-integer",
2709                     )
2710                     .emit();
2711                     None
2712                 }
2713             }
2714             Err(err) => {
2715                 let msg = match err {
2716                     ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
2717                         "enum discriminant evaluation failed"
2718                     }
2719                     ErrorHandled::TooGeneric => "enum discriminant depends on generics",
2720                 };
2721                 tcx.sess.delay_span_bug(tcx.def_span(expr_did), msg);
2722                 None
2723             }
2724         }
2725     }
2726
2727     #[inline]
2728     pub fn discriminants(
2729         &'tcx self,
2730         tcx: TyCtxt<'tcx>,
2731     ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
2732         assert!(self.is_enum());
2733         let repr_type = self.repr.discr_type();
2734         let initial = repr_type.initial_discriminant(tcx);
2735         let mut prev_discr = None::<Discr<'tcx>>;
2736         self.variants.iter_enumerated().map(move |(i, v)| {
2737             let mut discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
2738             if let VariantDiscr::Explicit(expr_did) = v.discr {
2739                 if let Some(new_discr) = self.eval_explicit_discr(tcx, expr_did) {
2740                     discr = new_discr;
2741                 }
2742             }
2743             prev_discr = Some(discr);
2744
2745             (i, discr)
2746         })
2747     }
2748
2749     #[inline]
2750     pub fn variant_range(&self) -> Range<VariantIdx> {
2751         VariantIdx::new(0)..VariantIdx::new(self.variants.len())
2752     }
2753
2754     /// Computes the discriminant value used by a specific variant.
2755     /// Unlike `discriminants`, this is (amortized) constant-time,
2756     /// only doing at most one query for evaluating an explicit
2757     /// discriminant (the last one before the requested variant),
2758     /// assuming there are no constant-evaluation errors there.
2759     #[inline]
2760     pub fn discriminant_for_variant(
2761         &self,
2762         tcx: TyCtxt<'tcx>,
2763         variant_index: VariantIdx,
2764     ) -> Discr<'tcx> {
2765         assert!(self.is_enum());
2766         let (val, offset) = self.discriminant_def_for_variant(variant_index);
2767         let explicit_value = val
2768             .and_then(|expr_did| self.eval_explicit_discr(tcx, expr_did))
2769             .unwrap_or_else(|| self.repr.discr_type().initial_discriminant(tcx));
2770         explicit_value.checked_add(tcx, offset as u128).0
2771     }
2772
2773     /// Yields a `DefId` for the discriminant and an offset to add to it
2774     /// Alternatively, if there is no explicit discriminant, returns the
2775     /// inferred discriminant directly.
2776     pub fn discriminant_def_for_variant(&self, variant_index: VariantIdx) -> (Option<DefId>, u32) {
2777         assert!(!self.variants.is_empty());
2778         let mut explicit_index = variant_index.as_u32();
2779         let expr_did;
2780         loop {
2781             match self.variants[VariantIdx::from_u32(explicit_index)].discr {
2782                 ty::VariantDiscr::Relative(0) => {
2783                     expr_did = None;
2784                     break;
2785                 }
2786                 ty::VariantDiscr::Relative(distance) => {
2787                     explicit_index -= distance;
2788                 }
2789                 ty::VariantDiscr::Explicit(did) => {
2790                     expr_did = Some(did);
2791                     break;
2792                 }
2793             }
2794         }
2795         (expr_did, variant_index.as_u32() - explicit_index)
2796     }
2797
2798     pub fn destructor(&self, tcx: TyCtxt<'tcx>) -> Option<Destructor> {
2799         tcx.adt_destructor(self.did)
2800     }
2801
2802     /// Returns a list of types such that `Self: Sized` if and only
2803     /// if that type is `Sized`, or `TyErr` if this type is recursive.
2804     ///
2805     /// Oddly enough, checking that the sized-constraint is `Sized` is
2806     /// actually more expressive than checking all members:
2807     /// the `Sized` trait is inductive, so an associated type that references
2808     /// `Self` would prevent its containing ADT from being `Sized`.
2809     ///
2810     /// Due to normalization being eager, this applies even if
2811     /// the associated type is behind a pointer (e.g., issue #31299).
2812     pub fn sized_constraint(&self, tcx: TyCtxt<'tcx>) -> &'tcx [Ty<'tcx>] {
2813         tcx.adt_sized_constraint(self.did).0
2814     }
2815 }
2816
2817 impl<'tcx> FieldDef {
2818     /// Returns the type of this field. The `subst` is typically obtained
2819     /// via the second field of `TyKind::AdtDef`.
2820     pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
2821         tcx.type_of(self.did).subst(tcx, subst)
2822     }
2823 }
2824
2825 /// Represents the various closure traits in the language. This
2826 /// will determine the type of the environment (`self`, in the
2827 /// desugaring) argument that the closure expects.
2828 ///
2829 /// You can get the environment type of a closure using
2830 /// `tcx.closure_env_ty()`.
2831 #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
2832 #[derive(HashStable)]
2833 pub enum ClosureKind {
2834     // Warning: Ordering is significant here! The ordering is chosen
2835     // because the trait Fn is a subtrait of FnMut and so in turn, and
2836     // hence we order it so that Fn < FnMut < FnOnce.
2837     Fn,
2838     FnMut,
2839     FnOnce,
2840 }
2841
2842 impl<'tcx> ClosureKind {
2843     // This is the initial value used when doing upvar inference.
2844     pub const LATTICE_BOTTOM: ClosureKind = ClosureKind::Fn;
2845
2846     pub fn trait_did(&self, tcx: TyCtxt<'tcx>) -> DefId {
2847         match *self {
2848             ClosureKind::Fn => tcx.require_lang_item(FnTraitLangItem, None),
2849             ClosureKind::FnMut => tcx.require_lang_item(FnMutTraitLangItem, None),
2850             ClosureKind::FnOnce => tcx.require_lang_item(FnOnceTraitLangItem, None),
2851         }
2852     }
2853
2854     /// Returns `true` if this a type that impls this closure kind
2855     /// must also implement `other`.
2856     pub fn extends(self, other: ty::ClosureKind) -> bool {
2857         match (self, other) {
2858             (ClosureKind::Fn, ClosureKind::Fn) => true,
2859             (ClosureKind::Fn, ClosureKind::FnMut) => true,
2860             (ClosureKind::Fn, ClosureKind::FnOnce) => true,
2861             (ClosureKind::FnMut, ClosureKind::FnMut) => true,
2862             (ClosureKind::FnMut, ClosureKind::FnOnce) => true,
2863             (ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
2864             _ => false,
2865         }
2866     }
2867
2868     /// Returns the representative scalar type for this closure kind.
2869     /// See `TyS::to_opt_closure_kind` for more details.
2870     pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2871         match self {
2872             ty::ClosureKind::Fn => tcx.types.i8,
2873             ty::ClosureKind::FnMut => tcx.types.i16,
2874             ty::ClosureKind::FnOnce => tcx.types.i32,
2875         }
2876     }
2877 }
2878
2879 impl BorrowKind {
2880     pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
2881         match m {
2882             hir::Mutability::Mut => MutBorrow,
2883             hir::Mutability::Not => ImmBorrow,
2884         }
2885     }
2886
2887     /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
2888     /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
2889     /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
2890     /// question.
2891     pub fn to_mutbl_lossy(self) -> hir::Mutability {
2892         match self {
2893             MutBorrow => hir::Mutability::Mut,
2894             ImmBorrow => hir::Mutability::Not,
2895
2896             // We have no type corresponding to a unique imm borrow, so
2897             // use `&mut`. It gives all the capabilities of an `&uniq`
2898             // and hence is a safe "over approximation".
2899             UniqueImmBorrow => hir::Mutability::Mut,
2900         }
2901     }
2902
2903     pub fn to_user_str(&self) -> &'static str {
2904         match *self {
2905             MutBorrow => "mutable",
2906             ImmBorrow => "immutable",
2907             UniqueImmBorrow => "uniquely immutable",
2908         }
2909     }
2910 }
2911
2912 pub type Attributes<'tcx> = &'tcx [ast::Attribute];
2913
2914 #[derive(Debug, PartialEq, Eq)]
2915 pub enum ImplOverlapKind {
2916     /// These impls are always allowed to overlap.
2917     Permitted {
2918         /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2919         marker: bool,
2920     },
2921     /// These impls are allowed to overlap, but that raises
2922     /// an issue #33140 future-compatibility warning.
2923     ///
2924     /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2925     /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2926     ///
2927     /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2928     /// that difference, making what reduces to the following set of impls:
2929     ///
2930     /// ```
2931     /// trait Trait {}
2932     /// impl Trait for dyn Send + Sync {}
2933     /// impl Trait for dyn Sync + Send {}
2934     /// ```
2935     ///
2936     /// Obviously, once we made these types be identical, that code causes a coherence
2937     /// error and a fairly big headache for us. However, luckily for us, the trait
2938     /// `Trait` used in this case is basically a marker trait, and therefore having
2939     /// overlapping impls for it is sound.
2940     ///
2941     /// To handle this, we basically regard the trait as a marker trait, with an additional
2942     /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2943     /// it has the following restrictions:
2944     ///
2945     /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2946     /// positive impls.
2947     /// 2. The trait-ref of both impls must be equal.
2948     /// 3. The trait-ref of both impls must be a trait object type consisting only of
2949     /// marker traits.
2950     /// 4. Neither of the impls can have any where-clauses.
2951     ///
2952     /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2953     Issue33140,
2954 }
2955
2956 impl<'tcx> TyCtxt<'tcx> {
2957     pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2958         self.typeck(self.hir().body_owner_def_id(body))
2959     }
2960
2961     /// Returns an iterator of the `DefId`s for all body-owners in this
2962     /// crate. If you would prefer to iterate over the bodies
2963     /// themselves, you can do `self.hir().krate().body_ids.iter()`.
2964     pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + Captures<'tcx> + 'tcx {
2965         self.hir()
2966             .krate()
2967             .body_ids
2968             .iter()
2969             .map(move |&body_id| self.hir().body_owner_def_id(body_id))
2970     }
2971
2972     pub fn par_body_owners<F: Fn(LocalDefId) + sync::Sync + sync::Send>(self, f: F) {
2973         par_iter(&self.hir().krate().body_ids)
2974             .for_each(|&body_id| f(self.hir().body_owner_def_id(body_id)));
2975     }
2976
2977     pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2978         self.associated_items(id)
2979             .in_definition_order()
2980             .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value())
2981     }
2982
2983     pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
2984         def_id
2985             .as_local()
2986             .and_then(|def_id| self.hir().get(self.hir().as_local_hir_id(def_id)).ident())
2987     }
2988
2989     pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2990         let is_associated_item = if let Some(def_id) = def_id.as_local() {
2991             match self.hir().get(self.hir().as_local_hir_id(def_id)) {
2992                 Node::TraitItem(_) | Node::ImplItem(_) => true,
2993                 _ => false,
2994             }
2995         } else {
2996             match self.def_kind(def_id) {
2997                 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => true,
2998                 _ => false,
2999             }
3000         };
3001
3002         is_associated_item.then(|| self.associated_item(def_id))
3003     }
3004
3005     pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
3006         typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
3007     }
3008
3009     pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
3010         variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id))
3011     }
3012
3013     /// Returns `true` if the impls are the same polarity and the trait either
3014     /// has no items or is annotated `#[marker]` and prevents item overrides.
3015     pub fn impls_are_allowed_to_overlap(
3016         self,
3017         def_id1: DefId,
3018         def_id2: DefId,
3019     ) -> Option<ImplOverlapKind> {
3020         // If either trait impl references an error, they're allowed to overlap,
3021         // as one of them essentially doesn't exist.
3022         if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
3023             || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
3024         {
3025             return Some(ImplOverlapKind::Permitted { marker: false });
3026         }
3027
3028         match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
3029             (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
3030                 // `#[rustc_reservation_impl]` impls don't overlap with anything
3031                 debug!(
3032                     "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
3033                     def_id1, def_id2
3034                 );
3035                 return Some(ImplOverlapKind::Permitted { marker: false });
3036             }
3037             (ImplPolarity::Positive, ImplPolarity::Negative)
3038             | (ImplPolarity::Negative, ImplPolarity::Positive) => {
3039                 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
3040                 debug!(
3041                     "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
3042                     def_id1, def_id2
3043                 );
3044                 return None;
3045             }
3046             (ImplPolarity::Positive, ImplPolarity::Positive)
3047             | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
3048         };
3049
3050         let is_marker_overlap = {
3051             let is_marker_impl = |def_id: DefId| -> bool {
3052                 let trait_ref = self.impl_trait_ref(def_id);
3053                 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
3054             };
3055             is_marker_impl(def_id1) && is_marker_impl(def_id2)
3056         };
3057
3058         if is_marker_overlap {
3059             debug!(
3060                 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
3061                 def_id1, def_id2
3062             );
3063             Some(ImplOverlapKind::Permitted { marker: true })
3064         } else {
3065             if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
3066                 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
3067                     if self_ty1 == self_ty2 {
3068                         debug!(
3069                             "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
3070                             def_id1, def_id2
3071                         );
3072                         return Some(ImplOverlapKind::Issue33140);
3073                     } else {
3074                         debug!(
3075                             "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
3076                             def_id1, def_id2, self_ty1, self_ty2
3077                         );
3078                     }
3079                 }
3080             }
3081
3082             debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
3083             None
3084         }
3085     }
3086
3087     /// Returns `ty::VariantDef` if `res` refers to a struct,
3088     /// or variant or their constructors, panics otherwise.
3089     pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
3090         match res {
3091             Res::Def(DefKind::Variant, did) => {
3092                 let enum_did = self.parent(did).unwrap();
3093                 self.adt_def(enum_did).variant_with_id(did)
3094             }
3095             Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
3096             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
3097                 let variant_did = self.parent(variant_ctor_did).unwrap();
3098                 let enum_did = self.parent(variant_did).unwrap();
3099                 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
3100             }
3101             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
3102                 let struct_did = self.parent(ctor_did).expect("struct ctor has no parent");
3103                 self.adt_def(struct_did).non_enum_variant()
3104             }
3105             _ => bug!("expect_variant_res used with unexpected res {:?}", res),
3106         }
3107     }
3108
3109     pub fn item_name(self, id: DefId) -> Symbol {
3110         if id.index == CRATE_DEF_INDEX {
3111             self.original_crate_name(id.krate)
3112         } else {
3113             let def_key = self.def_key(id);
3114             match def_key.disambiguated_data.data {
3115                 // The name of a constructor is that of its parent.
3116                 rustc_hir::definitions::DefPathData::Ctor => {
3117                     self.item_name(DefId { krate: id.krate, index: def_key.parent.unwrap() })
3118                 }
3119                 _ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
3120                     bug!("item_name: no name for {:?}", self.def_path(id));
3121                 }),
3122             }
3123         }
3124     }
3125
3126     /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
3127     pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
3128         match instance {
3129             ty::InstanceDef::Item(def) => {
3130                 if let Some((did, param_did)) = def.as_const_arg() {
3131                     self.optimized_mir_of_const_arg((did, param_did))
3132                 } else {
3133                     self.optimized_mir(def.did)
3134                 }
3135             }
3136             ty::InstanceDef::VtableShim(..)
3137             | ty::InstanceDef::ReifyShim(..)
3138             | ty::InstanceDef::Intrinsic(..)
3139             | ty::InstanceDef::FnPtrShim(..)
3140             | ty::InstanceDef::Virtual(..)
3141             | ty::InstanceDef::ClosureOnceShim { .. }
3142             | ty::InstanceDef::DropGlue(..)
3143             | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
3144         }
3145     }
3146
3147     /// Gets the attributes of a definition.
3148     pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
3149         if let Some(did) = did.as_local() {
3150             self.hir().attrs(self.hir().as_local_hir_id(did))
3151         } else {
3152             self.item_attrs(did)
3153         }
3154     }
3155
3156     /// Determines whether an item is annotated with an attribute.
3157     pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
3158         attr::contains_name(&self.get_attrs(did), attr)
3159     }
3160
3161     /// Returns `true` if this is an `auto trait`.
3162     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
3163         self.trait_def(trait_def_id).has_auto_impl
3164     }
3165
3166     pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> {
3167         self.optimized_mir(def_id).generator_layout.as_ref().unwrap()
3168     }
3169
3170     /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
3171     /// If it implements no trait, returns `None`.
3172     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
3173         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
3174     }
3175
3176     /// If the given defid describes a method belonging to an impl, returns the
3177     /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
3178     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
3179         self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
3180             TraitContainer(_) => None,
3181             ImplContainer(def_id) => Some(def_id),
3182         })
3183     }
3184
3185     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
3186     /// with the name of the crate containing the impl.
3187     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
3188         if let Some(impl_did) = impl_did.as_local() {
3189             let hir_id = self.hir().as_local_hir_id(impl_did);
3190             Ok(self.hir().span(hir_id))
3191         } else {
3192             Err(self.crate_name(impl_did.krate))
3193         }
3194     }
3195
3196     /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
3197     /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
3198     /// definition's parent/scope to perform comparison.
3199     pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
3200         // We could use `Ident::eq` here, but we deliberately don't. The name
3201         // comparison fails frequently, and we want to avoid the expensive
3202         // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
3203         use_name.name == def_name.name
3204             && use_name
3205                 .span
3206                 .ctxt()
3207                 .hygienic_eq(def_name.span.ctxt(), self.expansion_that_defined(def_parent_def_id))
3208     }
3209
3210     fn expansion_that_defined(self, scope: DefId) -> ExpnId {
3211         match scope.as_local() {
3212             Some(scope) => self.hir().definitions().expansion_that_defined(scope),
3213             None => ExpnId::root(),
3214         }
3215     }
3216
3217     pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
3218         ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
3219         ident
3220     }
3221
3222     pub fn adjust_ident_and_get_scope(
3223         self,
3224         mut ident: Ident,
3225         scope: DefId,
3226         block: hir::HirId,
3227     ) -> (Ident, DefId) {
3228         let scope =
3229             match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
3230             {
3231                 Some(actual_expansion) => {
3232                     self.hir().definitions().parent_module_of_macro_def(actual_expansion)
3233                 }
3234                 None => self.parent_module(block).to_def_id(),
3235             };
3236         (ident, scope)
3237     }
3238
3239     pub fn is_object_safe(self, key: DefId) -> bool {
3240         self.object_safety_violations(key).is_empty()
3241     }
3242 }
3243
3244 #[derive(Clone, HashStable)]
3245 pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
3246
3247 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
3248 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
3249     if let Some(def_id) = def_id.as_local() {
3250         if let Node::Item(item) = tcx.hir().get(tcx.hir().as_local_hir_id(def_id)) {
3251             if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
3252                 return opaque_ty.impl_trait_fn;
3253             }
3254         }
3255     }
3256     None
3257 }
3258
3259 pub fn provide(providers: &mut ty::query::Providers) {
3260     context::provide(providers);
3261     erase_regions::provide(providers);
3262     layout::provide(providers);
3263     super::util::bug::provide(providers);
3264     *providers = ty::query::Providers {
3265         trait_impls_of: trait_def::trait_impls_of_provider,
3266         all_local_trait_impls: trait_def::all_local_trait_impls,
3267         ..*providers
3268     };
3269 }
3270
3271 /// A map for the local crate mapping each type to a vector of its
3272 /// inherent impls. This is not meant to be used outside of coherence;
3273 /// rather, you should request the vector for a specific type via
3274 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
3275 /// (constructing this map requires touching the entire crate).
3276 #[derive(Clone, Debug, Default, HashStable)]
3277 pub struct CrateInherentImpls {
3278     pub inherent_impls: DefIdMap<Vec<DefId>>,
3279 }
3280
3281 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
3282 pub struct SymbolName<'tcx> {
3283     /// `&str` gives a consistent ordering, which ensures reproducible builds.
3284     pub name: &'tcx str,
3285 }
3286
3287 impl<'tcx> SymbolName<'tcx> {
3288     pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
3289         SymbolName {
3290             name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
3291         }
3292     }
3293 }
3294
3295 impl<'tcx> fmt::Display for SymbolName<'tcx> {
3296     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3297         fmt::Display::fmt(&self.name, fmt)
3298     }
3299 }
3300
3301 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
3302     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
3303         fmt::Display::fmt(&self.name, fmt)
3304     }
3305 }
3306
3307 impl<'tcx> rustc_serialize::UseSpecializedEncodable for SymbolName<'tcx> {
3308     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
3309         s.emit_str(self.name)
3310     }
3311 }
3312
3313 // The decoding takes place in `decode_symbol_name()`.
3314 impl<'tcx> rustc_serialize::UseSpecializedDecodable for SymbolName<'tcx> {}