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