Skip to main content

rustc_next_trait_solver/solve/assembly/
mod.rs

1//! Code shared by trait and projection goals for candidate assembly.
2
3pub(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::assembly::structural_traits::AmbiguousOrRerunNonErased;
27use crate::solve::inspect::ProbeKind;
28use crate::solve::{
29    BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource,
30    MaybeCause, NoSolution, OpaqueTypesJank, ParamEnvSource, QueryResult,
31    has_no_inference_or_external_constraints,
32};
33
34/// A candidate is a possible way to prove a goal.
35///
36/// It consists of both the `source`, which describes how that goal would be proven,
37/// and the `result` when using the given `source`.
38#[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)]
39pub(super) struct Candidate<I: Interner> {
40    pub(super) source: CandidateSource<I>,
41    pub(super) result: CanonicalResponse<I>,
42    pub(super) head_usages: CandidateHeadUsages,
43}
44
45/// Methods used to assemble candidates for either trait or projection goals.
46pub(super) trait GoalKind<D, I = <D as SolverDelegate>::Interner>:
47    TypeFoldable<I> + Copy + Eq + std::fmt::Display
48where
49    D: SolverDelegate<Interner = I>,
50    I: Interner,
51{
52    fn self_ty(self) -> I::Ty;
53
54    fn trait_ref(self, cx: I) -> ty::TraitRef<I>;
55
56    fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self;
57
58    fn trait_def_id(self, cx: I) -> I::TraitId;
59
60    /// Consider a clause, which consists of a "assumption" and some "requirements",
61    /// to satisfy a goal. If the requirements hold, then attempt to satisfy our
62    /// goal by equating it with the assumption.
63    fn probe_and_consider_implied_clause(
64        ecx: &mut EvalCtxt<'_, D>,
65        parent_source: CandidateSource<I>,
66        goal: Goal<I, Self>,
67        assumption: I::Clause,
68        requirements: impl IntoIterator<Item = (GoalSource, Goal<I, I::Predicate>)>,
69    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
70        Self::probe_and_match_goal_against_assumption(ecx, parent_source, goal, assumption, |ecx| {
71            for (nested_source, goal) in requirements {
72                ecx.add_goal(nested_source, goal)?;
73            }
74            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
75        })
76    }
77
78    /// Consider a clause specifically for a `dyn Trait` self type. This requires
79    /// additionally checking all of the supertraits and object bounds to hold,
80    /// since they're not implied by the well-formedness of the object type.
81    /// `NormalizesTo` overrides this to not check the supertraits for backwards
82    /// compatibility with the old solver. cc trait-system-refactor-initiative#245.
83    fn probe_and_consider_object_bound_candidate(
84        ecx: &mut EvalCtxt<'_, D>,
85        source: CandidateSource<I>,
86        goal: Goal<I, Self>,
87        assumption: I::Clause,
88    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
89        Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| {
90            let cx = ecx.cx();
91            let ty::Dynamic(bounds, _) = goal.predicate.self_ty().kind() else {
92                {
    ::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`");
93            };
94
95            let trait_ref = assumption.kind().map_bound(|clause| match clause {
96                ty::ClauseKind::Trait(pred) => pred.trait_ref,
97                ty::ClauseKind::Projection(proj) => proj.projection_term.trait_ref(cx),
98
99                ty::ClauseKind::RegionOutlives(..)
100                | ty::ClauseKind::TypeOutlives(..)
101                | ty::ClauseKind::ConstArgHasType(..)
102                | ty::ClauseKind::WellFormed(..)
103                | ty::ClauseKind::ConstEvaluatable(..)
104                | ty::ClauseKind::HostEffect(..)
105                | ty::ClauseKind::UnstableFeature(..) => {
106                    {
    ::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")
107                }
108            });
109
110            match structural_traits::predicates_for_object_candidate(
111                ecx,
112                goal.param_env,
113                trait_ref,
114                bounds,
115            ) {
116                Ok(requirements) => {
117                    ecx.add_goals(GoalSource::ImplWhereBound, requirements)?;
118                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
119                }
120                Err(AmbiguousOrRerunNonErased::Ambiguous) => {
121                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
122                }
123                Err(AmbiguousOrRerunNonErased::RerunNonErased(rerun)) => Err(rerun.into()),
124            }
125        })
126    }
127
128    /// Assemble additional assumptions for an alias that are not included
129    /// in the item bounds of the alias. For now, this is limited to the
130    /// `explicit_implied_const_bounds` for an associated type.
131    fn consider_additional_alias_assumptions(
132        ecx: &mut EvalCtxt<'_, D>,
133        goal: Goal<I, Self>,
134        alias_ty: ty::AliasTy<I>,
135    ) -> Vec<Candidate<I>>;
136
137    fn probe_and_consider_param_env_candidate(
138        ecx: &mut EvalCtxt<'_, D>,
139        goal: Goal<I, Self>,
140        assumption: I::Clause,
141    ) -> Result<Result<Candidate<I>, CandidateHeadUsages>, RerunNonErased> {
142        match Self::fast_reject_assumption(ecx, goal, assumption) {
143            Ok(()) => {}
144            Err(NoSolution) => return Ok(Err(CandidateHeadUsages::default())),
145        }
146
147        // Dealing with `ParamEnv` candidates is a bit of a mess as we need to lazily
148        // check whether the candidate is global while considering normalization.
149        //
150        // We need to write into `source` inside of `match_assumption`, but need to access it
151        // in `probe` even if the candidate does not apply before we get there. We handle this
152        // by using a `Cell` here. We only ever write into it inside of `match_assumption`.
153        let source = Cell::new(CandidateSource::ParamEnv(ParamEnvSource::Global));
154        let (result, head_usages) = ecx
155            .probe(|result: &QueryResult<I>| inspect::ProbeKind::TraitCandidate {
156                source: source.get(),
157                result: *result,
158            })
159            .enter_single_candidate(|ecx| {
160                Self::match_assumption(
161                    ecx,
162                    goal,
163                    assumption,
164                    |ecx| -> Result<_, NoSolutionOrRerunNonErased> {
165                        ecx.try_evaluate_added_goals()?;
166                        let (src, certainty) =
167                            ecx.characterize_param_env_assumption(goal.param_env, assumption)?;
168                        source.set(src);
169                        ecx.evaluate_added_goals_and_make_canonical_response(certainty)
170                    },
171                )
172                .map_err(Into::into)
173            });
174
175        Ok(match result.map_err_to_rerun()? {
176            Ok(result) => Ok(Candidate { source: source.get(), result, head_usages }),
177            Err(NoSolution) => Err(head_usages),
178        })
179    }
180
181    /// Try equating an assumption predicate against a goal's predicate. If it
182    /// holds, then execute the `then` callback, which should do any additional
183    /// work, then produce a response (typically by executing
184    /// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
185    fn probe_and_match_goal_against_assumption(
186        ecx: &mut EvalCtxt<'_, D>,
187        source: CandidateSource<I>,
188        goal: Goal<I, Self>,
189        assumption: I::Clause,
190        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
191    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
192        Self::fast_reject_assumption(ecx, goal, assumption)?;
193
194        ecx.probe_trait_candidate(source)
195            .enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
196    }
197
198    /// Try to reject the assumption based off of simple heuristics, such as [`ty::ClauseKind`]
199    /// and `DefId`.
200    fn fast_reject_assumption(
201        ecx: &mut EvalCtxt<'_, D>,
202        goal: Goal<I, Self>,
203        assumption: I::Clause,
204    ) -> Result<(), NoSolution>;
205
206    /// Relate the goal and assumption.
207    fn match_assumption(
208        ecx: &mut EvalCtxt<'_, D>,
209        goal: Goal<I, Self>,
210        assumption: I::Clause,
211        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
212    ) -> QueryResultOrRerunNonErased<I>;
213
214    /// Note: `goal_trait_ref` is derived from `goal`. Nonetheless, because
215    /// `consider_impl_candidate` is always called in a loop, we precompute `goal_trait_ref` once
216    /// and pass it in next to `goal` because the computation is expensive and loop-invariant.
217    fn consider_impl_candidate(
218        ecx: &mut EvalCtxt<'_, D>,
219        goal: Goal<I, Self>,
220        goal_trait_ref: ty::TraitRef<I>,
221        impl_def_id: I::ImplId,
222        then: impl FnOnce(&mut EvalCtxt<'_, D>, Certainty) -> QueryResultOrRerunNonErased<I>,
223    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
224
225    /// If the predicate contained an error, we want to avoid emitting unnecessary trait
226    /// errors but still want to emit errors for other trait goals. We have some special
227    /// handling for this case.
228    ///
229    /// Trait goals always hold while projection goals never do. This is a bit arbitrary
230    /// but prevents incorrect normalization while hiding any trait errors.
231    fn consider_error_guaranteed_candidate(
232        ecx: &mut EvalCtxt<'_, D>,
233        goal: Goal<I, Self>,
234        guar: I::ErrorGuaranteed,
235    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
236
237    /// A type implements an `auto trait` if its components do as well.
238    ///
239    /// These components are given by built-in rules from
240    /// [`structural_traits::instantiate_constituent_tys_for_auto_trait`].
241    fn consider_auto_trait_candidate(
242        ecx: &mut EvalCtxt<'_, D>,
243        goal: Goal<I, Self>,
244    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
245
246    /// A trait alias holds if the RHS traits and `where` clauses hold.
247    fn consider_trait_alias_candidate(
248        ecx: &mut EvalCtxt<'_, D>,
249        goal: Goal<I, Self>,
250    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
251
252    /// A type is `Sized` if its tail component is `Sized` and a type is `MetaSized` if its tail
253    /// component is `MetaSized`.
254    ///
255    /// These components are given by built-in rules from
256    /// [`structural_traits::instantiate_constituent_tys_for_sizedness_trait`].
257    fn consider_builtin_sizedness_candidates(
258        ecx: &mut EvalCtxt<'_, D>,
259        goal: Goal<I, Self>,
260        sizedness: SizedTraitKind,
261    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
262
263    /// A type is `Copy` or `Clone` if its components are `Copy` or `Clone`.
264    ///
265    /// These components are given by built-in rules from
266    /// [`structural_traits::instantiate_constituent_tys_for_copy_clone_trait`].
267    fn consider_builtin_copy_clone_candidate(
268        ecx: &mut EvalCtxt<'_, D>,
269        goal: Goal<I, Self>,
270    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
271
272    /// A type is a `FnPtr` if it is of `FnPtr` type.
273    fn consider_builtin_fn_ptr_trait_candidate(
274        ecx: &mut EvalCtxt<'_, D>,
275        goal: Goal<I, Self>,
276    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
277
278    /// A callable type (a closure, fn def, or fn ptr) is known to implement the `Fn<A>`
279    /// family of traits where `A` is given by the signature of the type.
280    fn consider_builtin_fn_trait_candidates(
281        ecx: &mut EvalCtxt<'_, D>,
282        goal: Goal<I, Self>,
283        kind: ty::ClosureKind,
284    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
285
286    /// An async closure is known to implement the `AsyncFn<A>` family of traits
287    /// where `A` is given by the signature of the type.
288    fn consider_builtin_async_fn_trait_candidates(
289        ecx: &mut EvalCtxt<'_, D>,
290        goal: Goal<I, Self>,
291        kind: ty::ClosureKind,
292    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
293
294    /// Compute the built-in logic of the `AsyncFnKindHelper` helper trait, which
295    /// is used internally to delay computation for async closures until after
296    /// upvar analysis is performed in HIR typeck.
297    fn consider_builtin_async_fn_kind_helper_candidate(
298        ecx: &mut EvalCtxt<'_, D>,
299        goal: Goal<I, Self>,
300    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
301
302    /// `Tuple` is implemented if the `Self` type is a tuple.
303    fn consider_builtin_tuple_candidate(
304        ecx: &mut EvalCtxt<'_, D>,
305        goal: Goal<I, Self>,
306    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
307
308    /// `Pointee` is always implemented.
309    ///
310    /// See the projection implementation for the `Metadata` types for all of
311    /// the built-in types. For structs, the metadata type is given by the struct
312    /// tail.
313    fn consider_builtin_pointee_candidate(
314        ecx: &mut EvalCtxt<'_, D>,
315        goal: Goal<I, Self>,
316    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
317
318    /// A coroutine (that comes from an `async` desugaring) is known to implement
319    /// `Future<Output = O>`, where `O` is given by the coroutine's return type
320    /// that was computed during type-checking.
321    fn consider_builtin_future_candidate(
322        ecx: &mut EvalCtxt<'_, D>,
323        goal: Goal<I, Self>,
324    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
325
326    /// A coroutine (that comes from a `gen` desugaring) is known to implement
327    /// `Iterator<Item = O>`, where `O` is given by the generator's yield type
328    /// that was computed during type-checking.
329    fn consider_builtin_iterator_candidate(
330        ecx: &mut EvalCtxt<'_, D>,
331        goal: Goal<I, Self>,
332    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
333
334    /// A coroutine (that comes from a `gen` desugaring) is known to implement
335    /// `FusedIterator`
336    fn consider_builtin_fused_iterator_candidate(
337        ecx: &mut EvalCtxt<'_, D>,
338        goal: Goal<I, Self>,
339    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
340
341    fn consider_builtin_async_iterator_candidate(
342        ecx: &mut EvalCtxt<'_, D>,
343        goal: Goal<I, Self>,
344    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
345
346    /// A coroutine (that doesn't come from an `async` or `gen` desugaring) is known to
347    /// implement `Coroutine<R, Yield = Y, Return = O>`, given the resume, yield,
348    /// and return types of the coroutine computed during type-checking.
349    fn consider_builtin_coroutine_candidate(
350        ecx: &mut EvalCtxt<'_, D>,
351        goal: Goal<I, Self>,
352    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
353
354    fn consider_builtin_discriminant_kind_candidate(
355        ecx: &mut EvalCtxt<'_, D>,
356        goal: Goal<I, Self>,
357    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
358
359    fn consider_builtin_destruct_candidate(
360        ecx: &mut EvalCtxt<'_, D>,
361        goal: Goal<I, Self>,
362    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
363
364    fn consider_builtin_transmute_candidate(
365        ecx: &mut EvalCtxt<'_, D>,
366        goal: Goal<I, Self>,
367    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
368
369    fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
370        ecx: &mut EvalCtxt<'_, D>,
371        goal: Goal<I, Self>,
372    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
373
374    fn consider_builtin_try_as_dyn_candidate(
375        ecx: &mut EvalCtxt<'_, D>,
376        goal: Goal<I, Self>,
377    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
378
379    /// Consider (possibly several) candidates to upcast or unsize a type to another
380    /// type, excluding the coercion of a sized type into a `dyn Trait`.
381    ///
382    /// We return the `BuiltinImplSource` for each candidate as it is needed
383    /// for unsize coercion in hir typeck and because it is difficult to
384    /// otherwise recompute this for codegen. This is a bit of a mess but the
385    /// easiest way to maintain the existing behavior for now.
386    fn consider_structural_builtin_unsize_candidates(
387        ecx: &mut EvalCtxt<'_, D>,
388        goal: Goal<I, Self>,
389    ) -> Result<Vec<Candidate<I>>, RerunNonErased>;
390
391    fn consider_builtin_field_candidate(
392        ecx: &mut EvalCtxt<'_, D>,
393        goal: Goal<I, Self>,
394    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
395}
396
397/// Allows callers of `assemble_and_evaluate_candidates` to choose whether to limit
398/// candidate assembly to param-env and alias-bound candidates.
399///
400/// On top of being a micro-optimization, as it avoids doing unnecessary work when
401/// a param-env trait bound candidate shadows impls for normalization, this is also
402/// required to prevent query cycles due to RPITIT inference. See the issue at:
403/// <https://github.com/rust-lang/trait-system-refactor-initiative/issues/173>.
404pub(super) enum AssembleCandidatesFrom {
405    All,
406    /// Only assemble candidates from the environment and alias bounds, ignoring
407    /// user-written and built-in impls. We only expect `ParamEnv` and `AliasBound`
408    /// candidates to be assembled.
409    EnvAndBounds,
410}
411
412impl AssembleCandidatesFrom {
413    fn should_assemble_impl_candidates(&self) -> bool {
414        match self {
415            AssembleCandidatesFrom::All => true,
416            AssembleCandidatesFrom::EnvAndBounds => false,
417        }
418    }
419}
420
421/// This is currently used to track the [CandidateHeadUsages] of all failed `ParamEnv`
422/// candidates. This is then used to ignore their head usages in case there's another
423/// always applicable `ParamEnv` candidate. Look at how `param_env_head_usages` is
424/// used in the code for more details.
425///
426/// We could easily extend this to also ignore head usages of other ignored candidates.
427/// However, we currently don't have any tests where this matters and the complexity of
428/// doing so does not feel worth it for now.
429#[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)]
430pub(super) struct FailedCandidateInfo {
431    pub param_env_head_usages: CandidateHeadUsages,
432}
433
434impl<D, I> EvalCtxt<'_, D>
435where
436    D: SolverDelegate<Interner = I>,
437    I: Interner,
438{
439    // FIXME(#155443): This function should only ever return an error
440    // as we want to force a rerun when accessing opaques. We should change
441    // this file to revert all the newly added places which return `NoSolution`.
442    pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<D>>(
443        &mut self,
444        goal: Goal<I, G>,
445        assemble_from: AssembleCandidatesFrom,
446    ) -> Result<(Vec<Candidate<I>>, FailedCandidateInfo), RerunNonErased> {
447        let mut candidates = ::alloc::vec::Vec::new()vec![];
448        let mut failed_candidate_info =
449            FailedCandidateInfo { param_env_head_usages: CandidateHeadUsages::default() };
450        let Ok(normalized_self_ty) =
451            self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty())
452        else {
453            return Ok((candidates, failed_candidate_info));
454        };
455
456        let goal: Goal<I, G> = goal
457            .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty));
458
459        if normalized_self_ty.is_ty_var() {
460            {
    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:460",
                        "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(460u32),
                        ::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");
461            self.try_assemble_bounds_via_registered_opaques(goal, assemble_from, &mut candidates)?;
462            return Ok((candidates, failed_candidate_info));
463        }
464
465        // Vars that show up in the rest of the goal substs may have been constrained by
466        // normalizing the self type as well, since type variables are not uniquified.
467        let goal = self.resolve_vars_if_possible(goal);
468
469        if self.typing_mode().is_coherence()
470            && let Ok(candidate) = self.consider_coherence_unknowable_candidate(goal)
471        {
472            candidates.push(candidate);
473            return Ok((candidates, failed_candidate_info));
474        }
475
476        self.assemble_alias_bound_candidates(goal, &mut candidates)?;
477        self.assemble_param_env_candidates(goal, &mut candidates, &mut failed_candidate_info)?;
478
479        match assemble_from {
480            AssembleCandidatesFrom::All => {
481                self.assemble_builtin_impl_candidates(goal, &mut candidates)?;
482                // For performance we only assemble impls if there are no candidates
483                // which would shadow them. This is necessary to avoid hangs in rayon,
484                // see trait-system-refactor-initiative#109 for more details.
485                //
486                // We always assemble builtin impls as trivial builtin impls have a higher
487                // priority than where-clauses.
488                //
489                // We only do this if any such candidate applies without any constraints
490                // as we may want to weaken inference guidance in the future and don't want
491                // to worry about causing major performance regressions when doing so.
492                // See trait-system-refactor-initiative#226 for some ideas here.
493                let assemble_impls = match self.typing_mode() {
494                    TypingMode::Coherence => true,
495                    TypingMode::Typeck { .. }
496                    | TypingMode::PostTypeckUntilBorrowck { .. }
497                    | TypingMode::Reflection
498                    | TypingMode::PostBorrowck { .. }
499                    | TypingMode::PostAnalysis
500                    | TypingMode::Codegen
501                    | TypingMode::ErasedNotCoherence(MayBeErased) => !candidates.iter().any(|c| {
502                        #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) |
        CandidateSource::AliasBound(_) => true,
    _ => false,
}matches!(
503                            c.source,
504                            CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)
505                                | CandidateSource::AliasBound(_)
506                        ) && has_no_inference_or_external_constraints(c.result)
507                    }),
508                };
509                if assemble_impls {
510                    self.assemble_impl_candidates(goal, &mut candidates)?;
511                    self.assemble_object_bound_candidates(goal, &mut candidates);
512                }
513            }
514            AssembleCandidatesFrom::EnvAndBounds => {
515                // This is somewhat inconsistent and may make #57893 slightly easier to exploit.
516                // However, it matches the behavior of the old solver. See
517                // `tests/ui/traits/next-solver/normalization-shadowing/use_object_if_empty_env.rs`.
518                if #[allow(non_exhaustive_omitted_patterns)] match normalized_self_ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(normalized_self_ty.kind(), ty::Dynamic(..))
519                    && !candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(_) => true,
    _ => false,
}matches!(c.source, CandidateSource::ParamEnv(_)))
520                {
521                    self.assemble_object_bound_candidates(goal, &mut candidates);
522                }
523            }
524        }
525
526        Ok((candidates, failed_candidate_info))
527    }
528
529    pub(super) fn forced_ambiguity(
530        &mut self,
531        maybe: MaybeInfo,
532    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
533        // This may fail if `try_evaluate_added_goals` overflows because it
534        // fails to reach a fixpoint but ends up getting an error after
535        // running for some additional step.
536        //
537        // FIXME(@lcnr): While I believe an error here to be possible, we
538        // currently don't have any test which actually triggers it. @lqd
539        // created a minimization for an ICE in typenum, but that one no
540        // longer fails here. cc trait-system-refactor-initiative#105.
541        let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
542        let certainty = Certainty::Maybe(maybe);
543        self.probe_trait_candidate(source)
544            .enter(|this| this.evaluate_added_goals_and_make_canonical_response(certainty))
545    }
546
547    #[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(547u32),
                                    ::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 goal_trait_ref = goal.predicate.trait_ref(cx);
            cx.for_each_relevant_impl(goal_trait_ref,
                |impl_def_id| -> Result<_, _>
                    {
                        match G::consider_impl_candidate(self, goal, goal_trait_ref,
                                        impl_def_id,
                                        |ecx, certainty|
                                            ecx.evaluate_added_goals_and_make_canonical_response(certainty)).map_err_to_rerun()?
                            {
                            Ok(candidate) => {
                                if !cx.impl_is_default(impl_def_id) {
                                    candidates.push(candidate);
                                }
                            }
                            Err(NoSolution) => {}
                        }
                        Ok(())
                    })
        }
    }
}#[instrument(level = "trace", skip_all)]
548    fn assemble_impl_candidates<G: GoalKind<D>>(
549        &mut self,
550        goal: Goal<I, G>,
551        candidates: &mut Vec<Candidate<I>>,
552    ) -> Result<(), RerunNonErased> {
553        let cx = self.cx();
554        let goal_trait_ref = goal.predicate.trait_ref(cx);
555        cx.for_each_relevant_impl(goal_trait_ref, |impl_def_id| -> Result<_, _> {
556            match G::consider_impl_candidate(
557                self,
558                goal,
559                goal_trait_ref,
560                impl_def_id,
561                |ecx, certainty| ecx.evaluate_added_goals_and_make_canonical_response(certainty),
562            )
563            .map_err_to_rerun()?
564            {
565                Ok(candidate) => {
566                    // For every `default impl`, there's always a non-default `impl`
567                    // that will *also* apply. There's no reason to register a candidate
568                    // for this impl, since it is *not* proof that the trait goal holds.
569                    if !cx.impl_is_default(impl_def_id) {
570                        candidates.push(candidate);
571                    }
572                }
573                Err(NoSolution) => {}
574            }
575
576            Ok(())
577        })
578    }
579
580    #[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(580u32),
                                    ::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)]
581    fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
582        &mut self,
583        goal: Goal<I, G>,
584        candidates: &mut Vec<Candidate<I>>,
585    ) -> Result<(), RerunNonErased> {
586        let cx = self.cx();
587        let trait_def_id = goal.predicate.trait_def_id(cx);
588
589        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
590        // of trying to handle these manually, we just reject all builtin impls in reflection
591        // mode. We can probably lift this restriction for specific cases, but this is safer.
592        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
593        if self.typing_mode().is_reflection() {
594            return Ok(());
595        }
596
597        // N.B. When assembling built-in candidates for lang items that are also
598        // `auto` traits, then the auto trait candidate that is assembled in
599        // `consider_auto_trait_candidate` MUST be disqualified to remain sound.
600        //
601        // Instead of adding the logic here, it's a better idea to add it in
602        // `EvalCtxt::disqualify_auto_trait_candidate_due_to_possible_impl` in
603        // `solve::trait_goals` instead.
604        let result = if let ty::Error(guar) = goal.predicate.self_ty().kind() {
605            G::consider_error_guaranteed_candidate(self, goal, guar)
606        } else if cx.trait_is_auto(trait_def_id) {
607            G::consider_auto_trait_candidate(self, goal)
608        } else if cx.trait_is_alias(trait_def_id) {
609            G::consider_trait_alias_candidate(self, goal)
610        } else {
611            match cx.as_trait_lang_item(trait_def_id) {
612                Some(SolverTraitLangItem::Sized) => {
613                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
614                }
615                Some(SolverTraitLangItem::MetaSized) => {
616                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
617                }
618                Some(SolverTraitLangItem::PointeeSized) => {
619                    unreachable!("`PointeeSized` is removed during lowering");
620                }
621                Some(
622                    SolverTraitLangItem::Copy
623                    | SolverTraitLangItem::Clone
624                    | SolverTraitLangItem::TrivialClone,
625                ) => G::consider_builtin_copy_clone_candidate(self, goal),
626                Some(SolverTraitLangItem::Fn) => {
627                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
628                }
629                Some(SolverTraitLangItem::FnMut) => {
630                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
631                }
632                Some(SolverTraitLangItem::FnOnce) => {
633                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
634                }
635                Some(SolverTraitLangItem::AsyncFn) => {
636                    G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
637                }
638                Some(SolverTraitLangItem::AsyncFnMut) => {
639                    G::consider_builtin_async_fn_trait_candidates(
640                        self,
641                        goal,
642                        ty::ClosureKind::FnMut,
643                    )
644                }
645                Some(SolverTraitLangItem::AsyncFnOnce) => {
646                    G::consider_builtin_async_fn_trait_candidates(
647                        self,
648                        goal,
649                        ty::ClosureKind::FnOnce,
650                    )
651                }
652                Some(SolverTraitLangItem::FnPtrTrait) => {
653                    G::consider_builtin_fn_ptr_trait_candidate(self, goal)
654                }
655                Some(SolverTraitLangItem::AsyncFnKindHelper) => {
656                    G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
657                }
658                Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
659                Some(SolverTraitLangItem::PointeeTrait) => {
660                    G::consider_builtin_pointee_candidate(self, goal)
661                }
662                Some(SolverTraitLangItem::Future) => {
663                    G::consider_builtin_future_candidate(self, goal)
664                }
665                Some(SolverTraitLangItem::Iterator) => {
666                    G::consider_builtin_iterator_candidate(self, goal)
667                }
668                Some(SolverTraitLangItem::FusedIterator) => {
669                    G::consider_builtin_fused_iterator_candidate(self, goal)
670                }
671                Some(SolverTraitLangItem::AsyncIterator) => {
672                    G::consider_builtin_async_iterator_candidate(self, goal)
673                }
674                Some(SolverTraitLangItem::Coroutine) => {
675                    G::consider_builtin_coroutine_candidate(self, goal)
676                }
677                Some(SolverTraitLangItem::DiscriminantKind) => {
678                    G::consider_builtin_discriminant_kind_candidate(self, goal)
679                }
680                Some(SolverTraitLangItem::Destruct) => {
681                    G::consider_builtin_destruct_candidate(self, goal)
682                }
683                Some(SolverTraitLangItem::TransmuteTrait) => {
684                    G::consider_builtin_transmute_candidate(self, goal)
685                }
686                Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
687                    G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
688                }
689                Some(SolverTraitLangItem::TryAsDyn) => {
690                    G::consider_builtin_try_as_dyn_candidate(self, goal)
691                }
692                Some(SolverTraitLangItem::Field) => G::consider_builtin_field_candidate(self, goal),
693                _ => Err(NoSolution.into()),
694            }
695        };
696
697        candidates.extend(result);
698
699        // There may be multiple unsize candidates for a trait with several supertraits:
700        // `trait Foo: Bar<A> + Bar<B>` and `dyn Foo: Unsize<dyn Bar<_>>`
701        if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
702            candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)?);
703        }
704
705        Ok(())
706    }
707
708    #[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(708u32),
                                    ::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)]
709    fn assemble_param_env_candidates<G: GoalKind<D>>(
710        &mut self,
711        goal: Goal<I, G>,
712        candidates: &mut Vec<Candidate<I>>,
713        failed_candidate_info: &mut FailedCandidateInfo,
714    ) -> Result<(), RerunNonErased> {
715        for assumption in goal.param_env.caller_bounds().iter() {
716            match G::probe_and_consider_param_env_candidate(self, goal, assumption)? {
717                Ok(candidate) => candidates.push(candidate),
718                Err(head_usages) => {
719                    failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
720                }
721            }
722        }
723
724        Ok(())
725    }
726
727    #[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(727u32),
                                    ::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)]
728    fn assemble_alias_bound_candidates<G: GoalKind<D>>(
729        &mut self,
730        goal: Goal<I, G>,
731        candidates: &mut Vec<Candidate<I>>,
732    ) -> Result<(), RerunNonErased> {
733        let res = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
734            ecx.assemble_alias_bound_candidates_recur(
735                goal.predicate.self_ty(),
736                goal,
737                candidates,
738                AliasBoundKind::SelfBounds,
739            )?;
740            Ok(())
741        });
742
743        // always returns Ok
744        match res {
745            Ok(_) => Ok(()),
746            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
747            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
748                unreachable!()
749            }
750        }
751    }
752
753    /// For some deeply nested `<T>::A::B::C::D` rigid associated type,
754    /// we should explore the item bounds for all levels, since the
755    /// `associated_type_bounds` feature means that a parent associated
756    /// type may carry bounds for a nested associated type.
757    ///
758    /// If we have a projection, check that its self type is a rigid projection.
759    /// If so, continue searching by recursively calling after normalization.
760    // FIXME: This may recurse infinitely, but I can't seem to trigger it without
761    // hitting another overflow error something. Add a depth parameter needed later.
762    fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
763        &mut self,
764        self_ty: I::Ty,
765        goal: Goal<I, G>,
766        candidates: &mut Vec<Candidate<I>>,
767        consider_self_bounds: AliasBoundKind,
768    ) -> Result<(), RerunNonErased> {
769        let (alias_ty, def_id) = match self_ty.kind() {
770            ty::Bool
771            | ty::Char
772            | ty::Int(_)
773            | ty::Uint(_)
774            | ty::Float(_)
775            | ty::Adt(_, _)
776            | ty::Foreign(_)
777            | ty::Str
778            | ty::Array(_, _)
779            | ty::Pat(_, _)
780            | ty::Slice(_)
781            | ty::RawPtr(_, _)
782            | ty::Ref(_, _, _)
783            | ty::FnDef(_, _)
784            | ty::FnPtr(..)
785            | ty::UnsafeBinder(_)
786            | ty::Dynamic(..)
787            | ty::Closure(..)
788            | ty::CoroutineClosure(..)
789            | ty::Coroutine(..)
790            | ty::CoroutineWitness(..)
791            | ty::Never
792            | ty::Tuple(_)
793            | ty::Param(_)
794            | ty::Placeholder(..)
795            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
796            | ty::Error(_) => return Ok(()),
797            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
798                {
    ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
            goal));
}panic!("unexpected self type for `{goal:?}`")
799            }
800
801            ty::Infer(ty::TyVar(_)) => {
802                // If we hit infer when normalizing the self type of an alias,
803                // then bail with ambiguity. We should never encounter this on
804                // the *first* iteration of this recursive function.
805                if let Ok(result) =
806                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
807                {
808                    candidates.push(Candidate {
809                        source: CandidateSource::AliasBound(consider_self_bounds),
810                        result,
811                        head_usages: CandidateHeadUsages::default(),
812                    });
813                }
814                return Ok(());
815            }
816
817            ty::Alias(
818                ty::IsRigid::Yes,
819                alias_ty @ AliasTy { kind: ty::Projection { def_id }, .. },
820            ) => (alias_ty, def_id.into()),
821
822            ty::Alias(ty::IsRigid::Yes, alias_ty @ AliasTy { kind: ty::Opaque { def_id }, .. }) => {
823                (alias_ty, def_id.into())
824            }
825
826            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:?}"),
827
828            ty::Alias(
829                ty::IsRigid::Yes,
830                AliasTy { kind: ty::Inherent { .. } | ty::Free { .. }, .. },
831            ) => {
832                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"));
833                return Ok(());
834            }
835        };
836
837        match consider_self_bounds {
838            AliasBoundKind::SelfBounds => {
839                for assumption in self
840                    .cx()
841                    .item_self_bounds(def_id)
842                    .iter_instantiated(self.cx(), alias_ty.args)
843                    .map(Unnormalized::skip_norm_wip)
844                {
845                    candidates.extend(G::probe_and_consider_implied_clause(
846                        self,
847                        CandidateSource::AliasBound(consider_self_bounds),
848                        goal,
849                        assumption,
850                        [],
851                    ));
852                }
853            }
854            AliasBoundKind::NonSelfBounds => {
855                for assumption in self
856                    .cx()
857                    .item_non_self_bounds(def_id)
858                    .iter_instantiated(self.cx(), alias_ty.args)
859                    .map(Unnormalized::skip_norm_wip)
860                {
861                    candidates.extend(G::probe_and_consider_implied_clause(
862                        self,
863                        CandidateSource::AliasBound(consider_self_bounds),
864                        goal,
865                        assumption,
866                        [],
867                    ));
868                }
869            }
870        }
871
872        candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
873
874        let Some(projection_ty) = alias_ty.try_to_projection() else {
875            return Ok(());
876        };
877
878        // Recurse on the self type of the projection.
879        match self.structurally_normalize_ty(goal.param_env, projection_ty.projection_self_ty()) {
880            Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
881                next_self_ty,
882                goal,
883                candidates,
884                AliasBoundKind::NonSelfBounds,
885            ),
886            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Ok(()),
887            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
888        }
889    }
890
891    #[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(891u32),
                                    ::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)]
892    fn assemble_object_bound_candidates<G: GoalKind<D>>(
893        &mut self,
894        goal: Goal<I, G>,
895        candidates: &mut Vec<Candidate<I>>,
896    ) {
897        let cx = self.cx();
898        if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
899            // `dyn MetaSized` is valid, but should get its `MetaSized` impl from
900            // being `dyn` (SizedCandidate), not from the object candidate.
901            return;
902        }
903
904        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
905        // of trying to handle these manually, we just reject all builtin impls in reflection
906        // mode. We can probably lift this restriction for specific cases, but this is safer.
907        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
908        if self.typing_mode().is_reflection() {
909            return;
910        }
911
912        let self_ty = goal.predicate.self_ty();
913        let bounds = match self_ty.kind() {
914            ty::Bool
915            | ty::Char
916            | ty::Int(_)
917            | ty::Uint(_)
918            | ty::Float(_)
919            | ty::Adt(_, _)
920            | ty::Foreign(_)
921            | ty::Str
922            | ty::Array(_, _)
923            | ty::Pat(_, _)
924            | ty::Slice(_)
925            | ty::RawPtr(_, _)
926            | ty::Ref(_, _, _)
927            | ty::FnDef(_, _)
928            | ty::FnPtr(..)
929            | ty::UnsafeBinder(_)
930            | ty::Alias(..)
931            | ty::Closure(..)
932            | ty::CoroutineClosure(..)
933            | ty::Coroutine(..)
934            | ty::CoroutineWitness(..)
935            | ty::Never
936            | ty::Tuple(_)
937            | ty::Param(_)
938            | ty::Placeholder(..)
939            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
940            | ty::Error(_) => return,
941            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
942            | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
943            ty::Dynamic(bounds, ..) => bounds,
944        };
945
946        // Do not consider built-in object impls for dyn-incompatible types.
947        if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
948            return;
949        }
950
951        // Consider all of the auto-trait and projection bounds, which don't
952        // need to be recorded as a `BuiltinImplSource::Object` since they don't
953        // really have a vtable base...
954        for bound in bounds.iter() {
955            match bound.skip_binder() {
956                ty::ExistentialPredicate::Trait(_) => {
957                    // Skip principal
958                }
959                ty::ExistentialPredicate::Projection(_)
960                | ty::ExistentialPredicate::AutoTrait(_) => {
961                    candidates.extend(G::probe_and_consider_object_bound_candidate(
962                        self,
963                        CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
964                        goal,
965                        bound.with_self_ty(cx, self_ty),
966                    ));
967                }
968            }
969        }
970
971        // FIXME: We only need to do *any* of this if we're considering a trait goal,
972        // since we don't need to look at any supertrait or anything if we are doing
973        // a projection goal.
974        if let Some(principal) = bounds.principal() {
975            let principal_trait_ref = principal.with_self_ty(cx, self_ty);
976            for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
977                candidates.extend(G::probe_and_consider_object_bound_candidate(
978                    self,
979                    CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
980                    goal,
981                    assumption.upcast(cx),
982                ));
983            }
984        }
985    }
986
987    /// In coherence we have to not only care about all impls we know about, but
988    /// also consider impls which may get added in a downstream or sibling crate
989    /// or which an upstream impl may add in a minor release.
990    ///
991    /// To do so we return a single ambiguous candidate in case such an unknown
992    /// impl could apply to the current goal.
993    #[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(993u32),
                                    ::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)]
994    fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
995        &mut self,
996        goal: Goal<I, G>,
997    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
998        self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
999            let cx = ecx.cx();
1000            let trait_ref = goal.predicate.trait_ref(cx);
1001            if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
1002                Err(NoSolution.into())
1003            } else {
1004                // While the trait bound itself may be unknowable, we may be able to
1005                // prove that a super trait is not implemented. For this, we recursively
1006                // prove the super trait bounds of the current goal.
1007                //
1008                // We skip the goal itself as that one would cycle.
1009                let predicate: I::Predicate = trait_ref.upcast(cx);
1010                ecx.add_goals(
1011                    GoalSource::Misc,
1012                    elaborate::elaborate(cx, [predicate])
1013                        .skip(1)
1014                        .map(|predicate| goal.with(cx, predicate)),
1015                )?;
1016                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1017            }
1018        })
1019    }
1020}
1021
1022pub(super) enum AllowInferenceConstraints {
1023    Yes,
1024    No,
1025}
1026
1027impl<D, I> EvalCtxt<'_, D>
1028where
1029    D: SolverDelegate<Interner = I>,
1030    I: Interner,
1031{
1032    /// Check whether we can ignore impl candidates due to specialization.
1033    ///
1034    /// This is only necessary for `feature(specialization)` and seems quite ugly.
1035    pub(super) fn filter_specialized_impls(
1036        &mut self,
1037        allow_inference_constraints: AllowInferenceConstraints,
1038        candidates: &mut Vec<Candidate<I>>,
1039    ) {
1040        if self.typing_mode().is_coherence() {
1041            return;
1042        }
1043
1044        let mut i = 0;
1045        'outer: while i < candidates.len() {
1046            let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
1047                i += 1;
1048                continue;
1049            };
1050
1051            for (j, c) in candidates.iter().enumerate() {
1052                if i == j {
1053                    continue;
1054                }
1055
1056                let CandidateSource::Impl(other_def_id) = c.source else {
1057                    continue;
1058                };
1059
1060                // See if we can toss out `victim` based on specialization.
1061                //
1062                // While this requires us to know *for sure* that the `lhs` impl applies
1063                // we still use modulo regions here. This is fine as specialization currently
1064                // assumes that specializing impls have to be always applicable, meaning that
1065                // the only allowed region constraints may be constraints also present on the default impl.
1066                if #[allow(non_exhaustive_omitted_patterns)] match allow_inference_constraints {
    AllowInferenceConstraints::Yes => true,
    _ => false,
}matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
1067                    || has_only_region_constraints(c.result)
1068                {
1069                    if self.cx().impl_specializes(other_def_id, victim_def_id) {
1070                        candidates.remove(i);
1071                        continue 'outer;
1072                    }
1073                }
1074            }
1075
1076            i += 1;
1077        }
1078    }
1079
1080    /// If the self type is the hidden type of an opaque, try to assemble
1081    /// candidates for it by consider its item bounds and by using blanket
1082    /// impls. This is used to incompletely guide type inference when handling
1083    /// non-defining uses in the defining scope.
1084    ///
1085    /// We otherwise just fail fail with ambiguity. Even if we're using an
1086    /// opaque type item bound or a blank impls, we still force its certainty
1087    /// to be `Maybe` so that we properly prove this goal later.
1088    ///
1089    /// See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/182>
1090    /// for why this is necessary.
1091    #[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(1091u32),
                                    ::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:1121",
                                        "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(1121u32),
                                        ::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();
                let goal_trait_ref = goal.predicate.trait_ref(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, goal_trait_ref,
                                                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))]
1092    fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
1093        &mut self,
1094        goal: Goal<I, G>,
1095        assemble_from: AssembleCandidatesFrom,
1096        candidates: &mut Vec<Candidate<I>>,
1097    ) -> Result<(), RerunNonErased> {
1098        let self_ty = goal.predicate.self_ty();
1099        // We only use this hack during HIR typeck.
1100        let opaque_types = match self.typing_mode() {
1101            TypingMode::Typeck { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
1102            TypingMode::Coherence
1103            | TypingMode::PostTypeckUntilBorrowck { .. }
1104            | TypingMode::PostBorrowck { .. }
1105            | TypingMode::PostAnalysis
1106            | TypingMode::Reflection
1107            | TypingMode::Codegen => vec![],
1108            TypingMode::ErasedNotCoherence(MayBeErased) => {
1109                self.opaque_accesses
1110                    .rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
1111                Vec::new()
1112            }
1113        };
1114
1115        if opaque_types.is_empty() {
1116            candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
1117            return Ok(());
1118        }
1119
1120        for &opaque_ty in &opaque_types {
1121            debug!("self ty is sub unified with {opaque_ty:?}");
1122
1123            struct ReplaceOpaque<I: Interner> {
1124                cx: I,
1125                opaque_ty: ty::OpaqueAliasTy<I>,
1126                self_ty: I::Ty,
1127            }
1128            impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
1129                fn cx(&self) -> I {
1130                    self.cx
1131                }
1132                fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1133                    if let ty::Alias(is_rigid, alias_ty) = ty.kind()
1134                        && let Some(opaque_ty) = alias_ty.try_to_opaque()
1135                    {
1136                        if opaque_ty == self.opaque_ty {
1137                            debug_assert_eq!(is_rigid, ty::IsRigid::No);
1138                            return self.self_ty;
1139                        }
1140                    }
1141                    ty.super_fold_with(self)
1142                }
1143            }
1144
1145            // We look at all item-bounds of the opaque, replacing the
1146            // opaque with the current self type before considering
1147            // them as a candidate. Imagine we've got `?x: Trait<?y>`
1148            // and `?x` has been sub-unified with the hidden type of
1149            // `impl Trait<u32>`, We take the item bound `opaque: Trait<u32>`
1150            // and replace all occurrences of `opaque` with `?x`. This results
1151            // in a `?x: Trait<u32>` alias-bound candidate.
1152            for item_bound in self
1153                .cx()
1154                .item_self_bounds(opaque_ty.kind.into())
1155                .iter_instantiated(self.cx(), opaque_ty.args)
1156                .map(Unnormalized::skip_norm_wip)
1157            {
1158                let assumption =
1159                    item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), opaque_ty, self_ty });
1160                candidates.extend(G::probe_and_match_goal_against_assumption(
1161                    self,
1162                    CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1163                    goal,
1164                    assumption,
1165                    |ecx| {
1166                        // We want to reprove this goal once we've inferred the
1167                        // hidden type, so we force the certainty to `Maybe`.
1168                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1169                    },
1170                ));
1171            }
1172        }
1173
1174        // If the self type is sub unified with any opaque type, we also look at blanket
1175        // impls for it.
1176        //
1177        // See tests/ui/impl-trait/non-defining-uses/use-blanket-impl.rs for an example.
1178        if assemble_from.should_assemble_impl_candidates() {
1179            let cx = self.cx();
1180            let goal_trait_ref = goal.predicate.trait_ref(cx);
1181            cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1182                // For every `default impl`, there's always a non-default `impl`
1183                // that will *also* apply. There's no reason to register a candidate
1184                // for this impl, since it is *not* proof that the trait goal holds.
1185                if cx.impl_is_default(impl_def_id) {
1186                    return Ok(());
1187                }
1188
1189                match G::consider_impl_candidate(
1190                    self,
1191                    goal,
1192                    goal_trait_ref,
1193                    impl_def_id,
1194                    |ecx, certainty| {
1195                        if ecx.shallow_resolve(self_ty).is_ty_var() {
1196                            // We force the certainty of impl candidates to be `Maybe`.
1197                            let certainty = certainty.and(Certainty::AMBIGUOUS);
1198                            ecx.evaluate_added_goals_and_make_canonical_response(certainty)
1199                        } else {
1200                            // We don't want to use impls if they constrain the opaque.
1201                            //
1202                            // FIXME(trait-system-refactor-initiative#229): This isn't
1203                            // perfect yet as it still allows us to incorrectly constrain
1204                            // other inference variables.
1205                            Err(NoSolution.into())
1206                        }
1207                    },
1208                )
1209                .map_err_to_rerun()?
1210                {
1211                    Ok(candidate) => candidates.push(candidate),
1212                    Err(NoSolution) => {}
1213                }
1214
1215                Ok(())
1216            })?;
1217        }
1218
1219        if candidates.is_empty() {
1220            let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1221            let certainty = Certainty::Maybe(MaybeInfo {
1222                cause: MaybeCause::Ambiguity,
1223                opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1224                stalled_on_coroutines: StalledOnCoroutines::No,
1225            });
1226            candidates
1227                .extend(self.probe_trait_candidate(source).enter(|this| {
1228                    this.evaluate_added_goals_and_make_canonical_response(certainty)
1229                }));
1230        }
1231
1232        Ok(())
1233    }
1234
1235    /// Assemble and merge candidates for goals which are related to an underlying trait
1236    /// goal. Right now, this is normalizes-to and host effect goals.
1237    ///
1238    /// We sadly can't simply take all possible candidates for normalization goals
1239    /// and check whether they result in the same constraints. We want to make sure
1240    /// that trying to normalize an alias doesn't result in constraints which aren't
1241    /// otherwise required.
1242    ///
1243    /// Most notably, when proving a trait goal by via a where-bound, we should not
1244    /// normalize via impls which have stricter region constraints than the where-bound:
1245    ///
1246    /// ```rust
1247    /// trait Trait<'a> {
1248    ///     type Assoc;
1249    /// }
1250    ///
1251    /// impl<'a, T: 'a> Trait<'a> for T {
1252    ///     type Assoc = u32;
1253    /// }
1254    ///
1255    /// fn with_bound<'a, T: Trait<'a>>(_value: T::Assoc) {}
1256    /// ```
1257    ///
1258    /// The where-bound of `with_bound` doesn't specify the associated type, so we would
1259    /// only be able to normalize `<T as Trait<'a>>::Assoc` by using the impl. This impl
1260    /// adds a `T: 'a` bound however, which would result in a region error. Given that the
1261    /// user explicitly wrote that `T: Trait<'a>` holds, this is undesirable and we instead
1262    /// treat the alias as rigid.
1263    ///
1264    /// See trait-system-refactor-initiative#124 for more details.
1265    x;#[instrument(level = "debug", skip_all, fields(proven_via, goal), ret)]
1266    pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1267        &mut self,
1268        proven_via: Option<TraitGoalProvenVia>,
1269        goal: Goal<I, G>,
1270        inject_forced_ambiguity_candidate: impl FnOnce(
1271            &mut EvalCtxt<'_, D>,
1272        ) -> Option<
1273            Result<CanonicalResponse<I>, NoSolutionOrRerunNonErased>,
1274        >,
1275        inject_normalize_to_rigid_candidate: impl FnOnce(
1276            &mut EvalCtxt<'_, D>,
1277        ) -> Result<
1278            CanonicalResponse<I>,
1279            NoSolutionOrRerunNonErased,
1280        >,
1281    ) -> QueryResultOrRerunNonErased<I> {
1282        let Some(proven_via) = proven_via else {
1283            // We don't care about overflow. If proving the trait goal overflowed, then
1284            // it's enough to report an overflow error for that, we don't also have to
1285            // overflow during normalization.
1286            //
1287            // We use `forced_ambiguity` here over `make_ambiguous_response_no_constraints`
1288            // because the former will also record a built-in candidate in the inspector.
1289            return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand| cand.result);
1290        };
1291
1292        match proven_via {
1293            TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1294                // Even when a trait bound has been proven using a where-bound, we
1295                // still need to consider alias-bounds for normalization, see
1296                // `tests/ui/next-solver/alias-bound-shadowed-by-env.rs`.
1297                let (mut candidates, _) = self
1298                    .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds)?;
1299                debug!(?candidates);
1300
1301                // If the trait goal has been proven by using the environment, we want to treat
1302                // aliases as rigid if there are no applicable projection bounds in the environment.
1303                if candidates.is_empty() {
1304                    return inject_normalize_to_rigid_candidate(self);
1305                }
1306
1307                // If we're normalizing an GAT, we bail if using a where-bound would constrain
1308                // its generic arguments.
1309                if let Some(result) = inject_forced_ambiguity_candidate(self) {
1310                    return result;
1311                }
1312
1313                // We still need to prefer where-bounds over alias-bounds however.
1314                // See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`.
1315                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1316                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1317                }
1318
1319                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1320                    Ok(response)
1321                } else {
1322                    self.flounder(&candidates).map_err(Into::into)
1323                }
1324            }
1325            TraitGoalProvenVia::Misc => {
1326                let (mut candidates, _) =
1327                    self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1328
1329                // Prefer "orphaned" param-env normalization predicates, which are used
1330                // (for example, and ideally only) when proving item bounds for an impl.
1331                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1332                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1333                }
1334
1335                // We drop specialized impls to allow normalization via a final impl here. In case
1336                // the specializing impl has different inference constraints from the specialized
1337                // impl, proving the trait goal is already ambiguous, so we never get here. This
1338                // means we can just ignore inference constraints and don't have to special-case
1339                // constraining the normalized-to `term`.
1340                self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1341                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1342                    Ok(response)
1343                } else {
1344                    self.flounder(&candidates).map_err(Into::into)
1345                }
1346            }
1347        }
1348    }
1349
1350    /// Compute whether a param-env assumption is global or non-global after normalizing it.
1351    ///
1352    /// This is necessary because, for example, given:
1353    ///
1354    /// ```ignore,rust
1355    /// where
1356    ///     T: Trait<Assoc = u32>,
1357    ///     i32: From<T::Assoc>,
1358    /// ```
1359    ///
1360    /// The `i32: From<T::Assoc>` bound is non-global before normalization, but is global after.
1361    /// Since the old trait solver normalized param-envs eagerly, we want to emulate this
1362    /// behavior lazily.
1363    fn characterize_param_env_assumption(
1364        &mut self,
1365        param_env: I::ParamEnv,
1366        assumption: I::Clause,
1367    ) -> Result<(CandidateSource<I>, Certainty), NoSolution> {
1368        // FIXME: This should be fixed, but it also requires changing the behavior
1369        // in the old solver which is currently relied on.
1370        if assumption.has_bound_vars() {
1371            return Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), Certainty::Yes));
1372        }
1373
1374        match assumption.visit_with(&mut FindParamInClause {
1375            ecx: self,
1376            param_env,
1377            universes: ::alloc::vec::Vec::new()vec![],
1378            recursion_depth: 0,
1379        }) {
1380            ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1381            ControlFlow::Break(Ok(certainty)) => {
1382                Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), certainty))
1383            }
1384            ControlFlow::Continue(()) => {
1385                Ok((CandidateSource::ParamEnv(ParamEnvSource::Global), Certainty::Yes))
1386            }
1387        }
1388    }
1389}
1390
1391struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1392    ecx: &'a mut EvalCtxt<'b, D>,
1393    param_env: I::ParamEnv,
1394    universes: Vec<Option<ty::UniverseIndex>>,
1395    recursion_depth: usize,
1396}
1397
1398impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1399where
1400    D: SolverDelegate<Interner = I>,
1401    I: Interner,
1402{
1403    // - `Continue(())`: no generic parameter was found, the type is global
1404    // - `Break(Ok(Certainty::Yes))`: a generic parameter was found, the type is non-global
1405    // - `Break(Ok(Certainty::Maybe(_)))`: the recursion limit reached, assume that the type is non-global
1406    // - `Break(Err(NoSolution))`: normalization failed
1407    type Result = ControlFlow<Result<Certainty, NoSolution>>;
1408
1409    fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1410        self.universes.push(None);
1411        t.super_visit_with(self)?;
1412        self.universes.pop();
1413        ControlFlow::Continue(())
1414    }
1415
1416    fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1417        let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1418        let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1419            return ControlFlow::Break(Err(NoSolution));
1420        };
1421
1422        match ty.kind() {
1423            ty::Placeholder(p) => {
1424                if p.universe() == ty::UniverseIndex::ROOT {
1425                    ControlFlow::Break(Ok(Certainty::Yes))
1426                } else {
1427                    ControlFlow::Continue(())
1428                }
1429            }
1430            ty::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1431            _ if ty.has_type_flags(
1432                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1433            ) =>
1434            {
1435                self.recursion_depth += 1;
1436                if self.recursion_depth > self.ecx.cx().recursion_limit() {
1437                    return ControlFlow::Break(Ok(Certainty::Maybe(MaybeInfo {
1438                        cause: MaybeCause::Overflow {
1439                            suggest_increasing_limit: true,
1440                            keep_constraints: false,
1441                        },
1442                        opaque_types_jank: OpaqueTypesJank::AllGood,
1443                        stalled_on_coroutines: StalledOnCoroutines::No,
1444                    })));
1445                }
1446                let result = ty.super_visit_with(self);
1447                self.recursion_depth -= 1;
1448                result
1449            }
1450            _ => ControlFlow::Continue(()),
1451        }
1452    }
1453
1454    fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1455        let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1456        let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1457            return ControlFlow::Break(Err(NoSolution));
1458        };
1459
1460        match ct.kind() {
1461            ty::ConstKind::Placeholder(p) => {
1462                if p.universe() == ty::UniverseIndex::ROOT {
1463                    ControlFlow::Break(Ok(Certainty::Yes))
1464                } else {
1465                    ControlFlow::Continue(())
1466                }
1467            }
1468            ty::ConstKind::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1469            _ if ct.has_type_flags(
1470                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1471            ) =>
1472            {
1473                // FIXME(mgca): we should also check the recursion limit here
1474                ct.super_visit_with(self)
1475            }
1476            _ => ControlFlow::Continue(()),
1477        }
1478    }
1479
1480    fn visit_region(&mut self, r: Region<I>) -> Self::Result {
1481        match self.ecx.eager_resolve_region(r).kind() {
1482            ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1483            ty::RePlaceholder(p) => {
1484                if p.universe() == ty::UniverseIndex::ROOT {
1485                    ControlFlow::Break(Ok(Certainty::Yes))
1486                } else {
1487                    ControlFlow::Continue(())
1488                }
1489            }
1490            ty::ReVar(_) => ControlFlow::Break(Ok(Certainty::Yes)),
1491            ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1492                {
    ::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")
1493            }
1494        }
1495    }
1496}