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_errors::ErrorGuaranteed;
6use rustc_hir as hir;
7use rustc_hir::def::{CtorKind, CtorOf, DefKind};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::lang_items::LangItem;
10use rustc_span::{DUMMY_SP, Span, Symbol};
11use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverLangItem, SolverTraitLangItem};
12use rustc_type_ir::{CollectAndApply, Interner, TypeFoldable, Unnormalized, search_graph};
13
14use crate::dep_graph::{DepKind, DepNodeIndex};
15use crate::infer::canonical::CanonicalVarKinds;
16use crate::traits::cache::WithDepNode;
17use crate::traits::solve::{
18    self, CanonicalInput, ExternalConstraints, ExternalConstraintsData, QueryResult, inspect,
19};
20use crate::ty::{
21    self, Clause, Const, List, ParamTy, Pattern, PolyExistentialPredicate, Predicate, Region, Ty,
22    TyCtxt,
23};
24
25#[allow(rustc::usage_of_ty_tykind)]
26impl<'tcx> Interner for TyCtxt<'tcx> {
27    fn next_trait_solver_globally(self) -> bool {
28        self.next_trait_solver_globally()
29    }
30
31    type DefId = DefId;
32    type LocalDefId = LocalDefId;
33    type TraitId = DefId;
34    type ForeignId = DefId;
35    type FunctionId = DefId;
36    type ClosureId = DefId;
37    type CoroutineClosureId = DefId;
38    type CoroutineId = DefId;
39    type AdtId = DefId;
40    type ImplId = DefId;
41    type UnevaluatedConstId = DefId;
42    type Span = Span;
43
44    type GenericArgs = ty::GenericArgsRef<'tcx>;
45
46    type GenericArgsSlice = &'tcx [ty::GenericArg<'tcx>];
47    type GenericArg = ty::GenericArg<'tcx>;
48    type Term = ty::Term<'tcx>;
49    type BoundVarKinds = &'tcx List<ty::BoundVariableKind<'tcx>>;
50
51    type PredefinedOpaques = solve::PredefinedOpaques<'tcx>;
52
53    fn mk_predefined_opaques_in_body(
54        self,
55        data: &[(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)],
56    ) -> Self::PredefinedOpaques {
57        self.mk_predefined_opaques_in_body(data)
58    }
59    type LocalDefIds = &'tcx ty::List<LocalDefId>;
60    type CanonicalVarKinds = CanonicalVarKinds<'tcx>;
61    fn mk_canonical_var_kinds(
62        self,
63        kinds: &[ty::CanonicalVarKind<Self>],
64    ) -> Self::CanonicalVarKinds {
65        self.mk_canonical_var_kinds(kinds)
66    }
67
68    type ExternalConstraints = ExternalConstraints<'tcx>;
69    fn mk_external_constraints(
70        self,
71        data: ExternalConstraintsData<Self>,
72    ) -> ExternalConstraints<'tcx> {
73        self.mk_external_constraints(data)
74    }
75    type DepNodeIndex = DepNodeIndex;
76    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, DepNodeIndex) {
77        self.dep_graph.with_anon_task(self, DepKind::TraitSelect, task)
78    }
79    type Ty = Ty<'tcx>;
80    type Tys = &'tcx List<Ty<'tcx>>;
81
82    type FnInputTys = &'tcx [Ty<'tcx>];
83    type ParamTy = ParamTy;
84    type Symbol = Symbol;
85
86    type ErrorGuaranteed = ErrorGuaranteed;
87    type BoundExistentialPredicates = &'tcx List<PolyExistentialPredicate<'tcx>>;
88
89    type AllocId = crate::mir::interpret::AllocId;
90    type Pat = Pattern<'tcx>;
91    type PatList = &'tcx List<Pattern<'tcx>>;
92    type Safety = hir::Safety;
93    type Const = ty::Const<'tcx>;
94    type Consts = &'tcx List<Self::Const>;
95
96    type ParamConst = ty::ParamConst;
97    type ValueConst = ty::Value<'tcx>;
98    type ExprConst = ty::Expr<'tcx>;
99    type ValTree = ty::ValTree<'tcx>;
100    type ScalarInt = ty::ScalarInt;
101
102    type Region = Region<'tcx>;
103    type EarlyParamRegion = ty::EarlyParamRegion;
104    type LateParamRegion = ty::LateParamRegion;
105
106    type RegionAssumptions = &'tcx ty::List<ty::ArgOutlivesPredicate<'tcx>>;
107
108    type ParamEnv = ty::ParamEnv<'tcx>;
109    type Predicate = Predicate<'tcx>;
110
111    type Clause = Clause<'tcx>;
112    type Clauses = ty::Clauses<'tcx>;
113
114    type Tracked<T: fmt::Debug + Clone> = WithDepNode<T>;
115    fn mk_tracked<T: fmt::Debug + Clone>(
116        self,
117        data: T,
118        dep_node: DepNodeIndex,
119    ) -> Self::Tracked<T> {
120        WithDepNode::new(dep_node, data)
121    }
122    fn get_tracked<T: fmt::Debug + Clone>(self, tracked: &Self::Tracked<T>) -> T {
123        tracked.get(self)
124    }
125
126    fn with_global_cache<R>(self, f: impl FnOnce(&mut search_graph::GlobalCache<Self>) -> R) -> R {
127        f(&mut *self.new_solver_evaluation_cache.lock())
128    }
129
130    fn canonical_param_env_cache_get_or_insert<R>(
131        self,
132        param_env: ty::ParamEnv<'tcx>,
133        f: impl FnOnce() -> ty::CanonicalParamEnvCacheEntry<Self>,
134        from_entry: impl FnOnce(&ty::CanonicalParamEnvCacheEntry<Self>) -> R,
135    ) -> R {
136        let mut cache = self.new_solver_canonical_param_env_cache.lock();
137        let entry = cache.entry(param_env).or_insert_with(f);
138        from_entry(entry)
139    }
140
141    fn assert_evaluation_is_concurrent(&self) {
142        // Turns out, the assumption for this function isn't perfect.
143        // See trait-system-refactor-initiative#234.
144    }
145
146    fn expand_abstract_consts<T: TypeFoldable<TyCtxt<'tcx>>>(self, t: T) -> T {
147        self.expand_abstract_consts(t)
148    }
149
150    type GenericsOf = &'tcx ty::Generics;
151
152    fn generics_of(self, def_id: DefId) -> &'tcx ty::Generics {
153        self.generics_of(def_id)
154    }
155
156    type VariancesOf = &'tcx [ty::Variance];
157
158    fn variances_of(self, def_id: DefId) -> Self::VariancesOf {
159        self.variances_of(def_id)
160    }
161
162    fn opt_alias_variances(
163        self,
164        kind: impl Into<ty::AliasTermKind<'tcx>>,
165    ) -> Option<&'tcx [ty::Variance]> {
166        self.opt_alias_variances(kind)
167    }
168
169    fn type_of(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
170        self.type_of(def_id)
171    }
172    fn type_of_opaque_hir_typeck(self, def_id: LocalDefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> {
173        self.type_of_opaque_hir_typeck(def_id)
174    }
175    fn const_of_item(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Const<'tcx>> {
176        self.const_of_item(def_id)
177    }
178    fn anon_const_kind(self, def_id: DefId) -> ty::AnonConstKind {
179        self.anon_const_kind(def_id)
180    }
181
182    type AdtDef = ty::AdtDef<'tcx>;
183    fn adt_def(self, adt_def_id: DefId) -> Self::AdtDef {
184        self.adt_def(adt_def_id)
185    }
186
187    fn alias_ty_kind_from_def_id(self, def_id: DefId) -> ty::AliasTyKind<'tcx> {
188        match self.def_kind(def_id) {
189            DefKind::AssocTy
190                if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) =>
191            {
192                ty::Inherent { def_id }
193            }
194            DefKind::AssocTy => ty::Projection { def_id },
195
196            DefKind::OpaqueTy => ty::Opaque { def_id },
197            DefKind::TyAlias => ty::Free { def_id },
198            kind => crate::util::bug::bug_fmt(format_args!("unexpected DefKind in AliasTy: {0:?}",
        kind))bug!("unexpected DefKind in AliasTy: {kind:?}"),
199        }
200    }
201
202    fn alias_term_kind_from_def_id(self, def_id: DefId) -> ty::AliasTermKind<'tcx> {
203        match self.def_kind(def_id) {
204            DefKind::AssocTy => {
205                if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) {
206                    ty::AliasTermKind::InherentTy { def_id }
207                } else {
208                    ty::AliasTermKind::ProjectionTy { def_id }
209                }
210            }
211            DefKind::AssocConst { .. } => {
212                if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) {
213                    ty::AliasTermKind::InherentConst { def_id }
214                } else {
215                    ty::AliasTermKind::ProjectionConst { def_id }
216                }
217            }
218            DefKind::OpaqueTy => ty::AliasTermKind::OpaqueTy { def_id },
219            DefKind::TyAlias => ty::AliasTermKind::FreeTy { def_id },
220            DefKind::Const { .. } => ty::AliasTermKind::FreeConst { def_id },
221            DefKind::AnonConst | DefKind::Ctor(_, CtorKind::Const) => {
222                ty::AliasTermKind::UnevaluatedConst { def_id }
223            }
224            kind => crate::util::bug::bug_fmt(format_args!("unexpected DefKind in AliasTy: {0:?}",
        kind))bug!("unexpected DefKind in AliasTy: {kind:?}"),
