]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/mod.rs
Rollup merge of #101021 - MingyuChen1:diagnostic, r=davidtwco
[rust.git] / compiler / rustc_middle / src / ty / mod.rs
1 //! Defines how the compiler represents types internally.
2 //!
3 //! Two important entities in this module are:
4 //!
5 //! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6 //! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7 //!
8 //! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
9 //!
10 //! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12 pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
13 pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
14 pub use self::AssocItemContainer::*;
15 pub use self::BorrowKind::*;
16 pub use self::IntVarValue::*;
17 pub use self::Variance::*;
18 use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
19 use crate::metadata::ModChild;
20 use crate::middle::privacy::AccessLevels;
21 use crate::mir::{Body, GeneratorLayout};
22 use crate::traits::{self, Reveal};
23 use crate::ty;
24 use crate::ty::fast_reject::SimplifiedType;
25 use crate::ty::util::Discr;
26 pub use adt::*;
27 pub use assoc::*;
28 pub use generics::*;
29 use rustc_ast as ast;
30 use rustc_ast::node_id::NodeMap;
31 use rustc_attr as attr;
32 use rustc_data_structures::fingerprint::Fingerprint;
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
34 use rustc_data_structures::intern::{Interned, WithStableHash};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
37 use rustc_hir as hir;
38 use rustc_hir::def::{CtorKind, CtorOf, DefKind, LifetimeRes, Res};
39 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap};
40 use rustc_hir::Node;
41 use rustc_index::vec::IndexVec;
42 use rustc_macros::HashStable;
43 use rustc_query_system::ich::StableHashingContext;
44 use rustc_span::hygiene::MacroKind;
45 use rustc_span::symbol::{kw, sym, Ident, Symbol};
46 use rustc_span::{ExpnId, Span};
47 use rustc_target::abi::{Align, VariantIdx};
48 pub use subst::*;
49 pub use vtable::*;
50
51 use std::fmt::Debug;
52 use std::hash::{Hash, Hasher};
53 use std::ops::ControlFlow;
54 use std::{fmt, str};
55
56 pub use crate::ty::diagnostics::*;
57 pub use rustc_type_ir::InferTy::*;
58 pub use rustc_type_ir::RegionKind::*;
59 pub use rustc_type_ir::TyKind::*;
60 pub use rustc_type_ir::*;
61
62 pub use self::binding::BindingMode;
63 pub use self::binding::BindingMode::*;
64 pub use self::closure::{
65     is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo,
66     CapturedPlace, ClosureKind, MinCaptureInformationMap, MinCaptureList,
67     RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath,
68     CAPTURE_STRUCT_LOCAL,
69 };
70 pub use self::consts::{
71     Const, ConstInt, ConstKind, ConstS, InferConst, ScalarInt, Unevaluated, ValTree,
72 };
73 pub use self::context::{
74     tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
75     CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorDiagnosticData,
76     GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TypeckResults, UserType,
77     UserTypeAnnotationIndex,
78 };
79 pub use self::instance::{Instance, InstanceDef};
80 pub use self::list::List;
81 pub use self::parameterized::ParameterizedOverTcx;
82 pub use self::rvalue_scopes::RvalueScopes;
83 pub use self::sty::BoundRegionKind::*;
84 pub use self::sty::{
85     Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar,
86     BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid,
87     EarlyBinder, EarlyBoundRegion, ExistentialPredicate, ExistentialProjection,
88     ExistentialTraitRef, FnSig, FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts,
89     InlineConstSubsts, InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialProjection,
90     PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind,
91     RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts, VarianceDiagInfo,
92 };
93 pub use self::trait_def::TraitDef;
94
95 pub mod _match;
96 pub mod abstract_const;
97 pub mod adjustment;
98 pub mod binding;
99 pub mod cast;
100 pub mod codec;
101 pub mod error;
102 pub mod fast_reject;
103 pub mod flags;
104 pub mod fold;
105 pub mod inhabitedness;
106 pub mod layout;
107 pub mod normalize_erasing_regions;
108 pub mod print;
109 pub mod query;
110 pub mod relate;
111 pub mod subst;
112 pub mod trait_def;
113 pub mod util;
114 pub mod visit;
115 pub mod vtable;
116 pub mod walk;
117
118 mod adt;
119 mod assoc;
120 mod closure;
121 mod consts;
122 mod context;
123 mod diagnostics;
124 mod erase_regions;
125 mod generics;
126 mod impls_ty;
127 mod instance;
128 mod layout_sanity_check;
129 mod list;
130 mod parameterized;
131 mod rvalue_scopes;
132 mod structural_impls;
133 mod sty;
134
135 // Data types
136
137 pub type RegisteredTools = FxHashSet<Ident>;
138
139 #[derive(Debug)]
140 pub struct ResolverOutputs {
141     pub visibilities: FxHashMap<LocalDefId, Visibility>,
142     /// This field is used to decide whether we should make `PRIVATE_IN_PUBLIC` a hard error.
143     pub has_pub_restricted: bool,
144     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
145     pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
146     /// Reference span for definitions.
147     pub source_span: IndexVec<LocalDefId, Span>,
148     pub access_levels: AccessLevels,
149     pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
150     pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
151     pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
152     pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
153     pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
154     /// Extern prelude entries. The value is `true` if the entry was introduced
155     /// via `extern crate` item and not `--extern` option or compiler built-in.
156     pub extern_prelude: FxHashMap<Symbol, bool>,
157     pub main_def: Option<MainDefinition>,
158     pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
159     /// A list of proc macro LocalDefIds, written out in the order in which
160     /// they are declared in the static array generated by proc_macro_harness.
161     pub proc_macros: Vec<LocalDefId>,
162     /// Mapping from ident span to path span for paths that don't exist as written, but that
163     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
164     pub confused_type_with_std_module: FxHashMap<Span, Span>,
165     pub registered_tools: RegisteredTools,
166 }
167
168 /// Resolutions that should only be used for lowering.
169 /// This struct is meant to be consumed by lowering.
170 #[derive(Debug)]
171 pub struct ResolverAstLowering {
172     pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
173
174     /// Resolutions for nodes that have a single resolution.
175     pub partial_res_map: NodeMap<hir::def::PartialRes>,
176     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
177     pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
178     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
179     pub label_res_map: NodeMap<ast::NodeId>,
180     /// Resolutions for lifetimes.
181     pub lifetimes_res_map: NodeMap<LifetimeRes>,
182     /// Lifetime parameters that lowering will have to introduce.
183     pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
184
185     pub next_node_id: ast::NodeId,
186
187     pub node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
188     pub def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
189
190     pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
191     /// A small map keeping true kinds of built-in macros that appear to be fn-like on
192     /// the surface (`macro` items in libcore), but are actually attributes or derives.
193     pub builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
194 }
195
196 #[derive(Clone, Copy, Debug)]
197 pub struct MainDefinition {
198     pub res: Res<ast::NodeId>,
199     pub is_import: bool,
200     pub span: Span,
201 }
202
203 impl MainDefinition {
204     pub fn opt_fn_def_id(self) -> Option<DefId> {
205         if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
206     }
207 }
208
209 /// The "header" of an impl is everything outside the body: a Self type, a trait
210 /// ref (in the case of a trait impl), and a set of predicates (from the
211 /// bounds / where-clauses).
212 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
213 pub struct ImplHeader<'tcx> {
214     pub impl_def_id: DefId,
215     pub self_ty: Ty<'tcx>,
216     pub trait_ref: Option<TraitRef<'tcx>>,
217     pub predicates: Vec<Predicate<'tcx>>,
218 }
219
220 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
221 pub enum ImplSubject<'tcx> {
222     Trait(TraitRef<'tcx>),
223     Inherent(Ty<'tcx>),
224 }
225
226 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
227 #[derive(TypeFoldable, TypeVisitable)]
228 pub enum ImplPolarity {
229     /// `impl Trait for Type`
230     Positive,
231     /// `impl !Trait for Type`
232     Negative,
233     /// `#[rustc_reservation_impl] impl Trait for Type`
234     ///
235     /// This is a "stability hack", not a real Rust feature.
236     /// See #64631 for details.
237     Reservation,
238 }
239
240 impl ImplPolarity {
241     /// Flips polarity by turning `Positive` into `Negative` and `Negative` into `Positive`.
242     pub fn flip(&self) -> Option<ImplPolarity> {
243         match self {
244             ImplPolarity::Positive => Some(ImplPolarity::Negative),
245             ImplPolarity::Negative => Some(ImplPolarity::Positive),
246             ImplPolarity::Reservation => None,
247         }
248     }
249 }
250
251 impl fmt::Display for ImplPolarity {
252     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253         match self {
254             Self::Positive => f.write_str("positive"),
255             Self::Negative => f.write_str("negative"),
256             Self::Reservation => f.write_str("reservation"),
257         }
258     }
259 }
260
261 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
262 pub enum Visibility {
263     /// Visible everywhere (including in other crates).
264     Public,
265     /// Visible only in the given crate-local module.
266     Restricted(DefId),
267 }
268
269 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
270 pub enum BoundConstness {
271     /// `T: Trait`
272     NotConst,
273     /// `T: ~const Trait`
274     ///
275     /// Requires resolving to const only when we are in a const context.
276     ConstIfConst,
277 }
278
279 impl BoundConstness {
280     /// Reduce `self` and `constness` to two possible combined states instead of four.
281     pub fn and(&mut self, constness: hir::Constness) -> hir::Constness {
282         match (constness, self) {
283             (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const,
284             (_, this) => {
285                 *this = BoundConstness::NotConst;
286                 hir::Constness::NotConst
287             }
288         }
289     }
290 }
291
292 impl fmt::Display for BoundConstness {
293     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294         match self {
295             Self::NotConst => f.write_str("normal"),
296             Self::ConstIfConst => f.write_str("`~const`"),
297         }
298     }
299 }
300
301 #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
302 #[derive(TypeFoldable, TypeVisitable)]
303 pub struct ClosureSizeProfileData<'tcx> {
304     /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
305     pub before_feature_tys: Ty<'tcx>,
306     /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
307     pub after_feature_tys: Ty<'tcx>,
308 }
309
310 pub trait DefIdTree: Copy {
311     fn opt_parent(self, id: DefId) -> Option<DefId>;
312
313     #[inline]
314     #[track_caller]
315     fn parent(self, id: DefId) -> DefId {
316         match self.opt_parent(id) {
317             Some(id) => id,
318             // not `unwrap_or_else` to avoid breaking caller tracking
319             None => bug!("{id:?} doesn't have a parent"),
320         }
321     }
322
323     #[inline]
324     #[track_caller]
325     fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
326         self.opt_parent(id.to_def_id()).map(DefId::expect_local)
327     }
328
329     #[inline]
330     #[track_caller]
331     fn local_parent(self, id: LocalDefId) -> LocalDefId {
332         self.parent(id.to_def_id()).expect_local()
333     }
334
335     fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
336         if descendant.krate != ancestor.krate {
337             return false;
338         }
339
340         while descendant != ancestor {
341             match self.opt_parent(descendant) {
342                 Some(parent) => descendant = parent,
343                 None => return false,
344             }
345         }
346         true
347     }
348 }
349
350 impl<'tcx> DefIdTree for TyCtxt<'tcx> {
351     #[inline]
352     fn opt_parent(self, id: DefId) -> Option<DefId> {
353         self.def_key(id).parent.map(|index| DefId { index, ..id })
354     }
355 }
356
357 impl Visibility {
358     /// Returns `true` if an item with this visibility is accessible from the given block.
359     pub fn is_accessible_from<T: DefIdTree>(self, module: DefId, tree: T) -> bool {
360         let restriction = match self {
361             // Public items are visible everywhere.
362             Visibility::Public => return true,
363             // Restricted items are visible in an arbitrary local module.
364             Visibility::Restricted(other) if other.krate != module.krate => return false,
365             Visibility::Restricted(module) => module,
366         };
367
368         tree.is_descendant_of(module, restriction)
369     }
370
371     /// Returns `true` if this visibility is at least as accessible as the given visibility
372     pub fn is_at_least<T: DefIdTree>(self, vis: Visibility, tree: T) -> bool {
373         let vis_restriction = match vis {
374             Visibility::Public => return self == Visibility::Public,
375             Visibility::Restricted(module) => module,
376         };
377
378         self.is_accessible_from(vis_restriction, tree)
379     }
380
381     // Returns `true` if this item is visible anywhere in the local crate.
382     pub fn is_visible_locally(self) -> bool {
383         match self {
384             Visibility::Public => true,
385             Visibility::Restricted(def_id) => def_id.is_local(),
386         }
387     }
388
389     pub fn is_public(self) -> bool {
390         matches!(self, Visibility::Public)
391     }
392 }
393
394 /// The crate variances map is computed during typeck and contains the
395 /// variance of every item in the local crate. You should not use it
396 /// directly, because to do so will make your pass dependent on the
397 /// HIR of every item in the local crate. Instead, use
398 /// `tcx.variances_of()` to get the variance for a *particular*
399 /// item.
400 #[derive(HashStable, Debug)]
401 pub struct CrateVariancesMap<'tcx> {
402     /// For each item with generics, maps to a vector of the variance
403     /// of its generics. If an item has no generics, it will have no
404     /// entry.
405     pub variances: FxHashMap<DefId, &'tcx [ty::Variance]>,
406 }
407
408 // Contains information needed to resolve types and (in the future) look up
409 // the types of AST nodes.
410 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
411 pub struct CReaderCacheKey {
412     pub cnum: Option<CrateNum>,
413     pub pos: usize,
414 }
415
416 /// Represents a type.
417 ///
418 /// IMPORTANT:
419 /// - This is a very "dumb" struct (with no derives and no `impls`).
420 /// - Values of this type are always interned and thus unique, and are stored
421 ///   as an `Interned<TyS>`.
422 /// - `Ty` (which contains a reference to a `Interned<TyS>`) or `Interned<TyS>`
423 ///   should be used everywhere instead of `TyS`. In particular, `Ty` has most
424 ///   of the relevant methods.
425 #[derive(PartialEq, Eq, PartialOrd, Ord)]
426 #[allow(rustc::usage_of_ty_tykind)]
427 pub(crate) struct TyS<'tcx> {
428     /// This field shouldn't be used directly and may be removed in the future.
429     /// Use `Ty::kind()` instead.
430     kind: TyKind<'tcx>,
431
432     /// This field provides fast access to information that is also contained
433     /// in `kind`.
434     ///
435     /// This field shouldn't be used directly and may be removed in the future.
436     /// Use `Ty::flags()` instead.
437     flags: TypeFlags,
438
439     /// This field provides fast access to information that is also contained
440     /// in `kind`.
441     ///
442     /// This is a kind of confusing thing: it stores the smallest
443     /// binder such that
444     ///
445     /// (a) the binder itself captures nothing but
446     /// (b) all the late-bound things within the type are captured
447     ///     by some sub-binder.
448     ///
449     /// So, for a type without any late-bound things, like `u32`, this
450     /// will be *innermost*, because that is the innermost binder that
451     /// captures nothing. But for a type `&'D u32`, where `'D` is a
452     /// late-bound region with De Bruijn index `D`, this would be `D + 1`
453     /// -- the binder itself does not capture `D`, but `D` is captured
454     /// by an inner binder.
455     ///
456     /// We call this concept an "exclusive" binder `D` because all
457     /// De Bruijn indices within the type are contained within `0..D`
458     /// (exclusive).
459     outer_exclusive_binder: ty::DebruijnIndex,
460 }
461
462 // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger.
463 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
464 static_assert_size!(TyS<'_>, 40);
465
466 // We are actually storing a stable hash cache next to the type, so let's
467 // also check the full size
468 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
469 static_assert_size!(WithStableHash<TyS<'_>>, 56);
470
471 /// Use this rather than `TyS`, whenever possible.
472 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
473 #[rustc_diagnostic_item = "Ty"]
474 #[rustc_pass_by_value]
475 pub struct Ty<'tcx>(Interned<'tcx, WithStableHash<TyS<'tcx>>>);
476
477 impl<'tcx> TyCtxt<'tcx> {
478     /// A "bool" type used in rustc_mir_transform unit tests when we
479     /// have not spun up a TyCtxt.
480     pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> = Ty(Interned::new_unchecked(&WithStableHash {
481         internee: TyS {
482             kind: ty::Bool,
483             flags: TypeFlags::empty(),
484             outer_exclusive_binder: DebruijnIndex::from_usize(0),
485         },
486         stable_hash: Fingerprint::ZERO,
487     }));
488 }
489
490 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for TyS<'tcx> {
491     #[inline]
492     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
493         let TyS {
494             kind,
495
496             // The other fields just provide fast access to information that is
497             // also contained in `kind`, so no need to hash them.
498             flags: _,
499
500             outer_exclusive_binder: _,
501         } = self;
502
503         kind.hash_stable(hcx, hasher)
504     }
505 }
506
507 impl ty::EarlyBoundRegion {
508     /// Does this early bound region have a name? Early bound regions normally
509     /// always have names except when using anonymous lifetimes (`'_`).
510     pub fn has_name(&self) -> bool {
511         self.name != kw::UnderscoreLifetime
512     }
513 }
514
515 /// Represents a predicate.
516 ///
517 /// See comments on `TyS`, which apply here too (albeit for
518 /// `PredicateS`/`Predicate` rather than `TyS`/`Ty`).
519 #[derive(Debug)]
520 pub(crate) struct PredicateS<'tcx> {
521     kind: Binder<'tcx, PredicateKind<'tcx>>,
522     flags: TypeFlags,
523     /// See the comment for the corresponding field of [TyS].
524     outer_exclusive_binder: ty::DebruijnIndex,
525 }
526
527 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
528 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
529 static_assert_size!(PredicateS<'_>, 56);
530
531 /// Use this rather than `PredicateS`, whenever possible.
532 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
533 #[rustc_pass_by_value]
534 pub struct Predicate<'tcx>(Interned<'tcx, PredicateS<'tcx>>);
535
536 impl<'tcx> Predicate<'tcx> {
537     /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`.
538     #[inline]
539     pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> {
540         self.0.kind
541     }
542
543     #[inline(always)]
544     pub fn flags(self) -> TypeFlags {
545         self.0.flags
546     }
547
548     #[inline(always)]
549     pub fn outer_exclusive_binder(self) -> DebruijnIndex {
550         self.0.outer_exclusive_binder
551     }
552
553     /// Flips the polarity of a Predicate.
554     ///
555     /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`.
556     pub fn flip_polarity(self, tcx: TyCtxt<'tcx>) -> Option<Predicate<'tcx>> {
557         let kind = self
558             .kind()
559             .map_bound(|kind| match kind {
560                 PredicateKind::Trait(TraitPredicate { trait_ref, constness, polarity }) => {
561                     Some(PredicateKind::Trait(TraitPredicate {
562                         trait_ref,
563                         constness,
564                         polarity: polarity.flip()?,
565                     }))
566                 }
567
568                 _ => None,
569             })
570             .transpose()?;
571
572         Some(tcx.mk_predicate(kind))
573     }
574
575     pub fn without_const(mut self, tcx: TyCtxt<'tcx>) -> Self {
576         if let PredicateKind::Trait(TraitPredicate { trait_ref, constness, polarity }) = self.kind().skip_binder()
577             && constness != BoundConstness::NotConst
578         {
579             self = tcx.mk_predicate(self.kind().rebind(PredicateKind::Trait(TraitPredicate {
580                 trait_ref,
581                 constness: BoundConstness::NotConst,
582                 polarity,
583             })));
584         }
585         self
586     }
587
588     /// Whether this projection can be soundly normalized.
589     ///
590     /// Wf predicates must not be normalized, as normalization
591     /// can remove required bounds which would cause us to
592     /// unsoundly accept some programs. See #91068.
593     #[inline]
594     pub fn allow_normalization(self) -> bool {
595         match self.kind().skip_binder() {
596             PredicateKind::WellFormed(_) => false,
597             PredicateKind::Trait(_)
598             | PredicateKind::RegionOutlives(_)
599             | PredicateKind::TypeOutlives(_)
600             | PredicateKind::Projection(_)
601             | PredicateKind::ObjectSafe(_)
602             | PredicateKind::ClosureKind(_, _, _)
603             | PredicateKind::Subtype(_)
604             | PredicateKind::Coerce(_)
605             | PredicateKind::ConstEvaluatable(_)
606             | PredicateKind::ConstEquate(_, _)
607             | PredicateKind::TypeWellFormedFromEnv(_) => true,
608         }
609     }
610 }
611
612 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Predicate<'tcx> {
613     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
614         let PredicateS {
615             ref kind,
616
617             // The other fields just provide fast access to information that is
618             // also contained in `kind`, so no need to hash them.
619             flags: _,
620             outer_exclusive_binder: _,
621         } = self.0.0;
622
623         kind.hash_stable(hcx, hasher);
624     }
625 }
626
627 impl rustc_errors::IntoDiagnosticArg for Predicate<'_> {
628     fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
629         rustc_errors::DiagnosticArgValue::Str(std::borrow::Cow::Owned(self.to_string()))
630     }
631 }
632
633 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
634 #[derive(HashStable, TypeFoldable, TypeVisitable)]
635 pub enum PredicateKind<'tcx> {
636     /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
637     /// the `Self` type of the trait reference and `A`, `B`, and `C`
638     /// would be the type parameters.
639     Trait(TraitPredicate<'tcx>),
640
641     /// `where 'a: 'b`
642     RegionOutlives(RegionOutlivesPredicate<'tcx>),
643
644     /// `where T: 'a`
645     TypeOutlives(TypeOutlivesPredicate<'tcx>),
646
647     /// `where <T as TraitRef>::Name == X`, approximately.
648     /// See the `ProjectionPredicate` struct for details.
649     Projection(ProjectionPredicate<'tcx>),
650
651     /// No syntax: `T` well-formed.
652     WellFormed(GenericArg<'tcx>),
653
654     /// Trait must be object-safe.
655     ObjectSafe(DefId),
656
657     /// No direct syntax. May be thought of as `where T: FnFoo<...>`
658     /// for some substitutions `...` and `T` being a closure type.
659     /// Satisfied (or refuted) once we know the closure's kind.
660     ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind),
661
662     /// `T1 <: T2`
663     ///
664     /// This obligation is created most often when we have two
665     /// unresolved type variables and hence don't have enough
666     /// information to process the subtyping obligation yet.
667     Subtype(SubtypePredicate<'tcx>),
668
669     /// `T1` coerced to `T2`
670     ///
671     /// Like a subtyping obligation, this is created most often
672     /// when we have two unresolved type variables and hence
673     /// don't have enough information to process the coercion
674     /// obligation yet. At the moment, we actually process coercions
675     /// very much like subtyping and don't handle the full coercion
676     /// logic.
677     Coerce(CoercePredicate<'tcx>),
678
679     /// Constant initializer must evaluate successfully.
680     ConstEvaluatable(ty::Unevaluated<'tcx, ()>),
681
682     /// Constants must be equal. The first component is the const that is expected.
683     ConstEquate(Const<'tcx>, Const<'tcx>),
684
685     /// Represents a type found in the environment that we can use for implied bounds.
686     ///
687     /// Only used for Chalk.
688     TypeWellFormedFromEnv(Ty<'tcx>),
689 }
690
691 /// The crate outlives map is computed during typeck and contains the
692 /// outlives of every item in the local crate. You should not use it
693 /// directly, because to do so will make your pass dependent on the
694 /// HIR of every item in the local crate. Instead, use
695 /// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
696 /// item.
697 #[derive(HashStable, Debug)]
698 pub struct CratePredicatesMap<'tcx> {
699     /// For each struct with outlive bounds, maps to a vector of the
700     /// predicate of its outlive bounds. If an item has no outlives
701     /// bounds, it will have no entry.
702     pub predicates: FxHashMap<DefId, &'tcx [(Predicate<'tcx>, Span)]>,
703 }
704
705 impl<'tcx> Predicate<'tcx> {
706     /// Performs a substitution suitable for going from a
707     /// poly-trait-ref to supertraits that must hold if that
708     /// poly-trait-ref holds. This is slightly different from a normal
709     /// substitution in terms of what happens with bound regions. See
710     /// lengthy comment below for details.
711     pub fn subst_supertrait(
712         self,
713         tcx: TyCtxt<'tcx>,
714         trait_ref: &ty::PolyTraitRef<'tcx>,
715     ) -> Predicate<'tcx> {
716         // The interaction between HRTB and supertraits is not entirely
717         // obvious. Let me walk you (and myself) through an example.
718         //
719         // Let's start with an easy case. Consider two traits:
720         //
721         //     trait Foo<'a>: Bar<'a,'a> { }
722         //     trait Bar<'b,'c> { }
723         //
724         // Now, if we have a trait reference `for<'x> T: Foo<'x>`, then
725         // we can deduce that `for<'x> T: Bar<'x,'x>`. Basically, if we
726         // knew that `Foo<'x>` (for any 'x) then we also know that
727         // `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
728         // normal substitution.
729         //
730         // In terms of why this is sound, the idea is that whenever there
731         // is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
732         // holds.  So if there is an impl of `T:Foo<'a>` that applies to
733         // all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
734         // `'a`.
735         //
736         // Another example to be careful of is this:
737         //
738         //     trait Foo1<'a>: for<'b> Bar1<'a,'b> { }
739         //     trait Bar1<'b,'c> { }
740         //
741         // Here, if we have `for<'x> T: Foo1<'x>`, then what do we know?
742         // The answer is that we know `for<'x,'b> T: Bar1<'x,'b>`. The
743         // reason is similar to the previous example: any impl of
744         // `T:Foo1<'x>` must show that `for<'b> T: Bar1<'x, 'b>`.  So
745         // basically we would want to collapse the bound lifetimes from
746         // the input (`trait_ref`) and the supertraits.
747         //
748         // To achieve this in practice is fairly straightforward. Let's
749         // consider the more complicated scenario:
750         //
751         // - We start out with `for<'x> T: Foo1<'x>`. In this case, `'x`
752         //   has a De Bruijn index of 1. We want to produce `for<'x,'b> T: Bar1<'x,'b>`,
753         //   where both `'x` and `'b` would have a DB index of 1.
754         //   The substitution from the input trait-ref is therefore going to be
755         //   `'a => 'x` (where `'x` has a DB index of 1).
756         // - The supertrait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
757         //   early-bound parameter and `'b' is a late-bound parameter with a
758         //   DB index of 1.
759         // - If we replace `'a` with `'x` from the input, it too will have
760         //   a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
761         //   just as we wanted.
762         //
763         // There is only one catch. If we just apply the substitution `'a
764         // => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
765         // adjust the DB index because we substituting into a binder (it
766         // tries to be so smart...) resulting in `for<'x> for<'b>
767         // Bar1<'x,'b>` (we have no syntax for this, so use your
768         // imagination). Basically the 'x will have DB index of 2 and 'b
769         // will have DB index of 1. Not quite what we want. So we apply
770         // the substitution to the *contents* of the trait reference,
771         // rather than the trait reference itself (put another way, the
772         // substitution code expects equal binding levels in the values
773         // from the substitution and the value being substituted into, and
774         // this trick achieves that).
775
776         // Working through the second example:
777         // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0]
778         // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0]
779         // We want to end up with:
780         //     for<'x, 'b> T: Bar1<'^0.0, '^0.1>
781         // To do this:
782         // 1) We must shift all bound vars in predicate by the length
783         //    of trait ref's bound vars. So, we would end up with predicate like
784         //    Self: Bar1<'a, '^0.1>
785         // 2) We can then apply the trait substs to this, ending up with
786         //    T: Bar1<'^0.0, '^0.1>
787         // 3) Finally, to create the final bound vars, we concatenate the bound
788         //    vars of the trait ref with those of the predicate:
789         //    ['x, 'b]
790         let bound_pred = self.kind();
791         let pred_bound_vars = bound_pred.bound_vars();
792         let trait_bound_vars = trait_ref.bound_vars();
793         // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1>
794         let shifted_pred =
795             tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
796         // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
797         let new = EarlyBinder(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
798         // 3) ['x] + ['b] -> ['x, 'b]
799         let bound_vars =
800             tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars));
801         tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars))
802     }
803 }
804
805 #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
806 #[derive(HashStable, TypeFoldable, TypeVisitable)]
807 pub struct TraitPredicate<'tcx> {
808     pub trait_ref: TraitRef<'tcx>,
809
810     pub constness: BoundConstness,
811
812     /// If polarity is Positive: we are proving that the trait is implemented.
813     ///
814     /// If polarity is Negative: we are proving that a negative impl of this trait
815     /// exists. (Note that coherence also checks whether negative impls of supertraits
816     /// exist via a series of predicates.)
817     ///
818     /// If polarity is Reserved: that's a bug.
819     pub polarity: ImplPolarity,
820 }
821
822 pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>;
823
824 impl<'tcx> TraitPredicate<'tcx> {
825     pub fn remap_constness(&mut self, param_env: &mut ParamEnv<'tcx>) {
826         *param_env = param_env.with_constness(self.constness.and(param_env.constness()))
827     }
828
829     /// Remap the constness of this predicate before emitting it for diagnostics.
830     pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
831         // this is different to `remap_constness` that callees want to print this predicate
832         // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the
833         // param_env is not const because it is always satisfied in non-const contexts.
834         if let hir::Constness::NotConst = param_env.constness() {
835             self.constness = ty::BoundConstness::NotConst;
836         }
837     }
838
839     pub fn def_id(self) -> DefId {
840         self.trait_ref.def_id
841     }
842
843     pub fn self_ty(self) -> Ty<'tcx> {
844         self.trait_ref.self_ty()
845     }
846
847     #[inline]
848     pub fn is_const_if_const(self) -> bool {
849         self.constness == BoundConstness::ConstIfConst
850     }
851
852     pub fn is_constness_satisfied_by(self, constness: hir::Constness) -> bool {
853         match (self.constness, constness) {
854             (BoundConstness::NotConst, _)
855             | (BoundConstness::ConstIfConst, hir::Constness::Const) => true,
856             (BoundConstness::ConstIfConst, hir::Constness::NotConst) => false,
857         }
858     }
859 }
860
861 impl<'tcx> PolyTraitPredicate<'tcx> {
862     pub fn def_id(self) -> DefId {
863         // Ok to skip binder since trait `DefId` does not care about regions.
864         self.skip_binder().def_id()
865     }
866
867     pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> {
868         self.map_bound(|trait_ref| trait_ref.self_ty())
869     }
870
871     /// Remap the constness of this predicate before emitting it for diagnostics.
872     pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) {
873         *self = self.map_bound(|mut p| {
874             p.remap_constness_diag(param_env);
875             p
876         });
877     }
878
879     #[inline]
880     pub fn is_const_if_const(self) -> bool {
881         self.skip_binder().is_const_if_const()
882     }
883 }
884
885 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
886 #[derive(HashStable, TypeFoldable, TypeVisitable)]
887 pub struct OutlivesPredicate<A, B>(pub A, pub B); // `A: B`
888 pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>;
889 pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>;
890 pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>;
891 pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>;
892
893 /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates
894 /// whether the `a` type is the type that we should label as "expected" when
895 /// presenting user diagnostics.
896 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
897 #[derive(HashStable, TypeFoldable, TypeVisitable)]
898 pub struct SubtypePredicate<'tcx> {
899     pub a_is_expected: bool,
900     pub a: Ty<'tcx>,
901     pub b: Ty<'tcx>,
902 }
903 pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>;
904
905 /// Encodes that we have to coerce *from* the `a` type to the `b` type.
906 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
907 #[derive(HashStable, TypeFoldable, TypeVisitable)]
908 pub struct CoercePredicate<'tcx> {
909     pub a: Ty<'tcx>,
910     pub b: Ty<'tcx>,
911 }
912 pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>;
913
914 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)]
915 #[derive(HashStable, TypeFoldable, TypeVisitable)]
916 pub enum Term<'tcx> {
917     Ty(Ty<'tcx>),
918     Const(Const<'tcx>),
919 }
920
921 impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
922     fn from(ty: Ty<'tcx>) -> Self {
923         Term::Ty(ty)
924     }
925 }
926
927 impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
928     fn from(c: Const<'tcx>) -> Self {
929         Term::Const(c)
930     }
931 }
932
933 impl<'tcx> Term<'tcx> {
934     pub fn ty(&self) -> Option<Ty<'tcx>> {
935         if let Term::Ty(ty) = self { Some(*ty) } else { None }
936     }
937
938     pub fn ct(&self) -> Option<Const<'tcx>> {
939         if let Term::Const(c) = self { Some(*c) } else { None }
940     }
941
942     pub fn into_arg(self) -> GenericArg<'tcx> {
943         match self {
944             Term::Ty(ty) => ty.into(),
945             Term::Const(c) => c.into(),
946         }
947     }
948 }
949
950 /// This kind of predicate has no *direct* correspondent in the
951 /// syntax, but it roughly corresponds to the syntactic forms:
952 ///
953 /// 1. `T: TraitRef<..., Item = Type>`
954 /// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
955 ///
956 /// In particular, form #1 is "desugared" to the combination of a
957 /// normal trait predicate (`T: TraitRef<...>`) and one of these
958 /// predicates. Form #2 is a broader form in that it also permits
959 /// equality between arbitrary types. Processing an instance of
960 /// Form #2 eventually yields one of these `ProjectionPredicate`
961 /// instances to normalize the LHS.
962 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
963 #[derive(HashStable, TypeFoldable, TypeVisitable)]
964 pub struct ProjectionPredicate<'tcx> {
965     pub projection_ty: ProjectionTy<'tcx>,
966     pub term: Term<'tcx>,
967 }
968
969 pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>;
970
971 impl<'tcx> PolyProjectionPredicate<'tcx> {
972     /// Returns the `DefId` of the trait of the associated item being projected.
973     #[inline]
974     pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
975         self.skip_binder().projection_ty.trait_def_id(tcx)
976     }
977
978     /// Get the [PolyTraitRef] required for this projection to be well formed.
979     /// Note that for generic associated types the predicates of the associated
980     /// type also need to be checked.
981     #[inline]
982     pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
983         // Note: unlike with `TraitRef::to_poly_trait_ref()`,
984         // `self.0.trait_ref` is permitted to have escaping regions.
985         // This is because here `self` has a `Binder` and so does our
986         // return value, so we are preserving the number of binding
987         // levels.
988         self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
989     }
990
991     pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
992         self.map_bound(|predicate| predicate.term)
993     }
994
995     /// The `DefId` of the `TraitItem` for the associated type.
996     ///
997     /// Note that this is not the `DefId` of the `TraitRef` containing this
998     /// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
999     pub fn projection_def_id(&self) -> DefId {
1000         // Ok to skip binder since trait `DefId` does not care about regions.
1001         self.skip_binder().projection_ty.item_def_id
1002     }
1003 }
1004
1005 pub trait ToPolyTraitRef<'tcx> {
1006     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
1007 }
1008
1009 impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
1010     fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
1011         self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
1012     }
1013 }
1014
1015 pub trait ToPredicate<'tcx> {
1016     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>;
1017 }
1018
1019 impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> {
1020     #[inline(always)]
1021     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1022         tcx.mk_predicate(self)
1023     }
1024 }
1025
1026 impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> {
1027     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1028         self.map_bound(PredicateKind::Trait).to_predicate(tcx)
1029     }
1030 }
1031
1032 impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
1033     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1034         self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx)
1035     }
1036 }
1037
1038 impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
1039     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1040         self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx)
1041     }
1042 }
1043
1044 impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
1045     fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> {
1046         self.map_bound(PredicateKind::Projection).to_predicate(tcx)
1047     }
1048 }
1049
1050 impl<'tcx> Predicate<'tcx> {
1051     pub fn to_opt_poly_trait_pred(self) -> Option<PolyTraitPredicate<'tcx>> {
1052         let predicate = self.kind();
1053         match predicate.skip_binder() {
1054             PredicateKind::Trait(t) => Some(predicate.rebind(t)),
1055             PredicateKind::Projection(..)
1056             | PredicateKind::Subtype(..)
1057             | PredicateKind::Coerce(..)
1058             | PredicateKind::RegionOutlives(..)
1059             | PredicateKind::WellFormed(..)
1060             | PredicateKind::ObjectSafe(..)
1061             | PredicateKind::ClosureKind(..)
1062             | PredicateKind::TypeOutlives(..)
1063             | PredicateKind::ConstEvaluatable(..)
1064             | PredicateKind::ConstEquate(..)
1065             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1066         }
1067     }
1068
1069     pub fn to_opt_poly_projection_pred(self) -> Option<PolyProjectionPredicate<'tcx>> {
1070         let predicate = self.kind();
1071         match predicate.skip_binder() {
1072             PredicateKind::Projection(t) => Some(predicate.rebind(t)),
1073             PredicateKind::Trait(..)
1074             | PredicateKind::Subtype(..)
1075             | PredicateKind::Coerce(..)
1076             | PredicateKind::RegionOutlives(..)
1077             | PredicateKind::WellFormed(..)
1078             | PredicateKind::ObjectSafe(..)
1079             | PredicateKind::ClosureKind(..)
1080             | PredicateKind::TypeOutlives(..)
1081             | PredicateKind::ConstEvaluatable(..)
1082             | PredicateKind::ConstEquate(..)
1083             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1084         }
1085     }
1086
1087     pub fn to_opt_type_outlives(self) -> Option<PolyTypeOutlivesPredicate<'tcx>> {
1088         let predicate = self.kind();
1089         match predicate.skip_binder() {
1090             PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)),
1091             PredicateKind::Trait(..)
1092             | PredicateKind::Projection(..)
1093             | PredicateKind::Subtype(..)
1094             | PredicateKind::Coerce(..)
1095             | PredicateKind::RegionOutlives(..)
1096             | PredicateKind::WellFormed(..)
1097             | PredicateKind::ObjectSafe(..)
1098             | PredicateKind::ClosureKind(..)
1099             | PredicateKind::ConstEvaluatable(..)
1100             | PredicateKind::ConstEquate(..)
1101             | PredicateKind::TypeWellFormedFromEnv(..) => None,
1102         }
1103     }
1104 }
1105
1106 /// Represents the bounds declared on a particular set of type
1107 /// parameters. Should eventually be generalized into a flag list of
1108 /// where-clauses. You can obtain an `InstantiatedPredicates` list from a
1109 /// `GenericPredicates` by using the `instantiate` method. Note that this method
1110 /// reflects an important semantic invariant of `InstantiatedPredicates`: while
1111 /// the `GenericPredicates` are expressed in terms of the bound type
1112 /// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
1113 /// represented a set of bounds for some particular instantiation,
1114 /// meaning that the generic parameters have been substituted with
1115 /// their values.
1116 ///
1117 /// Example:
1118 /// ```ignore (illustrative)
1119 /// struct Foo<T, U: Bar<T>> { ... }
1120 /// ```
1121 /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
1122 /// `[[], [U:Bar<T>]]`. Now if there were some particular reference
1123 /// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
1124 /// [usize:Bar<isize>]]`.
1125 #[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
1126 pub struct InstantiatedPredicates<'tcx> {
1127     pub predicates: Vec<Predicate<'tcx>>,
1128     pub spans: Vec<Span>,
1129 }
1130
1131 impl<'tcx> InstantiatedPredicates<'tcx> {
1132     pub fn empty() -> InstantiatedPredicates<'tcx> {
1133         InstantiatedPredicates { predicates: vec![], spans: vec![] }
1134     }
1135
1136     pub fn is_empty(&self) -> bool {
1137         self.predicates.is_empty()
1138     }
1139 }
1140
1141 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable, Lift)]
1142 #[derive(TypeFoldable, TypeVisitable)]
1143 pub struct OpaqueTypeKey<'tcx> {
1144     pub def_id: LocalDefId,
1145     pub substs: SubstsRef<'tcx>,
1146 }
1147
1148 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
1149 pub struct OpaqueHiddenType<'tcx> {
1150     /// The span of this particular definition of the opaque type. So
1151     /// for example:
1152     ///
1153     /// ```ignore (incomplete snippet)
1154     /// type Foo = impl Baz;
1155     /// fn bar() -> Foo {
1156     /// //          ^^^ This is the span we are looking for!
1157     /// }
1158     /// ```
1159     ///
1160     /// In cases where the fn returns `(impl Trait, impl Trait)` or
1161     /// other such combinations, the result is currently
1162     /// over-approximated, but better than nothing.
1163     pub span: Span,
1164
1165     /// The type variable that represents the value of the opaque type
1166     /// that we require. In other words, after we compile this function,
1167     /// we will be created a constraint like:
1168     /// ```ignore (pseudo-rust)
1169     /// Foo<'a, T> = ?C
1170     /// ```
1171     /// where `?C` is the value of this type variable. =) It may
1172     /// naturally refer to the type and lifetime parameters in scope
1173     /// in this function, though ultimately it should only reference
1174     /// those that are arguments to `Foo` in the constraint above. (In
1175     /// other words, `?C` should not include `'b`, even though it's a
1176     /// lifetime parameter on `foo`.)
1177     pub ty: Ty<'tcx>,
1178 }
1179
1180 impl<'tcx> OpaqueHiddenType<'tcx> {
1181     pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1182         // Found different concrete types for the opaque type.
1183         let sub_diag = if self.span == other.span {
1184             TypeMismatchReason::ConflictType { span: self.span }
1185         } else {
1186             TypeMismatchReason::PreviousUse { span: self.span }
1187         };
1188         tcx.sess.emit_err(OpaqueHiddenTypeMismatch {
1189             self_ty: self.ty,
1190             other_ty: other.ty,
1191             other_span: other.span,
1192             sub: sub_diag,
1193         });
1194     }
1195 }
1196
1197 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1198 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1199 /// regions/types/consts within the same universe simply have an unknown relationship to one
1200 /// another.
1201 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1202 #[derive(HashStable, TyEncodable, TyDecodable)]
1203 pub struct Placeholder<T> {
1204     pub universe: UniverseIndex,
1205     pub name: T,
1206 }
1207
1208 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1209
1210 pub type PlaceholderType = Placeholder<BoundVar>;
1211
1212 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1213 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1214 pub struct BoundConst<'tcx> {
1215     pub var: BoundVar,
1216     pub ty: Ty<'tcx>,
1217 }
1218
1219 pub type PlaceholderConst<'tcx> = Placeholder<BoundVar>;
1220
1221 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1222 /// the `DefId` of the generic parameter it instantiates.
1223 ///
1224 /// This is used to avoid calls to `type_of` for const arguments during typeck
1225 /// which cause cycle errors.
1226 ///
1227 /// ```rust
1228 /// struct A;
1229 /// impl A {
1230 ///     fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1231 ///     //           ^ const parameter
1232 /// }
1233 /// struct B;
1234 /// impl B {
1235 ///     fn foo<const M: u8>(&self) -> usize { 42 }
1236 ///     //           ^ const parameter
1237 /// }
1238 ///
1239 /// fn main() {
1240 ///     let a = A;
1241 ///     let _b = a.foo::<{ 3 + 7 }>();
1242 ///     //               ^^^^^^^^^ const argument
1243 /// }
1244 /// ```
1245 ///
1246 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1247 /// which `foo` is used until we know the type of `a`.
1248 ///
1249 /// We only know the type of `a` once we are inside of `typeck(main)`.
1250 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1251 /// requires us to evaluate the const argument.
1252 ///
1253 /// To evaluate that const argument we need to know its type,
1254 /// which we would get using `type_of(const_arg)`. This requires us to
1255 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1256 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1257 /// which results in a cycle.
1258 ///
1259 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1260 ///
1261 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1262 /// already resolved `foo` so we know which const parameter this argument instantiates.
1263 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1264 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1265 /// trivial to compute.
1266 ///
1267 /// If we now want to use that constant in a place which potentially needs its type
1268 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1269 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1270 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1271 /// to get the type of `did`.
1272 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift, TyEncodable, TyDecodable)]
1273 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1274 #[derive(Hash, HashStable)]
1275 pub struct WithOptConstParam<T> {
1276     pub did: T,
1277     /// The `DefId` of the corresponding generic parameter in case `did` is
1278     /// a const argument.
1279     ///
1280     /// Note that even if `did` is a const argument, this may still be `None`.
1281     /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1282     /// to potentially update `param_did` in the case it is `None`.
1283     pub const_param_did: Option<DefId>,
1284 }
1285
1286 impl<T> WithOptConstParam<T> {
1287     /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1288     #[inline(always)]
1289     pub fn unknown(did: T) -> WithOptConstParam<T> {
1290         WithOptConstParam { did, const_param_did: None }
1291     }
1292 }
1293
1294 impl WithOptConstParam<LocalDefId> {
1295     /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1296     /// `None` otherwise.
1297     #[inline(always)]
1298     pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1299         tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1300     }
1301
1302     /// In case `self` is unknown but `self.did` is a const argument, this returns
1303     /// a `WithOptConstParam` with the correct `const_param_did`.
1304     #[inline(always)]
1305     pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1306         if self.const_param_did.is_none() {
1307             if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1308                 return Some(WithOptConstParam { did: self.did, const_param_did });
1309             }
1310         }
1311
1312         None
1313     }
1314
1315     pub fn to_global(self) -> WithOptConstParam<DefId> {
1316         WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1317     }
1318
1319     pub fn def_id_for_type_of(self) -> DefId {
1320         if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1321     }
1322 }
1323
1324 impl WithOptConstParam<DefId> {
1325     pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1326         self.did
1327             .as_local()
1328             .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1329     }
1330
1331     pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1332         if let Some(param_did) = self.const_param_did {
1333             if let Some(did) = self.did.as_local() {
1334                 return Some((did, param_did));
1335             }
1336         }
1337
1338         None
1339     }
1340
1341     pub fn is_local(self) -> bool {
1342         self.did.is_local()
1343     }
1344
1345     pub fn def_id_for_type_of(self) -> DefId {
1346         self.const_param_did.unwrap_or(self.did)
1347     }
1348 }
1349
1350 /// When type checking, we use the `ParamEnv` to track
1351 /// details about the set of where-clauses that are in scope at this
1352 /// particular point.
1353 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1354 pub struct ParamEnv<'tcx> {
1355     /// This packs both caller bounds and the reveal enum into one pointer.
1356     ///
1357     /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1358     /// basically the set of bounds on the in-scope type parameters, translated
1359     /// into `Obligation`s, and elaborated and normalized.
1360     ///
1361     /// Use the `caller_bounds()` method to access.
1362     ///
1363     /// Typically, this is `Reveal::UserFacing`, but during codegen we
1364     /// want `Reveal::All`.
1365     ///
1366     /// Note: This is packed, use the reveal() method to access it.
1367     packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1368 }
1369
1370 #[derive(Copy, Clone)]
1371 struct ParamTag {
1372     reveal: traits::Reveal,
1373     constness: hir::Constness,
1374 }
1375
1376 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1377     const BITS: usize = 2;
1378     #[inline]
1379     fn into_usize(self) -> usize {
1380         match self {
1381             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1382             Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1383             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1384             Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1385         }
1386     }
1387     #[inline]
1388     unsafe fn from_usize(ptr: usize) -> Self {
1389         match ptr {
1390             0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1391             1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1392             2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1393             3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1394             _ => std::hint::unreachable_unchecked(),
1395         }
1396     }
1397 }
1398
1399 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1400     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1401         f.debug_struct("ParamEnv")
1402             .field("caller_bounds", &self.caller_bounds())
1403             .field("reveal", &self.reveal())
1404             .field("constness", &self.constness())
1405             .finish()
1406     }
1407 }
1408
1409 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1410     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1411         self.caller_bounds().hash_stable(hcx, hasher);
1412         self.reveal().hash_stable(hcx, hasher);
1413         self.constness().hash_stable(hcx, hasher);
1414     }
1415 }
1416
1417 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1418     fn try_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1419         self,
1420         folder: &mut F,
1421     ) -> Result<Self, F::Error> {
1422         Ok(ParamEnv::new(
1423             self.caller_bounds().try_fold_with(folder)?,
1424             self.reveal().try_fold_with(folder)?,
1425             self.constness().try_fold_with(folder)?,
1426         ))
1427     }
1428 }
1429
1430 impl<'tcx> TypeVisitable<'tcx> for ParamEnv<'tcx> {
1431     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1432         self.caller_bounds().visit_with(visitor)?;
1433         self.reveal().visit_with(visitor)?;
1434         self.constness().visit_with(visitor)
1435     }
1436 }
1437
1438 impl<'tcx> ParamEnv<'tcx> {
1439     /// Construct a trait environment suitable for contexts where
1440     /// there are no where-clauses in scope. Hidden types (like `impl
1441     /// Trait`) are left hidden, so this is suitable for ordinary
1442     /// type-checking.
1443     #[inline]
1444     pub fn empty() -> Self {
1445         Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1446     }
1447
1448     #[inline]
1449     pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1450         self.packed.pointer()
1451     }
1452
1453     #[inline]
1454     pub fn reveal(self) -> traits::Reveal {
1455         self.packed.tag().reveal
1456     }
1457
1458     #[inline]
1459     pub fn constness(self) -> hir::Constness {
1460         self.packed.tag().constness
1461     }
1462
1463     #[inline]
1464     pub fn is_const(self) -> bool {
1465         self.packed.tag().constness == hir::Constness::Const
1466     }
1467
1468     /// Construct a trait environment with no where-clauses in scope
1469     /// where the values of all `impl Trait` and other hidden types
1470     /// are revealed. This is suitable for monomorphized, post-typeck
1471     /// environments like codegen or doing optimizations.
1472     ///
1473     /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1474     /// or invoke `param_env.with_reveal_all()`.
1475     #[inline]
1476     pub fn reveal_all() -> Self {
1477         Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1478     }
1479
1480     /// Construct a trait environment with the given set of predicates.
1481     #[inline]
1482     pub fn new(
1483         caller_bounds: &'tcx List<Predicate<'tcx>>,
1484         reveal: Reveal,
1485         constness: hir::Constness,
1486     ) -> Self {
1487         ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1488     }
1489
1490     pub fn with_user_facing(mut self) -> Self {
1491         self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1492         self
1493     }
1494
1495     #[inline]
1496     pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1497         self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1498         self
1499     }
1500
1501     #[inline]
1502     pub fn with_const(mut self) -> Self {
1503         self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1504         self
1505     }
1506
1507     #[inline]
1508     pub fn without_const(mut self) -> Self {
1509         self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1510         self
1511     }
1512
1513     #[inline]
1514     pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1515         *self = self.with_constness(constness.and(self.constness()))
1516     }
1517
1518     /// Returns a new parameter environment with the same clauses, but
1519     /// which "reveals" the true results of projections in all cases
1520     /// (even for associated types that are specializable). This is
1521     /// the desired behavior during codegen and certain other special
1522     /// contexts; normally though we want to use `Reveal::UserFacing`,
1523     /// which is the default.
1524     /// All opaque types in the caller_bounds of the `ParamEnv`
1525     /// will be normalized to their underlying types.
1526     /// See PR #65989 and issue #65918 for more details
1527     pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1528         if self.packed.tag().reveal == traits::Reveal::All {
1529             return self;
1530         }
1531
1532         ParamEnv::new(
1533             tcx.normalize_opaque_types(self.caller_bounds()),
1534             Reveal::All,
1535             self.constness(),
1536         )
1537     }
1538
1539     /// Returns this same environment but with no caller bounds.
1540     #[inline]
1541     pub fn without_caller_bounds(self) -> Self {
1542         Self::new(List::empty(), self.reveal(), self.constness())
1543     }
1544
1545     /// Creates a suitable environment in which to perform trait
1546     /// queries on the given value. When type-checking, this is simply
1547     /// the pair of the environment plus value. But when reveal is set to
1548     /// All, then if `value` does not reference any type parameters, we will
1549     /// pair it with the empty environment. This improves caching and is generally
1550     /// invisible.
1551     ///
1552     /// N.B., we preserve the environment when type-checking because it
1553     /// is possible for the user to have wacky where-clauses like
1554     /// `where Box<u32>: Copy`, which are clearly never
1555     /// satisfiable. We generally want to behave as if they were true,
1556     /// although the surrounding function is never reachable.
1557     pub fn and<T: TypeVisitable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1558         match self.reveal() {
1559             Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1560
1561             Reveal::All => {
1562                 if value.is_global() {
1563                     ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1564                 } else {
1565                     ParamEnvAnd { param_env: self, value }
1566                 }
1567             }
1568         }
1569     }
1570 }
1571
1572 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1573 // the constness of trait bounds is being propagated correctly.
1574 impl<'tcx> PolyTraitRef<'tcx> {
1575     #[inline]
1576     pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1577         self.map_bound(|trait_ref| ty::TraitPredicate {
1578             trait_ref,
1579             constness,
1580             polarity: ty::ImplPolarity::Positive,
1581         })
1582     }
1583
1584     #[inline]
1585     pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1586         self.with_constness(BoundConstness::NotConst)
1587     }
1588 }
1589
1590 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1591 #[derive(HashStable)]
1592 pub struct ParamEnvAnd<'tcx, T> {
1593     pub param_env: ParamEnv<'tcx>,
1594     pub value: T,
1595 }
1596
1597 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1598     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1599         (self.param_env, self.value)
1600     }
1601
1602     #[inline]
1603     pub fn without_const(mut self) -> Self {
1604         self.param_env = self.param_env.without_const();
1605         self
1606     }
1607 }
1608
1609 #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1610 pub struct Destructor {
1611     /// The `DefId` of the destructor method
1612     pub did: DefId,
1613     /// The constness of the destructor method
1614     pub constness: hir::Constness,
1615 }
1616
1617 bitflags! {
1618     #[derive(HashStable, TyEncodable, TyDecodable)]
1619     pub struct VariantFlags: u32 {
1620         const NO_VARIANT_FLAGS        = 0;
1621         /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1622         const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1623         /// Indicates whether this variant was obtained as part of recovering from
1624         /// a syntactic error. May be incomplete or bogus.
1625         const IS_RECOVERED = 1 << 1;
1626     }
1627 }
1628
1629 /// Definition of a variant -- a struct's fields or an enum variant.
1630 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1631 pub struct VariantDef {
1632     /// `DefId` that identifies the variant itself.
1633     /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1634     pub def_id: DefId,
1635     /// `DefId` that identifies the variant's constructor.
1636     /// If this variant is a struct variant, then this is `None`.
1637     pub ctor_def_id: Option<DefId>,
1638     /// Variant or struct name.
1639     pub name: Symbol,
1640     /// Discriminant of this variant.
1641     pub discr: VariantDiscr,
1642     /// Fields of this variant.
1643     pub fields: Vec<FieldDef>,
1644     /// Type of constructor of variant.
1645     pub ctor_kind: CtorKind,
1646     /// Flags of the variant (e.g. is field list non-exhaustive)?
1647     flags: VariantFlags,
1648 }
1649
1650 impl VariantDef {
1651     /// Creates a new `VariantDef`.
1652     ///
1653     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1654     /// represents an enum variant).
1655     ///
1656     /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1657     /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1658     ///
1659     /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1660     /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1661     /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1662     /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1663     /// built-in trait), and we do not want to load attributes twice.
1664     ///
1665     /// If someone speeds up attribute loading to not be a performance concern, they can
1666     /// remove this hack and use the constructor `DefId` everywhere.
1667     pub fn new(
1668         name: Symbol,
1669         variant_did: Option<DefId>,
1670         ctor_def_id: Option<DefId>,
1671         discr: VariantDiscr,
1672         fields: Vec<FieldDef>,
1673         ctor_kind: CtorKind,
1674         adt_kind: AdtKind,
1675         parent_did: DefId,
1676         recovered: bool,
1677         is_field_list_non_exhaustive: bool,
1678     ) -> Self {
1679         debug!(
1680             "VariantDef::new(name = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?},
1681              fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})",
1682             name, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did,
1683         );
1684
1685         let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1686         if is_field_list_non_exhaustive {
1687             flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1688         }
1689
1690         if recovered {
1691             flags |= VariantFlags::IS_RECOVERED;
1692         }
1693
1694         VariantDef {
1695             def_id: variant_did.unwrap_or(parent_did),
1696             ctor_def_id,
1697             name,
1698             discr,
1699             fields,
1700             ctor_kind,
1701             flags,
1702         }
1703     }
1704
1705     /// Is this field list non-exhaustive?
1706     #[inline]
1707     pub fn is_field_list_non_exhaustive(&self) -> bool {
1708         self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1709     }
1710
1711     /// Was this variant obtained as part of recovering from a syntactic error?
1712     #[inline]
1713     pub fn is_recovered(&self) -> bool {
1714         self.flags.intersects(VariantFlags::IS_RECOVERED)
1715     }
1716
1717     /// Computes the `Ident` of this variant by looking up the `Span`
1718     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1719         Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1720     }
1721 }
1722
1723 impl PartialEq for VariantDef {
1724     #[inline]
1725     fn eq(&self, other: &Self) -> bool {
1726         // There should be only one `VariantDef` for each `def_id`, therefore
1727         // it is fine to implement `PartialEq` only based on `def_id`.
1728         //
1729         // Below, we exhaustively destructure `self` and `other` so that if the
1730         // definition of `VariantDef` changes, a compile-error will be produced,
1731         // reminding us to revisit this assumption.
1732
1733         let Self {
1734             def_id: lhs_def_id,
1735             ctor_def_id: _,
1736             name: _,
1737             discr: _,
1738             fields: _,
1739             ctor_kind: _,
1740             flags: _,
1741         } = &self;
1742
1743         let Self {
1744             def_id: rhs_def_id,
1745             ctor_def_id: _,
1746             name: _,
1747             discr: _,
1748             fields: _,
1749             ctor_kind: _,
1750             flags: _,
1751         } = other;
1752
1753         lhs_def_id == rhs_def_id
1754     }
1755 }
1756
1757 impl Eq for VariantDef {}
1758
1759 impl Hash for VariantDef {
1760     #[inline]
1761     fn hash<H: Hasher>(&self, s: &mut H) {
1762         // There should be only one `VariantDef` for each `def_id`, therefore
1763         // it is fine to implement `Hash` only based on `def_id`.
1764         //
1765         // Below, we exhaustively destructure `self` so that if the definition
1766         // of `VariantDef` changes, a compile-error will be produced, reminding
1767         // us to revisit this assumption.
1768
1769         let Self { def_id, ctor_def_id: _, name: _, discr: _, fields: _, ctor_kind: _, flags: _ } =
1770             &self;
1771
1772         def_id.hash(s)
1773     }
1774 }
1775
1776 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1777 pub enum VariantDiscr {
1778     /// Explicit value for this variant, i.e., `X = 123`.
1779     /// The `DefId` corresponds to the embedded constant.
1780     Explicit(DefId),
1781
1782     /// The previous variant's discriminant plus one.
1783     /// For efficiency reasons, the distance from the
1784     /// last `Explicit` discriminant is being stored,
1785     /// or `0` for the first variant, if it has none.
1786     Relative(u32),
1787 }
1788
1789 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1790 pub struct FieldDef {
1791     pub did: DefId,
1792     pub name: Symbol,
1793     pub vis: Visibility,
1794 }
1795
1796 impl PartialEq for FieldDef {
1797     #[inline]
1798     fn eq(&self, other: &Self) -> bool {
1799         // There should be only one `FieldDef` for each `did`, therefore it is
1800         // fine to implement `PartialEq` only based on `did`.
1801         //
1802         // Below, we exhaustively destructure `self` so that if the definition
1803         // of `FieldDef` changes, a compile-error will be produced, reminding
1804         // us to revisit this assumption.
1805
1806         let Self { did: lhs_did, name: _, vis: _ } = &self;
1807
1808         let Self { did: rhs_did, name: _, vis: _ } = other;
1809
1810         lhs_did == rhs_did
1811     }
1812 }
1813
1814 impl Eq for FieldDef {}
1815
1816 impl Hash for FieldDef {
1817     #[inline]
1818     fn hash<H: Hasher>(&self, s: &mut H) {
1819         // There should be only one `FieldDef` for each `did`, therefore it is
1820         // fine to implement `Hash` only based on `did`.
1821         //
1822         // Below, we exhaustively destructure `self` so that if the definition
1823         // of `FieldDef` changes, a compile-error will be produced, reminding
1824         // us to revisit this assumption.
1825
1826         let Self { did, name: _, vis: _ } = &self;
1827
1828         did.hash(s)
1829     }
1830 }
1831
1832 bitflags! {
1833     #[derive(TyEncodable, TyDecodable, Default, HashStable)]
1834     pub struct ReprFlags: u8 {
1835         const IS_C               = 1 << 0;
1836         const IS_SIMD            = 1 << 1;
1837         const IS_TRANSPARENT     = 1 << 2;
1838         // Internal only for now. If true, don't reorder fields.
1839         const IS_LINEAR          = 1 << 3;
1840         // If true, the type's layout can be randomized using
1841         // the seed stored in `ReprOptions.layout_seed`
1842         const RANDOMIZE_LAYOUT   = 1 << 4;
1843         // Any of these flags being set prevent field reordering optimisation.
1844         const IS_UNOPTIMISABLE   = ReprFlags::IS_C.bits
1845                                  | ReprFlags::IS_SIMD.bits
1846                                  | ReprFlags::IS_LINEAR.bits;
1847     }
1848 }
1849
1850 /// Represents the repr options provided by the user,
1851 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)]
1852 pub struct ReprOptions {
1853     pub int: Option<attr::IntType>,
1854     pub align: Option<Align>,
1855     pub pack: Option<Align>,
1856     pub flags: ReprFlags,
1857     /// The seed to be used for randomizing a type's layout
1858     ///
1859     /// Note: This could technically be a `[u8; 16]` (a `u128`) which would
1860     /// be the "most accurate" hash as it'd encompass the item and crate
1861     /// hash without loss, but it does pay the price of being larger.
1862     /// Everything's a tradeoff, a `u64` seed should be sufficient for our
1863     /// purposes (primarily `-Z randomize-layout`)
1864     pub field_shuffle_seed: u64,
1865 }
1866
1867 impl ReprOptions {
1868     pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions {
1869         let mut flags = ReprFlags::empty();
1870         let mut size = None;
1871         let mut max_align: Option<Align> = None;
1872         let mut min_pack: Option<Align> = None;
1873
1874         // Generate a deterministically-derived seed from the item's path hash
1875         // to allow for cross-crate compilation to actually work
1876         let mut field_shuffle_seed = tcx.def_path_hash(did).0.to_smaller_hash();
1877
1878         // If the user defined a custom seed for layout randomization, xor the item's
1879         // path hash with the user defined seed, this will allowing determinism while
1880         // still allowing users to further randomize layout generation for e.g. fuzzing
1881         if let Some(user_seed) = tcx.sess.opts.unstable_opts.layout_seed {
1882             field_shuffle_seed ^= user_seed;
1883         }
1884
1885         for attr in tcx.get_attrs(did, sym::repr) {
1886             for r in attr::parse_repr_attr(&tcx.sess, attr) {
1887                 flags.insert(match r {
1888                     attr::ReprC => ReprFlags::IS_C,
1889                     attr::ReprPacked(pack) => {
1890                         let pack = Align::from_bytes(pack as u64).unwrap();
1891                         min_pack = Some(if let Some(min_pack) = min_pack {
1892                             min_pack.min(pack)
1893                         } else {
1894                             pack
1895                         });
1896                         ReprFlags::empty()
1897                     }
1898                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1899                     attr::ReprSimd => ReprFlags::IS_SIMD,
1900                     attr::ReprInt(i) => {
1901                         size = Some(i);
1902                         ReprFlags::empty()
1903                     }
1904                     attr::ReprAlign(align) => {
1905                         max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
1906                         ReprFlags::empty()
1907                     }
1908                 });
1909             }
1910         }
1911
1912         // If `-Z randomize-layout` was enabled for the type definition then we can
1913         // consider performing layout randomization
1914         if tcx.sess.opts.unstable_opts.randomize_layout {
1915             flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1916         }
1917
1918         // This is here instead of layout because the choice must make it into metadata.
1919         if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) {
1920             flags.insert(ReprFlags::IS_LINEAR);
1921         }
1922
1923         Self { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1924     }
1925
1926     #[inline]
1927     pub fn simd(&self) -> bool {
1928         self.flags.contains(ReprFlags::IS_SIMD)
1929     }
1930
1931     #[inline]
1932     pub fn c(&self) -> bool {
1933         self.flags.contains(ReprFlags::IS_C)
1934     }
1935
1936     #[inline]
1937     pub fn packed(&self) -> bool {
1938         self.pack.is_some()
1939     }
1940
1941     #[inline]
1942     pub fn transparent(&self) -> bool {
1943         self.flags.contains(ReprFlags::IS_TRANSPARENT)
1944     }
1945
1946     #[inline]
1947     pub fn linear(&self) -> bool {
1948         self.flags.contains(ReprFlags::IS_LINEAR)
1949     }
1950
1951     /// Returns the discriminant type, given these `repr` options.
1952     /// This must only be called on enums!
1953     pub fn discr_type(&self) -> attr::IntType {
1954         self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize))
1955     }
1956
1957     /// Returns `true` if this `#[repr()]` should inhabit "smart enum
1958     /// layout" optimizations, such as representing `Foo<&T>` as a
1959     /// single pointer.
1960     pub fn inhibit_enum_layout_opt(&self) -> bool {
1961         self.c() || self.int.is_some()
1962     }
1963
1964     /// Returns `true` if this `#[repr()]` should inhibit struct field reordering
1965     /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr(<int>)`.
1966     pub fn inhibit_struct_field_reordering_opt(&self) -> bool {
1967         if let Some(pack) = self.pack {
1968             if pack.bytes() == 1 {
1969                 return true;
1970             }
1971         }
1972
1973         self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some()
1974     }
1975
1976     /// Returns `true` if this type is valid for reordering and `-Z randomize-layout`
1977     /// was enabled for its declaration crate
1978     pub fn can_randomize_type_layout(&self) -> bool {
1979         !self.inhibit_struct_field_reordering_opt()
1980             && self.flags.contains(ReprFlags::RANDOMIZE_LAYOUT)
1981     }
1982
1983     /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations.
1984     pub fn inhibit_union_abi_opt(&self) -> bool {
1985         self.c()
1986     }
1987 }
1988
1989 impl<'tcx> FieldDef {
1990     /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1991     /// typically obtained via the second field of [`TyKind::Adt`].
1992     pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1993         tcx.bound_type_of(self.did).subst(tcx, subst)
1994     }
1995
1996     /// Computes the `Ident` of this variant by looking up the `Span`
1997     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1998         Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1999     }
2000 }
2001
2002 pub type Attributes<'tcx> = impl Iterator<Item = &'tcx ast::Attribute>;
2003 #[derive(Debug, PartialEq, Eq)]
2004 pub enum ImplOverlapKind {
2005     /// These impls are always allowed to overlap.
2006     Permitted {
2007         /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2008         marker: bool,
2009     },
2010     /// These impls are allowed to overlap, but that raises
2011     /// an issue #33140 future-compatibility warning.
2012     ///
2013     /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2014     /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2015     ///
2016     /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2017     /// that difference, making what reduces to the following set of impls:
2018     ///
2019     /// ```compile_fail,(E0119)
2020     /// trait Trait {}
2021     /// impl Trait for dyn Send + Sync {}
2022     /// impl Trait for dyn Sync + Send {}
2023     /// ```
2024     ///
2025     /// Obviously, once we made these types be identical, that code causes a coherence
2026     /// error and a fairly big headache for us. However, luckily for us, the trait
2027     /// `Trait` used in this case is basically a marker trait, and therefore having
2028     /// overlapping impls for it is sound.
2029     ///
2030     /// To handle this, we basically regard the trait as a marker trait, with an additional
2031     /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2032     /// it has the following restrictions:
2033     ///
2034     /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2035     /// positive impls.
2036     /// 2. The trait-ref of both impls must be equal.
2037     /// 3. The trait-ref of both impls must be a trait object type consisting only of
2038     /// marker traits.
2039     /// 4. Neither of the impls can have any where-clauses.
2040     ///
2041     /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2042     Issue33140,
2043 }
2044
2045 impl<'tcx> TyCtxt<'tcx> {
2046     pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2047         self.typeck(self.hir().body_owner_def_id(body))
2048     }
2049
2050     pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2051         self.associated_items(id)
2052             .in_definition_order()
2053             .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
2054     }
2055
2056     /// Look up the name of a definition across crates. This does not look at HIR.
2057     pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2058         if let Some(cnum) = def_id.as_crate_root() {
2059             Some(self.crate_name(cnum))
2060         } else {
2061             let def_key = self.def_key(def_id);
2062             match def_key.disambiguated_data.data {
2063                 // The name of a constructor is that of its parent.
2064                 rustc_hir::definitions::DefPathData::Ctor => self
2065                     .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2066                 // The name of opaque types only exists in HIR.
2067                 rustc_hir::definitions::DefPathData::ImplTrait
2068                     if let Some(def_id) = def_id.as_local() =>
2069                     self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2070                 _ => def_key.get_opt_name(),
2071             }
2072         }
2073     }
2074
2075     /// Look up the name of a definition across crates. This does not look at HIR.
2076     ///
2077     /// This method will ICE if the corresponding item does not have a name.  In these cases, use
2078     /// [`opt_item_name`] instead.
2079     ///
2080     /// [`opt_item_name`]: Self::opt_item_name
2081     pub fn item_name(self, id: DefId) -> Symbol {
2082         self.opt_item_name(id).unwrap_or_else(|| {
2083             bug!("item_name: no name for {:?}", self.def_path(id));
2084         })
2085     }
2086
2087     /// Look up the name and span of a definition.
2088     ///
2089     /// See [`item_name`][Self::item_name] for more information.
2090     pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2091         let def = self.opt_item_name(def_id)?;
2092         let span = def_id
2093             .as_local()
2094             .and_then(|id| self.def_ident_span(id))
2095             .unwrap_or(rustc_span::DUMMY_SP);
2096         Some(Ident::new(def, span))
2097     }
2098
2099     pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2100         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2101             Some(self.associated_item(def_id))
2102         } else {
2103             None
2104         }
2105     }
2106
2107     pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize {
2108         typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field")
2109     }
2110
2111     pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2112         variant
2113             .fields
2114             .iter()
2115             .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2116     }
2117
2118     /// Returns `true` if the impls are the same polarity and the trait either
2119     /// has no items or is annotated `#[marker]` and prevents item overrides.
2120     pub fn impls_are_allowed_to_overlap(
2121         self,
2122         def_id1: DefId,
2123         def_id2: DefId,
2124     ) -> Option<ImplOverlapKind> {
2125         // If either trait impl references an error, they're allowed to overlap,
2126         // as one of them essentially doesn't exist.
2127         if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error())
2128             || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error())
2129         {
2130             return Some(ImplOverlapKind::Permitted { marker: false });
2131         }
2132
2133         match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2134             (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2135                 // `#[rustc_reservation_impl]` impls don't overlap with anything
2136                 debug!(
2137                     "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2138                     def_id1, def_id2
2139                 );
2140                 return Some(ImplOverlapKind::Permitted { marker: false });
2141             }
2142             (ImplPolarity::Positive, ImplPolarity::Negative)
2143             | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2144                 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2145                 debug!(
2146                     "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2147                     def_id1, def_id2
2148                 );
2149                 return None;
2150             }
2151             (ImplPolarity::Positive, ImplPolarity::Positive)
2152             | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2153         };
2154
2155         let is_marker_overlap = {
2156             let is_marker_impl = |def_id: DefId| -> bool {
2157                 let trait_ref = self.impl_trait_ref(def_id);
2158                 trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker)
2159             };
2160             is_marker_impl(def_id1) && is_marker_impl(def_id2)
2161         };
2162
2163         if is_marker_overlap {
2164             debug!(
2165                 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2166                 def_id1, def_id2
2167             );
2168             Some(ImplOverlapKind::Permitted { marker: true })
2169         } else {
2170             if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2171                 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2172                     if self_ty1 == self_ty2 {
2173                         debug!(
2174                             "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2175                             def_id1, def_id2
2176                         );
2177                         return Some(ImplOverlapKind::Issue33140);
2178                     } else {
2179                         debug!(
2180                             "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2181                             def_id1, def_id2, self_ty1, self_ty2
2182                         );
2183                     }
2184                 }
2185             }
2186
2187             debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2188             None
2189         }
2190     }
2191
2192     /// Returns `ty::VariantDef` if `res` refers to a struct,
2193     /// or variant or their constructors, panics otherwise.
2194     pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2195         match res {
2196             Res::Def(DefKind::Variant, did) => {
2197                 let enum_did = self.parent(did);
2198                 self.adt_def(enum_did).variant_with_id(did)
2199             }
2200             Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2201             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2202                 let variant_did = self.parent(variant_ctor_did);
2203                 let enum_did = self.parent(variant_did);
2204                 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2205             }
2206             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2207                 let struct_did = self.parent(ctor_did);
2208                 self.adt_def(struct_did).non_enum_variant()
2209             }
2210             _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2211         }
2212     }
2213
2214     /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2215     #[instrument(skip(self), level = "debug")]
2216     pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2217         match instance {
2218             ty::InstanceDef::Item(def) => {
2219                 debug!("calling def_kind on def: {:?}", def);
2220                 let def_kind = self.def_kind(def.did);
2221                 debug!("returned from def_kind: {:?}", def_kind);
2222                 match def_kind {
2223                     DefKind::Const
2224                     | DefKind::Static(..)
2225                     | DefKind::AssocConst
2226                     | DefKind::Ctor(..)
2227                     | DefKind::AnonConst
2228                     | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2229                     // If the caller wants `mir_for_ctfe` of a function they should not be using
2230                     // `instance_mir`, so we'll assume const fn also wants the optimized version.
2231                     _ => {
2232                         assert_eq!(def.const_param_did, None);
2233                         self.optimized_mir(def.did)
2234                     }
2235                 }
2236             }
2237             ty::InstanceDef::VTableShim(..)
2238             | ty::InstanceDef::ReifyShim(..)
2239             | ty::InstanceDef::Intrinsic(..)
2240             | ty::InstanceDef::FnPtrShim(..)
2241             | ty::InstanceDef::Virtual(..)
2242             | ty::InstanceDef::ClosureOnceShim { .. }
2243             | ty::InstanceDef::DropGlue(..)
2244             | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2245         }
2246     }
2247
2248     // FIXME(@lcnr): Remove this function.
2249     pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [ast::Attribute] {
2250         if let Some(did) = did.as_local() {
2251             self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2252         } else {
2253             self.item_attrs(did)
2254         }
2255     }
2256
2257     /// Gets all attributes with the given name.
2258     pub fn get_attrs(self, did: DefId, attr: Symbol) -> ty::Attributes<'tcx> {
2259         let filter_fn = move |a: &&ast::Attribute| a.has_name(attr);
2260         if let Some(did) = did.as_local() {
2261             self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn)
2262         } else if cfg!(debug_assertions) && rustc_feature::is_builtin_only_local(attr) {
2263             bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2264         } else {
2265             self.item_attrs(did).iter().filter(filter_fn)
2266         }
2267     }
2268
2269     pub fn get_attr(self, did: DefId, attr: Symbol) -> Option<&'tcx ast::Attribute> {
2270         if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
2271             bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
2272         } else {
2273             self.get_attrs(did, attr).next()
2274         }
2275     }
2276
2277     /// Determines whether an item is annotated with an attribute.
2278     pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2279         if cfg!(debug_assertions) && !did.is_local() && rustc_feature::is_builtin_only_local(attr) {
2280             bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2281         } else {
2282             self.get_attrs(did, attr).next().is_some()
2283         }
2284     }
2285
2286     /// Returns `true` if this is an `auto trait`.
2287     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2288         self.trait_def(trait_def_id).has_auto_impl
2289     }
2290
2291     /// Returns layout of a generator. Layout might be unavailable if the
2292     /// generator is tainted by errors.
2293     pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2294         self.optimized_mir(def_id).generator_layout()
2295     }
2296
2297     /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2298     /// If it implements no trait, returns `None`.
2299     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2300         self.impl_trait_ref(def_id).map(|tr| tr.def_id)
2301     }
2302
2303     /// If the given `DefId` describes an item belonging to a trait,
2304     /// returns the `DefId` of the trait that the trait item belongs to;
2305     /// otherwise, returns `None`.
2306     pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2307         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2308             let parent = self.parent(def_id);
2309             if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
2310                 return Some(parent);
2311             }
2312         }
2313         None
2314     }
2315
2316     /// If the given `DefId` describes a method belonging to an impl, returns the
2317     /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2318     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2319         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2320             let parent = self.parent(def_id);
2321             if let DefKind::Impl = self.def_kind(parent) {
2322                 return Some(parent);
2323             }
2324         }
2325         None
2326     }
2327
2328     /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2329     pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2330         self.has_attr(def_id, sym::automatically_derived)
2331     }
2332
2333     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2334     /// with the name of the crate containing the impl.
2335     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
2336         if let Some(impl_did) = impl_did.as_local() {
2337             Ok(self.def_span(impl_did))
2338         } else {
2339             Err(self.crate_name(impl_did.krate))
2340         }
2341     }
2342
2343     /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2344     /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2345     /// definition's parent/scope to perform comparison.
2346     pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2347         // We could use `Ident::eq` here, but we deliberately don't. The name
2348         // comparison fails frequently, and we want to avoid the expensive
2349         // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2350         use_name.name == def_name.name
2351             && use_name
2352                 .span
2353                 .ctxt()
2354                 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2355     }
2356
2357     pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2358         ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2359         ident
2360     }
2361
2362     pub fn adjust_ident_and_get_scope(
2363         self,
2364         mut ident: Ident,
2365         scope: DefId,
2366         block: hir::HirId,
2367     ) -> (Ident, DefId) {
2368         let scope = ident
2369             .span
2370             .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2371             .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2372             .unwrap_or_else(|| self.parent_module(block).to_def_id());
2373         (ident, scope)
2374     }
2375
2376     pub fn is_object_safe(self, key: DefId) -> bool {
2377         self.object_safety_violations(key).is_empty()
2378     }
2379
2380     #[inline]
2381     pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2382         matches!(self.def_kind(def_id), DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..))
2383             && self.constness(def_id) == hir::Constness::Const
2384     }
2385
2386     #[inline]
2387     pub fn is_const_default_method(self, def_id: DefId) -> bool {
2388         matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait))
2389     }
2390 }
2391
2392 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2393 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2394     let def_id = def_id.as_local()?;
2395     if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2396         if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2397             return match opaque_ty.origin {
2398                 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2399                     Some(parent)
2400                 }
2401                 hir::OpaqueTyOrigin::TyAlias => None,
2402             };
2403         }
2404     }
2405     None
2406 }
2407
2408 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2409     match ity {
2410         ast::IntTy::Isize => IntTy::Isize,
2411         ast::IntTy::I8 => IntTy::I8,
2412         ast::IntTy::I16 => IntTy::I16,
2413         ast::IntTy::I32 => IntTy::I32,
2414         ast::IntTy::I64 => IntTy::I64,
2415         ast::IntTy::I128 => IntTy::I128,
2416     }
2417 }
2418
2419 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2420     match uty {
2421         ast::UintTy::Usize => UintTy::Usize,
2422         ast::UintTy::U8 => UintTy::U8,
2423         ast::UintTy::U16 => UintTy::U16,
2424         ast::UintTy::U32 => UintTy::U32,
2425         ast::UintTy::U64 => UintTy::U64,
2426         ast::UintTy::U128 => UintTy::U128,
2427     }
2428 }
2429
2430 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2431     match fty {
2432         ast::FloatTy::F32 => FloatTy::F32,
2433         ast::FloatTy::F64 => FloatTy::F64,
2434     }
2435 }
2436
2437 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2438     match ity {
2439         IntTy::Isize => ast::IntTy::Isize,
2440         IntTy::I8 => ast::IntTy::I8,
2441         IntTy::I16 => ast::IntTy::I16,
2442         IntTy::I32 => ast::IntTy::I32,
2443         IntTy::I64 => ast::IntTy::I64,
2444         IntTy::I128 => ast::IntTy::I128,
2445     }
2446 }
2447
2448 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2449     match uty {
2450         UintTy::Usize => ast::UintTy::Usize,
2451         UintTy::U8 => ast::UintTy::U8,
2452         UintTy::U16 => ast::UintTy::U16,
2453         UintTy::U32 => ast::UintTy::U32,
2454         UintTy::U64 => ast::UintTy::U64,
2455         UintTy::U128 => ast::UintTy::U128,
2456     }
2457 }
2458
2459 pub fn provide(providers: &mut ty::query::Providers) {
2460     closure::provide(providers);
2461     context::provide(providers);
2462     erase_regions::provide(providers);
2463     layout::provide(providers);
2464     util::provide(providers);
2465     print::provide(providers);
2466     super::util::bug::provide(providers);
2467     super::middle::provide(providers);
2468     *providers = ty::query::Providers {
2469         trait_impls_of: trait_def::trait_impls_of_provider,
2470         incoherent_impls: trait_def::incoherent_impls_provider,
2471         type_uninhabited_from: inhabitedness::type_uninhabited_from,
2472         const_param_default: consts::const_param_default,
2473         vtable_allocation: vtable::vtable_allocation_provider,
2474         ..*providers
2475     };
2476 }
2477
2478 /// A map for the local crate mapping each type to a vector of its
2479 /// inherent impls. This is not meant to be used outside of coherence;
2480 /// rather, you should request the vector for a specific type via
2481 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2482 /// (constructing this map requires touching the entire crate).
2483 #[derive(Clone, Debug, Default, HashStable)]
2484 pub struct CrateInherentImpls {
2485     pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2486     pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2487 }
2488
2489 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2490 pub struct SymbolName<'tcx> {
2491     /// `&str` gives a consistent ordering, which ensures reproducible builds.
2492     pub name: &'tcx str,
2493 }
2494
2495 impl<'tcx> SymbolName<'tcx> {
2496     pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2497         SymbolName {
2498             name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2499         }
2500     }
2501 }
2502
2503 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2504     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2505         fmt::Display::fmt(&self.name, fmt)
2506     }
2507 }
2508
2509 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2510     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2511         fmt::Display::fmt(&self.name, fmt)
2512     }
2513 }
2514
2515 #[derive(Debug, Default, Copy, Clone)]
2516 pub struct FoundRelationships {
2517     /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2518     /// obligation, where:
2519     ///
2520     ///  * `Foo` is not `Sized`
2521     ///  * `(): Foo` may be satisfied
2522     pub self_in_trait: bool,
2523     /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2524     /// _>::AssocType = ?T`
2525     pub output: bool,
2526 }
2527
2528 /// The constituent parts of a type level constant of kind ADT or array.
2529 #[derive(Copy, Clone, Debug, HashStable)]
2530 pub struct DestructuredConst<'tcx> {
2531     pub variant: Option<VariantIdx>,
2532     pub fields: &'tcx [ty::Const<'tcx>],
2533 }