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