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