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};
112use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
113use crate::metadata::ModChild;
114use crate::middle::privacy::EffectiveVisibilities;
115use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
116use crate::query::{IntoQueryParam, Providers};
117use crate::ty;
118use crate::ty::codec::{TyDecoder, TyEncoder};
119pub use crate::ty::diagnostics::*;
120use crate::ty::fast_reject::SimplifiedType;
121use crate::ty::layout::LayoutError;
122use crate::ty::util::Discr;
123use crate::ty::walk::TypeWalker;
124
125pub mod abstract_const;
126pub mod adjustment;
127pub mod cast;
128pub mod codec;
129pub mod error;
130pub mod fast_reject;
131pub mod inhabitedness;
132pub mod layout;
133pub mod normalize_erasing_regions;
134pub mod pattern;
135pub mod print;
136pub mod relate;
137pub mod significant_drop_order;
138pub mod trait_def;
139pub mod util;
140pub mod vtable;
141
142mod adt;
143mod assoc;
144mod closure;
145mod consts;
146mod context;
147mod diagnostics;
148mod elaborate_impl;
149mod erase_regions;
150mod fold;
151mod generic_args;
152mod generics;
153mod impls_ty;
154mod instance;
155mod intrinsic;
156mod list;
157mod opaque_types;
158mod predicate;
159mod region;
160mod rvalue_scopes;
161mod structural_impls;
162#[allow(hidden_glob_reexports)]
163mod sty;
164mod typeck_results;
165mod visit;
166
167#[derive(Debug, HashStable)]
170pub struct ResolverGlobalCtxt {
171 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
172 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
174 pub effective_visibilities: EffectiveVisibilities,
175 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
176 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
177 pub module_children: LocalDefIdMap<Vec<ModChild>>,
178 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
179 pub main_def: Option<MainDefinition>,
180 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
181 pub proc_macros: Vec<LocalDefId>,
184 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
187 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
188 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
189 pub all_macro_rules: UnordSet<Symbol>,
190 pub stripped_cfg_items: Vec<StrippedCfgItem>,
191}
192
193#[derive(Debug)]
196pub struct ResolverAstLowering {
197 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
198
199 pub partial_res_map: NodeMap<hir::def::PartialRes>,
201 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
203 pub label_res_map: NodeMap<ast::NodeId>,
205 pub lifetimes_res_map: NodeMap<LifetimeRes>,
207 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
209
210 pub next_node_id: ast::NodeId,
211
212 pub node_id_to_def_id: NodeMap<LocalDefId>,
213
214 pub disambiguator: DisambiguatorState,
215
216 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
217 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
219
220 pub lint_buffer: Steal<LintBuffer>,
222
223 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
225}
226
227#[derive(Debug)]
228pub struct DelegationFnSig {
229 pub header: ast::FnHeader,
230 pub param_count: usize,
231 pub has_self: bool,
232 pub c_variadic: bool,
233 pub target_feature: bool,
234}
235
236#[derive(Clone, Copy, Debug, HashStable)]
237pub struct MainDefinition {
238 pub res: Res<ast::NodeId>,
239 pub is_import: bool,
240 pub span: Span,
241}
242
243impl MainDefinition {
244 pub fn opt_fn_def_id(self) -> Option<DefId> {
245 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
246 }
247}
248
249#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
250pub struct ImplTraitHeader<'tcx> {
251 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
252 pub polarity: ImplPolarity,
253 pub safety: hir::Safety,
254 pub constness: hir::Constness,
255}
256
257#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
258#[derive(TypeFoldable, TypeVisitable)]
259pub enum Asyncness {
260 Yes,
261 No,
262}
263
264impl Asyncness {
265 pub fn is_async(self) -> bool {
266 matches!(self, Asyncness::Yes)
267 }
268}
269
270#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
271pub enum Visibility<Id = LocalDefId> {
272 Public,
274 Restricted(Id),
276}
277
278impl Visibility {
279 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
280 match self {
281 ty::Visibility::Restricted(restricted_id) => {
282 if restricted_id.is_top_level_module() {
283 "pub(crate)".to_string()
284 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
285 "pub(self)".to_string()
286 } else {
287 format!(
288 "pub(in crate{})",
289 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
290 )
291 }
292 }
293 ty::Visibility::Public => "pub".to_string(),
294 }
295 }
296}
297
298#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
299#[derive(TypeFoldable, TypeVisitable)]
300pub struct ClosureSizeProfileData<'tcx> {
301 pub before_feature_tys: Ty<'tcx>,
303 pub after_feature_tys: Ty<'tcx>,
305}
306
307impl TyCtxt<'_> {
308 #[inline]
309 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
310 self.def_key(id).parent.map(|index| DefId { index, ..id })
311 }
312
313 #[inline]
314 #[track_caller]
315 pub fn parent(self, id: DefId) -> DefId {
316 match self.opt_parent(id) {
317 Some(id) => id,
318 None => bug!("{id:?} doesn't have a parent"),
320 }
321 }
322
323 #[inline]
324 #[track_caller]
325 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
326 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
327 }
328
329 #[inline]
330 #[track_caller]
331 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
332 self.parent(id.into().to_def_id()).expect_local()
333 }
334
335 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
336 if descendant.krate != ancestor.krate {
337 return false;
338 }
339
340 while descendant != ancestor {
341 match self.opt_parent(descendant) {
342 Some(parent) => descendant = parent,
343 None => return false,
344 }
345 }
346 true
347 }
348}
349
350impl<Id> Visibility<Id> {
351 pub fn is_public(self) -> bool {
352 matches!(self, Visibility::Public)
353 }
354
355 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
356 match self {
357 Visibility::Public => Visibility::Public,
358 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
359 }
360 }
361}
362
363impl<Id: Into<DefId>> Visibility<Id> {
364 pub fn to_def_id(self) -> Visibility<DefId> {
365 self.map_id(Into::into)
366 }
367
368 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
370 match self {
371 Visibility::Public => true,
373 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
374 }
375 }
376
377 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
379 match vis {
380 Visibility::Public => self.is_public(),
381 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
382 }
383 }
384}
385
386impl Visibility<DefId> {
387 pub fn expect_local(self) -> Visibility {
388 self.map_id(|id| id.expect_local())
389 }
390
391 pub fn is_visible_locally(self) -> bool {
393 match self {
394 Visibility::Public => true,
395 Visibility::Restricted(def_id) => def_id.is_local(),
396 }
397 }
398}
399
400#[derive(HashStable, Debug)]
407pub struct CrateVariancesMap<'tcx> {
408 pub variances: DefIdMap<&'tcx [ty::Variance]>,
412}
413
414#[derive(Copy, Clone, PartialEq, Eq, Hash)]
417pub struct CReaderCacheKey {
418 pub cnum: Option<CrateNum>,
419 pub pos: usize,
420}
421
422#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
424#[rustc_diagnostic_item = "Ty"]
425#[rustc_pass_by_value]
426pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
427
428impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
429 type Kind = TyKind<'tcx>;
430
431 fn kind(self) -> TyKind<'tcx> {
432 *self.kind()
433 }
434}
435
436impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
437 fn flags(&self) -> TypeFlags {
438 self.0.flags
439 }
440
441 fn outer_exclusive_binder(&self) -> DebruijnIndex {
442 self.0.outer_exclusive_binder
443 }
444}
445
446#[derive(HashStable, Debug)]
453pub struct CratePredicatesMap<'tcx> {
454 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
458}
459
460#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
461pub struct Term<'tcx> {
462 ptr: NonNull<()>,
463 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
464}
465
466impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
467
468impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
469 type Kind = TermKind<'tcx>;
470
471 fn kind(self) -> Self::Kind {
472 self.kind()
473 }
474}
475
476unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
477 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
478{
479}
480unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
481 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
482{
483}
484unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
485unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
486
487impl Debug for Term<'_> {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 match self.kind() {
490 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
491 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
492 }
493 }
494}
495
496impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
497 fn from(ty: Ty<'tcx>) -> Self {
498 TermKind::Ty(ty).pack()
499 }
500}
501
502impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
503 fn from(c: Const<'tcx>) -> Self {
504 TermKind::Const(c).pack()
505 }
506}
507
508impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
509 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
510 self.kind().hash_stable(hcx, hasher);
511 }
512}
513
514impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
515 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
516 self,
517 folder: &mut F,
518 ) -> Result<Self, F::Error> {
519 match self.kind() {
520 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
521 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
522 }
523 }
524
525 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
526 match self.kind() {
527 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
528 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
529 }
530 }
531}
532
533impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
534 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
535 match self.kind() {
536 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
537 ty::TermKind::Const(ct) => ct.visit_with(visitor),
538 }
539 }
540}
541
542impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
543 fn encode(&self, e: &mut E) {
544 self.kind().encode(e)
545 }
546}
547
548impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
549 fn decode(d: &mut D) -> Self {
550 let res: TermKind<'tcx> = Decodable::decode(d);
551 res.pack()
552 }
553}
554
555impl<'tcx> Term<'tcx> {
556 #[inline]
557 pub fn kind(self) -> TermKind<'tcx> {
558 let ptr =
559 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
560 unsafe {
564 match self.ptr.addr().get() & TAG_MASK {
565 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
566 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
567 ))),
568 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
569 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
570 ))),
571 _ => core::intrinsics::unreachable(),
572 }
573 }
574 }
575
576 pub fn as_type(&self) -> Option<Ty<'tcx>> {
577 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
578 }
579
580 pub fn expect_type(&self) -> Ty<'tcx> {
581 self.as_type().expect("expected a type, but found a const")
582 }
583
584 pub fn as_const(&self) -> Option<Const<'tcx>> {
585 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
586 }
587
588 pub fn expect_const(&self) -> Const<'tcx> {
589 self.as_const().expect("expected a const, but found a type")
590 }
591
592 pub fn into_arg(self) -> GenericArg<'tcx> {
593 match self.kind() {
594 TermKind::Ty(ty) => ty.into(),
595 TermKind::Const(c) => c.into(),
596 }
597 }
598
599 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
600 match self.kind() {
601 TermKind::Ty(ty) => match *ty.kind() {
602 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
603 _ => None,
604 },
605 TermKind::Const(ct) => match ct.kind() {
606 ConstKind::Unevaluated(uv) => Some(uv.into()),
607 _ => None,
608 },
609 }
610 }
611
612 pub fn is_infer(&self) -> bool {
613 match self.kind() {
614 TermKind::Ty(ty) => ty.is_ty_var(),
615 TermKind::Const(ct) => ct.is_ct_infer(),
616 }
617 }
618
619 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
620 match self.kind() {
621 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
622 TermKind::Const(ct) => ct.is_trivially_wf(),
623 }
624 }
625
626 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
637 TypeWalker::new(self.into())
638 }
639}
640
641const TAG_MASK: usize = 0b11;
642const TYPE_TAG: usize = 0b00;
643const CONST_TAG: usize = 0b01;
644
645#[extension(pub trait TermKindPackExt<'tcx>)]
646impl<'tcx> TermKind<'tcx> {
647 #[inline]
648 fn pack(self) -> Term<'tcx> {
649 let (tag, ptr) = match self {
650 TermKind::Ty(ty) => {
651 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
653 (TYPE_TAG, NonNull::from(ty.0.0).cast())
654 }
655 TermKind::Const(ct) => {
656 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
658 (CONST_TAG, NonNull::from(ct.0.0).cast())
659 }
660 };
661
662 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
663 }
664}
665
666#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
686pub struct InstantiatedPredicates<'tcx> {
687 pub predicates: Vec<Clause<'tcx>>,
688 pub spans: Vec<Span>,
689}
690
691impl<'tcx> InstantiatedPredicates<'tcx> {
692 pub fn empty() -> InstantiatedPredicates<'tcx> {
693 InstantiatedPredicates { predicates: vec![], spans: vec![] }
694 }
695
696 pub fn is_empty(&self) -> bool {
697 self.predicates.is_empty()
698 }
699
700 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
701 self.into_iter()
702 }
703}
704
705impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
706 type Item = (Clause<'tcx>, Span);
707
708 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
709
710 fn into_iter(self) -> Self::IntoIter {
711 debug_assert_eq!(self.predicates.len(), self.spans.len());
712 std::iter::zip(self.predicates, self.spans)
713 }
714}
715
716impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
717 type Item = (Clause<'tcx>, Span);
718
719 type IntoIter = std::iter::Zip<
720 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
721 std::iter::Copied<std::slice::Iter<'a, Span>>,
722 >;
723
724 fn into_iter(self) -> Self::IntoIter {
725 debug_assert_eq!(self.predicates.len(), self.spans.len());
726 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
727 }
728}
729
730#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
731pub struct OpaqueHiddenType<'tcx> {
732 pub span: Span,
746
747 pub ty: Ty<'tcx>,
760}
761
762#[derive(Debug, Clone, Copy)]
764pub enum DefiningScopeKind {
765 HirTypeck,
770 MirBorrowck,
771}
772
773impl<'tcx> OpaqueHiddenType<'tcx> {
774 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> OpaqueHiddenType<'tcx> {
775 OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
776 }
777
778 pub fn build_mismatch_error(
779 &self,
780 other: &Self,
781 tcx: TyCtxt<'tcx>,
782 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
783 (self.ty, other.ty).error_reported()?;
784 let sub_diag = if self.span == other.span {
786 TypeMismatchReason::ConflictType { span: self.span }
787 } else {
788 TypeMismatchReason::PreviousUse { span: self.span }
789 };
790 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
791 self_ty: self.ty,
792 other_ty: other.ty,
793 other_span: other.span,
794 sub: sub_diag,
795 }))
796 }
797
798 #[instrument(level = "debug", skip(tcx), ret)]
799 pub fn remap_generic_params_to_declaration_params(
800 self,
801 opaque_type_key: OpaqueTypeKey<'tcx>,
802 tcx: TyCtxt<'tcx>,
803 defining_scope_kind: DefiningScopeKind,
804 ) -> Self {
805 let OpaqueTypeKey { def_id, args } = opaque_type_key;
806
807 let id_args = GenericArgs::identity_for_item(tcx, def_id);
814 debug!(?id_args);
815
816 let map = args.iter().zip(id_args).collect();
820 debug!("map = {:#?}", map);
821
822 let this = match defining_scope_kind {
828 DefiningScopeKind::HirTypeck => fold_regions(tcx, self, |_, _| tcx.lifetimes.re_erased),
829 DefiningScopeKind::MirBorrowck => self,
830 };
831 let result = this.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
832 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
833 assert_eq!(result.ty, fold_regions(tcx, result.ty, |_, _| tcx.lifetimes.re_erased));
834 }
835 result
836 }
837}
838
839#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
844#[derive(HashStable, TyEncodable, TyDecodable)]
845pub struct Placeholder<T> {
846 pub universe: UniverseIndex,
847 pub bound: T,
848}
849
850pub type PlaceholderRegion = Placeholder<BoundRegion>;
851
852impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion {
853 type Bound = BoundRegion;
854
855 fn universe(self) -> UniverseIndex {
856 self.universe
857 }
858
859 fn var(self) -> BoundVar {
860 self.bound.var
861 }
862
863 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
864 Placeholder { universe: ui, ..self }
865 }
866
867 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
868 Placeholder { universe: ui, bound }
869 }
870
871 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
872 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
873 }
874}
875
876pub type PlaceholderType = Placeholder<BoundTy>;
877
878impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType {
879 type Bound = BoundTy;
880
881 fn universe(self) -> UniverseIndex {
882 self.universe
883 }
884
885 fn var(self) -> BoundVar {
886 self.bound.var
887 }
888
889 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
890 Placeholder { universe: ui, ..self }
891 }
892
893 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
894 Placeholder { universe: ui, bound }
895 }
896
897 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
898 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
899 }
900}
901
902#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
903#[derive(TyEncodable, TyDecodable)]
904pub struct BoundConst {
905 pub var: BoundVar,
906}
907
908impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
909 fn var(self) -> BoundVar {
910 self.var
911 }
912
913 fn assert_eq(self, var: ty::BoundVariableKind) {
914 var.expect_const()
915 }
916}
917
918pub type PlaceholderConst = Placeholder<BoundConst>;
919
920impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
921 type Bound = BoundConst;
922
923 fn universe(self) -> UniverseIndex {
924 self.universe
925 }
926
927 fn var(self) -> BoundVar {
928 self.bound.var
929 }
930
931 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
932 Placeholder { universe: ui, ..self }
933 }
934
935 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
936 Placeholder { universe: ui, bound }
937 }
938
939 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
940 Placeholder { universe: ui, bound: BoundConst { var } }
941 }
942}
943
944pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
945
946impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
947 fn flags(&self) -> TypeFlags {
948 (**self).flags()
949 }
950
951 fn outer_exclusive_binder(&self) -> DebruijnIndex {
952 (**self).outer_exclusive_binder()
953 }
954}
955
956#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
962#[derive(HashStable, TypeVisitable, TypeFoldable)]
963pub struct ParamEnv<'tcx> {
964 caller_bounds: Clauses<'tcx>,
970}
971
972impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
973 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
974 self.caller_bounds()
975 }
976}
977
978impl<'tcx> ParamEnv<'tcx> {
979 #[inline]
986 pub fn empty() -> Self {
987 Self::new(ListWithCachedTypeInfo::empty())
988 }
989
990 #[inline]
991 pub fn caller_bounds(self) -> Clauses<'tcx> {
992 self.caller_bounds
993 }
994
995 #[inline]
997 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
998 ParamEnv { caller_bounds }
999 }
1000
1001 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1003 ParamEnvAnd { param_env: self, value }
1004 }
1005}
1006
1007#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1008#[derive(HashStable)]
1009pub struct ParamEnvAnd<'tcx, T> {
1010 pub param_env: ParamEnv<'tcx>,
1011 pub value: T,
1012}
1013
1014#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1025#[derive(TypeVisitable, TypeFoldable)]
1026pub struct TypingEnv<'tcx> {
1027 #[type_foldable(identity)]
1028 #[type_visitable(ignore)]
1029 pub typing_mode: TypingMode<'tcx>,
1030 pub param_env: ParamEnv<'tcx>,
1031}
1032
1033impl<'tcx> TypingEnv<'tcx> {
1034 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1042 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1043 }
1044
1045 pub fn non_body_analysis(
1051 tcx: TyCtxt<'tcx>,
1052 def_id: impl IntoQueryParam<DefId>,
1053 ) -> TypingEnv<'tcx> {
1054 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1055 }
1056
1057 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1058 tcx.typing_env_normalized_for_post_analysis(def_id)
1059 }
1060
1061 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1064 let TypingEnv { typing_mode, param_env } = self;
1065 if let TypingMode::PostAnalysis = typing_mode {
1066 return self;
1067 }
1068
1069 let param_env = if tcx.next_trait_solver_globally() {
1072 param_env
1073 } else {
1074 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1075 };
1076 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1077 }
1078
1079 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1084 where
1085 T: TypeVisitable<TyCtxt<'tcx>>,
1086 {
1087 PseudoCanonicalInput { typing_env: self, value }
1100 }
1101}
1102
1103#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1113#[derive(HashStable, TypeVisitable, TypeFoldable)]
1114pub struct PseudoCanonicalInput<'tcx, T> {
1115 pub typing_env: TypingEnv<'tcx>,
1116 pub value: T,
1117}
1118
1119#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1120pub struct Destructor {
1121 pub did: DefId,
1123}
1124
1125#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1127pub struct AsyncDestructor {
1128 pub impl_did: DefId,
1130}
1131
1132#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1133pub struct VariantFlags(u8);
1134bitflags::bitflags! {
1135 impl VariantFlags: u8 {
1136 const NO_VARIANT_FLAGS = 0;
1137 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1139 }
1140}
1141rustc_data_structures::external_bitflags_debug! { VariantFlags }
1142
1143#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1145pub struct VariantDef {
1146 pub def_id: DefId,
1149 pub ctor: Option<(CtorKind, DefId)>,
1152 pub name: Symbol,
1154 pub discr: VariantDiscr,
1156 pub fields: IndexVec<FieldIdx, FieldDef>,
1158 tainted: Option<ErrorGuaranteed>,
1160 flags: VariantFlags,
1162}
1163
1164impl VariantDef {
1165 #[instrument(level = "debug")]
1182 pub fn new(
1183 name: Symbol,
1184 variant_did: Option<DefId>,
1185 ctor: Option<(CtorKind, DefId)>,
1186 discr: VariantDiscr,
1187 fields: IndexVec<FieldIdx, FieldDef>,
1188 parent_did: DefId,
1189 recover_tainted: Option<ErrorGuaranteed>,
1190 is_field_list_non_exhaustive: bool,
1191 ) -> Self {
1192 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1193 if is_field_list_non_exhaustive {
1194 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1195 }
1196
1197 VariantDef {
1198 def_id: variant_did.unwrap_or(parent_did),
1199 ctor,
1200 name,
1201 discr,
1202 fields,
1203 flags,
1204 tainted: recover_tainted,
1205 }
1206 }
1207
1208 #[inline]
1214 pub fn is_field_list_non_exhaustive(&self) -> bool {
1215 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1216 }
1217
1218 #[inline]
1221 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1222 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1223 }
1224
1225 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1227 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1228 }
1229
1230 #[inline]
1232 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1233 self.tainted.map_or(Ok(()), Err)
1234 }
1235
1236 #[inline]
1237 pub fn ctor_kind(&self) -> Option<CtorKind> {
1238 self.ctor.map(|(kind, _)| kind)
1239 }
1240
1241 #[inline]
1242 pub fn ctor_def_id(&self) -> Option<DefId> {
1243 self.ctor.map(|(_, def_id)| def_id)
1244 }
1245
1246 #[inline]
1250 pub fn single_field(&self) -> &FieldDef {
1251 assert!(self.fields.len() == 1);
1252
1253 &self.fields[FieldIdx::ZERO]
1254 }
1255
1256 #[inline]
1258 pub fn tail_opt(&self) -> Option<&FieldDef> {
1259 self.fields.raw.last()
1260 }
1261
1262 #[inline]
1268 pub fn tail(&self) -> &FieldDef {
1269 self.tail_opt().expect("expected unsized ADT to have a tail field")
1270 }
1271
1272 pub fn has_unsafe_fields(&self) -> bool {
1274 self.fields.iter().any(|x| x.safety.is_unsafe())
1275 }
1276}
1277
1278impl PartialEq for VariantDef {
1279 #[inline]
1280 fn eq(&self, other: &Self) -> bool {
1281 let Self {
1289 def_id: lhs_def_id,
1290 ctor: _,
1291 name: _,
1292 discr: _,
1293 fields: _,
1294 flags: _,
1295 tainted: _,
1296 } = &self;
1297 let Self {
1298 def_id: rhs_def_id,
1299 ctor: _,
1300 name: _,
1301 discr: _,
1302 fields: _,
1303 flags: _,
1304 tainted: _,
1305 } = other;
1306
1307 let res = lhs_def_id == rhs_def_id;
1308
1309 if cfg!(debug_assertions) && res {
1311 let deep = self.ctor == other.ctor
1312 && self.name == other.name
1313 && self.discr == other.discr
1314 && self.fields == other.fields
1315 && self.flags == other.flags;
1316 assert!(deep, "VariantDef for the same def-id has differing data");
1317 }
1318
1319 res
1320 }
1321}
1322
1323impl Eq for VariantDef {}
1324
1325impl Hash for VariantDef {
1326 #[inline]
1327 fn hash<H: Hasher>(&self, s: &mut H) {
1328 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1336 def_id.hash(s)
1337 }
1338}
1339
1340#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1341pub enum VariantDiscr {
1342 Explicit(DefId),
1345
1346 Relative(u32),
1351}
1352
1353#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1354pub struct FieldDef {
1355 pub did: DefId,
1356 pub name: Symbol,
1357 pub vis: Visibility<DefId>,
1358 pub safety: hir::Safety,
1359 pub value: Option<DefId>,
1360}
1361
1362impl PartialEq for FieldDef {
1363 #[inline]
1364 fn eq(&self, other: &Self) -> bool {
1365 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1373
1374 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1375
1376 let res = lhs_did == rhs_did;
1377
1378 if cfg!(debug_assertions) && res {
1380 let deep =
1381 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1382 assert!(deep, "FieldDef for the same def-id has differing data");
1383 }
1384
1385 res
1386 }
1387}
1388
1389impl Eq for FieldDef {}
1390
1391impl Hash for FieldDef {
1392 #[inline]
1393 fn hash<H: Hasher>(&self, s: &mut H) {
1394 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1402
1403 did.hash(s)
1404 }
1405}
1406
1407impl<'tcx> FieldDef {
1408 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1411 tcx.type_of(self.did).instantiate(tcx, args)
1412 }
1413
1414 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1416 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1417 }
1418}
1419
1420#[derive(Debug, PartialEq, Eq)]
1421pub enum ImplOverlapKind {
1422 Permitted {
1424 marker: bool,
1426 },
1427}
1428
1429#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1432pub enum ImplTraitInTraitData {
1433 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1434 Impl { fn_def_id: DefId },
1435}
1436
1437impl<'tcx> TyCtxt<'tcx> {
1438 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1439 self.typeck(self.hir_body_owner_def_id(body))
1440 }
1441
1442 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1443 self.associated_items(id)
1444 .in_definition_order()
1445 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1446 }
1447
1448 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1449 let mut flags = ReprFlags::empty();
1450 let mut size = None;
1451 let mut max_align: Option<Align> = None;
1452 let mut min_pack: Option<Align> = None;
1453
1454 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1457
1458 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1462 field_shuffle_seed ^= user_seed;
1463 }
1464
1465 if let Some(reprs) =
1466 find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs)
1467 {
1468 for (r, _) in reprs {
1469 flags.insert(match *r {
1470 attr::ReprRust => ReprFlags::empty(),
1471 attr::ReprC => ReprFlags::IS_C,
1472 attr::ReprPacked(pack) => {
1473 min_pack = Some(if let Some(min_pack) = min_pack {
1474 min_pack.min(pack)
1475 } else {
1476 pack
1477 });
1478 ReprFlags::empty()
1479 }
1480 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1481 attr::ReprSimd => ReprFlags::IS_SIMD,
1482 attr::ReprInt(i) => {
1483 size = Some(match i {
1484 attr::IntType::SignedInt(x) => match x {
1485 ast::IntTy::Isize => IntegerType::Pointer(true),
1486 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1487 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1488 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1489 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1490 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1491 },
1492 attr::IntType::UnsignedInt(x) => match x {
1493 ast::UintTy::Usize => IntegerType::Pointer(false),
1494 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1495 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1496 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1497 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1498 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1499 },
1500 });
1501 ReprFlags::empty()
1502 }
1503 attr::ReprAlign(align) => {
1504 max_align = max_align.max(Some(align));
1505 ReprFlags::empty()
1506 }
1507 });
1508 }
1509 }
1510
1511 if self.sess.opts.unstable_opts.randomize_layout {
1514 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1515 }
1516
1517 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1520
1521 if is_box {
1523 flags.insert(ReprFlags::IS_LINEAR);
1524 }
1525
1526 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1527 }
1528
1529 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1531 let def_id = def_id.into_query_param();
1532 if let Some(cnum) = def_id.as_crate_root() {
1533 Some(self.crate_name(cnum))
1534 } else {
1535 let def_key = self.def_key(def_id);
1536 match def_key.disambiguated_data.data {
1537 rustc_hir::definitions::DefPathData::Ctor => self
1539 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1540 _ => def_key.get_opt_name(),
1541 }
1542 }
1543 }
1544
1545 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1552 let id = id.into_query_param();
1553 self.opt_item_name(id).unwrap_or_else(|| {
1554 bug!("item_name: no name for {:?}", self.def_path(id));
1555 })
1556 }
1557
1558 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1562 let def_id = def_id.into_query_param();
1563 let def = self.opt_item_name(def_id)?;
1564 let span = self
1565 .def_ident_span(def_id)
1566 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1567 Some(Ident::new(def, span))
1568 }
1569
1570 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1574 let def_id = def_id.into_query_param();
1575 self.opt_item_ident(def_id).unwrap_or_else(|| {
1576 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1577 })
1578 }
1579
1580 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1581 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1582 Some(self.associated_item(def_id))
1583 } else {
1584 None
1585 }
1586 }
1587
1588 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1592 if let DefKind::AssocTy = self.def_kind(def_id)
1593 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1594 self.associated_item(def_id).kind
1595 {
1596 Some(rpitit_info)
1597 } else {
1598 None
1599 }
1600 }
1601
1602 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1603 variant.fields.iter_enumerated().find_map(|(i, field)| {
1604 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1605 })
1606 }
1607
1608 #[instrument(level = "debug", skip(self), ret)]
1611 pub fn impls_are_allowed_to_overlap(
1612 self,
1613 def_id1: DefId,
1614 def_id2: DefId,
1615 ) -> Option<ImplOverlapKind> {
1616 let impl1 = self.impl_trait_header(def_id1).unwrap();
1617 let impl2 = self.impl_trait_header(def_id2).unwrap();
1618
1619 let trait_ref1 = impl1.trait_ref.skip_binder();
1620 let trait_ref2 = impl2.trait_ref.skip_binder();
1621
1622 if trait_ref1.references_error() || trait_ref2.references_error() {
1625 return Some(ImplOverlapKind::Permitted { marker: false });
1626 }
1627
1628 match (impl1.polarity, impl2.polarity) {
1629 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1630 return Some(ImplOverlapKind::Permitted { marker: false });
1632 }
1633 (ImplPolarity::Positive, ImplPolarity::Negative)
1634 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1635 return None;
1637 }
1638 (ImplPolarity::Positive, ImplPolarity::Positive)
1639 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1640 };
1641
1642 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1643 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1644
1645 if is_marker_overlap {
1646 return Some(ImplOverlapKind::Permitted { marker: true });
1647 }
1648
1649 None
1650 }
1651
1652 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1655 match res {
1656 Res::Def(DefKind::Variant, did) => {
1657 let enum_did = self.parent(did);
1658 self.adt_def(enum_did).variant_with_id(did)
1659 }
1660 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1661 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1662 let variant_did = self.parent(variant_ctor_did);
1663 let enum_did = self.parent(variant_did);
1664 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1665 }
1666 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1667 let struct_did = self.parent(ctor_did);
1668 self.adt_def(struct_did).non_enum_variant()
1669 }
1670 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1671 }
1672 }
1673
1674 #[instrument(skip(self), level = "debug")]
1676 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1677 match instance {
1678 ty::InstanceKind::Item(def) => {
1679 debug!("calling def_kind on def: {:?}", def);
1680 let def_kind = self.def_kind(def);
1681 debug!("returned from def_kind: {:?}", def_kind);
1682 match def_kind {
1683 DefKind::Const
1684 | DefKind::Static { .. }
1685 | DefKind::AssocConst
1686 | DefKind::Ctor(..)
1687 | DefKind::AnonConst
1688 | DefKind::InlineConst => self.mir_for_ctfe(def),
1689 _ => self.optimized_mir(def),
1692 }
1693 }
1694 ty::InstanceKind::VTableShim(..)
1695 | ty::InstanceKind::ReifyShim(..)
1696 | ty::InstanceKind::Intrinsic(..)
1697 | ty::InstanceKind::FnPtrShim(..)
1698 | ty::InstanceKind::Virtual(..)
1699 | ty::InstanceKind::ClosureOnceShim { .. }
1700 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1701 | ty::InstanceKind::FutureDropPollShim(..)
1702 | ty::InstanceKind::DropGlue(..)
1703 | ty::InstanceKind::CloneShim(..)
1704 | ty::InstanceKind::ThreadLocalShim(..)
1705 | ty::InstanceKind::FnPtrAddrShim(..)
1706 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1707 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1708 }
1709 }
1710
1711 pub fn get_attrs(
1713 self,
1714 did: impl Into<DefId>,
1715 attr: Symbol,
1716 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1717 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1718 }
1719
1720 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1725 let did: DefId = did.into();
1726 if let Some(did) = did.as_local() {
1727 self.hir_attrs(self.local_def_id_to_hir_id(did))
1728 } else {
1729 self.attrs_for_def(did)
1730 }
1731 }
1732
1733 pub fn get_diagnostic_attr(
1742 self,
1743 did: impl Into<DefId>,
1744 attr: Symbol,
1745 ) -> Option<&'tcx hir::Attribute> {
1746 let did: DefId = did.into();
1747 if did.as_local().is_some() {
1748 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1750 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1751 } else {
1752 None
1753 }
1754 } else {
1755 debug_assert!(rustc_feature::encode_cross_crate(attr));
1758 self.attrs_for_def(did)
1759 .iter()
1760 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1761 }
1762 }
1763
1764 pub fn get_attrs_by_path(
1765 self,
1766 did: DefId,
1767 attr: &[Symbol],
1768 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1769 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1770 if let Some(did) = did.as_local() {
1771 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1772 } else {
1773 self.attrs_for_def(did).iter().filter(filter_fn)
1774 }
1775 }
1776
1777 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1778 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1779 let did: DefId = did.into();
1780 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1781 } else {
1782 self.get_attrs(did, attr).next()
1783 }
1784 }
1785
1786 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1788 self.get_attrs(did, attr).next().is_some()
1789 }
1790
1791 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1793 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1794 }
1795
1796 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1798 self.trait_def(trait_def_id).has_auto_impl
1799 }
1800
1801 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1804 self.trait_def(trait_def_id).is_coinductive
1805 }
1806
1807 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1809 self.def_kind(trait_def_id) == DefKind::TraitAlias
1810 }
1811
1812 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1814 self.arena.alloc(err)
1815 }
1816
1817 fn ordinary_coroutine_layout(
1823 self,
1824 def_id: DefId,
1825 args: GenericArgsRef<'tcx>,
1826 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1827 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1828 let mir = self.optimized_mir(def_id);
1829 let ty = || Ty::new_coroutine(self, def_id, args);
1830 if coroutine_kind_ty.is_unit() {
1832 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1833 } else {
1834 let ty::Coroutine(_, identity_args) =
1837 *self.type_of(def_id).instantiate_identity().kind()
1838 else {
1839 unreachable!();
1840 };
1841 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1842 if identity_kind_ty == coroutine_kind_ty {
1845 mir.coroutine_layout_raw()
1846 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1847 } else {
1848 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1849 assert_matches!(
1850 identity_kind_ty.to_opt_closure_kind(),
1851 Some(ClosureKind::Fn | ClosureKind::FnMut)
1852 );
1853 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1854 .coroutine_layout_raw()
1855 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1856 }
1857 }
1858 }
1859
1860 fn async_drop_coroutine_layout(
1864 self,
1865 def_id: DefId,
1866 args: GenericArgsRef<'tcx>,
1867 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1868 let ty = || Ty::new_coroutine(self, def_id, args);
1869 if args[0].has_placeholders() || args[0].has_non_region_param() {
1870 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1871 }
1872 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1873 self.mir_shims(instance)
1874 .coroutine_layout_raw()
1875 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1876 }
1877
1878 pub fn coroutine_layout(
1881 self,
1882 def_id: DefId,
1883 args: GenericArgsRef<'tcx>,
1884 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1885 if self.is_async_drop_in_place_coroutine(def_id) {
1886 let arg_cor_ty = args.first().unwrap().expect_ty();
1890 if arg_cor_ty.is_coroutine() {
1891 let span = self.def_span(def_id);
1892 let source_info = SourceInfo::outermost(span);
1893 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1896 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1897 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1898 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1899 let proxy_layout = CoroutineLayout {
1900 field_tys: [].into(),
1901 field_names: [].into(),
1902 variant_fields,
1903 variant_source_info,
1904 storage_conflicts: BitMatrix::new(0, 0),
1905 };
1906 return Ok(self.arena.alloc(proxy_layout));
1907 } else {
1908 self.async_drop_coroutine_layout(def_id, args)
1909 }
1910 } else {
1911 self.ordinary_coroutine_layout(def_id, args)
1912 }
1913 }
1914
1915 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1918 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1919 }
1920
1921 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1923 if !self.def_kind(def_id).is_assoc() {
1924 return None;
1925 }
1926 let parent = self.parent(def_id);
1927 let def_kind = self.def_kind(parent);
1928 Some((parent, def_kind))
1929 }
1930
1931 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
1933 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
1934 }
1935
1936 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1939 match self.assoc_parent(def_id) {
1940 Some((id, DefKind::Trait)) => Some(id),
1941 _ => None,
1942 }
1943 }
1944
1945 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1948 match self.assoc_parent(def_id) {
1949 Some((id, DefKind::Impl { .. })) => Some(id),
1950 _ => None,
1951 }
1952 }
1953
1954 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1957 match self.assoc_parent(def_id) {
1958 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
1959 _ => None,
1960 }
1961 }
1962
1963 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1966 match self.assoc_parent(def_id) {
1967 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
1968 _ => None,
1969 }
1970 }
1971
1972 pub fn is_exportable(self, def_id: DefId) -> bool {
1973 self.exportable_items(def_id.krate).contains(&def_id)
1974 }
1975
1976 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1979 if self.is_automatically_derived(def_id)
1980 && let Some(def_id) = def_id.as_local()
1981 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1982 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1983 && find_attr!(
1984 self.get_all_attrs(outer.macro_def_id.unwrap()),
1985 AttributeKind::RustcBuiltinMacro { .. }
1986 )
1987 {
1988 true
1989 } else {
1990 false
1991 }
1992 }
1993
1994 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1996 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
1997 }
1998
1999 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2002 if let Some(impl_def_id) = impl_def_id.as_local() {
2003 Ok(self.def_span(impl_def_id))
2004 } else {
2005 Err(self.crate_name(impl_def_id.krate))
2006 }
2007 }
2008
2009 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2013 use_ident.name == def_ident.name
2017 && use_ident
2018 .span
2019 .ctxt()
2020 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2021 }
2022
2023 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2024 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2025 ident
2026 }
2027
2028 pub fn adjust_ident_and_get_scope(
2030 self,
2031 mut ident: Ident,
2032 scope: DefId,
2033 block: hir::HirId,
2034 ) -> (Ident, DefId) {
2035 let scope = ident
2036 .span
2037 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2038 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2039 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2040 (ident, scope)
2041 }
2042
2043 #[inline]
2047 pub fn is_const_fn(self, def_id: DefId) -> bool {
2048 matches!(
2049 self.def_kind(def_id),
2050 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2051 ) && self.constness(def_id) == hir::Constness::Const
2052 }
2053
2054 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2061 let def_id: DefId = def_id.into();
2062 match self.def_kind(def_id) {
2063 DefKind::Impl { of_trait: true } => {
2064 let header = self.impl_trait_header(def_id).unwrap();
2065 header.constness == hir::Constness::Const
2066 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2067 }
2068 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2069 self.constness(def_id) == hir::Constness::Const
2070 }
2071 DefKind::Trait => self.is_const_trait(def_id),
2072 DefKind::AssocTy => {
2073 let parent_def_id = self.parent(def_id);
2074 match self.def_kind(parent_def_id) {
2075 DefKind::Impl { of_trait: false } => false,
2076 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2077 self.is_conditionally_const(parent_def_id)
2078 }
2079 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2080 }
2081 }
2082 DefKind::AssocFn => {
2083 let parent_def_id = self.parent(def_id);
2084 match self.def_kind(parent_def_id) {
2085 DefKind::Impl { of_trait: false } => {
2086 self.constness(def_id) == hir::Constness::Const
2087 }
2088 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2089 self.is_conditionally_const(parent_def_id)
2090 }
2091 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2092 }
2093 }
2094 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2095 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2096 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2097 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2099 },
2100 DefKind::Closure => {
2101 false
2104 }
2105 DefKind::Ctor(_, CtorKind::Const)
2106 | DefKind::Impl { of_trait: false }
2107 | DefKind::Mod
2108 | DefKind::Struct
2109 | DefKind::Union
2110 | DefKind::Enum
2111 | DefKind::Variant
2112 | DefKind::TyAlias
2113 | DefKind::ForeignTy
2114 | DefKind::TraitAlias
2115 | DefKind::TyParam
2116 | DefKind::Const
2117 | DefKind::ConstParam
2118 | DefKind::Static { .. }
2119 | DefKind::AssocConst
2120 | DefKind::Macro(_)
2121 | DefKind::ExternCrate
2122 | DefKind::Use
2123 | DefKind::ForeignMod
2124 | DefKind::AnonConst
2125 | DefKind::InlineConst
2126 | DefKind::Field
2127 | DefKind::LifetimeParam
2128 | DefKind::GlobalAsm
2129 | DefKind::SyntheticCoroutineBody => false,
2130 }
2131 }
2132
2133 #[inline]
2134 pub fn is_const_trait(self, def_id: DefId) -> bool {
2135 self.trait_def(def_id).constness == hir::Constness::Const
2136 }
2137
2138 #[inline]
2139 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2140 matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2141 }
2142
2143 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2144 if self.def_kind(def_id) != DefKind::AssocFn {
2145 return false;
2146 }
2147
2148 let Some(item) = self.opt_associated_item(def_id) else {
2149 return false;
2150 };
2151
2152 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2153 return false;
2154 };
2155
2156 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2157 }
2158}
2159
2160pub fn provide(providers: &mut Providers) {
2161 closure::provide(providers);
2162 context::provide(providers);
2163 erase_regions::provide(providers);
2164 inhabitedness::provide(providers);
2165 util::provide(providers);
2166 print::provide(providers);
2167 super::util::bug::provide(providers);
2168 *providers = Providers {
2169 trait_impls_of: trait_def::trait_impls_of_provider,
2170 incoherent_impls: trait_def::incoherent_impls_provider,
2171 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2172 traits: trait_def::traits_provider,
2173 vtable_allocation: vtable::vtable_allocation_provider,
2174 ..*providers
2175 };
2176}
2177
2178#[derive(Clone, Debug, Default, HashStable)]
2184pub struct CrateInherentImpls {
2185 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2186 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2187}
2188
2189#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2190pub struct SymbolName<'tcx> {
2191 pub name: &'tcx str,
2193}
2194
2195impl<'tcx> SymbolName<'tcx> {
2196 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2197 SymbolName { name: tcx.arena.alloc_str(name) }
2198 }
2199}
2200
2201impl<'tcx> fmt::Display for SymbolName<'tcx> {
2202 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2203 fmt::Display::fmt(&self.name, fmt)
2204 }
2205}
2206
2207impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2208 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2209 fmt::Display::fmt(&self.name, fmt)
2210 }
2211}
2212
2213#[derive(Copy, Clone, Debug, HashStable)]
2215pub struct DestructuredConst<'tcx> {
2216 pub variant: Option<VariantIdx>,
2217 pub fields: &'tcx [ty::Const<'tcx>],
2218}