1#![allow(rustc::usage_of_ty_tykind)]
4
5mod impl_interner;
6pub mod tls;
7
8use std::borrow::{Borrow, Cow};
9use std::cmp::Ordering;
10use std::env::VarError;
11use std::ffi::OsStr;
12use std::hash::{Hash, Hasher};
13use std::marker::PointeeSized;
14use std::ops::Deref;
15use std::sync::{Arc, OnceLock};
16use std::{debug_assert_matches, fmt, iter, mem};
17
18use rustc_abi::{ExternAbi, FieldIdx, Layout, LayoutData, TargetDataLayout, VariantIdx};
19use rustc_ast as ast;
20use rustc_attr_ir::find_attr;
21use rustc_attr_ir::lang_items::LangItem;
22use rustc_crate_store::{CrateStoreDyn, Untracked};
23use rustc_data_structures::defer;
24use rustc_data_structures::fx::FxHashMap;
25use rustc_data_structures::intern::Interned;
26use rustc_data_structures::profiling::SelfProfilerRef;
27use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
28use rustc_data_structures::stable_hash::StableHash;
29use rustc_data_structures::steal::Steal;
30use rustc_data_structures::sync::{
31 self, DynSend, DynSync, FreezeReadGuard, Lock, RwLock, WorkerLocal,
32};
33use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, MultiSpan};
34use rustc_hir::def::DefKind;
35use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId};
36use rustc_hir::definitions::{DefPathData, Definitions, PerParentDisambiguatorState};
37use rustc_hir::intravisit::Visitor;
38use rustc_hir::{self as hir, CRATE_HIR_ID, HirId, Node, TraitCandidate};
39use rustc_index::IndexVec;
40use rustc_lint_defs::Lint;
41use rustc_lint_defs::builtin::UNUSED_FEATURES;
42use rustc_macros::Diagnostic;
43use rustc_session::Session;
44use rustc_session::config::NextSolverConfig;
45use rustc_span::def_id::{CRATE_DEF_ID, DefPathHash, StableCrateId};
46use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, kw, sym};
47use rustc_structures::{CrateType, Limit};
48use rustc_type_ir::TyKind::*;
49pub use rustc_type_ir::lift::Lift;
50use rustc_type_ir::{
51 CollectAndApply, IncludeSizedImplicitBounds, PlaceholderType, TypeFlags, WithCachedTypeInfo,
52 elaborate, search_graph,
53};
54use tracing::{debug, instrument};
55
56use crate::arena::Arena;
57use crate::dep_graph::dep_node::make_metadata;
58use crate::dep_graph::{DepGraph, DepNodeIndex, IncrCompSession};
59use crate::hir::{ProjectedMaybeOwner, ProjectedOwnerInfo};
60use crate::ich::StableHashState;
61use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarKind};
62use crate::lint::emit_lint_base;
63use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature};
64use crate::middle::resolve::{ModChild, ResolverAstLowering};
65use crate::middle::resolve_bound_vars;
66use crate::mir::interpret::{self, Allocation, ConstAllocation};
67use crate::mir::{Body, Local, Place, PlaceElem, ProjectionKind, Promoted};
68use crate::query::{IntoQueryKey, LocalCrate, Providers, QuerySystem, TyCtxtAt};
69use crate::thir::Thir;
70use crate::traits;
71use crate::traits::solve::{
72 CanonicalInput, CanonicalInputData, ExternalConstraints, ExternalConstraintsData,
73 PredefinedOpaques,
74};
75use crate::ty::predicate::ExistentialPredicateStableCmpExt as _;
76use crate::ty::{
77 self, AdtDef, AdtDefData, AdtKind, Binder, CanonicalizerState, Clause, ClausePolarity, Clauses,
78 Const, ConstKind, FlagComputation, FnSigKind, GenericArg, GenericArgsUnsized,
79 GenericParamDefKind, List, ListWithCachedTypeInfo, ParamConst, Pattern, PatternKind,
80 PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, Region, RegionKind, ReprOptions,
81 TraitObjectVisitor, Ty, TyKind, TyVid, ValTree, ValTreeKind, Visibility,
82};
83
84impl<'tcx> rustc_type_ir::inherent::DefId<TyCtxt<'tcx>> for DefId {
85 fn is_local(self) -> bool {
86 self.is_local()
87 }
88
89 fn as_local(self) -> Option<LocalDefId> {
90 self.as_local()
91 }
92}
93
94impl<'tcx> rustc_type_ir::inherent::Safety<TyCtxt<'tcx>> for hir::Safety {
95 fn safe() -> Self {
96 hir::Safety::Safe
97 }
98
99 fn unsafe_mode() -> Self {
100 hir::Safety::Unsafe
101 }
102
103 fn is_safe(self) -> bool {
104 self.is_safe()
105 }
106
107 fn prefix_str(self) -> &'static str {
108 self.prefix_str()
109 }
110}
111
112impl<'tcx> rustc_type_ir::inherent::Features<TyCtxt<'tcx>> for &'tcx rustc_feature::Features {
113 fn generic_const_exprs(self) -> bool {
114 self.generic_const_exprs()
115 }
116
117 fn gca_const_items(self) -> bool {
118 self.gca_const_items()
119 }
120
121 fn coroutine_clone(self) -> bool {
122 self.coroutine_clone()
123 }
124
125 fn move_trait(self) -> bool {
126 self.move_trait()
127 }
128
129 fn feature_bound_holds_in_crate(self, symbol: Symbol) -> bool {
130 !self.staged_api() && self.enabled(symbol)
134 }
135}
136
137impl<'tcx> rustc_type_ir::inherent::Span<TyCtxt<'tcx>> for Span {
138 fn dummy() -> Self {
139 DUMMY_SP
140 }
141}
142
143type InternedSet<'tcx, T> = ShardedHashMap<InternedInSet<'tcx, T>, ()>;
144
145pub struct CtxtInterners<'tcx> {
146 arena: &'tcx WorkerLocal<Arena<'tcx>>,
148
149 type_: InternedSet<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>,
152 const_lists: InternedSet<'tcx, List<ty::Const<'tcx>>>,
153 args: InternedSet<'tcx, GenericArgsUnsized<'tcx>>,
154 type_lists: InternedSet<'tcx, List<Ty<'tcx>>>,
155 canonical_var_kinds: InternedSet<'tcx, List<CanonicalVarKind<'tcx>>>,
156 region: InternedSet<'tcx, RegionKind<'tcx>>,
157 poly_existential_predicates: InternedSet<'tcx, List<PolyExistentialPredicate<'tcx>>>,
158 predicate: InternedSet<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
159 clauses: InternedSet<'tcx, ListWithCachedTypeInfo<Clause<'tcx>>>,
160 projs: InternedSet<'tcx, List<ProjectionKind>>,
161 place_elems: InternedSet<'tcx, List<PlaceElem<'tcx>>>,
162 const_: InternedSet<'tcx, WithCachedTypeInfo<ty::ConstKind<'tcx>>>,
163 pat: InternedSet<'tcx, PatternKind<'tcx>>,
164 const_allocation: InternedSet<'tcx, Allocation>,
165 bound_variable_kinds: InternedSet<'tcx, List<ty::BoundVariableKind<'tcx>>>,
166 layout: InternedSet<'tcx, LayoutData<FieldIdx, VariantIdx>>,
167 adt_def: InternedSet<'tcx, AdtDefData>,
168 external_constraints: InternedSet<'tcx, ExternalConstraintsData<TyCtxt<'tcx>>>,
169 predefined_opaques_in_body: InternedSet<'tcx, List<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)>>,
170 fields: InternedSet<'tcx, List<FieldIdx>>,
171 local_def_ids: InternedSet<'tcx, List<LocalDefId>>,
172 captures: InternedSet<'tcx, List<&'tcx ty::CapturedPlace<'tcx>>>,
173 valtree: InternedSet<'tcx, ty::ValTreeKind<TyCtxt<'tcx>>>,
174 patterns: InternedSet<'tcx, List<ty::Pattern<'tcx>>>,
175 outlives: InternedSet<'tcx, List<ty::ArgOutlivesClause<'tcx>>>,
176 canonical_inputs: InternedSet<'tcx, CanonicalInputData<TyCtxt<'tcx>>>,
177}
178
179impl<'tcx> CtxtInterners<'tcx> {
180 fn new(arena: &'tcx WorkerLocal<Arena<'tcx>>) -> CtxtInterners<'tcx> {
181 const N: usize = 2048;
184 CtxtInterners {
185 arena,
186 type_: InternedSet::with_capacity(N * 16),
191 const_lists: InternedSet::with_capacity(N * 4),
192 args: InternedSet::with_capacity(N * 4),
193 type_lists: InternedSet::with_capacity(N * 4),
194 region: InternedSet::with_capacity(N * 4),
195 poly_existential_predicates: InternedSet::with_capacity(N / 4),
196 canonical_var_kinds: InternedSet::with_capacity(N / 2),
197 predicate: InternedSet::with_capacity(N),
198 clauses: InternedSet::with_capacity(N),
199 projs: InternedSet::with_capacity(N * 4),
200 place_elems: InternedSet::with_capacity(N * 2),
201 const_: InternedSet::with_capacity(N * 2),
202 pat: InternedSet::with_capacity(N),
203 const_allocation: InternedSet::with_capacity(N),
204 bound_variable_kinds: InternedSet::with_capacity(N * 2),
205 layout: InternedSet::with_capacity(N),
206 adt_def: InternedSet::with_capacity(N),
207 external_constraints: InternedSet::with_capacity(N),
208 predefined_opaques_in_body: InternedSet::with_capacity(N),
209 fields: InternedSet::with_capacity(N * 4),
210 local_def_ids: InternedSet::with_capacity(N),
211 captures: InternedSet::with_capacity(N),
212 valtree: InternedSet::with_capacity(N),
213 patterns: InternedSet::with_capacity(N),
214 outlives: InternedSet::with_capacity(N),
215 canonical_inputs: InternedSet::with_capacity(N),
216 }
217 }
218
219 #[allow(rustc::usage_of_ty_tykind)]
221 #[inline(never)]
222 fn intern_const(&self, kind: ty::ConstKind<'tcx>) -> Const<'tcx> {
223 Const(Interned::new_unchecked(
224 self.const_
225 .intern(kind, |kind: ty::ConstKind<'_>| {
226 let flags = ty::FlagComputation::<TyCtxt<'tcx>>::for_const_kind(&kind);
227 InternedInSet(self.arena.alloc(WithCachedTypeInfo {
228 internee: kind,
229 flags: flags.flags,
230 outer_exclusive_binder: flags.outer_exclusive_binder,
231 }))
232 })
233 .0,
234 ))
235 }
236
237 #[inline(never)]
239 fn intern_predicate(&self, kind: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
240 Predicate(Interned::new_unchecked(
241 self.predicate
242 .intern(kind, |kind| {
243 let flags = ty::FlagComputation::<TyCtxt<'tcx>>::for_predicate(kind);
244 InternedInSet(self.arena.alloc(WithCachedTypeInfo {
245 internee: kind,
246 flags: flags.flags,
247 outer_exclusive_binder: flags.outer_exclusive_binder,
248 }))
249 })
250 .0,
251 ))
252 }
253
254 fn intern_clauses(&self, clauses: &[Clause<'tcx>]) -> Clauses<'tcx> {
255 if clauses.is_empty() {
256 ListWithCachedTypeInfo::empty()
257 } else {
258 self.clauses
259 .intern_ref(clauses, || {
260 let flags = ty::FlagComputation::<TyCtxt<'tcx>>::for_clauses(clauses);
261
262 InternedInSet(ListWithCachedTypeInfo::from_arena(
263 &*self.arena,
264 flags.into(),
265 clauses,
266 ))
267 })
268 .0
269 }
270 }
271
272 #[allow(rustc::usage_of_ty_tykind)]
273 #[inline(always)]
274 fn intern_ty(
275 &self,
276 kind: ty::TyKind<'tcx>,
277 create_flags: impl FnOnce() -> FlagComputation<TyCtxt<'tcx>>,
278 ) -> Ty<'tcx> {
279 Ty(Interned::new_unchecked(
280 self.type_
281 .intern(kind, |_| {
282 let flags = create_flags();
283 InternedInSet(self.arena.alloc(WithCachedTypeInfo {
284 internee: kind,
285 flags: flags.flags,
286 outer_exclusive_binder: flags.outer_exclusive_binder,
287 }))
288 })
289 .0,
290 ))
291 }
292
293 #[inline(never)]
294 fn intern_with_empty_flags(&self, kind: ty::TyKind<'tcx>) -> Ty<'tcx> {
295 self.intern_ty(kind, || FlagComputation::for_flags(TypeFlags::empty()))
296 }
297
298 #[inline(never)]
299 pub(super) fn intern_pat(&self, base: Ty<'tcx>, pat: Pattern<'tcx>) -> Ty<'tcx> {
300 self.intern_ty(Pat(base, pat), || FlagComputation::for_pat(base, pat))
301 }
302
303 #[inline(never)]
304 pub(super) fn intern_coroutine_witness(
305 &self,
306 def_id: DefId,
307 args: ty::GenericArgs<'tcx>,
308 ) -> Ty<'tcx> {
309 self.intern_ty(ty::CoroutineWitness(def_id, args), || FlagComputation::for_args(args))
310 }
311
312 #[inline(never)]
313 pub(super) fn intern_infer(&self, infer: ty::InferTy) -> Ty<'tcx> {
314 self.intern_ty(Infer(infer), || FlagComputation::for_infer(infer))
315 }
316
317 #[inline(never)]
318 pub(super) fn intern_error(&self, error: rustc_errors::ErrorGuaranteed) -> Ty<'tcx> {
319 self.intern_ty(Error(error), || {
320 FlagComputation::for_flags(ty::TypeFlags::HAS_NON_REGION_ERROR)
321 })
322 }
323
324 #[inline(never)]
325 pub(super) fn intern_adt(&self, def: AdtDef<'tcx>, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> {
326 self.intern_ty(Adt(def, args), || FlagComputation::for_args(args))
327 }
328
329 #[inline(never)]
330 pub(super) fn intern_foreign(&self, def_id: DefId) -> Ty<'tcx> {
331 self.intern_ty(Foreign(def_id), || FlagComputation::for_flags(TypeFlags::empty()))
332 }
333
334 #[inline(never)]
335 pub(super) fn intern_array(&self, element: Ty<'tcx>, len: Const<'tcx>) -> Ty<'tcx> {
336 self.intern_ty(Array(element, len), || FlagComputation::for_array(element, len))
337 }
338
339 #[inline(never)]
340 pub(super) fn intern_slice(&self, element: Ty<'tcx>) -> Ty<'tcx> {
341 self.intern_ty(Slice(element), || FlagComputation::for_ty(element))
342 }
343
344 #[inline(never)]
345 pub(super) fn intern_raw_ptr(
346 &self,
347 pointee: Ty<'tcx>,
348 mutability: hir::Mutability,
349 ) -> Ty<'tcx> {
350 self.intern_ty(RawPtr(pointee, mutability), || FlagComputation::for_ty(pointee))
351 }
352
353 #[inline(never)]
354 pub(super) fn intern_ref(
355 &self,
356 region: Region<'tcx>,
357 pointee: Ty<'tcx>,
358 mutability: hir::Mutability,
359 ) -> Ty<'tcx> {
360 self.intern_ty(Ref(region, pointee, mutability), || {
361 FlagComputation::for_ref(region, pointee)
362 })
363 }
364
365 #[inline(never)]
366 pub(super) fn intern_fn_def(
367 &self,
368 def_id: DefId,
369 args: Binder<'tcx, ty::GenericArgs<'tcx>>,
370 ) -> Ty<'tcx> {
371 self.intern_ty(FnDef(def_id, args), || FlagComputation::for_fn_def(args))
372 }
373
374 #[inline(never)]
375 pub(super) fn intern_fn_ptr(
376 &self,
377 sig_tys: Binder<'tcx, ty::FnSigTys<TyCtxt<'tcx>>>,
378 header: ty::FnHeader<TyCtxt<'tcx>>,
379 ) -> Ty<'tcx> {
380 self.intern_ty(FnPtr(sig_tys, header), || FlagComputation::for_fn_ptr(sig_tys))
381 }
382
383 #[inline(never)]
384 pub(super) fn intern_unsafe_binder(
385 &self,
386 bound_ty: ty::UnsafeBinderInner<TyCtxt<'tcx>>,
387 ) -> Ty<'tcx> {
388 self.intern_ty(UnsafeBinder(bound_ty), || FlagComputation::for_unsafe_binder(bound_ty))
389 }
390
391 #[inline(never)]
392 pub(super) fn intern_dynamic(
393 &self,
394 predicates: &'tcx List<PolyExistentialPredicate<'tcx>>,
395 region: Region<'tcx>,
396 ) -> Ty<'tcx> {
397 self.intern_ty(Dynamic(predicates, region), || {
398 FlagComputation::for_dynamic(predicates, region)
399 })
400 }
401
402 #[inline(never)]
403 pub(super) fn intern_closure(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> {
404 self.intern_ty(Closure(def_id, args), || FlagComputation::for_args(args))
405 }
406
407 #[inline(never)]
408 pub(super) fn intern_coroutine_closure(
409 &self,
410 def_id: DefId,
411 args: ty::GenericArgs<'tcx>,
412 ) -> Ty<'tcx> {
413 self.intern_ty(CoroutineClosure(def_id, args), || FlagComputation::for_args(args))
414 }
415
416 #[inline(never)]
417 pub(super) fn intern_coroutine(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> {
418 self.intern_ty(Coroutine(def_id, args), || FlagComputation::for_coroutine(args))
419 }
420
421 #[inline(never)]
422 pub(super) fn intern_tuple(&self, types: &'tcx List<Ty<'tcx>>) -> Ty<'tcx> {
423 self.intern_ty(Tuple(types), || FlagComputation::for_tys(types))
424 }
425
426 #[inline(never)]
427 pub(super) fn intern_alias(&self, is_rigid: ty::IsRigid, alias: ty::AliasTy<'tcx>) -> Ty<'tcx> {
428 self.intern_ty(Alias(is_rigid, alias), || FlagComputation::for_alias(is_rigid, alias))
429 }
430
431 #[inline(never)]
432 pub(super) fn intern_param(&self, param: ty::ParamTy) -> Ty<'tcx> {
433 self.intern_ty(Param(param), || FlagComputation::for_flags(ty::TypeFlags::HAS_TY_PARAM))
434 }
435
436 #[inline(never)]
437 pub(super) fn intern_bound(
438 &self,
439 index: ty::BoundVarIndexKind,
440 bound_ty: ty::BoundTy<'tcx>,
441 ) -> Ty<'tcx> {
442 self.intern_ty(Bound(index, bound_ty), || FlagComputation::for_bound(index))
443 }
444
445 #[inline(never)]
446 pub(super) fn intern_placeholder(&self, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
447 self.intern_ty(Placeholder(placeholder), || {
448 FlagComputation::for_flags(ty::TypeFlags::HAS_TY_PLACEHOLDER)
449 })
450 }
451
452 #[inline(never)]
453 pub(super) fn intern_view(
454 &self,
455 def: ty::AdtDef<'tcx>,
456 args: ty::GenericArgs<'tcx>,
457 fields: Ty<'tcx>,
458 ) -> Ty<'tcx> {
459 self.intern_ty(View(def, args, fields), || FlagComputation::for_view(args, fields))
460 }
461}
462
463const NUM_PREINTERNED_INFER_TY_VARS: u32 = 512;
470const NUM_PREINTERNED_INFER_FRESH_TYS: u32 = 20;
471const NUM_PREINTERNED_INFER_FRESH_INT_TYS: u32 = 3;
472const NUM_PREINTERNED_INFER_FRESH_FLOAT_TYS: u32 = 3;
473const NUM_PREINTERNED_BOUND_BOUND_ANONS_I: u32 = 3;
474const NUM_PREINTERNED_BOUND_BOUND_ANONS_V: u32 = 20;
475const NUM_PREINTERNED_BOUND_CANONICAL_ANONS: u32 = 128;
476const NUM_PREINTERNED_PLACEHOLDER_ROOT_ANONS: u32 = 128;
477
478const NUM_PREINTERNED_RE_VARS: u32 = 500;
479const NUM_PREINTERNED_RE_BOUND_BOUND_ANONS_I: u32 = 3;
480const NUM_PREINTERNED_RE_BOUND_BOUND_ANONS_V: u32 = 20;
481const NUM_PREINTERNED_RE_BOUND_CANONICAL_ANONS: u32 = 20;
482
483pub struct CommonTypes<'tcx> {
484 pub unit: Ty<'tcx>,
485 pub bool: Ty<'tcx>,
486 pub char: Ty<'tcx>,
487 pub isize: Ty<'tcx>,
488 pub i8: Ty<'tcx>,
489 pub i16: Ty<'tcx>,
490 pub i32: Ty<'tcx>,
491 pub i64: Ty<'tcx>,
492 pub i128: Ty<'tcx>,
493 pub usize: Ty<'tcx>,
494 pub u8: Ty<'tcx>,
495 pub u16: Ty<'tcx>,
496 pub u32: Ty<'tcx>,
497 pub u64: Ty<'tcx>,
498 pub u128: Ty<'tcx>,
499 pub f16: Ty<'tcx>,
500 pub f32: Ty<'tcx>,
501 pub f64: Ty<'tcx>,
502 pub f128: Ty<'tcx>,
503 pub str_: Ty<'tcx>,
504 pub never: Ty<'tcx>,
505 pub self_param: Ty<'tcx>,
506
507 pub trait_object_dummy_self: Ty<'tcx>,
534
535 pub infer_ty_vars: Vec<Ty<'tcx>>,
537
538 pub infer_fresh_tys: Vec<Ty<'tcx>>,
540
541 pub infer_fresh_int_tys: Vec<Ty<'tcx>>,
543
544 pub infer_fresh_float_tys: Vec<Ty<'tcx>>,
546
547 pub bound_bound_anons: Vec<Vec<Ty<'tcx>>>,
554
555 pub bound_canonical_anons: Vec<Ty<'tcx>>,
559
560 pub placeholder_root_anons: Vec<Ty<'tcx>>,
567}
568
569pub struct CommonLifetimes<'tcx> {
570 pub re_static: Region<'tcx>,
572
573 pub re_erased: Region<'tcx>,
575
576 pub re_vars: Vec<Region<'tcx>>,
578
579 pub re_bound_bound_anons: Vec<Vec<Region<'tcx>>>,
583
584 pub re_bound_canonical_anons: Vec<Region<'tcx>>,
588}
589
590pub struct CommonConsts<'tcx> {
591 pub unit: Const<'tcx>,
592 pub true_: Const<'tcx>,
593 pub false_: Const<'tcx>,
594 pub(crate) valtree_zst: ValTree<'tcx>,
596}
597
598impl<'tcx> CommonTypes<'tcx> {
599 fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
600 let mk = |ty| interners.intern_with_empty_flags(ty);
601
602 let infer_ty_vars = (0..NUM_PREINTERNED_INFER_TY_VARS)
603 .map(|n| interners.intern_infer(ty::TyVar(TyVid::from(n))))
604 .collect();
605 let infer_fresh_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_TYS)
606 .map(|n| interners.intern_infer(ty::FreshTy(n)))
607 .collect();
608
609 let infer_fresh_int_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_INT_TYS)
610 .map(|n| interners.intern_infer(ty::FreshIntTy(n)))
611 .collect();
612 let infer_fresh_float_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_FLOAT_TYS)
613 .map(|n| interners.intern_infer(ty::FreshFloatTy(n)))
614 .collect();
615
616 let bound_bound_anons = (0..NUM_PREINTERNED_BOUND_BOUND_ANONS_I)
617 .map(|i| {
618 (0..NUM_PREINTERNED_BOUND_BOUND_ANONS_V)
619 .map(|v| {
620 interners.intern_bound(
621 ty::BoundVarIndexKind::Bound(ty::DebruijnIndex::from(i)),
622 ty::BoundTy { var: ty::BoundVar::from(v), kind: ty::BoundTyKind::Anon },
623 )
624 })
625 .collect()
626 })
627 .collect();
628
629 let bound_canonical_anons = (0..NUM_PREINTERNED_BOUND_CANONICAL_ANONS)
630 .map(|v| {
631 interners.intern_bound(
632 ty::BoundVarIndexKind::Canonical,
633 ty::BoundTy { var: ty::BoundVar::from(v), kind: ty::BoundTyKind::Anon },
634 )
635 })
636 .collect();
637
638 let placeholder_root_anons = (0..NUM_PREINTERNED_PLACEHOLDER_ROOT_ANONS)
639 .map(|v| {
640 interners.intern_placeholder(PlaceholderType::new_anon(
641 ty::UniverseIndex::ROOT,
642 ty::BoundVar::from(v),
643 ))
644 })
645 .collect();
646
647 CommonTypes {
648 unit: interners.intern_tuple(List::empty()),
649 bool: mk(Bool),
650 char: mk(Char),
651 never: mk(Never),
652 isize: mk(Int(ty::IntTy::Isize)),
653 i8: mk(Int(ty::IntTy::I8)),
654 i16: mk(Int(ty::IntTy::I16)),
655 i32: mk(Int(ty::IntTy::I32)),
656 i64: mk(Int(ty::IntTy::I64)),
657 i128: mk(Int(ty::IntTy::I128)),
658 usize: mk(Uint(ty::UintTy::Usize)),
659 u8: mk(Uint(ty::UintTy::U8)),
660 u16: mk(Uint(ty::UintTy::U16)),
661 u32: mk(Uint(ty::UintTy::U32)),
662 u64: mk(Uint(ty::UintTy::U64)),
663 u128: mk(Uint(ty::UintTy::U128)),
664 f16: mk(Float(ty::FloatTy::F16)),
665 f32: mk(Float(ty::FloatTy::F32)),
666 f64: mk(Float(ty::FloatTy::F64)),
667 f128: mk(Float(ty::FloatTy::F128)),
668 str_: mk(Str),
669
670 self_param: interners.intern_param(ty::ParamTy { index: 0, name: kw::SelfUpper }),
671
672 trait_object_dummy_self: infer_fresh_tys[0],
673
674 infer_ty_vars,
675 infer_fresh_tys,
676 infer_fresh_int_tys,
677 infer_fresh_float_tys,
678 bound_bound_anons,
679 bound_canonical_anons,
680 placeholder_root_anons,
681 }
682 }
683}
684
685impl<'tcx> CommonLifetimes<'tcx> {
686 fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> {
687 let mk = |r| {
688 Region(Interned::new_unchecked(
689 interners.region.intern(r, |r| InternedInSet(interners.arena.alloc(r))).0,
690 ))
691 };
692
693 let re_vars =
694 (0..NUM_PREINTERNED_RE_VARS).map(|n| mk(ty::ReVar(ty::RegionVid::from(n)))).collect();
695
696 let re_bound_bound_anons = (0..NUM_PREINTERNED_RE_BOUND_BOUND_ANONS_I)
697 .map(|i| {
698 (0..NUM_PREINTERNED_RE_BOUND_BOUND_ANONS_V)
699 .map(|v| {
700 mk(ty::ReBound(
701 ty::BoundVarIndexKind::Bound(ty::DebruijnIndex::from(i)),
702 ty::BoundRegion {
703 var: ty::BoundVar::from(v),
704 kind: ty::BoundRegionKind::Anon,
705 },
706 ))
707 })
708 .collect()
709 })
710 .collect();
711
712 let re_bound_canonical_anons = (0..NUM_PREINTERNED_RE_BOUND_CANONICAL_ANONS)
713 .map(|v| {
714 mk(ty::ReBound(
715 ty::BoundVarIndexKind::Canonical,
716 ty::BoundRegion { var: ty::BoundVar::from(v), kind: ty::BoundRegionKind::Anon },
717 ))
718 })
719 .collect();
720
721 CommonLifetimes {
722 re_static: mk(ty::ReStatic),
723 re_erased: mk(ty::ReErased),
724 re_vars,
725 re_bound_bound_anons,
726 re_bound_canonical_anons,
727 }
728 }
729}
730
731impl<'tcx> CommonConsts<'tcx> {
732 fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> {
733 let mk_const = |c| interners.intern_const(c);
734
735 let mk_valtree = |v| {
736 ty::ValTree(Interned::new_unchecked(
737 interners.valtree.intern(v, |v| InternedInSet(interners.arena.alloc(v))).0,
738 ))
739 };
740
741 let valtree_zst = mk_valtree(ty::ValTreeKind::Branch(List::empty()));
742 let valtree_true = mk_valtree(ty::ValTreeKind::Leaf(ty::ScalarInt::TRUE));
743 let valtree_false = mk_valtree(ty::ValTreeKind::Leaf(ty::ScalarInt::FALSE));
744
745 CommonConsts {
746 unit: mk_const(ty::ConstKind::Value(ty::Value {
747 ty: types.unit,
748 valtree: valtree_zst,
749 })),
750 true_: mk_const(ty::ConstKind::Value(ty::Value {
751 ty: types.bool,
752 valtree: valtree_true,
753 })),
754 false_: mk_const(ty::ConstKind::Value(ty::Value {
755 ty: types.bool,
756 valtree: valtree_false,
757 })),
758 valtree_zst,
759 }
760 }
761}
762
763#[derive(#[automatically_derived]impl ::core::fmt::Debug for FreeRegionInfo {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"FreeRegionInfo scope region_def_id is_impl_item", &self.scope,
&self.region_def_id, &&self.is_impl_item)
}
}Debug)]
766pub struct FreeRegionInfo {
767 pub scope: LocalDefId,
769 pub region_def_id: DefId,
771 pub is_impl_item: bool,
773}
774
775#[derive(#[automatically_derived]impl<'tcx, K: ::core::marker::Copy + Copy>
::core::marker::Copy for TyCtxtFeed<'tcx, K> {
}Copy, #[automatically_derived]impl<'tcx, K: ::core::clone::Clone + Copy>
::core::clone::Clone for TyCtxtFeed<'tcx, K> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
TyCtxtFeed {
tcx: ::core::clone::Clone::clone(&self.tcx),
key: ::core::clone::Clone::clone(&self.key),
}
}
}Clone)]
777pub struct TyCtxtFeed<'tcx, K: Copy> {
778 pub tcx: TyCtxt<'tcx>,
779 key: K,
781}
782
783impl<K: Copy> !StableHash for TyCtxtFeed<'_, K> {}
785
786impl<'tcx> TyCtxt<'tcx> {
791 pub fn feed_unit_query(self) -> TyCtxtFeed<'tcx, ()> {
794 self.dep_graph.assert_ignored();
795 TyCtxtFeed { tcx: self, key: () }
796 }
797
798 pub fn create_local_crate_def_id(self, span: Span) -> TyCtxtFeed<'tcx, LocalDefId> {
801 let key = self.untracked().source_span.push(span);
802 {
match (&key, &CRATE_DEF_ID) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(key, CRATE_DEF_ID);
803 TyCtxtFeed { tcx: self, key }
804 }
805
806 pub fn feed_anon_const_type(self, key: LocalDefId, value: ty::EarlyBinder<'tcx, Ty<'tcx>>) {
810 if true {
{
match (&self.def_kind(key), &DefKind::AnonConst) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.def_kind(key), DefKind::AnonConst);
811 if true {
if !(self.anon_const_kind(key) != ty::AnonConstKind::NonTypeSystemInline)
{
::core::panicking::panic("assertion failed: self.anon_const_kind(key) != ty::AnonConstKind::NonTypeSystemInline")
};
};debug_assert!(self.anon_const_kind(key) != ty::AnonConstKind::NonTypeSystemInline);
812 TyCtxtFeed { tcx: self, key }.type_of(value)
813 }
814
815 pub fn feed_visibility_for_trait_impl_item(self, key: LocalDefId, vis: ty::Visibility) {
823 if truecfg!(debug_assertions) {
824 match self.def_kind(self.local_parent(key)) {
825 DefKind::Impl { of_trait: true } => {}
826 other => ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} is not an assoc item of a trait impl: {1:?}", key,
other), Location::caller())bug!("{key:?} is not an assoc item of a trait impl: {other:?}"),
827 }
828 }
829 TyCtxtFeed { tcx: self, key }.visibility(vis.to_mod_id())
830 }
831}
832
833impl<'tcx, K: Copy> TyCtxtFeed<'tcx, K> {
834 #[inline(always)]
835 pub fn key(&self) -> K {
836 self.key
837 }
838}
839
840impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> {
841 #[inline(always)]
842 pub fn def_id(&self) -> LocalDefId {
843 self.key
844 }
845
846 pub fn feed_owner_id(&self) -> TyCtxtFeed<'tcx, hir::OwnerId> {
848 TyCtxtFeed { tcx: self.tcx, key: hir::OwnerId { def_id: self.key } }
849 }
850
851 pub fn feed_hir(&self) {
853 self.hir_owner(ProjectedMaybeOwner::Owner(ProjectedOwnerInfo::new(
854 self.tcx.arena.alloc(hir::OwnerNodes::synthetic()),
855 self.tcx.arena.alloc(Default::default()),
856 self.tcx.arena.alloc(Default::default()),
857 self.tcx.arena.alloc(Steal::new(Default::default())),
858 )));
859
860 self.feed_owner_id().hir_attr_map(hir::AttributeMap::EMPTY);
861 }
862}
863
864#[derive(#[automatically_derived]impl<'tcx> ::core::default::Default for
GlobalCaches<'tcx> {
#[inline]
fn default() -> Self {
GlobalCaches {
ty_rcache: ::core::default::Default::default(),
selection_cache: ::core::default::Default::default(),
evaluation_cache: ::core::default::Default::default(),
new_solver_evaluation_cache: ::core::default::Default::default(),
new_solver_canonical_param_env_cache: ::core::default::Default::default(),
canonicalizer_states: ::core::default::Default::default(),
canonical_param_env_cache: ::core::default::Default::default(),
highest_var_in_clauses_cache: ::core::default::Default::default(),
clauses_cache: ::core::default::Default::default(),
}
}
}Default)]
869pub struct GlobalCaches<'tcx> {
870 pub ty_rcache: Lock<FxHashMap<ty::CReaderCacheKey, Ty<'tcx>>>,
872
873 pub selection_cache: traits::SelectionCache<'tcx, ty::TypingEnv<'tcx>>,
876
877 pub evaluation_cache: traits::EvaluationCache<'tcx, ty::TypingEnv<'tcx>>,
881
882 new_solver_evaluation_cache: Lock<search_graph::GlobalCache<TyCtxt<'tcx>>>,
884 new_solver_canonical_param_env_cache: Lock<ty::CanonicalParamEnvCache<TyCtxt<'tcx>>>,
885
886 pub canonicalizer_states: Lock<Vec<Box<CanonicalizerState<TyCtxt<'tcx>>>>>,
892
893 pub canonical_param_env_cache: CanonicalParamEnvCache<'tcx>,
894
895 pub highest_var_in_clauses_cache: Lock<FxHashMap<ty::Clauses<'tcx>, usize>>,
897
898 pub clauses_cache:
900 Lock<FxHashMap<(ty::Clauses<'tcx>, &'tcx [ty::GenericArg<'tcx>]), ty::Clauses<'tcx>>>,
901}
902
903#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for TyCtxt<'tcx> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for TyCtxt<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for TyCtxt<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'tcx GlobalCtxt<'tcx>>;
*self
}
}Clone)]
921#[rustc_diagnostic_item = "TyCtxt"]
922#[cfg_attr(bootstrap, rustc_pass_by_value)]
923#[cfg_attr(not(bootstrap), lint::pass_by_value)]
924pub struct TyCtxt<'tcx> {
925 gcx: &'tcx GlobalCtxt<'tcx>,
926}
927
928unsafe impl DynSend for TyCtxt<'_> {}
932unsafe impl DynSync for TyCtxt<'_> {}
933fn _assert_tcx_fields() {
934 sync::assert_dyn_sync::<&'_ GlobalCtxt<'_>>();
935 sync::assert_dyn_send::<&'_ GlobalCtxt<'_>>();
936}
937
938impl<'tcx> Deref for TyCtxt<'tcx> {
939 type Target = &'tcx GlobalCtxt<'tcx>;
940 #[inline(always)]
941 fn deref(&self) -> &Self::Target {
942 &self.gcx
943 }
944}
945
946pub struct GlobalCtxt<'tcx> {
948 pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
949 pub hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
950
951 pub(super) interners: CtxtInterners<'tcx>,
952
953 pub sess: &'tcx Session,
954 crate_types: Vec<CrateType>,
955 stable_crate_id: StableCrateId,
961
962 pub incr_comp_session: Option<&'tcx IncrCompSession>,
963 pub dep_graph: DepGraph,
964
965 pub prof: SelfProfilerRef,
968
969 pub types: CommonTypes<'tcx>,
971
972 pub lifetimes: CommonLifetimes<'tcx>,
974
975 pub consts: CommonConsts<'tcx>,
977
978 pub(crate) hooks: crate::hooks::Providers,
981
982 untracked: Untracked,
983
984 pub query_system: QuerySystem<'tcx>,
985
986 pub caches: GlobalCaches<'tcx>,
987
988 pub data_layout: TargetDataLayout,
990
991 pub(crate) alloc_map: interpret::AllocMap<'tcx>,
993
994 current_gcx: CurrentGcx,
995}
996
997impl<'tcx> GlobalCtxt<'tcx> {
998 pub fn enter<F, R>(&'tcx self, f: F) -> R
1001 where
1002 F: FnOnce(TyCtxt<'tcx>) -> R,
1003 {
1004 let icx = tls::ImplicitCtxt::new(self);
1005
1006 let _on_drop = defer(move || {
1008 *self.current_gcx.value.write() = None;
1009 });
1010
1011 {
1013 let mut guard = self.current_gcx.value.write();
1014 if !guard.is_none() {
{
::core::panicking::panic_fmt(format_args!("no `GlobalCtxt` is currently set"));
}
};assert!(guard.is_none(), "no `GlobalCtxt` is currently set");
1015 *guard = Some(self as *const _ as *const ());
1016 }
1017
1018 tls::enter_context(&icx, || f(icx.tcx))
1019 }
1020}
1021
1022#[derive(#[automatically_derived]impl ::core::clone::Clone for CurrentGcx {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
CurrentGcx { value: ::core::clone::Clone::clone(&self.value) }
}
}Clone)]
1029pub struct CurrentGcx {
1030 value: Arc<RwLock<Option<*const ()>>>,
1033}
1034
1035unsafe impl DynSend for CurrentGcx {}
1036unsafe impl DynSync for CurrentGcx {}
1037
1038impl CurrentGcx {
1039 pub fn new() -> Self {
1040 Self { value: Arc::new(RwLock::new(None)) }
1041 }
1042
1043 pub fn access<R>(&self, f: impl for<'tcx> FnOnce(&'tcx GlobalCtxt<'tcx>) -> R) -> R {
1044 let read_guard = self.value.read();
1045 let gcx: *const GlobalCtxt<'_> = read_guard.unwrap() as *const _;
1046 f(unsafe { &*gcx })
1050 }
1051}
1052
1053impl<'tcx> TyCtxt<'tcx> {
1054 pub fn has_typeck_results(self, def_id: LocalDefId) -> bool {
1055 let root = self.typeck_root_def_id_local(def_id);
1058 self.hir_node_by_def_id(root).body_id().is_some()
1059 }
1060
1061 pub fn body_codegen_attrs(self, def_id: DefId) -> &'tcx CodegenFnAttrs {
1066 let def_kind = self.def_kind(def_id);
1067 if def_kind.has_codegen_attrs() {
1068 self.codegen_fn_attrs(def_id)
1069 } else if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::AnonConst | DefKind::AssocConst | DefKind::Const |
DefKind::GlobalAsm => true,
_ => false,
}matches!(
1070 def_kind,
1071 DefKind::AnonConst | DefKind::AssocConst | DefKind::Const | DefKind::GlobalAsm
1072 ) {
1073 CodegenFnAttrs::EMPTY
1074 } else {
1075 ::rustc_span::macros::bug_impl(None,
format_args!("body_codegen_fn_attrs called on unexpected definition: {0:?} {1:?}",
def_id, def_kind), Location::caller())bug!(
1076 "body_codegen_fn_attrs called on unexpected definition: {:?} {:?}",
1077 def_id,
1078 def_kind
1079 )
1080 }
1081 }
1082
1083 pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal<Thir<'tcx>> {
1084 self.arena.alloc(Steal::new(thir))
1085 }
1086
1087 pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal<Body<'tcx>> {
1088 self.arena.alloc(Steal::new(mir))
1089 }
1090
1091 pub fn alloc_steal_promoted(
1092 self,
1093 promoted: IndexVec<Promoted, Body<'tcx>>,
1094 ) -> &'tcx Steal<IndexVec<Promoted, Body<'tcx>>> {
1095 self.arena.alloc(Steal::new(promoted))
1096 }
1097
1098 pub fn mk_adt_def(
1099 self,
1100 did: DefId,
1101 kind: AdtKind,
1102 variants: IndexVec<VariantIdx, ty::VariantDef>,
1103 repr: ReprOptions,
1104 ) -> ty::AdtDef<'tcx> {
1105 self.mk_adt_def_from_data(ty::AdtDefData::new(self, did, kind, variants, repr))
1106 }
1107
1108 pub fn allocate_bytes_dedup<'a>(
1111 self,
1112 bytes: impl Into<Cow<'a, [u8]>>,
1113 salt: usize,
1114 ) -> interpret::AllocId {
1115 let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes, ());
1117 let alloc = self.mk_const_alloc(alloc);
1118 self.reserve_and_set_memory_dedup(alloc, salt)
1119 }
1120
1121 pub fn default_traits(self) -> &'static [LangItem] {
1123 if self.sess.opts.unstable_opts.experimental_default_bounds {
1124 &[
1125 LangItem::DefaultTrait1,
1126 LangItem::DefaultTrait2,
1127 LangItem::DefaultTrait3,
1128 LangItem::DefaultTrait4,
1129 ]
1130 } else {
1131 &[]
1132 }
1133 }
1134
1135 pub fn is_default_trait(self, def_id: DefId) -> bool {
1136 self.default_traits().iter().any(|&default_trait| self.is_lang_item(def_id, default_trait))
1137 }
1138
1139 pub fn is_implicit_trait(
1142 self,
1143 def_id: DefId,
1144 including_sized: IncludeSizedImplicitBounds,
1145 ) -> bool {
1146 self.is_default_trait(def_id)
1147 || self.is_move_trait(def_id)
1149 || (#[allow(non_exhaustive_omitted_patterns)] match including_sized {
IncludeSizedImplicitBounds::Yes => true,
_ => false,
}matches!(including_sized, IncludeSizedImplicitBounds::Yes) && self.is_sizedness_trait(def_id))
1150 }
1151
1152 pub fn is_move_trait(self, def_id: DefId) -> bool {
1153 #[allow(non_exhaustive_omitted_patterns)] match self.as_lang_item(def_id) {
Some(LangItem::Move) => true,
_ => false,
}matches!(self.as_lang_item(def_id), Some(LangItem::Move))
1154 }
1155
1156 pub fn is_sizedness_trait(self, def_id: DefId) -> bool {
1157 #[allow(non_exhaustive_omitted_patterns)] match self.as_lang_item(def_id) {
Some(LangItem::Sized | LangItem::MetaSized) => true,
_ => false,
}matches!(self.as_lang_item(def_id), Some(LangItem::Sized | LangItem::MetaSized))
1158 }
1159
1160 pub fn is_forget_trait(self, def_id: DefId) -> bool {
1161 #[allow(non_exhaustive_omitted_patterns)] match self.as_lang_item(def_id) {
Some(LangItem::Forget) => true,
_ => false,
}matches!(self.as_lang_item(def_id), Some(LangItem::Forget))
1162 }
1163
1164 pub fn lift<T: Lift<TyCtxt<'tcx>>>(self, value: T) -> T::Lifted {
1165 value.lift_to_interner(self)
1166 }
1167
1168 pub fn create_global_ctxt<T>(
1175 gcx_cell: &'tcx OnceLock<GlobalCtxt<'tcx>>,
1176 sess: &'tcx Session,
1177 crate_types: Vec<CrateType>,
1178 stable_crate_id: StableCrateId,
1179 arena: &'tcx WorkerLocal<Arena<'tcx>>,
1180 hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
1181 untracked: Untracked,
1182 incr_comp_session: Option<&'tcx IncrCompSession>,
1183 dep_graph: DepGraph,
1184 query_system: QuerySystem<'tcx>,
1185 hooks: crate::hooks::Providers,
1186 current_gcx: CurrentGcx,
1187 f: impl FnOnce(TyCtxt<'tcx>) -> T,
1188 ) -> T {
1189 let data_layout = sess.target.parse_data_layout().unwrap_or_else(|err| {
1190 sess.dcx().emit_fatal(err);
1191 });
1192 let interners = CtxtInterners::new(arena);
1193 let common_types = CommonTypes::new(&interners);
1194 let common_lifetimes = CommonLifetimes::new(&interners);
1195 let common_consts = CommonConsts::new(&interners, &common_types);
1196
1197 let gcx = gcx_cell.get_or_init(|| GlobalCtxt {
1198 sess,
1199 crate_types,
1200 stable_crate_id,
1201 arena,
1202 hir_arena,
1203 interners,
1204 incr_comp_session,
1205 dep_graph,
1206 hooks,
1207 prof: sess.prof.clone(),
1208 types: common_types,
1209 lifetimes: common_lifetimes,
1210 consts: common_consts,
1211 untracked,
1212 query_system,
1213 caches: Default::default(),
1214 data_layout,
1215 alloc_map: interpret::AllocMap::new(),
1216 current_gcx,
1217 });
1218
1219 gcx.enter(f)
1221 }
1222
1223 pub fn lang_items(self) -> &'tcx rustc_attr_ir::lang_items::LanguageItems {
1225 self.get_lang_items(())
1226 }
1227
1228 #[track_caller]
1230 pub fn ty_ordering_enum(self, span: Span) -> Ty<'tcx> {
1231 let ordering_enum = self.require_lang_item(LangItem::OrderingEnum, span);
1232 self.type_of(ordering_enum).no_bound_vars().unwrap()
1233 }
1234
1235 pub fn get_diagnostic_item(self, name: Symbol) -> Option<DefId> {
1238 self.all_diagnostic_items(()).name_to_id.get(&name).copied()
1239 }
1240
1241 pub fn get_diagnostic_name(self, id: DefId) -> Option<Symbol> {
1243 self.diagnostic_items(id.krate).id_to_name.get(&id).copied()
1244 }
1245
1246 pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool {
1248 self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did)
1249 }
1250
1251 pub fn is_coroutine(self, def_id: DefId) -> bool {
1252 self.coroutine_kind(def_id).is_some()
1253 }
1254
1255 pub fn is_async_drop_in_place_coroutine(self, def_id: DefId) -> bool {
1256 self.is_lang_item(self.parent(def_id), LangItem::AsyncDropInPlace)
1257 }
1258
1259 pub fn is_direct_const(self, def_id: DefId) -> bool {
1267 if true {
{
match self.def_kind(def_id) {
DefKind::Const | DefKind::AssocConst => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Const | DefKind::AssocConst",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::Const | DefKind::AssocConst);
1268 self.is_always_gca(def_id) || self.const_of_item(def_id).is_some()
1269 }
1270
1271 pub fn is_always_gca(self, def_id: DefId) -> bool {
1273 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(AlwaysGca) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self, def_id, AlwaysGca)
1274 }
1275
1276 pub fn coroutine_movability(self, def_id: DefId) -> hir::Movability {
1279 self.coroutine_kind(def_id).expect("expected a coroutine").movability()
1280 }
1281
1282 pub fn coroutine_is_async(self, def_id: DefId) -> bool {
1284 #[allow(non_exhaustive_omitted_patterns)] match self.coroutine_kind(def_id) {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) =>
true,
_ => false,
}matches!(
1285 self.coroutine_kind(def_id),
1286 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _))
1287 )
1288 }
1289
1290 pub fn is_synthetic_mir(self, def_id: impl Into<DefId>) -> bool {
1293 let def_id = def_id.into();
1294 match self.def_kind(def_id) {
1295 DefKind::SyntheticCoroutineBody => true,
1296 DefKind::Const | DefKind::AssocConst => self.const_of_item(def_id).is_some(),
1297 _ => false,
1298 }
1299 }
1300
1301 pub fn is_general_coroutine(self, def_id: DefId) -> bool {
1304 #[allow(non_exhaustive_omitted_patterns)] match self.coroutine_kind(def_id) {
Some(hir::CoroutineKind::Coroutine(_)) => true,
_ => false,
}matches!(self.coroutine_kind(def_id), Some(hir::CoroutineKind::Coroutine(_)))
1305 }
1306
1307 pub fn coroutine_is_gen(self, def_id: DefId) -> bool {
1309 #[allow(non_exhaustive_omitted_patterns)] match self.coroutine_kind(def_id) {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) =>
true,
_ => false,
}matches!(
1310 self.coroutine_kind(def_id),
1311 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _))
1312 )
1313 }
1314
1315 pub fn coroutine_is_async_gen(self, def_id: DefId) -> bool {
1317 #[allow(non_exhaustive_omitted_patterns)] match self.coroutine_kind(def_id) {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _))
=> true,
_ => false,
}matches!(
1318 self.coroutine_kind(def_id),
1319 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _))
1320 )
1321 }
1322
1323 pub fn features(self) -> &'tcx rustc_feature::Features {
1324 self.features_query(())
1325 }
1326
1327 pub fn def_key(self, id: impl IntoQueryKey<DefId>) -> rustc_hir::definitions::DefKey {
1328 let id = id.into_query_key();
1329 if let Some(id) = id.as_local() {
1331 self.definitions_untracked().def_key(id)
1332 } else {
1333 self.cstore_untracked().def_key(id)
1334 }
1335 }
1336
1337 pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath {
1343 if let Some(id) = id.as_local() {
1345 self.definitions_untracked().def_path(id)
1346 } else {
1347 self.cstore_untracked().def_path(id)
1348 }
1349 }
1350
1351 #[inline]
1352 pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash {
1353 if let Some(def_id) = def_id.as_local() {
1355 self.definitions_untracked().def_path_hash(def_id)
1356 } else {
1357 self.cstore_untracked().def_path_hash(def_id)
1358 }
1359 }
1360
1361 pub fn prelocked_def_path_hasher(
1367 self,
1368 ) -> impl Fn(DefId) -> rustc_hir::definitions::DefPathHash {
1369 let definitions = self.definitions_untracked();
1370 let cstore = self.cstore_untracked();
1371 move |def_id| match def_id.as_local() {
1372 Some(def_id) => definitions.def_path_hash(def_id),
1373 None => cstore.def_path_hash(def_id),
1374 }
1375 }
1376
1377 #[inline]
1378 pub fn crate_types(self) -> &'tcx [CrateType] {
1379 &self.crate_types
1380 }
1381
1382 pub fn needs_metadata(self) -> bool {
1383 self.crate_types().iter().any(|ty| match *ty {
1384 CrateType::Executable
1385 | CrateType::StaticLib
1386 | CrateType::Cdylib
1387 | CrateType::Sdylib => false,
1388 CrateType::Rlib | CrateType::Dylib | CrateType::ProcMacro => true,
1389 }) && !self.sess.opts.actually_rustdoc
1390 }
1391
1392 pub fn needs_hir_hash(self) -> bool {
1393 truecfg!(debug_assertions)
1405 || self.sess.opts.incremental.is_some()
1406 || self.needs_metadata()
1407 || self.sess.instrument_coverage()
1408 || self.sess.opts.unstable_opts.metrics_dir.is_some()
1409 }
1410
1411 pub fn needs_owner_info_hash(self) -> bool {
1426 self.needs_hir_hash()
1427 && (!self.sess.opts.unstable_opts.metadata_crate_hash
1428 || self.sess.opts.incremental.is_some()
1429 || truecfg!(debug_assertions))
1430 }
1431
1432 #[inline]
1433 pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId {
1434 if crate_num == LOCAL_CRATE {
1435 self.stable_crate_id
1436 } else {
1437 self.cstore_untracked().stable_crate_id(crate_num)
1438 }
1439 }
1440
1441 #[inline]
1444 pub fn stable_crate_id_to_crate_num(self, stable_crate_id: StableCrateId) -> CrateNum {
1445 if stable_crate_id == self.stable_crate_id(LOCAL_CRATE) {
1446 LOCAL_CRATE
1447 } else {
1448 *self
1449 .untracked()
1450 .stable_crate_ids
1451 .read()
1452 .get(&stable_crate_id)
1453 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("uninterned StableCrateId: {0:?}", stable_crate_id),
Location::caller())bug!("uninterned StableCrateId: {stable_crate_id:?}"))
1454 }
1455 }
1456
1457 pub fn def_path_hash_to_def_id(self, hash: DefPathHash) -> Option<DefId> {
1461 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs:1461",
"rustc_middle::ty::context", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs"),
::tracing_core::__macro_support::Option::Some(1461u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::context"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("def_path_hash_to_def_id({0:?})",
hash) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("def_path_hash_to_def_id({:?})", hash);
1462
1463 let stable_crate_id = hash.stable_crate_id();
1464
1465 if stable_crate_id == self.stable_crate_id(LOCAL_CRATE) {
1468 Some(self.untracked.definitions.read().local_def_path_hash_to_def_id(hash)?.to_def_id())
1469 } else {
1470 self.def_path_hash_to_def_id_extern(hash, stable_crate_id)
1471 }
1472 }
1473
1474 pub fn def_path_debug_str(self, def_id: DefId) -> String {
1475 let (crate_name, stable_crate_id) = if def_id.is_local() {
1480 (self.crate_name(LOCAL_CRATE), self.stable_crate_id(LOCAL_CRATE))
1481 } else {
1482 let cstore = &*self.cstore_untracked();
1483 (cstore.crate_name(def_id.krate), cstore.stable_crate_id(def_id.krate))
1484 };
1485
1486 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1:04x}]{2}", crate_name,
stable_crate_id.as_u64() >> (8 * 6),
self.def_path(def_id).to_string_no_crate_verbose()))
})format!(
1487 "{}[{:04x}]{}",
1488 crate_name,
1489 stable_crate_id.as_u64() >> (8 * 6),
1492 self.def_path(def_id).to_string_no_crate_verbose()
1493 )
1494 }
1495
1496 pub fn dcx(self) -> DiagCtxtHandle<'tcx> {
1497 self.sess.dcx()
1498 }
1499
1500 pub fn is_target_feature_call_safe(
1503 self,
1504 callee_features: &[TargetFeature],
1505 body_features: &[TargetFeature],
1506 ) -> bool {
1507 self.sess.target.options.is_like_wasm
1512 || callee_features
1513 .iter()
1514 .all(|feature| body_features.iter().any(|f| f.name == feature.name))
1515 }
1516
1517 pub fn adjust_target_feature_sig(
1520 self,
1521 fun_def: DefId,
1522 fun_sig: ty::Binder<'tcx, ty::FnSig<'tcx>>,
1523 caller: DefId,
1524 ) -> Option<ty::Binder<'tcx, ty::FnSig<'tcx>>> {
1525 let fun_features = &self.codegen_fn_attrs(fun_def).target_features;
1526 let caller_features = &self.body_codegen_attrs(caller).target_features;
1527 if self.is_target_feature_call_safe(&fun_features, &caller_features) {
1528 return Some(fun_sig.map_bound(|sig| ty::FnSig {
1529 fn_sig_kind: fun_sig.fn_sig_kind().set_safety(hir::Safety::Safe),
1530 ..sig
1531 }));
1532 }
1533 None
1534 }
1535
1536 pub fn env_var<K: ?Sized + AsRef<OsStr>>(self, key: &'tcx K) -> Result<&'tcx str, VarError> {
1539 match self.env_var_os(key.as_ref()) {
1540 Some(value) => value.to_str().ok_or_else(|| VarError::NotUnicode(value.to_os_string())),
1541 None => Err(VarError::NotPresent),
1542 }
1543 }
1544
1545 pub fn is_method(self, id: DefId) -> bool {
1546 self.opt_associated_item(id).is_some_and(|item| item.is_method())
1547 }
1548}
1549
1550impl<'tcx> TyCtxtAt<'tcx> {
1551 pub fn create_def(
1553 self,
1554 parent: LocalDefId,
1555 name: Option<Symbol>,
1556 def_kind: DefKind,
1557 override_def_path_data: Option<DefPathData>,
1558 disambiguator: &mut PerParentDisambiguatorState,
1559 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1560 let feed =
1561 self.tcx.create_def(parent, name, def_kind, override_def_path_data, disambiguator);
1562
1563 feed.def_span(self.span);
1564 feed
1565 }
1566}
1567
1568impl<'tcx> TyCtxt<'tcx> {
1569 pub fn create_def(
1571 self,
1572 parent: LocalDefId,
1573 name: Option<Symbol>,
1574 def_kind: DefKind,
1575 override_def_path_data: Option<DefPathData>,
1576 disambiguator: &mut PerParentDisambiguatorState,
1577 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1578 let data = override_def_path_data.unwrap_or_else(|| def_kind.def_path_data(name));
1579 let def_id = self.untracked.definitions.write().create_def(parent, data, disambiguator);
1589
1590 self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
1595
1596 let feed = TyCtxtFeed { tcx: self, key: def_id };
1597 feed.def_kind(def_kind);
1598 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Closure | DefKind::OpaqueTy => true,
_ => false,
}matches!(def_kind, DefKind::Closure | DefKind::OpaqueTy) {
1603 let parent_mod = self.parent_module_from_def_id(def_id);
1604 feed.visibility(ty::Visibility::Restricted(parent_mod.to_mod_id()));
1605 }
1606
1607 feed
1608 }
1609
1610 pub fn create_crate_num(
1611 self,
1612 stable_crate_id: StableCrateId,
1613 ) -> Result<TyCtxtFeed<'tcx, CrateNum>, CrateNum> {
1614 let mut lock = self.untracked().stable_crate_ids.write();
1615 if let Some(&existing) = lock.get(&stable_crate_id) {
1616 return Err(existing);
1617 }
1618 let num = CrateNum::new(lock.len());
1619 lock.insert(stable_crate_id, num);
1620 Ok(TyCtxtFeed { key: num, tcx: self })
1621 }
1622
1623 pub fn iter_local_def_id(self) -> impl Iterator<Item = LocalDefId> {
1624 self.ensure_ok().required_analysis(());
1626
1627 let definitions = &self.untracked.definitions;
1628 gen {
1629 let mut i = 0;
1630
1631 while i < { definitions.read().num_definitions() } {
1634 let local_def_index = rustc_span::def_id::DefIndex::from_usize(i);
1635 yield LocalDefId { local_def_index };
1636 i += 1;
1637 }
1638
1639 definitions.freeze();
1641 }
1642 }
1643
1644 pub fn definitions(self) -> &'tcx rustc_hir::definitions::Definitions {
1645 self.ensure_ok().required_analysis(());
1647
1648 self.untracked.definitions.freeze()
1651 }
1652
1653 pub fn def_path_hash_to_def_index_map(self) -> &'tcx rustc_hir::definitions::DefPathToIndexMap {
1654 self.ensure_ok().hir_crate_items(());
1657 self.untracked.definitions.freeze().def_path_hash_to_def_index_map()
1660 }
1661
1662 #[inline]
1665 pub fn cstore_untracked(self) -> FreezeReadGuard<'tcx, CrateStoreDyn> {
1666 FreezeReadGuard::map(self.untracked.cstore.read(), |c| &**c)
1667 }
1668
1669 pub fn untracked(self) -> &'tcx Untracked {
1671 &self.untracked
1672 }
1673 #[inline]
1676 pub fn definitions_untracked(self) -> FreezeReadGuard<'tcx, Definitions> {
1677 self.untracked.definitions.read()
1678 }
1679
1680 #[inline(always)]
1681 pub fn with_stable_hashing_context<R>(self, f: impl FnOnce(StableHashState<'_>) -> R) -> R {
1682 f(StableHashState::new(self.sess, &self.untracked))
1683 }
1684
1685 #[inline]
1686 pub fn local_crate_exports_generics(self) -> bool {
1687 if self.is_compiler_builtins(LOCAL_CRATE) {
1691 return false;
1692 }
1693 self.crate_types().iter().any(|crate_type| {
1694 match crate_type {
1695 CrateType::Executable
1696 | CrateType::StaticLib
1697 | CrateType::ProcMacro
1698 | CrateType::Cdylib
1699 | CrateType::Sdylib => false,
1700
1701 CrateType::Dylib => true,
1706
1707 CrateType::Rlib => true,
1708 }
1709 })
1710 }
1711
1712 pub fn is_suitable_region(
1714 self,
1715 generic_param_scope: LocalDefId,
1716 mut region: Region<'tcx>,
1717 ) -> Option<FreeRegionInfo> {
1718 let (suitable_region_binding_scope, region_def_id) = loop {
1719 let def_id =
1720 region.opt_param_def_id(self, generic_param_scope.to_def_id())?.as_local()?;
1721 let scope = self.local_parent(def_id);
1722 if self.def_kind(scope) == DefKind::OpaqueTy {
1723 region = self.map_opaque_lifetime_to_parent_lifetime(def_id);
1726 continue;
1727 }
1728 break (scope, def_id.into());
1729 };
1730
1731 let is_impl_item = match self.hir_node_by_def_id(suitable_region_binding_scope) {
1732 Node::Item(..) | Node::TraitItem(..) => false,
1733 Node::ImplItem(impl_item) => match impl_item.impl_kind {
1734 hir::ImplItemImplKind::Trait { .. } => true,
1741 _ => false,
1742 },
1743 _ => false,
1744 };
1745
1746 Some(FreeRegionInfo { scope: suitable_region_binding_scope, region_def_id, is_impl_item })
1747 }
1748
1749 pub fn return_type_impl_or_dyn_traits(
1751 self,
1752 scope_def_id: LocalDefId,
1753 ) -> Vec<&'tcx hir::Ty<'tcx>> {
1754 let hir_id = self.local_def_id_to_hir_id(scope_def_id);
1755 let Some(hir::FnDecl { output: hir::FnRetTy::Return(hir_output), .. }) =
1756 self.hir_fn_decl_by_hir_id(hir_id)
1757 else {
1758 return ::alloc::vec::Vec::new()vec![];
1759 };
1760
1761 let mut v = TraitObjectVisitor(::alloc::vec::Vec::new()vec![]);
1762 v.visit_ty_unambig(hir_output);
1763 v.0
1764 }
1765
1766 pub fn return_type_impl_or_dyn_traits_with_type_alias(
1770 self,
1771 scope_def_id: LocalDefId,
1772 ) -> Option<(Vec<&'tcx hir::Ty<'tcx>>, Span, Option<Span>)> {
1773 let hir_id = self.local_def_id_to_hir_id(scope_def_id);
1774 let mut v = TraitObjectVisitor(::alloc::vec::Vec::new()vec![]);
1775 if let Some(hir::FnDecl { output: hir::FnRetTy::Return(hir_output), .. }) = self.hir_fn_decl_by_hir_id(hir_id)
1777 && let hir::TyKind::Path(hir::QPath::Resolved(
1778 None,
1779 hir::Path { res: hir::def::Res::Def(DefKind::TyAlias, def_id), .. }, )) = hir_output.kind
1780 && let Some(local_id) = def_id.as_local()
1781 && let Some(alias_ty) = self.hir_node_by_def_id(local_id).alias_ty() && let Some(alias_generics) = self.hir_node_by_def_id(local_id).generics()
1783 {
1784 v.visit_ty_unambig(alias_ty);
1785 if !v.0.is_empty() {
1786 return Some((
1787 v.0,
1788 alias_generics.span,
1789 alias_generics.span_for_lifetime_suggestion(),
1790 ));
1791 }
1792 }
1793 None
1794 }
1795
1796 pub fn has_strict_asm_symbol_naming(self) -> bool {
1799 self.sess.target.llvm_target.starts_with("nvptx")
1800 }
1801
1802 pub fn caller_location_ty(self) -> Ty<'tcx> {
1804 Ty::new_imm_ref(
1805 self,
1806 self.lifetimes.re_static,
1807 self.type_of(self.require_lang_item(LangItem::PanicLocation, DUMMY_SP))
1808 .instantiate(self, self.mk_args(&[self.lifetimes.re_static.into()]))
1809 .skip_norm_wip(),
1810 )
1811 }
1812
1813 pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) {
1815 let kind = self.def_kind(def_id);
1816 (self.def_kind_descr_article(kind, def_id), self.def_kind_descr(kind, def_id))
1817 }
1818
1819 pub fn type_length_limit(self) -> Limit {
1820 self.limits(()).type_length_limit
1821 }
1822
1823 pub fn recursion_limit(self) -> Limit {
1824 self.limits(()).recursion_limit
1825 }
1826
1827 pub fn move_size_limit(self) -> Limit {
1828 self.limits(()).move_size_limit
1829 }
1830
1831 pub fn pattern_complexity_limit(self) -> Limit {
1832 self.limits(()).pattern_complexity_limit
1833 }
1834
1835 pub fn all_traits_including_private(self) -> impl Iterator<Item = DefId> {
1837 iter::once(LOCAL_CRATE)
1838 .chain(self.crates(()).iter().copied())
1839 .flat_map(move |cnum| self.traits(cnum).iter().copied())
1840 }
1841
1842 pub fn visible_traits(self) -> impl Iterator<Item = DefId> {
1844 let visible_crates =
1845 self.crates(()).iter().copied().filter(move |cnum| self.is_user_visible_dep(*cnum));
1846
1847 iter::once(LOCAL_CRATE)
1848 .chain(visible_crates)
1849 .flat_map(move |cnum| self.traits(cnum).iter().copied())
1850 }
1851
1852 #[inline]
1853 pub fn local_visibility(self, def_id: LocalDefId) -> Visibility {
1854 self.visibility(def_id).expect_local()
1855 }
1856
1857 {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("local_opaque_ty_origin",
"rustc_middle::ty::context", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs"),
::tracing_core::__macro_support::Option::Some(1858u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::context"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
hir::OpaqueTyOrigin<LocalDefId> = loop {};
return __tracing_attr_fake_return;
}
{ self.hir_expect_opaque_ty(def_id).origin }
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs:1858",
"rustc_middle::ty::context", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs"),
::tracing_core::__macro_support::Option::Some(1858u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::context"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(skip(self), level = "trace", ret)]
1859 pub fn local_opaque_ty_origin(self, def_id: LocalDefId) -> hir::OpaqueTyOrigin<LocalDefId> {
1860 self.hir_expect_opaque_ty(def_id).origin
1861 }
1862
1863 pub fn finish(self) {
1864 self.alloc_self_profile_query_strings();
1867
1868 self.save_dep_graph();
1869 self.verify_query_key_hashes();
1870
1871 if let Err((path, error)) = self.dep_graph.finish_encoding() {
1872 self.sess
1873 .dcx()
1874 .emit_fatal(crate::diagnostics::FailedWritingFile { path: &path, error });
1875 }
1876 }
1877
1878 pub fn report_unused_features(self) {
1879 #[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for UnusedFeature {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
match self {
UnusedFeature { feature: __binding_0 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("feature `{$feature}` is declared but not used")));
;
diag.arg("feature", __binding_0);
diag
}
}
}
}
};Diagnostic)]
1880 #[diag("feature `{$feature}` is declared but not used")]
1881 struct UnusedFeature {
1882 feature: Symbol,
1883 }
1884
1885 let used_features = self.query_system.used_features.lock();
1887 let unused_features = self
1888 .features()
1889 .enabled_features_iter_stable_order()
1890 .filter(|(f, _)| {
1891 !used_features.contains_key(f)
1892 && f.as_str() != "restricted_std"
1899 && *f != sym::doc_cfg
1903 })
1904 .collect::<Vec<_>>();
1905
1906 for (feature, span) in unused_features {
1907 self.emit_node_span_lint(
1908 UNUSED_FEATURES,
1909 CRATE_HIR_ID,
1910 span,
1911 UnusedFeature { feature },
1912 );
1913 }
1914 }
1915}
1916
1917macro_rules! nop_lift {
1918 ($set:ident; $ty:ty => $lifted:ty) => {
1919 impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for $ty {
1920 type Lifted = $lifted;
1921 #[track_caller]
1922 fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
1923 fn _intern_set_ty_from_interned_ty<'tcx, Inner>(
1928 _x: Interned<'tcx, Inner>,
1929 ) -> InternedSet<'tcx, Inner> {
1930 unreachable!()
1931 }
1932 fn _type_eq<T>(_x: &T, _y: &T) {}
1933 fn _test<'tcx>(x: $lifted, tcx: TyCtxt<'tcx>) {
1934 let interner = _intern_set_ty_from_interned_ty(x.0);
1938 _type_eq(&interner, &tcx.interners.$set);
1940 }
1941
1942 assert!(tcx.interners.$set.contains_pointer_to(&InternedInSet(&*self.0.0)));
1943 unsafe { mem::transmute(self) }
1946 }
1947 }
1948 };
1949}
1950
1951macro_rules! nop_list_lift {
1952 ($set:ident; $ty:ty => $lifted:ty) => {
1953 nop_list_lift! { $set: List; $ty => $lifted }
1954 };
1955 ($set:ident: $list:ident; $ty:ty => $lifted:ty) => {
1957 impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a $list<$ty> {
1958 type Lifted = &'tcx $list<$lifted>;
1959 fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
1960 if false {
1962 let _x: &InternedSet<'tcx, $list<$lifted>> = &tcx.interners.$set;
1963 }
1964
1965 if self.is_empty() {
1966 return $list::empty();
1967 }
1968 assert!(tcx.interners.$set.contains_pointer_to(&InternedInSet(self)));
1969 unsafe { mem::transmute(self) }
1972 }
1973 }
1974 };
1975}
1976
1977impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Ty<'a> {
type Lifted = Ty<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: Ty<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.type_);
}
if !tcx.interners.type_.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.type_.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { type_; Ty<'a> => Ty<'tcx> }
1978impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Pattern<'a> {
type Lifted = Pattern<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: Pattern<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.pat);
}
if !tcx.interners.pat.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.pat.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { pat; Pattern<'a> => Pattern<'tcx> }
1979impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for ConstAllocation<'a> {
type Lifted = ConstAllocation<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: ConstAllocation<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.const_allocation);
}
if !tcx.interners.const_allocation.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.const_allocation.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { const_allocation; ConstAllocation<'a> => ConstAllocation<'tcx> }
1980impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Predicate<'a> {
type Lifted = Predicate<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: Predicate<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.predicate);
}
if !tcx.interners.predicate.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.predicate.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { predicate; Predicate<'a> => Predicate<'tcx> }
1981impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Clause<'a> {
type Lifted = Clause<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: Clause<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.predicate);
}
if !tcx.interners.predicate.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.predicate.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { predicate; Clause<'a> => Clause<'tcx> }
1982impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Layout<'a> {
type Lifted = Layout<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: Layout<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.layout);
}
if !tcx.interners.layout.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.layout.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { layout; Layout<'a> => Layout<'tcx> }
1983impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for ValTree<'a> {
type Lifted = ValTree<'tcx>;
#[track_caller]
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
fn _intern_set_ty_from_interned_ty<'tcx,
Inner>(_x: Interned<'tcx, Inner>) -> InternedSet<'tcx, Inner> {
::core::panicking::unreachable_default_msg()
}
fn _type_eq<T>(_x: &T, _y: &T) {}
fn _test<'tcx>(x: ValTree<'tcx>, tcx: TyCtxt<'tcx>) {
let interner = _intern_set_ty_from_interned_ty(x.0);
_type_eq(&interner, &tcx.interners.valtree);
}
if !tcx.interners.valtree.contains_pointer_to(&InternedInSet(&*self.0.0))
{
::core::panicking::panic("assertion failed: tcx.interners.valtree.contains_pointer_to(&InternedInSet(&*self.0.0))")
};
unsafe { mem::transmute(self) }
}
}nop_lift! { valtree; ValTree<'a> => ValTree<'tcx> }
1984
1985impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Interned<'a, RegionKind<'a>> {
1986 type Lifted = Interned<'tcx, RegionKind<'tcx>>;
1987
1988 #[track_caller]
1989 fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
1990 if !tcx.interners.region.contains_pointer_to(&InternedInSet(&*self.0)) {
::core::panicking::panic("assertion failed: tcx.interners.region.contains_pointer_to(&InternedInSet(&*self.0))")
};assert!(tcx.interners.region.contains_pointer_to(&InternedInSet(&*self.0)));
1991 unsafe { mem::transmute(self) }
1994 }
1995}
1996
1997impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for Interned<'a, WithCachedTypeInfo<ConstKind<'a>>> {
1999 type Lifted = Interned<'tcx, WithCachedTypeInfo<ConstKind<'tcx>>>;
2000
2001 #[track_caller]
2002 fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
2003 if !tcx.interners.const_.contains_pointer_to(&InternedInSet(&*self.0)) {
::core::panicking::panic("assertion failed: tcx.interners.const_.contains_pointer_to(&InternedInSet(&*self.0))")
};assert!(tcx.interners.const_.contains_pointer_to(&InternedInSet(&*self.0)));
2004 unsafe { mem::transmute(self) }
2007 }
2008}
2009
2010impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a List<Ty<'a>> {
type Lifted = &'tcx List<Ty<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, List<Ty<'tcx>>> =
&tcx.interners.type_lists;
}
if self.is_empty() { return List::empty(); }
if !tcx.interners.type_lists.contains_pointer_to(&InternedInSet(self))
{
::core::panicking::panic("assertion failed: tcx.interners.type_lists.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! { type_lists; Ty<'a> => Ty<'tcx> }
2011impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a ListWithCachedTypeInfo<Clause<'a>> {
type Lifted = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, ListWithCachedTypeInfo<Clause<'tcx>>> =
&tcx.interners.clauses;
}
if self.is_empty() { return ListWithCachedTypeInfo::empty(); }
if !tcx.interners.clauses.contains_pointer_to(&InternedInSet(self)) {
::core::panicking::panic("assertion failed: tcx.interners.clauses.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! { clauses: ListWithCachedTypeInfo; Clause<'a> => Clause<'tcx> }
2012impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a List<PolyExistentialPredicate<'a>> {
type Lifted = &'tcx List<PolyExistentialPredicate<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, List<PolyExistentialPredicate<'tcx>>> =
&tcx.interners.poly_existential_predicates;
}
if self.is_empty() { return List::empty(); }
if !tcx.interners.poly_existential_predicates.contains_pointer_to(&InternedInSet(self))
{
::core::panicking::panic("assertion failed: tcx.interners.poly_existential_predicates.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! {
2013 poly_existential_predicates; PolyExistentialPredicate<'a> => PolyExistentialPredicate<'tcx>
2014}
2015impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a List<ty::BoundVariableKind<'a>> {
type Lifted = &'tcx List<ty::BoundVariableKind<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, List<ty::BoundVariableKind<'tcx>>> =
&tcx.interners.bound_variable_kinds;
}
if self.is_empty() { return List::empty(); }
if !tcx.interners.bound_variable_kinds.contains_pointer_to(&InternedInSet(self))
{
::core::panicking::panic("assertion failed: tcx.interners.bound_variable_kinds.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! { bound_variable_kinds; ty::BoundVariableKind<'a> => ty::BoundVariableKind<'tcx> }
2016impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a List<Pattern<'a>> {
type Lifted = &'tcx List<Pattern<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, List<Pattern<'tcx>>> =
&tcx.interners.patterns;
}
if self.is_empty() { return List::empty(); }
if !tcx.interners.patterns.contains_pointer_to(&InternedInSet(self)) {
::core::panicking::panic("assertion failed: tcx.interners.patterns.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! { patterns; Pattern<'a> => Pattern<'tcx> }
2017impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a List<ty::ArgOutlivesClause<'a>> {
type Lifted = &'tcx List<ty::ArgOutlivesClause<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, List<ty::ArgOutlivesClause<'tcx>>> =
&tcx.interners.outlives;
}
if self.is_empty() { return List::empty(); }
if !tcx.interners.outlives.contains_pointer_to(&InternedInSet(self)) {
::core::panicking::panic("assertion failed: tcx.interners.outlives.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! { outlives; ty::ArgOutlivesClause<'a> => ty::ArgOutlivesClause<'tcx> }
2018
2019impl<'a, 'tcx> Lift<TyCtxt<'tcx>> for &'a List<GenericArg<'a>> {
type Lifted = &'tcx List<GenericArg<'tcx>>;
fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Self::Lifted {
if false {
let _x: &InternedSet<'tcx, List<GenericArg<'tcx>>> =
&tcx.interners.args;
}
if self.is_empty() { return List::empty(); }
if !tcx.interners.args.contains_pointer_to(&InternedInSet(self)) {
::core::panicking::panic("assertion failed: tcx.interners.args.contains_pointer_to(&InternedInSet(self))")
};
unsafe { mem::transmute(self) }
}
}nop_list_lift! { args; GenericArg<'a> => GenericArg<'tcx> }
2021
2022macro_rules! sty_debug_print {
2023 ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{
2024 #[allow(non_snake_case, reason = "we're using variant names as local variables")]
2025 mod inner {
2026 use crate::ty::{self, TyCtxt};
2027 use crate::ty::context::InternedInSet;
2028
2029 #[derive(Copy, Clone)]
2030 struct DebugStat {
2031 total: usize,
2032 lt_infer: usize,
2033 ty_infer: usize,
2034 ct_infer: usize,
2035 all_infer: usize,
2036 }
2037
2038 pub(crate) fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result {
2039 let mut total = DebugStat {
2040 total: 0,
2041 lt_infer: 0,
2042 ty_infer: 0,
2043 ct_infer: 0,
2044 all_infer: 0,
2045 };
2046 $(let mut $variant = total;)*
2047
2048 for shard in tcx.interners.type_.lock_shards() {
2049 #[allow(rustc::potential_query_instability)]
2051 let types = shard.iter();
2052 for &(InternedInSet(t), ()) in types {
2053 let variant = match t.internee {
2054 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
2055 ty::Float(..) | ty::Str | ty::Never => continue,
2056 ty::Error(_) => continue,
2057 $(ty::$variant(..) => &mut $variant,)*
2058 };
2059 let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
2060 let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
2061 let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
2062
2063 variant.total += 1;
2064 total.total += 1;
2065 if lt { total.lt_infer += 1; variant.lt_infer += 1 }
2066 if ty { total.ty_infer += 1; variant.ty_infer += 1 }
2067 if ct { total.ct_infer += 1; variant.ct_infer += 1 }
2068 if lt && ty && ct { total.all_infer += 1; variant.all_infer += 1 }
2069 }
2070 }
2071 writeln!(fmt, "Ty interner total ty lt ct all")?;
2072 $(writeln!(fmt, " {:18}: {uses:6} {usespc:4.1}%, \
2073 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2074 stringify!($variant),
2075 uses = $variant.total,
2076 usespc = $variant.total as f64 * 100.0 / total.total as f64,
2077 ty = $variant.ty_infer as f64 * 100.0 / total.total as f64,
2078 lt = $variant.lt_infer as f64 * 100.0 / total.total as f64,
2079 ct = $variant.ct_infer as f64 * 100.0 / total.total as f64,
2080 all = $variant.all_infer as f64 * 100.0 / total.total as f64)?;
2081 )*
2082 writeln!(fmt, " total {uses:6} \
2083 {ty:4.1}% {lt:5.1}% {ct:4.1}% {all:4.1}%",
2084 uses = total.total,
2085 ty = total.ty_infer as f64 * 100.0 / total.total as f64,
2086 lt = total.lt_infer as f64 * 100.0 / total.total as f64,
2087 ct = total.ct_infer as f64 * 100.0 / total.total as f64,
2088 all = total.all_infer as f64 * 100.0 / total.total as f64)
2089 }
2090 }
2091
2092 inner::go($fmt, $ctxt)
2093 }}
2094}
2095
2096impl<'tcx> TyCtxt<'tcx> {
2097 pub fn debug_stats(self) -> impl fmt::Debug {
2098 fmt::from_fn(move |fmt| {
2099 {
#[allow(non_snake_case, reason =
"we're using variant names as local variables")]
mod inner {
use crate::ty::{self, TyCtxt};
use crate::ty::context::InternedInSet;
struct DebugStat {
total: usize,
lt_infer: usize,
ty_infer: usize,
ct_infer: usize,
all_infer: usize,
}
#[automatically_derived]
impl ::core::marker::Copy for DebugStat { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DebugStat { }
#[automatically_derived]
impl ::core::clone::Clone for DebugStat {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}
pub(crate) fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>)
-> std::fmt::Result {
let mut total =
DebugStat {
total: 0,
lt_infer: 0,
ty_infer: 0,
ct_infer: 0,
all_infer: 0,
};
let mut Adt = total;
let mut Array = total;
let mut Slice = total;
let mut RawPtr = total;
let mut Ref = total;
let mut FnDef = total;
let mut FnPtr = total;
let mut UnsafeBinder = total;
let mut Placeholder = total;
let mut Coroutine = total;
let mut CoroutineWitness = total;
let mut Dynamic = total;
let mut Closure = total;
let mut CoroutineClosure = total;
let mut Tuple = total;
let mut View = total;
let mut Bound = total;
let mut Param = total;
let mut Infer = total;
let mut Alias = total;
let mut Pat = total;
let mut Foreign = total;
for shard in tcx.interners.type_.lock_shards() {
#[allow(rustc :: potential_query_instability)]
let types = shard.iter();
for &(InternedInSet(t), ()) in types {
let variant =
match t.internee {
ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
ty::Float(..) | ty::Str | ty::Never => continue,
ty::Error(_) => continue,
ty::Adt(..) => &mut Adt,
ty::Array(..) => &mut Array,
ty::Slice(..) => &mut Slice,
ty::RawPtr(..) => &mut RawPtr,
ty::Ref(..) => &mut Ref,
ty::FnDef(..) => &mut FnDef,
ty::FnPtr(..) => &mut FnPtr,
ty::UnsafeBinder(..) => &mut UnsafeBinder,
ty::Placeholder(..) => &mut Placeholder,
ty::Coroutine(..) => &mut Coroutine,
ty::CoroutineWitness(..) => &mut CoroutineWitness,
ty::Dynamic(..) => &mut Dynamic,
ty::Closure(..) => &mut Closure,
ty::CoroutineClosure(..) => &mut CoroutineClosure,
ty::Tuple(..) => &mut Tuple,
ty::View(..) => &mut View,
ty::Bound(..) => &mut Bound,
ty::Param(..) => &mut Param,
ty::Infer(..) => &mut Infer,
ty::Alias(..) => &mut Alias,
ty::Pat(..) => &mut Pat,
ty::Foreign(..) => &mut Foreign,
};
let lt = t.flags.intersects(ty::TypeFlags::HAS_RE_INFER);
let ty = t.flags.intersects(ty::TypeFlags::HAS_TY_INFER);
let ct = t.flags.intersects(ty::TypeFlags::HAS_CT_INFER);
variant.total += 1;
total.total += 1;
if lt { total.lt_infer += 1; variant.lt_infer += 1 }
if ty { total.ty_infer += 1; variant.ty_infer += 1 }
if ct { total.ct_infer += 1; variant.ct_infer += 1 }
if lt && ty && ct {
total.all_infer += 1;
variant.all_infer += 1
}
}
}
fmt.write_fmt(format_args!("Ty interner total ty lt ct all\n"))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Adt", Adt.total,
Adt.total as f64 * 100.0 / total.total as f64,
Adt.ty_infer as f64 * 100.0 / total.total as f64,
Adt.lt_infer as f64 * 100.0 / total.total as f64,
Adt.ct_infer as f64 * 100.0 / total.total as f64,
Adt.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Array", Array.total,
Array.total as f64 * 100.0 / total.total as f64,
Array.ty_infer as f64 * 100.0 / total.total as f64,
Array.lt_infer as f64 * 100.0 / total.total as f64,
Array.ct_infer as f64 * 100.0 / total.total as f64,
Array.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Slice", Slice.total,
Slice.total as f64 * 100.0 / total.total as f64,
Slice.ty_infer as f64 * 100.0 / total.total as f64,
Slice.lt_infer as f64 * 100.0 / total.total as f64,
Slice.ct_infer as f64 * 100.0 / total.total as f64,
Slice.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"RawPtr", RawPtr.total,
RawPtr.total as f64 * 100.0 / total.total as f64,
RawPtr.ty_infer as f64 * 100.0 / total.total as f64,
RawPtr.lt_infer as f64 * 100.0 / total.total as f64,
RawPtr.ct_infer as f64 * 100.0 / total.total as f64,
RawPtr.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Ref", Ref.total,
Ref.total as f64 * 100.0 / total.total as f64,
Ref.ty_infer as f64 * 100.0 / total.total as f64,
Ref.lt_infer as f64 * 100.0 / total.total as f64,
Ref.ct_infer as f64 * 100.0 / total.total as f64,
Ref.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"FnDef", FnDef.total,
FnDef.total as f64 * 100.0 / total.total as f64,
FnDef.ty_infer as f64 * 100.0 / total.total as f64,
FnDef.lt_infer as f64 * 100.0 / total.total as f64,
FnDef.ct_infer as f64 * 100.0 / total.total as f64,
FnDef.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"FnPtr", FnPtr.total,
FnPtr.total as f64 * 100.0 / total.total as f64,
FnPtr.ty_infer as f64 * 100.0 / total.total as f64,
FnPtr.lt_infer as f64 * 100.0 / total.total as f64,
FnPtr.ct_infer as f64 * 100.0 / total.total as f64,
FnPtr.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"UnsafeBinder", UnsafeBinder.total,
UnsafeBinder.total as f64 * 100.0 / total.total as f64,
UnsafeBinder.ty_infer as f64 * 100.0 / total.total as f64,
UnsafeBinder.lt_infer as f64 * 100.0 / total.total as f64,
UnsafeBinder.ct_infer as f64 * 100.0 / total.total as f64,
UnsafeBinder.all_infer as f64 * 100.0 /
total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Placeholder", Placeholder.total,
Placeholder.total as f64 * 100.0 / total.total as f64,
Placeholder.ty_infer as f64 * 100.0 / total.total as f64,
Placeholder.lt_infer as f64 * 100.0 / total.total as f64,
Placeholder.ct_infer as f64 * 100.0 / total.total as f64,
Placeholder.all_infer as f64 * 100.0 /
total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Coroutine", Coroutine.total,
Coroutine.total as f64 * 100.0 / total.total as f64,
Coroutine.ty_infer as f64 * 100.0 / total.total as f64,
Coroutine.lt_infer as f64 * 100.0 / total.total as f64,
Coroutine.ct_infer as f64 * 100.0 / total.total as f64,
Coroutine.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"CoroutineWitness", CoroutineWitness.total,
CoroutineWitness.total as f64 * 100.0 / total.total as f64,
CoroutineWitness.ty_infer as f64 * 100.0 /
total.total as f64,
CoroutineWitness.lt_infer as f64 * 100.0 /
total.total as f64,
CoroutineWitness.ct_infer as f64 * 100.0 /
total.total as f64,
CoroutineWitness.all_infer as f64 * 100.0 /
total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Dynamic", Dynamic.total,
Dynamic.total as f64 * 100.0 / total.total as f64,
Dynamic.ty_infer as f64 * 100.0 / total.total as f64,
Dynamic.lt_infer as f64 * 100.0 / total.total as f64,
Dynamic.ct_infer as f64 * 100.0 / total.total as f64,
Dynamic.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Closure", Closure.total,
Closure.total as f64 * 100.0 / total.total as f64,
Closure.ty_infer as f64 * 100.0 / total.total as f64,
Closure.lt_infer as f64 * 100.0 / total.total as f64,
Closure.ct_infer as f64 * 100.0 / total.total as f64,
Closure.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"CoroutineClosure", CoroutineClosure.total,
CoroutineClosure.total as f64 * 100.0 / total.total as f64,
CoroutineClosure.ty_infer as f64 * 100.0 /
total.total as f64,
CoroutineClosure.lt_infer as f64 * 100.0 /
total.total as f64,
CoroutineClosure.ct_infer as f64 * 100.0 /
total.total as f64,
CoroutineClosure.all_infer as f64 * 100.0 /
total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Tuple", Tuple.total,
Tuple.total as f64 * 100.0 / total.total as f64,
Tuple.ty_infer as f64 * 100.0 / total.total as f64,
Tuple.lt_infer as f64 * 100.0 / total.total as f64,
Tuple.ct_infer as f64 * 100.0 / total.total as f64,
Tuple.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"View", View.total,
View.total as f64 * 100.0 / total.total as f64,
View.ty_infer as f64 * 100.0 / total.total as f64,
View.lt_infer as f64 * 100.0 / total.total as f64,
View.ct_infer as f64 * 100.0 / total.total as f64,
View.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Bound", Bound.total,
Bound.total as f64 * 100.0 / total.total as f64,
Bound.ty_infer as f64 * 100.0 / total.total as f64,
Bound.lt_infer as f64 * 100.0 / total.total as f64,
Bound.ct_infer as f64 * 100.0 / total.total as f64,
Bound.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Param", Param.total,
Param.total as f64 * 100.0 / total.total as f64,
Param.ty_infer as f64 * 100.0 / total.total as f64,
Param.lt_infer as f64 * 100.0 / total.total as f64,
Param.ct_infer as f64 * 100.0 / total.total as f64,
Param.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Infer", Infer.total,
Infer.total as f64 * 100.0 / total.total as f64,
Infer.ty_infer as f64 * 100.0 / total.total as f64,
Infer.lt_infer as f64 * 100.0 / total.total as f64,
Infer.ct_infer as f64 * 100.0 / total.total as f64,
Infer.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Alias", Alias.total,
Alias.total as f64 * 100.0 / total.total as f64,
Alias.ty_infer as f64 * 100.0 / total.total as f64,
Alias.lt_infer as f64 * 100.0 / total.total as f64,
Alias.ct_infer as f64 * 100.0 / total.total as f64,
Alias.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Pat", Pat.total,
Pat.total as f64 * 100.0 / total.total as f64,
Pat.ty_infer as f64 * 100.0 / total.total as f64,
Pat.lt_infer as f64 * 100.0 / total.total as f64,
Pat.ct_infer as f64 * 100.0 / total.total as f64,
Pat.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" {0:18}: {1:6} {2:4.1}%, {3:4.1}% {4:5.1}% {5:4.1}% {6:4.1}%\n",
"Foreign", Foreign.total,
Foreign.total as f64 * 100.0 / total.total as f64,
Foreign.ty_infer as f64 * 100.0 / total.total as f64,
Foreign.lt_infer as f64 * 100.0 / total.total as f64,
Foreign.ct_infer as f64 * 100.0 / total.total as f64,
Foreign.all_infer as f64 * 100.0 / total.total as f64))?;
fmt.write_fmt(format_args!(" total {0:6} {1:4.1}% {2:5.1}% {3:4.1}% {4:4.1}%\n",
total.total,
total.ty_infer as f64 * 100.0 / total.total as f64,
total.lt_infer as f64 * 100.0 / total.total as f64,
total.ct_infer as f64 * 100.0 / total.total as f64,
total.all_infer as f64 * 100.0 / total.total as f64))
}
}
inner::go(fmt, self)
}sty_debug_print!(
2100 fmt,
2101 self,
2102 Adt,
2103 Array,
2104 Slice,
2105 RawPtr,
2106 Ref,
2107 FnDef,
2108 FnPtr,
2109 UnsafeBinder,
2110 Placeholder,
2111 Coroutine,
2112 CoroutineWitness,
2113 Dynamic,
2114 Closure,
2115 CoroutineClosure,
2116 Tuple,
2117 View,
2118 Bound,
2119 Param,
2120 Infer,
2121 Alias,
2122 Pat,
2123 Foreign
2124 )?;
2125
2126 fmt.write_fmt(format_args!("GenericArgs interner: #{0}\n",
self.interners.args.len()))writeln!(fmt, "GenericArgs interner: #{}", self.interners.args.len())?;
2127 fmt.write_fmt(format_args!("Region interner: #{0}\n",
self.interners.region.len()))writeln!(fmt, "Region interner: #{}", self.interners.region.len())?;
2128 fmt.write_fmt(format_args!("Const Allocation interner: #{0}\n",
self.interners.const_allocation.len()))writeln!(fmt, "Const Allocation interner: #{}", self.interners.const_allocation.len())?;
2129 fmt.write_fmt(format_args!("Layout interner: #{0}\n",
self.interners.layout.len()))writeln!(fmt, "Layout interner: #{}", self.interners.layout.len())?;
2130
2131 Ok(())
2132 })
2133 }
2134}
2135
2136struct InternedInSet<'tcx, T: ?Sized + PointeeSized>(&'tcx T);
2141
2142impl<'tcx, T: 'tcx + ?Sized + PointeeSized> Clone for InternedInSet<'tcx, T> {
2143 fn clone(&self) -> Self {
2144 *self
2145 }
2146}
2147
2148impl<'tcx, T: 'tcx + ?Sized + PointeeSized> Copy for InternedInSet<'tcx, T> {}
2149
2150impl<'tcx, T: 'tcx + ?Sized + PointeeSized> IntoPointer for InternedInSet<'tcx, T> {
2151 fn into_pointer(&self) -> *const () {
2152 self.0 as *const _ as *const ()
2153 }
2154}
2155
2156#[allow(rustc::usage_of_ty_tykind)]
2157impl<'tcx, T> Borrow<T> for InternedInSet<'tcx, WithCachedTypeInfo<T>> {
2158 fn borrow(&self) -> &T {
2159 &self.0.internee
2160 }
2161}
2162
2163impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, WithCachedTypeInfo<T>> {
2164 fn eq(&self, other: &InternedInSet<'tcx, WithCachedTypeInfo<T>>) -> bool {
2165 self.0.internee == other.0.internee
2168 }
2169}
2170
2171impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, WithCachedTypeInfo<T>> {}
2172
2173impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, WithCachedTypeInfo<T>> {
2174 fn hash<H: Hasher>(&self, s: &mut H) {
2175 self.0.internee.hash(s)
2177 }
2178}
2179
2180impl<'tcx, T> Borrow<[T]> for InternedInSet<'tcx, List<T>> {
2181 fn borrow(&self) -> &[T] {
2182 &self.0[..]
2183 }
2184}
2185
2186impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, List<T>> {
2187 fn eq(&self, other: &InternedInSet<'tcx, List<T>>) -> bool {
2188 self.0[..] == other.0[..]
2191 }
2192}
2193
2194impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, List<T>> {}
2195
2196impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, List<T>> {
2197 fn hash<H: Hasher>(&self, s: &mut H) {
2198 self.0[..].hash(s)
2200 }
2201}
2202
2203impl<'tcx, T> Borrow<[T]> for InternedInSet<'tcx, ListWithCachedTypeInfo<T>> {
2204 fn borrow(&self) -> &[T] {
2205 &self.0[..]
2206 }
2207}
2208
2209impl<'tcx, T: PartialEq> PartialEq for InternedInSet<'tcx, ListWithCachedTypeInfo<T>> {
2210 fn eq(&self, other: &InternedInSet<'tcx, ListWithCachedTypeInfo<T>>) -> bool {
2211 self.0[..] == other.0[..]
2214 }
2215}
2216
2217impl<'tcx, T: Eq> Eq for InternedInSet<'tcx, ListWithCachedTypeInfo<T>> {}
2218
2219impl<'tcx, T: Hash> Hash for InternedInSet<'tcx, ListWithCachedTypeInfo<T>> {
2220 fn hash<H: Hasher>(&self, s: &mut H) {
2221 self.0[..].hash(s)
2223 }
2224}
2225
2226macro_rules! direct_interners {
2227 ($($name:ident: $vis:vis $method:ident($ty:ty): $ret_ctor:ident -> $ret_ty:ty,)+) => {
2228 $(impl<'tcx> Borrow<$ty> for InternedInSet<'tcx, $ty> {
2229 fn borrow<'a>(&'a self) -> &'a $ty {
2230 &self.0
2231 }
2232 }
2233
2234 impl<'tcx> PartialEq for InternedInSet<'tcx, $ty> {
2235 fn eq(&self, other: &Self) -> bool {
2236 self.0 == other.0
2239 }
2240 }
2241
2242 impl<'tcx> Eq for InternedInSet<'tcx, $ty> {}
2243
2244 impl<'tcx> Hash for InternedInSet<'tcx, $ty> {
2245 fn hash<H: Hasher>(&self, s: &mut H) {
2246 self.0.hash(s)
2249 }
2250 }
2251
2252 impl<'tcx> TyCtxt<'tcx> {
2253 $vis fn $method(self, v: $ty) -> $ret_ty {
2254 $ret_ctor(Interned::new_unchecked(self.interners.$name.intern(v, |v| {
2255 InternedInSet(self.interners.arena.alloc(v))
2256 }).0))
2257 }
2258 })+
2259 }
2260}
2261
2262impl<'tcx> Borrow<RegionKind<'tcx>> for InternedInSet<'tcx, RegionKind<'tcx>>
{
fn borrow<'a>(&'a self) -> &'a RegionKind<'tcx> { &self.0 }
}
impl<'tcx> PartialEq for InternedInSet<'tcx, RegionKind<'tcx>> {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, RegionKind<'tcx>> {}
impl<'tcx> Hash for InternedInSet<'tcx, RegionKind<'tcx>> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub(crate) fn intern_region(self, v: RegionKind<'tcx>) -> Region<'tcx> {
Region(Interned::new_unchecked(self.interners.region.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<ValTreeKind<TyCtxt<'tcx>>> for
InternedInSet<'tcx, ValTreeKind<TyCtxt<'tcx>>> {
fn borrow<'a>(&'a self) -> &'a ValTreeKind<TyCtxt<'tcx>> { &self.0 }
}
impl<'tcx> PartialEq for InternedInSet<'tcx, ValTreeKind<TyCtxt<'tcx>>> {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, ValTreeKind<TyCtxt<'tcx>>> {}
impl<'tcx> Hash for InternedInSet<'tcx, ValTreeKind<TyCtxt<'tcx>>> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub(crate) fn intern_valtree(self, v: ValTreeKind<TyCtxt<'tcx>>)
-> ValTree<'tcx> {
ValTree(Interned::new_unchecked(self.interners.valtree.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<PatternKind<'tcx>> for
InternedInSet<'tcx, PatternKind<'tcx>> {
fn borrow<'a>(&'a self) -> &'a PatternKind<'tcx> { &self.0 }
}
impl<'tcx> PartialEq for InternedInSet<'tcx, PatternKind<'tcx>> {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, PatternKind<'tcx>> {}
impl<'tcx> Hash for InternedInSet<'tcx, PatternKind<'tcx>> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub fn mk_pat(self, v: PatternKind<'tcx>) -> Pattern<'tcx> {
Pattern(Interned::new_unchecked(self.interners.pat.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<Allocation> for InternedInSet<'tcx, Allocation> {
fn borrow<'a>(&'a self) -> &'a Allocation { &self.0 }
}
impl<'tcx> PartialEq for InternedInSet<'tcx, Allocation> {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, Allocation> {}
impl<'tcx> Hash for InternedInSet<'tcx, Allocation> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub fn mk_const_alloc(self, v: Allocation) -> ConstAllocation<'tcx> {
ConstAllocation(Interned::new_unchecked(self.interners.const_allocation.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<LayoutData<FieldIdx, VariantIdx>> for
InternedInSet<'tcx, LayoutData<FieldIdx, VariantIdx>> {
fn borrow<'a>(&'a self) -> &'a LayoutData<FieldIdx, VariantIdx> {
&self.0
}
}
impl<'tcx> PartialEq for InternedInSet<'tcx, LayoutData<FieldIdx, VariantIdx>>
{
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, LayoutData<FieldIdx, VariantIdx>> {}
impl<'tcx> Hash for InternedInSet<'tcx, LayoutData<FieldIdx, VariantIdx>> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub fn mk_layout(self, v: LayoutData<FieldIdx, VariantIdx>)
-> Layout<'tcx> {
Layout(Interned::new_unchecked(self.interners.layout.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<AdtDefData> for InternedInSet<'tcx, AdtDefData> {
fn borrow<'a>(&'a self) -> &'a AdtDefData { &self.0 }
}
impl<'tcx> PartialEq for InternedInSet<'tcx, AdtDefData> {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, AdtDefData> {}
impl<'tcx> Hash for InternedInSet<'tcx, AdtDefData> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub fn mk_adt_def_from_data(self, v: AdtDefData) -> AdtDef<'tcx> {
AdtDef(Interned::new_unchecked(self.interners.adt_def.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<ExternalConstraintsData<TyCtxt<'tcx>>> for
InternedInSet<'tcx, ExternalConstraintsData<TyCtxt<'tcx>>> {
fn borrow<'a>(&'a self) -> &'a ExternalConstraintsData<TyCtxt<'tcx>> {
&self.0
}
}
impl<'tcx> PartialEq for
InternedInSet<'tcx, ExternalConstraintsData<TyCtxt<'tcx>>> {
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, ExternalConstraintsData<TyCtxt<'tcx>>>
{}
impl<'tcx> Hash for InternedInSet<'tcx, ExternalConstraintsData<TyCtxt<'tcx>>>
{
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
pub fn mk_external_constraints(self,
v: ExternalConstraintsData<TyCtxt<'tcx>>)
-> ExternalConstraints<'tcx> {
ExternalConstraints(Interned::new_unchecked(self.interners.external_constraints.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}
impl<'tcx> Borrow<CanonicalInputData<TyCtxt<'tcx>>> for
InternedInSet<'tcx, CanonicalInputData<TyCtxt<'tcx>>> {
fn borrow<'a>(&'a self) -> &'a CanonicalInputData<TyCtxt<'tcx>> {
&self.0
}
}
impl<'tcx> PartialEq for InternedInSet<'tcx, CanonicalInputData<TyCtxt<'tcx>>>
{
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
impl<'tcx> Eq for InternedInSet<'tcx, CanonicalInputData<TyCtxt<'tcx>>> {}
impl<'tcx> Hash for InternedInSet<'tcx, CanonicalInputData<TyCtxt<'tcx>>> {
fn hash<H: Hasher>(&self, s: &mut H) { self.0.hash(s) }
}
impl<'tcx> TyCtxt<'tcx> {
fn intern_canonical_input(self, v: CanonicalInputData<TyCtxt<'tcx>>)
-> CanonicalInput<'tcx> {
CanonicalInput(Interned::new_unchecked(self.interners.canonical_inputs.intern(v,
|v| { InternedInSet(self.interners.arena.alloc(v)) }).0))
}
}direct_interners! {
2266 region: pub(crate) intern_region(RegionKind<'tcx>): Region -> Region<'tcx>,
2267 valtree: pub(crate) intern_valtree(ValTreeKind<TyCtxt<'tcx>>): ValTree -> ValTree<'tcx>,
2268 pat: pub mk_pat(PatternKind<'tcx>): Pattern -> Pattern<'tcx>,
2269 const_allocation: pub mk_const_alloc(Allocation): ConstAllocation -> ConstAllocation<'tcx>,
2270 layout: pub mk_layout(LayoutData<FieldIdx, VariantIdx>): Layout -> Layout<'tcx>,
2271 adt_def: pub mk_adt_def_from_data(AdtDefData): AdtDef -> AdtDef<'tcx>,
2272 external_constraints: pub mk_external_constraints(ExternalConstraintsData<TyCtxt<'tcx>>):
2273 ExternalConstraints -> ExternalConstraints<'tcx>,
2274 canonical_inputs: intern_canonical_input(CanonicalInputData<TyCtxt<'tcx>>): CanonicalInput -> CanonicalInput<'tcx>,
2275}
2276
2277macro_rules! slice_interners {
2278 ($($field:ident: $vis:vis $method:ident($ty:ty)),+ $(,)?) => (
2279 impl<'tcx> TyCtxt<'tcx> {
2280 $($vis fn $method(self, v: &[$ty]) -> &'tcx List<$ty> {
2281 if v.is_empty() {
2282 List::empty()
2283 } else {
2284 self.interners.$field.intern_ref(v, || {
2285 InternedInSet(List::from_arena(&*self.arena, (), v))
2286 }).0
2287 }
2288 })+
2289 }
2290 );
2291}
2292
2293impl<'tcx> TyCtxt<'tcx> {
pub fn mk_const_list(self, v: &[Const<'tcx>]) -> &'tcx List<Const<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.const_lists.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_args_raw(self, v: &[GenericArg<'tcx>])
-> &'tcx List<GenericArg<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.args.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_type_list(self, v: &[Ty<'tcx>]) -> &'tcx List<Ty<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.type_lists.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_canonical_var_kinds(self, v: &[CanonicalVarKind<'tcx>])
-> &'tcx List<CanonicalVarKind<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.canonical_var_kinds.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
fn intern_poly_existential_predicates(self,
v: &[PolyExistentialPredicate<'tcx>])
-> &'tcx List<PolyExistentialPredicate<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.poly_existential_predicates.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_projs(self, v: &[ProjectionKind])
-> &'tcx List<ProjectionKind> {
if v.is_empty() {
List::empty()
} else {
self.interners.projs.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_place_elems(self, v: &[PlaceElem<'tcx>])
-> &'tcx List<PlaceElem<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.place_elems.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_bound_variable_kinds(self, v: &[ty::BoundVariableKind<'tcx>])
-> &'tcx List<ty::BoundVariableKind<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.bound_variable_kinds.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_fields(self, v: &[FieldIdx]) -> &'tcx List<FieldIdx> {
if v.is_empty() {
List::empty()
} else {
self.interners.fields.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
fn intern_local_def_ids(self, v: &[LocalDefId])
-> &'tcx List<LocalDefId> {
if v.is_empty() {
List::empty()
} else {
self.interners.local_def_ids.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
fn intern_captures(self, v: &[&'tcx ty::CapturedPlace<'tcx>])
-> &'tcx List<&'tcx ty::CapturedPlace<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.captures.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_patterns(self, v: &[Pattern<'tcx>])
-> &'tcx List<Pattern<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.patterns.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_outlives(self, v: &[ty::ArgOutlivesClause<'tcx>])
-> &'tcx List<ty::ArgOutlivesClause<'tcx>> {
if v.is_empty() {
List::empty()
} else {
self.interners.outlives.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
pub fn mk_predefined_opaques_in_body(self,
v: &[(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)])
-> &'tcx List<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)> {
if v.is_empty() {
List::empty()
} else {
self.interners.predefined_opaques_in_body.intern_ref(v,
||
{ InternedInSet(List::from_arena(&*self.arena, (), v)) }).0
}
}
}slice_interners!(
2297 const_lists: pub mk_const_list(Const<'tcx>),
2298 args: pub mk_args_raw(GenericArg<'tcx>),
2299 type_lists: pub mk_type_list(Ty<'tcx>),
2300 canonical_var_kinds: pub mk_canonical_var_kinds(CanonicalVarKind<'tcx>),
2301 poly_existential_predicates: intern_poly_existential_predicates(PolyExistentialPredicate<'tcx>),
2302 projs: pub mk_projs(ProjectionKind),
2303 place_elems: pub mk_place_elems(PlaceElem<'tcx>),
2304 bound_variable_kinds: pub mk_bound_variable_kinds(ty::BoundVariableKind<'tcx>),
2305 fields: pub mk_fields(FieldIdx),
2306 local_def_ids: intern_local_def_ids(LocalDefId),
2307 captures: intern_captures(&'tcx ty::CapturedPlace<'tcx>),
2308 patterns: pub mk_patterns(Pattern<'tcx>),
2309 outlives: pub mk_outlives(ty::ArgOutlivesClause<'tcx>),
2310 predefined_opaques_in_body: pub mk_predefined_opaques_in_body((ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)),
2311);
2312
2313impl<'tcx> TyCtxt<'tcx> {
2314 pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2318 if !sig.safety().is_safe() {
::core::panicking::panic("assertion failed: sig.safety().is_safe()")
};assert!(sig.safety().is_safe());
2319 Ty::new_fn_ptr(
2320 self,
2321 sig.map_bound(|sig| ty::FnSig {
2322 fn_sig_kind: sig.fn_sig_kind.set_safety(hir::Safety::Unsafe),
2323 ..sig
2324 }),
2325 )
2326 }
2327
2328 pub fn safe_to_unsafe_sig(self, sig: PolyFnSig<'tcx>) -> PolyFnSig<'tcx> {
2332 if !sig.safety().is_safe() {
::core::panicking::panic("assertion failed: sig.safety().is_safe()")
};assert!(sig.safety().is_safe());
2333 sig.map_bound(|sig| ty::FnSig {
2334 fn_sig_kind: sig.fn_sig_kind.set_safety(hir::Safety::Unsafe),
2335 ..sig
2336 })
2337 }
2338
2339 pub fn trait_may_define_assoc_item(self, trait_def_id: DefId, assoc_name: Ident) -> bool {
2342 elaborate::supertrait_def_ids(self, trait_def_id).any(|trait_did| {
2343 self.associated_items(trait_did)
2344 .filter_by_name_unhygienic(assoc_name.name)
2345 .any(|item| self.hygienic_eq(assoc_name, item.ident(self), trait_did))
2346 })
2347 }
2348
2349 pub fn ty_is_opaque_future(self, ty: Ty<'_>) -> bool {
2351 let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *ty.kind() else {
2352 return false;
2353 };
2354 let future_trait = self.require_lang_item(LangItem::Future, DUMMY_SP);
2355
2356 self.explicit_item_self_bounds(def_id).skip_binder().iter().any(|&(predicate, _)| {
2357 let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() else {
2358 return false;
2359 };
2360 trait_predicate.trait_ref.def_id == future_trait
2361 && trait_predicate.polarity == ClausePolarity::Positive
2362 })
2363 }
2364
2365 pub fn signature_unclosure(self, sig: PolyFnSig<'tcx>, safety: hir::Safety) -> PolyFnSig<'tcx> {
2373 sig.map_bound(|s| {
2374 let params = match s.inputs()[0].kind() {
2375 ty::Tuple(params) => *params,
2376 _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
2377 };
2378 if !s.splatted().is_none() {
::core::panicking::panic("assertion failed: s.splatted().is_none()")
};assert!(s.splatted().is_none());
2380 self.mk_fn_sig(
2381 params,
2382 s.output(),
2383 s.fn_sig_kind.set_safety(safety).set_abi(ExternAbi::Rust),
2384 )
2385 })
2386 }
2387
2388 #[inline]
2389 pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> {
2390 self.interners.intern_predicate(binder)
2391 }
2392
2393 #[inline]
2394 pub fn reuse_or_mk_predicate(
2395 self,
2396 pred: Predicate<'tcx>,
2397 binder: Binder<'tcx, PredicateKind<'tcx>>,
2398 ) -> Predicate<'tcx> {
2399 if pred.kind() != binder { self.mk_predicate(binder) } else { pred }
2400 }
2401
2402 pub fn check_args_compatible(self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> bool {
2408 let is_inherent_assoc_ty = #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::AssocTy => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::AssocTy)
2409 && #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(self.parent(def_id))
{
DefKind::Impl { of_trait: false } => true,
_ => false,
}matches!(self.def_kind(self.parent(def_id)), DefKind::Impl { of_trait: false });
2410 self.check_args_compatible_inner(def_id, args.as_slice(), is_inherent_assoc_ty)
2411 }
2412
2413 pub fn check_alias_term_args_compatible(
2414 self,
2415 kind: ty::AliasTermKind<'tcx>,
2416 args: ty::GenericArgs<'tcx>,
2417 ) -> bool {
2418 let (def_id, is_self_args) = match kind {
2419 ty::AliasTermKind::ProjectionTy { def_id }
2420 | ty::AliasTermKind::OpaqueTy { def_id }
2421 | ty::AliasTermKind::FreeTy { def_id }
2422 | ty::AliasTermKind::AnonConst { def_id }
2423 | ty::AliasTermKind::ProjectionConst { def_id }
2424 | ty::AliasTermKind::FreeConst { def_id }
2425 | ty::AliasTermKind::InherentConstImpl { def_id } => (def_id, false),
2426 ty::AliasTermKind::InherentTy { def_id }
2427 | ty::AliasTermKind::InherentConstSelf { def_id } => (def_id, true),
2428 };
2429 self.check_args_compatible_inner(def_id, args.as_slice(), is_self_args)
2430 }
2431
2432 fn check_args_compatible_inner(
2433 self,
2434 def_id: DefId,
2435 args: &[ty::GenericArg<'tcx>],
2436 is_self_args: bool,
2437 ) -> bool {
2438 let generics = self.generics_of(def_id);
2439 let own_args = if is_self_args {
2440 if generics.own_params.len() + 1 != args.len() {
2441 return false;
2442 }
2443
2444 if !#[allow(non_exhaustive_omitted_patterns)] match args[0].kind() {
ty::GenericArgKind::Type(_) => true,
_ => false,
}matches!(args[0].kind(), ty::GenericArgKind::Type(_)) {
2445 return false;
2446 }
2447
2448 &args[1..]
2449 } else {
2450 if generics.count() != args.len() {
2451 return false;
2452 }
2453
2454 let (parent_args, own_args) = args.split_at(generics.parent_count);
2455
2456 if let Some(parent) = generics.parent
2460 && !self.check_args_compatible_inner(parent, parent_args, false)
2461 {
2462 return false;
2463 }
2464
2465 own_args
2466 };
2467
2468 for (param, arg) in std::iter::zip(&generics.own_params, own_args) {
2469 match (¶m.kind, arg.kind()) {
2470 (ty::GenericParamDefKind::Type { .. }, ty::GenericArgKind::Type(_))
2471 | (ty::GenericParamDefKind::Lifetime, ty::GenericArgKind::Lifetime(_))
2472 | (ty::GenericParamDefKind::Const { .. }, ty::GenericArgKind::Const(_)) => {}
2473 _ => return false,
2474 }
2475 }
2476
2477 true
2478 }
2479
2480 pub fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgs<'tcx>) {
2487 if truecfg!(debug_assertions) && !self.check_args_compatible(def_id, args) {
2488 let is_inherent_assoc_ty = #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::AssocTy => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::AssocTy)
2489 && #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(self.parent(def_id))
{
DefKind::Impl { of_trait: false } => true,
_ => false,
}matches!(self.def_kind(self.parent(def_id)), DefKind::Impl { of_trait: false });
2490 self.emit_bug_args_compatible(def_id, args, is_inherent_assoc_ty);
2491 }
2492 }
2493
2494 pub fn debug_assert_alias_term_args_compatible(
2495 self,
2496 kind: ty::AliasTermKind<'tcx>,
2497 args: ty::GenericArgs<'tcx>,
2498 ) {
2499 if truecfg!(debug_assertions) {
2500 self.debug_assert_alias_term_kind_matches_def_kind(kind);
2501 if !self.check_alias_term_args_compatible(kind, args) {
2502 let (def_id, is_self_args) = match kind {
2503 ty::AliasTermKind::ProjectionTy { def_id }
2504 | ty::AliasTermKind::OpaqueTy { def_id }
2505 | ty::AliasTermKind::FreeTy { def_id }
2506 | ty::AliasTermKind::AnonConst { def_id }
2507 | ty::AliasTermKind::ProjectionConst { def_id }
2508 | ty::AliasTermKind::FreeConst { def_id }
2509 | ty::AliasTermKind::InherentConstImpl { def_id } => (def_id, false),
2510 ty::AliasTermKind::InherentTy { def_id }
2511 | ty::AliasTermKind::InherentConstSelf { def_id } => (def_id, true),
2512 };
2513 self.emit_bug_args_compatible(def_id, args, is_self_args);
2514 }
2515 }
2516 }
2517
2518 fn debug_assert_alias_term_kind_matches_def_kind(self, kind: ty::AliasTermKind<'tcx>) {
2519 match kind {
2520 ty::AliasTermKind::ProjectionTy { def_id } => {
2521 if true {
{
match self.def_kind(def_id) {
DefKind::AssocTy => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocTy", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy);
2522 if true {
{
match self.def_kind(self.parent(def_id)) {
DefKind::Trait | DefKind::Impl { of_trait: true } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Trait | DefKind::Impl { of_trait: true }",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
2523 self.def_kind(self.parent(def_id)),
2524 DefKind::Trait | DefKind::Impl { of_trait: true }
2525 );
2526 }
2527 ty::AliasTermKind::InherentTy { def_id } => {
2528 if true {
{
match self.def_kind(def_id) {
DefKind::AssocTy => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocTy", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy);
2529 if true {
{
match self.def_kind(self.parent(def_id)) {
DefKind::Impl { of_trait: false } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Impl { of_trait: false }",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
2530 self.def_kind(self.parent(def_id)),
2531 DefKind::Impl { of_trait: false }
2532 );
2533 }
2534 ty::AliasTermKind::OpaqueTy { def_id } => {
2535 if true {
{
match self.def_kind(def_id) {
DefKind::OpaqueTy => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::OpaqueTy", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::OpaqueTy);
2536 }
2537 ty::AliasTermKind::FreeTy { def_id } => {
2538 if true {
{
match self.def_kind(def_id) {
DefKind::TyAlias => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::TyAlias", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::TyAlias);
2539 }
2540 ty::AliasTermKind::AnonConst { def_id } => {
2541 if true {
{
match self.def_kind(def_id) {
DefKind::AnonConst => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AnonConst", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::AnonConst);
2542 }
2543 ty::AliasTermKind::ProjectionConst { def_id } => {
2544 if true {
{
match self.def_kind(def_id) {
DefKind::AssocConst => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocConst", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::AssocConst);
2545 if true {
{
match self.def_kind(self.parent(def_id)) {
DefKind::Trait | DefKind::Impl { of_trait: true } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Trait | DefKind::Impl { of_trait: true }",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
2546 self.def_kind(self.parent(def_id)),
2547 DefKind::Trait | DefKind::Impl { of_trait: true }
2548 );
2549 }
2550 ty::AliasTermKind::InherentConstSelf { def_id }
2551 | ty::AliasTermKind::InherentConstImpl { def_id } => {
2552 if true {
{
match self.def_kind(def_id) {
DefKind::AssocConst => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AssocConst", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::AssocConst);
2553 if true {
{
match self.def_kind(self.parent(def_id)) {
DefKind::Impl { of_trait: false } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Impl { of_trait: false }",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
2554 self.def_kind(self.parent(def_id)),
2555 DefKind::Impl { of_trait: false }
2556 );
2557 }
2558 ty::AliasTermKind::FreeConst { def_id } => {
2559 if true {
{
match self.def_kind(def_id) {
DefKind::Const => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Const", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.def_kind(def_id), DefKind::Const);
2560 }
2561 }
2562 }
2563
2564 pub(crate) fn debug_assert_adt_def_kind_compatible(self, def: AdtDef<'tcx>) {
2565 if truecfg!(debug_assertions) {
2566 match self.def_kind(def.did()) {
2567 DefKind::Struct | DefKind::Union | DefKind::Enum => {}
2568 DefKind::Mod
2569 | DefKind::Variant
2570 | DefKind::Trait
2571 | DefKind::TyAlias
2572 | DefKind::ForeignTy
2573 | DefKind::TraitAlias
2574 | DefKind::AssocTy
2575 | DefKind::TyParam
2576 | DefKind::Fn
2577 | DefKind::Const
2578 | DefKind::ConstParam
2579 | DefKind::Static { .. }
2580 | DefKind::Ctor(..)
2581 | DefKind::AssocFn
2582 | DefKind::AssocConst
2583 | DefKind::Macro(..)
2584 | DefKind::ExternCrate
2585 | DefKind::Use
2586 | DefKind::ForeignMod
2587 | DefKind::AnonConst
2588 | DefKind::OpaqueTy
2589 | DefKind::Field
2590 | DefKind::LifetimeParam
2591 | DefKind::GlobalAsm
2592 | DefKind::Impl { .. }
2593 | DefKind::Closure
2594 | DefKind::SyntheticCoroutineBody
2595 | DefKind::TestBinderConstraints => {
2596 ::rustc_span::macros::bug_impl(None,
format_args!("not an adt: {1:?} ({0:?})", self.def_kind(def.did()), def),
Location::caller())bug!("not an adt: {def:?} ({:?})", self.def_kind(def.did()))
2597 }
2598 }
2599 }
2600 }
2601
2602 pub fn debug_assert_encoded_viewed_fields_compatible(
2605 self,
2606 base_def: AdtDef<'tcx>,
2607 base_args: ty::GenericArgs<'tcx>,
2608 fields: Ty<'tcx>,
2609 ) {
2610 if truecfg!(debug_assertions) {
2611 let base_ty = Ty::new_adt(self, base_def, base_args);
2612
2613 let ty::Tuple(fields) = fields.kind() else {
2614 ::rustc_span::macros::bug_impl(None,
format_args!("incompatible encoded viewed fields type: {0:?}", fields),
Location::caller());bug!("incompatible encoded viewed fields type: {fields:?}");
2615 };
2616
2617 for field in *fields {
2618 let frt_args = match field.kind() {
2619 ty::Adt(def, args)
2620 if def.flags().contains(ty::AdtFlags::IS_FIELD_REPRESENTING_TYPE) =>
2621 {
2622 args
2623 }
2624 _ => ::rustc_span::macros::bug_impl(None,
format_args!("malformed encoded viewed field type: {0:?}", field),
Location::caller())bug!("malformed encoded viewed field type: {field:?}"),
2625 };
2626
2627 let referred_ty = frt_args[0].as_type().expect("first FRT arg is type");
2628
2629 {
match (&referred_ty, &base_ty) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("viewed field ({0:?}) does not refer to the base type ({1:?})",
referred_ty, base_ty)));
}
}
}
};assert_eq!(
2630 referred_ty, base_ty,
2631 "viewed field ({referred_ty:?}) does not refer to the base type ({base_ty:?})"
2632 );
2633 }
2634 }
2635 }
2636
2637 fn emit_bug_args_compatible(
2638 self,
2639 def_id: DefId,
2640 args: ty::GenericArgs<'tcx>,
2641 is_self_args: bool,
2642 ) -> ! {
2643 if is_self_args {
2644 ::rustc_span::macros::bug_impl(None,
format_args!("args not compatible with generics for {0}: args={1:#?}, generics={2:#?}",
self.def_path_str(def_id), args,
self.mk_args_from_iter([self.types.self_param.into()].into_iter().chain(self.generics_of(def_id).own_args(ty::GenericArgs::identity_for_item(self,
def_id).as_slice()).iter().copied()))), Location::caller());bug!(
2645 "args not compatible with generics for {}: args={:#?}, generics={:#?}",
2646 self.def_path_str(def_id),
2647 args,
2648 self.mk_args_from_iter(
2650 [self.types.self_param.into()].into_iter().chain(
2651 self.generics_of(def_id)
2652 .own_args(ty::GenericArgs::identity_for_item(self, def_id).as_slice())
2653 .iter()
2654 .copied()
2655 )
2656 )
2657 );
2658 } else {
2659 ::rustc_span::macros::bug_impl(None,
format_args!("args not compatible with generics for {0}: args={1:#?}, generics={2:#?}",
self.def_path_str(def_id), args,
ty::GenericArgs::identity_for_item(self, def_id)),
Location::caller());bug!(
2660 "args not compatible with generics for {}: args={:#?}, generics={:#?}",
2661 self.def_path_str(def_id),
2662 args,
2663 ty::GenericArgs::identity_for_item(self, def_id)
2664 );
2665 }
2666 }
2667
2668 #[inline(always)]
2669 pub(crate) fn check_and_mk_args(
2670 self,
2671 def_id: DefId,
2672 args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
2673 ) -> ty::GenericArgs<'tcx> {
2674 let args = self.mk_args_from_iter(args.into_iter().map(Into::into));
2675 self.debug_assert_args_compatible(def_id, args);
2676 args
2677 }
2678
2679 #[inline]
2680 pub fn mk_ct_from_kind(self, kind: ty::ConstKind<'tcx>) -> Const<'tcx> {
2681 self.interners.intern_const(kind)
2682 }
2683
2684 #[allow(rustc::usage_of_ty_tykind)]
2688 #[inline]
2689 pub fn mk_ty_from_kind(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2690 match st {
2691 ty::Bool => self.interners.intern_with_empty_flags(ty::Bool),
2692 ty::Char => self.interners.intern_with_empty_flags(ty::Char),
2693 ty::Int(int) => self.interners.intern_with_empty_flags(ty::Int(int)),
2694 ty::Uint(uint) => self.interners.intern_with_empty_flags(ty::Uint(uint)),
2695 ty::Float(float) => self.interners.intern_with_empty_flags(ty::Float(float)),
2696 ty::Adt(def, args) => self.interners.intern_adt(def, args),
2697 ty::Foreign(def_id) => self.interners.intern_foreign(def_id),
2698 ty::Str => self.interners.intern_with_empty_flags(ty::Str),
2699 ty::Array(element, len) => self.interners.intern_array(element, len),
2700 ty::Pat(base, pat) => self.interners.intern_pat(base, pat),
2701 ty::Slice(element) => self.interners.intern_slice(element),
2702 ty::RawPtr(pointee, mutability) => self.interners.intern_raw_ptr(pointee, mutability),
2703 ty::Ref(region, pointee, mutability) => {
2704 self.interners.intern_ref(region, pointee, mutability)
2705 }
2706 ty::FnDef(def_id, args) => self.interners.intern_fn_def(def_id, args),
2707 ty::FnPtr(sig_tys, header) => self.interners.intern_fn_ptr(sig_tys, header),
2708 ty::UnsafeBinder(bound_ty) => self.interners.intern_unsafe_binder(bound_ty),
2709 ty::Dynamic(predicates, region) => self.interners.intern_dynamic(predicates, region),
2710 ty::Closure(def_id, args) => self.interners.intern_closure(def_id, args),
2711 ty::CoroutineClosure(def_id, args) => {
2712 self.interners.intern_coroutine_closure(def_id, args)
2713 }
2714 ty::Coroutine(def_id, args) => self.interners.intern_coroutine(def_id, args),
2715 ty::CoroutineWitness(def_id, args) => {
2716 self.interners.intern_coroutine_witness(def_id, args)
2717 }
2718 ty::Never => self.interners.intern_with_empty_flags(ty::Never),
2719 ty::Tuple(types) => self.interners.intern_tuple(types),
2720 ty::Alias(is_rigid, alias) => self.interners.intern_alias(is_rigid, alias),
2721 ty::Param(param) => self.interners.intern_param(param),
2722 ty::Bound(index, bound_ty) => self.interners.intern_bound(index, bound_ty),
2723 ty::Placeholder(placeholder) => self.interners.intern_placeholder(placeholder),
2724 ty::Infer(infer) => self.interners.intern_infer(infer),
2725 ty::Error(error) => self.interners.intern_error(error),
2726 ty::View(def, args, fields) => self.interners.intern_view(def, args, fields),
2727 }
2728 }
2729
2730 pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
2731 match param.kind {
2732 GenericParamDefKind::Lifetime => {
2733 ty::Region::new_early_param(self, param.to_early_bound_region_data()).into()
2734 }
2735 GenericParamDefKind::Type { .. } => Ty::new_param(self, param.index, param.name).into(),
2736 GenericParamDefKind::Const { .. } => {
2737 ty::Const::new_param(self, ParamConst { index: param.index, name: param.name })
2738 .into()
2739 }
2740 }
2741 }
2742
2743 pub fn mk_place_field(self, place: Place<'tcx>, f: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
2744 self.mk_place_elem(place, PlaceElem::Field(f, ty))
2745 }
2746
2747 pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> {
2748 self.mk_place_elem(place, PlaceElem::Deref)
2749 }
2750
2751 pub fn mk_place_downcast(
2752 self,
2753 place: Place<'tcx>,
2754 adt_def: AdtDef<'tcx>,
2755 variant_index: VariantIdx,
2756 ) -> Place<'tcx> {
2757 self.mk_place_elem(
2758 place,
2759 PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index),
2760 )
2761 }
2762
2763 pub fn mk_place_downcast_unnamed(
2764 self,
2765 place: Place<'tcx>,
2766 variant_index: VariantIdx,
2767 ) -> Place<'tcx> {
2768 self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index))
2769 }
2770
2771 pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> {
2772 self.mk_place_elem(place, PlaceElem::Index(index))
2773 }
2774
2775 pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> {
2779 Place {
2780 local: place.local,
2781 projection: self.mk_place_elems_from_iter(place.projection.iter().chain([elem])),
2782 }
2783 }
2784
2785 pub fn mk_poly_existential_predicates(
2786 self,
2787 eps: &[PolyExistentialPredicate<'tcx>],
2788 ) -> &'tcx List<PolyExistentialPredicate<'tcx>> {
2789 if !!eps.is_empty() {
::core::panicking::panic("assertion failed: !eps.is_empty()")
};assert!(!eps.is_empty());
2790 if !eps.array_windows().all(|[a, b]|
a.skip_binder().stable_cmp(self, &b.skip_binder()) !=
Ordering::Greater) {
::core::panicking::panic("assertion failed: eps.array_windows().all(|[a, b]|\n a.skip_binder().stable_cmp(self, &b.skip_binder()) !=\n Ordering::Greater)")
};assert!(
2791 eps.array_windows()
2792 .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder())
2793 != Ordering::Greater)
2794 );
2795 self.intern_poly_existential_predicates(eps)
2796 }
2797
2798 pub fn mk_clauses(self, clauses: &[Clause<'tcx>]) -> Clauses<'tcx> {
2799 self.interners.intern_clauses(clauses)
2803 }
2804
2805 pub fn mk_local_def_ids(self, def_ids: &[LocalDefId]) -> &'tcx List<LocalDefId> {
2806 self.intern_local_def_ids(def_ids)
2810 }
2811
2812 pub fn mk_patterns_from_iter<I, T>(self, iter: I) -> T::Output
2813 where
2814 I: Iterator<Item = T>,
2815 T: CollectAndApply<ty::Pattern<'tcx>, &'tcx List<ty::Pattern<'tcx>>>,
2816 {
2817 T::collect_and_apply(iter, |xs| self.mk_patterns(xs))
2818 }
2819
2820 pub fn mk_local_def_ids_from_iter<I, T>(self, iter: I) -> T::Output
2821 where
2822 I: Iterator<Item = T>,
2823 T: CollectAndApply<LocalDefId, &'tcx List<LocalDefId>>,
2824 {
2825 T::collect_and_apply(iter, |xs| self.mk_local_def_ids(xs))
2826 }
2827
2828 pub fn mk_captures_from_iter<I, T>(self, iter: I) -> T::Output
2829 where
2830 I: Iterator<Item = T>,
2831 T: CollectAndApply<
2832 &'tcx ty::CapturedPlace<'tcx>,
2833 &'tcx List<&'tcx ty::CapturedPlace<'tcx>>,
2834 >,
2835 {
2836 T::collect_and_apply(iter, |xs| self.intern_captures(xs))
2837 }
2838
2839 pub fn mk_const_list_from_iter<I, T>(self, iter: I) -> T::Output
2840 where
2841 I: Iterator<Item = T>,
2842 T: CollectAndApply<ty::Const<'tcx>, &'tcx List<ty::Const<'tcx>>>,
2843 {
2844 T::collect_and_apply(iter, |xs| self.mk_const_list(xs))
2845 }
2846
2847 pub fn mk_fn_sig<I, T>(
2852 self,
2853 inputs: I,
2854 output: I::Item,
2855 fn_sig_kind: FnSigKind<'tcx>,
2856 ) -> T::Output
2857 where
2858 I: IntoIterator<Item = T>,
2859 T: CollectAndApply<Ty<'tcx>, ty::FnSig<'tcx>>,
2860 {
2861 T::collect_and_apply(inputs.into_iter().chain(iter::once(output)), |xs| ty::FnSig {
2862 inputs_and_output: self.mk_type_list(xs),
2863 fn_sig_kind,
2864 })
2865 }
2866
2867 pub fn mk_fn_sig_rust_abi<I, T>(
2869 self,
2870 inputs: I,
2871 output: I::Item,
2872 safety: hir::Safety,
2873 ) -> T::Output
2874 where
2875 I: IntoIterator<Item = T>,
2876 T: CollectAndApply<Ty<'tcx>, ty::FnSig<'tcx>>,
2877 {
2878 self.mk_fn_sig(inputs, output, FnSigKind::default().set_safety(safety))
2879 }
2880
2881 pub fn mk_fn_sig_safe_rust_abi<I, T>(self, inputs: I, output: I::Item) -> T::Output
2883 where
2884 I: IntoIterator<Item = T>,
2885 T: CollectAndApply<Ty<'tcx>, ty::FnSig<'tcx>>,
2886 {
2887 self.mk_fn_sig(inputs, output, FnSigKind::default().set_safety(hir::Safety::Safe))
2888 }
2889
2890 pub fn mk_fn_sig_unsafe_rust_abi<I, T>(self, inputs: I, output: I::Item) -> T::Output
2892 where
2893 I: IntoIterator<Item = T>,
2894 T: CollectAndApply<Ty<'tcx>, ty::FnSig<'tcx>>,
2895 {
2896 self.mk_fn_sig(inputs, output, FnSigKind::default().set_safety(hir::Safety::Unsafe))
2897 }
2898
2899 pub fn mk_poly_existential_predicates_from_iter<I, T>(self, iter: I) -> T::Output
2900 where
2901 I: Iterator<Item = T>,
2902 T: CollectAndApply<
2903 PolyExistentialPredicate<'tcx>,
2904 &'tcx List<PolyExistentialPredicate<'tcx>>,
2905 >,
2906 {
2907 T::collect_and_apply(iter, |xs| self.mk_poly_existential_predicates(xs))
2908 }
2909
2910 pub fn mk_predefined_opaques_in_body_from_iter<I, T>(self, iter: I) -> T::Output
2911 where
2912 I: Iterator<Item = T>,
2913 T: CollectAndApply<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>), PredefinedOpaques<'tcx>>,
2914 {
2915 T::collect_and_apply(iter, |xs| self.mk_predefined_opaques_in_body(xs))
2916 }
2917
2918 pub fn mk_clauses_from_iter<I, T>(self, iter: I) -> T::Output
2919 where
2920 I: Iterator<Item = T>,
2921 T: CollectAndApply<Clause<'tcx>, Clauses<'tcx>>,
2922 {
2923 T::collect_and_apply(iter, |xs| self.mk_clauses(xs))
2924 }
2925
2926 pub fn mk_type_list_from_iter<I, T>(self, iter: I) -> T::Output
2927 where
2928 I: Iterator<Item = T>,
2929 T: CollectAndApply<Ty<'tcx>, &'tcx List<Ty<'tcx>>>,
2930 {
2931 T::collect_and_apply(iter, |xs| self.mk_type_list(xs))
2932 }
2933
2934 pub fn mk_args(self, args: &[GenericArg<'tcx>]) -> ty::GenericArgs<'tcx> {
2935 ty::GenericArgs::from_args(self.mk_args_raw(args))
2936 }
2937
2938 pub fn mk_args_from_iter<I, T>(self, iter: I) -> T::Output
2939 where
2940 I: Iterator<Item = T>,
2941 T: CollectAndApply<GenericArg<'tcx>, ty::GenericArgs<'tcx>>,
2942 {
2943 T::collect_and_apply(iter, |xs| self.mk_args(xs))
2944 }
2945
2946 pub fn mk_canonical_var_infos_from_iter<I, T>(self, iter: I) -> T::Output
2947 where
2948 I: Iterator<Item = T>,
2949 T: CollectAndApply<CanonicalVarKind<'tcx>, &'tcx List<CanonicalVarKind<'tcx>>>,
2950 {
2951 T::collect_and_apply(iter, |xs| self.mk_canonical_var_kinds(xs))
2952 }
2953
2954 pub fn mk_place_elems_from_iter<I, T>(self, iter: I) -> T::Output
2955 where
2956 I: Iterator<Item = T>,
2957 T: CollectAndApply<PlaceElem<'tcx>, &'tcx List<PlaceElem<'tcx>>>,
2958 {
2959 T::collect_and_apply(iter, |xs| self.mk_place_elems(xs))
2960 }
2961
2962 pub fn mk_fields_from_iter<I, T>(self, iter: I) -> T::Output
2963 where
2964 I: Iterator<Item = T>,
2965 T: CollectAndApply<FieldIdx, &'tcx List<FieldIdx>>,
2966 {
2967 T::collect_and_apply(iter, |xs| self.mk_fields(xs))
2968 }
2969
2970 pub fn mk_args_trait(
2971 self,
2972 self_ty: Ty<'tcx>,
2973 rest: impl IntoIterator<Item = GenericArg<'tcx>>,
2974 ) -> ty::GenericArgs<'tcx> {
2975 self.mk_args_from_iter(iter::once(self_ty.into()).chain(rest))
2976 }
2977
2978 pub fn mk_bound_variable_kinds_from_iter<I, T>(self, iter: I) -> T::Output
2979 where
2980 I: Iterator<Item = T>,
2981 T: CollectAndApply<ty::BoundVariableKind<'tcx>, &'tcx List<ty::BoundVariableKind<'tcx>>>,
2982 {
2983 T::collect_and_apply(iter, |xs| self.mk_bound_variable_kinds(xs))
2984 }
2985
2986 pub fn mk_outlives_from_iter<I, T>(self, iter: I) -> T::Output
2987 where
2988 I: Iterator<Item = T>,
2989 T: CollectAndApply<
2990 ty::ArgOutlivesClause<'tcx>,
2991 &'tcx ty::List<ty::ArgOutlivesClause<'tcx>>,
2992 >,
2993 {
2994 T::collect_and_apply(iter, |xs| self.mk_outlives(xs))
2995 }
2996
2997 #[track_caller]
3000 pub fn emit_node_span_lint(
3001 self,
3002 lint: &'static Lint,
3003 hir_id: HirId,
3004 span: impl Into<MultiSpan>,
3005 decorator: impl for<'a> Diagnostic<'a>,
3006 ) {
3007 let level_spec = self.lint_level_spec_at_node(lint, hir_id);
3008 emit_lint_base(self.sess, lint, level_spec, Some(span.into()), decorator)
3009 }
3010
3011 pub fn crate_level_attribute_injection_span(self) -> Span {
3013 let node = self.hir_node(hir::CRATE_HIR_ID);
3014 let hir::Node::Crate(m) = node else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!() };
3015 m.spans.inject_use_span.shrink_to_lo()
3016 }
3017
3018 pub fn disabled_nightly_features(
3019 self,
3020 diag: &mut Diag<'_>,
3021 features: impl IntoIterator<Item = (String, Symbol)>,
3022 ) {
3023 if !self.sess.is_nightly_build() {
3024 return;
3025 }
3026
3027 let span = self.crate_level_attribute_injection_span();
3028 for (desc, feature) in features {
3029 let msg =
3031 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#![feature({0})]` to the crate attributes to enable{1}",
feature, desc))
})format!("add `#![feature({feature})]` to the crate attributes to enable{desc}");
3032 diag.span_suggestion_verbose(
3033 span,
3034 msg,
3035 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#![feature({0})]\n", feature))
})format!("#![feature({feature})]\n"),
3036 Applicability::MaybeIncorrect,
3037 );
3038 }
3039 }
3040
3041 #[track_caller]
3044 pub fn emit_node_lint(
3045 self,
3046 lint: &'static Lint,
3047 id: HirId,
3048 decorator: impl for<'a> Diagnostic<'a>,
3049 ) {
3050 let level_spec = self.lint_level_spec_at_node(lint, id);
3051 emit_lint_base(self.sess, lint, level_spec, None, decorator);
3052 }
3053
3054 pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate<'tcx>]> {
3055 let map = self.in_scope_traits_map(id.owner)?;
3056 let candidates = map.get(&id.local_id)?;
3057 Some(candidates)
3058 }
3059
3060 pub fn named_bound_var(self, id: HirId) -> Option<resolve_bound_vars::ResolvedArg> {
3061 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs:3061",
"rustc_middle::ty::context", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_middle/src/ty/context.rs"),
::tracing_core::__macro_support::Option::Some(3061u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::context"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("id")
}> =
::tracing::__macro_support::FieldName::new("id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("named_region")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?id, "named_region");
3062 self.named_variable_map(id.owner).get(&id.local_id).cloned()
3063 }
3064
3065 pub fn is_late_bound(self, id: HirId) -> bool {
3066 self.is_late_bound_map(id.owner).is_some_and(|set| set.contains(&id.local_id))
3067 }
3068
3069 pub fn late_bound_vars(self, id: HirId) -> &'tcx List<ty::BoundVariableKind<'tcx>> {
3070 self.mk_bound_variable_kinds(
3071 &self
3072 .late_bound_vars_map(id.owner)
3073 .get(&id.local_id)
3074 .cloned()
3075 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("No bound vars found for {0}", self.hir_id_to_string(id)),
Location::caller())bug!("No bound vars found for {}", self.hir_id_to_string(id))),
3076 )
3077 }
3078
3079 pub fn map_opaque_lifetime_to_parent_lifetime(
3087 self,
3088 mut opaque_lifetime_param_def_id: LocalDefId,
3089 ) -> ty::Region<'tcx> {
3090 if true {
if !#[allow(non_exhaustive_omitted_patterns)] match self.def_kind(opaque_lifetime_param_def_id)
{
DefKind::LifetimeParam => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("{1:?} is a {0}",
self.def_descr(opaque_lifetime_param_def_id.to_def_id()),
opaque_lifetime_param_def_id));
}
};
};debug_assert!(
3091 matches!(self.def_kind(opaque_lifetime_param_def_id), DefKind::LifetimeParam),
3092 "{opaque_lifetime_param_def_id:?} is a {}",
3093 self.def_descr(opaque_lifetime_param_def_id.to_def_id())
3094 );
3095
3096 loop {
3097 let parent = self.local_parent(opaque_lifetime_param_def_id);
3098 let lifetime_mapping = self.opaque_captured_lifetimes(parent);
3099
3100 let Some((lifetime, _)) = lifetime_mapping
3101 .iter()
3102 .find(|(_, duplicated_param)| *duplicated_param == opaque_lifetime_param_def_id)
3103 else {
3104 ::rustc_span::macros::bug_impl(None,
format_args!("duplicated lifetime param should be present"),
Location::caller());bug!("duplicated lifetime param should be present");
3105 };
3106
3107 match *lifetime {
3108 resolve_bound_vars::ResolvedArg::EarlyBound(ebv) => {
3109 let new_parent = self.local_parent(ebv);
3110
3111 if #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(new_parent) {
DefKind::OpaqueTy => true,
_ => false,
}matches!(self.def_kind(new_parent), DefKind::OpaqueTy) {
3114 if true {
{
match (&self.local_parent(parent), &new_parent) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.local_parent(parent), new_parent);
3115 opaque_lifetime_param_def_id = ebv;
3116 continue;
3117 }
3118
3119 let generics = self.generics_of(new_parent);
3120 return ty::Region::new_early_param(
3121 self,
3122 ty::EarlyParamRegion {
3123 index: generics
3124 .param_def_id_to_index(self, ebv.to_def_id())
3125 .expect("early-bound var should be present in fn generics"),
3126 name: self.item_name(ebv.to_def_id()),
3127 },
3128 );
3129 }
3130 resolve_bound_vars::ResolvedArg::LateBound(_, _, lbv) => {
3131 let new_parent = self.local_parent(lbv);
3132 return ty::Region::new_late_param(
3133 self,
3134 new_parent.to_def_id(),
3135 ty::LateParamRegionKind::Named(lbv.to_def_id()),
3136 );
3137 }
3138 resolve_bound_vars::ResolvedArg::Error(guar) => {
3139 return ty::Region::new_error(self, guar);
3140 }
3141 _ => {
3142 return ty::Region::new_error_with_message(
3143 self,
3144 self.def_span(opaque_lifetime_param_def_id),
3145 "cannot resolve lifetime",
3146 );
3147 }
3148 }
3149 }
3150 }
3151
3152 pub fn is_stable_const_fn(self, def_id: DefId) -> bool {
3157 self.is_const_fn(def_id)
3158 && match self.lookup_const_stability(def_id) {
3159 None => true, Some(stability) if stability.is_const_stable() => true,
3161 _ => false,
3162 }
3163 }
3164
3165 pub fn is_const_trait_impl(self, def_id: DefId) -> bool {
3167 self.def_kind(def_id) == DefKind::Impl { of_trait: true }
3168 && #[allow(non_exhaustive_omitted_patterns)] match self.impl_trait_header(def_id).constness
{
hir::Constness::Const { always: false } => true,
_ => false,
}matches!(
3169 self.impl_trait_header(def_id).constness,
3170 hir::Constness::Const { always: false }
3171 )
3172 }
3173
3174 pub fn is_sdylib_interface_build(self) -> bool {
3175 self.sess.opts.unstable_opts.build_sdylib_interface
3176 }
3177
3178 pub fn intrinsic(self, def_id: impl IntoQueryKey<DefId>) -> Option<ty::IntrinsicDef> {
3179 let def_id = def_id.into_query_key();
3180 match self.def_kind(def_id) {
3181 DefKind::Fn | DefKind::AssocFn => self.intrinsic_raw(def_id),
3182 _ => None,
3183 }
3184 }
3185
3186 pub fn is_intrinsic_that_must_be_overridden(self, def_id: impl IntoQueryKey<DefId>) -> bool {
3191 self.intrinsic(def_id).is_some_and(|i| i.must_be_overridden)
3192 }
3193
3194 pub fn next_trait_solver_globally(self) -> bool {
3195 self.sess.opts.unstable_opts.next_solver == NextSolverConfig::Globally
3196 && !self.sess.opts.unstable_opts.higher_ranked_assumptions
3197 && !self.features().generic_const_exprs()
3198 }
3199
3200 pub fn next_solver_overflow_fcw_limit(self) -> Option<usize> {
3201 self.sess.opts.unstable_opts.next_solver_overflow_fcw_limit
3202 }
3203
3204 pub fn disable_trait_solver_fast_paths(self) -> bool {
3205 self.sess.opts.unstable_opts.disable_fast_paths
3206 }
3207
3208 pub fn disable_param_env_normalization_hack(self) -> bool {
3209 self.sess.opts.unstable_opts.disable_param_env_normalization_hack
3210 }
3211
3212 pub fn renormalize_rigid_aliases(self) -> bool {
3213 self.sess.opts.unstable_opts.renormalize_rigid_aliases
3214 }
3215
3216 #[allow(rustc::bad_opt_access)]
3217 pub fn use_typing_mode_post_typeck_through_borrowck(self) -> bool {
3218 self.next_trait_solver_globally()
3219 }
3220
3221 pub fn assumptions_on_binders(self) -> bool {
3222 self.sess.opts.unstable_opts.assumptions_on_binders
3223 }
3224
3225 pub fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {
3226 self.opt_rpitit_info(def_id).is_some()
3227 }
3228
3229 pub fn get_impl_future_output_ty(self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
3230 let (def_id, args) = match *ty.kind() {
3231 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => (def_id, args),
3232 ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
3233 if self.is_impl_trait_in_trait(def_id) =>
3234 {
3235 (def_id, args)
3236 }
3237 _ => return None,
3238 };
3239
3240 let future_trait = self.require_lang_item(LangItem::Future, DUMMY_SP);
3241 let item_def_id = self.associated_item_def_ids(future_trait)[0];
3242
3243 self.explicit_item_self_bounds(def_id)
3244 .iter_instantiated_copied(self, args)
3245 .map(ty::Unnormalized::skip_norm_wip)
3246 .find_map(|(predicate, _)| {
3247 predicate
3248 .kind()
3249 .map_bound(|kind| match kind {
3250 ty::ClauseKind::Projection(projection_predicate)
3251 if projection_predicate.def_id() == item_def_id =>
3252 {
3253 projection_predicate.term.as_type()
3254 }
3255 _ => None,
3256 })
3257 .no_bound_vars()
3258 .flatten()
3259 })
3260 }
3261
3262 pub fn module_children_local(self, def_id: LocalDefId) -> &'tcx [ModChild] {
3272 self.resolutions(()).module_children.get(&def_id).map_or(&[], |v| &v[..])
3273 }
3274
3275 pub fn extern_mod_stmt_cnum(self, def_id: LocalDefId) -> Option<CrateNum> {
3277 self.resolutions(()).extern_crate_map.get(&def_id).copied()
3278 }
3279
3280 pub fn resolver_for_lowering(
3281 self,
3282 ) -> (&'tcx Steal<ResolverAstLowering<'tcx>>, &'tcx Steal<ast::Crate>) {
3283 let (resolver, krate, _) = self.resolver_for_lowering_raw(());
3284 (resolver, krate)
3285 }
3286
3287 pub fn metadata_dep_node(self) -> crate::dep_graph::DepNode {
3288 make_metadata(self)
3289 }
3290
3291 pub fn needs_coroutine_by_move_body_def_id(self, def_id: DefId) -> bool {
3292 if let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure)) =
3293 self.coroutine_kind(def_id)
3294 && let ty::Coroutine(_, args) =
3295 self.type_of(def_id).instantiate_identity().skip_norm_wip().kind()
3296 && args.as_coroutine().kind_ty().to_opt_closure_kind() != Some(ty::ClosureKind::FnOnce)
3297 {
3298 true
3299 } else {
3300 false
3301 }
3302 }
3303
3304 pub fn do_not_recommend_impl(self, def_id: DefId) -> bool {
3306 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(DoNotRecommend) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self, def_id, DoNotRecommend)
3307 }
3308
3309 pub fn is_trivial_const(self, def_id: impl IntoQueryKey<DefId>) -> bool {
3310 let def_id = def_id.into_query_key();
3311 self.trivial_const(def_id).is_some()
3312 }
3313
3314 pub fn is_entrypoint(self, def_id: DefId) -> bool {
3317 if self.is_lang_item(def_id, LangItem::Start) {
3318 return true;
3319 }
3320 if let Some((entry_def_id, _)) = self.entry_fn(())
3321 && entry_def_id == def_id
3322 {
3323 return true;
3324 }
3325 false
3326 }
3327}
3328
3329pub fn provide(providers: &mut Providers) {
3330 providers.is_panic_runtime = |tcx, LocalCrate| {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(PanicRuntime) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, PanicRuntime);
3331 providers.is_compiler_builtins = |tcx, LocalCrate| {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(CompilerBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, CompilerBuiltins);
3332 providers.has_panic_handler = |tcx, LocalCrate| {
3333 tcx.lang_items().panic_impl().is_some_and(|did| did.is_local())
3335 };
3336 providers.source_span = |tcx, def_id| tcx.untracked.source_span.get(def_id).unwrap_or(DUMMY_SP);
3337}