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 for arg in goal.predicate.alias.own_args(cx).iter() {
61 let Some(term) = arg.as_term() else {
62 continue;
63 };
64 match ecx.structurally_normalize_term(goal.param_env, term) {
65 Ok(term) => {
66 if term.is_infer() {
67 return Some(ecx.evaluate_added_goals_and_make_canonical_response(
68 Certainty::AMBIGUOUS,
69 ));
70 }
71 }
72 Err(
73 e @ (NoSolutionOrRerunNonErased::NoSolution(NoSolution)
74 | NoSolutionOrRerunNonErased::RerunNonErased(_)),
75 ) => {
76 return Some(Err(e));
77 }
78 }
79 }
80
81 None
82 },
83 |ecx| {
84 ecx.probe(|&result| ProbeKind::RigidAlias { result }).enter(|this| {
85 this.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
86 this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
87 })
88 },
89 )
90 }
91
92 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 fn instantiate_normalizes_to_term(
141 &mut self,
142 goal: Goal<I, NormalizesTo<I>>,
143 term: I::Term,
144 ) -> Result<(), NoSolutionOrRerunNonErased> {
145 self.push_const_arg_has_type_goal(goal.param_env, goal.predicate.alias, term)?;
146 self.eq(goal.param_env, goal.predicate.term, term)
147 .expect("expected goal term to be fully unconstrained");
148 Ok(())
149 }
150
151 fn structurally_instantiate_normalizes_to_term(
154 &mut self,
155 goal: Goal<I, NormalizesTo<I>>,
156 term: ty::AliasTerm<I>,
157 ) {
158 self.relate(
159 goal.param_env,
160 term.to_term(self.cx(), ty::IsRigid::Yes),
161 ty::Invariant,
162 goal.predicate.term,
163 )
164 .expect("expected goal term to be fully unconstrained");
165 }
166}
167
168impl<D, I> assembly::GoalKind<D> for NormalizesTo<I>
169where
170 D: SolverDelegate<Interner = I>,
171 I: Interner,
172{
173 fn self_ty(self) -> I::Ty {
174 self.self_ty()
175 }
176
177 fn trait_ref(self, cx: I) -> ty::TraitRef<I> {
178 self.alias.trait_ref(cx)
179 }
180
181 fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self {
182 self.with_replaced_self_ty(cx, self_ty)
183 }
184
185 fn trait_def_id(self, cx: I) -> I::TraitId {
186 self.trait_def_id(cx)
187 }
188
189 fn fast_reject_assumption(
190 ecx: &mut EvalCtxt<'_, D>,
191 goal: Goal<I, Self>,
192 assumption: I::Clause,
193 ) -> Result<(), NoSolution> {
194 let alias_def_id = match goal.predicate.alias.kind {
195 ty::AliasTermKind::ProjectionTy { def_id } => def_id.into(),
196 ty::AliasTermKind::ProjectionConst { def_id } => def_id.into(),
197 _ => return Err(NoSolution),
198 };
199 if let Some(projection_pred) = assumption.as_projection_clause()
200 && projection_pred.item_def_id() == alias_def_id
201 && DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify(
202 goal.predicate.alias.args,
203 projection_pred.skip_binder().projection_term.args,
204 )
205 {
206 Ok(())
207 } else {
208 Err(NoSolution)
209 }
210 }
211
212 fn match_assumption(
213 ecx: &mut EvalCtxt<'_, D>,
214 goal: Goal<I, Self>,
215 assumption: I::Clause,
216 then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
217 ) -> QueryResultOrRerunNonErased<I> {
218 let cx = ecx.cx();
219 let projection_pred = assumption.as_projection_clause().unwrap();
220 let assumption_projection_pred = ecx.instantiate_binder_with_infer(projection_pred);
221 ecx.eq(goal.param_env, goal.predicate.alias, assumption_projection_pred.projection_term)?;
222
223 ecx.instantiate_normalizes_to_term(goal, assumption_projection_pred.term)?;
224
225 ecx.add_goals(
228 GoalSource::AliasWellFormed,
229 cx.own_predicates_of(goal.predicate.alias.expect_projection_def_id().into())
230 .iter_instantiated(cx, goal.predicate.alias.args)
231 .map(Unnormalized::skip_norm_wip)
232 .map(|pred| goal.with(cx, pred)),
233 )?;
234
235 then(ecx)
236 }
237
238 fn probe_and_consider_object_bound_candidate(
242 ecx: &mut EvalCtxt<'_, D>,
243 source: CandidateSource<I>,
244 goal: Goal<I, Self>,
245 assumption: I::Clause,
246 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
247 Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| {
248 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
249 })
250 }
251
252 fn consider_additional_alias_assumptions(
253 _ecx: &mut EvalCtxt<'_, D>,
254 _goal: Goal<I, Self>,
255 _alias_ty: ty::AliasTy<I>,
256 ) -> Vec<Candidate<I>> {
257 ::alloc::vec::Vec::new()vec![]
258 }
259
260 fn consider_impl_candidate(
261 ecx: &mut EvalCtxt<'_, D>,
262 goal: Goal<I, NormalizesTo<I>>,
263 impl_def_id: I::ImplId,
264 then: impl FnOnce(&mut EvalCtxt<'_, D>, Certainty) -> QueryResultOrRerunNonErased<I>,
265 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
266 let cx = ecx.cx();
267
268 let alias_def_id = goal.predicate.alias.expect_projection_def_id();
269 let goal_trait_ref = goal.predicate.alias.trait_ref(cx);
270 let impl_trait_ref = cx.impl_trait_ref(impl_def_id);
271 if !DeepRejectCtxt::relate_rigid_infer(ecx.cx()).args_may_unify(
272 goal.predicate.alias.trait_ref(cx).args,
273 impl_trait_ref.skip_binder().args,
274 ) {
275 return Err(NoSolution.into());
276 }
277
278 let impl_polarity = cx.impl_polarity(impl_def_id);
280 match impl_polarity {
281 ty::ImplPolarity::Negative => return Err(NoSolution.into()),
282 ty::ImplPolarity::Reservation => {
283 {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("reservation impl for trait with assoc item: {0:?}",
goal)));
}unimplemented!("reservation impl for trait with assoc item: {:?}", goal)
284 }
285 ty::ImplPolarity::Positive => {}
286 };
287
288 ecx.probe_trait_candidate(CandidateSource::Impl(impl_def_id)).enter(|ecx| {
289 let impl_args = ecx.fresh_args_for_item(impl_def_id.into());
290 let impl_trait_ref = impl_trait_ref.instantiate(cx, impl_args).skip_norm_wip();
291
292 ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?;
293
294 let where_clause_bounds = cx
295 .predicates_of(impl_def_id.into())
296 .iter_instantiated(cx, impl_args)
297 .map(Unnormalized::skip_norm_wip)
298 .map(|pred| goal.with(cx, pred));
299 ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds)?;
300
301 ecx.try_evaluate_added_goals()?;
306
307 ecx.add_goals(
311 GoalSource::AliasWellFormed,
312 cx.own_predicates_of(alias_def_id.into())
313 .iter_instantiated(cx, goal.predicate.alias.args)
314 .map(Unnormalized::skip_norm_wip)
315 .map(|pred| goal.with(cx, pred)),
316 )?;
317
318 let error_response = |ecx: &mut EvalCtxt<'_, D>, guar| {
319 let error_term = match goal.predicate.alias.kind {
320 ty::AliasTermKind::ProjectionTy { .. } => Ty::new_error(cx, guar).into(),
321 ty::AliasTermKind::ProjectionConst { .. } => Const::new_error(cx, guar).into(),
322 kind => {
::core::panicking::panic_fmt(format_args!("expected projection, found {0:?}",
kind));
}panic!("expected projection, found {kind:?}"),
323 };
324 ecx.instantiate_normalizes_to_term(goal, error_term)?;
325 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
326 };
327
328 let target_item_def_id =
329 match ecx.fetch_eligible_assoc_item(goal_trait_ref, alias_def_id, impl_def_id) {
330 FetchEligibleAssocItemResponse::Found(target_item_def_id) => target_item_def_id,
331 FetchEligibleAssocItemResponse::NotFound(tm) => {
332 match tm {
333 ty::TypingMode::Coherence => {
345 ecx.add_goal(
346 GoalSource::Misc,
347 goal.with(cx, PredicateKind::Ambiguous),
348 )?;
349 return ecx.evaluate_added_goals_and_make_canonical_response(
350 Certainty::Yes,
351 );
352 }
353 ty::TypingMode::Typeck { .. }
355 | ty::TypingMode::PostTypeckUntilBorrowck { .. }
356 | ty::TypingMode::PostBorrowck { .. }
357 | ty::TypingMode::PostAnalysis
358 | ty::TypingMode::Codegen => {
359 ecx.structurally_instantiate_normalizes_to_term(
360 goal,
361 goal.predicate.alias,
362 );
363 return ecx.evaluate_added_goals_and_make_canonical_response(
364 Certainty::Yes,
365 );
366 }
367 };
368 }
369 FetchEligibleAssocItemResponse::Err(guar) => return error_response(ecx, guar),
370 FetchEligibleAssocItemResponse::NotFoundBecauseErased => {
371 ecx.opaque_accesses.rerun_always(RerunReason::FetchEligibleAssocItem)?;
372 return Err(NoSolution.into());
373 }
374 };
375
376 if !cx.has_item_definition(target_item_def_id) {
377 if cx.impl_self_is_guaranteed_unsized(impl_def_id) {
383 if ecx.typing_mode().is_coherence() {
384 ecx.add_goal(GoalSource::Misc, goal.with(cx, PredicateKind::Ambiguous))?;
395 return then(ecx, Certainty::Yes);
396 } else {
397 ecx.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
398 return then(ecx, Certainty::Yes);
399 }
400 } else {
401 return error_response(ecx, cx.delay_bug("missing item"));
402 }
403 }
404
405 let target_container_def_id = cx.impl_or_trait_assoc_term_parent(target_item_def_id);
406
407 let target_args = ecx.translate_args(
418 goal,
419 impl_def_id,
420 impl_args,
421 impl_trait_ref,
422 target_container_def_id,
423 )?;
424
425 if !cx.check_args_compatible(target_item_def_id.into(), target_args) {
426 return error_response(
427 ecx,
428 cx.delay_bug("associated item has mismatched arguments"),
429 );
430 }
431
432 let term = match goal.predicate.alias.kind {
434 ty::AliasTermKind::ProjectionTy { .. } => {
435 let t = cx.type_of(target_item_def_id.into()).instantiate(cx, target_args);
436 let t = ecx.normalize(GoalSource::Misc, goal.param_env, t)?;
437 t.into()
438 }
439 ty::AliasTermKind::ProjectionConst { .. }
440 if cx.is_type_const(target_item_def_id.into()) =>
441 {
442 let c =
443 cx.const_of_item(target_item_def_id.into()).instantiate(cx, target_args);
444 let c = ecx.normalize(GoalSource::Misc, goal.param_env, c)?;
445 c.into()
446 }
447 ty::AliasTermKind::ProjectionConst { .. } => {
448 let alias_const = ty::AliasConst::new(
449 cx,
450 ty::AliasConstKind::Projection {
451 def_id: target_item_def_id.into().try_into().unwrap(),
452 },
453 target_args,
454 );
455 return ecx.evaluate_const_and_instantiate_projection_term(
456 goal.param_env,
457 goal.predicate.alias,
458 goal.predicate.term,
459 alias_const,
460 );
461 }
462 kind => {
::core::panicking::panic_fmt(format_args!("expected projection, found {0:?}",
kind));
}panic!("expected projection, found {kind:?}"),
463 };
464
465 ecx.instantiate_normalizes_to_term(goal, term)?;
466 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
467 })
468 }
469
470 fn consider_error_guaranteed_candidate(
473 ecx: &mut EvalCtxt<'_, D>,
474 goal: Goal<I, Self>,
475 guar: I::ErrorGuaranteed,
476 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
477 let cx = ecx.cx();
478 let error_term = match goal.predicate.alias.kind {
479 ty::AliasTermKind::ProjectionTy { .. } => Ty::new_error(cx, guar).into(),
480 ty::AliasTermKind::ProjectionConst { .. } => Const::new_error(cx, guar).into(),
481 kind => {
::core::panicking::panic_fmt(format_args!("expected projection, found {0:?}",
kind));
}panic!("expected projection, found {kind:?}"),
482 };
483
484 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
485 ecx.instantiate_normalizes_to_term(goal, error_term)?;
486 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
487 })
488 }
489
490 fn consider_auto_trait_candidate(
491 ecx: &mut EvalCtxt<'_, D>,
492 _goal: Goal<I, Self>,
493 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
494 ecx.cx().delay_bug("associated types not allowed on auto traits");
495 Err(NoSolution.into())
496 }
497
498 fn consider_trait_alias_candidate(
499 _ecx: &mut EvalCtxt<'_, D>,
500 goal: Goal<I, Self>,
501 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
502 {
::core::panicking::panic_fmt(format_args!("trait aliases do not have associated types: {0:?}",
goal));
};panic!("trait aliases do not have associated types: {:?}", goal);
503 }
504
505 fn consider_builtin_sizedness_candidates(
506 _ecx: &mut EvalCtxt<'_, D>,
507 goal: Goal<I, Self>,
508 _sizedness: SizedTraitKind,
509 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
510 {
::core::panicking::panic_fmt(format_args!("`Sized`/`MetaSized` does not have an associated type: {0:?}",
goal));
};panic!("`Sized`/`MetaSized` does not have an associated type: {:?}", goal);
511 }
512
513 fn consider_builtin_copy_clone_candidate(
514 _ecx: &mut EvalCtxt<'_, D>,
515 goal: Goal<I, Self>,
516 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
517 {
::core::panicking::panic_fmt(format_args!("`Copy`/`Clone` does not have an associated type: {0:?}",
goal));
};panic!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
518 }
519
520 fn consider_builtin_fn_ptr_trait_candidate(
521 _ecx: &mut EvalCtxt<'_, D>,
522 goal: Goal<I, Self>,
523 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
524 {
::core::panicking::panic_fmt(format_args!("`FnPtr` does not have an associated type: {0:?}",
goal));
};panic!("`FnPtr` does not have an associated type: {:?}", goal);
525 }
526
527 fn consider_builtin_fn_trait_candidates(
528 ecx: &mut EvalCtxt<'_, D>,
529 goal: Goal<I, Self>,
530 goal_kind: ty::ClosureKind,
531 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
532 let cx = ecx.cx();
533 let Some(tupled_inputs_and_output) =
534 structural_traits::extract_tupled_inputs_and_output_from_callable(
535 cx,
536 goal.predicate.self_ty(),
537 goal_kind,
538 )?
539 else {
540 return ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS);
541 };
542 let (inputs, output) = ecx.instantiate_binder_with_infer(tupled_inputs_and_output);
543
544 let output_is_sized_pred =
547 ty::TraitRef::new(cx, cx.require_trait_lang_item(SolverTraitLangItem::Sized), [output]);
548
549 let pred = ty::ProjectionPredicate {
550 projection_term: ty::AliasTerm::new(
551 cx,
552 goal.predicate.alias.kind,
553 [goal.predicate.self_ty(), inputs],
554 ),
555 term: output.into(),
556 }
557 .upcast(cx);
558
559 Self::probe_and_consider_implied_clause(
560 ecx,
561 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
562 goal,
563 pred,
564 [(GoalSource::ImplWhereBound, goal.with(cx, output_is_sized_pred))],
565 )
566 }
567
568 fn consider_builtin_async_fn_trait_candidates(
569 ecx: &mut EvalCtxt<'_, D>,
570 goal: Goal<I, Self>,
571 goal_kind: ty::ClosureKind,
572 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
573 let cx = ecx.cx();
574 let def_id = goal.predicate.alias.expect_projection_ty_def_id();
575
576 let env_region = match goal_kind {
577 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => goal.predicate.alias.args.region_at(2),
578 ty::ClosureKind::FnOnce => Region::new_static(cx),
580 };
581 let (tupled_inputs_and_output_and_coroutine, nested_preds) =
582 structural_traits::extract_tupled_inputs_and_output_from_async_callable(
583 cx,
584 goal.predicate.self_ty(),
585 goal_kind,
586 env_region,
587 )?;
588 let AsyncCallableRelevantTypes {
589 tupled_inputs_ty,
590 output_coroutine_ty,
591 coroutine_return_ty,
592 } = ecx.instantiate_binder_with_infer(tupled_inputs_and_output_and_coroutine);
593
594 let output_is_sized_pred = ty::TraitRef::new(
597 cx,
598 cx.require_trait_lang_item(SolverTraitLangItem::Sized),
599 [output_coroutine_ty],
600 );
601
602 let (projection_term, term) = if cx
603 .is_projection_lang_item(def_id, SolverProjectionLangItem::CallOnceFuture)
604 {
605 (
606 ty::AliasTerm::new(
607 cx,
608 goal.predicate.alias.kind,
609 [goal.predicate.self_ty(), tupled_inputs_ty],
610 ),
611 output_coroutine_ty.into(),
612 )
613 } else if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::CallRefFuture) {
614 (
615 ty::AliasTerm::new(
616 cx,
617 goal.predicate.alias.kind,
618 [
619 I::GenericArg::from(goal.predicate.self_ty()),
620 tupled_inputs_ty.into(),
621 env_region.into(),
622 ],
623 ),
624 output_coroutine_ty.into(),
625 )
626 } else if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::AsyncFnOnceOutput) {
627 (
628 ty::AliasTerm::new(
629 cx,
630 goal.predicate.alias.kind,
631 [goal.predicate.self_ty(), tupled_inputs_ty],
632 ),
633 coroutine_return_ty.into(),
634 )
635 } else {
636 {
::core::panicking::panic_fmt(format_args!("no such associated type in `AsyncFn*`: {0:?}",
def_id));
}panic!("no such associated type in `AsyncFn*`: {:?}", def_id)
637 };
638 let pred = ty::ProjectionPredicate { projection_term, term }.upcast(cx);
639
640 Self::probe_and_consider_implied_clause(
641 ecx,
642 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
643 goal,
644 pred,
645 [goal.with(cx, output_is_sized_pred)]
646 .into_iter()
647 .chain(nested_preds.into_iter().map(|pred| goal.with(cx, pred)))
648 .map(|goal| (GoalSource::ImplWhereBound, goal)),
649 )
650 }
651
652 fn consider_builtin_async_fn_kind_helper_candidate(
653 ecx: &mut EvalCtxt<'_, D>,
654 goal: Goal<I, Self>,
655 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
656 let [
657 closure_fn_kind_ty,
658 goal_kind_ty,
659 borrow_region,
660 tupled_inputs_ty,
661 tupled_upvars_ty,
662 coroutine_captures_by_ref_ty,
663 ] = *goal.predicate.alias.args.as_slice()
664 else {
665 ::core::panicking::panic("explicit panic");panic!();
666 };
667
668 if tupled_upvars_ty.expect_ty().is_ty_var() {
670 return ecx.forced_ambiguity(MaybeInfo::AMBIGUOUS);
671 }
672
673 let Some(closure_kind) = closure_fn_kind_ty.expect_ty().to_opt_closure_kind() else {
674 return Err(NoSolution.into());
676 };
677 let Some(goal_kind) = goal_kind_ty.expect_ty().to_opt_closure_kind() else {
678 return Err(NoSolution.into());
679 };
680 if !closure_kind.extends(goal_kind) {
681 return Err(NoSolution.into());
682 }
683
684 let upvars_ty = ty::CoroutineClosureSignature::tupled_upvars_by_closure_kind(
685 ecx.cx(),
686 goal_kind,
687 tupled_inputs_ty.expect_ty(),
688 tupled_upvars_ty.expect_ty(),
689 coroutine_captures_by_ref_ty.expect_ty(),
690 borrow_region.expect_region(),
691 );
692
693 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
694 ecx.instantiate_normalizes_to_term(goal, upvars_ty.into())?;
695 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
696 })
697 }
698
699 fn consider_builtin_tuple_candidate(
700 _ecx: &mut EvalCtxt<'_, D>,
701 goal: Goal<I, Self>,
702 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
703 {
::core::panicking::panic_fmt(format_args!("`Tuple` does not have an associated type: {0:?}",
goal));
};panic!("`Tuple` does not have an associated type: {:?}", goal);
704 }
705
706 fn consider_builtin_pointee_candidate(
707 ecx: &mut EvalCtxt<'_, D>,
708 goal: Goal<I, Self>,
709 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
710 let cx = ecx.cx();
711 let metadata_def_id = cx.require_projection_lang_item(SolverProjectionLangItem::Metadata);
712 {
match (&ty::AliasTermKind::ProjectionTy { def_id: metadata_def_id },
&goal.predicate.alias.kind) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(
713 ty::AliasTermKind::ProjectionTy { def_id: metadata_def_id },
714 goal.predicate.alias.kind
715 );
716 let metadata_ty = match goal.predicate.self_ty().kind() {
717 ty::Bool
718 | ty::Char
719 | ty::Int(..)
720 | ty::Uint(..)
721 | ty::Float(..)
722 | ty::Array(..)
723 | ty::Pat(..)
724 | ty::RawPtr(..)
725 | ty::Ref(..)
726 | ty::FnDef(..)
727 | ty::FnPtr(..)
728 | ty::Closure(..)
729 | ty::CoroutineClosure(..)
730 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
731 | ty::Coroutine(..)
732 | ty::CoroutineWitness(..)
733 | ty::Never
734 | ty::Foreign(..) => Ty::new_unit(cx),
735
736 ty::Error(e) => Ty::new_error(cx, e),
737
738 ty::Str | ty::Slice(_) => Ty::new_usize(cx),
739
740 ty::Dynamic(_, _) => {
741 let dyn_metadata = cx.require_adt_lang_item(SolverAdtLangItem::DynMetadata);
742 cx.type_of(dyn_metadata.into())
743 .instantiate(cx, &[I::GenericArg::from(goal.predicate.self_ty())])
744 .skip_norm_wip()
745 }
746
747 ty::Alias(ty::IsRigid::Yes, _) | ty::Param(_) | ty::Placeholder(..) => {
748 let alias_bound_result = ecx
753 .probe_builtin_trait_candidate(BuiltinImplSource::Misc)
754 .enter(|ecx| {
755 let sized_predicate = ty::TraitRef::new(
756 cx,
757 cx.require_trait_lang_item(SolverTraitLangItem::Sized),
758 [I::GenericArg::from(goal.predicate.self_ty())],
759 );
760 ecx.add_goal(GoalSource::Misc, goal.with(cx, sized_predicate))?;
761 ecx.instantiate_normalizes_to_term(goal, Ty::new_unit(cx).into())?;
762 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
763 })
764 .map_err_to_rerun()?;
765
766 return alias_bound_result.or_else(|NoSolution| {
769 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|this| {
770 this.structurally_instantiate_normalizes_to_term(
771 goal,
772 goal.predicate.alias,
773 );
774 this.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
775 })
776 });
777 }
778
779 ty::Adt(def, args) if def.is_struct() => match def.struct_tail_ty(cx) {
780 None => Ty::new_unit(cx),
781 Some(tail_ty) => Ty::new_projection(
782 cx,
783 ty::IsRigid::No,
784 metadata_def_id,
785 [tail_ty.instantiate(cx, args).skip_norm_wip()],
786 ),
787 },
788 ty::Adt(_, _) => Ty::new_unit(cx),
789
790 ty::Tuple(elements) => match elements.last() {
791 None => Ty::new_unit(cx),
792 Some(tail_ty) => {
793 Ty::new_projection(cx, ty::IsRigid::No, metadata_def_id, [tail_ty])
794 }
795 },
796
797 ty::UnsafeBinder(_) => {
798 ::core::panicking::panic("not yet implemented")todo!()
800 }
801
802 ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
803 | ty::Alias(ty::IsRigid::No, _)
804 | ty::Bound(..) => {
::core::panicking::panic_fmt(format_args!("unexpected self ty `{0:?}` when normalizing `<T as Pointee>::Metadata`",
goal.predicate.self_ty()));
}panic!(
805 "unexpected self ty `{:?}` when normalizing `<T as Pointee>::Metadata`",
806 goal.predicate.self_ty()
807 ),
808 };
809
810 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
811 ecx.instantiate_normalizes_to_term(goal, metadata_ty.into())?;
812 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
813 })
814 }
815
816 fn consider_builtin_future_candidate(
817 ecx: &mut EvalCtxt<'_, D>,
818 goal: Goal<I, Self>,
819 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
820 let self_ty = goal.predicate.self_ty();
821 let ty::Coroutine(def_id, args) = self_ty.kind() else {
822 return Err(NoSolution.into());
823 };
824
825 let cx = ecx.cx();
827 if !cx.coroutine_is_async(def_id) {
828 return Err(NoSolution.into());
829 }
830
831 let term = args.as_coroutine().return_ty().into();
832
833 Self::probe_and_consider_implied_clause(
834 ecx,
835 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
836 goal,
837 ty::ProjectionPredicate {
838 projection_term: ty::AliasTerm::new(
839 ecx.cx(),
840 cx.alias_term_kind_from_def_id(
841 goal.predicate.alias.expect_projection_def_id().into(),
842 ),
843 [self_ty],
844 ),
845 term,
846 }
847 .upcast(cx),
848 [],
851 )
852 }
853
854 fn consider_builtin_iterator_candidate(
855 ecx: &mut EvalCtxt<'_, D>,
856 goal: Goal<I, Self>,
857 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
858 let self_ty = goal.predicate.self_ty();
859 let ty::Coroutine(def_id, args) = self_ty.kind() else {
860 return Err(NoSolution.into());
861 };
862
863 let cx = ecx.cx();
865 if !cx.coroutine_is_gen(def_id) {
866 return Err(NoSolution.into());
867 }
868
869 let term = args.as_coroutine().yield_ty().into();
870
871 Self::probe_and_consider_implied_clause(
872 ecx,
873 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
874 goal,
875 ty::ProjectionPredicate {
876 projection_term: ty::AliasTerm::new(
877 ecx.cx(),
878 cx.alias_term_kind_from_def_id(
879 goal.predicate.alias.expect_projection_def_id().into(),
880 ),
881 [self_ty],
882 ),
883 term,
884 }
885 .upcast(cx),
886 [],
889 )
890 }
891
892 fn consider_builtin_fused_iterator_candidate(
893 _ecx: &mut EvalCtxt<'_, D>,
894 goal: Goal<I, Self>,
895 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
896 {
::core::panicking::panic_fmt(format_args!("`FusedIterator` does not have an associated type: {0:?}",
goal));
};panic!("`FusedIterator` does not have an associated type: {:?}", goal);
897 }
898
899 fn consider_builtin_async_iterator_candidate(
900 ecx: &mut EvalCtxt<'_, D>,
901 goal: Goal<I, Self>,
902 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
903 let self_ty = goal.predicate.self_ty();
904 let ty::Coroutine(def_id, args) = self_ty.kind() else {
905 return Err(NoSolution.into());
906 };
907
908 let cx = ecx.cx();
910 if !cx.coroutine_is_async_gen(def_id) {
911 return Err(NoSolution.into());
912 }
913
914 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
915 let expected_ty = ecx.next_ty_infer();
916 let wrapped_expected_ty = Ty::new_adt(
919 cx,
920 cx.adt_def(cx.require_adt_lang_item(SolverAdtLangItem::Poll)),
921 cx.mk_args(&[Ty::new_adt(
922 cx,
923 cx.adt_def(cx.require_adt_lang_item(SolverAdtLangItem::Option)),
924 cx.mk_args(&[expected_ty.into()]),
925 )
926 .into()]),
927 );
928 let yield_ty = args.as_coroutine().yield_ty();
929 ecx.eq(goal.param_env, wrapped_expected_ty, yield_ty)?;
930 ecx.instantiate_normalizes_to_term(goal, expected_ty.into())?;
931 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
932 })
933 }
934
935 fn consider_builtin_coroutine_candidate(
936 ecx: &mut EvalCtxt<'_, D>,
937 goal: Goal<I, Self>,
938 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
939 let self_ty = goal.predicate.self_ty();
940 let ty::Coroutine(def_id, args) = self_ty.kind() else {
941 return Err(NoSolution.into());
942 };
943
944 let cx = ecx.cx();
946 if !cx.is_general_coroutine(def_id) {
947 return Err(NoSolution.into());
948 }
949
950 let coroutine = args.as_coroutine();
951 let def_id = goal.predicate.alias.expect_projection_ty_def_id();
952
953 let term = if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::CoroutineReturn)
954 {
955 coroutine.return_ty().into()
956 } else if cx.is_projection_lang_item(def_id, SolverProjectionLangItem::CoroutineYield) {
957 coroutine.yield_ty().into()
958 } else {
959 {
::core::panicking::panic_fmt(format_args!("unexpected associated item `{0:?}` for `{1:?}`",
def_id, self_ty));
}panic!("unexpected associated item `{:?}` for `{self_ty:?}`", def_id)
960 };
961
962 Self::probe_and_consider_implied_clause(
963 ecx,
964 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
965 goal,
966 ty::ProjectionPredicate {
967 projection_term: ty::AliasTerm::new(
968 ecx.cx(),
969 goal.predicate.alias.kind,
970 [self_ty, coroutine.resume_ty()],
971 ),
972 term,
973 }
974 .upcast(cx),
975 [],
978 )
979 }
980
981 fn consider_structural_builtin_unsize_candidates(
982 _ecx: &mut EvalCtxt<'_, D>,
983 goal: Goal<I, Self>,
984 ) -> Result<Vec<Candidate<I>>, RerunNonErased> {
985 {
::core::panicking::panic_fmt(format_args!("`Unsize` does not have an associated type: {0:?}",
goal));
};panic!("`Unsize` does not have an associated type: {:?}", goal);
986 }
987
988 fn consider_builtin_discriminant_kind_candidate(
989 ecx: &mut EvalCtxt<'_, D>,
990 goal: Goal<I, Self>,
991 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
992 let self_ty = goal.predicate.self_ty();
993 let discriminant_ty = match self_ty.kind() {
994 ty::Bool
995 | ty::Char
996 | ty::Int(..)
997 | ty::Uint(..)
998 | ty::Float(..)
999 | ty::Array(..)
1000 | ty::Pat(..)
1001 | ty::RawPtr(..)
1002 | ty::Ref(..)
1003 | ty::FnDef(..)
1004 | ty::FnPtr(..)
1005 | ty::Closure(..)
1006 | ty::CoroutineClosure(..)
1007 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
1008 | ty::Coroutine(..)
1009 | ty::CoroutineWitness(..)
1010 | ty::Never
1011 | ty::Foreign(..)
1012 | ty::Adt(_, _)
1013 | ty::Str
1014 | ty::Slice(_)
1015 | ty::Dynamic(_, _)
1016 | ty::Tuple(_)
1017 | ty::Error(_) => self_ty.discriminant_ty(ecx.cx()),
1018
1019 ty::UnsafeBinder(_) => {
1020 {
::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
format_args!("discr subgoal...")));
}todo!("discr subgoal...")
1022 }
1023
1024 ty::Alias(ty::IsRigid::Yes, _) | ty::Param(_) | ty::Placeholder(..) => {
1028 return ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1029 ecx.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
1030 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1031 });
1032 }
1033
1034 ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
1035 | ty::Alias(ty::IsRigid::No, _)
1036 | ty::Bound(..) => {
::core::panicking::panic_fmt(format_args!("unexpected self ty `{0:?}` when normalizing `<T as DiscriminantKind>::Discriminant`",
goal.predicate.self_ty()));
}panic!(
1037 "unexpected self ty `{:?}` when normalizing `<T as DiscriminantKind>::Discriminant`",
1038 goal.predicate.self_ty()
1039 ),
1040 };
1041
1042 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1043 ecx.instantiate_normalizes_to_term(goal, discriminant_ty.into())?;
1044 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1045 })
1046 }
1047
1048 fn consider_builtin_destruct_candidate(
1049 _ecx: &mut EvalCtxt<'_, D>,
1050 goal: Goal<I, Self>,
1051 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1052 {
::core::panicking::panic_fmt(format_args!("`Destruct` does not have an associated type: {0:?}",
goal));
};panic!("`Destruct` does not have an associated type: {:?}", goal);
1053 }
1054
1055 fn consider_builtin_transmute_candidate(
1056 _ecx: &mut EvalCtxt<'_, D>,
1057 goal: Goal<I, Self>,
1058 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1059 {
::core::panicking::panic_fmt(format_args!("`TransmuteFrom` does not have an associated type: {0:?}",
goal));
}panic!("`TransmuteFrom` does not have an associated type: {:?}", goal)
1060 }
1061
1062 fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
1063 _ecx: &mut EvalCtxt<'_, D>,
1064 goal: Goal<I, Self>,
1065 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1066 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`BikeshedGuaranteedNoDrop` does not have an associated type: {0:?}",
goal)));
}unreachable!("`BikeshedGuaranteedNoDrop` does not have an associated type: {:?}", goal)
1067 }
1068
1069 fn consider_builtin_field_candidate(
1070 ecx: &mut EvalCtxt<'_, D>,
1071 goal: Goal<I, Self>,
1072 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
1073 let self_ty = goal.predicate.self_ty();
1074 let ty::Adt(def, args) = self_ty.kind() else {
1075 return Err(NoSolution.into());
1076 };
1077 let Some(FieldInfo { base, ty, .. }) = def.field_representing_type_info(ecx.cx(), args)
1078 else {
1079 return Err(NoSolution.into());
1080 };
1081 let def_id = goal.predicate.alias.expect_projection_ty_def_id();
1082 let ty = match ecx.cx().as_projection_lang_item(def_id) {
1083 Some(SolverProjectionLangItem::FieldBase) => base,
1084 Some(SolverProjectionLangItem::FieldType) => ty,
1085 _ => {
::core::panicking::panic_fmt(format_args!("unexpected associated type {0:?} in `Field`",
goal.predicate));
}panic!("unexpected associated type {:?} in `Field`", goal.predicate),
1086 };
1087 ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| {
1088 ecx.instantiate_normalizes_to_term(goal, ty.into())?;
1089 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
1090 })
1091 }
1092}
1093
1094impl<D, I> EvalCtxt<'_, D>
1095where
1096 D: SolverDelegate<Interner = I>,
1097 I: Interner,
1098{
1099 fn translate_args(
1100 &mut self,
1101 goal: Goal<I, ty::NormalizesTo<I>>,
1102 impl_def_id: I::ImplId,
1103 impl_args: I::GenericArgs,
1104 impl_trait_ref: rustc_type_ir::TraitRef<I>,
1105 target_container_def_id: I::DefId,
1106 ) -> Result<I::GenericArgs, NoSolutionOrRerunNonErased> {
1107 let cx = self.cx();
1108 Ok(if target_container_def_id == impl_trait_ref.def_id.into() {
1109 goal.predicate.alias.args
1111 } else if target_container_def_id == impl_def_id.into() {
1112 goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id.into(), impl_args)
1115 } else {
1116 let target_args = self.fresh_args_for_item(target_container_def_id);
1117 let target_trait_ref = cx
1118 .impl_trait_ref(target_container_def_id.try_into().unwrap())
1119 .instantiate(cx, target_args)
1120 .skip_norm_wip();
1121 self.eq(goal.param_env, impl_trait_ref, target_trait_ref)?;
1123 self.add_goals(
1126 GoalSource::Misc,
1127 cx.predicates_of(target_container_def_id)
1128 .iter_instantiated(cx, target_args)
1129 .map(Unnormalized::skip_norm_wip)
1130 .map(|pred| goal.with(cx, pred)),
1131 )?;
1132 goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id.into(), target_args)
1133 })
1134 }
1135}