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};
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};
49use rustc_session::lint::LintBuffer;
50pub use rustc_session::lint::RegisteredTools;
51use rustc_span::hygiene::MacroKind;
52use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
53pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
54pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
55#[allow(
56 hidden_glob_reexports,
57 rustc::usage_of_type_ir_inherent,
58 rustc::non_glob_import_of_type_ir_inherent
59)]
60use rustc_type_ir::inherent;
61pub use rustc_type_ir::relate::VarianceDiagInfo;
62pub use rustc_type_ir::solve::SizedTraitKind;
63pub use rustc_type_ir::*;
64#[allow(hidden_glob_reexports, unused_imports)]
65use rustc_type_ir::{InferCtxtLike, Interner};
66use tracing::{debug, instrument};
67pub use vtable::*;
68use {rustc_ast as ast, rustc_hir as hir};
69
70pub use self::closure::{
71 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
72 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
73 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
74 place_to_string_for_capture,
75};
76pub use self::consts::{
77 AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
78 ExprKind, ScalarInt, UnevaluatedConst, ValTree, ValTreeKind, Value,
79};
80pub use self::context::{
81 CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
82 TyCtxtFeed, tls,
83};
84pub use self::fold::*;
85pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams};
86pub use self::list::{List, ListWithCachedTypeInfo};
87pub use self::opaque_types::OpaqueTypeKey;
88pub use self::pattern::{Pattern, PatternKind};
89pub use self::predicate::{
90 AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
91 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
92 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
93 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
94 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
95 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
96 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
97};
98pub use self::region::{
99 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
100 RegionKind, RegionVid,
101};
102pub use self::rvalue_scopes::RvalueScopes;
103pub use self::sty::{
104 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
105 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
106 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
107};
108pub use self::trait_def::TraitDef;
109pub use self::typeck_results::{
110 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
111 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
112};
113pub use self::visit::*;
114use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
115use crate::metadata::ModChild;
116use crate::middle::privacy::EffectiveVisibilities;
117use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
118use crate::query::{IntoQueryParam, Providers};
119use crate::ty;
120use crate::ty::codec::{TyDecoder, TyEncoder};
121pub use crate::ty::diagnostics::*;
122use crate::ty::fast_reject::SimplifiedType;
123use crate::ty::layout::LayoutError;
124use crate::ty::util::Discr;
125use crate::ty::walk::TypeWalker;
126
127pub mod abstract_const;
128pub mod adjustment;
129pub mod cast;
130pub mod codec;
131pub mod error;
132pub mod fast_reject;
133pub mod inhabitedness;
134pub mod layout;
135pub mod normalize_erasing_regions;
136pub mod pattern;
137pub mod print;
138pub mod relate;
139pub mod significant_drop_order;
140pub mod trait_def;
141pub mod util;
142pub mod vtable;
143
144mod adt;
145mod assoc;
146mod closure;
147mod consts;
148mod context;
149mod diagnostics;
150mod elaborate_impl;
151mod erase_regions;
152mod fold;
153mod generic_args;
154mod generics;
155mod impls_ty;
156mod instance;
157mod intrinsic;
158mod list;
159mod opaque_types;
160mod predicate;
161mod region;
162mod rvalue_scopes;
163mod structural_impls;
164#[allow(hidden_glob_reexports)]
165mod sty;
166mod typeck_results;
167mod visit;
168
169#[derive(Debug, HashStable)]
172pub struct ResolverGlobalCtxt {
173 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
174 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
176 pub effective_visibilities: EffectiveVisibilities,
177 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
178 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
179 pub module_children: LocalDefIdMap<Vec<ModChild>>,
180 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
181 pub main_def: Option<MainDefinition>,
182 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
183 pub proc_macros: Vec<LocalDefId>,
186 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
189 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
190 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
191 pub all_macro_rules: UnordSet<Symbol>,
192 pub stripped_cfg_items: Vec<StrippedCfgItem>,
193}
194
195#[derive(Debug)]
198pub struct ResolverAstLowering {
199 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
200
201 pub partial_res_map: NodeMap<hir::def::PartialRes>,
203 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
205 pub label_res_map: NodeMap<ast::NodeId>,
207 pub lifetimes_res_map: NodeMap<LifetimeRes>,
209 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
211
212 pub next_node_id: ast::NodeId,
213
214 pub node_id_to_def_id: NodeMap<LocalDefId>,
215
216 pub disambiguator: DisambiguatorState,
217
218 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
219 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
221
222 pub lint_buffer: Steal<LintBuffer>,
224
225 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
227}
228
229#[derive(Debug)]
230pub struct DelegationFnSig {
231 pub header: ast::FnHeader,
232 pub param_count: usize,
233 pub has_self: bool,
234 pub c_variadic: bool,
235 pub target_feature: bool,
236}
237
238#[derive(Clone, Copy, Debug, HashStable)]
239pub struct MainDefinition {
240 pub res: Res<ast::NodeId>,
241 pub is_import: bool,
242 pub span: Span,
243}
244
245impl MainDefinition {
246 pub fn opt_fn_def_id(self) -> Option<DefId> {
247 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
248 }
249}
250
251#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
252pub struct ImplTraitHeader<'tcx> {
253 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
254 pub polarity: ImplPolarity,
255 pub safety: hir::Safety,
256 pub constness: hir::Constness,
257}
258
259#[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
260pub enum ImplSubject<'tcx> {
261 Trait(TraitRef<'tcx>),
262 Inherent(Ty<'tcx>),
263}
264
265#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
266#[derive(TypeFoldable, TypeVisitable)]
267pub enum Asyncness {
268 Yes,
269 No,
270}
271
272impl Asyncness {
273 pub fn is_async(self) -> bool {
274 matches!(self, Asyncness::Yes)
275 }
276}
277
278#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
279pub enum Visibility<Id = LocalDefId> {
280 Public,
282 Restricted(Id),
284}
285
286impl Visibility {
287 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
288 match self {
289 ty::Visibility::Restricted(restricted_id) => {
290 if restricted_id.is_top_level_module() {
291 "pub(crate)".to_string()
292 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
293 "pub(self)".to_string()
294 } else {
295 format!(
296 "pub(in crate{})",
297 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
298 )
299 }
300 }
301 ty::Visibility::Public => "pub".to_string(),
302 }
303 }
304}
305
306#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
307#[derive(TypeFoldable, TypeVisitable)]
308pub struct ClosureSizeProfileData<'tcx> {
309 pub before_feature_tys: Ty<'tcx>,
311 pub after_feature_tys: Ty<'tcx>,
313}
314
315impl TyCtxt<'_> {
316 #[inline]
317 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
318 self.def_key(id).parent.map(|index| DefId { index, ..id })
319 }
320
321 #[inline]
322 #[track_caller]
323 pub fn parent(self, id: DefId) -> DefId {
324 match self.opt_parent(id) {
325 Some(id) => id,
326 None => bug!("{id:?} doesn't have a parent"),
328 }
329 }
330
331 #[inline]
332 #[track_caller]
333 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
334 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
335 }
336
337 #[inline]
338 #[track_caller]
339 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
340 self.parent(id.into().to_def_id()).expect_local()
341 }
342
343 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
344 if descendant.krate != ancestor.krate {
345 return false;
346 }
347
348 while descendant != ancestor {
349 match self.opt_parent(descendant) {
350 Some(parent) => descendant = parent,
351 None => return false,
352 }
353 }
354 true
355 }
356}
357
358impl<Id> Visibility<Id> {
359 pub fn is_public(self) -> bool {
360 matches!(self, Visibility::Public)
361 }
362
363 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
364 match self {
365 Visibility::Public => Visibility::Public,
366 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
367 }
368 }
369}
370
371impl<Id: Into<DefId>> Visibility<Id> {
372 pub fn to_def_id(self) -> Visibility<DefId> {
373 self.map_id(Into::into)
374 }
375
376 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
378 match self {
379 Visibility::Public => true,
381 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
382 }
383 }
384
385 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
387 match vis {
388 Visibility::Public => self.is_public(),
389 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
390 }
391 }
392}
393
394impl Visibility<DefId> {
395 pub fn expect_local(self) -> Visibility {
396 self.map_id(|id| id.expect_local())
397 }
398
399 pub fn is_visible_locally(self) -> bool {
401 match self {
402 Visibility::Public => true,
403 Visibility::Restricted(def_id) => def_id.is_local(),
404 }
405 }
406}
407
408#[derive(HashStable, Debug)]
415pub struct CrateVariancesMap<'tcx> {
416 pub variances: DefIdMap<&'tcx [ty::Variance]>,
420}
421
422#[derive(Copy, Clone, PartialEq, Eq, Hash)]
425pub struct CReaderCacheKey {
426 pub cnum: Option<CrateNum>,
427 pub pos: usize,
428}
429
430#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
432#[rustc_diagnostic_item = "Ty"]
433#[rustc_pass_by_value]
434pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
435
436impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
437 type Kind = TyKind<'tcx>;
438
439 fn kind(self) -> TyKind<'tcx> {
440 *self.kind()
441 }
442}
443
444impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
445 fn flags(&self) -> TypeFlags {
446 self.0.flags
447 }
448
449 fn outer_exclusive_binder(&self) -> DebruijnIndex {
450 self.0.outer_exclusive_binder
451 }
452}
453
454#[derive(HashStable, Debug)]
461pub struct CratePredicatesMap<'tcx> {
462 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
466}
467
468#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
469pub struct Term<'tcx> {
470 ptr: NonNull<()>,
471 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
472}
473
474impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
475
476impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
477 type Kind = TermKind<'tcx>;
478
479 fn kind(self) -> Self::Kind {
480 self.kind()
481 }
482}
483
484unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
485 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
486{
487}
488unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
489 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
490{
491}
492unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
493unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
494
495impl Debug for Term<'_> {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 match self.kind() {
498 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
499 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
500 }
501 }
502}
503
504impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
505 fn from(ty: Ty<'tcx>) -> Self {
506 TermKind::Ty(ty).pack()
507 }
508}
509
510impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
511 fn from(c: Const<'tcx>) -> Self {
512 TermKind::Const(c).pack()
513 }
514}
515
516impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
517 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
518 self.kind().hash_stable(hcx, hasher);
519 }
520}
521
522impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
523 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
524 self,
525 folder: &mut F,
526 ) -> Result<Self, F::Error> {
527 match self.kind() {
528 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
529 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
530 }
531 }
532
533 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
534 match self.kind() {
535 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
536 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
537 }
538 }
539}
540
541impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
542 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
543 match self.kind() {
544 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
545 ty::TermKind::Const(ct) => ct.visit_with(visitor),
546 }
547 }
548}
549
550impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
551 fn encode(&self, e: &mut E) {
552 self.kind().encode(e)
553 }
554}
555
556impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
557 fn decode(d: &mut D) -> Self {
558 let res: TermKind<'tcx> = Decodable::decode(d);
559 res.pack()
560 }
561}
562
563impl<'tcx> Term<'tcx> {
564 #[inline]
565 pub fn kind(self) -> TermKind<'tcx> {
566 let ptr =
567 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
568 unsafe {
572 match self.ptr.addr().get() & TAG_MASK {
573 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
574 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
575 ))),
576 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
577 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
578 ))),
579 _ => core::intrinsics::unreachable(),
580 }
581 }
582 }
583
584 pub fn as_type(&self) -> Option<Ty<'tcx>> {
585 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
586 }
587
588 pub fn expect_type(&self) -> Ty<'tcx> {
589 self.as_type().expect("expected a type, but found a const")
590 }
591
592 pub fn as_const(&self) -> Option<Const<'tcx>> {
593 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
594 }
595
596 pub fn expect_const(&self) -> Const<'tcx> {
597 self.as_const().expect("expected a const, but found a type")
598 }
599
600 pub fn into_arg(self) -> GenericArg<'tcx> {
601 match self.kind() {
602 TermKind::Ty(ty) => ty.into(),
603 TermKind::Const(c) => c.into(),
604 }
605 }
606
607 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
608 match self.kind() {
609 TermKind::Ty(ty) => match *ty.kind() {
610 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
611 _ => None,
612 },
613 TermKind::Const(ct) => match ct.kind() {
614 ConstKind::Unevaluated(uv) => Some(uv.into()),
615 _ => None,
616 },
617 }
618 }
619
620 pub fn is_infer(&self) -> bool {
621 match self.kind() {
622 TermKind::Ty(ty) => ty.is_ty_var(),
623 TermKind::Const(ct) => ct.is_ct_infer(),
624 }
625 }
626
627 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
628 match self.kind() {
629 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
630 TermKind::Const(ct) => ct.is_trivially_wf(),
631 }
632 }
633
634 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
645 TypeWalker::new(self.into())
646 }
647}
648
649const TAG_MASK: usize = 0b11;
650const TYPE_TAG: usize = 0b00;
651const CONST_TAG: usize = 0b01;
652
653#[extension(pub trait TermKindPackExt<'tcx>)]
654impl<'tcx> TermKind<'tcx> {
655 #[inline]
656 fn pack(self) -> Term<'tcx> {
657 let (tag, ptr) = match self {
658 TermKind::Ty(ty) => {
659 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
661 (TYPE_TAG, NonNull::from(ty.0.0).cast())
662 }
663 TermKind::Const(ct) => {
664 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
666 (CONST_TAG, NonNull::from(ct.0.0).cast())
667 }
668 };
669
670 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
671 }
672}
673
674#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
694pub struct InstantiatedPredicates<'tcx> {
695 pub predicates: Vec<Clause<'tcx>>,
696 pub spans: Vec<Span>,
697}
698
699impl<'tcx> InstantiatedPredicates<'tcx> {
700 pub fn empty() -> InstantiatedPredicates<'tcx> {
701 InstantiatedPredicates { predicates: vec![], spans: vec![] }
702 }
703
704 pub fn is_empty(&self) -> bool {
705 self.predicates.is_empty()
706 }
707
708 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
709 self.into_iter()
710 }
711}
712
713impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
714 type Item = (Clause<'tcx>, Span);
715
716 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
717
718 fn into_iter(self) -> Self::IntoIter {
719 debug_assert_eq!(self.predicates.len(), self.spans.len());
720 std::iter::zip(self.predicates, self.spans)
721 }
722}
723
724impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
725 type Item = (Clause<'tcx>, Span);
726
727 type IntoIter = std::iter::Zip<
728 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
729 std::iter::Copied<std::slice::Iter<'a, Span>>,
730 >;
731
732 fn into_iter(self) -> Self::IntoIter {
733 debug_assert_eq!(self.predicates.len(), self.spans.len());
734 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
735 }
736}
737
738#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
739pub struct OpaqueHiddenType<'tcx> {
740 pub span: Span,
754
755 pub ty: Ty<'tcx>,
768}
769
770#[derive(Debug, Clone, Copy)]
772pub enum DefiningScopeKind {
773 HirTypeck,
778 MirBorrowck,
779}
780
781impl<'tcx> OpaqueHiddenType<'tcx> {
782 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> OpaqueHiddenType<'tcx> {
783 OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
784 }
785
786 pub fn build_mismatch_error(
787 &self,
788 other: &Self,
789 tcx: TyCtxt<'tcx>,
790 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
791 (self.ty, other.ty).error_reported()?;
792 let sub_diag = if self.span == other.span {
794 TypeMismatchReason::ConflictType { span: self.span }
795 } else {
796 TypeMismatchReason::PreviousUse { span: self.span }
797 };
798 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
799 self_ty: self.ty,
800 other_ty: other.ty,
801 other_span: other.span,
802 sub: sub_diag,
803 }))
804 }
805
806 #[instrument(level = "debug", skip(tcx), ret)]
807 pub fn remap_generic_params_to_declaration_params(
808 self,
809 opaque_type_key: OpaqueTypeKey<'tcx>,
810 tcx: TyCtxt<'tcx>,
811 defining_scope_kind: DefiningScopeKind,
812 ) -> Self {
813 let OpaqueTypeKey { def_id, args } = opaque_type_key;
814
815 let id_args = GenericArgs::identity_for_item(tcx, def_id);
822 debug!(?id_args);
823
824 let map = args.iter().zip(id_args).collect();
828 debug!("map = {:#?}", map);
829
830 let this = match defining_scope_kind {
835 DefiningScopeKind::HirTypeck => tcx.erase_regions(self),
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, tcx.erase_regions(result.ty));
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<'tcx> {
912 pub var: BoundVar,
913 pub ty: Ty<'tcx>,
914}
915
916pub type PlaceholderConst = Placeholder<BoundVar>;
917
918impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
919 type Bound = BoundVar;
920
921 fn universe(self) -> UniverseIndex {
922 self.universe
923 }
924
925 fn var(self) -> BoundVar {
926 self.bound
927 }
928
929 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
930 Placeholder { universe: ui, ..self }
931 }
932
933 fn new(ui: UniverseIndex, bound: BoundVar) -> Self {
934 Placeholder { universe: ui, bound }
935 }
936
937 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
938 Placeholder { universe: ui, bound: var }
939 }
940}
941
942pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
943
944impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
945 fn flags(&self) -> TypeFlags {
946 (**self).flags()
947 }
948
949 fn outer_exclusive_binder(&self) -> DebruijnIndex {
950 (**self).outer_exclusive_binder()
951 }
952}
953
954#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
960#[derive(HashStable, TypeVisitable, TypeFoldable)]
961pub struct ParamEnv<'tcx> {
962 caller_bounds: Clauses<'tcx>,
968}
969
970impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
971 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
972 self.caller_bounds()
973 }
974}
975
976impl<'tcx> ParamEnv<'tcx> {
977 #[inline]
984 pub fn empty() -> Self {
985 Self::new(ListWithCachedTypeInfo::empty())
986 }
987
988 #[inline]
989 pub fn caller_bounds(self) -> Clauses<'tcx> {
990 self.caller_bounds
991 }
992
993 #[inline]
995 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
996 ParamEnv { caller_bounds }
997 }
998
999 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1001 ParamEnvAnd { param_env: self, value }
1002 }
1003}
1004
1005#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1006#[derive(HashStable)]
1007pub struct ParamEnvAnd<'tcx, T> {
1008 pub param_env: ParamEnv<'tcx>,
1009 pub value: T,
1010}
1011
1012#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1023#[derive(TypeVisitable, TypeFoldable)]
1024pub struct TypingEnv<'tcx> {
1025 pub typing_mode: TypingMode<'tcx>,
1026 pub param_env: ParamEnv<'tcx>,
1027}
1028
1029impl<'tcx> TypingEnv<'tcx> {
1030 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1038 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1039 }
1040
1041 pub fn non_body_analysis(
1047 tcx: TyCtxt<'tcx>,
1048 def_id: impl IntoQueryParam<DefId>,
1049 ) -> TypingEnv<'tcx> {
1050 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1051 }
1052
1053 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1054 tcx.typing_env_normalized_for_post_analysis(def_id)
1055 }
1056
1057 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1060 let TypingEnv { typing_mode, param_env } = self;
1061 if let TypingMode::PostAnalysis = typing_mode {
1062 return self;
1063 }
1064
1065 let param_env = if tcx.next_trait_solver_globally() {
1068 param_env
1069 } else {
1070 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1071 };
1072 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1073 }
1074
1075 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1080 where
1081 T: TypeVisitable<TyCtxt<'tcx>>,
1082 {
1083 PseudoCanonicalInput { typing_env: self, value }
1096 }
1097}
1098
1099#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1109#[derive(HashStable, TypeVisitable, TypeFoldable)]
1110pub struct PseudoCanonicalInput<'tcx, T> {
1111 pub typing_env: TypingEnv<'tcx>,
1112 pub value: T,
1113}
1114
1115#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1116pub struct Destructor {
1117 pub did: DefId,
1119}
1120
1121#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1123pub struct AsyncDestructor {
1124 pub impl_did: DefId,
1126}
1127
1128#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1129pub struct VariantFlags(u8);
1130bitflags::bitflags! {
1131 impl VariantFlags: u8 {
1132 const NO_VARIANT_FLAGS = 0;
1133 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1135 }
1136}
1137rustc_data_structures::external_bitflags_debug! { VariantFlags }
1138
1139#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1141pub struct VariantDef {
1142 pub def_id: DefId,
1145 pub ctor: Option<(CtorKind, DefId)>,
1148 pub name: Symbol,
1150 pub discr: VariantDiscr,
1152 pub fields: IndexVec<FieldIdx, FieldDef>,
1154 tainted: Option<ErrorGuaranteed>,
1156 flags: VariantFlags,
1158}
1159
1160impl VariantDef {
1161 #[instrument(level = "debug")]
1178 pub fn new(
1179 name: Symbol,
1180 variant_did: Option<DefId>,
1181 ctor: Option<(CtorKind, DefId)>,
1182 discr: VariantDiscr,
1183 fields: IndexVec<FieldIdx, FieldDef>,
1184 parent_did: DefId,
1185 recover_tainted: Option<ErrorGuaranteed>,
1186 is_field_list_non_exhaustive: bool,
1187 ) -> Self {
1188 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1189 if is_field_list_non_exhaustive {
1190 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1191 }
1192
1193 VariantDef {
1194 def_id: variant_did.unwrap_or(parent_did),
1195 ctor,
1196 name,
1197 discr,
1198 fields,
1199 flags,
1200 tainted: recover_tainted,
1201 }
1202 }
1203
1204 #[inline]
1210 pub fn is_field_list_non_exhaustive(&self) -> bool {
1211 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1212 }
1213
1214 #[inline]
1217 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1218 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1219 }
1220
1221 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1223 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1224 }
1225
1226 #[inline]
1228 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1229 self.tainted.map_or(Ok(()), Err)
1230 }
1231
1232 #[inline]
1233 pub fn ctor_kind(&self) -> Option<CtorKind> {
1234 self.ctor.map(|(kind, _)| kind)
1235 }
1236
1237 #[inline]
1238 pub fn ctor_def_id(&self) -> Option<DefId> {
1239 self.ctor.map(|(_, def_id)| def_id)
1240 }
1241
1242 #[inline]
1246 pub fn single_field(&self) -> &FieldDef {
1247 assert!(self.fields.len() == 1);
1248
1249 &self.fields[FieldIdx::ZERO]
1250 }
1251
1252 #[inline]
1254 pub fn tail_opt(&self) -> Option<&FieldDef> {
1255 self.fields.raw.last()
1256 }
1257
1258 #[inline]
1264 pub fn tail(&self) -> &FieldDef {
1265 self.tail_opt().expect("expected unsized ADT to have a tail field")
1266 }
1267
1268 pub fn has_unsafe_fields(&self) -> bool {
1270 self.fields.iter().any(|x| x.safety.is_unsafe())
1271 }
1272}
1273
1274impl PartialEq for VariantDef {
1275 #[inline]
1276 fn eq(&self, other: &Self) -> bool {
1277 let Self {
1285 def_id: lhs_def_id,
1286 ctor: _,
1287 name: _,
1288 discr: _,
1289 fields: _,
1290 flags: _,
1291 tainted: _,
1292 } = &self;
1293 let Self {
1294 def_id: rhs_def_id,
1295 ctor: _,
1296 name: _,
1297 discr: _,
1298 fields: _,
1299 flags: _,
1300 tainted: _,
1301 } = other;
1302
1303 let res = lhs_def_id == rhs_def_id;
1304
1305 if cfg!(debug_assertions) && res {
1307 let deep = self.ctor == other.ctor
1308 && self.name == other.name
1309 && self.discr == other.discr
1310 && self.fields == other.fields
1311 && self.flags == other.flags;
1312 assert!(deep, "VariantDef for the same def-id has differing data");
1313 }
1314
1315 res
1316 }
1317}
1318
1319impl Eq for VariantDef {}
1320
1321impl Hash for VariantDef {
1322 #[inline]
1323 fn hash<H: Hasher>(&self, s: &mut H) {
1324 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1332 def_id.hash(s)
1333 }
1334}
1335
1336#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1337pub enum VariantDiscr {
1338 Explicit(DefId),
1341
1342 Relative(u32),
1347}
1348
1349#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1350pub struct FieldDef {
1351 pub did: DefId,
1352 pub name: Symbol,
1353 pub vis: Visibility<DefId>,
1354 pub safety: hir::Safety,
1355 pub value: Option<DefId>,
1356}
1357
1358impl PartialEq for FieldDef {
1359 #[inline]
1360 fn eq(&self, other: &Self) -> bool {
1361 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1369
1370 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1371
1372 let res = lhs_did == rhs_did;
1373
1374 if cfg!(debug_assertions) && res {
1376 let deep =
1377 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1378 assert!(deep, "FieldDef for the same def-id has differing data");
1379 }
1380
1381 res
1382 }
1383}
1384
1385impl Eq for FieldDef {}
1386
1387impl Hash for FieldDef {
1388 #[inline]
1389 fn hash<H: Hasher>(&self, s: &mut H) {
1390 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1398
1399 did.hash(s)
1400 }
1401}
1402
1403impl<'tcx> FieldDef {
1404 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1407 tcx.type_of(self.did).instantiate(tcx, args)
1408 }
1409
1410 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1412 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1413 }
1414}
1415
1416#[derive(Debug, PartialEq, Eq)]
1417pub enum ImplOverlapKind {
1418 Permitted {
1420 marker: bool,
1422 },
1423}
1424
1425#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1428pub enum ImplTraitInTraitData {
1429 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1430 Impl { fn_def_id: DefId },
1431}
1432
1433impl<'tcx> TyCtxt<'tcx> {
1434 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1435 self.typeck(self.hir_body_owner_def_id(body))
1436 }
1437
1438 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1439 self.associated_items(id)
1440 .in_definition_order()
1441 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1442 }
1443
1444 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1445 let mut flags = ReprFlags::empty();
1446 let mut size = None;
1447 let mut max_align: Option<Align> = None;
1448 let mut min_pack: Option<Align> = None;
1449
1450 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1453
1454 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1458 field_shuffle_seed ^= user_seed;
1459 }
1460
1461 if let Some(reprs) =
1462 find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs)
1463 {
1464 for (r, _) in reprs {
1465 flags.insert(match *r {
1466 attr::ReprRust => ReprFlags::empty(),
1467 attr::ReprC => ReprFlags::IS_C,
1468 attr::ReprPacked(pack) => {
1469 min_pack = Some(if let Some(min_pack) = min_pack {
1470 min_pack.min(pack)
1471 } else {
1472 pack
1473 });
1474 ReprFlags::empty()
1475 }
1476 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1477 attr::ReprSimd => ReprFlags::IS_SIMD,
1478 attr::ReprInt(i) => {
1479 size = Some(match i {
1480 attr::IntType::SignedInt(x) => match x {
1481 ast::IntTy::Isize => IntegerType::Pointer(true),
1482 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1483 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1484 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1485 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1486 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1487 },
1488 attr::IntType::UnsignedInt(x) => match x {
1489 ast::UintTy::Usize => IntegerType::Pointer(false),
1490 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1491 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1492 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1493 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1494 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1495 },
1496 });
1497 ReprFlags::empty()
1498 }
1499 attr::ReprAlign(align) => {
1500 max_align = max_align.max(Some(align));
1501 ReprFlags::empty()
1502 }
1503 });
1504 }
1505 }
1506
1507 if self.sess.opts.unstable_opts.randomize_layout {
1510 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1511 }
1512
1513 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1516
1517 if is_box {
1519 flags.insert(ReprFlags::IS_LINEAR);
1520 }
1521
1522 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1523 }
1524
1525 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1527 let def_id = def_id.into_query_param();
1528 if let Some(cnum) = def_id.as_crate_root() {
1529 Some(self.crate_name(cnum))
1530 } else {
1531 let def_key = self.def_key(def_id);
1532 match def_key.disambiguated_data.data {
1533 rustc_hir::definitions::DefPathData::Ctor => self
1535 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1536 _ => def_key.get_opt_name(),
1537 }
1538 }
1539 }
1540
1541 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1548 let id = id.into_query_param();
1549 self.opt_item_name(id).unwrap_or_else(|| {
1550 bug!("item_name: no name for {:?}", self.def_path(id));
1551 })
1552 }
1553
1554 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1558 let def_id = def_id.into_query_param();
1559 let def = self.opt_item_name(def_id)?;
1560 let span = self
1561 .def_ident_span(def_id)
1562 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1563 Some(Ident::new(def, span))
1564 }
1565
1566 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1570 let def_id = def_id.into_query_param();
1571 self.opt_item_ident(def_id).unwrap_or_else(|| {
1572 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1573 })
1574 }
1575
1576 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1577 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1578 Some(self.associated_item(def_id))
1579 } else {
1580 None
1581 }
1582 }
1583
1584 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1588 if let DefKind::AssocTy = self.def_kind(def_id)
1589 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1590 self.associated_item(def_id).kind
1591 {
1592 Some(rpitit_info)
1593 } else {
1594 None
1595 }
1596 }
1597
1598 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1599 variant.fields.iter_enumerated().find_map(|(i, field)| {
1600 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1601 })
1602 }
1603
1604 #[instrument(level = "debug", skip(self), ret)]
1607 pub fn impls_are_allowed_to_overlap(
1608 self,
1609 def_id1: DefId,
1610 def_id2: DefId,
1611 ) -> Option<ImplOverlapKind> {
1612 let impl1 = self.impl_trait_header(def_id1).unwrap();
1613 let impl2 = self.impl_trait_header(def_id2).unwrap();
1614
1615 let trait_ref1 = impl1.trait_ref.skip_binder();
1616 let trait_ref2 = impl2.trait_ref.skip_binder();
1617
1618 if trait_ref1.references_error() || trait_ref2.references_error() {
1621 return Some(ImplOverlapKind::Permitted { marker: false });
1622 }
1623
1624 match (impl1.polarity, impl2.polarity) {
1625 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1626 return Some(ImplOverlapKind::Permitted { marker: false });
1628 }
1629 (ImplPolarity::Positive, ImplPolarity::Negative)
1630 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1631 return None;
1633 }
1634 (ImplPolarity::Positive, ImplPolarity::Positive)
1635 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1636 };
1637
1638 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1639 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1640
1641 if is_marker_overlap {
1642 return Some(ImplOverlapKind::Permitted { marker: true });
1643 }
1644
1645 None
1646 }
1647
1648 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1651 match res {
1652 Res::Def(DefKind::Variant, did) => {
1653 let enum_did = self.parent(did);
1654 self.adt_def(enum_did).variant_with_id(did)
1655 }
1656 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1657 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1658 let variant_did = self.parent(variant_ctor_did);
1659 let enum_did = self.parent(variant_did);
1660 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1661 }
1662 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1663 let struct_did = self.parent(ctor_did);
1664 self.adt_def(struct_did).non_enum_variant()
1665 }
1666 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1667 }
1668 }
1669
1670 #[instrument(skip(self), level = "debug")]
1672 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1673 match instance {
1674 ty::InstanceKind::Item(def) => {
1675 debug!("calling def_kind on def: {:?}", def);
1676 let def_kind = self.def_kind(def);
1677 debug!("returned from def_kind: {:?}", def_kind);
1678 match def_kind {
1679 DefKind::Const
1680 | DefKind::Static { .. }
1681 | DefKind::AssocConst
1682 | DefKind::Ctor(..)
1683 | DefKind::AnonConst
1684 | DefKind::InlineConst => self.mir_for_ctfe(def),
1685 _ => self.optimized_mir(def),
1688 }
1689 }
1690 ty::InstanceKind::VTableShim(..)
1691 | ty::InstanceKind::ReifyShim(..)
1692 | ty::InstanceKind::Intrinsic(..)
1693 | ty::InstanceKind::FnPtrShim(..)
1694 | ty::InstanceKind::Virtual(..)
1695 | ty::InstanceKind::ClosureOnceShim { .. }
1696 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1697 | ty::InstanceKind::FutureDropPollShim(..)
1698 | ty::InstanceKind::DropGlue(..)
1699 | ty::InstanceKind::CloneShim(..)
1700 | ty::InstanceKind::ThreadLocalShim(..)
1701 | ty::InstanceKind::FnPtrAddrShim(..)
1702 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1703 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1704 }
1705 }
1706
1707 pub fn get_attrs(
1709 self,
1710 did: impl Into<DefId>,
1711 attr: Symbol,
1712 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1713 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1714 }
1715
1716 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1721 let did: DefId = did.into();
1722 if let Some(did) = did.as_local() {
1723 self.hir_attrs(self.local_def_id_to_hir_id(did))
1724 } else {
1725 self.attrs_for_def(did)
1726 }
1727 }
1728
1729 pub fn get_diagnostic_attr(
1738 self,
1739 did: impl Into<DefId>,
1740 attr: Symbol,
1741 ) -> Option<&'tcx hir::Attribute> {
1742 let did: DefId = did.into();
1743 if did.as_local().is_some() {
1744 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1746 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1747 } else {
1748 None
1749 }
1750 } else {
1751 debug_assert!(rustc_feature::encode_cross_crate(attr));
1754 self.attrs_for_def(did)
1755 .iter()
1756 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1757 }
1758 }
1759
1760 pub fn get_attrs_by_path(
1761 self,
1762 did: DefId,
1763 attr: &[Symbol],
1764 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1765 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1766 if let Some(did) = did.as_local() {
1767 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1768 } else {
1769 self.attrs_for_def(did).iter().filter(filter_fn)
1770 }
1771 }
1772
1773 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1774 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1775 let did: DefId = did.into();
1776 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1777 } else {
1778 self.get_attrs(did, attr).next()
1779 }
1780 }
1781
1782 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1784 self.get_attrs(did, attr).next().is_some()
1785 }
1786
1787 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1789 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1790 }
1791
1792 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1794 self.trait_def(trait_def_id).has_auto_impl
1795 }
1796
1797 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1800 self.trait_def(trait_def_id).is_coinductive
1801 }
1802
1803 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1805 self.def_kind(trait_def_id) == DefKind::TraitAlias
1806 }
1807
1808 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1810 self.arena.alloc(err)
1811 }
1812
1813 fn ordinary_coroutine_layout(
1819 self,
1820 def_id: DefId,
1821 args: GenericArgsRef<'tcx>,
1822 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1823 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1824 let mir = self.optimized_mir(def_id);
1825 let ty = || Ty::new_coroutine(self, def_id, args);
1826 if coroutine_kind_ty.is_unit() {
1828 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1829 } else {
1830 let ty::Coroutine(_, identity_args) =
1833 *self.type_of(def_id).instantiate_identity().kind()
1834 else {
1835 unreachable!();
1836 };
1837 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1838 if identity_kind_ty == coroutine_kind_ty {
1841 mir.coroutine_layout_raw()
1842 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1843 } else {
1844 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1845 assert_matches!(
1846 identity_kind_ty.to_opt_closure_kind(),
1847 Some(ClosureKind::Fn | ClosureKind::FnMut)
1848 );
1849 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1850 .coroutine_layout_raw()
1851 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1852 }
1853 }
1854 }
1855
1856 fn async_drop_coroutine_layout(
1860 self,
1861 def_id: DefId,
1862 args: GenericArgsRef<'tcx>,
1863 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1864 let ty = || Ty::new_coroutine(self, def_id, args);
1865 if args[0].has_placeholders() || args[0].has_non_region_param() {
1866 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1867 }
1868 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1869 self.mir_shims(instance)
1870 .coroutine_layout_raw()
1871 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1872 }
1873
1874 pub fn coroutine_layout(
1877 self,
1878 def_id: DefId,
1879 args: GenericArgsRef<'tcx>,
1880 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1881 if self.is_async_drop_in_place_coroutine(def_id) {
1882 let arg_cor_ty = args.first().unwrap().expect_ty();
1886 if arg_cor_ty.is_coroutine() {
1887 let span = self.def_span(def_id);
1888 let source_info = SourceInfo::outermost(span);
1889 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1892 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1893 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1894 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1895 let proxy_layout = CoroutineLayout {
1896 field_tys: [].into(),
1897 field_names: [].into(),
1898 variant_fields,
1899 variant_source_info,
1900 storage_conflicts: BitMatrix::new(0, 0),
1901 };
1902 return Ok(self.arena.alloc(proxy_layout));
1903 } else {
1904 self.async_drop_coroutine_layout(def_id, args)
1905 }
1906 } else {
1907 self.ordinary_coroutine_layout(def_id, args)
1908 }
1909 }
1910
1911 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1914 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1915 }
1916
1917 pub fn assoc_parent(self, def_id: DefId) -> Option<DefId> {
1919 self.def_kind(def_id).is_assoc().then(|| self.parent(def_id))
1920 }
1921
1922 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1925 self.assoc_parent(def_id).filter(|id| self.def_kind(id) == DefKind::Trait)
1926 }
1927
1928 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1931 self.assoc_parent(def_id).filter(|id| matches!(self.def_kind(id), DefKind::Impl { .. }))
1932 }
1933
1934 pub fn is_exportable(self, def_id: DefId) -> bool {
1935 self.exportable_items(def_id.krate).contains(&def_id)
1936 }
1937
1938 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1941 if self.is_automatically_derived(def_id)
1942 && let Some(def_id) = def_id.as_local()
1943 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1944 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1945 && find_attr!(
1946 self.get_all_attrs(outer.macro_def_id.unwrap()),
1947 AttributeKind::RustcBuiltinMacro { .. }
1948 )
1949 {
1950 true
1951 } else {
1952 false
1953 }
1954 }
1955
1956 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1958 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
1959 }
1960
1961 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
1964 if let Some(impl_def_id) = impl_def_id.as_local() {
1965 Ok(self.def_span(impl_def_id))
1966 } else {
1967 Err(self.crate_name(impl_def_id.krate))
1968 }
1969 }
1970
1971 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
1975 use_ident.name == def_ident.name
1979 && use_ident
1980 .span
1981 .ctxt()
1982 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
1983 }
1984
1985 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
1986 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
1987 ident
1988 }
1989
1990 pub fn adjust_ident_and_get_scope(
1992 self,
1993 mut ident: Ident,
1994 scope: DefId,
1995 block: hir::HirId,
1996 ) -> (Ident, DefId) {
1997 let scope = ident
1998 .span
1999 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2000 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2001 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2002 (ident, scope)
2003 }
2004
2005 #[inline]
2009 pub fn is_const_fn(self, def_id: DefId) -> bool {
2010 matches!(
2011 self.def_kind(def_id),
2012 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2013 ) && self.constness(def_id) == hir::Constness::Const
2014 }
2015
2016 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2023 let def_id: DefId = def_id.into();
2024 match self.def_kind(def_id) {
2025 DefKind::Impl { of_trait: true } => {
2026 let header = self.impl_trait_header(def_id).unwrap();
2027 header.constness == hir::Constness::Const
2028 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2029 }
2030 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2031 self.constness(def_id) == hir::Constness::Const
2032 }
2033 DefKind::Trait => self.is_const_trait(def_id),
2034 DefKind::AssocTy => {
2035 let parent_def_id = self.parent(def_id);
2036 match self.def_kind(parent_def_id) {
2037 DefKind::Impl { of_trait: false } => false,
2038 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2039 self.is_conditionally_const(parent_def_id)
2040 }
2041 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2042 }
2043 }
2044 DefKind::AssocFn => {
2045 let parent_def_id = self.parent(def_id);
2046 match self.def_kind(parent_def_id) {
2047 DefKind::Impl { of_trait: false } => {
2048 self.constness(def_id) == hir::Constness::Const
2049 }
2050 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2051 self.is_conditionally_const(parent_def_id)
2052 }
2053 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2054 }
2055 }
2056 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2057 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2058 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2059 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2061 },
2062 DefKind::Closure => {
2063 false
2066 }
2067 DefKind::Ctor(_, CtorKind::Const)
2068 | DefKind::Impl { of_trait: false }
2069 | DefKind::Mod
2070 | DefKind::Struct
2071 | DefKind::Union
2072 | DefKind::Enum
2073 | DefKind::Variant
2074 | DefKind::TyAlias
2075 | DefKind::ForeignTy
2076 | DefKind::TraitAlias
2077 | DefKind::TyParam
2078 | DefKind::Const
2079 | DefKind::ConstParam
2080 | DefKind::Static { .. }
2081 | DefKind::AssocConst
2082 | DefKind::Macro(_)
2083 | DefKind::ExternCrate
2084 | DefKind::Use
2085 | DefKind::ForeignMod
2086 | DefKind::AnonConst
2087 | DefKind::InlineConst
2088 | DefKind::Field
2089 | DefKind::LifetimeParam
2090 | DefKind::GlobalAsm
2091 | DefKind::SyntheticCoroutineBody => false,
2092 }
2093 }
2094
2095 #[inline]
2096 pub fn is_const_trait(self, def_id: DefId) -> bool {
2097 self.trait_def(def_id).constness == hir::Constness::Const
2098 }
2099
2100 #[inline]
2101 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2102 matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2103 }
2104
2105 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2106 if self.def_kind(def_id) != DefKind::AssocFn {
2107 return false;
2108 }
2109
2110 let Some(item) = self.opt_associated_item(def_id) else {
2111 return false;
2112 };
2113 if item.container != ty::AssocItemContainer::Impl {
2114 return false;
2115 }
2116
2117 let Some(trait_item_def_id) = item.trait_item_def_id else {
2118 return false;
2119 };
2120
2121 return !self
2122 .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id)
2123 .is_empty();
2124 }
2125}
2126
2127pub fn provide(providers: &mut Providers) {
2128 closure::provide(providers);
2129 context::provide(providers);
2130 erase_regions::provide(providers);
2131 inhabitedness::provide(providers);
2132 util::provide(providers);
2133 print::provide(providers);
2134 super::util::bug::provide(providers);
2135 *providers = Providers {
2136 trait_impls_of: trait_def::trait_impls_of_provider,
2137 incoherent_impls: trait_def::incoherent_impls_provider,
2138 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2139 traits: trait_def::traits_provider,
2140 vtable_allocation: vtable::vtable_allocation_provider,
2141 ..*providers
2142 };
2143}
2144
2145#[derive(Clone, Debug, Default, HashStable)]
2151pub struct CrateInherentImpls {
2152 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2153 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2154}
2155
2156#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2157pub struct SymbolName<'tcx> {
2158 pub name: &'tcx str,
2160}
2161
2162impl<'tcx> SymbolName<'tcx> {
2163 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2164 SymbolName { name: tcx.arena.alloc_str(name) }
2165 }
2166}
2167
2168impl<'tcx> fmt::Display for SymbolName<'tcx> {
2169 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2170 fmt::Display::fmt(&self.name, fmt)
2171 }
2172}
2173
2174impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2175 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2176 fmt::Display::fmt(&self.name, fmt)
2177 }
2178}
2179
2180#[derive(Copy, Clone, Debug, HashStable)]
2182pub struct DestructuredConst<'tcx> {
2183 pub variant: Option<VariantIdx>,
2184 pub fields: &'tcx [ty::Const<'tcx>],
2185}