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, iter, 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::node_id::NodeMap;
29pub use rustc_ast_ir::{Movability, Mutability, try_visit};
30use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
31use rustc_data_structures::intern::Interned;
32use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
33use rustc_data_structures::steal::Steal;
34use rustc_data_structures::unord::{UnordMap, UnordSet};
35use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
36use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
37use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
38use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
39use rustc_hir::definitions::DisambiguatorState;
40use rustc_hir::{LangItem, attrs as attr, find_attr};
41use rustc_index::IndexVec;
42use rustc_index::bit_set::BitMatrix;
43use rustc_macros::{
44 Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
45 extension,
46};
47use rustc_query_system::ich::StableHashingContext;
48use rustc_serialize::{Decodable, Encodable};
49pub use rustc_session::lint::RegisteredTools;
50use rustc_span::hygiene::MacroKind;
51use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
52pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
53pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
54#[allow(
55 hidden_glob_reexports,
56 rustc::usage_of_type_ir_inherent,
57 rustc::non_glob_import_of_type_ir_inherent
58)]
59use rustc_type_ir::inherent;
60pub use rustc_type_ir::relate::VarianceDiagInfo;
61pub use rustc_type_ir::solve::SizedTraitKind;
62pub use rustc_type_ir::*;
63#[allow(hidden_glob_reexports, unused_imports)]
64use rustc_type_ir::{InferCtxtLike, Interner};
65use tracing::{debug, instrument};
66pub use vtable::*;
67use {rustc_ast as ast, rustc_hir as hir};
68
69pub use self::closure::{
70 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
71 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
72 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
73 place_to_string_for_capture,
74};
75pub use self::consts::{
76 AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
77 ExprKind, ScalarInt, UnevaluatedConst, ValTree, ValTreeKind, Value,
78};
79pub use self::context::{
80 CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
81 TyCtxtFeed, tls,
82};
83pub use self::fold::*;
84pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
85pub use self::list::{List, ListWithCachedTypeInfo};
86pub use self::opaque_types::OpaqueTypeKey;
87pub use self::pattern::{Pattern, PatternKind};
88pub use self::predicate::{
89 AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
90 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
91 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
92 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
93 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
94 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
95 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
96};
97pub use self::region::{
98 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
99 RegionKind, RegionVid,
100};
101pub use self::rvalue_scopes::RvalueScopes;
102pub use self::sty::{
103 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
104 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
105 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
106};
107pub use self::trait_def::TraitDef;
108pub use self::typeck_results::{
109 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
110 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
111};
112pub use self::visit::*;
113use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
114use crate::metadata::ModChild;
115use crate::middle::privacy::EffectiveVisibilities;
116use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
117use crate::query::{IntoQueryParam, Providers};
118use crate::ty;
119use crate::ty::codec::{TyDecoder, TyEncoder};
120pub use crate::ty::diagnostics::*;
121use crate::ty::fast_reject::SimplifiedType;
122use crate::ty::layout::LayoutError;
123use crate::ty::util::Discr;
124use crate::ty::walk::TypeWalker;
125
126pub mod abstract_const;
127pub mod adjustment;
128pub mod cast;
129pub mod codec;
130pub mod error;
131pub mod fast_reject;
132pub mod inhabitedness;
133pub mod layout;
134pub mod normalize_erasing_regions;
135pub mod pattern;
136pub mod print;
137pub mod relate;
138pub mod significant_drop_order;
139pub mod trait_def;
140pub mod util;
141pub mod vtable;
142
143mod adt;
144mod assoc;
145mod closure;
146mod consts;
147mod context;
148mod diagnostics;
149mod elaborate_impl;
150mod erase_regions;
151mod fold;
152mod generic_args;
153mod generics;
154mod impls_ty;
155mod instance;
156mod intrinsic;
157mod list;
158mod opaque_types;
159mod predicate;
160mod region;
161mod rvalue_scopes;
162mod structural_impls;
163#[allow(hidden_glob_reexports)]
164mod sty;
165mod typeck_results;
166mod visit;
167
168#[derive(Debug, HashStable)]
171pub struct ResolverGlobalCtxt {
172 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
173 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
175 pub effective_visibilities: EffectiveVisibilities,
176 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
177 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
178 pub module_children: LocalDefIdMap<Vec<ModChild>>,
179 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
180 pub main_def: Option<MainDefinition>,
181 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
182 pub proc_macros: Vec<LocalDefId>,
185 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
188 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
189 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
190 pub all_macro_rules: UnordSet<Symbol>,
191 pub stripped_cfg_items: Vec<StrippedCfgItem>,
192}
193
194#[derive(Debug)]
197pub struct ResolverAstLowering {
198 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
199
200 pub partial_res_map: NodeMap<hir::def::PartialRes>,
202 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
204 pub label_res_map: NodeMap<ast::NodeId>,
206 pub lifetimes_res_map: NodeMap<LifetimeRes>,
208 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
210
211 pub next_node_id: ast::NodeId,
212
213 pub node_id_to_def_id: NodeMap<LocalDefId>,
214
215 pub disambiguator: DisambiguatorState,
216
217 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
218 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
220
221 pub lint_buffer: Steal<LintBuffer>,
223
224 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
226}
227
228#[derive(Debug)]
229pub struct DelegationFnSig {
230 pub header: ast::FnHeader,
231 pub param_count: usize,
232 pub has_self: bool,
233 pub c_variadic: bool,
234 pub target_feature: bool,
235}
236
237#[derive(Clone, Copy, Debug, HashStable)]
238pub struct MainDefinition {
239 pub res: Res<ast::NodeId>,
240 pub is_import: bool,
241 pub span: Span,
242}
243
244impl MainDefinition {
245 pub fn opt_fn_def_id(self) -> Option<DefId> {
246 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
247 }
248}
249
250#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
251pub struct ImplTraitHeader<'tcx> {
252 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
253 pub polarity: ImplPolarity,
254 pub safety: hir::Safety,
255 pub constness: hir::Constness,
256}
257
258#[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
259pub enum ImplSubject<'tcx> {
260 Trait(TraitRef<'tcx>),
261 Inherent(Ty<'tcx>),
262}
263
264#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
265#[derive(TypeFoldable, TypeVisitable)]
266pub enum Asyncness {
267 Yes,
268 No,
269}
270
271impl Asyncness {
272 pub fn is_async(self) -> bool {
273 matches!(self, Asyncness::Yes)
274 }
275}
276
277#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
278pub enum Visibility<Id = LocalDefId> {
279 Public,
281 Restricted(Id),
283}
284
285impl Visibility {
286 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
287 match self {
288 ty::Visibility::Restricted(restricted_id) => {
289 if restricted_id.is_top_level_module() {
290 "pub(crate)".to_string()
291 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
292 "pub(self)".to_string()
293 } else {
294 format!(
295 "pub(in crate{})",
296 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
297 )
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::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
453#[derive(HashStable, Debug)]
460pub struct CratePredicatesMap<'tcx> {
461 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
465}
466
467#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
468pub struct Term<'tcx> {
469 ptr: NonNull<()>,
470 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
471}
472
473impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
474
475impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
476 type Kind = TermKind<'tcx>;
477
478 fn kind(self) -> Self::Kind {
479 self.kind()
480 }
481}
482
483unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
484 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
485{
486}
487unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
488 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
489{
490}
491unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
492unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
493
494impl Debug for Term<'_> {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 match self.kind() {
497 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
498 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
499 }
500 }
501}
502
503impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
504 fn from(ty: Ty<'tcx>) -> Self {
505 TermKind::Ty(ty).pack()
506 }
507}
508
509impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
510 fn from(c: Const<'tcx>) -> Self {
511 TermKind::Const(c).pack()
512 }
513}
514
515impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
516 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
517 self.kind().hash_stable(hcx, hasher);
518 }
519}
520
521impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
522 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
523 self,
524 folder: &mut F,
525 ) -> Result<Self, F::Error> {
526 match self.kind() {
527 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
528 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
529 }
530 }
531
532 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
533 match self.kind() {
534 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
535 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
536 }
537 }
538}
539
540impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
541 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
542 match self.kind() {
543 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
544 ty::TermKind::Const(ct) => ct.visit_with(visitor),
545 }
546 }
547}
548
549impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
550 fn encode(&self, e: &mut E) {
551 self.kind().encode(e)
552 }
553}
554
555impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
556 fn decode(d: &mut D) -> Self {
557 let res: TermKind<'tcx> = Decodable::decode(d);
558 res.pack()
559 }
560}
561
562impl<'tcx> Term<'tcx> {
563 #[inline]
564 pub fn kind(self) -> TermKind<'tcx> {
565 let ptr =
566 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
567 unsafe {
571 match self.ptr.addr().get() & TAG_MASK {
572 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
573 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
574 ))),
575 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
576 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
577 ))),
578 _ => core::intrinsics::unreachable(),
579 }
580 }
581 }
582
583 pub fn as_type(&self) -> Option<Ty<'tcx>> {
584 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
585 }
586
587 pub fn expect_type(&self) -> Ty<'tcx> {
588 self.as_type().expect("expected a type, but found a const")
589 }
590
591 pub fn as_const(&self) -> Option<Const<'tcx>> {
592 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
593 }
594
595 pub fn expect_const(&self) -> Const<'tcx> {
596 self.as_const().expect("expected a const, but found a type")
597 }
598
599 pub fn into_arg(self) -> GenericArg<'tcx> {
600 match self.kind() {
601 TermKind::Ty(ty) => ty.into(),
602 TermKind::Const(c) => c.into(),
603 }
604 }
605
606 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
607 match self.kind() {
608 TermKind::Ty(ty) => match *ty.kind() {
609 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
610 _ => None,
611 },
612 TermKind::Const(ct) => match ct.kind() {
613 ConstKind::Unevaluated(uv) => Some(uv.into()),
614 _ => None,
615 },
616 }
617 }
618
619 pub fn is_infer(&self) -> bool {
620 match self.kind() {
621 TermKind::Ty(ty) => ty.is_ty_var(),
622 TermKind::Const(ct) => ct.is_ct_infer(),
623 }
624 }
625
626 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
627 match self.kind() {
628 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
629 TermKind::Const(ct) => ct.is_trivially_wf(),
630 }
631 }
632
633 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
644 TypeWalker::new(self.into())
645 }
646}
647
648const TAG_MASK: usize = 0b11;
649const TYPE_TAG: usize = 0b00;
650const CONST_TAG: usize = 0b01;
651
652#[extension(pub trait TermKindPackExt<'tcx>)]
653impl<'tcx> TermKind<'tcx> {
654 #[inline]
655 fn pack(self) -> Term<'tcx> {
656 let (tag, ptr) = match self {
657 TermKind::Ty(ty) => {
658 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
660 (TYPE_TAG, NonNull::from(ty.0.0).cast())
661 }
662 TermKind::Const(ct) => {
663 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
665 (CONST_TAG, NonNull::from(ct.0.0).cast())
666 }
667 };
668
669 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
670 }
671}
672
673#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
693pub struct InstantiatedPredicates<'tcx> {
694 pub predicates: Vec<Clause<'tcx>>,
695 pub spans: Vec<Span>,
696}
697
698impl<'tcx> InstantiatedPredicates<'tcx> {
699 pub fn empty() -> InstantiatedPredicates<'tcx> {
700 InstantiatedPredicates { predicates: vec![], spans: vec![] }
701 }
702
703 pub fn is_empty(&self) -> bool {
704 self.predicates.is_empty()
705 }
706
707 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
708 self.into_iter()
709 }
710}
711
712impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
713 type Item = (Clause<'tcx>, Span);
714
715 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
716
717 fn into_iter(self) -> Self::IntoIter {
718 debug_assert_eq!(self.predicates.len(), self.spans.len());
719 std::iter::zip(self.predicates, self.spans)
720 }
721}
722
723impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
724 type Item = (Clause<'tcx>, Span);
725
726 type IntoIter = std::iter::Zip<
727 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
728 std::iter::Copied<std::slice::Iter<'a, Span>>,
729 >;
730
731 fn into_iter(self) -> Self::IntoIter {
732 debug_assert_eq!(self.predicates.len(), self.spans.len());
733 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
734 }
735}
736
737#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
738pub struct OpaqueHiddenType<'tcx> {
739 pub span: Span,
753
754 pub ty: Ty<'tcx>,
767}
768
769#[derive(Debug, Clone, Copy)]
771pub enum DefiningScopeKind {
772 HirTypeck,
777 MirBorrowck,
778}
779
780impl<'tcx> OpaqueHiddenType<'tcx> {
781 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> OpaqueHiddenType<'tcx> {
782 OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
783 }
784
785 pub fn build_mismatch_error(
786 &self,
787 other: &Self,
788 tcx: TyCtxt<'tcx>,
789 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
790 (self.ty, other.ty).error_reported()?;
791 let sub_diag = if self.span == other.span {
793 TypeMismatchReason::ConflictType { span: self.span }
794 } else {
795 TypeMismatchReason::PreviousUse { span: self.span }
796 };
797 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
798 self_ty: self.ty,
799 other_ty: other.ty,
800 other_span: other.span,
801 sub: sub_diag,
802 }))
803 }
804
805 #[instrument(level = "debug", skip(tcx), ret)]
806 pub fn remap_generic_params_to_declaration_params(
807 self,
808 opaque_type_key: OpaqueTypeKey<'tcx>,
809 tcx: TyCtxt<'tcx>,
810 defining_scope_kind: DefiningScopeKind,
811 ) -> Self {
812 let OpaqueTypeKey { def_id, args } = opaque_type_key;
813
814 let id_args = GenericArgs::identity_for_item(tcx, def_id);
821 debug!(?id_args);
822
823 let map = args.iter().zip(id_args).collect();
827 debug!("map = {:#?}", map);
828
829 let this = match defining_scope_kind {
834 DefiningScopeKind::HirTypeck => tcx.erase_regions(self),
835 DefiningScopeKind::MirBorrowck => self,
836 };
837 let result = this.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
838 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
839 assert_eq!(result.ty, tcx.erase_regions(result.ty));
840 }
841 result
842 }
843}
844
845#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
850#[derive(HashStable, TyEncodable, TyDecodable)]
851pub struct Placeholder<T> {
852 pub universe: UniverseIndex,
853 pub bound: T,
854}
855
856pub type PlaceholderRegion = Placeholder<BoundRegion>;
857
858impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion {
859 type Bound = BoundRegion;
860
861 fn universe(self) -> UniverseIndex {
862 self.universe
863 }
864
865 fn var(self) -> BoundVar {
866 self.bound.var
867 }
868
869 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
870 Placeholder { universe: ui, ..self }
871 }
872
873 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
874 Placeholder { universe: ui, bound }
875 }
876
877 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
878 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
879 }
880}
881
882pub type PlaceholderType = Placeholder<BoundTy>;
883
884impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType {
885 type Bound = BoundTy;
886
887 fn universe(self) -> UniverseIndex {
888 self.universe
889 }
890
891 fn var(self) -> BoundVar {
892 self.bound.var
893 }
894
895 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
896 Placeholder { universe: ui, ..self }
897 }
898
899 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
900 Placeholder { universe: ui, bound }
901 }
902
903 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
904 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
905 }
906}
907
908#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
909#[derive(TyEncodable, TyDecodable)]
910pub struct BoundConst {
911 pub var: BoundVar,
912}
913
914impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
915 fn var(self) -> BoundVar {
916 self.var
917 }
918
919 fn assert_eq(self, var: ty::BoundVariableKind) {
920 var.expect_const()
921 }
922}
923
924pub type PlaceholderConst = Placeholder<BoundConst>;
925
926impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
927 type Bound = BoundConst;
928
929 fn universe(self) -> UniverseIndex {
930 self.universe
931 }
932
933 fn var(self) -> BoundVar {
934 self.bound.var
935 }
936
937 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
938 Placeholder { universe: ui, ..self }
939 }
940
941 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
942 Placeholder { universe: ui, bound }
943 }
944
945 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
946 Placeholder { universe: ui, bound: BoundConst { var } }
947 }
948}
949
950pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
951
952impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
953 fn flags(&self) -> TypeFlags {
954 (**self).flags()
955 }
956
957 fn outer_exclusive_binder(&self) -> DebruijnIndex {
958 (**self).outer_exclusive_binder()
959 }
960}
961
962#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
968#[derive(HashStable, TypeVisitable, TypeFoldable)]
969pub struct ParamEnv<'tcx> {
970 caller_bounds: Clauses<'tcx>,
976}
977
978impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
979 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
980 self.caller_bounds()
981 }
982}
983
984impl<'tcx> ParamEnv<'tcx> {
985 #[inline]
992 pub fn empty() -> Self {
993 Self::new(ListWithCachedTypeInfo::empty())
994 }
995
996 #[inline]
997 pub fn caller_bounds(self) -> Clauses<'tcx> {
998 self.caller_bounds
999 }
1000
1001 #[inline]
1003 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1004 ParamEnv { caller_bounds }
1005 }
1006
1007 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1009 ParamEnvAnd { param_env: self, value }
1010 }
1011}
1012
1013#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1014#[derive(HashStable)]
1015pub struct ParamEnvAnd<'tcx, T> {
1016 pub param_env: ParamEnv<'tcx>,
1017 pub value: T,
1018}
1019
1020#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1031#[derive(TypeVisitable, TypeFoldable)]
1032pub struct TypingEnv<'tcx> {
1033 #[type_foldable(identity)]
1034 #[type_visitable(ignore)]
1035 pub typing_mode: TypingMode<'tcx>,
1036 pub param_env: ParamEnv<'tcx>,
1037}
1038
1039impl<'tcx> TypingEnv<'tcx> {
1040 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1048 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1049 }
1050
1051 pub fn non_body_analysis(
1057 tcx: TyCtxt<'tcx>,
1058 def_id: impl IntoQueryParam<DefId>,
1059 ) -> TypingEnv<'tcx> {
1060 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1061 }
1062
1063 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1064 tcx.typing_env_normalized_for_post_analysis(def_id)
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 param_env
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 }
1106 }
1107}
1108
1109#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1119#[derive(HashStable, TypeVisitable, TypeFoldable)]
1120pub struct PseudoCanonicalInput<'tcx, T> {
1121 pub typing_env: TypingEnv<'tcx>,
1122 pub value: T,
1123}
1124
1125#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1126pub struct Destructor {
1127 pub did: DefId,
1129}
1130
1131#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1133pub struct AsyncDestructor {
1134 pub impl_did: 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 #[instrument(level = "debug")]
1188 pub fn new(
1189 name: Symbol,
1190 variant_did: Option<DefId>,
1191 ctor: Option<(CtorKind, DefId)>,
1192 discr: VariantDiscr,
1193 fields: IndexVec<FieldIdx, FieldDef>,
1194 parent_did: DefId,
1195 recover_tainted: Option<ErrorGuaranteed>,
1196 is_field_list_non_exhaustive: bool,
1197 ) -> Self {
1198 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1199 if is_field_list_non_exhaustive {
1200 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1201 }
1202
1203 VariantDef {
1204 def_id: variant_did.unwrap_or(parent_did),
1205 ctor,
1206 name,
1207 discr,
1208 fields,
1209 flags,
1210 tainted: recover_tainted,
1211 }
1212 }
1213
1214 #[inline]
1220 pub fn is_field_list_non_exhaustive(&self) -> bool {
1221 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1222 }
1223
1224 #[inline]
1227 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1228 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1229 }
1230
1231 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1233 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1234 }
1235
1236 #[inline]
1238 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1239 self.tainted.map_or(Ok(()), Err)
1240 }
1241
1242 #[inline]
1243 pub fn ctor_kind(&self) -> Option<CtorKind> {
1244 self.ctor.map(|(kind, _)| kind)
1245 }
1246
1247 #[inline]
1248 pub fn ctor_def_id(&self) -> Option<DefId> {
1249 self.ctor.map(|(_, def_id)| def_id)
1250 }
1251
1252 #[inline]
1256 pub fn single_field(&self) -> &FieldDef {
1257 assert!(self.fields.len() == 1);
1258
1259 &self.fields[FieldIdx::ZERO]
1260 }
1261
1262 #[inline]
1264 pub fn tail_opt(&self) -> Option<&FieldDef> {
1265 self.fields.raw.last()
1266 }
1267
1268 #[inline]
1274 pub fn tail(&self) -> &FieldDef {
1275 self.tail_opt().expect("expected unsized ADT to have a tail field")
1276 }
1277
1278 pub fn has_unsafe_fields(&self) -> bool {
1280 self.fields.iter().any(|x| x.safety.is_unsafe())
1281 }
1282}
1283
1284impl PartialEq for VariantDef {
1285 #[inline]
1286 fn eq(&self, other: &Self) -> bool {
1287 let Self {
1295 def_id: lhs_def_id,
1296 ctor: _,
1297 name: _,
1298 discr: _,
1299 fields: _,
1300 flags: _,
1301 tainted: _,
1302 } = &self;
1303 let Self {
1304 def_id: rhs_def_id,
1305 ctor: _,
1306 name: _,
1307 discr: _,
1308 fields: _,
1309 flags: _,
1310 tainted: _,
1311 } = other;
1312
1313 let res = lhs_def_id == rhs_def_id;
1314
1315 if cfg!(debug_assertions) && res {
1317 let deep = self.ctor == other.ctor
1318 && self.name == other.name
1319 && self.discr == other.discr
1320 && self.fields == other.fields
1321 && self.flags == other.flags;
1322 assert!(deep, "VariantDef for the same def-id has differing data");
1323 }
1324
1325 res
1326 }
1327}
1328
1329impl Eq for VariantDef {}
1330
1331impl Hash for VariantDef {
1332 #[inline]
1333 fn hash<H: Hasher>(&self, s: &mut H) {
1334 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1342 def_id.hash(s)
1343 }
1344}
1345
1346#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1347pub enum VariantDiscr {
1348 Explicit(DefId),
1351
1352 Relative(u32),
1357}
1358
1359#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1360pub struct FieldDef {
1361 pub did: DefId,
1362 pub name: Symbol,
1363 pub vis: Visibility<DefId>,
1364 pub safety: hir::Safety,
1365 pub value: Option<DefId>,
1366}
1367
1368impl PartialEq for FieldDef {
1369 #[inline]
1370 fn eq(&self, other: &Self) -> bool {
1371 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1379
1380 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1381
1382 let res = lhs_did == rhs_did;
1383
1384 if cfg!(debug_assertions) && res {
1386 let deep =
1387 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1388 assert!(deep, "FieldDef for the same def-id has differing data");
1389 }
1390
1391 res
1392 }
1393}
1394
1395impl Eq for FieldDef {}
1396
1397impl Hash for FieldDef {
1398 #[inline]
1399 fn hash<H: Hasher>(&self, s: &mut H) {
1400 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1408
1409 did.hash(s)
1410 }
1411}
1412
1413impl<'tcx> FieldDef {
1414 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1417 tcx.type_of(self.did).instantiate(tcx, args)
1418 }
1419
1420 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1422 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1423 }
1424}
1425
1426#[derive(Debug, PartialEq, Eq)]
1427pub enum ImplOverlapKind {
1428 Permitted {
1430 marker: bool,
1432 },
1433}
1434
1435#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1438pub enum ImplTraitInTraitData {
1439 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1440 Impl { fn_def_id: DefId },
1441}
1442
1443impl<'tcx> TyCtxt<'tcx> {
1444 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1445 self.typeck(self.hir_body_owner_def_id(body))
1446 }
1447
1448 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1449 self.associated_items(id)
1450 .in_definition_order()
1451 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1452 }
1453
1454 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1455 let mut flags = ReprFlags::empty();
1456 let mut size = None;
1457 let mut max_align: Option<Align> = None;
1458 let mut min_pack: Option<Align> = None;
1459
1460 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1463
1464 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1468 field_shuffle_seed ^= user_seed;
1469 }
1470
1471 if let Some(reprs) =
1472 find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs)
1473 {
1474 for (r, _) in reprs {
1475 flags.insert(match *r {
1476 attr::ReprRust => ReprFlags::empty(),
1477 attr::ReprC => ReprFlags::IS_C,
1478 attr::ReprPacked(pack) => {
1479 min_pack = Some(if let Some(min_pack) = min_pack {
1480 min_pack.min(pack)
1481 } else {
1482 pack
1483 });
1484 ReprFlags::empty()
1485 }
1486 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1487 attr::ReprSimd => ReprFlags::IS_SIMD,
1488 attr::ReprInt(i) => {
1489 size = Some(match i {
1490 attr::IntType::SignedInt(x) => match x {
1491 ast::IntTy::Isize => IntegerType::Pointer(true),
1492 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1493 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1494 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1495 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1496 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1497 },
1498 attr::IntType::UnsignedInt(x) => match x {
1499 ast::UintTy::Usize => IntegerType::Pointer(false),
1500 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1501 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1502 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1503 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1504 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1505 },
1506 });
1507 ReprFlags::empty()
1508 }
1509 attr::ReprAlign(align) => {
1510 max_align = max_align.max(Some(align));
1511 ReprFlags::empty()
1512 }
1513 });
1514 }
1515 }
1516
1517 if self.sess.opts.unstable_opts.randomize_layout {
1520 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1521 }
1522
1523 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1526
1527 if is_box {
1529 flags.insert(ReprFlags::IS_LINEAR);
1530 }
1531
1532 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1533 }
1534
1535 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1537 let def_id = def_id.into_query_param();
1538 if let Some(cnum) = def_id.as_crate_root() {
1539 Some(self.crate_name(cnum))
1540 } else {
1541 let def_key = self.def_key(def_id);
1542 match def_key.disambiguated_data.data {
1543 rustc_hir::definitions::DefPathData::Ctor => self
1545 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1546 _ => def_key.get_opt_name(),
1547 }
1548 }
1549 }
1550
1551 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1558 let id = id.into_query_param();
1559 self.opt_item_name(id).unwrap_or_else(|| {
1560 bug!("item_name: no name for {:?}", self.def_path(id));
1561 })
1562 }
1563
1564 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1568 let def_id = def_id.into_query_param();
1569 let def = self.opt_item_name(def_id)?;
1570 let span = self
1571 .def_ident_span(def_id)
1572 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1573 Some(Ident::new(def, span))
1574 }
1575
1576 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1580 let def_id = def_id.into_query_param();
1581 self.opt_item_ident(def_id).unwrap_or_else(|| {
1582 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1583 })
1584 }
1585
1586 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1587 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1588 Some(self.associated_item(def_id))
1589 } else {
1590 None
1591 }
1592 }
1593
1594 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1598 if let DefKind::AssocTy = self.def_kind(def_id)
1599 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1600 self.associated_item(def_id).kind
1601 {
1602 Some(rpitit_info)
1603 } else {
1604 None
1605 }
1606 }
1607
1608 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1609 variant.fields.iter_enumerated().find_map(|(i, field)| {
1610 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1611 })
1612 }
1613
1614 #[instrument(level = "debug", skip(self), ret)]
1617 pub fn impls_are_allowed_to_overlap(
1618 self,
1619 def_id1: DefId,
1620 def_id2: DefId,
1621 ) -> Option<ImplOverlapKind> {
1622 let impl1 = self.impl_trait_header(def_id1).unwrap();
1623 let impl2 = self.impl_trait_header(def_id2).unwrap();
1624
1625 let trait_ref1 = impl1.trait_ref.skip_binder();
1626 let trait_ref2 = impl2.trait_ref.skip_binder();
1627
1628 if trait_ref1.references_error() || trait_ref2.references_error() {
1631 return Some(ImplOverlapKind::Permitted { marker: false });
1632 }
1633
1634 match (impl1.polarity, impl2.polarity) {
1635 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1636 return Some(ImplOverlapKind::Permitted { marker: false });
1638 }
1639 (ImplPolarity::Positive, ImplPolarity::Negative)
1640 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1641 return None;
1643 }
1644 (ImplPolarity::Positive, ImplPolarity::Positive)
1645 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1646 };
1647
1648 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1649 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1650
1651 if is_marker_overlap {
1652 return Some(ImplOverlapKind::Permitted { marker: true });
1653 }
1654
1655 None
1656 }
1657
1658 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1661 match res {
1662 Res::Def(DefKind::Variant, did) => {
1663 let enum_did = self.parent(did);
1664 self.adt_def(enum_did).variant_with_id(did)
1665 }
1666 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1667 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1668 let variant_did = self.parent(variant_ctor_did);
1669 let enum_did = self.parent(variant_did);
1670 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1671 }
1672 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1673 let struct_did = self.parent(ctor_did);
1674 self.adt_def(struct_did).non_enum_variant()
1675 }
1676 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1677 }
1678 }
1679
1680 #[instrument(skip(self), level = "debug")]
1682 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1683 match instance {
1684 ty::InstanceKind::Item(def) => {
1685 debug!("calling def_kind on def: {:?}", def);
1686 let def_kind = self.def_kind(def);
1687 debug!("returned from def_kind: {:?}", def_kind);
1688 match def_kind {
1689 DefKind::Const
1690 | DefKind::Static { .. }
1691 | DefKind::AssocConst
1692 | DefKind::Ctor(..)
1693 | DefKind::AnonConst
1694 | DefKind::InlineConst => self.mir_for_ctfe(def),
1695 _ => self.optimized_mir(def),
1698 }
1699 }
1700 ty::InstanceKind::VTableShim(..)
1701 | ty::InstanceKind::ReifyShim(..)
1702 | ty::InstanceKind::Intrinsic(..)
1703 | ty::InstanceKind::FnPtrShim(..)
1704 | ty::InstanceKind::Virtual(..)
1705 | ty::InstanceKind::ClosureOnceShim { .. }
1706 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1707 | ty::InstanceKind::FutureDropPollShim(..)
1708 | ty::InstanceKind::DropGlue(..)
1709 | ty::InstanceKind::CloneShim(..)
1710 | ty::InstanceKind::ThreadLocalShim(..)
1711 | ty::InstanceKind::FnPtrAddrShim(..)
1712 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1713 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1714 }
1715 }
1716
1717 pub fn get_attrs(
1719 self,
1720 did: impl Into<DefId>,
1721 attr: Symbol,
1722 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1723 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1724 }
1725
1726 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1731 let did: DefId = did.into();
1732 if let Some(did) = did.as_local() {
1733 self.hir_attrs(self.local_def_id_to_hir_id(did))
1734 } else {
1735 self.attrs_for_def(did)
1736 }
1737 }
1738
1739 pub fn get_diagnostic_attr(
1748 self,
1749 did: impl Into<DefId>,
1750 attr: Symbol,
1751 ) -> Option<&'tcx hir::Attribute> {
1752 let did: DefId = did.into();
1753 if did.as_local().is_some() {
1754 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1756 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1757 } else {
1758 None
1759 }
1760 } else {
1761 debug_assert!(rustc_feature::encode_cross_crate(attr));
1764 self.attrs_for_def(did)
1765 .iter()
1766 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1767 }
1768 }
1769
1770 pub fn get_attrs_by_path(
1771 self,
1772 did: DefId,
1773 attr: &[Symbol],
1774 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1775 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1776 if let Some(did) = did.as_local() {
1777 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1778 } else {
1779 self.attrs_for_def(did).iter().filter(filter_fn)
1780 }
1781 }
1782
1783 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1784 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1785 let did: DefId = did.into();
1786 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1787 } else {
1788 self.get_attrs(did, attr).next()
1789 }
1790 }
1791
1792 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1794 self.get_attrs(did, attr).next().is_some()
1795 }
1796
1797 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1799 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1800 }
1801
1802 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1804 self.trait_def(trait_def_id).has_auto_impl
1805 }
1806
1807 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1810 self.trait_def(trait_def_id).is_coinductive
1811 }
1812
1813 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1815 self.def_kind(trait_def_id) == DefKind::TraitAlias
1816 }
1817
1818 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1820 self.arena.alloc(err)
1821 }
1822
1823 fn ordinary_coroutine_layout(
1829 self,
1830 def_id: DefId,
1831 args: GenericArgsRef<'tcx>,
1832 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1833 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1834 let mir = self.optimized_mir(def_id);
1835 let ty = || Ty::new_coroutine(self, def_id, args);
1836 if coroutine_kind_ty.is_unit() {
1838 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1839 } else {
1840 let ty::Coroutine(_, identity_args) =
1843 *self.type_of(def_id).instantiate_identity().kind()
1844 else {
1845 unreachable!();
1846 };
1847 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1848 if identity_kind_ty == coroutine_kind_ty {
1851 mir.coroutine_layout_raw()
1852 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1853 } else {
1854 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1855 assert_matches!(
1856 identity_kind_ty.to_opt_closure_kind(),
1857 Some(ClosureKind::Fn | ClosureKind::FnMut)
1858 );
1859 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1860 .coroutine_layout_raw()
1861 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1862 }
1863 }
1864 }
1865
1866 fn async_drop_coroutine_layout(
1870 self,
1871 def_id: DefId,
1872 args: GenericArgsRef<'tcx>,
1873 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1874 let ty = || Ty::new_coroutine(self, def_id, args);
1875 if args[0].has_placeholders() || args[0].has_non_region_param() {
1876 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1877 }
1878 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1879 self.mir_shims(instance)
1880 .coroutine_layout_raw()
1881 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1882 }
1883
1884 pub fn coroutine_layout(
1887 self,
1888 def_id: DefId,
1889 args: GenericArgsRef<'tcx>,
1890 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1891 if self.is_async_drop_in_place_coroutine(def_id) {
1892 let arg_cor_ty = args.first().unwrap().expect_ty();
1896 if arg_cor_ty.is_coroutine() {
1897 let span = self.def_span(def_id);
1898 let source_info = SourceInfo::outermost(span);
1899 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1902 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1903 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1904 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1905 let proxy_layout = CoroutineLayout {
1906 field_tys: [].into(),
1907 field_names: [].into(),
1908 variant_fields,
1909 variant_source_info,
1910 storage_conflicts: BitMatrix::new(0, 0),
1911 };
1912 return Ok(self.arena.alloc(proxy_layout));
1913 } else {
1914 self.async_drop_coroutine_layout(def_id, args)
1915 }
1916 } else {
1917 self.ordinary_coroutine_layout(def_id, args)
1918 }
1919 }
1920
1921 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1924 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1925 }
1926
1927 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1929 if !self.def_kind(def_id).is_assoc() {
1930 return None;
1931 }
1932 let parent = self.parent(def_id);
1933 let def_kind = self.def_kind(parent);
1934 Some((parent, def_kind))
1935 }
1936
1937 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1940 match self.assoc_parent(def_id) {
1941 Some((id, DefKind::Trait)) => Some(id),
1942 _ => None,
1943 }
1944 }
1945
1946 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1949 match self.assoc_parent(def_id) {
1950 Some((id, DefKind::Impl { .. })) => Some(id),
1951 _ => None,
1952 }
1953 }
1954
1955 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1958 match self.assoc_parent(def_id) {
1959 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
1960 _ => None,
1961 }
1962 }
1963
1964 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1967 match self.assoc_parent(def_id) {
1968 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
1969 _ => None,
1970 }
1971 }
1972
1973 pub fn is_exportable(self, def_id: DefId) -> bool {
1974 self.exportable_items(def_id.krate).contains(&def_id)
1975 }
1976
1977 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1980 if self.is_automatically_derived(def_id)
1981 && let Some(def_id) = def_id.as_local()
1982 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1983 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1984 && find_attr!(
1985 self.get_all_attrs(outer.macro_def_id.unwrap()),
1986 AttributeKind::RustcBuiltinMacro { .. }
1987 )
1988 {
1989 true
1990 } else {
1991 false
1992 }
1993 }
1994
1995 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1997 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
1998 }
1999
2000 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2003 if let Some(impl_def_id) = impl_def_id.as_local() {
2004 Ok(self.def_span(impl_def_id))
2005 } else {
2006 Err(self.crate_name(impl_def_id.krate))
2007 }
2008 }
2009
2010 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2014 use_ident.name == def_ident.name
2018 && use_ident
2019 .span
2020 .ctxt()
2021 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2022 }
2023
2024 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2025 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2026 ident
2027 }
2028
2029 pub fn adjust_ident_and_get_scope(
2031 self,
2032 mut ident: Ident,
2033 scope: DefId,
2034 block: hir::HirId,
2035 ) -> (Ident, DefId) {
2036 let scope = ident
2037 .span
2038 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2039 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2040 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2041 (ident, scope)
2042 }
2043
2044 #[inline]
2048 pub fn is_const_fn(self, def_id: DefId) -> bool {
2049 matches!(
2050 self.def_kind(def_id),
2051 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2052 ) && self.constness(def_id) == hir::Constness::Const
2053 }
2054
2055 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2062 let def_id: DefId = def_id.into();
2063 match self.def_kind(def_id) {
2064 DefKind::Impl { of_trait: true } => {
2065 let header = self.impl_trait_header(def_id).unwrap();
2066 header.constness == hir::Constness::Const
2067 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2068 }
2069 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2070 self.constness(def_id) == hir::Constness::Const
2071 }
2072 DefKind::Trait => self.is_const_trait(def_id),
2073 DefKind::AssocTy => {
2074 let parent_def_id = self.parent(def_id);
2075 match self.def_kind(parent_def_id) {
2076 DefKind::Impl { of_trait: false } => false,
2077 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2078 self.is_conditionally_const(parent_def_id)
2079 }
2080 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2081 }
2082 }
2083 DefKind::AssocFn => {
2084 let parent_def_id = self.parent(def_id);
2085 match self.def_kind(parent_def_id) {
2086 DefKind::Impl { of_trait: false } => {
2087 self.constness(def_id) == hir::Constness::Const
2088 }
2089 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2090 self.is_conditionally_const(parent_def_id)
2091 }
2092 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2093 }
2094 }
2095 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2096 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2097 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2098 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2100 },
2101 DefKind::Closure => {
2102 false
2105 }
2106 DefKind::Ctor(_, CtorKind::Const)
2107 | DefKind::Impl { of_trait: false }
2108 | DefKind::Mod
2109 | DefKind::Struct
2110 | DefKind::Union
2111 | DefKind::Enum
2112 | DefKind::Variant
2113 | DefKind::TyAlias
2114 | DefKind::ForeignTy
2115 | DefKind::TraitAlias
2116 | DefKind::TyParam
2117 | DefKind::Const
2118 | DefKind::ConstParam
2119 | DefKind::Static { .. }
2120 | DefKind::AssocConst
2121 | DefKind::Macro(_)
2122 | DefKind::ExternCrate
2123 | DefKind::Use
2124 | DefKind::ForeignMod
2125 | DefKind::AnonConst
2126 | DefKind::InlineConst
2127 | DefKind::Field
2128 | DefKind::LifetimeParam
2129 | DefKind::GlobalAsm
2130 | DefKind::SyntheticCoroutineBody => false,
2131 }
2132 }
2133
2134 #[inline]
2135 pub fn is_const_trait(self, def_id: DefId) -> bool {
2136 self.trait_def(def_id).constness == hir::Constness::Const
2137 }
2138
2139 #[inline]
2140 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2141 matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2142 }
2143
2144 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2145 if self.def_kind(def_id) != DefKind::AssocFn {
2146 return false;
2147 }
2148
2149 let Some(item) = self.opt_associated_item(def_id) else {
2150 return false;
2151 };
2152 if item.container != ty::AssocItemContainer::Impl {
2153 return false;
2154 }
2155
2156 let Some(trait_item_def_id) = item.trait_item_def_id else {
2157 return false;
2158 };
2159
2160 return !self
2161 .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id)
2162 .is_empty();
2163 }
2164}
2165
2166pub fn provide(providers: &mut Providers) {
2167 closure::provide(providers);
2168 context::provide(providers);
2169 erase_regions::provide(providers);
2170 inhabitedness::provide(providers);
2171 util::provide(providers);
2172 print::provide(providers);
2173 super::util::bug::provide(providers);
2174 *providers = Providers {
2175 trait_impls_of: trait_def::trait_impls_of_provider,
2176 incoherent_impls: trait_def::incoherent_impls_provider,
2177 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2178 traits: trait_def::traits_provider,
2179 vtable_allocation: vtable::vtable_allocation_provider,
2180 ..*providers
2181 };
2182}
2183
2184#[derive(Clone, Debug, Default, HashStable)]
2190pub struct CrateInherentImpls {
2191 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2192 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2193}
2194
2195#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2196pub struct SymbolName<'tcx> {
2197 pub name: &'tcx str,
2199}
2200
2201impl<'tcx> SymbolName<'tcx> {
2202 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2203 SymbolName { name: tcx.arena.alloc_str(name) }
2204 }
2205}
2206
2207impl<'tcx> fmt::Display for SymbolName<'tcx> {
2208 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2209 fmt::Display::fmt(&self.name, fmt)
2210 }
2211}
2212
2213impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2214 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2215 fmt::Display::fmt(&self.name, fmt)
2216 }
2217}
2218
2219#[derive(Copy, Clone, Debug, HashStable)]
2221pub struct DestructuredConst<'tcx> {
2222 pub variant: Option<VariantIdx>,
2223 pub fields: &'tcx [ty::Const<'tcx>],
2224}