Skip to main content

rustc_middle/ty/context/
impl_interner.rs

1//! Implementation of [`rustc_type_ir::Interner`] for [`TyCtxt`].
2
3use std::{debug_assert_matches, fmt};
4
5use rustc_data_structures::Limit;
6use rustc_data_structures::intern::Interned;
7use rustc_errors::ErrorGuaranteed;
8use rustc_hir as hir;
9use rustc_hir::CRATE_HIR_ID;
10use rustc_hir::attrs::lang_items::LangItem;
11use rustc_hir::def::{CtorKind, DefKind, Namespace};
12use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
13use rustc_span::{DUMMY_SP, Span, Symbol};
14use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverProjectionLangItem, SolverTraitLangItem};
15use rustc_type_ir::{
16    BoundVar, CollectAndApply, DebruijnIndex, Interner, TypeFoldable, Unnormalized, VisitorResult,
17    search_graph, try_visit,
18};
19
20use crate::dep_graph::{DepKind, DepNodeIndex};
21use crate::infer::canonical::CanonicalVarKinds;
22use crate::traits::cache::WithDepNode;
23use crate::traits::solve::{
24    self, CanonicalInput, ExternalConstraints, ExternalConstraintsData, QueryResult, inspect,
25};
26use crate::ty::print::{FmtPrinter, Print};
27use crate::ty::{
28    self, BoundRegion, Clause, Const, List, ParamTy, Pattern, PolyExistentialPredicate, Predicate,
29    Region, RegionKind, Ty, TyCtxt,
30};
31
32#[allow(rustc::usage_of_ty_tykind)]
33impl<'tcx> Interner for TyCtxt<'tcx> {
34    fn next_trait_solver_globally(self) -> bool {
35        self.next_trait_solver_globally()
36    }
37
38    type DefId = DefId;
39    type LocalDefId = LocalDefId;
40    type TraitId = DefId;
41    type ForeignId = DefId;
42    type FunctionId = DefId;
43    type ClosureId = DefId;
44    type CoroutineClosureId = DefId;
45    type CoroutineId = DefId;
46    type AdtId = DefId;
47    type ImplId = DefId;
48    type AnonConstId = DefId;
49    type TraitAssocTyId = DefId;
50    type TraitAssocConstId = DefId;
51    type TraitAssocTermId = DefId;
52    type OpaqueTyId = DefId;
53    type LocalOpaqueTyId = LocalDefId;
54    type FreeTyAliasId = DefId;
55    type FreeConstAliasId = DefId;
56    type FreeTermAliasId = DefId;
57    type ImplOrTraitAssocTyId = DefId;
58    type ImplOrTraitAssocConstId = DefId;
59    type ImplOrTraitAssocTermId = DefId;
60    type InherentAssocTyId = DefId;
61    type InherentAssocConstId = DefId;
62    type InherentAssocTermId = DefId;
63    type Span = Span;
64
65    type GenericArgs = ty::GenericArgsRef<'tcx>;
66
67    type GenericArgsSlice = &'tcx [ty::GenericArg<'tcx>];
68    type GenericArg = ty::GenericArg<'tcx>;
69    type Term = ty::Term<'tcx>;
70    type BoundVarKinds = &'tcx List<ty::BoundVariableKind<'tcx>>;
71
72    type PredefinedOpaques = solve::PredefinedOpaques<'tcx>;
73
74    fn mk_predefined_opaques_in_body(
75        self,
76        data: &[(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)],
77    ) -> Self::PredefinedOpaques {
78        self.mk_predefined_opaques_in_body(data)
79    }
80    type LocalDefIds = &'tcx ty::List<LocalDefId>;
81    type CanonicalVarKinds = CanonicalVarKinds<'tcx>;
82    fn mk_canonical_var_kinds(
83        self,
84        kinds: &[ty::CanonicalVarKind<Self>],
85    ) -> Self::CanonicalVarKinds {
86        self.mk_canonical_var_kinds(kinds)
87    }
88
89    type ExternalConstraints = ExternalConstraints<'tcx>;
90    fn mk_external_constraints(
91        self,
92        data: ExternalConstraintsData<Self>,
93    ) -> ExternalConstraints<'tcx> {
94        self.mk_external_constraints(data)
95    }
96    type DepNodeIndex = DepNodeIndex;
97    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, DepNodeIndex) {
98        self.dep_graph.with_anon_task(self, DepKind::TraitSelect, task)
99    }
100    type Ty = Ty<'tcx>;
101    type Tys = &'tcx List<Ty<'tcx>>;
102
103    type FnInputTys = &'tcx [Ty<'tcx>];
104    type ParamTy = ParamTy;
105    type Symbol = Symbol;
106
107    type ErrorGuaranteed = ErrorGuaranteed;
108    type BoundExistentialPredicates = &'tcx List<PolyExistentialPredicate<'tcx>>;
109
110    type AllocId = crate::mir::interpret::AllocId;
111    type Pat = Pattern<'tcx>;
112    type PatList = &'tcx List<Pattern<'tcx>>;
113    type Safety = hir::Safety;
114    type Const = ty::Const<'tcx>;
115    type Consts = &'tcx List<Self::Const>;
116
117    type ParamConst = ty::ParamConst;
118    type ValueConst = ty::Value<'tcx>;
119    type ExprConst = ty::Expr<'tcx>;
120    type ValTree = ty::ValTree<'tcx>;
121    type ScalarInt = ty::ScalarInt;
122    type InternedRegionKind = Interned<'tcx, ty::RegionKind<'tcx>>;
123    type EarlyParamRegion = ty::EarlyParamRegion;
124    type LateParamRegion = ty::LateParamRegion;
125
126    type RegionAssumptions = &'tcx ty::List<ty::ArgOutlivesClause<'tcx>>;
127
128    type ParamEnv = ty::ParamEnv<'tcx>;
129    type Predicate = Predicate<'tcx>;
130
131    type Clause = Clause<'tcx>;
132    type Clauses = ty::Clauses<'tcx>;
133
134    type Tracked<T: fmt::Debug + Clone> = WithDepNode<T>;
135    fn mk_tracked<T: fmt::Debug + Clone>(
136        self,
137        data: T,
138        dep_node: DepNodeIndex,
139    ) -> Self::Tracked<T> {
140        WithDepNode::new(dep_node, data)
141    }
142    fn get_tracked<T: fmt::Debug + Clone>(self, tracked: &Self::Tracked<T>) -> T {
143        tracked.get(self)
144    }
145
146    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R {
147        f(&mut *self.new_solver_evaluation_cache.lock())
148    }
149
150    fn with_canonical_param_env_cache<R>(
151        self,
152        f: impl FnOnce(&mut ty::CanonicalParamEnvCache<Self>) -> R,
153    ) -> R {
154        f(&mut *self.new_solver_canonical_param_env_cache.lock())
155    }
156
157    fn assert_evaluation_is_concurrent(&self) {
158        // Turns out, the assumption for this function isn't perfect.
159        // See trait-system-refactor-initiative#234.
160    }
161
162    fn expand_abstract_consts<T: TypeFoldable<TyCtxt<'tcx>>>(self, t: T) -> T {
163        self.expand_abstract_consts(t)
164    }
165
166    type GenericsOf = &'tcx ty::Generics;
167
168    fn generics_of(self, def_id: DefId) -> &'tcx ty::Generics {
169        self.generics_of(def_id)
170    }
171
172    type VariancesOf = &'tcx [ty::Variance];
173
174    fn variances_of(self, def_id: DefId) -> Self::VariancesOf {
175        self.variances_of(def_id)
176    }
177
178    fn opt_alias_variances(
179        self,
180        kind: impl Into<ty::AliasTermKind<'tcx>>,
181    ) -> Option<&'tcx [ty::Variance]> {
182        self.opt_alias_variances(kind)
183    }
184
185    fn type_of(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
186        self.type_of(def_id)
187    }
188    fn type_of_opaque_hir_typeck(self, def_id: LocalDefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
189        self.type_of_opaque_hir_typeck(def_id)
190    }
191    fn is_type_const(self, def_id: DefId) -> bool {
192        self.is_type_const(def_id)
193    }
194    fn const_of_item(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Const<'tcx>> {
195        self.const_of_item(def_id)
196    }
197    fn anon_const_kind(self, def_id: DefId) -> ty::AnonConstKind {
198        self.anon_const_kind(def_id)
199    }
200
201    fn def_span(self, def_id: DefId) -> Span {
202        self.def_span(def_id)
203    }
204
205    type AdtDef = ty::AdtDef<'tcx>;
206    fn adt_def(self, adt_def_id: DefId) -> Self::AdtDef {
207        self.adt_def(adt_def_id)
208    }
209
210    fn alias_const_kind_from_def_id(self, def_id: Self::DefId) -> ty::AliasConstKind<'tcx> {
211        match self.def_kind(def_id) {
212            DefKind::AssocConst { .. } => {
213                if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) {
214                    ty::AliasConstKind::Inherent { def_id }
215                } else {
216                    ty::AliasConstKind::Projection { def_id }
217                }
218            }
219            DefKind::Const { .. } => ty::AliasConstKind::Free { def_id },
220            DefKind::AnonConst | DefKind::Ctor(_, CtorKind::Const) => {
221                ty::AliasConstKind::Anon { def_id }
222            }
223            kind => crate::util::bug::bug_fmt(format_args!("unexpected DefKind in AliasConst: {0:?}",
        kind))bug!("unexpected DefKind in AliasConst: {kind:?}"),
