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