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