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 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 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 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 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 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 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 ecx.try_evaluate_added_goals()?;
253
254 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 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 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 cx.impl_self_is_guaranteed_unsized(impl_def_id) {
322 match ecx.typing_mode() {
323 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 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 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 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 Some(tupled_inputs_and_output) =
449 structural_traits::extract_tupled_inputs_and_output_from_callable(
450 cx,
451 goal.predicate.self_ty(),
452 goal_kind,
453 )?
454 else {
455 return ecx.forced_ambiguity(MaybeCause::Ambiguity);
456 };
457 let (inputs, output) = ecx.instantiate_binder_with_infer(tupled_inputs_and_output);
458
459 let output_is_sized_pred =
462 ty::TraitRef::new(cx, cx.require_trait_lang_item(SolverTraitLangItem::Sized), [output]);
463
464 let pred = ty::ProjectionPredicate {
465 projection_term: ty::AliasTerm::new(
466 cx,
467 goal.predicate.def_id(),
468 [goal.predicate.self_ty(), inputs],
469 ),
470 term: output.into(),
471 }
472 .upcast(cx);
473
474 Self::probe_and_consider_implied_clause(
475 ecx,
476 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
477 goal,
478 pred,
479 [(GoalSource::ImplWhereBound, goal.with(cx, output_is_sized_pred))],
480 )
481 }
482
483 fn consider_builtin_async_fn_trait_candidates(
484 ecx: &mut EvalCtxt<'_, D>,
485 goal: Goal<I, Self>,
486 goal_kind: ty::ClosureKind,
487 ) -> Result<Candidate<I>, NoSolution> {
488 let cx = ecx.cx();
489
490 let env_region = match goal_kind {
491 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => goal.predicate.alias.args.region_at(2),
492 ty::ClosureKind::FnOnce => Region::new_static(cx),
494 };
495 let (tupled_inputs_and_output_and_coroutine, nested_preds) =
496 structural_traits::extract_tupled_inputs_and_output_from_async_callable(
497 cx,
498 goal.predicate.self_ty(),
499 goal_kind,
500 env_region,
501 )?;
502 let AsyncCallableRelevantTypes {
503 tupled_inputs_ty,
504 output_coroutine_ty,
505 coroutine_return_ty,
506 } = ecx.instantiate_binder_with_infer(tupled_inputs_and_output_and_coroutine);
507
508 let output_is_sized_pred = ty::TraitRef::new(
511 cx,
512 cx.require_trait_lang_item(SolverTraitLangItem::Sized),
513 [output_coroutine_ty],
514 );
515
516 let (projection_term, term) =
517 if cx.is_lang_item(goal.predicate.def_id(), SolverLangItem::CallOnceFuture) {
518 (
519 ty::AliasTerm::new(
520 cx,
521 goal.predicate.def_id(),
522 [goal.predicate.self_ty(), tupled_inputs_ty],
523 ),
524 output_coroutine_ty.into(),
525 )
526 } else if cx.is_lang_item(goal.predicate.def_id(), SolverLangItem::CallRefFuture) {
527 (
528 ty::AliasTerm::new(
529 cx,
530 goal.predicate.def_id(),
531 [
532 I::GenericArg::from(goal.predicate.self_ty()),
533 tupled_inputs_ty.into(),
534 env_region.into(),
535 ],
536 ),
537 output_coroutine_ty.into(),
538 )
539 } else if cx.is_lang_item(goal.predicate.def_id(), SolverLangItem::AsyncFnOnceOutput) {
540 (
541 ty::AliasTerm::new(
542 cx,
543 goal.predicate.def_id(),
544 [goal.predicate.self_ty(), tupled_inputs_ty],
545 ),
546 coroutine_return_ty.into(),
547 )
548 } else {
549 panic!("no such associated type in `AsyncFn*`: {:?}", goal.predicate.def_id())
550 };
551 let pred = ty::ProjectionPredicate { projection_term, term }.upcast(cx);
552
553 Self::probe_and_consider_implied_clause(
554 ecx,
555 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
556 goal,
557 pred,
558 [goal.with(cx, output_is_sized_pred)]
559 .into_iter()
560 .chain(nested_preds.into_iter().map(|pred| goal.with(cx, pred)))
561 .map(|goal| (GoalSource::ImplWhereBound, goal)),
562 )
563 }
564
565 fn consider_builtin_async_fn_kind_helper_candidate(
566 ecx: &mut EvalCtxt<'_, D>,
567 goal: Goal<I, Self>,
568 ) -> Result<Candidate<I>, NoSolution> {
569 let [
570 closure_fn_kind_ty,
571 goal_kind_ty,
572 borrow_region,
573 tupled_inputs_ty,
574 tupled_upvars_ty,
575 coroutine_captures_by_ref_ty,
576 ] = *goal.predicate.alias.args.as_slice()
577 else {
578 panic!();
579 };
580
581 if tupled_upvars_ty.expect_ty().is_ty_var() {
583 return ecx.forced_ambiguity(MaybeCause::Ambiguity);
584 }
585
586 let Some(closure_kind) = closure_fn_kind_ty.expect_ty().to_opt_closure_kind() else {
587 return Err(NoSolution);
589 };
590 let Some(goal_kind) = goal_kind_ty.expect_ty().to_opt_closure_kind() else {
591 return Err(NoSolution);
592 };
593 if !closure_kind.extends(goal_kind) {
594 return Err(NoSolution);
595 }
596
597 let upvars_ty = ty::CoroutineClosureSignature::tupled_upvars_by_closure_kind(
598 ecx.cx(),
599 goal_kind,
600 tupled_inputs_ty.expect_ty(),
601 tupled_upvars_ty.expect_ty(),
602 coroutine_captures_by_ref_ty.expect_ty(),
603 borrow_region.expect_region(),
604 );
605
606 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
607 ecx.instantiate_normalizes_to_term(goal, upvars_ty.into());
608 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
609 })
610 }
611
612 fn consider_builtin_tuple_candidate(
613 _ecx: &mut EvalCtxt<'_, D>,
614 goal: Goal<I, Self>,
615 ) -> Result<Candidate<I>, NoSolution> {
616 panic!("`Tuple` does not have an associated type: {:?}", goal);
617 }
618
619 fn consider_builtin_pointee_candidate(
620 ecx: &mut EvalCtxt<'_, D>,
621 goal: Goal<I, Self>,
622 ) -> Result<Candidate<I>, NoSolution> {
623 let cx = ecx.cx();
624 let metadata_def_id = cx.require_lang_item(SolverLangItem::Metadata);
625 assert_eq!(metadata_def_id, goal.predicate.def_id());
626 let metadata_ty = match goal.predicate.self_ty().kind() {
627 ty::Bool
628 | ty::Char
629 | ty::Int(..)
630 | ty::Uint(..)
631 | ty::Float(..)
632 | ty::Array(..)
633 | ty::Pat(..)
634 | ty::RawPtr(..)
635 | ty::Ref(..)
636 | ty::FnDef(..)
637 | ty::FnPtr(..)
638 | ty::Closure(..)
639 | ty::CoroutineClosure(..)
640 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
641 | ty::Coroutine(..)
642 | ty::CoroutineWitness(..)
643 | ty::Never
644 | ty::Foreign(..) => Ty::new_unit(cx),
645
646 ty::Error(e) => Ty::new_error(cx, e),
647
648 ty::Str | ty::Slice(_) => Ty::new_usize(cx),
649
650 ty::Dynamic(_, _) => {
651 let dyn_metadata = cx.require_lang_item(SolverLangItem::DynMetadata);
652 cx.type_of(dyn_metadata)
653 .instantiate(cx, &[I::GenericArg::from(goal.predicate.self_ty())])
654 }
655
656 ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => {
657 let alias_bound_result =
662 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
663 let sized_predicate = ty::TraitRef::new(
664 cx,
665 cx.require_trait_lang_item(SolverTraitLangItem::Sized),
666 [I::GenericArg::from(goal.predicate.self_ty())],
667 );
668 ecx.add_goal(GoalSource::Misc, goal.with(cx, sized_predicate));
669 ecx.instantiate_normalizes_to_term(goal, Ty::new_unit(cx).into());
670 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
671 });
672 return alias_bound_result.or_else(|NoSolution| {
675 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|this| {
676 this.structurally_instantiate_normalizes_to_term(
677 goal,
678 goal.predicate.alias,
679 );
680 this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
681 })
682 });
683 }
684
685 ty::Adt(def, args) if def.is_struct() => match def.struct_tail_ty(cx) {
686 None => Ty::new_unit(cx),
687 Some(tail_ty) => {
688 Ty::new_projection(cx, metadata_def_id, [tail_ty.instantiate(cx, args)])
689 }
690 },
691 ty::Adt(_, _) => Ty::new_unit(cx),
692
693 ty::Tuple(elements) => match elements.last() {
694 None => Ty::new_unit(cx),
695 Some(tail_ty) => Ty::new_projection(cx, metadata_def_id, [tail_ty]),
696 },
697
698 ty::UnsafeBinder(_) => {
699 todo!()
701 }
702
703 ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
704 | ty::Bound(..) => panic!(
705 "unexpected self ty `{:?}` when normalizing `<T as Pointee>::Metadata`",
706 goal.predicate.self_ty()
707 ),
708 };
709
710 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
711 ecx.instantiate_normalizes_to_term(goal, metadata_ty.into());
712 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
713 })
714 }
715
716 fn consider_builtin_future_candidate(
717 ecx: &mut EvalCtxt<'_, D>,
718 goal: Goal<I, Self>,
719 ) -> Result<Candidate<I>, NoSolution> {
720 let self_ty = goal.predicate.self_ty();
721 let ty::Coroutine(def_id, args) = self_ty.kind() else {
722 return Err(NoSolution);
723 };
724
725 let cx = ecx.cx();
727 if !cx.coroutine_is_async(def_id) {
728 return Err(NoSolution);
729 }
730
731 let term = args.as_coroutine().return_ty().into();
732
733 Self::probe_and_consider_implied_clause(
734 ecx,
735 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
736 goal,
737 ty::ProjectionPredicate {
738 projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.def_id(), [self_ty]),
739 term,
740 }
741 .upcast(cx),
742 [],
745 )
746 }
747
748 fn consider_builtin_iterator_candidate(
749 ecx: &mut EvalCtxt<'_, D>,
750 goal: Goal<I, Self>,
751 ) -> Result<Candidate<I>, NoSolution> {
752 let self_ty = goal.predicate.self_ty();
753 let ty::Coroutine(def_id, args) = self_ty.kind() else {
754 return Err(NoSolution);
755 };
756
757 let cx = ecx.cx();
759 if !cx.coroutine_is_gen(def_id) {
760 return Err(NoSolution);
761 }
762
763 let term = args.as_coroutine().yield_ty().into();
764
765 Self::probe_and_consider_implied_clause(
766 ecx,
767 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
768 goal,
769 ty::ProjectionPredicate {
770 projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.def_id(), [self_ty]),
771 term,
772 }
773 .upcast(cx),
774 [],
777 )
778 }
779
780 fn consider_builtin_fused_iterator_candidate(
781 _ecx: &mut EvalCtxt<'_, D>,
782 goal: Goal<I, Self>,
783 ) -> Result<Candidate<I>, NoSolution> {
784 panic!("`FusedIterator` does not have an associated type: {:?}", goal);
785 }
786
787 fn consider_builtin_async_iterator_candidate(
788 ecx: &mut EvalCtxt<'_, D>,
789 goal: Goal<I, Self>,
790 ) -> Result<Candidate<I>, NoSolution> {
791 let self_ty = goal.predicate.self_ty();
792 let ty::Coroutine(def_id, args) = self_ty.kind() else {
793 return Err(NoSolution);
794 };
795
796 let cx = ecx.cx();
798 if !cx.coroutine_is_async_gen(def_id) {
799 return Err(NoSolution);
800 }
801
802 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
803 let expected_ty = ecx.next_ty_infer();
804 let wrapped_expected_ty = Ty::new_adt(
807 cx,
808 cx.adt_def(cx.require_adt_lang_item(SolverAdtLangItem::Poll)),
809 cx.mk_args(&[Ty::new_adt(
810 cx,
811 cx.adt_def(cx.require_adt_lang_item(SolverAdtLangItem::Option)),
812 cx.mk_args(&[expected_ty.into()]),
813 )
814 .into()]),
815 );
816 let yield_ty = args.as_coroutine().yield_ty();
817 ecx.eq(goal.param_env, wrapped_expected_ty, yield_ty)?;
818 ecx.instantiate_normalizes_to_term(goal, expected_ty.into());
819 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
820 })
821 }
822
823 fn consider_builtin_coroutine_candidate(
824 ecx: &mut EvalCtxt<'_, D>,
825 goal: Goal<I, Self>,
826 ) -> Result<Candidate<I>, NoSolution> {
827 let self_ty = goal.predicate.self_ty();
828 let ty::Coroutine(def_id, args) = self_ty.kind() else {
829 return Err(NoSolution);
830 };
831
832 let cx = ecx.cx();
834 if !cx.is_general_coroutine(def_id) {
835 return Err(NoSolution);
836 }
837
838 let coroutine = args.as_coroutine();
839
840 let term = if cx.is_lang_item(goal.predicate.def_id(), SolverLangItem::CoroutineReturn) {
841 coroutine.return_ty().into()
842 } else if cx.is_lang_item(goal.predicate.def_id(), SolverLangItem::CoroutineYield) {
843 coroutine.yield_ty().into()
844 } else {
845 panic!("unexpected associated item `{:?}` for `{self_ty:?}`", goal.predicate.def_id())
846 };
847
848 Self::probe_and_consider_implied_clause(
849 ecx,
850 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
851 goal,
852 ty::ProjectionPredicate {
853 projection_term: ty::AliasTerm::new(
854 ecx.cx(),
855 goal.predicate.def_id(),
856 [self_ty, coroutine.resume_ty()],
857 ),
858 term,
859 }
860 .upcast(cx),
861 [],
864 )
865 }
866
867 fn consider_structural_builtin_unsize_candidates(
868 _ecx: &mut EvalCtxt<'_, D>,
869 goal: Goal<I, Self>,
870 ) -> Vec<Candidate<I>> {
871 panic!("`Unsize` does not have an associated type: {:?}", goal);
872 }
873
874 fn consider_builtin_discriminant_kind_candidate(
875 ecx: &mut EvalCtxt<'_, D>,
876 goal: Goal<I, Self>,
877 ) -> Result<Candidate<I>, NoSolution> {
878 let self_ty = goal.predicate.self_ty();
879 let discriminant_ty = match self_ty.kind() {
880 ty::Bool
881 | ty::Char
882 | ty::Int(..)
883 | ty::Uint(..)
884 | ty::Float(..)
885 | ty::Array(..)
886 | ty::Pat(..)
887 | ty::RawPtr(..)
888 | ty::Ref(..)
889 | ty::FnDef(..)
890 | ty::FnPtr(..)
891 | ty::Closure(..)
892 | ty::CoroutineClosure(..)
893 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
894 | ty::Coroutine(..)
895 | ty::CoroutineWitness(..)
896 | ty::Never
897 | ty::Foreign(..)
898 | ty::Adt(_, _)
899 | ty::Str
900 | ty::Slice(_)
901 | ty::Dynamic(_, _)
902 | ty::Tuple(_)
903 | ty::Error(_) => self_ty.discriminant_ty(ecx.cx()),
904
905 ty::UnsafeBinder(_) => {
906 todo!("discr subgoal...")
908 }
909
910 ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => {
914 return ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
915 ecx.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
916 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
917 });
918 }
919
920 ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
921 | ty::Bound(..) => panic!(
922 "unexpected self ty `{:?}` when normalizing `<T as DiscriminantKind>::Discriminant`",
923 goal.predicate.self_ty()
924 ),
925 };
926
927 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
928 ecx.instantiate_normalizes_to_term(goal, discriminant_ty.into());
929 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
930 })
931 }
932
933 fn consider_builtin_destruct_candidate(
934 _ecx: &mut EvalCtxt<'_, D>,
935 goal: Goal<I, Self>,
936 ) -> Result<Candidate<I>, NoSolution> {
937 panic!("`Destruct` does not have an associated type: {:?}", goal);
938 }
939
940 fn consider_builtin_transmute_candidate(
941 _ecx: &mut EvalCtxt<'_, D>,
942 goal: Goal<I, Self>,
943 ) -> Result<Candidate<I>, NoSolution> {
944 panic!("`TransmuteFrom` does not have an associated type: {:?}", goal)
945 }
946
947 fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
948 _ecx: &mut EvalCtxt<'_, D>,
949 goal: Goal<I, Self>,
950 ) -> Result<Candidate<I>, NoSolution> {
951 unreachable!("`BikeshedGuaranteedNoDrop` does not have an associated type: {:?}", goal)
952 }
953}
954
955impl<D, I> EvalCtxt<'_, D>
956where
957 D: SolverDelegate<Interner = I>,
958 I: Interner,
959{
960 fn translate_args(
961 &mut self,
962 goal: Goal<I, ty::NormalizesTo<I>>,
963 impl_def_id: I::ImplId,
964 impl_args: I::GenericArgs,
965 impl_trait_ref: rustc_type_ir::TraitRef<I>,
966 target_container_def_id: I::DefId,
967 ) -> Result<I::GenericArgs, NoSolution> {
968 let cx = self.cx();
969 Ok(if target_container_def_id == impl_trait_ref.def_id.into() {
970 goal.predicate.alias.args
972 } else if target_container_def_id == impl_def_id.into() {
973 goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id.into(), impl_args)
976 } else {
977 let target_args = self.fresh_args_for_item(target_container_def_id);
978 let target_trait_ref = cx
979 .impl_trait_ref(target_container_def_id.try_into().unwrap())
980 .instantiate(cx, target_args);
981 self.eq(goal.param_env, impl_trait_ref, target_trait_ref)?;
983 self.add_goals(
986 GoalSource::Misc,
987 cx.predicates_of(target_container_def_id)
988 .iter_instantiated(cx, target_args)
989 .map(|pred| goal.with(cx, pred)),
990 );
991 goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id.into(), target_args)
992 })
993 }
994}