rustc_next_trait_solver/solve/normalizes_to/
mod.rs

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