Skip to main content

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