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 {
835 DefiningScopeKind::HirTypeck => fold_regions(tcx, self, |_, _| tcx.lifetimes.re_erased),
836 DefiningScopeKind::MirBorrowck => self,
837 };
838 let result = this.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
839 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
840 assert_eq!(result.ty, fold_regions(tcx, result.ty, |_, _| tcx.lifetimes.re_erased));
841 }
842 result
843 }
844}
845
846#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
851#[derive(HashStable, TyEncodable, TyDecodable)]
852pub struct Placeholder<T> {
853 pub universe: UniverseIndex,
854 pub bound: T,
855}
856
857pub type PlaceholderRegion = Placeholder<BoundRegion>;
858
859impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion {
860 type Bound = BoundRegion;
861
862 fn universe(self) -> UniverseIndex {
863 self.universe
864 }
865
866 fn var(self) -> BoundVar {
867 self.bound.var
868 }
869
870 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
871 Placeholder { universe: ui, ..self }
872 }
873
874 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
875 Placeholder { universe: ui, bound }
876 }
877
878 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
879 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
880 }
881}
882
883pub type PlaceholderType = Placeholder<BoundTy>;
884
885impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType {
886 type Bound = BoundTy;
887
888 fn universe(self) -> UniverseIndex {
889 self.universe
890 }
891
892 fn var(self) -> BoundVar {
893 self.bound.var
894 }
895
896 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
897 Placeholder { universe: ui, ..self }
898 }
899
900 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
901 Placeholder { universe: ui, bound }
902 }
903
904 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
905 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
906 }
907}
908
909#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
910#[derive(TyEncodable, TyDecodable)]
911pub struct BoundConst {
912 pub var: BoundVar,
913}
914
915impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
916 fn var(self) -> BoundVar {
917 self.var
918 }
919
920 fn assert_eq(self, var: ty::BoundVariableKind) {
921 var.expect_const()
922 }
923}
924
925pub type PlaceholderConst = Placeholder<BoundConst>;
926
927impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
928 type Bound = BoundConst;
929
930 fn universe(self) -> UniverseIndex {
931 self.universe
932 }
933
934 fn var(self) -> BoundVar {
935 self.bound.var
936 }
937
938 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
939 Placeholder { universe: ui, ..self }
940 }
941
942 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
943 Placeholder { universe: ui, bound }
944 }
945
946 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
947 Placeholder { universe: ui, bound: BoundConst { var } }
948 }
949}
950
951pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
952
953impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
954 fn flags(&self) -> TypeFlags {
955 (**self).flags()
956 }
957
958 fn outer_exclusive_binder(&self) -> DebruijnIndex {
959 (**self).outer_exclusive_binder()
960 }
961}
962
963#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
969#[derive(HashStable, TypeVisitable, TypeFoldable)]
970pub struct ParamEnv<'tcx> {
971 caller_bounds: Clauses<'tcx>,
977}
978
979impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
980 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
981 self.caller_bounds()
982 }
983}
984
985impl<'tcx> ParamEnv<'tcx> {
986 #[inline]
993 pub fn empty() -> Self {
994 Self::new(ListWithCachedTypeInfo::empty())
995 }
996
997 #[inline]
998 pub fn caller_bounds(self) -> Clauses<'tcx> {
999 self.caller_bounds
1000 }
1001
1002 #[inline]
1004 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1005 ParamEnv { caller_bounds }
1006 }
1007
1008 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1010 ParamEnvAnd { param_env: self, value }
1011 }
1012}
1013
1014#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1015#[derive(HashStable)]
1016pub struct ParamEnvAnd<'tcx, T> {
1017 pub param_env: ParamEnv<'tcx>,
1018 pub value: T,
1019}
1020
1021#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1032#[derive(TypeVisitable, TypeFoldable)]
1033pub struct TypingEnv<'tcx> {
1034 #[type_foldable(identity)]
1035 #[type_visitable(ignore)]
1036 pub typing_mode: TypingMode<'tcx>,
1037 pub param_env: ParamEnv<'tcx>,
1038}
1039
1040impl<'tcx> TypingEnv<'tcx> {
1041 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1049 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1050 }
1051
1052 pub fn non_body_analysis(
1058 tcx: TyCtxt<'tcx>,
1059 def_id: impl IntoQueryParam<DefId>,
1060 ) -> TypingEnv<'tcx> {
1061 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1062 }
1063
1064 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1065 tcx.typing_env_normalized_for_post_analysis(def_id)
1066 }
1067
1068 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1071 let TypingEnv { typing_mode, param_env } = self;
1072 if let TypingMode::PostAnalysis = typing_mode {
1073 return self;
1074 }
1075
1076 let param_env = if tcx.next_trait_solver_globally() {
1079 param_env
1080 } else {
1081 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1082 };
1083 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1084 }
1085
1086 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1091 where
1092 T: TypeVisitable<TyCtxt<'tcx>>,
1093 {
1094 PseudoCanonicalInput { typing_env: self, value }
1107 }
1108}
1109
1110#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1120#[derive(HashStable, TypeVisitable, TypeFoldable)]
1121pub struct PseudoCanonicalInput<'tcx, T> {
1122 pub typing_env: TypingEnv<'tcx>,
1123 pub value: T,
1124}
1125
1126#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1127pub struct Destructor {
1128 pub did: DefId,
1130}
1131
1132#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1134pub struct AsyncDestructor {
1135 pub impl_did: DefId,
1137}
1138
1139#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1140pub struct VariantFlags(u8);
1141bitflags::bitflags! {
1142 impl VariantFlags: u8 {
1143 const NO_VARIANT_FLAGS = 0;
1144 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1146 }
1147}
1148rustc_data_structures::external_bitflags_debug! { VariantFlags }
1149
1150#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1152pub struct VariantDef {
1153 pub def_id: DefId,
1156 pub ctor: Option<(CtorKind, DefId)>,
1159 pub name: Symbol,
1161 pub discr: VariantDiscr,
1163 pub fields: IndexVec<FieldIdx, FieldDef>,
1165 tainted: Option<ErrorGuaranteed>,
1167 flags: VariantFlags,
1169}
1170
1171impl VariantDef {
1172 #[instrument(level = "debug")]
1189 pub fn new(
1190 name: Symbol,
1191 variant_did: Option<DefId>,
1192 ctor: Option<(CtorKind, DefId)>,
1193 discr: VariantDiscr,
1194 fields: IndexVec<FieldIdx, FieldDef>,
1195 parent_did: DefId,
1196 recover_tainted: Option<ErrorGuaranteed>,
1197 is_field_list_non_exhaustive: bool,
1198 ) -> Self {
1199 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1200 if is_field_list_non_exhaustive {
1201 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1202 }
1203
1204 VariantDef {
1205 def_id: variant_did.unwrap_or(parent_did),
1206 ctor,
1207 name,
1208 discr,
1209 fields,
1210 flags,
1211 tainted: recover_tainted,
1212 }
1213 }
1214
1215 #[inline]
1221 pub fn is_field_list_non_exhaustive(&self) -> bool {
1222 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1223 }
1224
1225 #[inline]
1228 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1229 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1230 }
1231
1232 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1234 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1235 }
1236
1237 #[inline]
1239 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1240 self.tainted.map_or(Ok(()), Err)
1241 }
1242
1243 #[inline]
1244 pub fn ctor_kind(&self) -> Option<CtorKind> {
1245 self.ctor.map(|(kind, _)| kind)
1246 }
1247
1248 #[inline]
1249 pub fn ctor_def_id(&self) -> Option<DefId> {
1250 self.ctor.map(|(_, def_id)| def_id)
1251 }
1252
1253 #[inline]
1257 pub fn single_field(&self) -> &FieldDef {
1258 assert!(self.fields.len() == 1);
1259
1260 &self.fields[FieldIdx::ZERO]
1261 }
1262
1263 #[inline]
1265 pub fn tail_opt(&self) -> Option<&FieldDef> {
1266 self.fields.raw.last()
1267 }
1268
1269 #[inline]
1275 pub fn tail(&self) -> &FieldDef {
1276 self.tail_opt().expect("expected unsized ADT to have a tail field")
1277 }
1278
1279 pub fn has_unsafe_fields(&self) -> bool {
1281 self.fields.iter().any(|x| x.safety.is_unsafe())
1282 }
1283}
1284
1285impl PartialEq for VariantDef {
1286 #[inline]
1287 fn eq(&self, other: &Self) -> bool {
1288 let Self {
1296 def_id: lhs_def_id,
1297 ctor: _,
1298 name: _,
1299 discr: _,
1300 fields: _,
1301 flags: _,
1302 tainted: _,
1303 } = &self;
1304 let Self {
1305 def_id: rhs_def_id,
1306 ctor: _,
1307 name: _,
1308 discr: _,
1309 fields: _,
1310 flags: _,
1311 tainted: _,
1312 } = other;
1313
1314 let res = lhs_def_id == rhs_def_id;
1315
1316 if cfg!(debug_assertions) && res {
1318 let deep = self.ctor == other.ctor
1319 && self.name == other.name
1320 && self.discr == other.discr
1321 && self.fields == other.fields
1322 && self.flags == other.flags;
1323 assert!(deep, "VariantDef for the same def-id has differing data");
1324 }
1325
1326 res
1327 }
1328}
1329
1330impl Eq for VariantDef {}
1331
1332impl Hash for VariantDef {
1333 #[inline]
1334 fn hash<H: Hasher>(&self, s: &mut H) {
1335 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1343 def_id.hash(s)
1344 }
1345}
1346
1347#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1348pub enum VariantDiscr {
1349 Explicit(DefId),
1352
1353 Relative(u32),
1358}
1359
1360#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1361pub struct FieldDef {
1362 pub did: DefId,
1363 pub name: Symbol,
1364 pub vis: Visibility<DefId>,
1365 pub safety: hir::Safety,
1366 pub value: Option<DefId>,
1367}
1368
1369impl PartialEq for FieldDef {
1370 #[inline]
1371 fn eq(&self, other: &Self) -> bool {
1372 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1380
1381 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1382
1383 let res = lhs_did == rhs_did;
1384
1385 if cfg!(debug_assertions) && res {
1387 let deep =
1388 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1389 assert!(deep, "FieldDef for the same def-id has differing data");
1390 }
1391
1392 res
1393 }
1394}
1395
1396impl Eq for FieldDef {}
1397
1398impl Hash for FieldDef {
1399 #[inline]
1400 fn hash<H: Hasher>(&self, s: &mut H) {
1401 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1409
1410 did.hash(s)
1411 }
1412}
1413
1414impl<'tcx> FieldDef {
1415 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1418 tcx.type_of(self.did).instantiate(tcx, args)
1419 }
1420
1421 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1423 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1424 }
1425}
1426
1427#[derive(Debug, PartialEq, Eq)]
1428pub enum ImplOverlapKind {
1429 Permitted {
1431 marker: bool,
1433 },
1434}
1435
1436#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1439pub enum ImplTraitInTraitData {
1440 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1441 Impl { fn_def_id: DefId },
1442}
1443
1444impl<'tcx> TyCtxt<'tcx> {
1445 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1446 self.typeck(self.hir_body_owner_def_id(body))
1447 }
1448
1449 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1450 self.associated_items(id)
1451 .in_definition_order()
1452 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1453 }
1454
1455 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1456 let mut flags = ReprFlags::empty();
1457 let mut size = None;
1458 let mut max_align: Option<Align> = None;
1459 let mut min_pack: Option<Align> = None;
1460
1461 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1464
1465 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1469 field_shuffle_seed ^= user_seed;
1470 }
1471
1472 if let Some(reprs) =
1473 find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs)
1474 {
1475 for (r, _) in reprs {
1476 flags.insert(match *r {
1477 attr::ReprRust => ReprFlags::empty(),
1478 attr::ReprC => ReprFlags::IS_C,
1479 attr::ReprPacked(pack) => {
1480 min_pack = Some(if let Some(min_pack) = min_pack {
1481 min_pack.min(pack)
1482 } else {
1483 pack
1484 });
1485 ReprFlags::empty()
1486 }
1487 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1488 attr::ReprSimd => ReprFlags::IS_SIMD,
1489 attr::ReprInt(i) => {
1490 size = Some(match i {
1491 attr::IntType::SignedInt(x) => match x {
1492 ast::IntTy::Isize => IntegerType::Pointer(true),
1493 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1494 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1495 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1496 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1497 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1498 },
1499 attr::IntType::UnsignedInt(x) => match x {
1500 ast::UintTy::Usize => IntegerType::Pointer(false),
1501 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1502 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1503 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1504 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1505 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1506 },
1507 });
1508 ReprFlags::empty()
1509 }
1510 attr::ReprAlign(align) => {
1511 max_align = max_align.max(Some(align));
1512 ReprFlags::empty()
1513 }
1514 });
1515 }
1516 }
1517
1518 if self.sess.opts.unstable_opts.randomize_layout {
1521 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1522 }
1523
1524 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1527
1528 if is_box {
1530 flags.insert(ReprFlags::IS_LINEAR);
1531 }
1532
1533 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1534 }
1535
1536 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1538 let def_id = def_id.into_query_param();
1539 if let Some(cnum) = def_id.as_crate_root() {
1540 Some(self.crate_name(cnum))
1541 } else {
1542 let def_key = self.def_key(def_id);
1543 match def_key.disambiguated_data.data {
1544 rustc_hir::definitions::DefPathData::Ctor => self
1546 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1547 _ => def_key.get_opt_name(),
1548 }
1549 }
1550 }
1551
1552 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1559 let id = id.into_query_param();
1560 self.opt_item_name(id).unwrap_or_else(|| {
1561 bug!("item_name: no name for {:?}", self.def_path(id));
1562 })
1563 }
1564
1565 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1569 let def_id = def_id.into_query_param();
1570 let def = self.opt_item_name(def_id)?;
1571 let span = self
1572 .def_ident_span(def_id)
1573 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1574 Some(Ident::new(def, span))
1575 }
1576
1577 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1581 let def_id = def_id.into_query_param();
1582 self.opt_item_ident(def_id).unwrap_or_else(|| {
1583 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1584 })
1585 }
1586
1587 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1588 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1589 Some(self.associated_item(def_id))
1590 } else {
1591 None
1592 }
1593 }
1594
1595 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1599 if let DefKind::AssocTy = self.def_kind(def_id)
1600 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1601 self.associated_item(def_id).kind
1602 {
1603 Some(rpitit_info)
1604 } else {
1605 None
1606 }
1607 }
1608
1609 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1610 variant.fields.iter_enumerated().find_map(|(i, field)| {
1611 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1612 })
1613 }
1614
1615 #[instrument(level = "debug", skip(self), ret)]
1618 pub fn impls_are_allowed_to_overlap(
1619 self,
1620 def_id1: DefId,
1621 def_id2: DefId,
1622 ) -> Option<ImplOverlapKind> {
1623 let impl1 = self.impl_trait_header(def_id1).unwrap();
1624 let impl2 = self.impl_trait_header(def_id2).unwrap();
1625
1626 let trait_ref1 = impl1.trait_ref.skip_binder();
1627 let trait_ref2 = impl2.trait_ref.skip_binder();
1628
1629 if trait_ref1.references_error() || trait_ref2.references_error() {
1632 return Some(ImplOverlapKind::Permitted { marker: false });
1633 }
1634
1635 match (impl1.polarity, impl2.polarity) {
1636 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1637 return Some(ImplOverlapKind::Permitted { marker: false });
1639 }
1640 (ImplPolarity::Positive, ImplPolarity::Negative)
1641 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1642 return None;
1644 }
1645 (ImplPolarity::Positive, ImplPolarity::Positive)
1646 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1647 };
1648
1649 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1650 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1651
1652 if is_marker_overlap {
1653 return Some(ImplOverlapKind::Permitted { marker: true });
1654 }
1655
1656 None
1657 }
1658
1659 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1662 match res {
1663 Res::Def(DefKind::Variant, did) => {
1664 let enum_did = self.parent(did);
1665 self.adt_def(enum_did).variant_with_id(did)
1666 }
1667 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1668 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1669 let variant_did = self.parent(variant_ctor_did);
1670 let enum_did = self.parent(variant_did);
1671 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1672 }
1673 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1674 let struct_did = self.parent(ctor_did);
1675 self.adt_def(struct_did).non_enum_variant()
1676 }
1677 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1678 }
1679 }
1680
1681 #[instrument(skip(self), level = "debug")]
1683 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1684 match instance {
1685 ty::InstanceKind::Item(def) => {
1686 debug!("calling def_kind on def: {:?}", def);
1687 let def_kind = self.def_kind(def);
1688 debug!("returned from def_kind: {:?}", def_kind);
1689 match def_kind {
1690 DefKind::Const
1691 | DefKind::Static { .. }
1692 | DefKind::AssocConst
1693 | DefKind::Ctor(..)
1694 | DefKind::AnonConst
1695 | DefKind::InlineConst => self.mir_for_ctfe(def),
1696 _ => self.optimized_mir(def),
1699 }
1700 }
1701 ty::InstanceKind::VTableShim(..)
1702 | ty::InstanceKind::ReifyShim(..)
1703 | ty::InstanceKind::Intrinsic(..)
1704 | ty::InstanceKind::FnPtrShim(..)
1705 | ty::InstanceKind::Virtual(..)
1706 | ty::InstanceKind::ClosureOnceShim { .. }
1707 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1708 | ty::InstanceKind::FutureDropPollShim(..)
1709 | ty::InstanceKind::DropGlue(..)
1710 | ty::InstanceKind::CloneShim(..)
1711 | ty::InstanceKind::ThreadLocalShim(..)
1712 | ty::InstanceKind::FnPtrAddrShim(..)
1713 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1714 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1715 }
1716 }
1717
1718 pub fn get_attrs(
1720 self,
1721 did: impl Into<DefId>,
1722 attr: Symbol,
1723 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1724 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1725 }
1726
1727 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1732 let did: DefId = did.into();
1733 if let Some(did) = did.as_local() {
1734 self.hir_attrs(self.local_def_id_to_hir_id(did))
1735 } else {
1736 self.attrs_for_def(did)
1737 }
1738 }
1739
1740 pub fn get_diagnostic_attr(
1749 self,
1750 did: impl Into<DefId>,
1751 attr: Symbol,
1752 ) -> Option<&'tcx hir::Attribute> {
1753 let did: DefId = did.into();
1754 if did.as_local().is_some() {
1755 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1757 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1758 } else {
1759 None
1760 }
1761 } else {
1762 debug_assert!(rustc_feature::encode_cross_crate(attr));
1765 self.attrs_for_def(did)
1766 .iter()
1767 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1768 }
1769 }
1770
1771 pub fn get_attrs_by_path(
1772 self,
1773 did: DefId,
1774 attr: &[Symbol],
1775 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1776 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1777 if let Some(did) = did.as_local() {
1778 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1779 } else {
1780 self.attrs_for_def(did).iter().filter(filter_fn)
1781 }
1782 }
1783
1784 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1785 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1786 let did: DefId = did.into();
1787 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1788 } else {
1789 self.get_attrs(did, attr).next()
1790 }
1791 }
1792
1793 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1795 self.get_attrs(did, attr).next().is_some()
1796 }
1797
1798 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1800 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1801 }
1802
1803 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1805 self.trait_def(trait_def_id).has_auto_impl
1806 }
1807
1808 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1811 self.trait_def(trait_def_id).is_coinductive
1812 }
1813
1814 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1816 self.def_kind(trait_def_id) == DefKind::TraitAlias
1817 }
1818
1819 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1821 self.arena.alloc(err)
1822 }
1823
1824 fn ordinary_coroutine_layout(
1830 self,
1831 def_id: DefId,
1832 args: GenericArgsRef<'tcx>,
1833 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1834 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1835 let mir = self.optimized_mir(def_id);
1836 let ty = || Ty::new_coroutine(self, def_id, args);
1837 if coroutine_kind_ty.is_unit() {
1839 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1840 } else {
1841 let ty::Coroutine(_, identity_args) =
1844 *self.type_of(def_id).instantiate_identity().kind()
1845 else {
1846 unreachable!();
1847 };
1848 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1849 if identity_kind_ty == coroutine_kind_ty {
1852 mir.coroutine_layout_raw()
1853 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1854 } else {
1855 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1856 assert_matches!(
1857 identity_kind_ty.to_opt_closure_kind(),
1858 Some(ClosureKind::Fn | ClosureKind::FnMut)
1859 );
1860 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1861 .coroutine_layout_raw()
1862 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1863 }
1864 }
1865 }
1866
1867 fn async_drop_coroutine_layout(
1871 self,
1872 def_id: DefId,
1873 args: GenericArgsRef<'tcx>,
1874 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1875 let ty = || Ty::new_coroutine(self, def_id, args);
1876 if args[0].has_placeholders() || args[0].has_non_region_param() {
1877 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1878 }
1879 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1880 self.mir_shims(instance)
1881 .coroutine_layout_raw()
1882 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1883 }
1884
1885 pub fn coroutine_layout(
1888 self,
1889 def_id: DefId,
1890 args: GenericArgsRef<'tcx>,
1891 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1892 if self.is_async_drop_in_place_coroutine(def_id) {
1893 let arg_cor_ty = args.first().unwrap().expect_ty();
1897 if arg_cor_ty.is_coroutine() {
1898 let span = self.def_span(def_id);
1899 let source_info = SourceInfo::outermost(span);
1900 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1903 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1904 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1905 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1906 let proxy_layout = CoroutineLayout {
1907 field_tys: [].into(),
1908 field_names: [].into(),
1909 variant_fields,
1910 variant_source_info,
1911 storage_conflicts: BitMatrix::new(0, 0),
1912 };
1913 return Ok(self.arena.alloc(proxy_layout));
1914 } else {
1915 self.async_drop_coroutine_layout(def_id, args)
1916 }
1917 } else {
1918 self.ordinary_coroutine_layout(def_id, args)
1919 }
1920 }
1921
1922 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1925 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1926 }
1927
1928 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1930 if !self.def_kind(def_id).is_assoc() {
1931 return None;
1932 }
1933 let parent = self.parent(def_id);
1934 let def_kind = self.def_kind(parent);
1935 Some((parent, def_kind))
1936 }
1937
1938 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1941 match self.assoc_parent(def_id) {
1942 Some((id, DefKind::Trait)) => Some(id),
1943 _ => None,
1944 }
1945 }
1946
1947 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1950 match self.assoc_parent(def_id) {
1951 Some((id, DefKind::Impl { .. })) => Some(id),
1952 _ => None,
1953 }
1954 }
1955
1956 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1959 match self.assoc_parent(def_id) {
1960 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
1961 _ => None,
1962 }
1963 }
1964
1965 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1968 match self.assoc_parent(def_id) {
1969 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
1970 _ => None,
1971 }
1972 }
1973
1974 pub fn is_exportable(self, def_id: DefId) -> bool {
1975 self.exportable_items(def_id.krate).contains(&def_id)
1976 }
1977
1978 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1981 if self.is_automatically_derived(def_id)
1982 && let Some(def_id) = def_id.as_local()
1983 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1984 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1985 && find_attr!(
1986 self.get_all_attrs(outer.macro_def_id.unwrap()),
1987 AttributeKind::RustcBuiltinMacro { .. }
1988 )
1989 {
1990 true
1991 } else {
1992 false
1993 }
1994 }
1995
1996 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1998 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
1999 }
2000
2001 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2004 if let Some(impl_def_id) = impl_def_id.as_local() {
2005 Ok(self.def_span(impl_def_id))
2006 } else {
2007 Err(self.crate_name(impl_def_id.krate))
2008 }
2009 }
2010
2011 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2015 use_ident.name == def_ident.name
2019 && use_ident
2020 .span
2021 .ctxt()
2022 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2023 }
2024
2025 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2026 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2027 ident
2028 }
2029
2030 pub fn adjust_ident_and_get_scope(
2032 self,
2033 mut ident: Ident,
2034 scope: DefId,
2035 block: hir::HirId,
2036 ) -> (Ident, DefId) {
2037 let scope = ident
2038 .span
2039 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2040 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2041 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2042 (ident, scope)
2043 }
2044
2045 #[inline]
2049 pub fn is_const_fn(self, def_id: DefId) -> bool {
2050 matches!(
2051 self.def_kind(def_id),
2052 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2053 ) && self.constness(def_id) == hir::Constness::Const
2054 }
2055
2056 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2063 let def_id: DefId = def_id.into();
2064 match self.def_kind(def_id) {
2065 DefKind::Impl { of_trait: true } => {
2066 let header = self.impl_trait_header(def_id).unwrap();
2067 header.constness == hir::Constness::Const
2068 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2069 }
2070 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2071 self.constness(def_id) == hir::Constness::Const
2072 }
2073 DefKind::Trait => self.is_const_trait(def_id),
2074 DefKind::AssocTy => {
2075 let parent_def_id = self.parent(def_id);
2076 match self.def_kind(parent_def_id) {
2077 DefKind::Impl { of_trait: false } => false,
2078 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2079 self.is_conditionally_const(parent_def_id)
2080 }
2081 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2082 }
2083 }
2084 DefKind::AssocFn => {
2085 let parent_def_id = self.parent(def_id);
2086 match self.def_kind(parent_def_id) {
2087 DefKind::Impl { of_trait: false } => {
2088 self.constness(def_id) == hir::Constness::Const
2089 }
2090 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2091 self.is_conditionally_const(parent_def_id)
2092 }
2093 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2094 }
2095 }
2096 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2097 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2098 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2099 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2101 },
2102 DefKind::Closure => {
2103 false
2106 }
2107 DefKind::Ctor(_, CtorKind::Const)
2108 | DefKind::Impl { of_trait: false }
2109 | DefKind::Mod
2110 | DefKind::Struct
2111 | DefKind::Union
2112 | DefKind::Enum
2113 | DefKind::Variant
2114 | DefKind::TyAlias
2115 | DefKind::ForeignTy
2116 | DefKind::TraitAlias
2117 | DefKind::TyParam
2118 | DefKind::Const
2119 | DefKind::ConstParam
2120 | DefKind::Static { .. }
2121 | DefKind::AssocConst
2122 | DefKind::Macro(_)
2123 | DefKind::ExternCrate
2124 | DefKind::Use
2125 | DefKind::ForeignMod
2126 | DefKind::AnonConst
2127 | DefKind::InlineConst
2128 | DefKind::Field
2129 | DefKind::LifetimeParam
2130 | DefKind::GlobalAsm
2131 | DefKind::SyntheticCoroutineBody => false,
2132 }
2133 }
2134
2135 #[inline]
2136 pub fn is_const_trait(self, def_id: DefId) -> bool {
2137 self.trait_def(def_id).constness == hir::Constness::Const
2138 }
2139
2140 #[inline]
2141 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2142 matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2143 }
2144
2145 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2146 if self.def_kind(def_id) != DefKind::AssocFn {
2147 return false;
2148 }
2149
2150 let Some(item) = self.opt_associated_item(def_id) else {
2151 return false;
2152 };
2153 if item.container != ty::AssocItemContainer::Impl {
2154 return false;
2155 }
2156
2157 let Some(trait_item_def_id) = item.trait_item_def_id else {
2158 return false;
2159 };
2160
2161 return !self
2162 .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id)
2163 .is_empty();
2164 }
2165}
2166
2167pub fn provide(providers: &mut Providers) {
2168 closure::provide(providers);
2169 context::provide(providers);
2170 erase_regions::provide(providers);
2171 inhabitedness::provide(providers);
2172 util::provide(providers);
2173 print::provide(providers);
2174 super::util::bug::provide(providers);
2175 *providers = Providers {
2176 trait_impls_of: trait_def::trait_impls_of_provider,
2177 incoherent_impls: trait_def::incoherent_impls_provider,
2178 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2179 traits: trait_def::traits_provider,
2180 vtable_allocation: vtable::vtable_allocation_provider,
2181 ..*providers
2182 };
2183}
2184
2185#[derive(Clone, Debug, Default, HashStable)]
2191pub struct CrateInherentImpls {
2192 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2193 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2194}
2195
2196#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2197pub struct SymbolName<'tcx> {
2198 pub name: &'tcx str,
2200}
2201
2202impl<'tcx> SymbolName<'tcx> {
2203 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2204 SymbolName { name: tcx.arena.alloc_str(name) }
2205 }
2206}
2207
2208impl<'tcx> fmt::Display for SymbolName<'tcx> {
2209 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2210 fmt::Display::fmt(&self.name, fmt)
2211 }
2212}
2213
2214impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2215 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2216 fmt::Display::fmt(&self.name, fmt)
2217 }
2218}
2219
2220#[derive(Copy, Clone, Debug, HashStable)]
2222pub struct DestructuredConst<'tcx> {
2223 pub variant: Option<VariantIdx>,
2224 pub fields: &'tcx [ty::Const<'tcx>],
2225}