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, 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_attr_data_structures::AttributeKind;
32use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
33use rustc_data_structures::intern::Interned;
34use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
35use rustc_data_structures::steal::Steal;
36use rustc_data_structures::unord::UnordMap;
37use rustc_errors::{Diag, ErrorGuaranteed};
38use rustc_hir::LangItem;
39use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
40use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
41use rustc_index::IndexVec;
42use rustc_macros::{
43 Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
44 extension,
45};
46use rustc_query_system::ich::StableHashingContext;
47use rustc_serialize::{Decodable, Encodable};
48use rustc_session::lint::LintBuffer;
49pub use rustc_session::lint::RegisteredTools;
50use rustc_span::hygiene::MacroKind;
51use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, kw, sym};
52pub use rustc_type_ir::relate::VarianceDiagInfo;
53pub use rustc_type_ir::*;
54use tracing::{debug, instrument};
55pub use vtable::*;
56use {rustc_ast as ast, rustc_attr_data_structures as attr, rustc_hir as hir};
57
58pub use self::closure::{
59 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
60 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
61 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
62 place_to_string_for_capture,
63};
64pub use self::consts::{
65 Const, ConstInt, ConstKind, Expr, ExprKind, ScalarInt, UnevaluatedConst, ValTree, ValTreeKind,
66 Value,
67};
68pub use self::context::{
69 CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
70 TyCtxtFeed, tls,
71};
72pub use self::fold::*;
73pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams};
74pub use self::list::{List, ListWithCachedTypeInfo};
75pub use self::opaque_types::OpaqueTypeKey;
76pub use self::parameterized::ParameterizedOverTcx;
77pub use self::pattern::{Pattern, PatternKind};
78pub use self::predicate::{
79 AliasTerm, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
80 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
81 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
82 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
83 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
84 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
85 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
86};
87pub use self::region::{
88 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
89 RegionKind, RegionVid,
90};
91pub use self::rvalue_scopes::RvalueScopes;
92pub use self::sty::{
93 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
94 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
95 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
96};
97pub use self::trait_def::TraitDef;
98pub use self::typeck_results::{
99 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
100 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
101};
102pub use self::visit::*;
103use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
104use crate::metadata::ModChild;
105use crate::middle::privacy::EffectiveVisibilities;
106use crate::mir::{Body, CoroutineLayout};
107use crate::query::{IntoQueryParam, Providers};
108use crate::ty;
109use crate::ty::codec::{TyDecoder, TyEncoder};
110pub use crate::ty::diagnostics::*;
111use crate::ty::fast_reject::SimplifiedType;
112use crate::ty::util::Discr;
113
114pub mod abstract_const;
115pub mod adjustment;
116pub mod cast;
117pub mod codec;
118pub mod error;
119pub mod fast_reject;
120pub mod inhabitedness;
121pub mod layout;
122pub mod normalize_erasing_regions;
123pub mod pattern;
124pub mod print;
125pub mod relate;
126pub mod significant_drop_order;
127pub mod trait_def;
128pub mod util;
129pub mod vtable;
130
131mod adt;
132mod assoc;
133mod closure;
134mod consts;
135mod context;
136mod diagnostics;
137mod elaborate_impl;
138mod erase_regions;
139mod fold;
140mod generic_args;
141mod generics;
142mod impls_ty;
143mod instance;
144mod intrinsic;
145mod list;
146mod opaque_types;
147mod parameterized;
148mod predicate;
149mod region;
150mod rvalue_scopes;
151mod structural_impls;
152#[allow(hidden_glob_reexports)]
153mod sty;
154mod typeck_results;
155mod visit;
156
157pub struct ResolverOutputs {
160 pub global_ctxt: ResolverGlobalCtxt,
161 pub ast_lowering: ResolverAstLowering,
162}
163
164#[derive(Debug)]
165pub struct ResolverGlobalCtxt {
166 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
167 pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
169 pub effective_visibilities: EffectiveVisibilities,
170 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
171 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
172 pub module_children: LocalDefIdMap<Vec<ModChild>>,
173 pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
174 pub main_def: Option<MainDefinition>,
175 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
176 pub proc_macros: Vec<LocalDefId>,
179 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
182 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
183 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
184 pub all_macro_rules: FxHashSet<Symbol>,
185 pub stripped_cfg_items: Steal<Vec<StrippedCfgItem>>,
186}
187
188#[derive(Debug)]
191pub struct ResolverAstLowering {
192 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
193
194 pub partial_res_map: NodeMap<hir::def::PartialRes>,
196 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
198 pub label_res_map: NodeMap<ast::NodeId>,
200 pub lifetimes_res_map: NodeMap<LifetimeRes>,
202 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
204
205 pub next_node_id: ast::NodeId,
206
207 pub node_id_to_def_id: NodeMap<LocalDefId>,
208
209 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
210 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
212
213 pub lint_buffer: Steal<LintBuffer>,
215
216 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
218}
219
220#[derive(Debug)]
221pub struct DelegationFnSig {
222 pub header: ast::FnHeader,
223 pub param_count: usize,
224 pub has_self: bool,
225 pub c_variadic: bool,
226 pub target_feature: bool,
227}
228
229#[derive(Clone, Copy, Debug)]
230pub struct MainDefinition {
231 pub res: Res<ast::NodeId>,
232 pub is_import: bool,
233 pub span: Span,
234}
235
236impl MainDefinition {
237 pub fn opt_fn_def_id(self) -> Option<DefId> {
238 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
239 }
240}
241
242#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
246pub struct ImplHeader<'tcx> {
247 pub impl_def_id: DefId,
248 pub impl_args: ty::GenericArgsRef<'tcx>,
249 pub self_ty: Ty<'tcx>,
250 pub trait_ref: Option<TraitRef<'tcx>>,
251 pub predicates: Vec<Predicate<'tcx>>,
252}
253
254#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
255pub struct ImplTraitHeader<'tcx> {
256 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
257 pub polarity: ImplPolarity,
258 pub safety: hir::Safety,
259 pub constness: hir::Constness,
260}
261
262#[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
263pub enum ImplSubject<'tcx> {
264 Trait(TraitRef<'tcx>),
265 Inherent(Ty<'tcx>),
266}
267
268#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
269#[derive(TypeFoldable, TypeVisitable)]
270pub enum Asyncness {
271 Yes,
272 No,
273}
274
275impl Asyncness {
276 pub fn is_async(self) -> bool {
277 matches!(self, Asyncness::Yes)
278 }
279}
280
281#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
282pub enum Visibility<Id = LocalDefId> {
283 Public,
285 Restricted(Id),
287}
288
289impl Visibility {
290 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
291 match self {
292 ty::Visibility::Restricted(restricted_id) => {
293 if restricted_id.is_top_level_module() {
294 "pub(crate)".to_string()
295 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
296 "pub(self)".to_string()
297 } else {
298 format!("pub({})", tcx.item_name(restricted_id.to_def_id()))
299 }
300 }
301 ty::Visibility::Public => "pub".to_string(),
302 }
303 }
304}
305
306#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
307#[derive(TypeFoldable, TypeVisitable)]
308pub struct ClosureSizeProfileData<'tcx> {
309 pub before_feature_tys: Ty<'tcx>,
311 pub after_feature_tys: Ty<'tcx>,
313}
314
315impl TyCtxt<'_> {
316 #[inline]
317 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
318 self.def_key(id).parent.map(|index| DefId { index, ..id })
319 }
320
321 #[inline]
322 #[track_caller]
323 pub fn parent(self, id: DefId) -> DefId {
324 match self.opt_parent(id) {
325 Some(id) => id,
326 None => bug!("{id:?} doesn't have a parent"),
328 }
329 }
330
331 #[inline]
332 #[track_caller]
333 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
334 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
335 }
336
337 #[inline]
338 #[track_caller]
339 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
340 self.parent(id.into().to_def_id()).expect_local()
341 }
342
343 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
344 if descendant.krate != ancestor.krate {
345 return false;
346 }
347
348 while descendant != ancestor {
349 match self.opt_parent(descendant) {
350 Some(parent) => descendant = parent,
351 None => return false,
352 }
353 }
354 true
355 }
356}
357
358impl<Id> Visibility<Id> {
359 pub fn is_public(self) -> bool {
360 matches!(self, Visibility::Public)
361 }
362
363 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
364 match self {
365 Visibility::Public => Visibility::Public,
366 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
367 }
368 }
369}
370
371impl<Id: Into<DefId>> Visibility<Id> {
372 pub fn to_def_id(self) -> Visibility<DefId> {
373 self.map_id(Into::into)
374 }
375
376 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
378 match self {
379 Visibility::Public => true,
381 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
382 }
383 }
384
385 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
387 match vis {
388 Visibility::Public => self.is_public(),
389 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
390 }
391 }
392}
393
394impl Visibility<DefId> {
395 pub fn expect_local(self) -> Visibility {
396 self.map_id(|id| id.expect_local())
397 }
398
399 pub fn is_visible_locally(self) -> bool {
401 match self {
402 Visibility::Public => true,
403 Visibility::Restricted(def_id) => def_id.is_local(),
404 }
405 }
406}
407
408#[derive(HashStable, Debug)]
415pub struct CrateVariancesMap<'tcx> {
416 pub variances: DefIdMap<&'tcx [ty::Variance]>,
420}
421
422#[derive(Copy, Clone, PartialEq, Eq, Hash)]
425pub struct CReaderCacheKey {
426 pub cnum: Option<CrateNum>,
427 pub pos: usize,
428}
429
430#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
432#[rustc_diagnostic_item = "Ty"]
433#[rustc_pass_by_value]
434pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
435
436impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
437 type Kind = TyKind<'tcx>;
438
439 fn kind(self) -> TyKind<'tcx> {
440 *self.kind()
441 }
442}
443
444impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
445 fn flags(&self) -> TypeFlags {
446 self.0.flags
447 }
448
449 fn outer_exclusive_binder(&self) -> DebruijnIndex {
450 self.0.outer_exclusive_binder
451 }
452}
453
454impl EarlyParamRegion {
455 pub fn has_name(&self) -> bool {
458 self.name != kw::UnderscoreLifetime
459 }
460}
461
462#[derive(HashStable, Debug)]
469pub struct CratePredicatesMap<'tcx> {
470 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
474}
475
476#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
477pub struct Term<'tcx> {
478 ptr: NonNull<()>,
479 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
480}
481
482impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
483
484impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
485 type Kind = TermKind<'tcx>;
486
487 fn kind(self) -> Self::Kind {
488 self.unpack()
489 }
490}
491
492unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
493 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
494{
495}
496unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
497 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
498{
499}
500unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
501unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
502
503impl Debug for Term<'_> {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 match self.unpack() {
506 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
507 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
508 }
509 }
510}
511
512impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
513 fn from(ty: Ty<'tcx>) -> Self {
514 TermKind::Ty(ty).pack()
515 }
516}
517
518impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
519 fn from(c: Const<'tcx>) -> Self {
520 TermKind::Const(c).pack()
521 }
522}
523
524impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
525 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
526 self.unpack().hash_stable(hcx, hasher);
527 }
528}
529
530impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
531 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
532 self,
533 folder: &mut F,
534 ) -> Result<Self, F::Error> {
535 match self.unpack() {
536 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
537 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
538 }
539 }
540
541 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
542 match self.unpack() {
543 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
544 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
545 }
546 }
547}
548
549impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
550 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
551 match self.unpack() {
552 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
553 ty::TermKind::Const(ct) => ct.visit_with(visitor),
554 }
555 }
556}
557
558impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
559 fn encode(&self, e: &mut E) {
560 self.unpack().encode(e)
561 }
562}
563
564impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
565 fn decode(d: &mut D) -> Self {
566 let res: TermKind<'tcx> = Decodable::decode(d);
567 res.pack()
568 }
569}
570
571impl<'tcx> Term<'tcx> {
572 #[inline]
573 pub fn unpack(self) -> TermKind<'tcx> {
574 let ptr =
575 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
576 unsafe {
580 match self.ptr.addr().get() & TAG_MASK {
581 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
582 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
583 ))),
584 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
585 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
586 ))),
587 _ => core::intrinsics::unreachable(),
588 }
589 }
590 }
591
592 pub fn as_type(&self) -> Option<Ty<'tcx>> {
593 if let TermKind::Ty(ty) = self.unpack() { Some(ty) } else { None }
594 }
595
596 pub fn expect_type(&self) -> Ty<'tcx> {
597 self.as_type().expect("expected a type, but found a const")
598 }
599
600 pub fn as_const(&self) -> Option<Const<'tcx>> {
601 if let TermKind::Const(c) = self.unpack() { Some(c) } else { None }
602 }
603
604 pub fn expect_const(&self) -> Const<'tcx> {
605 self.as_const().expect("expected a const, but found a type")
606 }
607
608 pub fn into_arg(self) -> GenericArg<'tcx> {
609 match self.unpack() {
610 TermKind::Ty(ty) => ty.into(),
611 TermKind::Const(c) => c.into(),
612 }
613 }
614
615 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
616 match self.unpack() {
617 TermKind::Ty(ty) => match *ty.kind() {
618 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
619 _ => None,
620 },
621 TermKind::Const(ct) => match ct.kind() {
622 ConstKind::Unevaluated(uv) => Some(uv.into()),
623 _ => None,
624 },
625 }
626 }
627
628 pub fn is_infer(&self) -> bool {
629 match self.unpack() {
630 TermKind::Ty(ty) => ty.is_ty_var(),
631 TermKind::Const(ct) => ct.is_ct_infer(),
632 }
633 }
634}
635
636const TAG_MASK: usize = 0b11;
637const TYPE_TAG: usize = 0b00;
638const CONST_TAG: usize = 0b01;
639
640#[extension(pub trait TermKindPackExt<'tcx>)]
641impl<'tcx> TermKind<'tcx> {
642 #[inline]
643 fn pack(self) -> Term<'tcx> {
644 let (tag, ptr) = match self {
645 TermKind::Ty(ty) => {
646 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
648 (TYPE_TAG, NonNull::from(ty.0.0).cast())
649 }
650 TermKind::Const(ct) => {
651 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
653 (CONST_TAG, NonNull::from(ct.0.0).cast())
654 }
655 };
656
657 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
658 }
659}
660
661#[derive(Copy, Clone, PartialEq, Eq, Debug)]
662pub enum ParamTerm {
663 Ty(ParamTy),
664 Const(ParamConst),
665}
666
667impl ParamTerm {
668 pub fn index(self) -> usize {
669 match self {
670 ParamTerm::Ty(ty) => ty.index as usize,
671 ParamTerm::Const(ct) => ct.index as usize,
672 }
673 }
674}
675
676#[derive(Copy, Clone, Eq, PartialEq, Debug)]
677pub enum TermVid {
678 Ty(ty::TyVid),
679 Const(ty::ConstVid),
680}
681
682impl From<ty::TyVid> for TermVid {
683 fn from(value: ty::TyVid) -> Self {
684 TermVid::Ty(value)
685 }
686}
687
688impl From<ty::ConstVid> for TermVid {
689 fn from(value: ty::ConstVid) -> Self {
690 TermVid::Const(value)
691 }
692}
693
694#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
714pub struct InstantiatedPredicates<'tcx> {
715 pub predicates: Vec<Clause<'tcx>>,
716 pub spans: Vec<Span>,
717}
718
719impl<'tcx> InstantiatedPredicates<'tcx> {
720 pub fn empty() -> InstantiatedPredicates<'tcx> {
721 InstantiatedPredicates { predicates: vec![], spans: vec![] }
722 }
723
724 pub fn is_empty(&self) -> bool {
725 self.predicates.is_empty()
726 }
727
728 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
729 self.into_iter()
730 }
731}
732
733impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
734 type Item = (Clause<'tcx>, Span);
735
736 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
737
738 fn into_iter(self) -> Self::IntoIter {
739 debug_assert_eq!(self.predicates.len(), self.spans.len());
740 std::iter::zip(self.predicates, self.spans)
741 }
742}
743
744impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
745 type Item = (Clause<'tcx>, Span);
746
747 type IntoIter = std::iter::Zip<
748 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
749 std::iter::Copied<std::slice::Iter<'a, Span>>,
750 >;
751
752 fn into_iter(self) -> Self::IntoIter {
753 debug_assert_eq!(self.predicates.len(), self.spans.len());
754 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
755 }
756}
757
758#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
759pub struct OpaqueHiddenType<'tcx> {
760 pub span: Span,
774
775 pub ty: Ty<'tcx>,
788}
789
790#[derive(Debug, Clone, Copy)]
792pub enum DefiningScopeKind {
793 HirTypeck,
798 MirBorrowck,
799}
800
801impl<'tcx> OpaqueHiddenType<'tcx> {
802 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> OpaqueHiddenType<'tcx> {
803 OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
804 }
805
806 pub fn build_mismatch_error(
807 &self,
808 other: &Self,
809 tcx: TyCtxt<'tcx>,
810 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
811 (self.ty, other.ty).error_reported()?;
812 let sub_diag = if self.span == other.span {
814 TypeMismatchReason::ConflictType { span: self.span }
815 } else {
816 TypeMismatchReason::PreviousUse { span: self.span }
817 };
818 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
819 self_ty: self.ty,
820 other_ty: other.ty,
821 other_span: other.span,
822 sub: sub_diag,
823 }))
824 }
825
826 #[instrument(level = "debug", skip(tcx), ret)]
827 pub fn remap_generic_params_to_declaration_params(
828 self,
829 opaque_type_key: OpaqueTypeKey<'tcx>,
830 tcx: TyCtxt<'tcx>,
831 defining_scope_kind: DefiningScopeKind,
832 ) -> Self {
833 let OpaqueTypeKey { def_id, args } = opaque_type_key;
834
835 let id_args = GenericArgs::identity_for_item(tcx, def_id);
842 debug!(?id_args);
843
844 let map = args.iter().zip(id_args).collect();
848 debug!("map = {:#?}", map);
849
850 let this = match defining_scope_kind {
855 DefiningScopeKind::HirTypeck => tcx.erase_regions(self),
856 DefiningScopeKind::MirBorrowck => self,
857 };
858 let result = this.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
859 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
860 assert_eq!(result.ty, tcx.erase_regions(result.ty));
861 }
862 result
863 }
864}
865
866#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
871#[derive(HashStable, TyEncodable, TyDecodable)]
872pub struct Placeholder<T> {
873 pub universe: UniverseIndex,
874 pub bound: T,
875}
876impl Placeholder<BoundVar> {
877 pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
878 let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
879 match clause.kind().skip_binder() {
881 ty::ClauseKind::ConstArgHasType(placeholder_ct, ty) => {
882 assert!(!(placeholder_ct, ty).has_escaping_bound_vars());
883
884 match placeholder_ct.kind() {
885 ty::ConstKind::Placeholder(placeholder_ct) if placeholder_ct == self => {
886 Some(ty)
887 }
888 _ => None,
889 }
890 }
891 _ => None,
892 }
893 });
894
895 let ty = candidates.next().unwrap();
896 assert!(candidates.next().is_none());
897 ty
898 }
899}
900
901pub type PlaceholderRegion = Placeholder<BoundRegion>;
902
903impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderRegion {
904 fn universe(self) -> UniverseIndex {
905 self.universe
906 }
907
908 fn var(self) -> BoundVar {
909 self.bound.var
910 }
911
912 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
913 Placeholder { universe: ui, ..self }
914 }
915
916 fn new(ui: UniverseIndex, var: BoundVar) -> Self {
917 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
918 }
919}
920
921pub type PlaceholderType = Placeholder<BoundTy>;
922
923impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderType {
924 fn universe(self) -> UniverseIndex {
925 self.universe
926 }
927
928 fn var(self) -> BoundVar {
929 self.bound.var
930 }
931
932 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
933 Placeholder { universe: ui, ..self }
934 }
935
936 fn new(ui: UniverseIndex, var: BoundVar) -> Self {
937 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
938 }
939}
940
941#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
942#[derive(TyEncodable, TyDecodable)]
943pub struct BoundConst<'tcx> {
944 pub var: BoundVar,
945 pub ty: Ty<'tcx>,
946}
947
948pub type PlaceholderConst = Placeholder<BoundVar>;
949
950impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderConst {
951 fn universe(self) -> UniverseIndex {
952 self.universe
953 }
954
955 fn var(self) -> BoundVar {
956 self.bound
957 }
958
959 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
960 Placeholder { universe: ui, ..self }
961 }
962
963 fn new(ui: UniverseIndex, var: BoundVar) -> Self {
964 Placeholder { universe: ui, bound: var }
965 }
966}
967
968pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
969
970impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
971 fn flags(&self) -> TypeFlags {
972 (**self).flags()
973 }
974
975 fn outer_exclusive_binder(&self) -> DebruijnIndex {
976 (**self).outer_exclusive_binder()
977 }
978}
979
980#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
986#[derive(HashStable, TypeVisitable, TypeFoldable)]
987pub struct ParamEnv<'tcx> {
988 caller_bounds: Clauses<'tcx>,
994}
995
996impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
997 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
998 self.caller_bounds()
999 }
1000}
1001
1002impl<'tcx> ParamEnv<'tcx> {
1003 #[inline]
1010 pub fn empty() -> Self {
1011 Self::new(ListWithCachedTypeInfo::empty())
1012 }
1013
1014 #[inline]
1015 pub fn caller_bounds(self) -> Clauses<'tcx> {
1016 self.caller_bounds
1017 }
1018
1019 #[inline]
1021 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1022 ParamEnv { caller_bounds }
1023 }
1024
1025 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1027 ParamEnvAnd { param_env: self, value }
1028 }
1029}
1030
1031#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1032#[derive(HashStable)]
1033pub struct ParamEnvAnd<'tcx, T> {
1034 pub param_env: ParamEnv<'tcx>,
1035 pub value: T,
1036}
1037
1038impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1039 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1040 (self.param_env, self.value)
1041 }
1042}
1043
1044#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1055#[derive(TypeVisitable, TypeFoldable)]
1056pub struct TypingEnv<'tcx> {
1057 pub typing_mode: TypingMode<'tcx>,
1058 pub param_env: ParamEnv<'tcx>,
1059}
1060
1061impl<'tcx> TypingEnv<'tcx> {
1062 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1070 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1071 }
1072
1073 pub fn non_body_analysis(
1079 tcx: TyCtxt<'tcx>,
1080 def_id: impl IntoQueryParam<DefId>,
1081 ) -> TypingEnv<'tcx> {
1082 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1083 }
1084
1085 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1086 TypingEnv {
1087 typing_mode: TypingMode::PostAnalysis,
1088 param_env: tcx.param_env_normalized_for_post_analysis(def_id),
1089 }
1090 }
1091
1092 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1095 let TypingEnv { typing_mode, param_env } = self;
1096 if let TypingMode::PostAnalysis = typing_mode {
1097 return self;
1098 }
1099
1100 let param_env = if tcx.next_trait_solver_globally() {
1103 ParamEnv::new(param_env.caller_bounds())
1104 } else {
1105 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1106 };
1107 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1108 }
1109
1110 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1115 where
1116 T: TypeVisitable<TyCtxt<'tcx>>,
1117 {
1118 PseudoCanonicalInput { typing_env: self, value }
1127 }
1128}
1129
1130#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1140#[derive(HashStable, TypeVisitable, TypeFoldable)]
1141pub struct PseudoCanonicalInput<'tcx, T> {
1142 pub typing_env: TypingEnv<'tcx>,
1143 pub value: T,
1144}
1145
1146#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1147pub struct Destructor {
1148 pub did: DefId,
1150}
1151
1152#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1154pub struct AsyncDestructor {
1155 pub impl_did: LocalDefId,
1157}
1158
1159#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1160pub struct VariantFlags(u8);
1161bitflags::bitflags! {
1162 impl VariantFlags: u8 {
1163 const NO_VARIANT_FLAGS = 0;
1164 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1166 }
1167}
1168rustc_data_structures::external_bitflags_debug! { VariantFlags }
1169
1170#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1172pub struct VariantDef {
1173 pub def_id: DefId,
1176 pub ctor: Option<(CtorKind, DefId)>,
1179 pub name: Symbol,
1181 pub discr: VariantDiscr,
1183 pub fields: IndexVec<FieldIdx, FieldDef>,
1185 tainted: Option<ErrorGuaranteed>,
1187 flags: VariantFlags,
1189}
1190
1191impl VariantDef {
1192 #[instrument(level = "debug")]
1209 pub fn new(
1210 name: Symbol,
1211 variant_did: Option<DefId>,
1212 ctor: Option<(CtorKind, DefId)>,
1213 discr: VariantDiscr,
1214 fields: IndexVec<FieldIdx, FieldDef>,
1215 parent_did: DefId,
1216 recover_tainted: Option<ErrorGuaranteed>,
1217 is_field_list_non_exhaustive: bool,
1218 ) -> Self {
1219 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1220 if is_field_list_non_exhaustive {
1221 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1222 }
1223
1224 VariantDef {
1225 def_id: variant_did.unwrap_or(parent_did),
1226 ctor,
1227 name,
1228 discr,
1229 fields,
1230 flags,
1231 tainted: recover_tainted,
1232 }
1233 }
1234
1235 #[inline]
1241 pub fn is_field_list_non_exhaustive(&self) -> bool {
1242 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1243 }
1244
1245 #[inline]
1248 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1249 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1250 }
1251
1252 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1254 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1255 }
1256
1257 #[inline]
1259 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1260 self.tainted.map_or(Ok(()), Err)
1261 }
1262
1263 #[inline]
1264 pub fn ctor_kind(&self) -> Option<CtorKind> {
1265 self.ctor.map(|(kind, _)| kind)
1266 }
1267
1268 #[inline]
1269 pub fn ctor_def_id(&self) -> Option<DefId> {
1270 self.ctor.map(|(_, def_id)| def_id)
1271 }
1272
1273 #[inline]
1277 pub fn single_field(&self) -> &FieldDef {
1278 assert!(self.fields.len() == 1);
1279
1280 &self.fields[FieldIdx::ZERO]
1281 }
1282
1283 #[inline]
1285 pub fn tail_opt(&self) -> Option<&FieldDef> {
1286 self.fields.raw.last()
1287 }
1288
1289 #[inline]
1295 pub fn tail(&self) -> &FieldDef {
1296 self.tail_opt().expect("expected unsized ADT to have a tail field")
1297 }
1298
1299 pub fn has_unsafe_fields(&self) -> bool {
1301 self.fields.iter().any(|x| x.safety.is_unsafe())
1302 }
1303}
1304
1305impl PartialEq for VariantDef {
1306 #[inline]
1307 fn eq(&self, other: &Self) -> bool {
1308 let Self {
1316 def_id: lhs_def_id,
1317 ctor: _,
1318 name: _,
1319 discr: _,
1320 fields: _,
1321 flags: _,
1322 tainted: _,
1323 } = &self;
1324 let Self {
1325 def_id: rhs_def_id,
1326 ctor: _,
1327 name: _,
1328 discr: _,
1329 fields: _,
1330 flags: _,
1331 tainted: _,
1332 } = other;
1333
1334 let res = lhs_def_id == rhs_def_id;
1335
1336 if cfg!(debug_assertions) && res {
1338 let deep = self.ctor == other.ctor
1339 && self.name == other.name
1340 && self.discr == other.discr
1341 && self.fields == other.fields
1342 && self.flags == other.flags;
1343 assert!(deep, "VariantDef for the same def-id has differing data");
1344 }
1345
1346 res
1347 }
1348}
1349
1350impl Eq for VariantDef {}
1351
1352impl Hash for VariantDef {
1353 #[inline]
1354 fn hash<H: Hasher>(&self, s: &mut H) {
1355 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1363 def_id.hash(s)
1364 }
1365}
1366
1367#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1368pub enum VariantDiscr {
1369 Explicit(DefId),
1372
1373 Relative(u32),
1378}
1379
1380#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1381pub struct FieldDef {
1382 pub did: DefId,
1383 pub name: Symbol,
1384 pub vis: Visibility<DefId>,
1385 pub safety: hir::Safety,
1386 pub value: Option<DefId>,
1387}
1388
1389impl PartialEq for FieldDef {
1390 #[inline]
1391 fn eq(&self, other: &Self) -> bool {
1392 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1400
1401 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1402
1403 let res = lhs_did == rhs_did;
1404
1405 if cfg!(debug_assertions) && res {
1407 let deep =
1408 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1409 assert!(deep, "FieldDef for the same def-id has differing data");
1410 }
1411
1412 res
1413 }
1414}
1415
1416impl Eq for FieldDef {}
1417
1418impl Hash for FieldDef {
1419 #[inline]
1420 fn hash<H: Hasher>(&self, s: &mut H) {
1421 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1429
1430 did.hash(s)
1431 }
1432}
1433
1434impl<'tcx> FieldDef {
1435 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1438 tcx.type_of(self.did).instantiate(tcx, args)
1439 }
1440
1441 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1443 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1444 }
1445}
1446
1447#[derive(Debug, PartialEq, Eq)]
1448pub enum ImplOverlapKind {
1449 Permitted {
1451 marker: bool,
1453 },
1454}
1455
1456#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1459pub enum ImplTraitInTraitData {
1460 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1461 Impl { fn_def_id: DefId },
1462}
1463
1464impl<'tcx> TyCtxt<'tcx> {
1465 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1466 self.typeck(self.hir_body_owner_def_id(body))
1467 }
1468
1469 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1470 self.associated_items(id)
1471 .in_definition_order()
1472 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1473 }
1474
1475 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1476 let mut flags = ReprFlags::empty();
1477 let mut size = None;
1478 let mut max_align: Option<Align> = None;
1479 let mut min_pack: Option<Align> = None;
1480
1481 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1484
1485 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1489 field_shuffle_seed ^= user_seed;
1490 }
1491
1492 if let Some(reprs) = attr::find_attr!(self.get_all_attrs(did), AttributeKind::Repr(r) => r)
1493 {
1494 for (r, _) in reprs {
1495 flags.insert(match *r {
1496 attr::ReprRust => ReprFlags::empty(),
1497 attr::ReprC => ReprFlags::IS_C,
1498 attr::ReprPacked(pack) => {
1499 min_pack = Some(if let Some(min_pack) = min_pack {
1500 min_pack.min(pack)
1501 } else {
1502 pack
1503 });
1504 ReprFlags::empty()
1505 }
1506 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1507 attr::ReprSimd => ReprFlags::IS_SIMD,
1508 attr::ReprInt(i) => {
1509 size = Some(match i {
1510 attr::IntType::SignedInt(x) => match x {
1511 ast::IntTy::Isize => IntegerType::Pointer(true),
1512 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1513 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1514 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1515 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1516 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1517 },
1518 attr::IntType::UnsignedInt(x) => match x {
1519 ast::UintTy::Usize => IntegerType::Pointer(false),
1520 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1521 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1522 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1523 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1524 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1525 },
1526 });
1527 ReprFlags::empty()
1528 }
1529 attr::ReprAlign(align) => {
1530 max_align = max_align.max(Some(align));
1531 ReprFlags::empty()
1532 }
1533 attr::ReprEmpty => {
1534 ReprFlags::empty()
1536 }
1537 });
1538 }
1539 }
1540
1541 if self.sess.opts.unstable_opts.randomize_layout {
1544 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1545 }
1546
1547 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1550
1551 if is_box {
1553 flags.insert(ReprFlags::IS_LINEAR);
1554 }
1555
1556 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1557 }
1558
1559 pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
1561 if let Some(cnum) = def_id.as_crate_root() {
1562 Some(self.crate_name(cnum))
1563 } else {
1564 let def_key = self.def_key(def_id);
1565 match def_key.disambiguated_data.data {
1566 rustc_hir::definitions::DefPathData::Ctor => self
1568 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1569 _ => def_key.get_opt_name(),
1570 }
1571 }
1572 }
1573
1574 pub fn item_name(self, id: DefId) -> Symbol {
1581 self.opt_item_name(id).unwrap_or_else(|| {
1582 bug!("item_name: no name for {:?}", self.def_path(id));
1583 })
1584 }
1585
1586 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
1590 let def = self.opt_item_name(def_id)?;
1591 let span = self
1592 .def_ident_span(def_id)
1593 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1594 Some(Ident::new(def, span))
1595 }
1596
1597 pub fn item_ident(self, def_id: DefId) -> Ident {
1601 self.opt_item_ident(def_id).unwrap_or_else(|| {
1602 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1603 })
1604 }
1605
1606 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1607 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1608 Some(self.associated_item(def_id))
1609 } else {
1610 None
1611 }
1612 }
1613
1614 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1618 if let DefKind::AssocTy = self.def_kind(def_id)
1619 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1620 self.associated_item(def_id).kind
1621 {
1622 Some(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 None
1676 }
1677
1678 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1681 match res {
1682 Res::Def(DefKind::Variant, did) => {
1683 let enum_did = self.parent(did);
1684 self.adt_def(enum_did).variant_with_id(did)
1685 }
1686 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1687 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1688 let variant_did = self.parent(variant_ctor_did);
1689 let enum_did = self.parent(variant_did);
1690 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1691 }
1692 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1693 let struct_did = self.parent(ctor_did);
1694 self.adt_def(struct_did).non_enum_variant()
1695 }
1696 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1697 }
1698 }
1699
1700 #[instrument(skip(self), level = "debug")]
1702 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1703 match instance {
1704 ty::InstanceKind::Item(def) => {
1705 debug!("calling def_kind on def: {:?}", def);
1706 let def_kind = self.def_kind(def);
1707 debug!("returned from def_kind: {:?}", def_kind);
1708 match def_kind {
1709 DefKind::Const
1710 | DefKind::Static { .. }
1711 | DefKind::AssocConst
1712 | DefKind::Ctor(..)
1713 | DefKind::AnonConst
1714 | DefKind::InlineConst => self.mir_for_ctfe(def),
1715 _ => self.optimized_mir(def),
1718 }
1719 }
1720 ty::InstanceKind::VTableShim(..)
1721 | ty::InstanceKind::ReifyShim(..)
1722 | ty::InstanceKind::Intrinsic(..)
1723 | ty::InstanceKind::FnPtrShim(..)
1724 | ty::InstanceKind::Virtual(..)
1725 | ty::InstanceKind::ClosureOnceShim { .. }
1726 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1727 | ty::InstanceKind::DropGlue(..)
1728 | ty::InstanceKind::CloneShim(..)
1729 | ty::InstanceKind::ThreadLocalShim(..)
1730 | ty::InstanceKind::FnPtrAddrShim(..)
1731 | ty::InstanceKind::AsyncDropGlueCtorShim(..) => self.mir_shims(instance),
1732 }
1733 }
1734
1735 pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [hir::Attribute] {
1737 if let Some(did) = did.as_local() {
1738 self.hir_attrs(self.local_def_id_to_hir_id(did))
1739 } else {
1740 self.attrs_for_def(did)
1741 }
1742 }
1743
1744 pub fn get_attrs(
1746 self,
1747 did: impl Into<DefId>,
1748 attr: Symbol,
1749 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1750 self.get_all_attrs(did).filter(move |a: &&hir::Attribute| a.has_name(attr))
1751 }
1752
1753 pub fn get_all_attrs(
1757 self,
1758 did: impl Into<DefId>,
1759 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1760 let did: DefId = did.into();
1761 if let Some(did) = did.as_local() {
1762 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter()
1763 } else {
1764 self.attrs_for_def(did).iter()
1765 }
1766 }
1767
1768 pub fn get_diagnostic_attr(
1777 self,
1778 did: impl Into<DefId>,
1779 attr: Symbol,
1780 ) -> Option<&'tcx hir::Attribute> {
1781 let did: DefId = did.into();
1782 if did.as_local().is_some() {
1783 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1785 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1786 } else {
1787 None
1788 }
1789 } else {
1790 debug_assert!(rustc_feature::encode_cross_crate(attr));
1793 self.attrs_for_def(did)
1794 .iter()
1795 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1796 }
1797 }
1798
1799 pub fn get_attrs_by_path(
1800 self,
1801 did: DefId,
1802 attr: &[Symbol],
1803 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1804 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1805 if let Some(did) = did.as_local() {
1806 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1807 } else {
1808 self.attrs_for_def(did).iter().filter(filter_fn)
1809 }
1810 }
1811
1812 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1813 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1814 let did: DefId = did.into();
1815 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1816 } else {
1817 self.get_attrs(did, attr).next()
1818 }
1819 }
1820
1821 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1823 self.get_attrs(did, attr).next().is_some()
1824 }
1825
1826 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1828 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1829 }
1830
1831 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1833 self.trait_def(trait_def_id).has_auto_impl
1834 }
1835
1836 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1839 self.trait_def(trait_def_id).is_coinductive
1840 }
1841
1842 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1844 self.def_kind(trait_def_id) == DefKind::TraitAlias
1845 }
1846
1847 pub fn coroutine_layout(
1853 self,
1854 def_id: DefId,
1855 coroutine_kind_ty: Ty<'tcx>,
1856 ) -> Option<&'tcx CoroutineLayout<'tcx>> {
1857 let mir = self.optimized_mir(def_id);
1858 if coroutine_kind_ty.is_unit() {
1860 mir.coroutine_layout_raw()
1861 } else {
1862 let ty::Coroutine(_, identity_args) =
1865 *self.type_of(def_id).instantiate_identity().kind()
1866 else {
1867 unreachable!();
1868 };
1869 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1870 if identity_kind_ty == coroutine_kind_ty {
1873 mir.coroutine_layout_raw()
1874 } else {
1875 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1876 assert_matches!(
1877 identity_kind_ty.to_opt_closure_kind(),
1878 Some(ClosureKind::Fn | ClosureKind::FnMut)
1879 );
1880 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1881 .coroutine_layout_raw()
1882 }
1883 }
1884 }
1885
1886 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1889 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1890 }
1891
1892 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
1896 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1897 let parent = self.parent(def_id);
1898 if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
1899 return Some(parent);
1900 }
1901 }
1902 None
1903 }
1904
1905 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
1908 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1909 let parent = self.parent(def_id);
1910 if let DefKind::Impl { .. } = self.def_kind(parent) {
1911 return Some(parent);
1912 }
1913 }
1914 None
1915 }
1916
1917 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1920 if self.is_automatically_derived(def_id)
1921 && let Some(def_id) = def_id.as_local()
1922 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1923 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1924 && self.has_attr(outer.macro_def_id.unwrap(), sym::rustc_builtin_macro)
1925 {
1926 true
1927 } else {
1928 false
1929 }
1930 }
1931
1932 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1934 self.has_attr(def_id, sym::automatically_derived)
1935 }
1936
1937 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
1940 if let Some(impl_def_id) = impl_def_id.as_local() {
1941 Ok(self.def_span(impl_def_id))
1942 } else {
1943 Err(self.crate_name(impl_def_id.krate))
1944 }
1945 }
1946
1947 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
1951 use_ident.name == def_ident.name
1955 && use_ident
1956 .span
1957 .ctxt()
1958 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
1959 }
1960
1961 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
1962 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
1963 ident
1964 }
1965
1966 pub fn adjust_ident_and_get_scope(
1968 self,
1969 mut ident: Ident,
1970 scope: DefId,
1971 block: hir::HirId,
1972 ) -> (Ident, DefId) {
1973 let scope = ident
1974 .span
1975 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
1976 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
1977 .unwrap_or_else(|| self.parent_module(block).to_def_id());
1978 (ident, scope)
1979 }
1980
1981 #[inline]
1985 pub fn is_const_fn(self, def_id: DefId) -> bool {
1986 matches!(
1987 self.def_kind(def_id),
1988 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
1989 ) && self.constness(def_id) == hir::Constness::Const
1990 }
1991
1992 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
1999 let def_id: DefId = def_id.into();
2000 match self.def_kind(def_id) {
2001 DefKind::Impl { of_trait: true } => {
2002 let header = self.impl_trait_header(def_id).unwrap();
2003 header.constness == hir::Constness::Const
2004 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2005 }
2006 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2007 self.constness(def_id) == hir::Constness::Const
2008 }
2009 DefKind::Trait => self.is_const_trait(def_id),
2010 DefKind::AssocTy => {
2011 let parent_def_id = self.parent(def_id);
2012 match self.def_kind(parent_def_id) {
2013 DefKind::Impl { of_trait: false } => false,
2014 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2015 self.is_conditionally_const(parent_def_id)
2016 }
2017 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2018 }
2019 }
2020 DefKind::AssocFn => {
2021 let parent_def_id = self.parent(def_id);
2022 match self.def_kind(parent_def_id) {
2023 DefKind::Impl { of_trait: false } => {
2024 self.constness(def_id) == hir::Constness::Const
2025 }
2026 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2027 self.is_conditionally_const(parent_def_id)
2028 }
2029 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2030 }
2031 }
2032 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2033 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2034 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2035 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2037 },
2038 DefKind::Closure => {
2039 false
2042 }
2043 DefKind::Ctor(_, CtorKind::Const)
2044 | DefKind::Impl { of_trait: false }
2045 | DefKind::Mod
2046 | DefKind::Struct
2047 | DefKind::Union
2048 | DefKind::Enum
2049 | DefKind::Variant
2050 | DefKind::TyAlias
2051 | DefKind::ForeignTy
2052 | DefKind::TraitAlias
2053 | DefKind::TyParam
2054 | DefKind::Const
2055 | DefKind::ConstParam
2056 | DefKind::Static { .. }
2057 | DefKind::AssocConst
2058 | DefKind::Macro(_)
2059 | DefKind::ExternCrate
2060 | DefKind::Use
2061 | DefKind::ForeignMod
2062 | DefKind::AnonConst
2063 | DefKind::InlineConst
2064 | DefKind::Field
2065 | DefKind::LifetimeParam
2066 | DefKind::GlobalAsm
2067 | DefKind::SyntheticCoroutineBody => false,
2068 }
2069 }
2070
2071 #[inline]
2072 pub fn is_const_trait(self, def_id: DefId) -> bool {
2073 self.trait_def(def_id).constness == hir::Constness::Const
2074 }
2075
2076 #[inline]
2077 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2078 matches!(self.trait_of_item(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2079 }
2080
2081 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2082 if self.def_kind(def_id) != DefKind::AssocFn {
2083 return false;
2084 }
2085
2086 let Some(item) = self.opt_associated_item(def_id) else {
2087 return false;
2088 };
2089 if item.container != ty::AssocItemContainer::Impl {
2090 return false;
2091 }
2092
2093 let Some(trait_item_def_id) = item.trait_item_def_id else {
2094 return false;
2095 };
2096
2097 return !self
2098 .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id)
2099 .is_empty();
2100 }
2101}
2102
2103pub fn int_ty(ity: ast::IntTy) -> IntTy {
2104 match ity {
2105 ast::IntTy::Isize => IntTy::Isize,
2106 ast::IntTy::I8 => IntTy::I8,
2107 ast::IntTy::I16 => IntTy::I16,
2108 ast::IntTy::I32 => IntTy::I32,
2109 ast::IntTy::I64 => IntTy::I64,
2110 ast::IntTy::I128 => IntTy::I128,
2111 }
2112}
2113
2114pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2115 match uty {
2116 ast::UintTy::Usize => UintTy::Usize,
2117 ast::UintTy::U8 => UintTy::U8,
2118 ast::UintTy::U16 => UintTy::U16,
2119 ast::UintTy::U32 => UintTy::U32,
2120 ast::UintTy::U64 => UintTy::U64,
2121 ast::UintTy::U128 => UintTy::U128,
2122 }
2123}
2124
2125pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2126 match fty {
2127 ast::FloatTy::F16 => FloatTy::F16,
2128 ast::FloatTy::F32 => FloatTy::F32,
2129 ast::FloatTy::F64 => FloatTy::F64,
2130 ast::FloatTy::F128 => FloatTy::F128,
2131 }
2132}
2133
2134pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2135 match ity {
2136 IntTy::Isize => ast::IntTy::Isize,
2137 IntTy::I8 => ast::IntTy::I8,
2138 IntTy::I16 => ast::IntTy::I16,
2139 IntTy::I32 => ast::IntTy::I32,
2140 IntTy::I64 => ast::IntTy::I64,
2141 IntTy::I128 => ast::IntTy::I128,
2142 }
2143}
2144
2145pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2146 match uty {
2147 UintTy::Usize => ast::UintTy::Usize,
2148 UintTy::U8 => ast::UintTy::U8,
2149 UintTy::U16 => ast::UintTy::U16,
2150 UintTy::U32 => ast::UintTy::U32,
2151 UintTy::U64 => ast::UintTy::U64,
2152 UintTy::U128 => ast::UintTy::U128,
2153 }
2154}
2155
2156pub fn provide(providers: &mut Providers) {
2157 closure::provide(providers);
2158 context::provide(providers);
2159 erase_regions::provide(providers);
2160 inhabitedness::provide(providers);
2161 util::provide(providers);
2162 print::provide(providers);
2163 super::util::bug::provide(providers);
2164 *providers = Providers {
2165 trait_impls_of: trait_def::trait_impls_of_provider,
2166 incoherent_impls: trait_def::incoherent_impls_provider,
2167 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2168 traits: trait_def::traits_provider,
2169 vtable_allocation: vtable::vtable_allocation_provider,
2170 ..*providers
2171 };
2172}
2173
2174#[derive(Clone, Debug, Default, HashStable)]
2180pub struct CrateInherentImpls {
2181 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2182 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2183}
2184
2185#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2186pub struct SymbolName<'tcx> {
2187 pub name: &'tcx str,
2189}
2190
2191impl<'tcx> SymbolName<'tcx> {
2192 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2193 SymbolName { name: tcx.arena.alloc_str(name) }
2194 }
2195}
2196
2197impl<'tcx> fmt::Display for SymbolName<'tcx> {
2198 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2199 fmt::Display::fmt(&self.name, fmt)
2200 }
2201}
2202
2203impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2204 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2205 fmt::Display::fmt(&self.name, fmt)
2206 }
2207}
2208
2209#[derive(Debug, Default, Copy, Clone)]
2210pub struct InferVarInfo {
2211 pub self_in_trait: bool,
2217 pub output: bool,
2220}
2221
2222#[derive(Copy, Clone, Debug, HashStable)]
2224pub struct DestructuredConst<'tcx> {
2225 pub variant: Option<VariantIdx>,
2226 pub fields: &'tcx [ty::Const<'tcx>],
2227}
2228
2229#[cfg(target_pointer_width = "64")]
2231mod size_asserts {
2232 use rustc_data_structures::static_assert_size;
2233
2234 use super::*;
2235 static_assert_size!(PredicateKind<'_>, 32);
2237 static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 48);
2238 }