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