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