]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/mod.rs
Rollup merge of #106888 - GuillaumeGomez:tidy-gui-test, r=notriddle
[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
1257 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable, Lift)]
1258 #[derive(TypeFoldable, TypeVisitable)]
1259 pub struct OpaqueTypeKey<'tcx> {
1260     pub def_id: LocalDefId,
1261     pub substs: SubstsRef<'tcx>,
1262 }
1263
1264 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
1265 pub struct OpaqueHiddenType<'tcx> {
1266     /// The span of this particular definition of the opaque type. So
1267     /// for example:
1268     ///
1269     /// ```ignore (incomplete snippet)
1270     /// type Foo = impl Baz;
1271     /// fn bar() -> Foo {
1272     /// //          ^^^ This is the span we are looking for!
1273     /// }
1274     /// ```
1275     ///
1276     /// In cases where the fn returns `(impl Trait, impl Trait)` or
1277     /// other such combinations, the result is currently
1278     /// over-approximated, but better than nothing.
1279     pub span: Span,
1280
1281     /// The type variable that represents the value of the opaque type
1282     /// that we require. In other words, after we compile this function,
1283     /// we will be created a constraint like:
1284     /// ```ignore (pseudo-rust)
1285     /// Foo<'a, T> = ?C
1286     /// ```
1287     /// where `?C` is the value of this type variable. =) It may
1288     /// naturally refer to the type and lifetime parameters in scope
1289     /// in this function, though ultimately it should only reference
1290     /// those that are arguments to `Foo` in the constraint above. (In
1291     /// other words, `?C` should not include `'b`, even though it's a
1292     /// lifetime parameter on `foo`.)
1293     pub ty: Ty<'tcx>,
1294 }
1295
1296 impl<'tcx> OpaqueHiddenType<'tcx> {
1297     pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) {
1298         // Found different concrete types for the opaque type.
1299         let sub_diag = if self.span == other.span {
1300             TypeMismatchReason::ConflictType { span: self.span }
1301         } else {
1302             TypeMismatchReason::PreviousUse { span: self.span }
1303         };
1304         tcx.sess.emit_err(OpaqueHiddenTypeMismatch {
1305             self_ty: self.ty,
1306             other_ty: other.ty,
1307             other_span: other.span,
1308             sub: sub_diag,
1309         });
1310     }
1311
1312     #[instrument(level = "debug", skip(tcx), ret)]
1313     pub fn remap_generic_params_to_declaration_params(
1314         self,
1315         opaque_type_key: OpaqueTypeKey<'tcx>,
1316         tcx: TyCtxt<'tcx>,
1317         // typeck errors have subpar spans for opaque types, so delay error reporting until borrowck.
1318         ignore_errors: bool,
1319         origin: OpaqueTyOrigin,
1320     ) -> Self {
1321         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
1322
1323         // Use substs to build up a reverse map from regions to their
1324         // identity mappings. This is necessary because of `impl
1325         // Trait` lifetimes are computed by replacing existing
1326         // lifetimes with 'static and remapping only those used in the
1327         // `impl Trait` return type, resulting in the parameters
1328         // shifting.
1329         let id_substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
1330         debug!(?id_substs);
1331
1332         // This zip may have several times the same lifetime in `substs` paired with a different
1333         // lifetime from `id_substs`.  Simply `collect`ing the iterator is the correct behaviour:
1334         // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
1335         let map = substs.iter().zip(id_substs);
1336
1337         let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> = match origin {
1338             // HACK: The HIR lowering for async fn does not generate
1339             // any `+ Captures<'x>` bounds for the `impl Future<...>`, so all async fns with lifetimes
1340             // would now fail to compile. We should probably just make hir lowering fill this in properly.
1341             OpaqueTyOrigin::AsyncFn(_) => map.collect(),
1342             OpaqueTyOrigin::FnReturn(_) | OpaqueTyOrigin::TyAlias => {
1343                 // Opaque types may only use regions that are bound. So for
1344                 // ```rust
1345                 // type Foo<'a, 'b, 'c> = impl Trait<'a> + 'b;
1346                 // ```
1347                 // we may not use `'c` in the hidden type.
1348                 let variances = tcx.variances_of(def_id);
1349                 debug!(?variances);
1350
1351                 map.filter(|(_, v)| {
1352                     let ty::GenericArgKind::Lifetime(lt) = v.unpack() else { return true };
1353                     let ty::ReEarlyBound(ebr) = lt.kind() else { bug!() };
1354                     variances[ebr.index as usize] == ty::Variance::Invariant
1355                 })
1356                 .collect()
1357             }
1358         };
1359         debug!("map = {:#?}", map);
1360
1361         // Convert the type from the function into a type valid outside
1362         // the function, by replacing invalid regions with 'static,
1363         // after producing an error for each of them.
1364         self.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span, ignore_errors))
1365     }
1366 }
1367
1368 /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are
1369 /// identified by both a universe, as well as a name residing within that universe. Distinct bound
1370 /// regions/types/consts within the same universe simply have an unknown relationship to one
1371 /// another.
1372 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1373 #[derive(HashStable, TyEncodable, TyDecodable)]
1374 pub struct Placeholder<T> {
1375     pub universe: UniverseIndex,
1376     pub name: T,
1377 }
1378
1379 pub type PlaceholderRegion = Placeholder<BoundRegionKind>;
1380
1381 pub type PlaceholderType = Placeholder<BoundVar>;
1382
1383 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1384 #[derive(TyEncodable, TyDecodable, PartialOrd, Ord)]
1385 pub struct BoundConst<'tcx> {
1386     pub var: BoundVar,
1387     pub ty: Ty<'tcx>,
1388 }
1389
1390 pub type PlaceholderConst<'tcx> = Placeholder<BoundVar>;
1391
1392 /// A `DefId` which, in case it is a const argument, is potentially bundled with
1393 /// the `DefId` of the generic parameter it instantiates.
1394 ///
1395 /// This is used to avoid calls to `type_of` for const arguments during typeck
1396 /// which cause cycle errors.
1397 ///
1398 /// ```rust
1399 /// struct A;
1400 /// impl A {
1401 ///     fn foo<const N: usize>(&self) -> [u8; N] { [0; N] }
1402 ///     //           ^ const parameter
1403 /// }
1404 /// struct B;
1405 /// impl B {
1406 ///     fn foo<const M: u8>(&self) -> usize { 42 }
1407 ///     //           ^ const parameter
1408 /// }
1409 ///
1410 /// fn main() {
1411 ///     let a = A;
1412 ///     let _b = a.foo::<{ 3 + 7 }>();
1413 ///     //               ^^^^^^^^^ const argument
1414 /// }
1415 /// ```
1416 ///
1417 /// Let's look at the call `a.foo::<{ 3 + 7 }>()` here. We do not know
1418 /// which `foo` is used until we know the type of `a`.
1419 ///
1420 /// We only know the type of `a` once we are inside of `typeck(main)`.
1421 /// We also end up normalizing the type of `_b` during `typeck(main)` which
1422 /// requires us to evaluate the const argument.
1423 ///
1424 /// To evaluate that const argument we need to know its type,
1425 /// which we would get using `type_of(const_arg)`. This requires us to
1426 /// resolve `foo` as it can be either `usize` or `u8` in this example.
1427 /// However, resolving `foo` once again requires `typeck(main)` to get the type of `a`,
1428 /// which results in a cycle.
1429 ///
1430 /// In short we must not call `type_of(const_arg)` during `typeck(main)`.
1431 ///
1432 /// When first creating the `ty::Const` of the const argument inside of `typeck` we have
1433 /// already resolved `foo` so we know which const parameter this argument instantiates.
1434 /// This means that we also know the expected result of `type_of(const_arg)` even if we
1435 /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is
1436 /// trivial to compute.
1437 ///
1438 /// If we now want to use that constant in a place which potentially needs its type
1439 /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`,
1440 /// except that instead of a `Ty` we bundle the `DefId` of the const parameter.
1441 /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some`
1442 /// to get the type of `did`.
1443 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift, TyEncodable, TyDecodable)]
1444 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1445 #[derive(Hash, HashStable)]
1446 pub struct WithOptConstParam<T> {
1447     pub did: T,
1448     /// The `DefId` of the corresponding generic parameter in case `did` is
1449     /// a const argument.
1450     ///
1451     /// Note that even if `did` is a const argument, this may still be `None`.
1452     /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)`
1453     /// to potentially update `param_did` in the case it is `None`.
1454     pub const_param_did: Option<DefId>,
1455 }
1456
1457 impl<T> WithOptConstParam<T> {
1458     /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`.
1459     #[inline(always)]
1460     pub fn unknown(did: T) -> WithOptConstParam<T> {
1461         WithOptConstParam { did, const_param_did: None }
1462     }
1463 }
1464
1465 impl WithOptConstParam<LocalDefId> {
1466     /// Returns `Some((did, param_did))` if `def_id` is a const argument,
1467     /// `None` otherwise.
1468     #[inline(always)]
1469     pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> {
1470         tcx.opt_const_param_of(did).map(|param_did| (did, param_did))
1471     }
1472
1473     /// In case `self` is unknown but `self.did` is a const argument, this returns
1474     /// a `WithOptConstParam` with the correct `const_param_did`.
1475     #[inline(always)]
1476     pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option<WithOptConstParam<LocalDefId>> {
1477         if self.const_param_did.is_none() {
1478             if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) {
1479                 return Some(WithOptConstParam { did: self.did, const_param_did });
1480             }
1481         }
1482
1483         None
1484     }
1485
1486     pub fn to_global(self) -> WithOptConstParam<DefId> {
1487         WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did }
1488     }
1489
1490     pub fn def_id_for_type_of(self) -> DefId {
1491         if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() }
1492     }
1493 }
1494
1495 impl WithOptConstParam<DefId> {
1496     pub fn as_local(self) -> Option<WithOptConstParam<LocalDefId>> {
1497         self.did
1498             .as_local()
1499             .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did })
1500     }
1501
1502     pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> {
1503         if let Some(param_did) = self.const_param_did {
1504             if let Some(did) = self.did.as_local() {
1505                 return Some((did, param_did));
1506             }
1507         }
1508
1509         None
1510     }
1511
1512     pub fn is_local(self) -> bool {
1513         self.did.is_local()
1514     }
1515
1516     pub fn def_id_for_type_of(self) -> DefId {
1517         self.const_param_did.unwrap_or(self.did)
1518     }
1519 }
1520
1521 /// When type checking, we use the `ParamEnv` to track
1522 /// details about the set of where-clauses that are in scope at this
1523 /// particular point.
1524 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
1525 pub struct ParamEnv<'tcx> {
1526     /// This packs both caller bounds and the reveal enum into one pointer.
1527     ///
1528     /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1529     /// basically the set of bounds on the in-scope type parameters, translated
1530     /// into `Obligation`s, and elaborated and normalized.
1531     ///
1532     /// Use the `caller_bounds()` method to access.
1533     ///
1534     /// Typically, this is `Reveal::UserFacing`, but during codegen we
1535     /// want `Reveal::All`.
1536     ///
1537     /// Note: This is packed, use the reveal() method to access it.
1538     packed: CopyTaggedPtr<&'tcx List<Predicate<'tcx>>, ParamTag, true>,
1539 }
1540
1541 #[derive(Copy, Clone)]
1542 struct ParamTag {
1543     reveal: traits::Reveal,
1544     constness: hir::Constness,
1545 }
1546
1547 unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag {
1548     const BITS: usize = 2;
1549     #[inline]
1550     fn into_usize(self) -> usize {
1551         match self {
1552             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0,
1553             Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1,
1554             Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2,
1555             Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3,
1556         }
1557     }
1558     #[inline]
1559     unsafe fn from_usize(ptr: usize) -> Self {
1560         match ptr {
1561             0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst },
1562             1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst },
1563             2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const },
1564             3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const },
1565             _ => std::hint::unreachable_unchecked(),
1566         }
1567     }
1568 }
1569
1570 impl<'tcx> fmt::Debug for ParamEnv<'tcx> {
1571     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1572         f.debug_struct("ParamEnv")
1573             .field("caller_bounds", &self.caller_bounds())
1574             .field("reveal", &self.reveal())
1575             .field("constness", &self.constness())
1576             .finish()
1577     }
1578 }
1579
1580 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ParamEnv<'tcx> {
1581     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
1582         self.caller_bounds().hash_stable(hcx, hasher);
1583         self.reveal().hash_stable(hcx, hasher);
1584         self.constness().hash_stable(hcx, hasher);
1585     }
1586 }
1587
1588 impl<'tcx> TypeFoldable<'tcx> for ParamEnv<'tcx> {
1589     fn try_fold_with<F: ty::fold::FallibleTypeFolder<'tcx>>(
1590         self,
1591         folder: &mut F,
1592     ) -> Result<Self, F::Error> {
1593         Ok(ParamEnv::new(
1594             self.caller_bounds().try_fold_with(folder)?,
1595             self.reveal().try_fold_with(folder)?,
1596             self.constness(),
1597         ))
1598     }
1599 }
1600
1601 impl<'tcx> TypeVisitable<'tcx> for ParamEnv<'tcx> {
1602     fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
1603         self.caller_bounds().visit_with(visitor)?;
1604         self.reveal().visit_with(visitor)
1605     }
1606 }
1607
1608 impl<'tcx> ParamEnv<'tcx> {
1609     /// Construct a trait environment suitable for contexts where
1610     /// there are no where-clauses in scope. Hidden types (like `impl
1611     /// Trait`) are left hidden, so this is suitable for ordinary
1612     /// type-checking.
1613     #[inline]
1614     pub fn empty() -> Self {
1615         Self::new(List::empty(), Reveal::UserFacing, hir::Constness::NotConst)
1616     }
1617
1618     #[inline]
1619     pub fn caller_bounds(self) -> &'tcx List<Predicate<'tcx>> {
1620         self.packed.pointer()
1621     }
1622
1623     #[inline]
1624     pub fn reveal(self) -> traits::Reveal {
1625         self.packed.tag().reveal
1626     }
1627
1628     #[inline]
1629     pub fn constness(self) -> hir::Constness {
1630         self.packed.tag().constness
1631     }
1632
1633     #[inline]
1634     pub fn is_const(self) -> bool {
1635         self.packed.tag().constness == hir::Constness::Const
1636     }
1637
1638     /// Construct a trait environment with no where-clauses in scope
1639     /// where the values of all `impl Trait` and other hidden types
1640     /// are revealed. This is suitable for monomorphized, post-typeck
1641     /// environments like codegen or doing optimizations.
1642     ///
1643     /// N.B., if you want to have predicates in scope, use `ParamEnv::new`,
1644     /// or invoke `param_env.with_reveal_all()`.
1645     #[inline]
1646     pub fn reveal_all() -> Self {
1647         Self::new(List::empty(), Reveal::All, hir::Constness::NotConst)
1648     }
1649
1650     /// Construct a trait environment with the given set of predicates.
1651     #[inline]
1652     pub fn new(
1653         caller_bounds: &'tcx List<Predicate<'tcx>>,
1654         reveal: Reveal,
1655         constness: hir::Constness,
1656     ) -> Self {
1657         ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) }
1658     }
1659
1660     pub fn with_user_facing(mut self) -> Self {
1661         self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() });
1662         self
1663     }
1664
1665     #[inline]
1666     pub fn with_constness(mut self, constness: hir::Constness) -> Self {
1667         self.packed.set_tag(ParamTag { constness, ..self.packed.tag() });
1668         self
1669     }
1670
1671     #[inline]
1672     pub fn with_const(mut self) -> Self {
1673         self.packed.set_tag(ParamTag { constness: hir::Constness::Const, ..self.packed.tag() });
1674         self
1675     }
1676
1677     #[inline]
1678     pub fn without_const(mut self) -> Self {
1679         self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() });
1680         self
1681     }
1682
1683     #[inline]
1684     pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) {
1685         *self = self.with_constness(constness.and(self.constness()))
1686     }
1687
1688     /// Returns a new parameter environment with the same clauses, but
1689     /// which "reveals" the true results of projections in all cases
1690     /// (even for associated types that are specializable). This is
1691     /// the desired behavior during codegen and certain other special
1692     /// contexts; normally though we want to use `Reveal::UserFacing`,
1693     /// which is the default.
1694     /// All opaque types in the caller_bounds of the `ParamEnv`
1695     /// will be normalized to their underlying types.
1696     /// See PR #65989 and issue #65918 for more details
1697     pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self {
1698         if self.packed.tag().reveal == traits::Reveal::All {
1699             return self;
1700         }
1701
1702         ParamEnv::new(
1703             tcx.reveal_opaque_types_in_bounds(self.caller_bounds()),
1704             Reveal::All,
1705             self.constness(),
1706         )
1707     }
1708
1709     /// Returns this same environment but with no caller bounds.
1710     #[inline]
1711     pub fn without_caller_bounds(self) -> Self {
1712         Self::new(List::empty(), self.reveal(), self.constness())
1713     }
1714
1715     /// Creates a suitable environment in which to perform trait
1716     /// queries on the given value. When type-checking, this is simply
1717     /// the pair of the environment plus value. But when reveal is set to
1718     /// All, then if `value` does not reference any type parameters, we will
1719     /// pair it with the empty environment. This improves caching and is generally
1720     /// invisible.
1721     ///
1722     /// N.B., we preserve the environment when type-checking because it
1723     /// is possible for the user to have wacky where-clauses like
1724     /// `where Box<u32>: Copy`, which are clearly never
1725     /// satisfiable. We generally want to behave as if they were true,
1726     /// although the surrounding function is never reachable.
1727     pub fn and<T: TypeVisitable<'tcx>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1728         match self.reveal() {
1729             Reveal::UserFacing => ParamEnvAnd { param_env: self, value },
1730
1731             Reveal::All => {
1732                 if value.is_global() {
1733                     ParamEnvAnd { param_env: self.without_caller_bounds(), value }
1734                 } else {
1735                     ParamEnvAnd { param_env: self, value }
1736                 }
1737             }
1738         }
1739     }
1740 }
1741
1742 // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that
1743 // the constness of trait bounds is being propagated correctly.
1744 impl<'tcx> PolyTraitRef<'tcx> {
1745     #[inline]
1746     pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> {
1747         self.map_bound(|trait_ref| ty::TraitPredicate {
1748             trait_ref,
1749             constness,
1750             polarity: ty::ImplPolarity::Positive,
1751         })
1752     }
1753
1754     #[inline]
1755     pub fn without_const(self) -> PolyTraitPredicate<'tcx> {
1756         self.with_constness(BoundConstness::NotConst)
1757     }
1758 }
1759
1760 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1761 #[derive(HashStable, Lift)]
1762 pub struct ParamEnvAnd<'tcx, T> {
1763     pub param_env: ParamEnv<'tcx>,
1764     pub value: T,
1765 }
1766
1767 impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1768     pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1769         (self.param_env, self.value)
1770     }
1771
1772     #[inline]
1773     pub fn without_const(mut self) -> Self {
1774         self.param_env = self.param_env.without_const();
1775         self
1776     }
1777 }
1778
1779 #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1780 pub struct Destructor {
1781     /// The `DefId` of the destructor method
1782     pub did: DefId,
1783     /// The constness of the destructor method
1784     pub constness: hir::Constness,
1785 }
1786
1787 bitflags! {
1788     #[derive(HashStable, TyEncodable, TyDecodable)]
1789     pub struct VariantFlags: u32 {
1790         const NO_VARIANT_FLAGS        = 0;
1791         /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1792         const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1793         /// Indicates whether this variant was obtained as part of recovering from
1794         /// a syntactic error. May be incomplete or bogus.
1795         const IS_RECOVERED = 1 << 1;
1796     }
1797 }
1798
1799 /// Definition of a variant -- a struct's fields or an enum variant.
1800 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1801 pub struct VariantDef {
1802     /// `DefId` that identifies the variant itself.
1803     /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1804     pub def_id: DefId,
1805     /// `DefId` that identifies the variant's constructor.
1806     /// If this variant is a struct variant, then this is `None`.
1807     pub ctor: Option<(CtorKind, DefId)>,
1808     /// Variant or struct name.
1809     pub name: Symbol,
1810     /// Discriminant of this variant.
1811     pub discr: VariantDiscr,
1812     /// Fields of this variant.
1813     pub fields: Vec<FieldDef>,
1814     /// Flags of the variant (e.g. is field list non-exhaustive)?
1815     flags: VariantFlags,
1816 }
1817
1818 impl VariantDef {
1819     /// Creates a new `VariantDef`.
1820     ///
1821     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1822     /// represents an enum variant).
1823     ///
1824     /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1825     /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1826     ///
1827     /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1828     /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1829     /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1830     /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1831     /// built-in trait), and we do not want to load attributes twice.
1832     ///
1833     /// If someone speeds up attribute loading to not be a performance concern, they can
1834     /// remove this hack and use the constructor `DefId` everywhere.
1835     pub fn new(
1836         name: Symbol,
1837         variant_did: Option<DefId>,
1838         ctor: Option<(CtorKind, DefId)>,
1839         discr: VariantDiscr,
1840         fields: Vec<FieldDef>,
1841         adt_kind: AdtKind,
1842         parent_did: DefId,
1843         recovered: bool,
1844         is_field_list_non_exhaustive: bool,
1845     ) -> Self {
1846         debug!(
1847             "VariantDef::new(name = {:?}, variant_did = {:?}, ctor = {:?}, discr = {:?},
1848              fields = {:?}, adt_kind = {:?}, parent_did = {:?})",
1849             name, variant_did, ctor, discr, fields, adt_kind, parent_did,
1850         );
1851
1852         let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1853         if is_field_list_non_exhaustive {
1854             flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1855         }
1856
1857         if recovered {
1858             flags |= VariantFlags::IS_RECOVERED;
1859         }
1860
1861         VariantDef { def_id: variant_did.unwrap_or(parent_did), ctor, name, discr, fields, flags }
1862     }
1863
1864     /// Is this field list non-exhaustive?
1865     #[inline]
1866     pub fn is_field_list_non_exhaustive(&self) -> bool {
1867         self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1868     }
1869
1870     /// Was this variant obtained as part of recovering from a syntactic error?
1871     #[inline]
1872     pub fn is_recovered(&self) -> bool {
1873         self.flags.intersects(VariantFlags::IS_RECOVERED)
1874     }
1875
1876     /// Computes the `Ident` of this variant by looking up the `Span`
1877     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1878         Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1879     }
1880
1881     #[inline]
1882     pub fn ctor_kind(&self) -> Option<CtorKind> {
1883         self.ctor.map(|(kind, _)| kind)
1884     }
1885
1886     #[inline]
1887     pub fn ctor_def_id(&self) -> Option<DefId> {
1888         self.ctor.map(|(_, def_id)| def_id)
1889     }
1890 }
1891
1892 impl PartialEq for VariantDef {
1893     #[inline]
1894     fn eq(&self, other: &Self) -> bool {
1895         // There should be only one `VariantDef` for each `def_id`, therefore
1896         // it is fine to implement `PartialEq` only based on `def_id`.
1897         //
1898         // Below, we exhaustively destructure `self` and `other` so that if the
1899         // definition of `VariantDef` changes, a compile-error will be produced,
1900         // reminding us to revisit this assumption.
1901
1902         let Self { def_id: lhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1903         let Self { def_id: rhs_def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = other;
1904         lhs_def_id == rhs_def_id
1905     }
1906 }
1907
1908 impl Eq for VariantDef {}
1909
1910 impl Hash for VariantDef {
1911     #[inline]
1912     fn hash<H: Hasher>(&self, s: &mut H) {
1913         // There should be only one `VariantDef` for each `def_id`, therefore
1914         // it is fine to implement `Hash` only based on `def_id`.
1915         //
1916         // Below, we exhaustively destructure `self` so that if the definition
1917         // of `VariantDef` changes, a compile-error will be produced, reminding
1918         // us to revisit this assumption.
1919
1920         let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _ } = &self;
1921         def_id.hash(s)
1922     }
1923 }
1924
1925 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1926 pub enum VariantDiscr {
1927     /// Explicit value for this variant, i.e., `X = 123`.
1928     /// The `DefId` corresponds to the embedded constant.
1929     Explicit(DefId),
1930
1931     /// The previous variant's discriminant plus one.
1932     /// For efficiency reasons, the distance from the
1933     /// last `Explicit` discriminant is being stored,
1934     /// or `0` for the first variant, if it has none.
1935     Relative(u32),
1936 }
1937
1938 #[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1939 pub struct FieldDef {
1940     pub did: DefId,
1941     pub name: Symbol,
1942     pub vis: Visibility<DefId>,
1943 }
1944
1945 impl PartialEq for FieldDef {
1946     #[inline]
1947     fn eq(&self, other: &Self) -> bool {
1948         // There should be only one `FieldDef` for each `did`, therefore it is
1949         // fine to implement `PartialEq` only based on `did`.
1950         //
1951         // Below, we exhaustively destructure `self` so that if the definition
1952         // of `FieldDef` changes, a compile-error will be produced, reminding
1953         // us to revisit this assumption.
1954
1955         let Self { did: lhs_did, name: _, vis: _ } = &self;
1956
1957         let Self { did: rhs_did, name: _, vis: _ } = other;
1958
1959         lhs_did == rhs_did
1960     }
1961 }
1962
1963 impl Eq for FieldDef {}
1964
1965 impl Hash for FieldDef {
1966     #[inline]
1967     fn hash<H: Hasher>(&self, s: &mut H) {
1968         // There should be only one `FieldDef` for each `did`, therefore it is
1969         // fine to implement `Hash` only based on `did`.
1970         //
1971         // Below, we exhaustively destructure `self` so that if the definition
1972         // of `FieldDef` changes, a compile-error will be produced, reminding
1973         // us to revisit this assumption.
1974
1975         let Self { did, name: _, vis: _ } = &self;
1976
1977         did.hash(s)
1978     }
1979 }
1980
1981 impl<'tcx> FieldDef {
1982     /// Returns the type of this field. The resulting type is not normalized. The `subst` is
1983     /// typically obtained via the second field of [`TyKind::Adt`].
1984     pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> {
1985         tcx.bound_type_of(self.did).subst(tcx, subst)
1986     }
1987
1988     /// Computes the `Ident` of this variant by looking up the `Span`
1989     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1990         Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1991     }
1992 }
1993
1994 pub type Attributes<'tcx> = impl Iterator<Item = &'tcx ast::Attribute>;
1995 #[derive(Debug, PartialEq, Eq)]
1996 pub enum ImplOverlapKind {
1997     /// These impls are always allowed to overlap.
1998     Permitted {
1999         /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
2000         marker: bool,
2001     },
2002     /// These impls are allowed to overlap, but that raises
2003     /// an issue #33140 future-compatibility warning.
2004     ///
2005     /// Some background: in Rust 1.0, the trait-object types `Send + Sync` (today's
2006     /// `dyn Send + Sync`) and `Sync + Send` (now `dyn Sync + Send`) were different.
2007     ///
2008     /// The widely-used version 0.1.0 of the crate `traitobject` had accidentally relied
2009     /// that difference, making what reduces to the following set of impls:
2010     ///
2011     /// ```compile_fail,(E0119)
2012     /// trait Trait {}
2013     /// impl Trait for dyn Send + Sync {}
2014     /// impl Trait for dyn Sync + Send {}
2015     /// ```
2016     ///
2017     /// Obviously, once we made these types be identical, that code causes a coherence
2018     /// error and a fairly big headache for us. However, luckily for us, the trait
2019     /// `Trait` used in this case is basically a marker trait, and therefore having
2020     /// overlapping impls for it is sound.
2021     ///
2022     /// To handle this, we basically regard the trait as a marker trait, with an additional
2023     /// future-compatibility warning. To avoid accidentally "stabilizing" this feature,
2024     /// it has the following restrictions:
2025     ///
2026     /// 1. The trait must indeed be a marker-like trait (i.e., no items), and must be
2027     /// positive impls.
2028     /// 2. The trait-ref of both impls must be equal.
2029     /// 3. The trait-ref of both impls must be a trait object type consisting only of
2030     /// marker traits.
2031     /// 4. Neither of the impls can have any where-clauses.
2032     ///
2033     /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed.
2034     Issue33140,
2035 }
2036
2037 impl<'tcx> TyCtxt<'tcx> {
2038     pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
2039         self.typeck(self.hir().body_owner_def_id(body))
2040     }
2041
2042     pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
2043         self.associated_items(id)
2044             .in_definition_order()
2045             .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
2046     }
2047
2048     pub fn repr_options_of_def(self, did: DefId) -> ReprOptions {
2049         let mut flags = ReprFlags::empty();
2050         let mut size = None;
2051         let mut max_align: Option<Align> = None;
2052         let mut min_pack: Option<Align> = None;
2053
2054         // Generate a deterministically-derived seed from the item's path hash
2055         // to allow for cross-crate compilation to actually work
2056         let mut field_shuffle_seed = self.def_path_hash(did).0.to_smaller_hash();
2057
2058         // If the user defined a custom seed for layout randomization, xor the item's
2059         // path hash with the user defined seed, this will allowing determinism while
2060         // still allowing users to further randomize layout generation for e.g. fuzzing
2061         if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
2062             field_shuffle_seed ^= user_seed;
2063         }
2064
2065         for attr in self.get_attrs(did, sym::repr) {
2066             for r in attr::parse_repr_attr(&self.sess, attr) {
2067                 flags.insert(match r {
2068                     attr::ReprC => ReprFlags::IS_C,
2069                     attr::ReprPacked(pack) => {
2070                         let pack = Align::from_bytes(pack as u64).unwrap();
2071                         min_pack = Some(if let Some(min_pack) = min_pack {
2072                             min_pack.min(pack)
2073                         } else {
2074                             pack
2075                         });
2076                         ReprFlags::empty()
2077                     }
2078                     attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
2079                     attr::ReprSimd => ReprFlags::IS_SIMD,
2080                     attr::ReprInt(i) => {
2081                         size = Some(match i {
2082                             attr::IntType::SignedInt(x) => match x {
2083                                 ast::IntTy::Isize => IntegerType::Pointer(true),
2084                                 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
2085                                 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
2086                                 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
2087                                 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
2088                                 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
2089                             },
2090                             attr::IntType::UnsignedInt(x) => match x {
2091                                 ast::UintTy::Usize => IntegerType::Pointer(false),
2092                                 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
2093                                 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
2094                                 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
2095                                 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
2096                                 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
2097                             },
2098                         });
2099                         ReprFlags::empty()
2100                     }
2101                     attr::ReprAlign(align) => {
2102                         max_align = max_align.max(Some(Align::from_bytes(align as u64).unwrap()));
2103                         ReprFlags::empty()
2104                     }
2105                 });
2106             }
2107         }
2108
2109         // If `-Z randomize-layout` was enabled for the type definition then we can
2110         // consider performing layout randomization
2111         if self.sess.opts.unstable_opts.randomize_layout {
2112             flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
2113         }
2114
2115         // This is here instead of layout because the choice must make it into metadata.
2116         if !self.consider_optimizing(|| format!("Reorder fields of {:?}", self.def_path_str(did))) {
2117             flags.insert(ReprFlags::IS_LINEAR);
2118         }
2119
2120         ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
2121     }
2122
2123     /// Look up the name of a definition across crates. This does not look at HIR.
2124     pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
2125         if let Some(cnum) = def_id.as_crate_root() {
2126             Some(self.crate_name(cnum))
2127         } else {
2128             let def_key = self.def_key(def_id);
2129             match def_key.disambiguated_data.data {
2130                 // The name of a constructor is that of its parent.
2131                 rustc_hir::definitions::DefPathData::Ctor => self
2132                     .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
2133                 // The name of opaque types only exists in HIR.
2134                 rustc_hir::definitions::DefPathData::ImplTrait
2135                     if let Some(def_id) = def_id.as_local() =>
2136                     self.hir().opt_name(self.hir().local_def_id_to_hir_id(def_id)),
2137                 _ => def_key.get_opt_name(),
2138             }
2139         }
2140     }
2141
2142     /// Look up the name of a definition across crates. This does not look at HIR.
2143     ///
2144     /// This method will ICE if the corresponding item does not have a name.  In these cases, use
2145     /// [`opt_item_name`] instead.
2146     ///
2147     /// [`opt_item_name`]: Self::opt_item_name
2148     pub fn item_name(self, id: DefId) -> Symbol {
2149         self.opt_item_name(id).unwrap_or_else(|| {
2150             bug!("item_name: no name for {:?}", self.def_path(id));
2151         })
2152     }
2153
2154     /// Look up the name and span of a definition.
2155     ///
2156     /// See [`item_name`][Self::item_name] for more information.
2157     pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
2158         let def = self.opt_item_name(def_id)?;
2159         let span = def_id
2160             .as_local()
2161             .and_then(|id| self.def_ident_span(id))
2162             .unwrap_or(rustc_span::DUMMY_SP);
2163         Some(Ident::new(def, span))
2164     }
2165
2166     pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> {
2167         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2168             Some(self.associated_item(def_id))
2169         } else {
2170             None
2171         }
2172     }
2173
2174     pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> {
2175         variant
2176             .fields
2177             .iter()
2178             .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id))
2179     }
2180
2181     /// Returns `true` if the impls are the same polarity and the trait either
2182     /// has no items or is annotated `#[marker]` and prevents item overrides.
2183     pub fn impls_are_allowed_to_overlap(
2184         self,
2185         def_id1: DefId,
2186         def_id2: DefId,
2187     ) -> Option<ImplOverlapKind> {
2188         // If either trait impl references an error, they're allowed to overlap,
2189         // as one of them essentially doesn't exist.
2190         if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.subst_identity().references_error())
2191             || self
2192                 .impl_trait_ref(def_id2)
2193                 .map_or(false, |tr| tr.subst_identity().references_error())
2194         {
2195             return Some(ImplOverlapKind::Permitted { marker: false });
2196         }
2197
2198         match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) {
2199             (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
2200                 // `#[rustc_reservation_impl]` impls don't overlap with anything
2201                 debug!(
2202                     "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)",
2203                     def_id1, def_id2
2204                 );
2205                 return Some(ImplOverlapKind::Permitted { marker: false });
2206             }
2207             (ImplPolarity::Positive, ImplPolarity::Negative)
2208             | (ImplPolarity::Negative, ImplPolarity::Positive) => {
2209                 // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
2210                 debug!(
2211                     "impls_are_allowed_to_overlap({:?}, {:?}) - None (differing polarities)",
2212                     def_id1, def_id2
2213                 );
2214                 return None;
2215             }
2216             (ImplPolarity::Positive, ImplPolarity::Positive)
2217             | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
2218         };
2219
2220         let is_marker_overlap = {
2221             let is_marker_impl = |def_id: DefId| -> bool {
2222                 let trait_ref = self.impl_trait_ref(def_id);
2223                 trait_ref.map_or(false, |tr| self.trait_def(tr.skip_binder().def_id).is_marker)
2224             };
2225             is_marker_impl(def_id1) && is_marker_impl(def_id2)
2226         };
2227
2228         if is_marker_overlap {
2229             debug!(
2230                 "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)",
2231                 def_id1, def_id2
2232             );
2233             Some(ImplOverlapKind::Permitted { marker: true })
2234         } else {
2235             if let Some(self_ty1) = self.issue33140_self_ty(def_id1) {
2236                 if let Some(self_ty2) = self.issue33140_self_ty(def_id2) {
2237                     if self_ty1 == self_ty2 {
2238                         debug!(
2239                             "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK",
2240                             def_id1, def_id2
2241                         );
2242                         return Some(ImplOverlapKind::Issue33140);
2243                     } else {
2244                         debug!(
2245                             "impls_are_allowed_to_overlap({:?}, {:?}) - found {:?} != {:?}",
2246                             def_id1, def_id2, self_ty1, self_ty2
2247                         );
2248                     }
2249                 }
2250             }
2251
2252             debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2);
2253             None
2254         }
2255     }
2256
2257     /// Returns `ty::VariantDef` if `res` refers to a struct,
2258     /// or variant or their constructors, panics otherwise.
2259     pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
2260         match res {
2261             Res::Def(DefKind::Variant, did) => {
2262                 let enum_did = self.parent(did);
2263                 self.adt_def(enum_did).variant_with_id(did)
2264             }
2265             Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
2266             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
2267                 let variant_did = self.parent(variant_ctor_did);
2268                 let enum_did = self.parent(variant_did);
2269                 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
2270             }
2271             Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
2272                 let struct_did = self.parent(ctor_did);
2273                 self.adt_def(struct_did).non_enum_variant()
2274             }
2275             _ => bug!("expect_variant_res used with unexpected res {:?}", res),
2276         }
2277     }
2278
2279     /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair.
2280     #[instrument(skip(self), level = "debug")]
2281     pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> {
2282         match instance {
2283             ty::InstanceDef::Item(def) => {
2284                 debug!("calling def_kind on def: {:?}", def);
2285                 let def_kind = self.def_kind(def.did);
2286                 debug!("returned from def_kind: {:?}", def_kind);
2287                 match def_kind {
2288                     DefKind::Const
2289                     | DefKind::Static(..)
2290                     | DefKind::AssocConst
2291                     | DefKind::Ctor(..)
2292                     | DefKind::AnonConst
2293                     | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def),
2294                     // If the caller wants `mir_for_ctfe` of a function they should not be using
2295                     // `instance_mir`, so we'll assume const fn also wants the optimized version.
2296                     _ => {
2297                         assert_eq!(def.const_param_did, None);
2298                         self.optimized_mir(def.did)
2299                     }
2300                 }
2301             }
2302             ty::InstanceDef::VTableShim(..)
2303             | ty::InstanceDef::ReifyShim(..)
2304             | ty::InstanceDef::Intrinsic(..)
2305             | ty::InstanceDef::FnPtrShim(..)
2306             | ty::InstanceDef::Virtual(..)
2307             | ty::InstanceDef::ClosureOnceShim { .. }
2308             | ty::InstanceDef::DropGlue(..)
2309             | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance),
2310         }
2311     }
2312
2313     // FIXME(@lcnr): Remove this function.
2314     pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [ast::Attribute] {
2315         if let Some(did) = did.as_local() {
2316             self.hir().attrs(self.hir().local_def_id_to_hir_id(did))
2317         } else {
2318             self.item_attrs(did)
2319         }
2320     }
2321
2322     /// Gets all attributes with the given name.
2323     pub fn get_attrs(self, did: DefId, attr: Symbol) -> ty::Attributes<'tcx> {
2324         let filter_fn = move |a: &&ast::Attribute| a.has_name(attr);
2325         if let Some(did) = did.as_local() {
2326             self.hir().attrs(self.hir().local_def_id_to_hir_id(did)).iter().filter(filter_fn)
2327         } else if cfg!(debug_assertions) && rustc_feature::is_builtin_only_local(attr) {
2328             bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2329         } else {
2330             self.item_attrs(did).iter().filter(filter_fn)
2331         }
2332     }
2333
2334     pub fn get_attr(self, did: DefId, attr: Symbol) -> Option<&'tcx ast::Attribute> {
2335         if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
2336             bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
2337         } else {
2338             self.get_attrs(did, attr).next()
2339         }
2340     }
2341
2342     /// Determines whether an item is annotated with an attribute.
2343     pub fn has_attr(self, did: DefId, attr: Symbol) -> bool {
2344         if cfg!(debug_assertions) && !did.is_local() && rustc_feature::is_builtin_only_local(attr) {
2345             bug!("tried to access the `only_local` attribute `{}` from an extern crate", attr);
2346         } else {
2347             self.get_attrs(did, attr).next().is_some()
2348         }
2349     }
2350
2351     /// Returns `true` if this is an `auto trait`.
2352     pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
2353         self.trait_def(trait_def_id).has_auto_impl
2354     }
2355
2356     pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
2357         self.trait_is_auto(trait_def_id) || self.lang_items().sized_trait() == Some(trait_def_id)
2358     }
2359
2360     /// Returns layout of a generator. Layout might be unavailable if the
2361     /// generator is tainted by errors.
2362     pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> {
2363         self.optimized_mir(def_id).generator_layout()
2364     }
2365
2366     /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2367     /// If it implements no trait, returns `None`.
2368     pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
2369         self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
2370     }
2371
2372     /// If the given `DefId` describes an item belonging to a trait,
2373     /// returns the `DefId` of the trait that the trait item belongs to;
2374     /// otherwise, returns `None`.
2375     pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
2376         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2377             let parent = self.parent(def_id);
2378             if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
2379                 return Some(parent);
2380             }
2381         }
2382         None
2383     }
2384
2385     /// If the given `DefId` describes a method belonging to an impl, returns the
2386     /// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
2387     pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2388         if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2389             let parent = self.parent(def_id);
2390             if let DefKind::Impl = self.def_kind(parent) {
2391                 return Some(parent);
2392             }
2393         }
2394         None
2395     }
2396
2397     /// If the given `DefId` belongs to a trait that was automatically derived, returns `true`.
2398     pub fn is_builtin_derive(self, def_id: DefId) -> bool {
2399         self.has_attr(def_id, sym::automatically_derived)
2400     }
2401
2402     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2403     /// with the name of the crate containing the impl.
2404     pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2405         if let Some(impl_def_id) = impl_def_id.as_local() {
2406             Ok(self.def_span(impl_def_id))
2407         } else {
2408             Err(self.crate_name(impl_def_id.krate))
2409         }
2410     }
2411
2412     /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2413     /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2414     /// definition's parent/scope to perform comparison.
2415     pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
2416         // We could use `Ident::eq` here, but we deliberately don't. The name
2417         // comparison fails frequently, and we want to avoid the expensive
2418         // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2419         use_name.name == def_name.name
2420             && use_name
2421                 .span
2422                 .ctxt()
2423                 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2424     }
2425
2426     pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2427         ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2428         ident
2429     }
2430
2431     pub fn adjust_ident_and_get_scope(
2432         self,
2433         mut ident: Ident,
2434         scope: DefId,
2435         block: hir::HirId,
2436     ) -> (Ident, DefId) {
2437         let scope = ident
2438             .span
2439             .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2440             .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2441             .unwrap_or_else(|| self.parent_module(block).to_def_id());
2442         (ident, scope)
2443     }
2444
2445     /// Returns `true` if the debuginfo for `span` should be collapsed to the outermost expansion
2446     /// site. Only applies when `Span` is the result of macro expansion.
2447     ///
2448     /// - If the `collapse_debuginfo` feature is enabled then debuginfo is not collapsed by default
2449     ///   and only when a macro definition is annotated with `#[collapse_debuginfo]`.
2450     /// - If `collapse_debuginfo` is not enabled, then debuginfo is collapsed by default.
2451     ///
2452     /// When `-Zdebug-macros` is provided then debuginfo will never be collapsed.
2453     pub fn should_collapse_debuginfo(self, span: Span) -> bool {
2454         !self.sess.opts.unstable_opts.debug_macros
2455             && if self.features().collapse_debuginfo {
2456                 span.in_macro_expansion_with_collapse_debuginfo()
2457             } else {
2458                 // Inlined spans should not be collapsed as that leads to all of the
2459                 // inlined code being attributed to the inline callsite.
2460                 span.from_expansion() && !span.is_inlined()
2461             }
2462     }
2463
2464     pub fn is_object_safe(self, key: DefId) -> bool {
2465         self.object_safety_violations(key).is_empty()
2466     }
2467
2468     #[inline]
2469     pub fn is_const_fn_raw(self, def_id: DefId) -> bool {
2470         matches!(
2471             self.def_kind(def_id),
2472             DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Closure
2473         ) && self.constness(def_id) == hir::Constness::Const
2474     }
2475
2476     #[inline]
2477     pub fn is_const_default_method(self, def_id: DefId) -> bool {
2478         matches!(self.trait_of_item(def_id), Some(trait_id) if self.has_attr(trait_id, sym::const_trait))
2479     }
2480
2481     pub fn impl_trait_in_trait_parent(self, mut def_id: DefId) -> DefId {
2482         while let def_kind = self.def_kind(def_id) && def_kind != DefKind::AssocFn {
2483             debug_assert_eq!(def_kind, DefKind::ImplTraitPlaceholder);
2484             def_id = self.parent(def_id);
2485         }
2486         def_id
2487     }
2488 }
2489
2490 /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition.
2491 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<LocalDefId> {
2492     let def_id = def_id.as_local()?;
2493     if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) {
2494         if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
2495             return match opaque_ty.origin {
2496                 hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => {
2497                     Some(parent)
2498                 }
2499                 hir::OpaqueTyOrigin::TyAlias => None,
2500             };
2501         }
2502     }
2503     None
2504 }
2505
2506 pub fn int_ty(ity: ast::IntTy) -> IntTy {
2507     match ity {
2508         ast::IntTy::Isize => IntTy::Isize,
2509         ast::IntTy::I8 => IntTy::I8,
2510         ast::IntTy::I16 => IntTy::I16,
2511         ast::IntTy::I32 => IntTy::I32,
2512         ast::IntTy::I64 => IntTy::I64,
2513         ast::IntTy::I128 => IntTy::I128,
2514     }
2515 }
2516
2517 pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2518     match uty {
2519         ast::UintTy::Usize => UintTy::Usize,
2520         ast::UintTy::U8 => UintTy::U8,
2521         ast::UintTy::U16 => UintTy::U16,
2522         ast::UintTy::U32 => UintTy::U32,
2523         ast::UintTy::U64 => UintTy::U64,
2524         ast::UintTy::U128 => UintTy::U128,
2525     }
2526 }
2527
2528 pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2529     match fty {
2530         ast::FloatTy::F32 => FloatTy::F32,
2531         ast::FloatTy::F64 => FloatTy::F64,
2532     }
2533 }
2534
2535 pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2536     match ity {
2537         IntTy::Isize => ast::IntTy::Isize,
2538         IntTy::I8 => ast::IntTy::I8,
2539         IntTy::I16 => ast::IntTy::I16,
2540         IntTy::I32 => ast::IntTy::I32,
2541         IntTy::I64 => ast::IntTy::I64,
2542         IntTy::I128 => ast::IntTy::I128,
2543     }
2544 }
2545
2546 pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2547     match uty {
2548         UintTy::Usize => ast::UintTy::Usize,
2549         UintTy::U8 => ast::UintTy::U8,
2550         UintTy::U16 => ast::UintTy::U16,
2551         UintTy::U32 => ast::UintTy::U32,
2552         UintTy::U64 => ast::UintTy::U64,
2553         UintTy::U128 => ast::UintTy::U128,
2554     }
2555 }
2556
2557 pub fn provide(providers: &mut ty::query::Providers) {
2558     closure::provide(providers);
2559     context::provide(providers);
2560     erase_regions::provide(providers);
2561     inhabitedness::provide(providers);
2562     util::provide(providers);
2563     print::provide(providers);
2564     super::util::bug::provide(providers);
2565     super::middle::provide(providers);
2566     *providers = ty::query::Providers {
2567         trait_impls_of: trait_def::trait_impls_of_provider,
2568         incoherent_impls: trait_def::incoherent_impls_provider,
2569         const_param_default: consts::const_param_default,
2570         vtable_allocation: vtable::vtable_allocation_provider,
2571         ..*providers
2572     };
2573 }
2574
2575 /// A map for the local crate mapping each type to a vector of its
2576 /// inherent impls. This is not meant to be used outside of coherence;
2577 /// rather, you should request the vector for a specific type via
2578 /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2579 /// (constructing this map requires touching the entire crate).
2580 #[derive(Clone, Debug, Default, HashStable)]
2581 pub struct CrateInherentImpls {
2582     pub inherent_impls: LocalDefIdMap<Vec<DefId>>,
2583     pub incoherent_impls: FxHashMap<SimplifiedType, Vec<LocalDefId>>,
2584 }
2585
2586 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2587 pub struct SymbolName<'tcx> {
2588     /// `&str` gives a consistent ordering, which ensures reproducible builds.
2589     pub name: &'tcx str,
2590 }
2591
2592 impl<'tcx> SymbolName<'tcx> {
2593     pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2594         SymbolName {
2595             name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2596         }
2597     }
2598 }
2599
2600 impl<'tcx> fmt::Display for SymbolName<'tcx> {
2601     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2602         fmt::Display::fmt(&self.name, fmt)
2603     }
2604 }
2605
2606 impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2607     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2608         fmt::Display::fmt(&self.name, fmt)
2609     }
2610 }
2611
2612 #[derive(Debug, Default, Copy, Clone)]
2613 pub struct FoundRelationships {
2614     /// This is true if we identified that this Ty (`?T`) is found in a `?T: Foo`
2615     /// obligation, where:
2616     ///
2617     ///  * `Foo` is not `Sized`
2618     ///  * `(): Foo` may be satisfied
2619     pub self_in_trait: bool,
2620     /// This is true if we identified that this Ty (`?T`) is found in a `<_ as
2621     /// _>::AssocType = ?T`
2622     pub output: bool,
2623 }
2624
2625 /// The constituent parts of a type level constant of kind ADT or array.
2626 #[derive(Copy, Clone, Debug, HashStable)]
2627 pub struct DestructuredConst<'tcx> {
2628     pub variant: Option<VariantIdx>,
2629     pub fields: &'tcx [ty::Const<'tcx>],
2630 }
2631
2632 // Some types are used a lot. Make sure they don't unintentionally get bigger.
2633 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2634 mod size_asserts {
2635     use super::*;
2636     use rustc_data_structures::static_assert_size;
2637     // tidy-alphabetical-start
2638     static_assert_size!(PredicateKind<'_>, 32);
2639     static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 56);
2640     // tidy-alphabetical-end
2641 }