Skip to main content

rustc_next_trait_solver/solve/
select_assoc_candidate.rs

1use std::debug_assert_matches;
2
3use rustc_type_ir::fast_reject::DeepRejectCtxt;
4use rustc_type_ir::inherent::*;
5use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverProjectionLangItem, SolverTraitLangItem};
6use rustc_type_ir::solve::{
7    FetchEligibleAssocItemResponse, NoSolutionOrRerunNonErased, QueryResultOrRerunNonErased,
8    RerunNonErased, RerunReason, RerunResultExt,
9};
10use rustc_type_ir::{
11    self as ty, CallerBoundsIterator, Const, FieldInfo, Interner, PredicateKind, Region,
12    SelectAssocCandidate, Unnormalized, Upcast as _,
13};
14use tracing::instrument;
15
16use crate::delegate::SolverDelegate;
17use crate::solve::assembly::structural_traits::{self, AsyncCallableRelevantTypes};
18use crate::solve::assembly::{self, Candidate};
19use crate::solve::inspect::ProbeKind;
20use crate::solve::{
21    BuiltinImplSource, CandidateSource, Certainty, EvalCtxt, Goal, GoalSource, MaybeInfo,
22    NoSolution, SizedTraitKind,
23};
24
25impl<D, I> EvalCtxt<'_, D>
26where
27    D: SolverDelegate<Interner = I>,
28    I: Interner,
29{
30    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::TRACE <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("compute_select_assoc_candidate_goal",
                                "rustc_next_trait_solver::solve::select_assoc_candidate",
                                ::tracing::Level::TRACE,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/select_assoc_candidate.rs"),
                                ::tracing_core::__macro_support::Option::Some(30u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::select_assoc_candidate"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("goal")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("goal");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                QueryResultOrRerunNonErased<I> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if true {
                            if !self.term_is_fully_unconstrained(goal) {
                                ::core::panicking::panic("assertion failed: self.term_is_fully_unconstrained(goal)")
                            };
                        };
                        if true {
                            {
                                match goal.predicate.alias.kind {
                                    ty::AliasTermKind::ProjectionTy { .. } |
                                        ty::AliasTermKind::ProjectionConst { .. } => {}
                                    ref left_val => {
                                        ::core::panicking::assert_matches_failed(left_val,
                                            "ty::AliasTermKind::ProjectionTy { .. } |\nty::AliasTermKind::ProjectionConst { .. }",
                                            ::core::option::Option::None);
                                    }
                                }
                            };
                        };
                        let cx = self.cx();
                        let trait_ref = goal.predicate.alias.trait_ref(cx);
                        let (_, proven_via) =
                            self.probe(|_|
                                            ProbeKind::ShadowedEnvProbing).enter(|ecx|
                                        {
                                            let trait_goal: Goal<I, ty::TraitClause<I>> =
                                                goal.with(cx, trait_ref);
                                            ecx.compute_trait_goal(trait_goal)
                                        })?;
                        self.assemble_and_merge_candidates(proven_via, goal,
                            |ecx|
                                {
                                    for arg in goal.predicate.alias.own_args(cx).iter() {
                                        let Some(term) = arg.as_term() else { continue; };
                                        match ecx.structurally_normalize_term(goal.param_env, term)
                                            {
                                            Ok(term) => {
                                                if term.is_infer() {
                                                    return Some(ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS));
                                                }
                                            }
                                            Err(e @
                                                (NoSolutionOrRerunNonErased::NoSolution(NoSolution) |
                                                NoSolutionOrRerunNonErased::RerunNonErased(_))) => {
                                                return Some(Err(e));
                                            }
                                        }
                                    }
                                    None
                                },
                            |ecx|
                                {
                                    ecx.probe(|&result|
                                                ProbeKind::RigidAlias {
                                                    result,
                                                }).enter(|this|
                                            {
                                                this.instantiate_select_assoc_candidate_as_rigid(goal)?;
                                                this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                                            })
                                })
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/select_assoc_candidate.rs:30",
                        "rustc_next_trait_solver::solve::select_assoc_candidate",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_next_trait_solver/src/solve/select_assoc_candidate.rs"),
                        ::tracing_core::__macro_support::Option::Some(30u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::select_assoc_candidate"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "trace", skip(self), ret)]
31    pub(super) fn compute_select_assoc_candidate_goal(
32        &mut self,
33        goal: Goal<I, SelectAssocCandidate<I>>,
34    ) -> QueryResultOrRerunNonErased<I> {
35        debug_assert!(self.term_is_fully_unconstrained(goal));
36        debug_assert_matches!(
37            goal.predicate.alias.kind,
38            ty::AliasTermKind::ProjectionTy { .. } | ty::AliasTermKind::ProjectionConst { .. }
39        );
40
41        let cx = self.cx();
42
43        let trait_ref = goal.predicate.alias.trait_ref(cx);
44        let (_, proven_via) = self.probe(|_| ProbeKind::ShadowedEnvProbing).enter(|ecx| {
45            let trait_goal: Goal<I, ty::TraitClause<I>> = goal.with(cx, trait_ref);
46            ecx.compute_trait_goal(trait_goal)
47        })?;
48        self.assemble_and_merge_candidates(
49            proven_via,
50            goal,
51            |ecx| {
52                // FIXME(generic_associated_types): Addresses aggressive inference in #92917.
53                //
54                // If this type is a GAT with currently unconstrained arguments, we do not
55                // want to normalize it via a candidate which only applies for a specific
56                // instantiation. We could otherwise keep the GAT as rigid and succeed this way.
57                // See tests/ui/generic-associated-types/no-incomplete-gat-arg-inference.rs.
58                //
59                // This only avoids normalization if a GAT argument is fully unconstrained.
60                // This is quite arbitrary but fixing it causes some ambiguity, see #125196.
61                for arg in goal.predicate.alias.own_args(cx).iter() {
62                    let Some(term) = arg.as_term() else {
63                        continue;
64                    };
65                    match ecx.structurally_normalize_term(goal.param_env, term) {
66                        Ok(term) => {
67                            if term.is_infer() {
68                                return Some(ecx.evaluate_added_goals_and_make_canonical_response(
69                                    Certainty::AMBIGUOUS,
70                                ));
71                            }
72                        }
73                        Err(
74                            e @ (NoSolutionOrRerunNonErased::NoSolution(NoSolution)
75                            | NoSolutionOrRerunNonErased::RerunNonErased(_)),
76                        ) => {
77                            return Some(Err(e));
78                        }
79                    }
80                }
81
82                None
83            },
84            |ecx| {
85                ecx.probe(|&result| ProbeKind::RigidAlias { result }).enter(|this| {
86                    this.instantiate_select_assoc_candidate_as_rigid(goal)?;
87                    this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
88                })
89            },
90        )
91    }
92
93    /// When normalizing a const alias, register a `ConstArgHasType` goal
94    /// to ensure the const value's type matches the declared type.
95    pub fn push_const_arg_has_type_goal(
96        &mut self,
97        param_env: I::ParamEnv,
98        alias: ty::AliasTerm<I>,
99        term: I::Term,
100    ) -> Result<(), NoSolutionOrRerunNonErased> {
101        if let Some(ct) = term.as_const() {
102            let cx = self.cx();
103            let expected_ty = alias.expect_ct().type_of(cx).skip_norm_wip();
104            self.add_goal(
105                GoalSource::Misc,
106                Goal {
107                    param_env,
108                    predicate: ty::ClauseKind::ConstArgHasType(ct, expected_ty).upcast(cx),
109                },
110            )?;
111        }
112        Ok(())
113    }
114
115    /// When normalizing an associated item, constrain the expected term to `value`.
116    ///
117    /// Additionally, when `value` is a const, this registers a `ConstArgHasType`
118    /// goal to ensure that the const value's type matches the declared type of
119    /// the alias it was normalized from.
120    ///
121    /// You may reasonably wonder: shouldn't `wfcheck::check_type_const` already
122    /// catch any such type mismatch at the definition site, so that the
123    /// definition is tainted and we never even attempt to normalize a reference
124    /// to it? In principle that's exactly what should happen. However, we cannot
125    /// simply force the defining item's wfcheck to run before all uses are
126    /// normalized: wfcheck itself may depend on typeck, trait solving, and
127    /// normalization, so enforcing such a strict ordering would easily create
128    /// query cycles.
129    ///
130    /// However, when CTFE runs on a MIR body, normalizing a type const within
131    /// that body can change the type of the resulting value, causing the MIR
132    /// to become ill-formed. If `check_type_const` for that alias has not yet
133    /// reported its error, no prior error has been recorded and MIR validation
134    /// fires a `span_bug!`. Registering the obligation here ensures the type
135    /// mismatch is reported during normalization itself, tainting the MIR
136    /// before validation runs.
137    fn instantiate_select_assoc_candidate_term(
138        &mut self,
139        goal: Goal<I, SelectAssocCandidate<I>>,
140        value: I::Term,
141    ) -> Result<(), NoSolutionOrRerunNonErased> {
142        self.push_const_arg_has_type_goal(goal.param_env, goal.predicate.alias, value)?;
143        // While `goal.predicate.term` should always be a fully unconstrained inference variable,
144        // `eq` can still fail if `value` is not fully normalized, due to `eq` eagerly normalizing,
145        // and that normalization can fail.
146        self.eq(goal.param_env, goal.predicate.term, value)?;
147        Ok(())
148    }
149
150    fn instantiate_select_assoc_candidate_as_rigid(
151        &mut self,
152        goal: Goal<I, SelectAssocCandidate<I>>,
153    ) -> Result<(), NoSolutionOrRerunNonErased> {
154        self.eq(
155            goal.param_env,
156            goal.predicate.term,
157            goal.predicate.alias.to_term(self.cx(), ty::IsRigid::Yes),
158        )
159    }
160}
161
162impl<D, I> assembly::GoalKind<D> for SelectAssocCandidate<I>
163where
164    D: SolverDelegate<Interner = I>,
165    I: Interner,
166{
167    fn self_ty(self) -> I::Ty {
168        self.self_ty()
169    }
170
171    fn trait_ref(self, cx: I) -> ty::TraitRef<I> {
172        self.alias.trait_ref(cx)
173    }
174
175    fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self {
176        self.with_replaced_self_ty(cx, self_ty)
177    }
178
179    fn trait_def_id(self, cx: I) -> I::TraitId {
180        self.trait_def_id(cx)
181    }
182
183    fn non_fast_rejected_caller_bounds(
184        ecx: &mut EvalCtxt<'_, D>,
185        goal: Goal<I, Self>,
186    ) -> impl Iterator<Item = ty::Binder<I, ty::ClauseKind<I>>> {
187        goal.param_env.caller_bounds().non_trait_clauses().iter().filter_map(move |assumption| {
188            match Self::fast_reject_assumption(ecx, goal, assumption) {
189                Ok(()) => Some(assumption.kind()),
190                Err(NoSolution) => None,
191            }
192        })
193    }
194
195    fn fast_reject_assumption(
196        ecx: &mut EvalCtxt<'_, D>,
197        goal: Goal<I, Self>,
198        assumption: I::Clause,
199    ) -> Result<(), NoSolution> {
200        let alias_def_id = match goal.predicate.alias.kind {
201            ty::AliasTermKind::ProjectionTy { def_id } => def_id.into(),
202            ty::AliasTermKind::ProjectionConst { def_id } => def_id.into(),
203            _ => return Err(NoSolution),
204        };
205        if let Some(projection_pred) = assumption.as_projection_clause()
206            && projection_pred.item_def_id() == alias_def_id
207            && DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify(
208                goal.predicate.alias.args,
209                projection_pred.skip_binder().projection_term.args,
210            )
211        {
212            Ok(())
213        } else {
214            Err(NoSolution)
215        }
216    }
217
218    fn match_assumption(
219        ecx: &mut EvalCtxt<'_, D>,
220        goal: Goal<I, Self>,
221        assumption: ty::Binder<I, ty::ClauseKind<I>>,
222        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
223    ) -> QueryResultOrRerunNonErased<I> {
224        let cx = ecx.cx();
225        let projection_pred = assumption
226            .map_bound(|i| match i {
227                ty::ClauseKind::Projection(p) => Some(p),
228                _ => None,
229            })
230            .transpose()
231            .unwrap();
232
233        let assumption_projection_pred = ecx.instantiate_binder_with_infer(projection_pred);
234        ecx.eq(goal.param_env, goal.predicate.alias, assumption_projection_pred.projection_term)?;
235
236        ecx.instantiate_select_assoc_candidate_term(goal, assumption_projection_pred.term)?;
237
238        // Add GAT where clauses from the trait's definition
239        // FIXME: We don't need these, since these are the type's own WF obligations.
240        ecx.add_goals(
241            GoalSource::AliasWellFormed,
242            cx.own_clauses_of(goal.predicate.alias.expect_projection_def_id().into())
243                .iter_instantiated(cx, goal.predicate.alias.args)
244                .map(Unnormalized::skip_norm_wip)
245                .map(|clause| goal.with(cx, clause)),
246        )?;
247
248        then(ecx)
249    }
250
251    // Hack for trait-system-refactor-initiative#245.
252    // FIXME(-Zhigher-ranked-assumptions): this impl differs from trait goals and we should unify
253    // them again once we properly support binders.
254    fn probe_and_consider_object_bound_candidate(
255        ecx: &mut EvalCtxt<'_, D>,
256        source: CandidateSource<I>,
257        goal: Goal<I, Self>,
258        assumption: I::Clause,
259    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
260        Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| {
261            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
262        })
263    }
264
265    fn consider_additional_alias_assumptions(
266        _ecx: &mut EvalCtxt<'_, D>,
267        _goal: Goal<I, Self>,
268        _alias_ty: ty::AliasTy<I>,
269    ) -> Vec<Candidate<I>> {
270        ::alloc::vec::Vec::new()vec![]
271    }
272
273    fn consider_impl_candidate(
274        ecx: &mut EvalCtxt<'_, D>,
275        goal: Goal<I, SelectAssocCandidate<I>>,
276        goal_trait_ref: ty::TraitRef<I>,
277        impl_def_id: I::ImplId,
278        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
279    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
280        let cx = ecx.cx();
281
282        // We have to ignore negative impls when projecting.
283        let impl_polarity = cx.impl_polarity(impl_def_id);
284        match impl_polarity {
285            ty::ImplPolarity::Negative => return Err(NoSolution.into()),
286            ty::ImplPolarity::Positive => {}
287        };
288
289        ecx.probe_trait_candidate(CandidateSource::Impl(impl_def_id)).enter(|ecx| {
290            let impl_args = ecx.fresh_args_for_item(impl_def_id.into());
291            let impl_trait_ref = cx.impl_trait_ref(impl_def_id);
292            let impl_trait_ref = impl_trait_ref.instantiate(cx, impl_args).skip_norm_wip();
293
294            ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?;
295
296            let where_clause_bounds = cx
297                .clauses_of(impl_def_id.into())
298                .iter_instantiated(cx, impl_args)
299                .map(Unnormalized::skip_norm_wip)
300                .map(|clause| goal.with(cx, clause));
301            ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds)?;
302
303            // Bail if the nested goals don't hold here. This is to avoid unnecessarily
304            // computing the `type_of` query for associated types that never apply, as
305            // this may result in query cycles in the case of RPITITs.
306            // See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/185>.
307            ecx.try_evaluate_added_goals()?;
308
309            // Add GAT where clauses from the trait's definition. This is necessary
310            // for soundness until we properly handle implied bounds on binders,
311            // see tests/ui/generic-associated-types/must-prove-where-clauses-on-norm.rs.
312            let alias_def_id = goal.predicate.alias.expect_projection_def_id();
313            ecx.add_goals(
314                GoalSource::AliasWellFormed,
315                cx.own_clauses_of(alias_def_id.into())
316                    .iter_instantiated(cx, goal.predicate.alias.args)
317                    .map(Unnormalized::skip_norm_wip)
318                    .map(|clause| goal.with(cx, clause)),
319            )?;
320
321            let error_response = |ecx: &mut EvalCtxt<'_, D>, guar| {
322                let error_term = match goal.predicate.alias.kind {
323                    ty::AliasTermKind::ProjectionTy { .. } => Ty::new_error(cx, guar).into(),
324                    ty::AliasTermKind::ProjectionConst { .. } => Const::new_error(cx, guar).into(),
325                    kind => {
    ::core::panicking::panic_fmt(format_args!("expected projection, found {0:?}",
            kind));
}panic!("expected projection, found {kind:?}"),
326                };
327                ecx.instantiate_select_assoc_candidate_term(goal, error_term)?;
328                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
329            };
330
331            let target_item_def_id =
332                match ecx.fetch_eligible_assoc_item(goal_trait_ref, alias_def_id, impl_def_id) {
333                    FetchEligibleAssocItemResponse::Found(target_item_def_id) => target_item_def_id,
334                    FetchEligibleAssocItemResponse::NotFound(tm) => {
335                        match tm {
336                            // In case the associated item is hidden due to specialization,
337                            // normalizing this associated item is always ambiguous. Treating
338                            // the associated item as rigid would be incomplete and allow for
339                            // overlapping impls, see #105782.
340                            //
341                            // As this ambiguity is unavoidable we emit a nested ambiguous
342                            // goal instead of using `Certainty::AMBIGUOUS`. This allows us to
343                            // return the nested goals to the parent `AliasRelate` goal. This
344                            // would be relevant if any of the nested goals refer to the `term`.
345                            // This is not the case here and we only prefer adding an ambiguous
346                            // nested goal for consistency.
347                            ty::TypingMode::Coherence => {
348                                ecx.add_goal(
349                                    GoalSource::Misc,
350                                    goal.with(cx, PredicateKind::Ambiguous),
351                                )?;
352                                return ecx.evaluate_added_goals_and_make_canonical_response(
353                                    Certainty::Yes,
354                                );
355                            }
356                            // Outside of coherence, we treat the associated item as rigid instead.
357                            ty::TypingMode::Typeck { .. }
358                            | ty::TypingMode::PostTypeckThroughBorrowck { .. }
359                            | ty::TypingMode::PostBorrowck { .. }
360                            | ty::TypingMode::PostAnalysis
361                            | ty::TypingMode::Reflection
362                            | ty::TypingMode::Codegen => {
363                                ecx.instantiate_select_assoc_candidate_as_rigid(goal)?;
364                                return ecx.evaluate_added_goals_and_make_canonical_response(
365                                    Certainty::Yes,
366                                );
367                            }
368                        };
369                    }
370                    FetchEligibleAssocItemResponse::Err(guar) => return error_response(ecx, guar),
371                    FetchEligibleAssocItemResponse::NotFoundBecauseErased => {
372                        match ecx
373                            .opaque_accesses
374                            .rerun_always(RerunReason::FetchEligibleAssocItem)? {}
375                    }
376                };
377
378            if !cx.has_item_definition(target_item_def_id) {
379                // If the impl is missing an item, it's either because the user forgot to
380                // provide it, or the user is not *obligated* to provide it (because it
381                // has a trivially false `Sized` predicate). If it's the latter, we cannot
382                // delay a bug because we can have trivially false where clauses, so we
383                // treat it as rigid.
384                if cx.impl_self_is_guaranteed_unsized(impl_def_id) {
385                    if ecx.typing_mode().is_coherence() {
386                        // Trying to normalize such associated items is always ambiguous
387                        // during coherence to avoid cyclic reasoning. See the example in
388                        // tests/ui/traits/trivial-unsized-projection-in-coherence.rs.
389                        //
390                        // As this ambiguity is unavoidable we emit a nested ambiguous
391                        // goal instead of using `Certainty::AMBIGUOUS`. This allows us to
392                        // return the nested goals to the parent `AliasRelate` goal. This
393                        // would be relevant if any of the nested goals refer to the `term`.
394                        // This is not the case here and we only prefer adding an ambiguous
395                        // nested goal for consistency.
396                        ecx.add_goal(GoalSource::Misc, goal.with(cx, PredicateKind::Ambiguous))?;
397                        return then(ecx);
398                    } else {
399                        ecx.instantiate_select_assoc_candidate_as_rigid(goal)?;
400                        return then(ecx);
401                    }
402                } else {
403                    return error_response(ecx, cx.delay_bug("missing item"));
404                }
405            }
406
407            let target_container_def_id = cx.impl_or_trait_assoc_term_parent(target_item_def_id);
408
409            // Getting the right args here is complex, e.g. given:
410            // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>`
411            // - the applicable impl `impl<T> Trait<i32> for Vec<T>`
412            // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>`
413            //
414            // We first rebase the goal args onto the impl, going from `[Vec<u32>, i32, u64]`
415            // to `[u32, u64]`.
416            //
417            // And then map these args to the args of the defining impl of `Assoc`, going
418            // from `[u32, u64]` to `[u32, i32, u64]`.
419            let target_args = ecx.translate_args(
420                goal,
421                impl_def_id,
422                impl_args,
423                impl_trait_ref,
424                target_container_def_id,
425            )?;
426
427            let target_item_def_id: I::DefId = target_item_def_id.into();
428
429            let target_item_kind = if goal.predicate.alias.kind.is_type() {
430                ty::AliasTermKind::ProjectionTy { def_id: target_item_def_id.try_into().unwrap() }
431            } else {
432                ty::AliasTermKind::ProjectionConst {
433                    def_id: target_item_def_id.try_into().unwrap(),
434                }
435            };
436
437            if !cx.check_alias_term_args_compatible(target_item_kind, target_args) {
438                return error_response(
439                    ecx,
440                    cx.delay_bug("associated item has mismatched arguments"),
441                );
442            }
443
444            // Finally we construct the actual value of the associated type.
445            let term = match target_item_kind {
446                ty::AliasTermKind::ProjectionTy { .. } => {
447                    let t = cx.type_of(target_item_def_id).instantiate(cx, target_args);
448                    let t = ecx.normalize(goal.param_env, t)?;
449                    t.into()
450                }
451                ty::AliasTermKind::ProjectionConst { def_id }
452                    if let Some(c) =
453                        cx.const_of_item(ty::AliasConstKind::Projection { def_id }) =>
454                {
455                    let c = c.instantiate(cx, target_args);
456                    let c = ecx.normalize(goal.param_env, c)?;
457                    c.into()
458                }
459                ty::AliasTermKind::ProjectionConst { .. } => {
460                    let alias_const = ty::AliasConst::new(
461                        cx,
462                        ty::AliasConstKind::Projection {
463                            def_id: target_item_def_id.try_into().unwrap(),
464                        },
465                        target_args,
466                    );
467                    return ecx.evaluate_const(
468                        goal.param_env,
469                        goal.predicate.alias,
470                        goal.predicate.term,
471                        alias_const,
472                    );
473                }
474                kind => {
    ::core::panicking::panic_fmt(format_args!("expected projection, found {0:?}",
            kind));
}panic!("expected projection, found {kind:?}"),
475            };
476
477            ecx.instantiate_select_assoc_candidate_term(goal, term)?;
478            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
479        })
480    }
481
482    /// Fail to normalize if the predicate contains an error, alternatively, we could normalize to `ty::Error`
483    /// and succeed. Can experiment with this to figure out what results in better error messages.
484    fn consider_error_guaranteed_candidate(
485        ecx: &mut EvalCtxt<'_, D>,
486        goal: Goal<I, Self>,
487        guar: I::ErrorGuaranteed,
488    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
489        let cx = ecx.cx();
490        let error_term = match goal.predicate.alias.kind {
491            ty::AliasTermKind::ProjectionTy { .. } => Ty::new_error(cx, guar).into(),
492            ty::AliasTermKind::ProjectionConst { .. } => Const::new_error(cx, guar).into(),
493            kind => {
    ::core::panicking::panic_fmt(format_args!("expected projection, found {0:?}",
            kind));
}panic!("expected projection, found {kind:?}"),
494        };
495
496        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
497            ecx.instantiate_select_assoc_candidate_term(goal, error_term)?;
498            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
499        })
500    }
501
502    fn consider_auto_trait_candidate(
503        ecx: &mut EvalCtxt<'_, D>,
504        _goal: Goal<I, Self>,
505    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
506        ecx.cx().delay_bug("associated types not allowed on auto traits");
507        Err(NoSolution.into())
508    }
509
510    fn consider_trait_alias_candidate(
511        _ecx: &mut EvalCtxt<'_, D>,
512        goal: Goal<I, Self>,
513    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
514        {
    ::core::panicking::panic_fmt(format_args!("trait aliases do not have associated types: {0:?}",
            goal));
};panic!("trait aliases do not have associated types: {:?}", goal);
515    }
516
517    fn consider_builtin_sizedness_candidates(
518        _ecx: &mut EvalCtxt<'_, D>,
519        goal: Goal<I, Self>,
520        _sizedness: SizedTraitKind,
521    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
522        {
    ::core::panicking::panic_fmt(format_args!("`Sized`/`MetaSized` does not have an associated type: {0:?}",
            goal));
};panic!("`Sized`/`MetaSized` does not have an associated type: {:?}", goal);
523    }
524
525    fn consider_builtin_copy_clone_candidate(
526        _ecx: &mut EvalCtxt<'_, D>,
527        goal: Goal<I, Self>,
528    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
529        {
    ::core::panicking::panic_fmt(format_args!("`Copy`/`Clone` does not have an associated type: {0:?}",
            goal));
};panic!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
530    }
531
532    fn consider_builtin_fn_ptr_trait_candidate(
533        _ecx: &mut EvalCtxt<'_, D>,
534        goal: Goal<I, Self>,
535    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
536        {
    ::core::panicking::panic_fmt(format_args!("`FnPtr` does not have an associated type: {0:?}",
            goal));
};panic!("`FnPtr` does not have an associated type: {:?}", goal);
537    }
538
539    fn consider_builtin_fn_static_trait_candidate(
540        _ecx: &mut EvalCtxt<'_, D>,
541        goal: Goal<I, Self>,
542    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
543        {
    ::core::panicking::panic_fmt(format_args!("`FnStatic` does not have an associated type: {0:?}",
            goal));
};panic!("`FnStatic` does not have an associated type: {:?}", goal);
544    }
545
546    fn consider_builtin_fn_trait_candidates(
547        ecx: &mut EvalCtxt<'_, D>,
548        goal: Goal<I, Self>,
549        goal_kind: ty::ClosureKind,
550    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
551        let cx = ecx.cx();
552        let Some(tupled_inputs_and_output) =
553            structural_traits::extract_tupled_inputs_and_output_from_callable(
554                cx,
555                goal.predicate.self_ty(),
556                goal_kind,
557            )?
558        else {
559            return ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS);
560        };
561        let (inputs, output) = ecx.instantiate_binder_with_infer(tupled_inputs_and_output);
562
563        // A built-in `Fn` impl only holds if the output is sized.
564        // (FIXME: technically we only need to check this if the type is a fn ptr...)
565        let output_is_sized_pred =
566            ty::TraitRef::new(cx, cx.require_trait_lang_item(SolverTraitLangItem::Sized), [output]);
567
568        let pred = ty::ProjectionClause {
569            projection_term: ty::AliasTerm::new(
570                cx,
571                goal.predicate.alias.kind,
572                [goal.predicate.self_ty(), inputs],
573            ),
574            term: output.into(),
575        }
576        .upcast(cx);
577
578        Self::probe_and_consider_implied_clause(
579            ecx,
580            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
581            goal,
582            pred,
583            [(GoalSource::ImplWhereBound, goal.with(cx, output_is_sized_pred))],
584        )
585    }
586
587    fn consider_builtin_async_fn_trait_candidates(
588        ecx: &mut EvalCtxt<'_, D>,
589        goal: Goal<I, Self>,
590        goal_kind: ty::ClosureKind,
591    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
592        let cx = ecx.cx();
593        let def_id = goal.predicate.alias.expect_projection_ty_def_id();
594
595        let env_region = match goal_kind {
596            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => goal.predicate.alias.args.region_at(2),
597            // Doesn't matter what this region is
598            ty::ClosureKind::FnOnce => Region::new_static(cx),
599        };
600        let (tupled_inputs_and_output_and_coroutine, nested_preds) =
601            structural_traits::extract_tupled_inputs_and_output_from_async_callable(
602                cx,
603                goal.predicate.self_ty(),
604                goal_kind,
605                env_region,
606            )?;
607        let AsyncCallableRelevantTypes {
608            tupled_inputs_ty,
609            output_coroutine_ty,
610            coroutine_return_ty,
611        } = ecx.instantiate_binder_with_infer(tupled_inputs_and_output_and_coroutine);
612
613        // A built-in `AsyncFn` impl only holds if the output is sized.
614        // (FIXME: technically we only need to check this if the type is a fn ptr...)
615        let output_is_sized_pred = ty::TraitRef::new(
616            cx,
617            cx.require_trait_lang_item(SolverTraitLangItem::Sized),
618            [output_coroutine_ty],
619        );
620
621        let (projection_term, term) = if cx
622            .is_projection_lang_item(def_id, SolverProjectionLangItem::CallOnceFuture)
623        {
624            (
625                ty::AliasTerm::new(
626                    cx,
627                    goal.predicate.alias.kind,
628                    [goal.predicate.self_ty(), tupled_inputs_ty],
629                ),
630                output_coroutine_ty.into(),
631            )
632        } else if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::CallRefFuture) {
633            (
634                ty::AliasTerm::new(
635                    cx,
636                    goal.predicate.alias.kind,
637                    [
638                        I::GenericArg::from(goal.predicate.self_ty()),
639                        tupled_inputs_ty.into(),
640                        env_region.into(),
641                    ],
642                ),
643                output_coroutine_ty.into(),
644            )
645        } else if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::AsyncFnOnceOutput) {
646            (
647                ty::AliasTerm::new(
648                    cx,
649                    goal.predicate.alias.kind,
650                    [goal.predicate.self_ty(), tupled_inputs_ty],
651                ),
652                coroutine_return_ty.into(),
653            )
654        } else {
655            {
    ::core::panicking::panic_fmt(format_args!("no such associated type in `AsyncFn*`: {0:?}",
            def_id));
}panic!("no such associated type in `AsyncFn*`: {:?}", def_id)
656        };
657        let pred = ty::ProjectionClause { projection_term, term }.upcast(cx);
658
659        Self::probe_and_consider_implied_clause(
660            ecx,
661            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
662            goal,
663            pred,
664            [goal.with(cx, output_is_sized_pred)]
665                .into_iter()
666                .chain(nested_preds.into_iter().map(|pred| goal.with(cx, pred)))
667                .map(|goal| (GoalSource::ImplWhereBound, goal)),
668        )
669    }
670
671    fn consider_builtin_async_fn_kind_helper_candidate(
672        ecx: &mut EvalCtxt<'_, D>,
673        goal: Goal<I, Self>,
674    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
675        let [
676            closure_fn_kind_ty,
677            goal_kind_ty,
678            borrow_region,
679            tupled_inputs_ty,
680            tupled_upvars_ty,
681            coroutine_captures_by_ref_ty,
682        ] = *goal.predicate.alias.args.as_slice()
683        else {
684            ::core::panicking::panic_default_msg();panic!();
685        };
686
687        // Bail if the upvars haven't been constrained.
688        if tupled_upvars_ty.expect_ty().is_ty_var() {
689            return ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS);
690        }
691
692        let Some(closure_kind) = closure_fn_kind_ty.expect_ty().to_opt_closure_kind() else {
693            // We don't need to worry about the self type being an infer var.
694            return Err(NoSolution.into());
695        };
696        let Some(goal_kind) = goal_kind_ty.expect_ty().to_opt_closure_kind() else {
697            return Err(NoSolution.into());
698        };
699        if !closure_kind.extends(goal_kind) {
700            return Err(NoSolution.into());
701        }
702
703        let upvars_ty = ty::CoroutineClosureSignature::tupled_upvars_by_closure_kind(
704            ecx.cx(),
705            goal_kind,
706            tupled_inputs_ty.expect_ty(),
707            tupled_upvars_ty.expect_ty(),
708            coroutine_captures_by_ref_ty.expect_ty(),
709            borrow_region.expect_region(),
710        );
711
712        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
713            ecx.instantiate_select_assoc_candidate_term(goal, upvars_ty.into())?;
714            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
715        })
716    }
717
718    fn consider_builtin_tuple_candidate(
719        _ecx: &mut EvalCtxt<'_, D>,
720        goal: Goal<I, Self>,
721    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
722        {
    ::core::panicking::panic_fmt(format_args!("`Tuple` does not have an associated type: {0:?}",
            goal));
};panic!("`Tuple` does not have an associated type: {:?}", goal);
723    }
724
725    fn consider_builtin_pointee_candidate(
726        ecx: &mut EvalCtxt<'_, D>,
727        goal: Goal<I, Self>,
728    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
729        let cx = ecx.cx();
730        let metadata_def_id = cx.require_projection_lang_item(SolverProjectionLangItem::Metadata);
731        {
    match (&ty::AliasTermKind::ProjectionTy { def_id: metadata_def_id },
            &goal.predicate.alias.kind) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(
732            ty::AliasTermKind::ProjectionTy { def_id: metadata_def_id },
733            goal.predicate.alias.kind
734        );
735        let metadata_ty = match goal.predicate.self_ty().kind() {
736            ty::Bool
737            | ty::Char
738            | ty::Int(..)
739            | ty::Uint(..)
740            | ty::Float(..)
741            | ty::Array(..)
742            | ty::Pat(..)
743            | ty::RawPtr(..)
744            | ty::Ref(..)
745            | ty::FnDef(..)
746            | ty::FnPtr(..)
747            | ty::Closure(..)
748            | ty::CoroutineClosure(..)
749            | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
750            | ty::Coroutine(..)
751            | ty::CoroutineWitness(..)
752            | ty::Never
753            | ty::Foreign(..) => Ty::new_unit(cx),
754
755            ty::Error(e) => Ty::new_error(cx, e),
756
757            ty::Str | ty::Slice(_) => Ty::new_usize(cx),
758
759            ty::Dynamic(_, _) => {
760                let dyn_metadata = cx.require_adt_lang_item(SolverAdtLangItem::DynMetadata);
761                cx.type_of(dyn_metadata.into())
762                    .instantiate(cx, &[I::GenericArg::from(goal.predicate.self_ty())])
763                    .skip_norm_wip()
764            }
765
766            ty::Alias(ty::IsRigid::Yes, _) | ty::Param(_) | ty::Placeholder(..) => {
767                // This is the "fallback impl" for type parameters, unnormalizable projections
768                // and opaque types: If the `self_ty` is `Sized`, then the metadata is `()`.
769                // FIXME(ptr_metadata): This impl overlaps with the other impls and shouldn't
770                // exist. Instead, `Pointee<Metadata = ()>` should be a supertrait of `Sized`.
771                let alias_bound_result = ecx
772                    .probe_builtin_trait_candidate(BuiltinImplSource::Misc)
773                    .enter(|ecx| {
774                        let sized_predicate = ty::TraitRef::new(
775                            cx,
776                            cx.require_trait_lang_item(SolverTraitLangItem::Sized),
777                            [I::GenericArg::from(goal.predicate.self_ty())],
778                        );
779                        ecx.add_goal(GoalSource::Misc, goal.with(cx, sized_predicate))?;
780                        ecx.instantiate_select_assoc_candidate_term(goal, Ty::new_unit(cx).into())?;
781                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
782                    })
783                    .map_err_to_rerun()?;
784
785                // In case the dummy alias-bound candidate does not apply, we instead treat this projection
786                // as rigid.
787                return alias_bound_result.or_else(|NoSolution| {
788                    ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|this| {
789                        this.instantiate_select_assoc_candidate_as_rigid(goal)?;
790                        this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
791                    })
792                });
793            }
794
795            ty::Adt(def, args) if def.is_struct() => match def.struct_tail_ty(cx) {
796                None => Ty::new_unit(cx),
797                Some(tail_ty) => Ty::new_projection(
798                    cx,
799                    ty::IsRigid::No,
800                    metadata_def_id,
801                    [tail_ty.instantiate(cx, args).skip_norm_wip()],
802                ),
803            },
804            ty::Adt(_, _) => Ty::new_unit(cx),
805
806            ty::Tuple(elements) => match elements.last() {
807                None => Ty::new_unit(cx),
808                Some(tail_ty) => {
809                    Ty::new_projection(cx, ty::IsRigid::No, metadata_def_id, [tail_ty])
810                }
811            },
812
813            ty::UnsafeBinder(_) => {
814                // FIXME(unsafe_binder): Figure out how to handle pointee for unsafe binders.
815                ::core::panicking::unimplemented_default_msg()unimplemented!()
816            }
817
818            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
819            | ty::Alias(ty::IsRigid::No, _)
820            | ty::Bound(..) => {
    ::core::panicking::panic_fmt(format_args!("unexpected self ty `{0:?}` when normalizing `<T as Pointee>::Metadata`",
            goal.predicate.self_ty()));
}panic!(
821                "unexpected self ty `{:?}` when normalizing `<T as Pointee>::Metadata`",
822                goal.predicate.self_ty()
823            ),
824
825            // FIXME(scrabsha)
826            ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
827        };
828
829        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
830            ecx.instantiate_select_assoc_candidate_term(goal, metadata_ty.into())?;
831            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
832        })
833    }
834
835    fn consider_builtin_future_candidate(
836        ecx: &mut EvalCtxt<'_, D>,
837        goal: Goal<I, Self>,
838    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
839        let self_ty = goal.predicate.self_ty();
840        let ty::Coroutine(def_id, args) = self_ty.kind() else {
841            return Err(NoSolution.into());
842        };
843
844        // Coroutines are not futures unless they come from `async` desugaring
845        let cx = ecx.cx();
846        if !cx.coroutine_is_async(def_id) {
847            return Err(NoSolution.into());
848        }
849
850        let term = args.as_coroutine().return_ty().into();
851
852        Self::probe_and_consider_implied_clause(
853            ecx,
854            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
855            goal,
856            ty::ProjectionClause {
857                projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.alias.kind, [self_ty]),
858                term,
859            }
860            .upcast(cx),
861            // Technically, we need to check that the future type is Sized,
862            // but that's already proven by the coroutine being WF.
863            [],
864        )
865    }
866
867    fn consider_builtin_iterator_candidate(
868        ecx: &mut EvalCtxt<'_, D>,
869        goal: Goal<I, Self>,
870    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
871        let self_ty = goal.predicate.self_ty();
872        let ty::Coroutine(def_id, args) = self_ty.kind() else {
873            return Err(NoSolution.into());
874        };
875
876        // Coroutines are not Iterators unless they come from `gen` desugaring
877        let cx = ecx.cx();
878        if !cx.coroutine_is_gen(def_id) {
879            return Err(NoSolution.into());
880        }
881
882        let term = args.as_coroutine().yield_ty().into();
883
884        Self::probe_and_consider_implied_clause(
885            ecx,
886            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
887            goal,
888            ty::ProjectionClause {
889                projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.alias.kind, [self_ty]),
890                term,
891            }
892            .upcast(cx),
893            // Technically, we need to check that the iterator type is Sized,
894            // but that's already proven by the generator being WF.
895            [],
896        )
897    }
898
899    fn consider_builtin_fused_iterator_candidate(
900        _ecx: &mut EvalCtxt<'_, D>,
901        goal: Goal<I, Self>,
902    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
903        {
    ::core::panicking::panic_fmt(format_args!("`FusedIterator` does not have an associated type: {0:?}",
            goal));
};panic!("`FusedIterator` does not have an associated type: {:?}", goal);
904    }
905
906    fn consider_builtin_async_iterator_candidate(
907        ecx: &mut EvalCtxt<'_, D>,
908        goal: Goal<I, Self>,
909    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
910        let self_ty = goal.predicate.self_ty();
911        let ty::Coroutine(def_id, args) = self_ty.kind() else {
912            return Err(NoSolution.into());
913        };
914
915        // Coroutines are not AsyncIterators unless they come from `gen` desugaring
916        let cx = ecx.cx();
917        if !cx.coroutine_is_async_gen(def_id) {
918            return Err(NoSolution.into());
919        }
920
921        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
922            let expected_ty = ecx.next_ty_infer();
923            // Take `AsyncIterator<Item = I>` and turn it into the corresponding
924            // coroutine yield ty `Poll<Option<I>>`.
925            let wrapped_expected_ty = Ty::new_adt(
926                cx,
927                cx.adt_def(cx.require_adt_lang_item(SolverAdtLangItem::Poll)),
928                cx.mk_args(&[Ty::new_adt(
929                    cx,
930                    cx.adt_def(cx.require_adt_lang_item(SolverAdtLangItem::Option)),
931                    cx.mk_args(&[expected_ty.into()]),
932                )
933                .into()]),
934            );
935            let yield_ty = args.as_coroutine().yield_ty();
936            ecx.eq(goal.param_env, wrapped_expected_ty, yield_ty)?;
937            ecx.instantiate_select_assoc_candidate_term(goal, expected_ty.into())?;
938            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
939        })
940    }
941
942    fn consider_builtin_coroutine_candidate(
943        ecx: &mut EvalCtxt<'_, D>,
944        goal: Goal<I, Self>,
945    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
946        let self_ty = goal.predicate.self_ty();
947        let ty::Coroutine(def_id, args) = self_ty.kind() else {
948            return Err(NoSolution.into());
949        };
950
951        // `async`-desugared coroutines do not implement the coroutine trait
952        let cx = ecx.cx();
953        if !cx.is_general_coroutine(def_id) {
954            return Err(NoSolution.into());
955        }
956
957        let coroutine = args.as_coroutine();
958        let def_id = goal.predicate.alias.expect_projection_ty_def_id();
959
960        let term = if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::CoroutineReturn)
961        {
962            coroutine.return_ty().into()
963        } else if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::CoroutineYield) {
964            coroutine.yield_ty().into()
965        } else {
966            {
    ::core::panicking::panic_fmt(format_args!("unexpected associated item `{0:?}` for `{1:?}`",
            def_id, self_ty));
}panic!("unexpected associated item `{:?}` for `{self_ty:?}`", def_id)
967        };
968
969        Self::probe_and_consider_implied_clause(
970            ecx,
971            CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
972            goal,
973            ty::ProjectionClause {
974                projection_term: ty::AliasTerm::new(
975                    ecx.cx(),
976                    goal.predicate.alias.kind,
977                    [self_ty, coroutine.resume_ty()],
978                ),
979                term,
980            }
981            .upcast(cx),
982            // Technically, we need to check that the coroutine type is Sized,
983            // but that's already proven by the coroutine being WF.
984            [],
985        )
986    }
987
988    fn consider_structural_builtin_unsize_candidates(
989        _ecx: &mut EvalCtxt<'_, D>,
990        goal: Goal<I, Self>,
991    ) -> Result<Vec<Candidate<I>>, RerunNonErased> {
992        {
    ::core::panicking::panic_fmt(format_args!("`Unsize` does not have an associated type: {0:?}",
            goal));
};panic!("`Unsize` does not have an associated type: {:?}", goal);
993    }
994
995    fn consider_builtin_discriminant_kind_candidate(
996        ecx: &mut EvalCtxt<'_, D>,
997        goal: Goal<I, Self>,
998    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
999        let self_ty = goal.predicate.self_ty();
1000        let discriminant_ty = match self_ty.kind() {
1001            ty::Bool
1002            | ty::Char
1003            | ty::Int(..)
1004            | ty::Uint(..)
1005            | ty::Float(..)
1006            | ty::Array(..)
1007            | ty::Pat(..)
1008            | ty::RawPtr(..)
1009            | ty::Ref(..)
1010            | ty::FnDef(..)
1011            | ty::FnPtr(..)
1012            | ty::Closure(..)
1013            | ty::CoroutineClosure(..)
1014            | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
1015            | ty::Coroutine(..)
1016            | ty::CoroutineWitness(..)
1017            | ty::Never
1018            | ty::Foreign(..)
1019            | ty::Adt(_, _)
1020            | ty::Str
1021            | ty::Slice(_)
1022            | ty::Dynamic(_, _)
1023            | ty::Tuple(_)
1024            | ty::Error(_) => self_ty.discriminant_ty(ecx.cx()),
1025
1026            ty::UnsafeBinder(_) => {
1027                // FIXME(unsafe_binders): instantiate this with placeholders?? i guess??
1028                {
    ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
            format_args!("discr subgoal...")));
}unimplemented!("discr subgoal...")
1029            }
1030
1031            // Given an alias, parameter, or placeholder we add an impl candidate normalizing to a rigid
1032            // alias. In case there's a where-bound further constraining this alias it is preferred over
1033            // this impl candidate anyways. It's still a bit scuffed.
1034            ty::Alias(ty::IsRigid::Yes, _) | ty::Param(_) | ty::Placeholder(..) => {
1035                return ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1036                    ecx.instantiate_select_assoc_candidate_as_rigid(goal)?;
1037                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1038                });
1039            }
1040
1041            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
1042            | ty::Alias(ty::IsRigid::No, _)
1043            | ty::Bound(..) => {
    ::core::panicking::panic_fmt(format_args!("unexpected self ty `{0:?}` when normalizing `<T as DiscriminantKind>::Discriminant`",
            goal.predicate.self_ty()));
}panic!(
1044                "unexpected self ty `{:?}` when normalizing `<T as DiscriminantKind>::Discriminant`",
1045                goal.predicate.self_ty()
1046            ),
1047
1048            // FIXME(scrabsha)
1049            ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
1050        };
1051
1052        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1053            ecx.instantiate_select_assoc_candidate_term(goal, discriminant_ty.into())?;
1054            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1055        })
1056    }
1057
1058    fn consider_builtin_destruct_candidate(
1059        _ecx: &mut EvalCtxt<'_, D>,
1060        goal: Goal<I, Self>,
1061    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1062        {
    ::core::panicking::panic_fmt(format_args!("`Destruct` does not have an associated type: {0:?}",
            goal));
};panic!("`Destruct` does not have an associated type: {:?}", goal);
1063    }
1064
1065    fn consider_builtin_transmute_candidate(
1066        _ecx: &mut EvalCtxt<'_, D>,
1067        goal: Goal<I, Self>,
1068    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1069        {
    ::core::panicking::panic_fmt(format_args!("`TransmuteFrom` does not have an associated type: {0:?}",
            goal));
}panic!("`TransmuteFrom` does not have an associated type: {:?}", goal)
1070    }
1071
1072    fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
1073        _ecx: &mut EvalCtxt<'_, D>,
1074        goal: Goal<I, Self>,
1075    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1076        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`BikeshedGuaranteedNoDrop` does not have an associated type: {0:?}",
                goal)));
}unreachable!("`BikeshedGuaranteedNoDrop` does not have an associated type: {:?}", goal)
1077    }
1078
1079    fn consider_builtin_field_candidate(
1080        ecx: &mut EvalCtxt<'_, D>,
1081        goal: Goal<I, Self>,
1082    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1083        let self_ty = goal.predicate.self_ty();
1084        let ty::Adt(def, args) = self_ty.kind() else {
1085            return Err(NoSolution.into());
1086        };
1087        let Some(FieldInfo { base, ty, .. }) = def.field_representing_type_info(ecx.cx(), args)
1088        else {
1089            return Err(NoSolution.into());
1090        };
1091        let def_id = goal.predicate.alias.expect_projection_ty_def_id();
1092        let ty = match ecx.cx().as_projection_lang_item(def_id) {
1093            Some(SolverProjectionLangItem::FieldBase) => base,
1094            Some(SolverProjectionLangItem::FieldType) => ty,
1095            _ => {
    ::core::panicking::panic_fmt(format_args!("unexpected associated type {0:?} in `Field`",
            goal.predicate));
}panic!("unexpected associated type {:?} in `Field`", goal.predicate),
1096        };
1097        ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1098            ecx.instantiate_select_assoc_candidate_term(goal, ty.into())?;
1099            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1100        })
1101    }
1102
1103    fn consider_builtin_try_as_dyn_candidate(
1104        _ecx: &mut EvalCtxt<'_, D>,
1105        _goal: Goal<I, Self>,
1106    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1107        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("try_as_dyn helper trait doesn\'t have assoc types")));
}unreachable!("try_as_dyn helper trait doesn't have assoc types")
1108    }
1109}
1110
1111impl<D, I> EvalCtxt<'_, D>
1112where
1113    D: SolverDelegate<Interner = I>,
1114    I: Interner,
1115{
1116    fn translate_args(
1117        &mut self,
1118        goal: Goal<I, ty::SelectAssocCandidate<I>>,
1119        impl_def_id: I::ImplId,
1120        impl_args: I::GenericArgs,
1121        impl_trait_ref: rustc_type_ir::TraitRef<I>,
1122        target_container_def_id: I::DefId,
1123    ) -> Result<I::GenericArgs, NoSolutionOrRerunNonErased> {
1124        let cx = self.cx();
1125        Ok(if target_container_def_id == impl_trait_ref.def_id.into() {
1126            // Default value from the trait definition. No need to rebase.
1127            goal.predicate.alias.args
1128        } else if target_container_def_id == impl_def_id.into() {
1129            // Same impl, no need to fully translate, just a rebase from
1130            // the trait is sufficient.
1131            goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id.into(), impl_args)
1132        } else {
1133            let target_args = self.fresh_args_for_item(target_container_def_id);
1134            let target_trait_ref = cx
1135                .impl_trait_ref(target_container_def_id.try_into().unwrap())
1136                .instantiate(cx, target_args)
1137                .skip_norm_wip();
1138            // Relate source impl to target impl by equating trait refs.
1139            self.eq(goal.param_env, impl_trait_ref, target_trait_ref)?;
1140            // Also add predicates since they may be needed to constrain the
1141            // target impl's params.
1142            self.add_goals(
1143                GoalSource::Misc,
1144                cx.clauses_of(target_container_def_id)
1145                    .iter_instantiated(cx, target_args)
1146                    .map(Unnormalized::skip_norm_wip)
1147                    .map(|clause| goal.with(cx, clause)),
1148            )?;
1149            goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id.into(), target_args)
1150        })
1151    }
1152}