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