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