1#![allow(rustc::usage_of_ty_tykind)]
13
14use std::assert_matches::assert_matches;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ptr::NonNull;
20use std::{fmt, mem, str};
21
22pub use adt::*;
23pub use assoc::*;
24pub use generic_args::{GenericArgKind, TermKind, *};
25pub use generics::*;
26pub use intrinsic::IntrinsicDef;
27use rustc_abi::{Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, VariantIdx};
28use rustc_ast::expand::StrippedCfgItem;
29use rustc_ast::node_id::NodeMap;
30pub use rustc_ast_ir::{Movability, Mutability, try_visit};
31use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
32use rustc_data_structures::intern::Interned;
33use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34use rustc_data_structures::steal::Steal;
35use rustc_errors::{Diag, ErrorGuaranteed};
36use rustc_hir::LangItem;
37use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
38use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
39use rustc_index::IndexVec;
40use rustc_macros::{
41 Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
42 extension,
43};
44use rustc_query_system::ich::StableHashingContext;
45use rustc_serialize::{Decodable, Encodable};
46use rustc_session::lint::LintBuffer;
47pub use rustc_session::lint::RegisteredTools;
48use rustc_span::hygiene::MacroKind;
49use rustc_span::{ExpnId, ExpnKind, Ident, Span, Symbol, kw, sym};
50pub use rustc_type_ir::relate::VarianceDiagInfo;
51pub use rustc_type_ir::*;
52use tracing::{debug, instrument};
53pub use vtable::*;
54use {rustc_ast as ast, rustc_attr_parsing as attr, rustc_hir as hir};
55
56pub use self::closure::{
57 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
58 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
59 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
60 place_to_string_for_capture,
61};
62pub use self::consts::{
63 Const, ConstInt, ConstKind, Expr, ExprKind, ScalarInt, UnevaluatedConst, ValTree, ValTreeKind,
64 Value,
65};
66pub use self::context::{
67 CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
68 TyCtxtFeed, tls,
69};
70pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable};
71pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams};
72pub use self::list::{List, ListWithCachedTypeInfo};
73pub use self::opaque_types::OpaqueTypeKey;
74pub use self::parameterized::ParameterizedOverTcx;
75pub use self::pattern::{Pattern, PatternKind};
76pub use self::predicate::{
77 AliasTerm, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
78 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
79 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
80 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
81 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
82 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
83 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
84};
85pub use self::region::{
86 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
87 RegionKind, RegionVid,
88};
89pub use self::rvalue_scopes::RvalueScopes;
90pub use self::sty::{
91 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
92 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
93 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
94};
95pub use self::trait_def::TraitDef;
96pub use self::typeck_results::{
97 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
98 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
99};
100pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
101use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
102use crate::metadata::ModChild;
103use crate::middle::privacy::EffectiveVisibilities;
104use crate::mir::{Body, CoroutineLayout};
105use crate::query::{IntoQueryParam, Providers};
106use crate::ty;
107pub use crate::ty::diagnostics::*;
108use crate::ty::fast_reject::SimplifiedType;
109use crate::ty::util::Discr;
110
111pub mod abstract_const;
112pub mod adjustment;
113pub mod cast;
114pub mod codec;
115pub mod error;
116pub mod fast_reject;
117pub mod flags;
118pub mod fold;
119pub mod inhabitedness;
120pub mod layout;
121pub mod normalize_erasing_regions;
122pub mod pattern;
123pub mod print;
124pub mod relate;
125pub mod trait_def;
126pub mod util;
127pub mod visit;
128pub mod vtable;
129pub mod walk;
130
131mod adt;
132mod assoc;
133mod closure;
134mod consts;
135mod context;
136mod diagnostics;
137mod elaborate_impl;
138mod erase_regions;
139mod generic_args;
140mod generics;
141mod impls_ty;
142mod instance;
143mod intrinsic;
144mod list;
145mod opaque_types;
146mod parameterized;
147mod predicate;
148mod region;
149mod return_position_impl_trait_in_trait;
150mod rvalue_scopes;
151mod structural_impls;
152#[allow(hidden_glob_reexports)]
153mod sty;
154mod typeck_results;
155
156pub struct ResolverOutputs {
159 pub global_ctxt: ResolverGlobalCtxt,
160 pub ast_lowering: ResolverAstLowering,
161}
162
163#[derive(Debug)]
164pub struct ResolverGlobalCtxt {
165 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
166 pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
168 pub effective_visibilities: EffectiveVisibilities,
169 pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
170 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
171 pub module_children: LocalDefIdMap<Vec<ModChild>>,
172 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
173 pub main_def: Option<MainDefinition>,
174 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
175 pub proc_macros: Vec<LocalDefId>,
178 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
181 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
182 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
183 pub all_macro_rules: FxHashMap<Symbol, Res<ast::NodeId>>,
184 pub stripped_cfg_items: Steal<Vec<StrippedCfgItem>>,
185}
186
187#[derive(Debug)]
190pub struct ResolverAstLowering {
191 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
192
193 pub partial_res_map: NodeMap<hir::def::PartialRes>,
195 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
197 pub label_res_map: NodeMap<ast::NodeId>,
199 pub lifetimes_res_map: NodeMap<LifetimeRes>,
201 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
203
204 pub next_node_id: ast::NodeId,
205
206 pub node_id_to_def_id: NodeMap<LocalDefId>,
207
208 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
209 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
211
212 pub lint_buffer: Steal<LintBuffer>,
214
215 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
217}
218
219#[derive(Debug)]
220pub struct DelegationFnSig {
221 pub header: ast::FnHeader,
222 pub param_count: usize,
223 pub has_self: bool,
224 pub c_variadic: bool,
225 pub target_feature: bool,
226}
227
228#[derive(Clone, Copy, Debug)]
229pub struct MainDefinition {
230 pub res: Res<ast::NodeId>,
231 pub is_import: bool,
232 pub span: Span,
233}
234
235impl MainDefinition {
236 pub fn opt_fn_def_id(self) -> Option<DefId> {
237 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
238 }
239}
240
241#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
245pub struct ImplHeader<'tcx> {
246 pub impl_def_id: DefId,
247 pub impl_args: ty::GenericArgsRef<'tcx>,
248 pub self_ty: Ty<'tcx>,
249 pub trait_ref: Option<TraitRef<'tcx>>,
250 pub predicates: Vec<Predicate<'tcx>>,
251}
252
253#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
254pub struct ImplTraitHeader<'tcx> {
255 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
256 pub polarity: ImplPolarity,
257 pub safety: hir::Safety,
258 pub constness: hir::Constness,
259}
260
261#[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
262pub enum ImplSubject<'tcx> {
263 Trait(TraitRef<'tcx>),
264 Inherent(Ty<'tcx>),
265}
266
267#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
268#[derive(TypeFoldable, TypeVisitable)]
269pub enum Asyncness {
270 Yes,
271 No,
272}
273
274impl Asyncness {
275 pub fn is_async(self) -> bool {
276 matches!(self, Asyncness::Yes)
277 }
278}
279
280#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
281pub enum Visibility<Id = LocalDefId> {
282 Public,
284 Restricted(Id),
286}
287
288impl Visibility {
289 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
290 match self {
291 ty::Visibility::Restricted(restricted_id) => {
292 if restricted_id.is_top_level_module() {
293 "pub(crate)".to_string()
294 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
295 "pub(self)".to_string()
296 } else {
297 format!("pub({})", tcx.item_name(restricted_id.to_def_id()))
298 }
299 }
300 ty::Visibility::Public => "pub".to_string(),
301 }
302 }
303}
304
305#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
306#[derive(TypeFoldable, TypeVisitable)]
307pub struct ClosureSizeProfileData<'tcx> {
308 pub before_feature_tys: Ty<'tcx>,
310 pub after_feature_tys: Ty<'tcx>,
312}
313
314impl TyCtxt<'_> {
315 #[inline]
316 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
317 self.def_key(id).parent.map(|index| DefId { index, ..id })
318 }
319
320 #[inline]
321 #[track_caller]
322 pub fn parent(self, id: DefId) -> DefId {
323 match self.opt_parent(id) {
324 Some(id) => id,
325 None => bug!("{id:?} doesn't have a parent"),
327 }
328 }
329
330 #[inline]
331 #[track_caller]
332 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
333 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
334 }
335
336 #[inline]
337 #[track_caller]
338 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
339 self.parent(id.into().to_def_id()).expect_local()
340 }
341
342 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
343 if descendant.krate != ancestor.krate {
344 return false;
345 }
346
347 while descendant != ancestor {
348 match self.opt_parent(descendant) {
349 Some(parent) => descendant = parent,
350 None => return false,
351 }
352 }
353 true
354 }
355}
356
357impl<Id> Visibility<Id> {
358 pub fn is_public(self) -> bool {
359 matches!(self, Visibility::Public)
360 }
361
362 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
363 match self {
364 Visibility::Public => Visibility::Public,
365 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
366 }
367 }
368}
369
370impl<Id: Into<DefId>> Visibility<Id> {
371 pub fn to_def_id(self) -> Visibility<DefId> {
372 self.map_id(Into::into)
373 }
374
375 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
377 match self {
378 Visibility::Public => true,
380 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
381 }
382 }
383
384 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
386 match vis {
387 Visibility::Public => self.is_public(),
388 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
389 }
390 }
391}
392
393impl Visibility<DefId> {
394 pub fn expect_local(self) -> Visibility {
395 self.map_id(|id| id.expect_local())
396 }
397
398 pub fn is_visible_locally(self) -> bool {
400 match self {
401 Visibility::Public => true,
402 Visibility::Restricted(def_id) => def_id.is_local(),
403 }
404 }
405}
406
407#[derive(HashStable, Debug)]
414pub struct CrateVariancesMap<'tcx> {
415 pub variances: DefIdMap<&'tcx [ty::Variance]>,
419}
420
421#[derive(Copy, Clone, PartialEq, Eq, Hash)]
424pub struct CReaderCacheKey {
425 pub cnum: Option<CrateNum>,
426 pub pos: usize,
427}
428
429#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
431#[rustc_diagnostic_item = "Ty"]
432#[rustc_pass_by_value]
433pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
434
435impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
436 type Kind = TyKind<'tcx>;
437
438 fn kind(self) -> TyKind<'tcx> {
439 *self.kind()
440 }
441}
442
443impl<'tcx> rustc_type_ir::visit::Flags for Ty<'tcx> {
444 fn flags(&self) -> TypeFlags {
445 self.0.flags
446 }
447
448 fn outer_exclusive_binder(&self) -> DebruijnIndex {
449 self.0.outer_exclusive_binder
450 }
451}
452
453impl EarlyParamRegion {
454 pub fn has_name(&self) -> bool {
457 self.name != kw::UnderscoreLifetime && self.name != kw::Empty
458 }
459}
460
461#[derive(HashStable, Debug)]
468pub struct CratePredicatesMap<'tcx> {
469 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
473}
474
475#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
476pub struct Term<'tcx> {
477 ptr: NonNull<()>,
478 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
479}
480
481impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
482
483impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
484 type Kind = TermKind<'tcx>;
485
486 fn kind(self) -> Self::Kind {
487 self.unpack()
488 }
489}
490
491unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
492 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
493{
494}
495unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
496 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
497{
498}
499unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
500unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
501
502impl Debug for Term<'_> {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 match self.unpack() {
505 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
506 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
507 }
508 }
509}
510
511impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
512 fn from(ty: Ty<'tcx>) -> Self {
513 TermKind::Ty(ty).pack()
514 }
515}
516
517impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
518 fn from(c: Const<'tcx>) -> Self {
519 TermKind::Const(c).pack()
520 }
521}
522
523impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
524 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
525 self.unpack().hash_stable(hcx, hasher);
526 }
527}
528
529impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
530 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
531 self,
532 folder: &mut F,
533 ) -> Result<Self, F::Error> {
534 match self.unpack() {
535 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
536 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
537 }
538 }
539}
540
541impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
542 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
543 match self.unpack() {
544 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
545 ty::TermKind::Const(ct) => ct.visit_with(visitor),
546 }
547 }
548}
549
550impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Term<'tcx> {
551 fn encode(&self, e: &mut E) {
552 self.unpack().encode(e)
553 }
554}
555
556impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Term<'tcx> {
557 fn decode(d: &mut D) -> Self {
558 let res: TermKind<'tcx> = Decodable::decode(d);
559 res.pack()
560 }
561}
562
563impl<'tcx> Term<'tcx> {
564 #[inline]
565 pub fn unpack(self) -> TermKind<'tcx> {
566 let ptr =
567 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
568 unsafe {
572 match self.ptr.addr().get() & TAG_MASK {
573 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
574 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
575 ))),
576 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
577 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
578 ))),
579 _ => core::intrinsics::unreachable(),
580 }
581 }
582 }
583
584 pub fn as_type(&self) -> Option<Ty<'tcx>> {
585 if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
586 }
587
588 pub fn expect_type(&self) -> Ty<'tcx> {
589 self.as_type().expect("expected a type, but found a const")
590 }
591
592 pub fn as_const(&self) -> Option<Const<'tcx>> {
593 if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
594 }
595
596 pub fn expect_const(&self) -> Const<'tcx> {
597 self.as_const().expect("expected a const, but found a type")
598 }
599
600 pub fn into_arg(self) -> GenericArg<'tcx> {
601 match self.unpack() {
602 TermKind::Ty(ty) => ty.into(),
603 TermKind::Const(c) => c.into(),
604 }
605 }
606
607 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
608 match self.unpack() {
609 TermKind::Ty(ty) => match *ty.kind() {
610 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
611 _ => None,
612 },
613 TermKind::Const(ct) => match ct.kind() {
614 ConstKind::Unevaluated(uv) => Some(uv.into()),
615 _ => None,
616 },
617 }
618 }
619
620 pub fn is_infer(&self) -> bool {
621 match self.unpack() {
622 TermKind::Ty(ty) => ty.is_ty_var(),
623 TermKind::Const(ct) => ct.is_ct_infer(),
624 }
625 }
626}
627
628const TAG_MASK: usize = 0b11;
629const TYPE_TAG: usize = 0b00;
630const CONST_TAG: usize = 0b01;
631
632#[extension(pub trait TermKindPackExt<'tcx>)]
633impl<'tcx> TermKind<'tcx> {
634 #[inline]
635 fn pack(self) -> Term<'tcx> {
636 let (tag, ptr) = match self {
637 TermKind::Ty(ty) => {
638 assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0);
640 (TYPE_TAG, NonNull::from(ty.0.0).cast())
641 }
642 TermKind::Const(ct) => {
643 assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0);
645 (CONST_TAG, NonNull::from(ct.0.0).cast())
646 }
647 };
648
649 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
650 }
651}
652
653#[derive(Copy, Clone, PartialEq, Eq, Debug)]
654pub enum ParamTerm {
655 Ty(ParamTy),
656 Const(ParamConst),
657}
658
659impl ParamTerm {
660 pub fn index(self) -> usize {
661 match self {
662 ParamTerm::Ty(ty) => ty.index as usize,
663 ParamTerm::Const(ct) => ct.index as usize,
664 }
665 }
666}
667
668#[derive(Copy, Clone, Eq, PartialEq, Debug)]
669pub enum TermVid {
670 Ty(ty::TyVid),
671 Const(ty::ConstVid),
672}
673
674impl From<ty::TyVid> for TermVid {
675 fn from(value: ty::TyVid) -> Self {
676 TermVid::Ty(value)
677 }
678}
679
680impl From<ty::ConstVid> for TermVid {
681 fn from(value: ty::ConstVid) -> Self {
682 TermVid::Const(value)
683 }
684}
685
686#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
706pub struct InstantiatedPredicates<'tcx> {
707 pub predicates: Vec<Clause<'tcx>>,
708 pub spans: Vec<Span>,
709}
710
711impl<'tcx> InstantiatedPredicates<'tcx> {
712 pub fn empty() -> InstantiatedPredicates<'tcx> {
713 InstantiatedPredicates { predicates: vec![], spans: vec![] }
714 }
715
716 pub fn is_empty(&self) -> bool {
717 self.predicates.is_empty()
718 }
719
720 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
721 self.into_iter()
722 }
723}
724
725impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
726 type Item = (Clause<'tcx>, Span);
727
728 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
729
730 fn into_iter(self) -> Self::IntoIter {
731 debug_assert_eq!(self.predicates.len(), self.spans.len());
732 std::iter::zip(self.predicates, self.spans)
733 }
734}
735
736impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
737 type Item = (Clause<'tcx>, Span);
738
739 type IntoIter = std::iter::Zip<
740 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
741 std::iter::Copied<std::slice::Iter<'a, Span>>,
742 >;
743
744 fn into_iter(self) -> Self::IntoIter {
745 debug_assert_eq!(self.predicates.len(), self.spans.len());
746 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
747 }
748}
749
750#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
751pub struct OpaqueHiddenType<'tcx> {
752 pub span: Span,
766
767 pub ty: Ty<'tcx>,
780}
781
782impl<'tcx> OpaqueHiddenType<'tcx> {
783 pub fn build_mismatch_error(
784 &self,
785 other: &Self,
786 tcx: TyCtxt<'tcx>,
787 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
788 (self.ty, other.ty).error_reported()?;
789 let sub_diag = if self.span == other.span {
791 TypeMismatchReason::ConflictType { span: self.span }
792 } else {
793 TypeMismatchReason::PreviousUse { span: self.span }
794 };
795 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
796 self_ty: self.ty,
797 other_ty: other.ty,
798 other_span: other.span,
799 sub: sub_diag,
800 }))
801 }
802
803 #[instrument(level = "debug", skip(tcx), ret)]
804 pub fn remap_generic_params_to_declaration_params(
805 self,
806 opaque_type_key: OpaqueTypeKey<'tcx>,
807 tcx: TyCtxt<'tcx>,
808 ignore_errors: bool,
810 ) -> Self {
811 let OpaqueTypeKey { def_id, args } = opaque_type_key;
812
813 let id_args = GenericArgs::identity_for_item(tcx, def_id);
820 debug!(?id_args);
821
822 let map = args.iter().zip(id_args).collect();
826 debug!("map = {:#?}", map);
827
828 self.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span, ignore_errors))
832 }
833}
834
835#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
840#[derive(HashStable, TyEncodable, TyDecodable)]
841pub struct Placeholder<T> {
842 pub universe: UniverseIndex,
843 pub bound: T,
844}
845impl Placeholder<BoundVar> {
846 pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
847 let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
848 match clause.kind().skip_binder() {
850 ty::ClauseKind::ConstArgHasType(placeholder_ct, ty) => {
851 assert!(!(placeholder_ct, ty).has_escaping_bound_vars());
852
853 match placeholder_ct.kind() {
854 ty::ConstKind::Placeholder(placeholder_ct) if placeholder_ct == self => {
855 Some(ty)
856 }
857 _ => None,
858 }
859 }
860 _ => None,
861 }
862 });
863
864 let ty = candidates.next().unwrap();
865 assert!(candidates.next().is_none());
866 ty
867 }
868}
869
870pub type PlaceholderRegion = Placeholder<BoundRegion>;
871
872impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderRegion {
873 fn universe(self) -> UniverseIndex {
874 self.universe
875 }
876
877 fn var(self) -> BoundVar {
878 self.bound.var
879 }
880
881 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
882 Placeholder { universe: ui, ..self }
883 }
884
885 fn new(ui: UniverseIndex, var: BoundVar) -> Self {
886 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
887 }
888}
889
890pub type PlaceholderType = Placeholder<BoundTy>;
891
892impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderType {
893 fn universe(self) -> UniverseIndex {
894 self.universe
895 }
896
897 fn var(self) -> BoundVar {
898 self.bound.var
899 }
900
901 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
902 Placeholder { universe: ui, ..self }
903 }
904
905 fn new(ui: UniverseIndex, var: BoundVar) -> Self {
906 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
907 }
908}
909
910#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
911#[derive(TyEncodable, TyDecodable)]
912pub struct BoundConst<'tcx> {
913 pub var: BoundVar,
914 pub ty: Ty<'tcx>,
915}
916
917pub type PlaceholderConst = Placeholder<BoundVar>;
918
919impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderConst {
920 fn universe(self) -> UniverseIndex {
921 self.universe
922 }
923
924 fn var(self) -> BoundVar {
925 self.bound
926 }
927
928 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
929 Placeholder { universe: ui, ..self }
930 }
931
932 fn new(ui: UniverseIndex, var: BoundVar) -> Self {
933 Placeholder { universe: ui, bound: var }
934 }
935}
936
937pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
938
939impl<'tcx> rustc_type_ir::visit::Flags for Clauses<'tcx> {
940 fn flags(&self) -> TypeFlags {
941 (**self).flags()
942 }
943
944 fn outer_exclusive_binder(&self) -> DebruijnIndex {
945 (**self).outer_exclusive_binder()
946 }
947}
948
949#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
955#[derive(HashStable, TypeVisitable, TypeFoldable)]
956pub struct ParamEnv<'tcx> {
957 caller_bounds: Clauses<'tcx>,
963}
964
965impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
966 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
967 self.caller_bounds()
968 }
969}
970
971impl<'tcx> ParamEnv<'tcx> {
972 #[inline]
979 pub fn empty() -> Self {
980 Self::new(ListWithCachedTypeInfo::empty())
981 }
982
983 #[inline]
984 pub fn caller_bounds(self) -> Clauses<'tcx> {
985 self.caller_bounds
986 }
987
988 #[inline]
990 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
991 ParamEnv { caller_bounds }
992 }
993
994 #[inline]
996 pub fn without_caller_bounds(self) -> Self {
997 Self::new(ListWithCachedTypeInfo::empty())
998 }
999
1000 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1002 ParamEnvAnd { param_env: self, value }
1003 }
1004}
1005
1006#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1007#[derive(HashStable)]
1008pub struct ParamEnvAnd<'tcx, T> {
1009 pub param_env: ParamEnv<'tcx>,
1010 pub value: T,
1011}
1012
1013impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1014 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1015 (self.param_env, self.value)
1016 }
1017}
1018
1019#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1030#[derive(TypeVisitable, TypeFoldable)]
1031pub struct TypingEnv<'tcx> {
1032 pub typing_mode: TypingMode<'tcx>,
1033 pub param_env: ParamEnv<'tcx>,
1034}
1035
1036impl<'tcx> TypingEnv<'tcx> {
1037 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1045 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1046 }
1047
1048 pub fn non_body_analysis(
1054 tcx: TyCtxt<'tcx>,
1055 def_id: impl IntoQueryParam<DefId>,
1056 ) -> TypingEnv<'tcx> {
1057 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1058 }
1059
1060 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1061 TypingEnv {
1062 typing_mode: TypingMode::PostAnalysis,
1063 param_env: tcx.param_env_normalized_for_post_analysis(def_id),
1064 }
1065 }
1066
1067 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1070 let TypingEnv { typing_mode, param_env } = self;
1071 if let TypingMode::PostAnalysis = typing_mode {
1072 return self;
1073 }
1074
1075 let param_env = if tcx.next_trait_solver_globally() {
1078 ParamEnv::new(param_env.caller_bounds())
1079 } else {
1080 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1081 };
1082 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1083 }
1084
1085 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1090 where
1091 T: TypeVisitable<TyCtxt<'tcx>>,
1092 {
1093 PseudoCanonicalInput { typing_env: self, value }
1102 }
1103}
1104
1105#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1115#[derive(HashStable, TypeVisitable, TypeFoldable)]
1116pub struct PseudoCanonicalInput<'tcx, T> {
1117 pub typing_env: TypingEnv<'tcx>,
1118 pub value: T,
1119}
1120
1121#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1122pub struct Destructor {
1123 pub did: DefId,
1125 pub constness: hir::Constness,
1127}
1128
1129#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1131pub struct AsyncDestructor {
1132 pub ctor: DefId,
1134 pub future: DefId,
1136}
1137
1138#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1139pub struct VariantFlags(u8);
1140bitflags::bitflags! {
1141 impl VariantFlags: u8 {
1142 const NO_VARIANT_FLAGS = 0;
1143 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1145 }
1146}
1147rustc_data_structures::external_bitflags_debug! { VariantFlags }
1148
1149#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1151pub struct VariantDef {
1152 pub def_id: DefId,
1155 pub ctor: Option<(CtorKind, DefId)>,
1158 pub name: Symbol,
1160 pub discr: VariantDiscr,
1162 pub fields: IndexVec<FieldIdx, FieldDef>,
1164 tainted: Option<ErrorGuaranteed>,
1166 flags: VariantFlags,
1168}
1169
1170impl VariantDef {
1171 pub fn new(
1188 name: Symbol,
1189 variant_did: Option<DefId>,
1190 ctor: Option<(CtorKind, DefId)>,
1191 discr: VariantDiscr,
1192 fields: IndexVec<FieldIdx, FieldDef>,
1193 adt_kind: AdtKind,
1194 parent_did: DefId,
1195 recover_tainted: Option<ErrorGuaranteed>,
1196 is_field_list_non_exhaustive: bool,
1197 ) -> Self {
1198 debug!(
1199 "VariantDef::new(name = {:?}, variant_did = {:?}, ctor = {:?}, discr = {:?},
1200 fields = {:?}, adt_kind = {:?}, parent_did = {:?})",
1201 name, variant_did, ctor, discr, fields, adt_kind, parent_did,
1202 );
1203
1204 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1205 if is_field_list_non_exhaustive {
1206 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1207 }
1208
1209 VariantDef {
1210 def_id: variant_did.unwrap_or(parent_did),
1211 ctor,
1212 name,
1213 discr,
1214 fields,
1215 flags,
1216 tainted: recover_tainted,
1217 }
1218 }
1219
1220 #[inline]
1222 pub fn is_field_list_non_exhaustive(&self) -> bool {
1223 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1224 }
1225
1226 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1228 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1229 }
1230
1231 #[inline]
1233 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1234 self.tainted.map_or(Ok(()), Err)
1235 }
1236
1237 #[inline]
1238 pub fn ctor_kind(&self) -> Option<CtorKind> {
1239 self.ctor.map(|(kind, _)| kind)
1240 }
1241
1242 #[inline]
1243 pub fn ctor_def_id(&self) -> Option<DefId> {
1244 self.ctor.map(|(_, def_id)| def_id)
1245 }
1246
1247 #[inline]
1251 pub fn single_field(&self) -> &FieldDef {
1252 assert!(self.fields.len() == 1);
1253
1254 &self.fields[FieldIdx::ZERO]
1255 }
1256
1257 #[inline]
1259 pub fn tail_opt(&self) -> Option<&FieldDef> {
1260 self.fields.raw.last()
1261 }
1262
1263 #[inline]
1269 pub fn tail(&self) -> &FieldDef {
1270 self.tail_opt().expect("expected unsized ADT to have a tail field")
1271 }
1272
1273 pub fn has_unsafe_fields(&self) -> bool {
1275 self.fields.iter().any(|x| x.safety.is_unsafe())
1276 }
1277}
1278
1279impl PartialEq for VariantDef {
1280 #[inline]
1281 fn eq(&self, other: &Self) -> bool {
1282 let Self {
1290 def_id: lhs_def_id,
1291 ctor: _,
1292 name: _,
1293 discr: _,
1294 fields: _,
1295 flags: _,
1296 tainted: _,
1297 } = &self;
1298 let Self {
1299 def_id: rhs_def_id,
1300 ctor: _,
1301 name: _,
1302 discr: _,
1303 fields: _,
1304 flags: _,
1305 tainted: _,
1306 } = other;
1307
1308 let res = lhs_def_id == rhs_def_id;
1309
1310 if cfg!(debug_assertions) && res {
1312 let deep = self.ctor == other.ctor
1313 && self.name == other.name
1314 && self.discr == other.discr
1315 && self.fields == other.fields
1316 && self.flags == other.flags;
1317 assert!(deep, "VariantDef for the same def-id has differing data");
1318 }
1319
1320 res
1321 }
1322}
1323
1324impl Eq for VariantDef {}
1325
1326impl Hash for VariantDef {
1327 #[inline]
1328 fn hash<H: Hasher>(&self, s: &mut H) {
1329 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1337 def_id.hash(s)
1338 }
1339}
1340
1341#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1342pub enum VariantDiscr {
1343 Explicit(DefId),
1346
1347 Relative(u32),
1352}
1353
1354#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1355pub struct FieldDef {
1356 pub did: DefId,
1357 pub name: Symbol,
1358 pub vis: Visibility<DefId>,
1359 pub safety: hir::Safety,
1360 pub value: Option<DefId>,
1361}
1362
1363impl PartialEq for FieldDef {
1364 #[inline]
1365 fn eq(&self, other: &Self) -> bool {
1366 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1374
1375 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1376
1377 let res = lhs_did == rhs_did;
1378
1379 if cfg!(debug_assertions) && res {
1381 let deep =
1382 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1383 assert!(deep, "FieldDef for the same def-id has differing data");
1384 }
1385
1386 res
1387 }
1388}
1389
1390impl Eq for FieldDef {}
1391
1392impl Hash for FieldDef {
1393 #[inline]
1394 fn hash<H: Hasher>(&self, s: &mut H) {
1395 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1403
1404 did.hash(s)
1405 }
1406}
1407
1408impl<'tcx> FieldDef {
1409 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1412 tcx.type_of(self.did).instantiate(tcx, args)
1413 }
1414
1415 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1417 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1418 }
1419}
1420
1421#[derive(Debug, PartialEq, Eq)]
1422pub enum ImplOverlapKind {
1423 Permitted {
1425 marker: bool,
1427 },
1428 FutureCompatOrderDepTraitObjects,
1461}
1462
1463#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1466pub enum ImplTraitInTraitData {
1467 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1468 Impl { fn_def_id: DefId },
1469}
1470
1471impl<'tcx> TyCtxt<'tcx> {
1472 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1473 self.typeck(self.hir().body_owner_def_id(body))
1474 }
1475
1476 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1477 self.associated_items(id)
1478 .in_definition_order()
1479 .filter(move |item| item.kind == AssocKind::Fn && item.defaultness(self).has_value())
1480 }
1481
1482 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1483 let mut flags = ReprFlags::empty();
1484 let mut size = None;
1485 let mut max_align: Option<Align> = None;
1486 let mut min_pack: Option<Align> = None;
1487
1488 let mut field_shuffle_seed =
1491 self.def_path_hash(did.to_def_id()).0.to_smaller_hash().as_u64();
1492
1493 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1497 field_shuffle_seed ^= user_seed;
1498 }
1499
1500 for attr in self.get_attrs(did, sym::repr) {
1501 for r in attr::parse_repr_attr(self.sess, attr) {
1502 flags.insert(match r {
1503 attr::ReprRust => ReprFlags::empty(),
1504 attr::ReprC => ReprFlags::IS_C,
1505 attr::ReprPacked(pack) => {
1506 min_pack = Some(if let Some(min_pack) = min_pack {
1507 min_pack.min(pack)
1508 } else {
1509 pack
1510 });
1511 ReprFlags::empty()
1512 }
1513 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1514 attr::ReprSimd => ReprFlags::IS_SIMD,
1515 attr::ReprInt(i) => {
1516 size = Some(match i {
1517 attr::IntType::SignedInt(x) => match x {
1518 ast::IntTy::Isize => IntegerType::Pointer(true),
1519 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1520 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1521 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1522 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1523 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1524 },
1525 attr::IntType::UnsignedInt(x) => match x {
1526 ast::UintTy::Usize => IntegerType::Pointer(false),
1527 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1528 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1529 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1530 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1531 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1532 },
1533 });
1534 ReprFlags::empty()
1535 }
1536 attr::ReprAlign(align) => {
1537 max_align = max_align.max(Some(align));
1538 ReprFlags::empty()
1539 }
1540 });
1541 }
1542 }
1543
1544 if self.sess.opts.unstable_opts.randomize_layout {
1547 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1548 }
1549
1550 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1553
1554 if is_box {
1556 flags.insert(ReprFlags::IS_LINEAR);
1557 }
1558
1559 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1560 }
1561
1562 pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
1564 if let Some(cnum) = def_id.as_crate_root() {
1565 Some(self.crate_name(cnum))
1566 } else {
1567 let def_key = self.def_key(def_id);
1568 match def_key.disambiguated_data.data {
1569 rustc_hir::definitions::DefPathData::Ctor => self
1571 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1572 _ => def_key.get_opt_name(),
1573 }
1574 }
1575 }
1576
1577 pub fn item_name(self, id: DefId) -> Symbol {
1584 self.opt_item_name(id).unwrap_or_else(|| {
1585 bug!("item_name: no name for {:?}", self.def_path(id));
1586 })
1587 }
1588
1589 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
1593 let def = self.opt_item_name(def_id)?;
1594 let span = self
1595 .def_ident_span(def_id)
1596 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1597 Some(Ident::new(def, span))
1598 }
1599
1600 pub fn item_ident(self, def_id: DefId) -> Ident {
1604 self.opt_item_ident(def_id).unwrap_or_else(|| {
1605 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1606 })
1607 }
1608
1609 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1610 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1611 Some(self.associated_item(def_id))
1612 } else {
1613 None
1614 }
1615 }
1616
1617 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1621 if let DefKind::AssocTy = self.def_kind(def_id) {
1622 self.associated_item(def_id).opt_rpitit_info
1623 } else {
1624 None
1625 }
1626 }
1627
1628 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1629 variant.fields.iter_enumerated().find_map(|(i, field)| {
1630 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1631 })
1632 }
1633
1634 #[instrument(level = "debug", skip(self), ret)]
1637 pub fn impls_are_allowed_to_overlap(
1638 self,
1639 def_id1: DefId,
1640 def_id2: DefId,
1641 ) -> Option<ImplOverlapKind> {
1642 let impl1 = self.impl_trait_header(def_id1).unwrap();
1643 let impl2 = self.impl_trait_header(def_id2).unwrap();
1644
1645 let trait_ref1 = impl1.trait_ref.skip_binder();
1646 let trait_ref2 = impl2.trait_ref.skip_binder();
1647
1648 if trait_ref1.references_error() || trait_ref2.references_error() {
1651 return Some(ImplOverlapKind::Permitted { marker: false });
1652 }
1653
1654 match (impl1.polarity, impl2.polarity) {
1655 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1656 return Some(ImplOverlapKind::Permitted { marker: false });
1658 }
1659 (ImplPolarity::Positive, ImplPolarity::Negative)
1660 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1661 return None;
1663 }
1664 (ImplPolarity::Positive, ImplPolarity::Positive)
1665 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1666 };
1667
1668 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1669 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1670
1671 if is_marker_overlap {
1672 return Some(ImplOverlapKind::Permitted { marker: true });
1673 }
1674
1675 if let Some(self_ty1) =
1676 self.self_ty_of_trait_impl_enabling_order_dep_trait_object_hack(def_id1)
1677 && let Some(self_ty2) =
1678 self.self_ty_of_trait_impl_enabling_order_dep_trait_object_hack(def_id2)
1679 {
1680 if self_ty1 == self_ty2 {
1681 return Some(ImplOverlapKind::FutureCompatOrderDepTraitObjects);
1682 } else {
1683 debug!("found {self_ty1:?} != {self_ty2:?}");
1684 }
1685 }
1686
1687 None
1688 }
1689
1690 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1693 match res {
1694 Res::Def(DefKind::Variant, did) => {
1695 let enum_did = self.parent(did);
1696 self.adt_def(enum_did).variant_with_id(did)
1697 }
1698 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1699 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1700 let variant_did = self.parent(variant_ctor_did);
1701 let enum_did = self.parent(variant_did);
1702 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1703 }
1704 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1705 let struct_did = self.parent(ctor_did);
1706 self.adt_def(struct_did).non_enum_variant()
1707 }
1708 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1709 }
1710 }
1711
1712 #[instrument(skip(self), level = "debug")]
1714 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1715 match instance {
1716 ty::InstanceKind::Item(def) => {
1717 debug!("calling def_kind on def: {:?}", def);
1718 let def_kind = self.def_kind(def);
1719 debug!("returned from def_kind: {:?}", def_kind);
1720 match def_kind {
1721 DefKind::Const
1722 | DefKind::Static { .. }
1723 | DefKind::AssocConst
1724 | DefKind::Ctor(..)
1725 | DefKind::AnonConst
1726 | DefKind::InlineConst => self.mir_for_ctfe(def),
1727 _ => self.optimized_mir(def),
1730 }
1731 }
1732 ty::InstanceKind::VTableShim(..)
1733 | ty::InstanceKind::ReifyShim(..)
1734 | ty::InstanceKind::Intrinsic(..)
1735 | ty::InstanceKind::FnPtrShim(..)
1736 | ty::InstanceKind::Virtual(..)
1737 | ty::InstanceKind::ClosureOnceShim { .. }
1738 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1739 | ty::InstanceKind::DropGlue(..)
1740 | ty::InstanceKind::CloneShim(..)
1741 | ty::InstanceKind::ThreadLocalShim(..)
1742 | ty::InstanceKind::FnPtrAddrShim(..)
1743 | ty::InstanceKind::AsyncDropGlueCtorShim(..) => self.mir_shims(instance),
1744 }
1745 }
1746
1747 pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [hir::Attribute] {
1749 if let Some(did) = did.as_local() {
1750 self.hir().attrs(self.local_def_id_to_hir_id(did))
1751 } else {
1752 self.attrs_for_def(did)
1753 }
1754 }
1755
1756 pub fn get_attrs(
1758 self,
1759 did: impl Into<DefId>,
1760 attr: Symbol,
1761 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1762 let did: DefId = did.into();
1763 let filter_fn = move |a: &&hir::Attribute| a.has_name(attr);
1764 if let Some(did) = did.as_local() {
1765 self.hir().attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1766 } else {
1767 debug_assert!(rustc_feature::encode_cross_crate(attr));
1768 self.attrs_for_def(did).iter().filter(filter_fn)
1769 }
1770 }
1771
1772 pub fn get_diagnostic_attr(
1781 self,
1782 did: impl Into<DefId>,
1783 attr: Symbol,
1784 ) -> Option<&'tcx hir::Attribute> {
1785 let did: DefId = did.into();
1786 if did.as_local().is_some() {
1787 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1789 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1790 } else {
1791 None
1792 }
1793 } else {
1794 debug_assert!(rustc_feature::encode_cross_crate(attr));
1797 self.attrs_for_def(did)
1798 .iter()
1799 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1800 }
1801 }
1802
1803 pub fn get_attrs_by_path<'attr>(
1804 self,
1805 did: DefId,
1806 attr: &'attr [Symbol],
1807 ) -> impl Iterator<Item = &'tcx hir::Attribute> + 'attr
1808 where
1809 'tcx: 'attr,
1810 {
1811 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1812 if let Some(did) = did.as_local() {
1813 self.hir().attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1814 } else {
1815 self.attrs_for_def(did).iter().filter(filter_fn)
1816 }
1817 }
1818
1819 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1820 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1821 let did: DefId = did.into();
1822 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1823 } else {
1824 self.get_attrs(did, attr).next()
1825 }
1826 }
1827
1828 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1830 self.get_attrs(did, attr).next().is_some()
1831 }
1832
1833 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1835 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1836 }
1837
1838 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1840 self.trait_def(trait_def_id).has_auto_impl
1841 }
1842
1843 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1846 self.trait_def(trait_def_id).is_coinductive
1847 }
1848
1849 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1851 self.def_kind(trait_def_id) == DefKind::TraitAlias
1852 }
1853
1854 pub fn coroutine_layout(
1860 self,
1861 def_id: DefId,
1862 coroutine_kind_ty: Ty<'tcx>,
1863 ) -> Option<&'tcx CoroutineLayout<'tcx>> {
1864 let mir = self.optimized_mir(def_id);
1865 if coroutine_kind_ty.is_unit() {
1867 mir.coroutine_layout_raw()
1868 } else {
1869 let ty::Coroutine(_, identity_args) =
1872 *self.type_of(def_id).instantiate_identity().kind()
1873 else {
1874 unreachable!();
1875 };
1876 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1877 if identity_kind_ty == coroutine_kind_ty {
1880 mir.coroutine_layout_raw()
1881 } else {
1882 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1883 assert_matches!(
1884 identity_kind_ty.to_opt_closure_kind(),
1885 Some(ClosureKind::Fn | ClosureKind::FnMut)
1886 );
1887 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1888 .coroutine_layout_raw()
1889 }
1890 }
1891 }
1892
1893 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1896 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1897 }
1898
1899 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
1903 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1904 let parent = self.parent(def_id);
1905 if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
1906 return Some(parent);
1907 }
1908 }
1909 None
1910 }
1911
1912 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
1915 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1916 let parent = self.parent(def_id);
1917 if let DefKind::Impl { .. } = self.def_kind(parent) {
1918 return Some(parent);
1919 }
1920 }
1921 None
1922 }
1923
1924 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1927 if self.is_automatically_derived(def_id)
1928 && let Some(def_id) = def_id.as_local()
1929 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1930 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1931 && self.has_attr(outer.macro_def_id.unwrap(), sym::rustc_builtin_macro)
1932 {
1933 true
1934 } else {
1935 false
1936 }
1937 }
1938
1939 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1941 self.has_attr(def_id, sym::automatically_derived)
1942 }
1943
1944 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
1947 if let Some(impl_def_id) = impl_def_id.as_local() {
1948 Ok(self.def_span(impl_def_id))
1949 } else {
1950 Err(self.crate_name(impl_def_id.krate))
1951 }
1952 }
1953
1954 pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
1958 use_name.name == def_name.name
1962 && use_name
1963 .span
1964 .ctxt()
1965 .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id))
1966 }
1967
1968 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
1969 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
1970 ident
1971 }
1972
1973 pub fn adjust_ident_and_get_scope(
1975 self,
1976 mut ident: Ident,
1977 scope: DefId,
1978 block: hir::HirId,
1979 ) -> (Ident, DefId) {
1980 let scope = ident
1981 .span
1982 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
1983 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
1984 .unwrap_or_else(|| self.parent_module(block).to_def_id());
1985 (ident, scope)
1986 }
1987
1988 #[inline]
1992 pub fn is_const_fn(self, def_id: DefId) -> bool {
1993 matches!(
1994 self.def_kind(def_id),
1995 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
1996 ) && self.constness(def_id) == hir::Constness::Const
1997 }
1998
1999 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2006 let def_id: DefId = def_id.into();
2007 match self.def_kind(def_id) {
2008 DefKind::Impl { of_trait: true } => {
2009 let header = self.impl_trait_header(def_id).unwrap();
2010 header.constness == hir::Constness::Const
2011 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2012 }
2013 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2014 self.constness(def_id) == hir::Constness::Const
2015 }
2016 DefKind::Trait => self.is_const_trait(def_id),
2017 DefKind::AssocTy => {
2018 let parent_def_id = self.parent(def_id);
2019 match self.def_kind(parent_def_id) {
2020 DefKind::Impl { of_trait: false } => false,
2021 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2022 self.is_conditionally_const(parent_def_id)
2023 }
2024 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2025 }
2026 }
2027 DefKind::AssocFn => {
2028 let parent_def_id = self.parent(def_id);
2029 match self.def_kind(parent_def_id) {
2030 DefKind::Impl { of_trait: false } => {
2031 self.constness(def_id) == hir::Constness::Const
2032 }
2033 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2034 self.is_conditionally_const(parent_def_id)
2035 }
2036 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2037 }
2038 }
2039 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2040 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2041 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2042 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2044 },
2045 DefKind::Closure => {
2046 false
2049 }
2050 DefKind::Ctor(_, CtorKind::Const)
2051 | DefKind::Impl { of_trait: false }
2052 | DefKind::Mod
2053 | DefKind::Struct
2054 | DefKind::Union
2055 | DefKind::Enum
2056 | DefKind::Variant
2057 | DefKind::TyAlias
2058 | DefKind::ForeignTy
2059 | DefKind::TraitAlias
2060 | DefKind::TyParam
2061 | DefKind::Const
2062 | DefKind::ConstParam
2063 | DefKind::Static { .. }
2064 | DefKind::AssocConst
2065 | DefKind::Macro(_)
2066 | DefKind::ExternCrate
2067 | DefKind::Use
2068 | DefKind::ForeignMod
2069 | DefKind::AnonConst
2070 | DefKind::InlineConst
2071 | DefKind::Field
2072 | DefKind::LifetimeParam
2073 | DefKind::GlobalAsm
2074 | DefKind::SyntheticCoroutineBody => false,
2075 }
2076 }
2077
2078 #[inline]
2079 pub fn is_const_trait(self, def_id: DefId) -> bool {
2080 self.trait_def(def_id).constness == hir::Constness::Const
2081 }
2082
2083 #[inline]
2084 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2085 matches!(self.trait_of_item(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2086 }
2087
2088 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2089 if self.def_kind(def_id) != DefKind::AssocFn {
2090 return false;
2091 }
2092
2093 let Some(item) = self.opt_associated_item(def_id) else {
2094 return false;
2095 };
2096 if item.container != ty::AssocItemContainer::Impl {
2097 return false;
2098 }
2099
2100 let Some(trait_item_def_id) = item.trait_item_def_id else {
2101 return false;
2102 };
2103
2104 return !self
2105 .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id)
2106 .is_empty();
2107 }
2108}
2109
2110pub fn int_ty(ity: ast::IntTy) -> IntTy {
2111 match ity {
2112 ast::IntTy::Isize => IntTy::Isize,
2113 ast::IntTy::I8 => IntTy::I8,
2114 ast::IntTy::I16 => IntTy::I16,
2115 ast::IntTy::I32 => IntTy::I32,
2116 ast::IntTy::I64 => IntTy::I64,
2117 ast::IntTy::I128 => IntTy::I128,
2118 }
2119}
2120
2121pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2122 match uty {
2123 ast::UintTy::Usize => UintTy::Usize,
2124 ast::UintTy::U8 => UintTy::U8,
2125 ast::UintTy::U16 => UintTy::U16,
2126 ast::UintTy::U32 => UintTy::U32,
2127 ast::UintTy::U64 => UintTy::U64,
2128 ast::UintTy::U128 => UintTy::U128,
2129 }
2130}
2131
2132pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2133 match fty {
2134 ast::FloatTy::F16 => FloatTy::F16,
2135 ast::FloatTy::F32 => FloatTy::F32,
2136 ast::FloatTy::F64 => FloatTy::F64,
2137 ast::FloatTy::F128 => FloatTy::F128,
2138 }
2139}
2140
2141pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2142 match ity {
2143 IntTy::Isize => ast::IntTy::Isize,
2144 IntTy::I8 => ast::IntTy::I8,
2145 IntTy::I16 => ast::IntTy::I16,
2146 IntTy::I32 => ast::IntTy::I32,
2147 IntTy::I64 => ast::IntTy::I64,
2148 IntTy::I128 => ast::IntTy::I128,
2149 }
2150}
2151
2152pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2153 match uty {
2154 UintTy::Usize => ast::UintTy::Usize,
2155 UintTy::U8 => ast::UintTy::U8,
2156 UintTy::U16 => ast::UintTy::U16,
2157 UintTy::U32 => ast::UintTy::U32,
2158 UintTy::U64 => ast::UintTy::U64,
2159 UintTy::U128 => ast::UintTy::U128,
2160 }
2161}
2162
2163pub fn provide(providers: &mut Providers) {
2164 closure::provide(providers);
2165 context::provide(providers);
2166 erase_regions::provide(providers);
2167 inhabitedness::provide(providers);
2168 util::provide(providers);
2169 print::provide(providers);
2170 super::util::bug::provide(providers);
2171 super::middle::provide(providers);
2172 *providers = Providers {
2173 trait_impls_of: trait_def::trait_impls_of_provider,
2174 incoherent_impls: trait_def::incoherent_impls_provider,
2175 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2176 traits: trait_def::traits_provider,
2177 vtable_allocation: vtable::vtable_allocation_provider,
2178 ..*providers
2179 };
2180}
2181
2182#[derive(Clone, Debug, Default, HashStable)]
2188pub struct CrateInherentImpls {
2189 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2190 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2191}
2192
2193#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2194pub struct SymbolName<'tcx> {
2195 pub name: &'tcx str,
2197}
2198
2199impl<'tcx> SymbolName<'tcx> {
2200 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2201 SymbolName { name: tcx.arena.alloc_str(name) }
2202 }
2203}
2204
2205impl<'tcx> fmt::Display for SymbolName<'tcx> {
2206 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2207 fmt::Display::fmt(&self.name, fmt)
2208 }
2209}
2210
2211impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2212 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2213 fmt::Display::fmt(&self.name, fmt)
2214 }
2215}
2216
2217#[derive(Debug, Default, Copy, Clone)]
2218pub struct InferVarInfo {
2219 pub self_in_trait: bool,
2225 pub output: bool,
2228}
2229
2230#[derive(Copy, Clone, Debug, HashStable)]
2232pub struct DestructuredConst<'tcx> {
2233 pub variant: Option<VariantIdx>,
2234 pub fields: &'tcx [ty::Const<'tcx>],
2235}
2236
2237#[cfg(target_pointer_width = "64")]
2239mod size_asserts {
2240 use rustc_data_structures::static_assert_size;
2241
2242 use super::*;
2243 static_assert_size!(PredicateKind<'_>, 32);
2245 static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 48);
2246 }