225        }
226    }
227
228    fn trait_ref_and_own_args_for_alias(
229        self,
230        def_id: DefId,
231        args: ty::GenericArgsRef<'tcx>,
232    ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
233        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 { .. });
234        let trait_def_id = self.parent(def_id);
235        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);
236        let trait_ref = ty::TraitRef::from_assoc(self, trait_def_id, args);
237        (trait_ref, &args[trait_ref.args.len()..])
238    }
239
240    fn mk_args(self, args: &[Self::GenericArg]) -> ty::GenericArgsRef<'tcx> {
241        self.mk_args(args)
242    }
243
244    fn mk_args_from_iter<I, T>(self, args: I) -> T::Output
245    where
246        I: Iterator<Item = T>,
247        T: CollectAndApply<Self::GenericArg, ty::GenericArgsRef<'tcx>>,
248    {
249        self.mk_args_from_iter(args)
250    }
251
252    fn check_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> bool {
253        self.check_args_compatible(def_id, args)
254    }
255
256    fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) {
257        self.debug_assert_args_compatible(def_id, args);
258    }
259
260    /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection`
261    /// are compatible with the `DefId`. Since we're missing a `Self` type, stick on
262    /// a dummy self type and forward to `debug_assert_args_compatible`.
263    fn debug_assert_existential_args_compatible(
264        self,
265        def_id: Self::DefId,
266        args: Self::GenericArgs,
267    ) {
268        // FIXME: We could perhaps add a `skip: usize` to `debug_assert_args_compatible`
269        // to avoid needing to reintern the set of args...
270        if truecfg!(debug_assertions) {
271            self.debug_assert_args_compatible(
272                def_id,
273                self.mk_args_from_iter(
274                    [self.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()),
275                ),
276            );
277        }
278    }
279
280    fn mk_type_list_from_iter<I, T>(self, args: I) -> T::Output
281    where
282        I: Iterator<Item = T>,
283        T: CollectAndApply<Ty<'tcx>, &'tcx List<Ty<'tcx>>>,
284    {
285        self.mk_type_list_from_iter(args)
286    }
287
288    fn parent(self, def_id: DefId) -> DefId {
289        self.parent(def_id)
290    }
291
292    fn recursion_limit(self) -> usize {
293        self.recursion_limit().0
294    }
295
296    type Features = &'tcx rustc_feature::Features;
297
298    fn features(self) -> Self::Features {
299        self.features()
300    }
301
302    fn coroutine_hidden_types(
303        self,
304        def_id: DefId,
305    ) -> ty::EarlyBinder<'tcx, ty::Binder<'tcx, ty::CoroutineWitnessTypes<TyCtxt<'tcx>>>> {
306        self.coroutine_hidden_types(def_id)
307    }
308
309    fn fn_sig(self, def_id: DefId) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> {
310        self.fn_sig(def_id)
311    }
312
313    fn coroutine_movability(self, def_id: DefId) -> rustc_ast::Movability {
314        self.coroutine_movability(def_id)
315    }
316
317    fn coroutine_for_closure(self, def_id: DefId) -> DefId {
318        self.coroutine_for_closure(def_id)
319    }
320
321    fn generics_require_sized_self(self, def_id: DefId) -> bool {
322        self.generics_require_sized_self(def_id)
323    }
324
325    fn item_bounds(
326        self,
327        def_id: DefId,
328    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
329        self.item_bounds(def_id).map_bound(IntoIterator::into_iter)
330    }
331
332    fn item_self_bounds(
333        self,
334        def_id: DefId,
335    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
336        self.item_self_bounds(def_id).map_bound(IntoIterator::into_iter)
337    }
338
339    fn item_non_self_bounds(
340        self,
341        def_id: DefId,
342    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
343        self.item_non_self_bounds(def_id).map_bound(IntoIterator::into_iter)
344    }
345
346    fn predicates_of(
347        self,
348        def_id: DefId,
349    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
350        ty::EarlyBinder::bind(
351            self.predicates_of(def_id)
352                .instantiate_identity(self)
353                .predicates
354                .into_iter()
355                .map(Unnormalized::skip_normalization),
356        )
357    }
358
359    fn own_predicates_of(
360        self,
361        def_id: DefId,
362    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
363        ty::EarlyBinder::bind(
364            self.predicates_of(def_id)
365                .instantiate_own_identity()
366                .map(|(clause, _)| clause.skip_normalization()),
367        )
368    }
369
370    fn explicit_super_predicates_of(
371        self,
372        def_id: DefId,
373    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>> {
374        self.explicit_super_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied())
375    }
376
377    fn explicit_implied_predicates_of(
378        self,
379        def_id: DefId,
380    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>> {
381        self.explicit_implied_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied())
382    }
383
384    fn impl_super_outlives(
385        self,
386        impl_def_id: DefId,
387    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
388        self.impl_super_outlives(impl_def_id)
389    }
390
391    fn impl_is_const(self, def_id: DefId) -> bool {
392        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 });
393        self.is_conditionally_const(def_id)
394    }
395
396    fn fn_is_const(self, def_id: DefId) -> bool {
397        if true {
    {
        match self.def_kind(def_id) {
            DefKind::Fn | DefKind::AssocFn |
                DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(CtorOf::Struct, CtorKind::Fn)",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(
398            self.def_kind(def_id),
399            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(CtorOf::Struct, CtorKind::Fn)
400        );
401        self.is_conditionally_const(def_id)
402    }
403
404    fn closure_is_const(self, def_id: DefId) -> bool {
405        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);
406        self.constness(def_id) == hir::Constness::Const
407    }
408
409    fn alias_has_const_conditions(self, def_id: DefId) -> bool {
410        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);
411        self.is_conditionally_const(def_id)
412    }
413
414    fn const_conditions(
415        self,
416        def_id: DefId,
417    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Binder<'tcx, ty::TraitRef<'tcx>>>> {
418        ty::EarlyBinder::bind(
419            self.const_conditions(def_id)
420                .instantiate_identity(self)
421                .into_iter()
422                .map(|(c, _)| c.skip_normalization()),
423        )
424    }
425
426    fn explicit_implied_const_bounds(
427        self,
428        def_id: DefId,
429    ) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Binder<'tcx, ty::TraitRef<'tcx>>>> {
430        ty::EarlyBinder::bind(
431            self.explicit_implied_const_bounds(def_id)
432                .iter_identity_copied()
433                .map(Unnormalized::skip_normalization)
434                .map(|(c, _)| c),
435        )
436    }
437
438    fn impl_self_is_guaranteed_unsized(self, impl_def_id: DefId) -> bool {
439        self.impl_self_is_guaranteed_unsized(impl_def_id)
440    }
441
442    fn has_target_features(self, def_id: DefId) -> bool {
443        !self.codegen_fn_attrs(def_id).target_features.is_empty()
444    }
445
446    fn require_lang_item(self, lang_item: SolverLangItem) -> DefId {
447        self.require_lang_item(solver_lang_item_to_lang_item(lang_item), DUMMY_SP)
448    }
449
450    fn require_trait_lang_item(self, lang_item: SolverTraitLangItem) -> DefId {
451        self.require_lang_item(solver_trait_lang_item_to_lang_item(lang_item), DUMMY_SP)
452    }
453
454    fn require_adt_lang_item(self, lang_item: SolverAdtLangItem) -> DefId {
455        self.require_lang_item(solver_adt_lang_item_to_lang_item(lang_item), DUMMY_SP)
456    }
457
458    fn is_lang_item(self, def_id: DefId, lang_item: SolverLangItem) -> bool {
459        self.is_lang_item(def_id, solver_lang_item_to_lang_item(lang_item))
460    }
461
462    fn is_trait_lang_item(self, def_id: DefId, lang_item: SolverTraitLangItem) -> bool {
463        self.is_lang_item(def_id, solver_trait_lang_item_to_lang_item(lang_item))
464    }
465
466    fn is_adt_lang_item(self, def_id: DefId, lang_item: SolverAdtLangItem) -> bool {
467        self.is_lang_item(def_id, solver_adt_lang_item_to_lang_item(lang_item))
468    }
469
470    fn is_default_trait(self, def_id: DefId) -> bool {
471        self.is_default_trait(def_id)
472    }
473
474    fn is_sizedness_trait(self, def_id: DefId) -> bool {
475        self.is_sizedness_trait(def_id)
476    }
477
478    fn as_lang_item(self, def_id: DefId) -> Option<SolverLangItem> {
479        lang_item_to_solver_lang_item(self.lang_items().from_def_id(def_id)?)
480    }
481
482    fn as_trait_lang_item(self, def_id: DefId) -> Option<SolverTraitLangItem> {
483        lang_item_to_solver_trait_lang_item(self.lang_items().from_def_id(def_id)?)
484    }
485
486    fn as_adt_lang_item(self, def_id: DefId) -> Option<SolverAdtLangItem> {
487        lang_item_to_solver_adt_lang_item(self.lang_items().from_def_id(def_id)?)
488    }
489
490    fn associated_type_def_ids(self, def_id: DefId) -> impl IntoIterator<Item = DefId> {
491        self.associated_items(def_id)
492            .in_definition_order()
493            .filter(|assoc_item| assoc_item.is_type())
494            .map(|assoc_item| assoc_item.def_id)
495    }
496
497    // This implementation is a bit different from `TyCtxt::for_each_relevant_impl`,
498    // since we want to skip over blanket impls for non-rigid aliases, and also we
499    // only want to consider types that *actually* unify with float/int vars.
500    fn for_each_relevant_impl(
501        self,
502        trait_def_id: DefId,
503        self_ty: Ty<'tcx>,
504        mut f: impl FnMut(DefId),
505    ) {
506        let tcx = self;
507        let trait_impls = tcx.trait_impls_of(trait_def_id);
508        let mut consider_impls_for_simplified_type = |simp| {
509            if let Some(impls_for_type) = trait_impls.non_blanket_impls().get(&simp) {
510                for &impl_def_id in impls_for_type {
511                    f(impl_def_id);
512                }
513            }
514        };
515
516        match self_ty.kind() {
517            ty::Bool
518            | ty::Char
519            | ty::Int(_)
520            | ty::Uint(_)
521            | ty::Float(_)
522            | ty::Adt(_, _)
523            | ty::Foreign(_)
524            | ty::Str
525            | ty::Array(_, _)
526            | ty::Pat(_, _)
527            | ty::Slice(_)
528            | ty::RawPtr(_, _)
529            | ty::Ref(_, _, _)
530            | ty::FnDef(_, _)
531            | ty::FnPtr(..)
532            | ty::Dynamic(_, _)
533            | ty::Closure(..)
534            | ty::CoroutineClosure(..)
535            | ty::Coroutine(_, _)
536            | ty::Never
537            | ty::Tuple(_)
538            | ty::UnsafeBinder(_) => {
539                if let Some(simp) = ty::fast_reject::simplify_type(
540                    tcx,
541                    self_ty,
542                    ty::fast_reject::TreatParams::AsRigid,
543                ) {
544                    consider_impls_for_simplified_type(simp);
545                }
546            }
547
548            // HACK: For integer and float variables we have to manually look at all impls
549            // which have some integer or float as a self type.
550            ty::Infer(ty::IntVar(_)) => {
551                use ty::IntTy::*;
552                use ty::UintTy::*;
553                // This causes a compiler error if any new integer kinds are added.
554                let (I8 | I16 | I32 | I64 | I128 | Isize): ty::IntTy;
555                let (U8 | U16 | U32 | U64 | U128 | Usize): ty::UintTy;
556                let possible_integers = [
557                    // signed integers
558                    ty::SimplifiedType::Int(I8),
559                    ty::SimplifiedType::Int(I16),
560                    ty::SimplifiedType::Int(I32),
561                    ty::SimplifiedType::Int(I64),
562                    ty::SimplifiedType::Int(I128),
563                    ty::SimplifiedType::Int(Isize),
564                    // unsigned integers
565                    ty::SimplifiedType::Uint(U8),
566                    ty::SimplifiedType::Uint(U16),
567                    ty::SimplifiedType::Uint(U32),
568                    ty::SimplifiedType::Uint(U64),
569                    ty::SimplifiedType::Uint(U128),
570                    ty::SimplifiedType::Uint(Usize),
571                ];
572                for simp in possible_integers {
573                    consider_impls_for_simplified_type(simp);
574                }
575            }
576
577            ty::Infer(ty::FloatVar(_)) => {
578                // This causes a compiler error if any new float kinds are added.
579                let (ty::FloatTy::F16 | ty::FloatTy::F32 | ty::FloatTy::F64 | ty::FloatTy::F128);
580                let possible_floats = [
581                    ty::SimplifiedType::Float(ty::FloatTy::F16),
582                    ty::SimplifiedType::Float(ty::FloatTy::F32),
583                    ty::SimplifiedType::Float(ty::FloatTy::F64),
584                    ty::SimplifiedType::Float(ty::FloatTy::F128),
585                ];
586
587                for simp in possible_floats {
588                    consider_impls_for_simplified_type(simp);
589                }
590            }
591
592            // The only traits applying to aliases and placeholders are blanket impls.
593            //
594            // Impls which apply to an alias after normalization are handled by
595            // `assemble_candidates_after_normalizing_self_ty`.
596            ty::Alias(_) | ty::Placeholder(..) | ty::Error(_) => (),
597
598            // FIXME: These should ideally not exist as a self type. It would be nice for
599            // the builtin auto trait impls of coroutines to instead directly recurse
600            // into the witness.
601            ty::CoroutineWitness(..) => (),
602
603            // These variants should not exist as a self type.
604            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
605            | ty::Param(_)
606            | ty::Bound(_, _) => crate::util::bug::bug_fmt(format_args!("unexpected self type: {0}", self_ty))bug!("unexpected self type: {self_ty}"),
607        }
608
609        #[allow(rustc::usage_of_type_ir_traits)]
610        self.for_each_blanket_impl(trait_def_id, f)
611    }
612    fn for_each_blanket_impl(self, trait_def_id: DefId, mut f: impl FnMut(DefId)) {
613        let trait_impls = self.trait_impls_of(trait_def_id);
614        for &impl_def_id in trait_impls.blanket_impls() {
615            f(impl_def_id);
616        }
617    }
618
619    fn has_item_definition(self, def_id: DefId) -> bool {
620        self.defaultness(def_id).has_value()
621    }
622
623    fn impl_specializes(self, impl_def_id: Self::DefId, victim_def_id: Self::DefId) -> bool {
624        self.specializes((impl_def_id, victim_def_id))
625    }
626
627    fn impl_is_default(self, impl_def_id: DefId) -> bool {
628        self.defaultness(impl_def_id).is_default()
629    }
630
631    fn impl_trait_ref(self, impl_def_id: DefId) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
632        self.impl_trait_ref(impl_def_id)
633    }
634
635    fn impl_polarity(self, impl_def_id: DefId) -> ty::ImplPolarity {
636        self.impl_polarity(impl_def_id)
637    }
638
639    fn trait_is_auto(self, trait_def_id: DefId) -> bool {
640        self.trait_is_auto(trait_def_id)
641    }
642
643    fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
644        self.trait_is_coinductive(trait_def_id)
645    }
646
647    fn trait_is_alias(self, trait_def_id: DefId) -> bool {
648        self.trait_is_alias(trait_def_id)
649    }
650
651    fn trait_is_dyn_compatible(self, trait_def_id: DefId) -> bool {
652        self.is_dyn_compatible(trait_def_id)
653    }
654
655    fn trait_is_fundamental(self, def_id: DefId) -> bool {
656        self.trait_def(def_id).is_fundamental
657    }
658
659    fn trait_is_unsafe(self, trait_def_id: Self::DefId) -> bool {
660        self.trait_def(trait_def_id).safety.is_unsafe()
661    }
662
663    fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {
664        self.is_impl_trait_in_trait(def_id)
665    }
666
667    fn delay_bug(self, msg: impl ToString) -> ErrorGuaranteed {
668        self.dcx().span_delayed_bug(DUMMY_SP, msg.to_string())
669    }
670
671    fn is_general_coroutine(self, coroutine_def_id: DefId) -> bool {
672        self.is_general_coroutine(coroutine_def_id)
673    }
674
675    fn coroutine_is_async(self, coroutine_def_id: DefId) -> bool {
676        self.coroutine_is_async(coroutine_def_id)
677    }
678
679    fn coroutine_is_gen(self, coroutine_def_id: DefId) -> bool {
680        self.coroutine_is_gen(coroutine_def_id)
681    }
682
683    fn coroutine_is_async_gen(self, coroutine_def_id: DefId) -> bool {
684        self.coroutine_is_async_gen(coroutine_def_id)
685    }
686
687    type UnsizingParams = &'tcx rustc_index::bit_set::DenseBitSet<u32>;
688    fn unsizing_params_for_adt(self, adt_def_id: DefId) -> Self::UnsizingParams {
689        self.unsizing_params_for_adt(adt_def_id)
690    }
691
692    fn anonymize_bound_vars<T: TypeFoldable<TyCtxt<'tcx>>>(
693        self,
694        binder: ty::Binder<'tcx, T>,
695    ) -> ty::Binder<'tcx, T> {
696        self.anonymize_bound_vars(binder)
697    }
698
699    fn opaque_types_defined_by(self, defining_anchor: LocalDefId) -> Self::LocalDefIds {
700        self.opaque_types_defined_by(defining_anchor)
701    }
702
703    fn opaque_types_and_coroutines_defined_by(
704        self,
705        defining_anchor: Self::LocalDefId,
706    ) -> Self::LocalDefIds {
707        let coroutines_defined_by = self
708            .nested_bodies_within(defining_anchor)
709            .iter()
710            .filter(|def_id| self.is_coroutine(def_id.to_def_id()));
711        self.mk_local_def_ids_from_iter(
712            self.opaque_types_defined_by(defining_anchor).iter().chain(coroutines_defined_by),
713        )
714    }
715
716    type Probe = &'tcx inspect::Probe<TyCtxt<'tcx>>;
717    fn mk_probe(self, probe: inspect::Probe<Self>) -> &'tcx inspect::Probe<TyCtxt<'tcx>> {
718        self.arena.alloc(probe)
719    }
720    fn evaluate_root_goal_for_proof_tree_raw(
721        self,
722        canonical_goal: CanonicalInput<'tcx>,
723    ) -> (QueryResult<'tcx>, &'tcx inspect::Probe<TyCtxt<'tcx>>) {
724        self.evaluate_root_goal_for_proof_tree_raw(canonical_goal)
725    }
726
727    fn item_name(self, id: DefId) -> Symbol {
728        self.opt_item_name(id).unwrap_or_else(|| {
729            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));
730        })
731    }
732}
733
734/// Defines trivial conversion functions between the main [`LangItem`] enum,
735/// and some other lang-item enum that is a subset of it.
736macro_rules! bidirectional_lang_item_map {
737    (
738        $solver_ty:ident, fn $to_solver:ident, fn $from_solver:ident;
739        $($name:ident),+ $(,)?
740    ) => {
741        fn $from_solver(lang_item: $solver_ty) -> LangItem {
742            match lang_item {
743                $($solver_ty::$name => LangItem::$name,)+
744            }
745        }
746
747        fn $to_solver(lang_item: LangItem) -> Option<$solver_ty> {
748            Some(match lang_item {
749                $(LangItem::$name => $solver_ty::$name,)+
750                _ => return None,
751            })
752        }
753    }
754}
755
756fn solver_lang_item_to_lang_item(lang_item: SolverLangItem) -> LangItem {
    match lang_item {
        SolverLangItem::AsyncFnKindUpvars => LangItem::AsyncFnKindUpvars,
        SolverLangItem::AsyncFnOnceOutput => LangItem::AsyncFnOnceOutput,
        SolverLangItem::CallOnceFuture => LangItem::CallOnceFuture,
        SolverLangItem::CallRefFuture => LangItem::CallRefFuture,
        SolverLangItem::CoroutineReturn => LangItem::CoroutineReturn,
        SolverLangItem::CoroutineYield => LangItem::CoroutineYield,
        SolverLangItem::DynMetadata => LangItem::DynMetadata,
        SolverLangItem::FieldBase => LangItem::FieldBase,
        SolverLangItem::FieldType => LangItem::FieldType,
        SolverLangItem::FutureOutput => LangItem::FutureOutput,
        SolverLangItem::Metadata => LangItem::Metadata,
    }
}
fn lang_item_to_solver_lang_item(lang_item: LangItem)
    -> Option<SolverLangItem> {
    Some(match lang_item {
            LangItem::AsyncFnKindUpvars => SolverLangItem::AsyncFnKindUpvars,
            LangItem::AsyncFnOnceOutput => SolverLangItem::AsyncFnOnceOutput,
            LangItem::CallOnceFuture => SolverLangItem::CallOnceFuture,
            LangItem::CallRefFuture => SolverLangItem::CallRefFuture,
            LangItem::CoroutineReturn => SolverLangItem::CoroutineReturn,
            LangItem::CoroutineYield => SolverLangItem::CoroutineYield,
            LangItem::DynMetadata => SolverLangItem::DynMetadata,
            LangItem::FieldBase => SolverLangItem::FieldBase,
            LangItem::FieldType => SolverLangItem::FieldType,
            LangItem::FutureOutput => SolverLangItem::FutureOutput,
            LangItem::Metadata => SolverLangItem::Metadata,
            _ => return None,
        })
}bidirectional_lang_item_map! {
757    SolverLangItem, fn lang_item_to_solver_lang_item, fn solver_lang_item_to_lang_item;
758
759// tidy-alphabetical-start
760    AsyncFnKindUpvars,
761    AsyncFnOnceOutput,
762    CallOnceFuture,
763    CallRefFuture,
764    CoroutineReturn,
765    CoroutineYield,
766    DynMetadata,
767    FieldBase,
768    FieldType,
769    FutureOutput,
770    Metadata,
771// tidy-alphabetical-end
772}
773
774fn solver_adt_lang_item_to_lang_item(lang_item: SolverAdtLangItem)
    -> LangItem {
    match lang_item {
        SolverAdtLangItem::Option => LangItem::Option,
        SolverAdtLangItem::Poll => LangItem::Poll,
    }
}
fn lang_item_to_solver_adt_lang_item(lang_item: LangItem)
    -> Option<SolverAdtLangItem> {
    Some(match lang_item {
            LangItem::Option => SolverAdtLangItem::Option,
            LangItem::Poll => SolverAdtLangItem::Poll,
            _ => return None,
        })
}bidirectional_lang_item_map! {
775    SolverAdtLangItem, fn lang_item_to_solver_adt_lang_item, fn solver_adt_lang_item_to_lang_item;
776
777// tidy-alphabetical-start
778    Option,
779    Poll,
780// tidy-alphabetical-end
781}
782
783fn 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::AsyncFnOnceOutput => LangItem::AsyncFnOnceOutput,
        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::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::AsyncFnOnceOutput =>
                SolverTraitLangItem::AsyncFnOnceOutput,
            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::Tuple => SolverTraitLangItem::Tuple,
            LangItem::Unpin => SolverTraitLangItem::Unpin,
            LangItem::Unsize => SolverTraitLangItem::Unsize,
            _ => return None,
        })
}bidirectional_lang_item_map! {
784    SolverTraitLangItem, fn lang_item_to_solver_trait_lang_item, fn solver_trait_lang_item_to_lang_item;
785
786// tidy-alphabetical-start
787    AsyncFn,
788    AsyncFnKindHelper,
789    AsyncFnMut,
790    AsyncFnOnce,
791    AsyncFnOnceOutput,
792    AsyncIterator,
793    BikeshedGuaranteedNoDrop,
794    Clone,
795    Copy,
796    Coroutine,
797    Destruct,
798    DiscriminantKind,
799    Drop,
800    Field,
801    Fn,
802    FnMut,
803    FnOnce,
804    FnPtrTrait,
805    FusedIterator,
806    Future,
807    Iterator,
808    MetaSized,
809    PointeeSized,
810    PointeeTrait,
811    Sized,
812    TransmuteTrait,
813    TrivialClone,
814    Tuple,
815    Unpin,
816    Unsize,
817// tidy-alphabetical-end
818}