1pub(super) mod structural_traits;
4
5use std::cell::Cell;
6use std::ops::ControlFlow;
7
8use derive_where::derive_where;
9use rustc_type_ir::inherent::*;
10use rustc_type_ir::lang_items::SolverTraitLangItem;
11use rustc_type_ir::search_graph::CandidateHeadUsages;
12use rustc_type_ir::solve::{
13 AliasBoundKind, MaybeInfo, NoSolutionOrRerunNonErased, QueryResultOrRerunNonErased,
14 RerunNonErased, RerunReason, RerunResultExt, SizedTraitKind, StalledOnCoroutines,
15};
16use rustc_type_ir::{
17 self as ty, AliasTy, Interner, MayBeErased, Region, TypeFlags, TypeFoldable, TypeFolder,
18 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
19 TypingMode, Unnormalized, Upcast, elaborate,
20};
21use tracing::{debug, instrument};
22
23use super::trait_goals::TraitGoalProvenVia;
24use super::{has_only_region_constraints, inspect};
25use crate::delegate::SolverDelegate;
26use crate::solve::inspect::ProbeKind;
27use crate::solve::{
28 BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource,
29 MaybeCause, NoSolution, OpaqueTypesJank, ParamEnvSource, QueryResult,
30 has_no_inference_or_external_constraints,
31};
32
33#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for Candidate<I> where I: Interner {
fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
-> ::core::fmt::Result {
match self {
Candidate {
source: ref __field_source,
result: ref __field_result,
head_usages: ref __field_head_usages } => {
let mut __builder =
::core::fmt::Formatter::debug_struct(__f, "Candidate");
::core::fmt::DebugStruct::field(&mut __builder, "source",
__field_source);
::core::fmt::DebugStruct::field(&mut __builder, "result",
__field_result);
::core::fmt::DebugStruct::field(&mut __builder, "head_usages",
__field_head_usages);
::core::fmt::DebugStruct::finish(&mut __builder)
}
}
}
}#[derive_where(Debug; I: Interner)]
38pub(super) struct Candidate<I: Interner> {
39 pub(super) source: CandidateSource<I>,
40 pub(super) result: CanonicalResponse<I>,
41 pub(super) head_usages: CandidateHeadUsages,
42}
43
44pub(super) trait GoalKind<D, I = <D as SolverDelegate>::Interner>:
46 TypeFoldable<I> + Copy + Eq + std::fmt::Display
47where
48 D: SolverDelegate<Interner = I>,
49 I: Interner,
50{
51 fn self_ty(self) -> I::Ty;
52
53 fn trait_ref(self, cx: I) -> ty::TraitRef<I>;
54
55 fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self;
56
57 fn trait_def_id(self, cx: I) -> I::TraitId;
58
59 fn probe_and_consider_implied_clause(
63 ecx: &mut EvalCtxt<'_, D>,
64 parent_source: CandidateSource<I>,
65 goal: Goal<I, Self>,
66 assumption: I::Clause,
67 requirements: impl IntoIterator<Item = (GoalSource, Goal<I, I::Predicate>)>,
68 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
69 Self::probe_and_match_goal_against_assumption(ecx, parent_source, goal, assumption, |ecx| {
70 for (nested_source, goal) in requirements {
71 ecx.add_goal(nested_source, goal)?;
72 }
73 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
74 })
75 }
76
77 fn probe_and_consider_object_bound_candidate(
83 ecx: &mut EvalCtxt<'_, D>,
84 source: CandidateSource<I>,
85 goal: Goal<I, Self>,
86 assumption: I::Clause,
87 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
88 Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| {
89 let cx = ecx.cx();
90 let ty::Dynamic(bounds, _) = goal.predicate.self_ty().kind() else {
91 {
::core::panicking::panic_fmt(format_args!("expected object type in `probe_and_consider_object_bound_candidate`"));
};panic!("expected object type in `probe_and_consider_object_bound_candidate`");
92 };
93
94 let trait_ref = assumption.kind().map_bound(|clause| match clause {
95 ty::ClauseKind::Trait(pred) => pred.trait_ref,
96 ty::ClauseKind::Projection(proj) => proj.projection_term.trait_ref(cx),
97
98 ty::ClauseKind::RegionOutlives(..)
99 | ty::ClauseKind::TypeOutlives(..)
100 | ty::ClauseKind::ConstArgHasType(..)
101 | ty::ClauseKind::WellFormed(..)
102 | ty::ClauseKind::ConstEvaluatable(..)
103 | ty::ClauseKind::HostEffect(..)
104 | ty::ClauseKind::UnstableFeature(..) => {
105 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("expected trait or projection predicate as an assumption")));
}unreachable!("expected trait or projection predicate as an assumption")
106 }
107 });
108
109 match structural_traits::predicates_for_object_candidate(
110 ecx,
111 goal.param_env,
112 trait_ref,
113 bounds,
114 ) {
115 Ok(requirements) => {
116 ecx.add_goals(GoalSource::ImplWhereBound, requirements)?;
117 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
118 }
119 Err(_) => {
120 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
121 }
122 }
123 })
124 }
125
126 fn consider_additional_alias_assumptions(
130 ecx: &mut EvalCtxt<'_, D>,
131 goal: Goal<I, Self>,
132 alias_ty: ty::AliasTy<I>,
133 ) -> Vec<Candidate<I>>;
134
135 fn probe_and_consider_param_env_candidate(
136 ecx: &mut EvalCtxt<'_, D>,
137 goal: Goal<I, Self>,
138 assumption: I::Clause,
139 ) -> Result<Result<Candidate<I>, CandidateHeadUsages>, RerunNonErased> {
140 match Self::fast_reject_assumption(ecx, goal, assumption) {
141 Ok(()) => {}
142 Err(NoSolution) => return Ok(Err(CandidateHeadUsages::default())),
143 }
144
145 let source = Cell::new(CandidateSource::ParamEnv(ParamEnvSource::Global));
152 let (result, head_usages) = ecx
153 .probe(|result: &QueryResult<I>| inspect::ProbeKind::TraitCandidate {
154 source: source.get(),
155 result: *result,
156 })
157 .enter_single_candidate(|ecx| {
158 Self::match_assumption(
159 ecx,
160 goal,
161 assumption,
162 |ecx| -> Result<_, NoSolutionOrRerunNonErased> {
163 ecx.try_evaluate_added_goals()?;
164 let (src, certainty) =
165 ecx.characterize_param_env_assumption(goal.param_env, assumption)?;
166 source.set(src);
167 ecx.evaluate_added_goals_and_make_canonical_response(certainty)
168 },
169 )
170 .map_err(Into::into)
171 });
172
173 Ok(match result.map_err_to_rerun()? {
174 Ok(result) => Ok(Candidate { source: source.get(), result, head_usages }),
175 Err(NoSolution) => Err(head_usages),
176 })
177 }
178
179 fn probe_and_match_goal_against_assumption(
184 ecx: &mut EvalCtxt<'_, D>,
185 source: CandidateSource<I>,
186 goal: Goal<I, Self>,
187 assumption: I::Clause,
188 then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
189 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
190 Self::fast_reject_assumption(ecx, goal, assumption)?;
191
192 ecx.probe_trait_candidate(source)
193 .enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
194 }
195
196 fn fast_reject_assumption(
199 ecx: &mut EvalCtxt<'_, D>,
200 goal: Goal<I, Self>,
201 assumption: I::Clause,
202 ) -> Result<(), NoSolution>;
203
204 fn match_assumption(
206 ecx: &mut EvalCtxt<'_, D>,
207 goal: Goal<I, Self>,
208 assumption: I::Clause,
209 then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
210 ) -> QueryResultOrRerunNonErased<I>;
211
212 fn consider_impl_candidate(
213 ecx: &mut EvalCtxt<'_, D>,
214 goal: Goal<I, Self>,
215 impl_def_id: I::ImplId,
216 then: impl FnOnce(&mut EvalCtxt<'_, D>, Certainty) -> QueryResultOrRerunNonErased<I>,
217 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
218
219 fn consider_error_guaranteed_candidate(
226 ecx: &mut EvalCtxt<'_, D>,
227 goal: Goal<I, Self>,
228 guar: I::ErrorGuaranteed,
229 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
230
231 fn consider_auto_trait_candidate(
236 ecx: &mut EvalCtxt<'_, D>,
237 goal: Goal<I, Self>,
238 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
239
240 fn consider_trait_alias_candidate(
242 ecx: &mut EvalCtxt<'_, D>,
243 goal: Goal<I, Self>,
244 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
245
246 fn consider_builtin_sizedness_candidates(
252 ecx: &mut EvalCtxt<'_, D>,
253 goal: Goal<I, Self>,
254 sizedness: SizedTraitKind,
255 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
256
257 fn consider_builtin_copy_clone_candidate(
262 ecx: &mut EvalCtxt<'_, D>,
263 goal: Goal<I, Self>,
264 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
265
266 fn consider_builtin_fn_ptr_trait_candidate(
268 ecx: &mut EvalCtxt<'_, D>,
269 goal: Goal<I, Self>,
270 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
271
272 fn consider_builtin_fn_trait_candidates(
275 ecx: &mut EvalCtxt<'_, D>,
276 goal: Goal<I, Self>,
277 kind: ty::ClosureKind,
278 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
279
280 fn consider_builtin_async_fn_trait_candidates(
283 ecx: &mut EvalCtxt<'_, D>,
284 goal: Goal<I, Self>,
285 kind: ty::ClosureKind,
286 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
287
288 fn consider_builtin_async_fn_kind_helper_candidate(
292 ecx: &mut EvalCtxt<'_, D>,
293 goal: Goal<I, Self>,
294 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
295
296 fn consider_builtin_tuple_candidate(
298 ecx: &mut EvalCtxt<'_, D>,
299 goal: Goal<I, Self>,
300 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
301
302 fn consider_builtin_pointee_candidate(
308 ecx: &mut EvalCtxt<'_, D>,
309 goal: Goal<I, Self>,
310 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
311
312 fn consider_builtin_future_candidate(
316 ecx: &mut EvalCtxt<'_, D>,
317 goal: Goal<I, Self>,
318 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
319
320 fn consider_builtin_iterator_candidate(
324 ecx: &mut EvalCtxt<'_, D>,
325 goal: Goal<I, Self>,
326 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
327
328 fn consider_builtin_fused_iterator_candidate(
331 ecx: &mut EvalCtxt<'_, D>,
332 goal: Goal<I, Self>,
333 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
334
335 fn consider_builtin_async_iterator_candidate(
336 ecx: &mut EvalCtxt<'_, D>,
337 goal: Goal<I, Self>,
338 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
339
340 fn consider_builtin_coroutine_candidate(
344 ecx: &mut EvalCtxt<'_, D>,
345 goal: Goal<I, Self>,
346 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
347
348 fn consider_builtin_discriminant_kind_candidate(
349 ecx: &mut EvalCtxt<'_, D>,
350 goal: Goal<I, Self>,
351 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
352
353 fn consider_builtin_destruct_candidate(
354 ecx: &mut EvalCtxt<'_, D>,
355 goal: Goal<I, Self>,
356 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
357
358 fn consider_builtin_transmute_candidate(
359 ecx: &mut EvalCtxt<'_, D>,
360 goal: Goal<I, Self>,
361 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
362
363 fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
364 ecx: &mut EvalCtxt<'_, D>,
365 goal: Goal<I, Self>,
366 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
367
368 fn consider_builtin_try_as_dyn_candidate(
369 ecx: &mut EvalCtxt<'_, D>,
370 goal: Goal<I, Self>,
371 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
372
373 fn consider_structural_builtin_unsize_candidates(
381 ecx: &mut EvalCtxt<'_, D>,
382 goal: Goal<I, Self>,
383 ) -> Result<Vec<Candidate<I>>, RerunNonErased>;
384
385 fn consider_builtin_field_candidate(
386 ecx: &mut EvalCtxt<'_, D>,
387 goal: Goal<I, Self>,
388 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
389}
390
391pub(super) enum AssembleCandidatesFrom {
399 All,
400 EnvAndBounds,
404}
405
406impl AssembleCandidatesFrom {
407 fn should_assemble_impl_candidates(&self) -> bool {
408 match self {
409 AssembleCandidatesFrom::All => true,
410 AssembleCandidatesFrom::EnvAndBounds => false,
411 }
412 }
413}
414
415#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FailedCandidateInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"FailedCandidateInfo", "param_env_head_usages",
&&self.param_env_head_usages)
}
}Debug)]
424pub(super) struct FailedCandidateInfo {
425 pub param_env_head_usages: CandidateHeadUsages,
426}
427
428impl<D, I> EvalCtxt<'_, D>
429where
430 D: SolverDelegate<Interner = I>,
431 I: Interner,
432{
433 pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<D>>(
437 &mut self,
438 goal: Goal<I, G>,
439 assemble_from: AssembleCandidatesFrom,
440 ) -> Result<(Vec<Candidate<I>>, FailedCandidateInfo), RerunNonErased> {
441 let mut candidates = ::alloc::vec::Vec::new()vec![];
442 let mut failed_candidate_info =
443 FailedCandidateInfo { param_env_head_usages: CandidateHeadUsages::default() };
444 let Ok(normalized_self_ty) =
445 self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty())
446 else {
447 return Ok((candidates, failed_candidate_info));
448 };
449
450 let goal: Goal<I, G> = goal
451 .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty));
452
453 if normalized_self_ty.is_ty_var() {
454 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:454",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(454u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self type has been normalized to infer")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("self type has been normalized to infer");
455 self.try_assemble_bounds_via_registered_opaques(goal, assemble_from, &mut candidates)?;
456 return Ok((candidates, failed_candidate_info));
457 }
458
459 let goal = self.resolve_vars_if_possible(goal);
462
463 if self.typing_mode().is_coherence()
464 && let Ok(candidate) = self.consider_coherence_unknowable_candidate(goal)
465 {
466 candidates.push(candidate);
467 return Ok((candidates, failed_candidate_info));
468 }
469
470 self.assemble_alias_bound_candidates(goal, &mut candidates)?;
471 self.assemble_param_env_candidates(goal, &mut candidates, &mut failed_candidate_info)?;
472
473 match assemble_from {
474 AssembleCandidatesFrom::All => {
475 self.assemble_builtin_impl_candidates(goal, &mut candidates)?;
476 let assemble_impls = match self.typing_mode() {
488 TypingMode::Coherence => true,
489 TypingMode::Typeck { .. }
490 | TypingMode::PostTypeckUntilBorrowck { .. }
491 | TypingMode::Reflection
492 | TypingMode::PostBorrowck { .. }
493 | TypingMode::PostAnalysis
494 | TypingMode::Codegen
495 | TypingMode::ErasedNotCoherence(MayBeErased) => !candidates.iter().any(|c| {
496 #[allow(non_exhaustive_omitted_patterns)] match c.source {
CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) |
CandidateSource::AliasBound(_) => true,
_ => false,
}matches!(
497 c.source,
498 CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)
499 | CandidateSource::AliasBound(_)
500 ) && has_no_inference_or_external_constraints(c.result)
501 }),
502 };
503 if assemble_impls {
504 self.assemble_impl_candidates(goal, &mut candidates)?;
505 self.assemble_object_bound_candidates(goal, &mut candidates);
506 }
507 }
508 AssembleCandidatesFrom::EnvAndBounds => {
509 if #[allow(non_exhaustive_omitted_patterns)] match normalized_self_ty.kind() {
ty::Dynamic(..) => true,
_ => false,
}matches!(normalized_self_ty.kind(), ty::Dynamic(..))
513 && !candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.source {
CandidateSource::ParamEnv(_) => true,
_ => false,
}matches!(c.source, CandidateSource::ParamEnv(_)))
514 {
515 self.assemble_object_bound_candidates(goal, &mut candidates);
516 }
517 }
518 }
519
520 Ok((candidates, failed_candidate_info))
521 }
522
523 pub(super) fn forced_ambiguity(
524 &mut self,
525 maybe: MaybeInfo,
526 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
527 let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
536 let certainty = Certainty::Maybe(maybe);
537 self.probe_trait_candidate(source)
538 .enter(|this| this.evaluate_added_goals_and_make_canonical_response(certainty))
539 }
540
541 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("assemble_impl_candidates",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(541u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), RerunNonErased> =
loop {};
return __tracing_attr_fake_return;
}
{
let cx = self.cx();
cx.for_each_relevant_impl(goal.predicate.trait_ref(cx),
|impl_def_id| -> Result<_, _>
{
if cx.impl_is_default(impl_def_id) { return Ok(()); }
match G::consider_impl_candidate(self, goal, impl_def_id,
|ecx, certainty|
{
ecx.evaluate_added_goals_and_make_canonical_response(certainty)
}).map_err_to_rerun()? {
Ok(candidate) => candidates.push(candidate),
Err(NoSolution) => {}
}
Ok(())
})
}
}
}#[instrument(level = "trace", skip_all)]
542 fn assemble_impl_candidates<G: GoalKind<D>>(
543 &mut self,
544 goal: Goal<I, G>,
545 candidates: &mut Vec<Candidate<I>>,
546 ) -> Result<(), RerunNonErased> {
547 let cx = self.cx();
548 cx.for_each_relevant_impl(goal.predicate.trait_ref(cx), |impl_def_id| -> Result<_, _> {
549 if cx.impl_is_default(impl_def_id) {
553 return Ok(());
554 }
555 match G::consider_impl_candidate(self, goal, impl_def_id, |ecx, certainty| {
556 ecx.evaluate_added_goals_and_make_canonical_response(certainty)
557 })
558 .map_err_to_rerun()?
559 {
560 Ok(candidate) => candidates.push(candidate),
561 Err(NoSolution) => {}
562 }
563
564 Ok(())
565 })
566 }
567
568 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("assemble_builtin_impl_candidates",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(568u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), RerunNonErased> =
loop {};
return __tracing_attr_fake_return;
}
{
let cx = self.cx();
let trait_def_id = goal.predicate.trait_def_id(cx);
if self.typing_mode().is_reflection() { return Ok(()); }
let result =
if let ty::Error(guar) = goal.predicate.self_ty().kind() {
G::consider_error_guaranteed_candidate(self, goal, guar)
} else if cx.trait_is_auto(trait_def_id) {
G::consider_auto_trait_candidate(self, goal)
} else if cx.trait_is_alias(trait_def_id) {
G::consider_trait_alias_candidate(self, goal)
} else {
match cx.as_trait_lang_item(trait_def_id) {
Some(SolverTraitLangItem::Sized) => {
G::consider_builtin_sizedness_candidates(self, goal,
SizedTraitKind::Sized)
}
Some(SolverTraitLangItem::MetaSized) => {
G::consider_builtin_sizedness_candidates(self, goal,
SizedTraitKind::MetaSized)
}
Some(SolverTraitLangItem::PointeeSized) => {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`PointeeSized` is removed during lowering")));
};
}
Some(SolverTraitLangItem::Copy | SolverTraitLangItem::Clone
| SolverTraitLangItem::TrivialClone) =>
G::consider_builtin_copy_clone_candidate(self, goal),
Some(SolverTraitLangItem::Fn) => {
G::consider_builtin_fn_trait_candidates(self, goal,
ty::ClosureKind::Fn)
}
Some(SolverTraitLangItem::FnMut) => {
G::consider_builtin_fn_trait_candidates(self, goal,
ty::ClosureKind::FnMut)
}
Some(SolverTraitLangItem::FnOnce) => {
G::consider_builtin_fn_trait_candidates(self, goal,
ty::ClosureKind::FnOnce)
}
Some(SolverTraitLangItem::AsyncFn) => {
G::consider_builtin_async_fn_trait_candidates(self, goal,
ty::ClosureKind::Fn)
}
Some(SolverTraitLangItem::AsyncFnMut) => {
G::consider_builtin_async_fn_trait_candidates(self, goal,
ty::ClosureKind::FnMut)
}
Some(SolverTraitLangItem::AsyncFnOnce) => {
G::consider_builtin_async_fn_trait_candidates(self, goal,
ty::ClosureKind::FnOnce)
}
Some(SolverTraitLangItem::FnPtrTrait) => {
G::consider_builtin_fn_ptr_trait_candidate(self, goal)
}
Some(SolverTraitLangItem::AsyncFnKindHelper) => {
G::consider_builtin_async_fn_kind_helper_candidate(self,
goal)
}
Some(SolverTraitLangItem::Tuple) =>
G::consider_builtin_tuple_candidate(self, goal),
Some(SolverTraitLangItem::PointeeTrait) => {
G::consider_builtin_pointee_candidate(self, goal)
}
Some(SolverTraitLangItem::Future) => {
G::consider_builtin_future_candidate(self, goal)
}
Some(SolverTraitLangItem::Iterator) => {
G::consider_builtin_iterator_candidate(self, goal)
}
Some(SolverTraitLangItem::FusedIterator) => {
G::consider_builtin_fused_iterator_candidate(self, goal)
}
Some(SolverTraitLangItem::AsyncIterator) => {
G::consider_builtin_async_iterator_candidate(self, goal)
}
Some(SolverTraitLangItem::Coroutine) => {
G::consider_builtin_coroutine_candidate(self, goal)
}
Some(SolverTraitLangItem::DiscriminantKind) => {
G::consider_builtin_discriminant_kind_candidate(self, goal)
}
Some(SolverTraitLangItem::Destruct) => {
G::consider_builtin_destruct_candidate(self, goal)
}
Some(SolverTraitLangItem::TransmuteTrait) => {
G::consider_builtin_transmute_candidate(self, goal)
}
Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self,
goal)
}
Some(SolverTraitLangItem::TryAsDyn) => {
G::consider_builtin_try_as_dyn_candidate(self, goal)
}
Some(SolverTraitLangItem::Field) =>
G::consider_builtin_field_candidate(self, goal),
_ => Err(NoSolution.into()),
}
};
candidates.extend(result);
if cx.is_trait_lang_item(trait_def_id,
SolverTraitLangItem::Unsize) {
candidates.extend(G::consider_structural_builtin_unsize_candidates(self,
goal)?);
}
Ok(())
}
}
}#[instrument(level = "trace", skip_all)]
569 fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
570 &mut self,
571 goal: Goal<I, G>,
572 candidates: &mut Vec<Candidate<I>>,
573 ) -> Result<(), RerunNonErased> {
574 let cx = self.cx();
575 let trait_def_id = goal.predicate.trait_def_id(cx);
576
577 if self.typing_mode().is_reflection() {
582 return Ok(());
583 }
584
585 let result = if let ty::Error(guar) = goal.predicate.self_ty().kind() {
593 G::consider_error_guaranteed_candidate(self, goal, guar)
594 } else if cx.trait_is_auto(trait_def_id) {
595 G::consider_auto_trait_candidate(self, goal)
596 } else if cx.trait_is_alias(trait_def_id) {
597 G::consider_trait_alias_candidate(self, goal)
598 } else {
599 match cx.as_trait_lang_item(trait_def_id) {
600 Some(SolverTraitLangItem::Sized) => {
601 G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
602 }
603 Some(SolverTraitLangItem::MetaSized) => {
604 G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
605 }
606 Some(SolverTraitLangItem::PointeeSized) => {
607 unreachable!("`PointeeSized` is removed during lowering");
608 }
609 Some(
610 SolverTraitLangItem::Copy
611 | SolverTraitLangItem::Clone
612 | SolverTraitLangItem::TrivialClone,
613 ) => G::consider_builtin_copy_clone_candidate(self, goal),
614 Some(SolverTraitLangItem::Fn) => {
615 G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
616 }
617 Some(SolverTraitLangItem::FnMut) => {
618 G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
619 }
620 Some(SolverTraitLangItem::FnOnce) => {
621 G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
622 }
623 Some(SolverTraitLangItem::AsyncFn) => {
624 G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
625 }
626 Some(SolverTraitLangItem::AsyncFnMut) => {
627 G::consider_builtin_async_fn_trait_candidates(
628 self,
629 goal,
630 ty::ClosureKind::FnMut,
631 )
632 }
633 Some(SolverTraitLangItem::AsyncFnOnce) => {
634 G::consider_builtin_async_fn_trait_candidates(
635 self,
636 goal,
637 ty::ClosureKind::FnOnce,
638 )
639 }
640 Some(SolverTraitLangItem::FnPtrTrait) => {
641 G::consider_builtin_fn_ptr_trait_candidate(self, goal)
642 }
643 Some(SolverTraitLangItem::AsyncFnKindHelper) => {
644 G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
645 }
646 Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
647 Some(SolverTraitLangItem::PointeeTrait) => {
648 G::consider_builtin_pointee_candidate(self, goal)
649 }
650 Some(SolverTraitLangItem::Future) => {
651 G::consider_builtin_future_candidate(self, goal)
652 }
653 Some(SolverTraitLangItem::Iterator) => {
654 G::consider_builtin_iterator_candidate(self, goal)
655 }
656 Some(SolverTraitLangItem::FusedIterator) => {
657 G::consider_builtin_fused_iterator_candidate(self, goal)
658 }
659 Some(SolverTraitLangItem::AsyncIterator) => {
660 G::consider_builtin_async_iterator_candidate(self, goal)
661 }
662 Some(SolverTraitLangItem::Coroutine) => {
663 G::consider_builtin_coroutine_candidate(self, goal)
664 }
665 Some(SolverTraitLangItem::DiscriminantKind) => {
666 G::consider_builtin_discriminant_kind_candidate(self, goal)
667 }
668 Some(SolverTraitLangItem::Destruct) => {
669 G::consider_builtin_destruct_candidate(self, goal)
670 }
671 Some(SolverTraitLangItem::TransmuteTrait) => {
672 G::consider_builtin_transmute_candidate(self, goal)
673 }
674 Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
675 G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
676 }
677 Some(SolverTraitLangItem::TryAsDyn) => {
678 G::consider_builtin_try_as_dyn_candidate(self, goal)
679 }
680 Some(SolverTraitLangItem::Field) => G::consider_builtin_field_candidate(self, goal),
681 _ => Err(NoSolution.into()),
682 }
683 };
684
685 candidates.extend(result);
686
687 if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
690 candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)?);
691 }
692
693 Ok(())
694 }
695
696 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("assemble_param_env_candidates",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(696u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), RerunNonErased> =
loop {};
return __tracing_attr_fake_return;
}
{
for assumption in goal.param_env.caller_bounds().iter() {
match G::probe_and_consider_param_env_candidate(self, goal,
assumption)? {
Ok(candidate) => candidates.push(candidate),
Err(head_usages) => {
failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
}
}
}
Ok(())
}
}
}#[instrument(level = "trace", skip_all)]
697 fn assemble_param_env_candidates<G: GoalKind<D>>(
698 &mut self,
699 goal: Goal<I, G>,
700 candidates: &mut Vec<Candidate<I>>,
701 failed_candidate_info: &mut FailedCandidateInfo,
702 ) -> Result<(), RerunNonErased> {
703 for assumption in goal.param_env.caller_bounds().iter() {
704 match G::probe_and_consider_param_env_candidate(self, goal, assumption)? {
705 Ok(candidate) => candidates.push(candidate),
706 Err(head_usages) => {
707 failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
708 }
709 }
710 }
711
712 Ok(())
713 }
714
715 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("assemble_alias_bound_candidates",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(715u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), RerunNonErased> =
loop {};
return __tracing_attr_fake_return;
}
{
let res =
self.probe(|_|
ProbeKind::NormalizedSelfTyAssembly).enter(|ecx|
{
ecx.assemble_alias_bound_candidates_recur(goal.predicate.self_ty(),
goal, candidates, AliasBoundKind::SelfBounds)?;
Ok(())
});
match res {
Ok(_) => Ok(()),
Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
::core::panicking::panic("internal error: entered unreachable code")
}
}
}
}
}#[instrument(level = "trace", skip_all)]
716 fn assemble_alias_bound_candidates<G: GoalKind<D>>(
717 &mut self,
718 goal: Goal<I, G>,
719 candidates: &mut Vec<Candidate<I>>,
720 ) -> Result<(), RerunNonErased> {
721 let res = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
722 ecx.assemble_alias_bound_candidates_recur(
723 goal.predicate.self_ty(),
724 goal,
725 candidates,
726 AliasBoundKind::SelfBounds,
727 )?;
728 Ok(())
729 });
730
731 match res {
733 Ok(_) => Ok(()),
734 Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
735 Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
736 unreachable!()
737 }
738 }
739 }
740
741 fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
751 &mut self,
752 self_ty: I::Ty,
753 goal: Goal<I, G>,
754 candidates: &mut Vec<Candidate<I>>,
755 consider_self_bounds: AliasBoundKind,
756 ) -> Result<(), RerunNonErased> {
757 let (alias_ty, def_id) = match self_ty.kind() {
758 ty::Bool
759 | ty::Char
760 | ty::Int(_)
761 | ty::Uint(_)
762 | ty::Float(_)
763 | ty::Adt(_, _)
764 | ty::Foreign(_)
765 | ty::Str
766 | ty::Array(_, _)
767 | ty::Pat(_, _)
768 | ty::Slice(_)
769 | ty::RawPtr(_, _)
770 | ty::Ref(_, _, _)
771 | ty::FnDef(_, _)
772 | ty::FnPtr(..)
773 | ty::UnsafeBinder(_)
774 | ty::Dynamic(..)
775 | ty::Closure(..)
776 | ty::CoroutineClosure(..)
777 | ty::Coroutine(..)
778 | ty::CoroutineWitness(..)
779 | ty::Never
780 | ty::Tuple(_)
781 | ty::Param(_)
782 | ty::Placeholder(..)
783 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
784 | ty::Error(_) => return Ok(()),
785 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
786 {
::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
goal));
}panic!("unexpected self type for `{goal:?}`")
787 }
788
789 ty::Infer(ty::TyVar(_)) => {
790 if let Ok(result) =
794 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
795 {
796 candidates.push(Candidate {
797 source: CandidateSource::AliasBound(consider_self_bounds),
798 result,
799 head_usages: CandidateHeadUsages::default(),
800 });
801 }
802 return Ok(());
803 }
804
805 ty::Alias(
806 ty::IsRigid::Yes,
807 alias_ty @ AliasTy { kind: ty::Projection { def_id }, .. },
808 ) => (alias_ty, def_id.into()),
809
810 ty::Alias(ty::IsRigid::Yes, alias_ty @ AliasTy { kind: ty::Opaque { def_id }, .. }) => {
811 (alias_ty, def_id.into())
812 }
813
814 ty::Alias(ty::IsRigid::No, _) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("non-rigid self type: {0:?}", self_ty)));
}unreachable!("non-rigid self type: {self_ty:?}"),
815
816 ty::Alias(
817 ty::IsRigid::Yes,
818 AliasTy { kind: ty::Inherent { .. } | ty::Free { .. }, .. },
819 ) => {
820 self.cx().delay_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not normalize {0:?}, it is not WF",
self_ty))
})format!("could not normalize {self_ty:?}, it is not WF"));
821 return Ok(());
822 }
823 };
824
825 match consider_self_bounds {
826 AliasBoundKind::SelfBounds => {
827 for assumption in self
828 .cx()
829 .item_self_bounds(def_id)
830 .iter_instantiated(self.cx(), alias_ty.args)
831 .map(Unnormalized::skip_norm_wip)
832 {
833 candidates.extend(G::probe_and_consider_implied_clause(
834 self,
835 CandidateSource::AliasBound(consider_self_bounds),
836 goal,
837 assumption,
838 [],
839 ));
840 }
841 }
842 AliasBoundKind::NonSelfBounds => {
843 for assumption in self
844 .cx()
845 .item_non_self_bounds(def_id)
846 .iter_instantiated(self.cx(), alias_ty.args)
847 .map(Unnormalized::skip_norm_wip)
848 {
849 candidates.extend(G::probe_and_consider_implied_clause(
850 self,
851 CandidateSource::AliasBound(consider_self_bounds),
852 goal,
853 assumption,
854 [],
855 ));
856 }
857 }
858 }
859
860 candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
861
862 let Some(projection_ty) = alias_ty.try_to_projection() else {
863 return Ok(());
864 };
865
866 match self.structurally_normalize_ty(goal.param_env, projection_ty.projection_self_ty()) {
868 Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
869 next_self_ty,
870 goal,
871 candidates,
872 AliasBoundKind::NonSelfBounds,
873 ),
874 Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Ok(()),
875 Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
876 }
877 }
878
879 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("assemble_object_bound_candidates",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(879u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let cx = self.cx();
if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
return;
}
if self.typing_mode().is_reflection() { return; }
let self_ty = goal.predicate.self_ty();
let bounds =
match self_ty.kind() {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) |
ty::Float(_) | ty::Adt(_, _) | ty::Foreign(_) | ty::Str |
ty::Array(_, _) | ty::Pat(_, _) | ty::Slice(_) |
ty::RawPtr(_, _) | ty::Ref(_, _, _) | ty::FnDef(_, _) |
ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::Alias(..) |
ty::Closure(..) | ty::CoroutineClosure(..) |
ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Never |
ty::Tuple(_) | ty::Param(_) | ty::Placeholder(..) |
ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) =>
return,
ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_)
| ty::FreshFloatTy(_)) | ty::Bound(..) => {
::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
goal));
}
ty::Dynamic(bounds, ..) => bounds,
};
if bounds.principal_def_id().is_some_and(|def_id|
!cx.trait_is_dyn_compatible(def_id)) {
return;
}
for bound in bounds.iter() {
match bound.skip_binder() {
ty::ExistentialPredicate::Trait(_) => {}
ty::ExistentialPredicate::Projection(_) |
ty::ExistentialPredicate::AutoTrait(_) => {
candidates.extend(G::probe_and_consider_object_bound_candidate(self,
CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal,
bound.with_self_ty(cx, self_ty)));
}
}
}
if let Some(principal) = bounds.principal() {
let principal_trait_ref = principal.with_self_ty(cx, self_ty);
for (idx, assumption) in
elaborate::supertraits(cx, principal_trait_ref).enumerate()
{
candidates.extend(G::probe_and_consider_object_bound_candidate(self,
CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
goal, assumption.upcast(cx)));
}
}
}
}
}#[instrument(level = "trace", skip_all)]
880 fn assemble_object_bound_candidates<G: GoalKind<D>>(
881 &mut self,
882 goal: Goal<I, G>,
883 candidates: &mut Vec<Candidate<I>>,
884 ) {
885 let cx = self.cx();
886 if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
887 return;
890 }
891
892 if self.typing_mode().is_reflection() {
897 return;
898 }
899
900 let self_ty = goal.predicate.self_ty();
901 let bounds = match self_ty.kind() {
902 ty::Bool
903 | ty::Char
904 | ty::Int(_)
905 | ty::Uint(_)
906 | ty::Float(_)
907 | ty::Adt(_, _)
908 | ty::Foreign(_)
909 | ty::Str
910 | ty::Array(_, _)
911 | ty::Pat(_, _)
912 | ty::Slice(_)
913 | ty::RawPtr(_, _)
914 | ty::Ref(_, _, _)
915 | ty::FnDef(_, _)
916 | ty::FnPtr(..)
917 | ty::UnsafeBinder(_)
918 | ty::Alias(..)
919 | ty::Closure(..)
920 | ty::CoroutineClosure(..)
921 | ty::Coroutine(..)
922 | ty::CoroutineWitness(..)
923 | ty::Never
924 | ty::Tuple(_)
925 | ty::Param(_)
926 | ty::Placeholder(..)
927 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
928 | ty::Error(_) => return,
929 ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
930 | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
931 ty::Dynamic(bounds, ..) => bounds,
932 };
933
934 if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
936 return;
937 }
938
939 for bound in bounds.iter() {
943 match bound.skip_binder() {
944 ty::ExistentialPredicate::Trait(_) => {
945 }
947 ty::ExistentialPredicate::Projection(_)
948 | ty::ExistentialPredicate::AutoTrait(_) => {
949 candidates.extend(G::probe_and_consider_object_bound_candidate(
950 self,
951 CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
952 goal,
953 bound.with_self_ty(cx, self_ty),
954 ));
955 }
956 }
957 }
958
959 if let Some(principal) = bounds.principal() {
963 let principal_trait_ref = principal.with_self_ty(cx, self_ty);
964 for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
965 candidates.extend(G::probe_and_consider_object_bound_candidate(
966 self,
967 CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
968 goal,
969 assumption.upcast(cx),
970 ));
971 }
972 }
973 }
974
975 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("consider_coherence_unknowable_candidate",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(981u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<Candidate<I>, NoSolutionOrRerunNonErased> = loop {};
return __tracing_attr_fake_return;
}
{
self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx|
{
let cx = ecx.cx();
let trait_ref = goal.predicate.trait_ref(cx);
if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
Err(NoSolution.into())
} else {
let predicate: I::Predicate = trait_ref.upcast(cx);
ecx.add_goals(GoalSource::Misc,
elaborate::elaborate(cx,
[predicate]).skip(1).map(|predicate|
goal.with(cx, predicate)))?;
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
}
})
}
}
}#[instrument(level = "trace", skip_all)]
982 fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
983 &mut self,
984 goal: Goal<I, G>,
985 ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
986 self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
987 let cx = ecx.cx();
988 let trait_ref = goal.predicate.trait_ref(cx);
989 if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
990 Err(NoSolution.into())
991 } else {
992 let predicate: I::Predicate = trait_ref.upcast(cx);
998 ecx.add_goals(
999 GoalSource::Misc,
1000 elaborate::elaborate(cx, [predicate])
1001 .skip(1)
1002 .map(|predicate| goal.with(cx, predicate)),
1003 )?;
1004 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1005 }
1006 })
1007 }
1008}
1009
1010pub(super) enum AllowInferenceConstraints {
1011 Yes,
1012 No,
1013}
1014
1015impl<D, I> EvalCtxt<'_, D>
1016where
1017 D: SolverDelegate<Interner = I>,
1018 I: Interner,
1019{
1020 pub(super) fn filter_specialized_impls(
1024 &mut self,
1025 allow_inference_constraints: AllowInferenceConstraints,
1026 candidates: &mut Vec<Candidate<I>>,
1027 ) {
1028 if self.typing_mode().is_coherence() {
1029 return;
1030 }
1031
1032 let mut i = 0;
1033 'outer: while i < candidates.len() {
1034 let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
1035 i += 1;
1036 continue;
1037 };
1038
1039 for (j, c) in candidates.iter().enumerate() {
1040 if i == j {
1041 continue;
1042 }
1043
1044 let CandidateSource::Impl(other_def_id) = c.source else {
1045 continue;
1046 };
1047
1048 if #[allow(non_exhaustive_omitted_patterns)] match allow_inference_constraints {
AllowInferenceConstraints::Yes => true,
_ => false,
}matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
1055 || has_only_region_constraints(c.result)
1056 {
1057 if self.cx().impl_specializes(other_def_id, victim_def_id) {
1058 candidates.remove(i);
1059 continue 'outer;
1060 }
1061 }
1062 }
1063
1064 i += 1;
1065 }
1066 }
1067
1068 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_assemble_bounds_via_registered_opaques",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(1079u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("goal")
}> =
::tracing::__macro_support::FieldName::new("goal");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("candidates")
}> =
::tracing::__macro_support::FieldName::new("candidates");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), RerunNonErased> =
loop {};
return __tracing_attr_fake_return;
}
{
let self_ty = goal.predicate.self_ty();
let opaque_types =
match self.typing_mode() {
TypingMode::Typeck { .. } =>
self.opaques_with_sub_unified_hidden_type(self_ty),
TypingMode::Coherence |
TypingMode::PostTypeckUntilBorrowck { .. } |
TypingMode::PostBorrowck { .. } | TypingMode::PostAnalysis |
TypingMode::Reflection | TypingMode::Codegen =>
::alloc::vec::Vec::new(),
TypingMode::ErasedNotCoherence(MayBeErased) => {
self.opaque_accesses.rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
Vec::new()
}
};
if opaque_types.is_empty() {
candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
return Ok(());
}
for &opaque_ty in &opaque_types {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1109",
"rustc_next_trait_solver::solve::assembly",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
::tracing_core::__macro_support::Option::Some(1109u32),
::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self ty is sub unified with {0:?}",
opaque_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
struct ReplaceOpaque<I: Interner> {
cx: I,
opaque_ty: ty::OpaqueAliasTy<I>,
self_ty: I::Ty,
}
impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
fn cx(&self) -> I { self.cx }
fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
if let ty::Alias(is_rigid, alias_ty) = ty.kind() &&
let Some(opaque_ty) = alias_ty.try_to_opaque() {
if opaque_ty == self.opaque_ty {
if true {
{
match (&is_rigid, &ty::IsRigid::No) {
(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);
}
}
}
};
};
return self.self_ty;
}
}
ty.super_fold_with(self)
}
}
for item_bound in
self.cx().item_self_bounds(opaque_ty.kind.into()).iter_instantiated(self.cx(),
opaque_ty.args).map(Unnormalized::skip_norm_wip) {
let assumption =
item_bound.fold_with(&mut ReplaceOpaque {
cx: self.cx(),
opaque_ty,
self_ty,
});
candidates.extend(G::probe_and_match_goal_against_assumption(self,
CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
goal, assumption,
|ecx|
{
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
}));
}
}
if assemble_from.should_assemble_impl_candidates() {
let cx = self.cx();
cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx),
|impl_def_id|
{
if cx.impl_is_default(impl_def_id) { return Ok(()); }
match G::consider_impl_candidate(self, goal, impl_def_id,
|ecx, certainty|
{
if ecx.shallow_resolve(self_ty).is_ty_var() {
let certainty = certainty.and(Certainty::AMBIGUOUS);
ecx.evaluate_added_goals_and_make_canonical_response(certainty)
} else { Err(NoSolution.into()) }
}).map_err_to_rerun()? {
Ok(candidate) => candidates.push(candidate),
Err(NoSolution) => {}
}
Ok(())
})?;
}
if candidates.is_empty() {
let source =
CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
let certainty =
Certainty::Maybe(MaybeInfo {
cause: MaybeCause::Ambiguity,
opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
stalled_on_coroutines: StalledOnCoroutines::No,
});
candidates.extend(self.probe_trait_candidate(source).enter(|this|
{
this.evaluate_added_goals_and_make_canonical_response(certainty)
}));
}
Ok(())
}
}
}#[tracing::instrument(skip(self, assemble_from))]
1080 fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
1081 &mut self,
1082 goal: Goal<I, G>,
1083 assemble_from: AssembleCandidatesFrom,
1084 candidates: &mut Vec<Candidate<I>>,
1085 ) -> Result<(), RerunNonErased> {
1086 let self_ty = goal.predicate.self_ty();
1087 let opaque_types = match self.typing_mode() {
1089 TypingMode::Typeck { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
1090 TypingMode::Coherence
1091 | TypingMode::PostTypeckUntilBorrowck { .. }
1092 | TypingMode::PostBorrowck { .. }
1093 | TypingMode::PostAnalysis
1094 | TypingMode::Reflection
1095 | TypingMode::Codegen => vec![],
1096 TypingMode::ErasedNotCoherence(MayBeErased) => {
1097 self.opaque_accesses
1098 .rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
1099 Vec::new()
1100 }
1101 };
1102
1103 if opaque_types.is_empty() {
1104 candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
1105 return Ok(());
1106 }
1107
1108 for &opaque_ty in &opaque_types {
1109 debug!("self ty is sub unified with {opaque_ty:?}");
1110
1111 struct ReplaceOpaque<I: Interner> {
1112 cx: I,
1113 opaque_ty: ty::OpaqueAliasTy<I>,
1114 self_ty: I::Ty,
1115 }
1116 impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
1117 fn cx(&self) -> I {
1118 self.cx
1119 }
1120 fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1121 if let ty::Alias(is_rigid, alias_ty) = ty.kind()
1122 && let Some(opaque_ty) = alias_ty.try_to_opaque()
1123 {
1124 if opaque_ty == self.opaque_ty {
1125 debug_assert_eq!(is_rigid, ty::IsRigid::No);
1126 return self.self_ty;
1127 }
1128 }
1129 ty.super_fold_with(self)
1130 }
1131 }
1132
1133 for item_bound in self
1141 .cx()
1142 .item_self_bounds(opaque_ty.kind.into())
1143 .iter_instantiated(self.cx(), opaque_ty.args)
1144 .map(Unnormalized::skip_norm_wip)
1145 {
1146 let assumption =
1147 item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), opaque_ty, self_ty });
1148 candidates.extend(G::probe_and_match_goal_against_assumption(
1149 self,
1150 CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1151 goal,
1152 assumption,
1153 |ecx| {
1154 ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1157 },
1158 ));
1159 }
1160 }
1161
1162 if assemble_from.should_assemble_impl_candidates() {
1167 let cx = self.cx();
1168 cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1169 if cx.impl_is_default(impl_def_id) {
1173 return Ok(());
1174 }
1175
1176 match G::consider_impl_candidate(self, goal, impl_def_id, |ecx, certainty| {
1177 if ecx.shallow_resolve(self_ty).is_ty_var() {
1178 let certainty = certainty.and(Certainty::AMBIGUOUS);
1180 ecx.evaluate_added_goals_and_make_canonical_response(certainty)
1181 } else {
1182 Err(NoSolution.into())
1188 }
1189 })
1190 .map_err_to_rerun()?
1191 {
1192 Ok(candidate) => candidates.push(candidate),
1193 Err(NoSolution) => {}
1194 }
1195
1196 Ok(())
1197 })?;
1198 }
1199
1200 if candidates.is_empty() {
1201 let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1202 let certainty = Certainty::Maybe(MaybeInfo {
1203 cause: MaybeCause::Ambiguity,
1204 opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1205 stalled_on_coroutines: StalledOnCoroutines::No,
1206 });
1207 candidates
1208 .extend(self.probe_trait_candidate(source).enter(|this| {
1209 this.evaluate_added_goals_and_make_canonical_response(certainty)
1210 }));
1211 }
1212
1213 Ok(())
1214 }
1215
1216 x;#[instrument(level = "debug", skip_all, fields(proven_via, goal), ret)]
1247 pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1248 &mut self,
1249 proven_via: Option<TraitGoalProvenVia>,
1250 goal: Goal<I, G>,
1251 inject_forced_ambiguity_candidate: impl FnOnce(
1252 &mut EvalCtxt<'_, D>,
1253 ) -> Option<
1254 Result<CanonicalResponse<I>, NoSolutionOrRerunNonErased>,
1255 >,
1256 inject_normalize_to_rigid_candidate: impl FnOnce(
1257 &mut EvalCtxt<'_, D>,
1258 ) -> Result<
1259 CanonicalResponse<I>,
1260 NoSolutionOrRerunNonErased,
1261 >,
1262 ) -> QueryResultOrRerunNonErased<I> {
1263 let Some(proven_via) = proven_via else {
1264 return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand| cand.result);
1271 };
1272
1273 match proven_via {
1274 TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1275 let (mut candidates, _) = self
1279 .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds)?;
1280 debug!(?candidates);
1281
1282 if candidates.is_empty() {
1285 return inject_normalize_to_rigid_candidate(self);
1286 }
1287
1288 if let Some(result) = inject_forced_ambiguity_candidate(self) {
1291 return result;
1292 }
1293
1294 if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1297 candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1298 }
1299
1300 if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1301 Ok(response)
1302 } else {
1303 self.flounder(&candidates).map_err(Into::into)
1304 }
1305 }
1306 TraitGoalProvenVia::Misc => {
1307 let (mut candidates, _) =
1308 self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1309
1310 if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1313 candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1314 }
1315
1316 self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1322 if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1323 Ok(response)
1324 } else {
1325 self.flounder(&candidates).map_err(Into::into)
1326 }
1327 }
1328 }
1329 }
1330
1331 fn characterize_param_env_assumption(
1345 &mut self,
1346 param_env: I::ParamEnv,
1347 assumption: I::Clause,
1348 ) -> Result<(CandidateSource<I>, Certainty), NoSolution> {
1349 if assumption.has_bound_vars() {
1352 return Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), Certainty::Yes));
1353 }
1354
1355 match assumption.visit_with(&mut FindParamInClause {
1356 ecx: self,
1357 param_env,
1358 universes: ::alloc::vec::Vec::new()vec![],
1359 recursion_depth: 0,
1360 }) {
1361 ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1362 ControlFlow::Break(Ok(certainty)) => {
1363 Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), certainty))
1364 }
1365 ControlFlow::Continue(()) => {
1366 Ok((CandidateSource::ParamEnv(ParamEnvSource::Global), Certainty::Yes))
1367 }
1368 }
1369 }
1370}
1371
1372struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1373 ecx: &'a mut EvalCtxt<'b, D>,
1374 param_env: I::ParamEnv,
1375 universes: Vec<Option<ty::UniverseIndex>>,
1376 recursion_depth: usize,
1377}
1378
1379impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1380where
1381 D: SolverDelegate<Interner = I>,
1382 I: Interner,
1383{
1384 type Result = ControlFlow<Result<Certainty, NoSolution>>;
1389
1390 fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1391 self.universes.push(None);
1392 t.super_visit_with(self)?;
1393 self.universes.pop();
1394 ControlFlow::Continue(())
1395 }
1396
1397 fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1398 let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1399 let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1400 return ControlFlow::Break(Err(NoSolution));
1401 };
1402
1403 match ty.kind() {
1404 ty::Placeholder(p) => {
1405 if p.universe() == ty::UniverseIndex::ROOT {
1406 ControlFlow::Break(Ok(Certainty::Yes))
1407 } else {
1408 ControlFlow::Continue(())
1409 }
1410 }
1411 ty::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1412 _ if ty.has_type_flags(
1413 TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1414 ) =>
1415 {
1416 self.recursion_depth += 1;
1417 if self.recursion_depth > self.ecx.cx().recursion_limit() {
1418 return ControlFlow::Break(Ok(Certainty::Maybe(MaybeInfo {
1419 cause: MaybeCause::Overflow {
1420 suggest_increasing_limit: true,
1421 keep_constraints: false,
1422 },
1423 opaque_types_jank: OpaqueTypesJank::AllGood,
1424 stalled_on_coroutines: StalledOnCoroutines::No,
1425 })));
1426 }
1427 let result = ty.super_visit_with(self);
1428 self.recursion_depth -= 1;
1429 result
1430 }
1431 _ => ControlFlow::Continue(()),
1432 }
1433 }
1434
1435 fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1436 let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1437 let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1438 return ControlFlow::Break(Err(NoSolution));
1439 };
1440
1441 match ct.kind() {
1442 ty::ConstKind::Placeholder(p) => {
1443 if p.universe() == ty::UniverseIndex::ROOT {
1444 ControlFlow::Break(Ok(Certainty::Yes))
1445 } else {
1446 ControlFlow::Continue(())
1447 }
1448 }
1449 ty::ConstKind::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1450 _ if ct.has_type_flags(
1451 TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1452 ) =>
1453 {
1454 ct.super_visit_with(self)
1456 }
1457 _ => ControlFlow::Continue(()),
1458 }
1459 }
1460
1461 fn visit_region(&mut self, r: Region<I>) -> Self::Result {
1462 match self.ecx.eager_resolve_region(r).kind() {
1463 ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1464 ty::RePlaceholder(p) => {
1465 if p.universe() == ty::UniverseIndex::ROOT {
1466 ControlFlow::Break(Ok(Certainty::Yes))
1467 } else {
1468 ControlFlow::Continue(())
1469 }
1470 }
1471 ty::ReVar(_) => ControlFlow::Break(Ok(Certainty::Yes)),
1472 ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1473 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unexpected region in param-env clause")));
}unreachable!("unexpected region in param-env clause")
1474 }
1475 }
1476 }
1477}