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