224        }
225    }
226
227    fn alias_term_kind_from_def_id(self, def_id: DefId) -> ty::AliasTermKind<'tcx> {
228        match self.def_kind(def_id) {
229            DefKind::AssocTy => {
230                if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) {
231                    ty::AliasTermKind::InherentTy { def_id }
232                } else {
233                    ty::AliasTermKind::ProjectionTy { def_id }
234                }
235            }
236            DefKind::AssocConst { .. } => {
237                if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) {
238                    ty::AliasTermKind::InherentConst { def_id }
239                } else {
240                    ty::AliasTermKind::ProjectionConst { def_id }
241                }
242            }
243            DefKind::OpaqueTy => ty::AliasTermKind::OpaqueTy { def_id },
244            DefKind::TyAlias => ty::AliasTermKind::FreeTy { def_id },
245            DefKind::Const { .. } => ty::AliasTermKind::FreeConst { def_id },
246            DefKind::AnonConst | DefKind::Ctor(_, CtorKind::Const) => {
247                ty::AliasTermKind::AnonConst { def_id }
248            }
249            kind => crate::util::bug::bug_fmt(format_args!("unexpected DefKind in AliasTy: {0:?}",
        kind))bug!("unexpected DefKind in AliasTy: {kind:?}"),
250        }
251    }
252
253    fn trait_ref_and_own_args_for_alias(
254        self,
255        def_id: DefId,
256        args: ty::GenericArgsRef<'tcx>,
257    ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
258        if true {
    {
        match self.def_kind(def_id) {
            DefKind::AssocTy | DefKind::AssocConst { .. } => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::AssocTy | DefKind::AssocConst { .. }",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::AssocConst { .. });
259        let trait_def_id = self.parent(def_id);
260        if true {
    {
        match self.def_kind(trait_def_id) {
            DefKind::Trait => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::Trait", ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.def_kind(trait_def_id), DefKind::Trait);
261        let trait_ref = ty::TraitRef::from_assoc(self, trait_def_id, args);
262        (trait_ref, &args[trait_ref.args.len()..])
263    }
264
265    fn mk_args(self, args: &[Self::GenericArg]) -> ty::GenericArgsRef<'tcx> {
266        self.mk_args(args)
267    }
268
269    fn mk_args_from_iter<I, T>(self, args: I) -> T::Output
270    where
271        I: Iterator<Item = T>,
272        T: CollectAndApply<Self::GenericArg, ty::GenericArgsRef<'tcx>>,
273    {
274        self.mk_args_from_iter(args)
275    }
276
277    fn check_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> bool {
278        self.check_args_compatible(def_id, args)
279    }
280
281    fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) {
282        self.debug_assert_args_compatible(def_id, args);
283    }
284
285    /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection`
286    /// are compatible with the `DefId`. Since we're missing a `Self` type, stick on
287    /// a dummy self type and forward to `debug_assert_args_compatible`.
288    fn debug_assert_existential_args_compatible(
289        self,
290        def_id: Self::DefId,
291        args: Self::GenericArgs,
292    ) {
293        // FIXME: We could perhaps add a `skip: usize` to `debug_assert_args_compatible`
294        // to avoid needing to reintern the set of args...
295        if truecfg!(debug_assertions) {
296            self.debug_assert_args_compatible(
297                def_id,
298                self.mk_args_from_iter(
299                    [self.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()),
300                ),
301            );
302        }
303    }
304
305    fn mk_type_list_from_iter<I, T>(self, args: I) -> T::Output
306    where
307        I: Iterator<Item = T>,
308        T: CollectAndApply<Ty<'tcx>, &'tcx List<Ty<'tcx>>>,
309    {
310        self.mk_type_list_from_iter(args)
311    }
312
313    fn projection_parent(self, def_id: Self::TraitAssocTermId) -> Self::TraitId {
314        self.parent(def_id)
315    }
316
317    fn impl_or_trait_assoc_term_parent(self, def_id: Self::ImplOrTraitAssocTyId) -> DefId {
318        self.parent(def_id)
319    }
320
321    fn inherent_alias_term_parent(self, def_id: Self::InherentAssocTermId) -> Self::ImplId {
322        self.parent(def_id)
323    }
324
325    fn recursion_limit(self) -> usize {
326        self.recursion_limit().0
327    }
328
329    type Features = &'tcx rustc_feature::Features;
330
331    fn features(self) -> Self::Features {
332        self.features()
333    }
334
335    fn assumptions_on_binders(self) -> bool {
336        self.assumptions_on_binders()
337    }
338
339    fn renormalize_rigid_aliases(self) -> bool {
340        self.renormalize_rigid_aliases()
341    }
342
343    fn coroutine_hidden_types(
344        self,
345        def_id: DefId,
346    ) -> ty::EarlyBinder<'tcx, ty::Binder<'tcx, ty::CoroutineWitnessTypes<TyCtxt<'tcx>>>> {
347        self.coroutine_hidden_types(def_id)
348    }
349
350    fn fn_sig(self, def_id: DefId) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> {
351        self.fn_sig(def_id)
352    }
353
354    fn coroutine_movability(self, def_id: DefId) -> rustc_ast::Movability {
355        self.coroutine_movability(def_id)
356    }
357
358    fn coroutine_for_closure(self, def_id: DefId) -> DefId {
359        self.coroutine_for_closure(def_id)
360    }
361
362    fn generics_require_sized_self(self, def_id: DefId) -> bool {
363        self.generics_require_sized_self(def_id)
364    }
365
366    fn item_bounds(
367        self,
368        def_id: DefId,
369    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
370        self.item_bounds(def_id).map_bound(IntoIterator::into_iter)
371    }
372
373    fn item_self_bounds(
374        self,
375        def_id: DefId,
376    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
377        self.item_self_bounds(def_id).map_bound(IntoIterator::into_iter)
378    }
379
380    fn item_non_self_bounds(
381        self,
382        def_id: DefId,
383    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
384        self.item_non_self_bounds(def_id).map_bound(IntoIterator::into_iter)
385    }
386
387    fn clauses_of(
388        self,
389        def_id: DefId,
390    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
391        ty::EarlyBinder::bind_iter(
392            self.clauses_of(def_id)
393                .instantiate_identity(self)
394                .clauses
395                .into_iter()
396                .map(Unnormalized::skip_normalization),
397        )
398    }
399
400    fn own_clauses_of(
401        self,
402        def_id: DefId,
403    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
404        ty::EarlyBinder::bind_iter(
405            self.clauses_of(def_id)
406                .instantiate_own_identity()
407                .map(|(clause, _)| clause.skip_normalization()),
408        )
409    }
410
411    fn explicit_super_clauses_of(
412        self,
413        def_id: DefId,
414    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>> {
415        self.explicit_super_clauses_of(def_id).map_bound(|preds| preds.into_iter().copied())
416    }
417
418    fn explicit_implied_clauses_of(
419        self,
420        def_id: DefId,
421    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>> {
422        self.explicit_implied_clauses_of(def_id).map_bound(|preds| preds.into_iter().copied())
423    }
424
425    fn impl_super_outlives(
426        self,
427        impl_def_id: DefId,
428    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
429        self.impl_super_outlives(impl_def_id)
430    }
431
432    fn impl_is_const(self, def_id: DefId) -> bool {
433        if true {
    {
        match self.def_kind(def_id) {
            DefKind::Impl { of_trait: true } => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::Impl { of_trait: true }",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.def_kind(def_id), DefKind::Impl { of_trait: true });
434        self.is_conditionally_const(def_id)
435    }
436
437    fn fn_is_const(self, def_id: DefId) -> bool {
438        if true {
    {
        match self.def_kind(def_id) {
            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) =>
                {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn)",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(
439            self.def_kind(def_id),
440            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn)
441        );
442        self.is_conditionally_const(def_id)
443    }
444
445    fn closure_is_const(self, def_id: DefId) -> bool {
446        if true {
    {
        match self.def_kind(def_id) {
            DefKind::Closure => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::Closure", ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.def_kind(def_id), DefKind::Closure);
447        #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(self.constness(def_id), hir::Constness::Const { always: false })
448    }
449
450    fn alias_has_const_conditions(self, def_id: DefId) -> bool {
451        if true {
    {
        match self.def_kind(def_id) {
            DefKind::AssocTy | DefKind::OpaqueTy => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::AssocTy | DefKind::OpaqueTy",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::OpaqueTy);
452        self.is_conditionally_const(def_id)
453    }
454
455    fn const_conditions(
456        self,
457        def_id: DefId,
458    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Binder<'tcx, ty::TraitRef<'tcx>>>> {
459        ty::EarlyBinder::bind_iter(
460            self.const_conditions(def_id)
461                .instantiate_identity(self)
462                .into_iter()
463                .map(|(c, _)| c.skip_normalization()),
464        )
465    }
466
467    fn explicit_implied_const_bounds(
468        self,
469        def_id: DefId,
470    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Binder<'tcx, ty::TraitRef<'tcx>>>> {
471        ty::EarlyBinder::bind_iter(
472            self.explicit_implied_const_bounds(def_id)
473                .iter_identity_copied()
474                .map(Unnormalized::skip_normalization)
475                .map(|(c, _)| c),
476        )
477    }
478
479    fn impl_self_is_guaranteed_unsized(self, impl_def_id: DefId) -> bool {
480        self.impl_self_is_guaranteed_unsized(impl_def_id)
481    }
482
483    fn has_target_features(self, def_id: DefId) -> bool {
484        !self.codegen_fn_attrs(def_id).target_features.is_empty()
485    }
486
487    fn require_projection_lang_item(self, lang_item: SolverProjectionLangItem) -> DefId {
488        self.require_lang_item(solver_lang_item_to_lang_item(lang_item), DUMMY_SP)
489    }
490
491    fn require_trait_lang_item(self, lang_item: SolverTraitLangItem) -> DefId {
492        self.require_lang_item(solver_trait_lang_item_to_lang_item(lang_item), DUMMY_SP)
493    }
494
495    fn require_adt_lang_item(self, lang_item: SolverAdtLangItem) -> DefId {
496        self.require_lang_item(solver_adt_lang_item_to_lang_item(lang_item), DUMMY_SP)
497    }
498
499    fn is_projection_lang_item(self, def_id: DefId, lang_item: SolverProjectionLangItem) -> bool {
500        self.is_lang_item(def_id, solver_lang_item_to_lang_item(lang_item))
501    }
502
503    fn is_trait_lang_item(self, def_id: DefId, lang_item: SolverTraitLangItem) -> bool {
504        self.is_lang_item(def_id, solver_trait_lang_item_to_lang_item(lang_item))
505    }
506
507    fn is_adt_lang_item(self, def_id: DefId, lang_item: SolverAdtLangItem) -> bool {
508        self.is_lang_item(def_id, solver_adt_lang_item_to_lang_item(lang_item))
509    }
510
511    fn is_default_trait(self, def_id: DefId) -> bool {
512        self.is_default_trait(def_id)
513    }
514
515    fn is_sizedness_trait(self, def_id: DefId) -> bool {
516        self.is_sizedness_trait(def_id)
517    }
518
519    fn as_projection_lang_item(self, def_id: DefId) -> Option<SolverProjectionLangItem> {
520        lang_item_to_solver_lang_item(self.lang_items().from_def_id(def_id)?)
521    }
522
523    fn as_trait_lang_item(self, def_id: DefId) -> Option<SolverTraitLangItem> {
524        lang_item_to_solver_trait_lang_item(self.lang_items().from_def_id(def_id)?)
525    }
526
527    fn as_adt_lang_item(self, def_id: DefId) -> Option<SolverAdtLangItem> {
528        lang_item_to_solver_adt_lang_item(self.lang_items().from_def_id(def_id)?)
529    }
530
531    fn associated_type_def_ids(self, def_id: DefId) -> impl IntoIterator<Item = DefId> {
532        self.associated_items(def_id)
533            .in_definition_order()
534            .filter(|assoc_item| assoc_item.is_type())
535            .map(|assoc_item| assoc_item.def_id)
536    }
537
538    // This signature is a bit different from `TyCtxt::for_each_relevant_impl`.
539    // While rustc only needs self_ty, rust-analyzer's impl needs to use all the args.
540    fn for_each_relevant_impl<R: VisitorResult>(
541        self,
542        trait_ref: ty::TraitRef<'tcx>,
543        f: impl FnMut(DefId) -> R,
544    ) -> R {
545        let self_ty = trait_ref.args.type_at(0);
546        if true {
    if !!#[allow(non_exhaustive_omitted_patterns)] match self_ty.kind() {
                    ty::Infer(ty::TyVar(_)) | ty::Param(_) | ty::Bound(_, _) =>
                        true,
                    _ => false,
                } {
        {
            ::core::panicking::panic_fmt(format_args!("we should not have them as self ty in the next solver"));
        }
    };
};debug_assert!(
547            !matches!(self_ty.kind(), ty::Infer(ty::TyVar(_)) | ty::Param(_) | ty::Bound(_, _)),
548            "we should not have them as self ty in the next solver"
549        );
550        TyCtxt::for_each_relevant_impl(self, trait_ref.def_id, self_ty, f)
551    }
552    fn for_each_blanket_impl<R: VisitorResult>(
553        self,
554        trait_def_id: DefId,
555        mut f: impl FnMut(DefId) -> R,
556    ) -> R {
557        let trait_impls = self.trait_impls_of(trait_def_id);
558        for &impl_def_id in trait_impls.blanket_impls() {
559            match ::rustc_ast_ir::visit::VisitorResult::branch(f(impl_def_id)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(f(impl_def_id));
560        }
561
562        R::output()
563    }
564
565    fn has_item_definition(self, def_id: DefId) -> bool {
566        self.defaultness(def_id).has_value()
567    }
568
569    fn impl_specializes(self, impl_def_id: Self::DefId, victim_def_id: Self::DefId) -> bool {
570        self.specializes((impl_def_id, victim_def_id))
571    }
572
573    fn impl_is_default(self, impl_def_id: DefId) -> bool {
574        self.defaultness(impl_def_id).is_default()
575    }
576
577    fn impl_trait_ref(self, impl_def_id: DefId) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
578        self.impl_trait_ref(impl_def_id)
579    }
580
581    fn impl_polarity(self, impl_def_id: DefId) -> ty::ImplPolarity {
582        self.impl_polarity(impl_def_id)
583    }
584
585    fn is_fully_generic_for_reflection(self, impl_def_id: Self::ImplId) -> bool {
586        self.impl_is_fully_generic_for_reflection(impl_def_id)
587    }
588
589    fn trait_is_auto(self, trait_def_id: DefId) -> bool {
590        self.trait_is_auto(trait_def_id)
591    }
592
593    fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
594        self.trait_is_coinductive(trait_def_id)
595    }
596
597    fn trait_is_alias(self, trait_def_id: DefId) -> bool {
598        self.trait_is_alias(trait_def_id)
599    }
600
601    fn trait_is_dyn_compatible(self, trait_def_id: DefId) -> bool {
602        self.is_dyn_compatible(trait_def_id)
603    }
604
605    fn trait_is_fundamental(self, def_id: DefId) -> bool {
606        self.trait_def(def_id).is_fundamental
607    }
608
609    fn trait_is_unsafe(self, trait_def_id: Self::DefId) -> bool {
610        self.trait_def(trait_def_id).safety.is_unsafe()
611    }
612
613    fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {
614        self.is_impl_trait_in_trait(def_id)
615    }
616
617    fn delay_bug(self, msg: impl ToString) -> ErrorGuaranteed {
618        self.dcx().span_delayed_bug(DUMMY_SP, msg.to_string())
619    }
620
621    fn is_general_coroutine(self, coroutine_def_id: DefId) -> bool {
622        self.is_general_coroutine(coroutine_def_id)
623    }
624
625    fn coroutine_is_async(self, coroutine_def_id: DefId) -> bool {
626        self.coroutine_is_async(coroutine_def_id)
627    }
628
629    fn coroutine_is_gen(self, coroutine_def_id: DefId) -> bool {
630        self.coroutine_is_gen(coroutine_def_id)
631    }
632
633    fn coroutine_is_async_gen(self, coroutine_def_id: DefId) -> bool {
634        self.coroutine_is_async_gen(coroutine_def_id)
635    }
636
637    type UnsizingParams = &'tcx rustc_index::bit_set::DenseBitSet<u32>;
638    fn unsizing_params_for_adt(self, adt_def_id: DefId) -> Self::UnsizingParams {
639        self.unsizing_params_for_adt(adt_def_id)
640    }
641
642    fn anonymize_bound_vars<T: TypeFoldable<TyCtxt<'tcx>>>(
643        self,
644        binder: ty::Binder<'tcx, T>,
645    ) -> ty::Binder<'tcx, T> {
646        self.anonymize_bound_vars(binder)
647    }
648
649    fn opaque_types_defined_by(self, defining_anchor: LocalDefId) -> Self::LocalDefIds {
650        self.opaque_types_defined_by(defining_anchor)
651    }
652
653    fn opaque_types_and_coroutines_defined_by(
654        self,
655        defining_anchor: Self::LocalDefId,
656    ) -> Self::LocalDefIds {
657        let coroutines_defined_by = self
658            .nested_bodies_within(defining_anchor)
659            .iter()
660            .filter(|def_id| self.is_coroutine(def_id.to_def_id()));
661        self.mk_local_def_ids_from_iter(
662            self.opaque_types_defined_by(defining_anchor).iter().chain(coroutines_defined_by),
663        )
664    }
665
666    type Probe = &'tcx inspect::Probe<TyCtxt<'tcx>>;
667    fn mk_probe(self, probe: inspect::Probe<Self>) -> &'tcx inspect::Probe<TyCtxt<'tcx>> {
668        self.arena.alloc(probe)
669    }
670    fn evaluate_root_goal_for_proof_tree_raw(
671        self,
672        canonical_goal: CanonicalInput<'tcx>,
673        root_depth: usize,
674    ) -> (QueryResult<'tcx>, &'tcx inspect::Probe<TyCtxt<'tcx>>) {
675        self.evaluate_root_goal_for_proof_tree_raw((canonical_goal, root_depth))
676    }
677
678    fn emit_next_solver_overflow_fcw(self, predicate: ty::Predicate<'tcx>, span: Span) {
679        self.emit_node_span_lint(
680            rustc_session::lint::builtin::RECURSION_DEPTH_EXCEEDING_LIMIT,
681            CRATE_HIR_ID,
682            span,
683            rustc_errors::DiagDecorator(|diag| {
684                // FIXME: share this with overflow error in fulfillment instead of duplicating.
685                let pred_str = {
686                    let s = predicate.to_string();
687                    if s.len() > 50 {
688                        let mut p: FmtPrinter<'_, '_> =
689                            FmtPrinter::new_with_limit(self, Namespace::TypeNS, Limit(6));
690                        predicate.print(&mut p).unwrap();
691                        p.into_buffer()
692                    } else {
693                        s
694                    }
695                };
696                diag.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred_str))
    })format!(
697                    "overflow evaluating the requirement `{pred_str}`",
698                ));
699                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider increasing the recursion limit by adding a `#![recursion_limit = \"{0}\"]` attribute to your crate (`{1}`)",
                self.recursion_limit() * 2, self.crate_name(LOCAL_CRATE)))
    })format!(
700                    "consider increasing the recursion limit by adding a \
701                     `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
702                    self.recursion_limit() * 2,
703                    self.crate_name(LOCAL_CRATE),
704                ));
705                diag.help(
706                    "or consider adding a manual `impl` of auto traits like `Send` for intermediate types, if auto traits are involved",
707                );
708                diag.note("this lint is attached to the whole crate and can't be disabled on a per-function basis");
709            }),
710        )
711    }
712
713    fn item_name(self, id: DefId) -> Symbol {
714        self.opt_item_name(id).unwrap_or_else(|| {
715            crate::util::bug::bug_fmt(format_args!("item_name: no name for {0:?}",
        self.def_path(id)));bug!("item_name: no name for {:?}", self.def_path(id));
716        })
717    }
718
719    fn get_anon_re_bounds_lifetime(self, idx: usize, var_idx: usize) -> Option<Region<'tcx>> {
720        if let Some(inner) = self.lifetimes.anon_re_bounds.get(idx) {
721            inner.get(var_idx).copied()
722        } else {
723            None
724        }
725    }
726
727    fn get_anon_re_canonical_bounds_lifetime(self, idx: usize) -> Option<Region<'tcx>> {
728        self.lifetimes.anon_re_canonical_bounds.get(idx).copied()
729    }
730
731    fn get_re_static_lifetime(self) -> Region<'tcx> {
732        self.lifetimes.re_static
733    }
734
735    fn intern_region(self, region_kind: RegionKind<'tcx>) -> Region<'tcx> {
736        self.intern_region(region_kind)
737    }
738
739    fn intern_bound_region(
740        self,
741        debruijn: DebruijnIndex,
742        bound_region: BoundRegion<'tcx>,
743    ) -> Region<'tcx> {
744        // Use a pre-interned one when possible.
745        if let ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon } = bound_region
746            && let Some(inner) = self.lifetimes.anon_re_bounds.get(debruijn.as_usize())
747            && let Some(re) = inner.get(var.as_usize()).copied()
748        {
749            re
750        } else {
751            self.intern_region(ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), bound_region))
752        }
753    }
754
755    fn intern_canonical_bound(self, var: BoundVar) -> Region<'tcx> {
756        // Use a pre-interned one when possible.
757        if let Some(re) = self.lifetimes.anon_re_canonical_bounds.get(var.as_usize()).copied() {
758            re
759        } else {
760            self.intern_region(ty::ReBound(
761                ty::BoundVarIndexKind::Canonical,
762                BoundRegion { var, kind: ty::BoundRegionKind::Anon },
763            ))
764        }
765    }
766}
767
768impl<'tcx, T: std::fmt::Debug + Clone + Copy> rustc_type_ir::intern::Interned<TyCtxt<'tcx>>
769    for Interned<'tcx, T>
770{
771    type Value = T;
772    fn get(self) -> T {
773        *self.0
774    }
775}
776
777/// Defines trivial conversion functions between the main [`LangItem`] enum,
778/// and some other lang-item enum that is a subset of it.
779macro_rules! bidirectional_lang_item_map {
780    (
781        $solver_ty:ident, fn $to_solver:ident, fn $from_solver:ident;
782        $($name:ident),+ $(,)?
783    ) => {
784        fn $from_solver(lang_item: $solver_ty) -> LangItem {
785            match lang_item {
786                $($solver_ty::$name => LangItem::$name,)+
787            }
788        }
789
790        fn $to_solver(lang_item: LangItem) -> Option<$solver_ty> {
791            Some(match lang_item {
792                $(LangItem::$name => $solver_ty::$name,)+
793                _ => return None,
794            })
795        }
796    }
797}
798
799fn solver_lang_item_to_lang_item(lang_item: SolverProjectionLangItem)
    -> LangItem {
    match lang_item {
        SolverProjectionLangItem::AsyncFnKindUpvars =>
            LangItem::AsyncFnKindUpvars,
        SolverProjectionLangItem::AsyncFnOnceOutput =>
            LangItem::AsyncFnOnceOutput,
        SolverProjectionLangItem::CallOnceFuture => LangItem::CallOnceFuture,
        SolverProjectionLangItem::CallRefFuture => LangItem::CallRefFuture,
        SolverProjectionLangItem::CoroutineReturn =>
            LangItem::CoroutineReturn,
        SolverProjectionLangItem::CoroutineYield => LangItem::CoroutineYield,
        SolverProjectionLangItem::FieldBase => LangItem::FieldBase,
        SolverProjectionLangItem::FieldType => LangItem::FieldType,
        SolverProjectionLangItem::FutureOutput => LangItem::FutureOutput,
        SolverProjectionLangItem::Metadata => LangItem::Metadata,
    }
}
fn lang_item_to_solver_lang_item(lang_item: LangItem)
    -> Option<SolverProjectionLangItem> {
    Some(match lang_item {
            LangItem::AsyncFnKindUpvars =>
                SolverProjectionLangItem::AsyncFnKindUpvars,
            LangItem::AsyncFnOnceOutput =>
                SolverProjectionLangItem::AsyncFnOnceOutput,
            LangItem::CallOnceFuture =>
                SolverProjectionLangItem::CallOnceFuture,
            LangItem::CallRefFuture =>
                SolverProjectionLangItem::CallRefFuture,
            LangItem::CoroutineReturn =>
                SolverProjectionLangItem::CoroutineReturn,
            LangItem::CoroutineYield =>
                SolverProjectionLangItem::CoroutineYield,
            LangItem::FieldBase => SolverProjectionLangItem::FieldBase,
            LangItem::FieldType => SolverProjectionLangItem::FieldType,
            LangItem::FutureOutput => SolverProjectionLangItem::FutureOutput,
            LangItem::Metadata => SolverProjectionLangItem::Metadata,
            _ => return None,
        })
}bidirectional_lang_item_map! {
800    SolverProjectionLangItem, fn lang_item_to_solver_lang_item, fn solver_lang_item_to_lang_item;
801
802// tidy-alphabetical-start
803    AsyncFnKindUpvars,
804    AsyncFnOnceOutput,
805    CallOnceFuture,
806    CallRefFuture,
807    CoroutineReturn,
808    CoroutineYield,
809    FieldBase,
810    FieldType,
811    FutureOutput,
812    Metadata,
813// tidy-alphabetical-end
814}
815
816fn solver_adt_lang_item_to_lang_item(lang_item: SolverAdtLangItem)
    -> LangItem {
    match lang_item {
        SolverAdtLangItem::DynMetadata => LangItem::DynMetadata,
        SolverAdtLangItem::Option => LangItem::Option,
        SolverAdtLangItem::OwnedBox => LangItem::OwnedBox,
        SolverAdtLangItem::Poll => LangItem::Poll,
    }
}
fn lang_item_to_solver_adt_lang_item(lang_item: LangItem)
    -> Option<SolverAdtLangItem> {
    Some(match lang_item {
            LangItem::DynMetadata => SolverAdtLangItem::DynMetadata,
            LangItem::Option => SolverAdtLangItem::Option,
            LangItem::OwnedBox => SolverAdtLangItem::OwnedBox,
            LangItem::Poll => SolverAdtLangItem::Poll,
            _ => return None,
        })
}bidirectional_lang_item_map! {
817    SolverAdtLangItem, fn lang_item_to_solver_adt_lang_item, fn solver_adt_lang_item_to_lang_item;
818
819// tidy-alphabetical-start
820    DynMetadata,
821    Option,
822    OwnedBox,
823    Poll,
824// tidy-alphabetical-end
825}
826
827fn solver_trait_lang_item_to_lang_item(lang_item: SolverTraitLangItem)
    -> LangItem {
    match lang_item {
        SolverTraitLangItem::AsyncFn => LangItem::AsyncFn,
        SolverTraitLangItem::AsyncFnKindHelper => LangItem::AsyncFnKindHelper,
        SolverTraitLangItem::AsyncFnMut => LangItem::AsyncFnMut,
        SolverTraitLangItem::AsyncFnOnce => LangItem::AsyncFnOnce,
        SolverTraitLangItem::AsyncIterator => LangItem::AsyncIterator,
        SolverTraitLangItem::BikeshedGuaranteedNoDrop =>
            LangItem::BikeshedGuaranteedNoDrop,
        SolverTraitLangItem::Clone => LangItem::Clone,
        SolverTraitLangItem::Copy => LangItem::Copy,
        SolverTraitLangItem::Coroutine => LangItem::Coroutine,
        SolverTraitLangItem::Destruct => LangItem::Destruct,
        SolverTraitLangItem::DiscriminantKind => LangItem::DiscriminantKind,
        SolverTraitLangItem::Drop => LangItem::Drop,
        SolverTraitLangItem::Field => LangItem::Field,
        SolverTraitLangItem::Fn => LangItem::Fn,
        SolverTraitLangItem::FnMut => LangItem::FnMut,
        SolverTraitLangItem::FnOnce => LangItem::FnOnce,
        SolverTraitLangItem::FnPtrTrait => LangItem::FnPtrTrait,
        SolverTraitLangItem::FusedIterator => LangItem::FusedIterator,
        SolverTraitLangItem::Future => LangItem::Future,
        SolverTraitLangItem::Iterator => LangItem::Iterator,
        SolverTraitLangItem::MetaSized => LangItem::MetaSized,
        SolverTraitLangItem::PointeeSized => LangItem::PointeeSized,
        SolverTraitLangItem::PointeeTrait => LangItem::PointeeTrait,
        SolverTraitLangItem::Sized => LangItem::Sized,
        SolverTraitLangItem::TransmuteTrait => LangItem::TransmuteTrait,
        SolverTraitLangItem::TrivialClone => LangItem::TrivialClone,
        SolverTraitLangItem::TryAsDyn => LangItem::TryAsDyn,
        SolverTraitLangItem::Tuple => LangItem::Tuple,
        SolverTraitLangItem::Unpin => LangItem::Unpin,
        SolverTraitLangItem::Unsize => LangItem::Unsize,
    }
}
fn lang_item_to_solver_trait_lang_item(lang_item: LangItem)
    -> Option<SolverTraitLangItem> {
    Some(match lang_item {
            LangItem::AsyncFn => SolverTraitLangItem::AsyncFn,
            LangItem::AsyncFnKindHelper =>
                SolverTraitLangItem::AsyncFnKindHelper,
            LangItem::AsyncFnMut => SolverTraitLangItem::AsyncFnMut,
            LangItem::AsyncFnOnce => SolverTraitLangItem::AsyncFnOnce,
            LangItem::AsyncIterator => SolverTraitLangItem::AsyncIterator,
            LangItem::BikeshedGuaranteedNoDrop =>
                SolverTraitLangItem::BikeshedGuaranteedNoDrop,
            LangItem::Clone => SolverTraitLangItem::Clone,
            LangItem::Copy => SolverTraitLangItem::Copy,
            LangItem::Coroutine => SolverTraitLangItem::Coroutine,
            LangItem::Destruct => SolverTraitLangItem::Destruct,
            LangItem::DiscriminantKind =>
                SolverTraitLangItem::DiscriminantKind,
            LangItem::Drop => SolverTraitLangItem::Drop,
            LangItem::Field => SolverTraitLangItem::Field,
            LangItem::Fn => SolverTraitLangItem::Fn,
            LangItem::FnMut => SolverTraitLangItem::FnMut,
            LangItem::FnOnce => SolverTraitLangItem::FnOnce,
            LangItem::FnPtrTrait => SolverTraitLangItem::FnPtrTrait,
            LangItem::FusedIterator => SolverTraitLangItem::FusedIterator,
            LangItem::Future => SolverTraitLangItem::Future,
            LangItem::Iterator => SolverTraitLangItem::Iterator,
            LangItem::MetaSized => SolverTraitLangItem::MetaSized,
            LangItem::PointeeSized => SolverTraitLangItem::PointeeSized,
            LangItem::PointeeTrait => SolverTraitLangItem::PointeeTrait,
            LangItem::Sized => SolverTraitLangItem::Sized,
            LangItem::TransmuteTrait => SolverTraitLangItem::TransmuteTrait,
            LangItem::TrivialClone => SolverTraitLangItem::TrivialClone,
            LangItem::TryAsDyn => SolverTraitLangItem::TryAsDyn,
            LangItem::Tuple => SolverTraitLangItem::Tuple,
            LangItem::Unpin => SolverTraitLangItem::Unpin,
            LangItem::Unsize => SolverTraitLangItem::Unsize,
            _ => return None,
        })
}bidirectional_lang_item_map! {
828    SolverTraitLangItem, fn lang_item_to_solver_trait_lang_item, fn solver_trait_lang_item_to_lang_item;
829
830// tidy-alphabetical-start
831    AsyncFn,
832    AsyncFnKindHelper,
833    AsyncFnMut,
834    AsyncFnOnce,
835    AsyncIterator,
836    BikeshedGuaranteedNoDrop,
837    Clone,
838    Copy,
839    Coroutine,
840    Destruct,
841    DiscriminantKind,
842    Drop,
843    Field,
844    Fn,
845    FnMut,
846    FnOnce,
847    FnPtrTrait,
848    FusedIterator,
849    Future,
850    Iterator,
851    MetaSized,
852    PointeeSized,
853    PointeeTrait,
854    Sized,
855    TransmuteTrait,
856    TrivialClone,
857    TryAsDyn,
858    Tuple,
859    Unpin,
860    Unsize,
861// tidy-alphabetical-end
862}