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