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) => 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) => candidates.push(candidate),
566                Err(NoSolution) => {}
567            }
568
569            Ok(())
570        })
571    }
572
573    #[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(573u32),
                                    ::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)]
574    fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
575        &mut self,
576        goal: Goal<I, G>,
577        candidates: &mut Vec<Candidate<I>>,
578    ) -> Result<(), RerunNonErased> {
579        let cx = self.cx();
580        let trait_def_id = goal.predicate.trait_def_id(cx);
581
582        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
583        // of trying to handle these manually, we just reject all builtin impls in reflection
584        // mode. We can probably lift this restriction for specific cases, but this is safer.
585        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
586        if self.typing_mode().is_reflection() {
587            return Ok(());
588        }
589
590        // N.B. When assembling built-in candidates for lang items that are also
591        // `auto` traits, then the auto trait candidate that is assembled in
592        // `consider_auto_trait_candidate` MUST be disqualified to remain sound.
593        //
594        // Instead of adding the logic here, it's a better idea to add it in
595        // `EvalCtxt::disqualify_auto_trait_candidate_due_to_possible_impl` in
596        // `solve::trait_goals` instead.
597        let result = if let ty::Error(guar) = goal.predicate.self_ty().kind() {
598            G::consider_error_guaranteed_candidate(self, goal, guar)
599        } else if cx.trait_is_auto(trait_def_id) {
600            G::consider_auto_trait_candidate(self, goal)
601        } else if cx.trait_is_alias(trait_def_id) {
602            G::consider_trait_alias_candidate(self, goal)
603        } else {
604            match cx.as_trait_lang_item(trait_def_id) {
605                Some(SolverTraitLangItem::Sized) => {
606                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
607                }
608                Some(SolverTraitLangItem::MetaSized) => {
609                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
610                }
611                Some(SolverTraitLangItem::PointeeSized) => {
612                    unreachable!("`PointeeSized` is removed during lowering");
613                }
614                Some(
615                    SolverTraitLangItem::Copy
616                    | SolverTraitLangItem::Clone
617                    | SolverTraitLangItem::TrivialClone,
618                ) => G::consider_builtin_copy_clone_candidate(self, goal),
619                Some(SolverTraitLangItem::Fn) => {
620                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
621                }
622                Some(SolverTraitLangItem::FnMut) => {
623                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
624                }
625                Some(SolverTraitLangItem::FnOnce) => {
626                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
627                }
628                Some(SolverTraitLangItem::AsyncFn) => {
629                    G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
630                }
631                Some(SolverTraitLangItem::AsyncFnMut) => {
632                    G::consider_builtin_async_fn_trait_candidates(
633                        self,
634                        goal,
635                        ty::ClosureKind::FnMut,
636                    )
637                }
638                Some(SolverTraitLangItem::AsyncFnOnce) => {
639                    G::consider_builtin_async_fn_trait_candidates(
640                        self,
641                        goal,
642                        ty::ClosureKind::FnOnce,
643                    )
644                }
645                Some(SolverTraitLangItem::FnPtrTrait) => {
646                    G::consider_builtin_fn_ptr_trait_candidate(self, goal)
647                }
648                Some(SolverTraitLangItem::AsyncFnKindHelper) => {
649                    G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
650                }
651                Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
652                Some(SolverTraitLangItem::PointeeTrait) => {
653                    G::consider_builtin_pointee_candidate(self, goal)
654                }
655                Some(SolverTraitLangItem::Future) => {
656                    G::consider_builtin_future_candidate(self, goal)
657                }
658                Some(SolverTraitLangItem::Iterator) => {
659                    G::consider_builtin_iterator_candidate(self, goal)
660                }
661                Some(SolverTraitLangItem::FusedIterator) => {
662                    G::consider_builtin_fused_iterator_candidate(self, goal)
663                }
664                Some(SolverTraitLangItem::AsyncIterator) => {
665                    G::consider_builtin_async_iterator_candidate(self, goal)
666                }
667                Some(SolverTraitLangItem::Coroutine) => {
668                    G::consider_builtin_coroutine_candidate(self, goal)
669                }
670                Some(SolverTraitLangItem::DiscriminantKind) => {
671                    G::consider_builtin_discriminant_kind_candidate(self, goal)
672                }
673                Some(SolverTraitLangItem::Destruct) => {
674                    G::consider_builtin_destruct_candidate(self, goal)
675                }
676                Some(SolverTraitLangItem::TransmuteTrait) => {
677                    G::consider_builtin_transmute_candidate(self, goal)
678                }
679                Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
680                    G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
681                }
682                Some(SolverTraitLangItem::TryAsDyn) => {
683                    G::consider_builtin_try_as_dyn_candidate(self, goal)
684                }
685                Some(SolverTraitLangItem::Field) => G::consider_builtin_field_candidate(self, goal),
686                _ => Err(NoSolution.into()),
687            }
688        };
689
690        candidates.extend(result);
691
692        // There may be multiple unsize candidates for a trait with several supertraits:
693        // `trait Foo: Bar<A> + Bar<B>` and `dyn Foo: Unsize<dyn Bar<_>>`
694        if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
695            candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)?);
696        }
697
698        Ok(())
699    }
700
701    #[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(701u32),
                                    ::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)]
702    fn assemble_param_env_candidates<G: GoalKind<D>>(
703        &mut self,
704        goal: Goal<I, G>,
705        candidates: &mut Vec<Candidate<I>>,
706        failed_candidate_info: &mut FailedCandidateInfo,
707    ) -> Result<(), RerunNonErased> {
708        for assumption in goal.param_env.caller_bounds().iter() {
709            match G::probe_and_consider_param_env_candidate(self, goal, assumption)? {
710                Ok(candidate) => candidates.push(candidate),
711                Err(head_usages) => {
712                    failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
713                }
714            }
715        }
716
717        Ok(())
718    }
719
720    #[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(720u32),
                                    ::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)]
721    fn assemble_alias_bound_candidates<G: GoalKind<D>>(
722        &mut self,
723        goal: Goal<I, G>,
724        candidates: &mut Vec<Candidate<I>>,
725    ) -> Result<(), RerunNonErased> {
726        let res = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
727            ecx.assemble_alias_bound_candidates_recur(
728                goal.predicate.self_ty(),
729                goal,
730                candidates,
731                AliasBoundKind::SelfBounds,
732            )?;
733            Ok(())
734        });
735
736        // always returns Ok
737        match res {
738            Ok(_) => Ok(()),
739            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
740            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
741                unreachable!()
742            }
743        }
744    }
745
746    /// For some deeply nested `<T>::A::B::C::D` rigid associated type,
747    /// we should explore the item bounds for all levels, since the
748    /// `associated_type_bounds` feature means that a parent associated
749    /// type may carry bounds for a nested associated type.
750    ///
751    /// If we have a projection, check that its self type is a rigid projection.
752    /// If so, continue searching by recursively calling after normalization.
753    // FIXME: This may recurse infinitely, but I can't seem to trigger it without
754    // hitting another overflow error something. Add a depth parameter needed later.
755    fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
756        &mut self,
757        self_ty: I::Ty,
758        goal: Goal<I, G>,
759        candidates: &mut Vec<Candidate<I>>,
760        consider_self_bounds: AliasBoundKind,
761    ) -> Result<(), RerunNonErased> {
762        let (alias_ty, def_id) = match self_ty.kind() {
763            ty::Bool
764            | ty::Char
765            | ty::Int(_)
766            | ty::Uint(_)
767            | ty::Float(_)
768            | ty::Adt(_, _)
769            | ty::Foreign(_)
770            | ty::Str
771            | ty::Array(_, _)
772            | ty::Pat(_, _)
773            | ty::Slice(_)
774            | ty::RawPtr(_, _)
775            | ty::Ref(_, _, _)
776            | ty::FnDef(_, _)
777            | ty::FnPtr(..)
778            | ty::UnsafeBinder(_)
779            | ty::Dynamic(..)
780            | ty::Closure(..)
781            | ty::CoroutineClosure(..)
782            | ty::Coroutine(..)
783            | ty::CoroutineWitness(..)
784            | ty::Never
785            | ty::Tuple(_)
786            | ty::Param(_)
787            | ty::Placeholder(..)
788            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
789            | ty::Error(_) => return Ok(()),
790            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
791                {
    ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
            goal));
}panic!("unexpected self type for `{goal:?}`")
792            }
793
794            ty::Infer(ty::TyVar(_)) => {
795                // If we hit infer when normalizing the self type of an alias,
796                // then bail with ambiguity. We should never encounter this on
797                // the *first* iteration of this recursive function.
798                if let Ok(result) =
799                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
800                {
801                    candidates.push(Candidate {
802                        source: CandidateSource::AliasBound(consider_self_bounds),
803                        result,
804                        head_usages: CandidateHeadUsages::default(),
805                    });
806                }
807                return Ok(());
808            }
809
810            ty::Alias(
811                ty::IsRigid::Yes,
812                alias_ty @ AliasTy { kind: ty::Projection { def_id }, .. },
813            ) => (alias_ty, def_id.into()),
814
815            ty::Alias(ty::IsRigid::Yes, alias_ty @ AliasTy { kind: ty::Opaque { def_id }, .. }) => {
816                (alias_ty, def_id.into())
817            }
818
819            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:?}"),
820
821            ty::Alias(
822                ty::IsRigid::Yes,
823                AliasTy { kind: ty::Inherent { .. } | ty::Free { .. }, .. },
824            ) => {
825                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"));
826                return Ok(());
827            }
828        };
829
830        match consider_self_bounds {
831            AliasBoundKind::SelfBounds => {
832                for assumption in self
833                    .cx()
834                    .item_self_bounds(def_id)
835                    .iter_instantiated(self.cx(), alias_ty.args)
836                    .map(Unnormalized::skip_norm_wip)
837                {
838                    candidates.extend(G::probe_and_consider_implied_clause(
839                        self,
840                        CandidateSource::AliasBound(consider_self_bounds),
841                        goal,
842                        assumption,
843                        [],
844                    ));
845                }
846            }
847            AliasBoundKind::NonSelfBounds => {
848                for assumption in self
849                    .cx()
850                    .item_non_self_bounds(def_id)
851                    .iter_instantiated(self.cx(), alias_ty.args)
852                    .map(Unnormalized::skip_norm_wip)
853                {
854                    candidates.extend(G::probe_and_consider_implied_clause(
855                        self,
856                        CandidateSource::AliasBound(consider_self_bounds),
857                        goal,
858                        assumption,
859                        [],
860                    ));
861                }
862            }
863        }
864
865        candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
866
867        let Some(projection_ty) = alias_ty.try_to_projection() else {
868            return Ok(());
869        };
870
871        // Recurse on the self type of the projection.
872        match self.structurally_normalize_ty(goal.param_env, projection_ty.projection_self_ty()) {
873            Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
874                next_self_ty,
875                goal,
876                candidates,
877                AliasBoundKind::NonSelfBounds,
878            ),
879            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Ok(()),
880            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
881        }
882    }
883
884    #[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(884u32),
                                    ::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)]
885    fn assemble_object_bound_candidates<G: GoalKind<D>>(
886        &mut self,
887        goal: Goal<I, G>,
888        candidates: &mut Vec<Candidate<I>>,
889    ) {
890        let cx = self.cx();
891        if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
892            // `dyn MetaSized` is valid, but should get its `MetaSized` impl from
893            // being `dyn` (SizedCandidate), not from the object candidate.
894            return;
895        }
896
897        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
898        // of trying to handle these manually, we just reject all builtin impls in reflection
899        // mode. We can probably lift this restriction for specific cases, but this is safer.
900        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
901        if self.typing_mode().is_reflection() {
902            return;
903        }
904
905        let self_ty = goal.predicate.self_ty();
906        let bounds = match self_ty.kind() {
907            ty::Bool
908            | ty::Char
909            | ty::Int(_)
910            | ty::Uint(_)
911            | ty::Float(_)
912            | ty::Adt(_, _)
913            | ty::Foreign(_)
914            | ty::Str
915            | ty::Array(_, _)
916            | ty::Pat(_, _)
917            | ty::Slice(_)
918            | ty::RawPtr(_, _)
919            | ty::Ref(_, _, _)
920            | ty::FnDef(_, _)
921            | ty::FnPtr(..)
922            | ty::UnsafeBinder(_)
923            | ty::Alias(..)
924            | ty::Closure(..)
925            | ty::CoroutineClosure(..)
926            | ty::Coroutine(..)
927            | ty::CoroutineWitness(..)
928            | ty::Never
929            | ty::Tuple(_)
930            | ty::Param(_)
931            | ty::Placeholder(..)
932            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
933            | ty::Error(_) => return,
934            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
935            | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
936            ty::Dynamic(bounds, ..) => bounds,
937        };
938
939        // Do not consider built-in object impls for dyn-incompatible types.
940        if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
941            return;
942        }
943
944        // Consider all of the auto-trait and projection bounds, which don't
945        // need to be recorded as a `BuiltinImplSource::Object` since they don't
946        // really have a vtable base...
947        for bound in bounds.iter() {
948            match bound.skip_binder() {
949                ty::ExistentialPredicate::Trait(_) => {
950                    // Skip principal
951                }
952                ty::ExistentialPredicate::Projection(_)
953                | ty::ExistentialPredicate::AutoTrait(_) => {
954                    candidates.extend(G::probe_and_consider_object_bound_candidate(
955                        self,
956                        CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
957                        goal,
958                        bound.with_self_ty(cx, self_ty),
959                    ));
960                }
961            }
962        }
963
964        // FIXME: We only need to do *any* of this if we're considering a trait goal,
965        // since we don't need to look at any supertrait or anything if we are doing
966        // a projection goal.
967        if let Some(principal) = bounds.principal() {
968            let principal_trait_ref = principal.with_self_ty(cx, self_ty);
969            for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
970                candidates.extend(G::probe_and_consider_object_bound_candidate(
971                    self,
972                    CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
973                    goal,
974                    assumption.upcast(cx),
975                ));
976            }
977        }
978    }
979
980    /// In coherence we have to not only care about all impls we know about, but
981    /// also consider impls which may get added in a downstream or sibling crate
982    /// or which an upstream impl may add in a minor release.
983    ///
984    /// To do so we return a single ambiguous candidate in case such an unknown
985    /// impl could apply to the current goal.
986    #[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(986u32),
                                    ::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)]
987    fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
988        &mut self,
989        goal: Goal<I, G>,
990    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
991        self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
992            let cx = ecx.cx();
993            let trait_ref = goal.predicate.trait_ref(cx);
994            if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
995                Err(NoSolution.into())
996            } else {
997                // While the trait bound itself may be unknowable, we may be able to
998                // prove that a super trait is not implemented. For this, we recursively
999                // prove the super trait bounds of the current goal.
1000                //
1001                // We skip the goal itself as that one would cycle.
1002                let predicate: I::Predicate = trait_ref.upcast(cx);
1003                ecx.add_goals(
1004                    GoalSource::Misc,
1005                    elaborate::elaborate(cx, [predicate])
1006                        .skip(1)
1007                        .map(|predicate| goal.with(cx, predicate)),
1008                )?;
1009                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1010            }
1011        })
1012    }
1013}
1014
1015pub(super) enum AllowInferenceConstraints {
1016    Yes,
1017    No,
1018}
1019
1020impl<D, I> EvalCtxt<'_, D>
1021where
1022    D: SolverDelegate<Interner = I>,
1023    I: Interner,
1024{
1025    /// Check whether we can ignore impl candidates due to specialization.
1026    ///
1027    /// This is only necessary for `feature(specialization)` and seems quite ugly.
1028    pub(super) fn filter_specialized_impls(
1029        &mut self,
1030        allow_inference_constraints: AllowInferenceConstraints,
1031        candidates: &mut Vec<Candidate<I>>,
1032    ) {
1033        if self.typing_mode().is_coherence() {
1034            return;
1035        }
1036
1037        let mut i = 0;
1038        'outer: while i < candidates.len() {
1039            let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
1040                i += 1;
1041                continue;
1042            };
1043
1044            for (j, c) in candidates.iter().enumerate() {
1045                if i == j {
1046                    continue;
1047                }
1048
1049                let CandidateSource::Impl(other_def_id) = c.source else {
1050                    continue;
1051                };
1052
1053                // See if we can toss out `victim` based on specialization.
1054                //
1055                // While this requires us to know *for sure* that the `lhs` impl applies
1056                // we still use modulo regions here. This is fine as specialization currently
1057                // assumes that specializing impls have to be always applicable, meaning that
1058                // the only allowed region constraints may be constraints also present on the default impl.
1059                if #[allow(non_exhaustive_omitted_patterns)] match allow_inference_constraints {
    AllowInferenceConstraints::Yes => true,
    _ => false,
}matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
1060                    || has_only_region_constraints(c.result)
1061                {
1062                    if self.cx().impl_specializes(other_def_id, victim_def_id) {
1063                        candidates.remove(i);
1064                        continue 'outer;
1065                    }
1066                }
1067            }
1068
1069            i += 1;
1070        }
1071    }
1072
1073    /// If the self type is the hidden type of an opaque, try to assemble
1074    /// candidates for it by consider its item bounds and by using blanket
1075    /// impls. This is used to incompletely guide type inference when handling
1076    /// non-defining uses in the defining scope.
1077    ///
1078    /// We otherwise just fail fail with ambiguity. Even if we're using an
1079    /// opaque type item bound or a blank impls, we still force its certainty
1080    /// to be `Maybe` so that we properly prove this goal later.
1081    ///
1082    /// See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/182>
1083    /// for why this is necessary.
1084    #[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(1084u32),
                                    ::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:1114",
                                        "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(1114u32),
                                        ::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|
                            {
                                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))]
1085    fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
1086        &mut self,
1087        goal: Goal<I, G>,
1088        assemble_from: AssembleCandidatesFrom,
1089        candidates: &mut Vec<Candidate<I>>,
1090    ) -> Result<(), RerunNonErased> {
1091        let self_ty = goal.predicate.self_ty();
1092        // We only use this hack during HIR typeck.
1093        let opaque_types = match self.typing_mode() {
1094            TypingMode::Typeck { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
1095            TypingMode::Coherence
1096            | TypingMode::PostTypeckUntilBorrowck { .. }
1097            | TypingMode::PostBorrowck { .. }
1098            | TypingMode::PostAnalysis
1099            | TypingMode::Reflection
1100            | TypingMode::Codegen => vec![],
1101            TypingMode::ErasedNotCoherence(MayBeErased) => {
1102                self.opaque_accesses
1103                    .rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
1104                Vec::new()
1105            }
1106        };
1107
1108        if opaque_types.is_empty() {
1109            candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
1110            return Ok(());
1111        }
1112
1113        for &opaque_ty in &opaque_types {
1114            debug!("self ty is sub unified with {opaque_ty:?}");
1115
1116            struct ReplaceOpaque<I: Interner> {
1117                cx: I,
1118                opaque_ty: ty::OpaqueAliasTy<I>,
1119                self_ty: I::Ty,
1120            }
1121            impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
1122                fn cx(&self) -> I {
1123                    self.cx
1124                }
1125                fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1126                    if let ty::Alias(is_rigid, alias_ty) = ty.kind()
1127                        && let Some(opaque_ty) = alias_ty.try_to_opaque()
1128                    {
1129                        if opaque_ty == self.opaque_ty {
1130                            debug_assert_eq!(is_rigid, ty::IsRigid::No);
1131                            return self.self_ty;
1132                        }
1133                    }
1134                    ty.super_fold_with(self)
1135                }
1136            }
1137
1138            // We look at all item-bounds of the opaque, replacing the
1139            // opaque with the current self type before considering
1140            // them as a candidate. Imagine we've got `?x: Trait<?y>`
1141            // and `?x` has been sub-unified with the hidden type of
1142            // `impl Trait<u32>`, We take the item bound `opaque: Trait<u32>`
1143            // and replace all occurrences of `opaque` with `?x`. This results
1144            // in a `?x: Trait<u32>` alias-bound candidate.
1145            for item_bound in self
1146                .cx()
1147                .item_self_bounds(opaque_ty.kind.into())
1148                .iter_instantiated(self.cx(), opaque_ty.args)
1149                .map(Unnormalized::skip_norm_wip)
1150            {
1151                let assumption =
1152                    item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), opaque_ty, self_ty });
1153                candidates.extend(G::probe_and_match_goal_against_assumption(
1154                    self,
1155                    CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1156                    goal,
1157                    assumption,
1158                    |ecx| {
1159                        // We want to reprove this goal once we've inferred the
1160                        // hidden type, so we force the certainty to `Maybe`.
1161                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1162                    },
1163                ));
1164            }
1165        }
1166
1167        // If the self type is sub unified with any opaque type, we also look at blanket
1168        // impls for it.
1169        //
1170        // See tests/ui/impl-trait/non-defining-uses/use-blanket-impl.rs for an example.
1171        if assemble_from.should_assemble_impl_candidates() {
1172            let cx = self.cx();
1173            let goal_trait_ref = goal.predicate.trait_ref(cx);
1174            cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1175                match G::consider_impl_candidate(
1176                    self,
1177                    goal,
1178                    goal_trait_ref,
1179                    impl_def_id,
1180                    |ecx, certainty| {
1181                        if ecx.shallow_resolve(self_ty).is_ty_var() {
1182                            // We force the certainty of impl candidates to be `Maybe`.
1183                            let certainty = certainty.and(Certainty::AMBIGUOUS);
1184                            ecx.evaluate_added_goals_and_make_canonical_response(certainty)
1185                        } else {
1186                            // We don't want to use impls if they constrain the opaque.
1187                            //
1188                            // FIXME(trait-system-refactor-initiative#229): This isn't
1189                            // perfect yet as it still allows us to incorrectly constrain
1190                            // other inference variables.
1191                            Err(NoSolution.into())
1192                        }
1193                    },
1194                )
1195                .map_err_to_rerun()?
1196                {
1197                    Ok(candidate) => candidates.push(candidate),
1198                    Err(NoSolution) => {}
1199                }
1200
1201                Ok(())
1202            })?;
1203        }
1204
1205        if candidates.is_empty() {
1206            let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1207            let certainty = Certainty::Maybe(MaybeInfo {
1208                cause: MaybeCause::Ambiguity,
1209                opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1210                stalled_on_coroutines: StalledOnCoroutines::No,
1211            });
1212            candidates
1213                .extend(self.probe_trait_candidate(source).enter(|this| {
1214                    this.evaluate_added_goals_and_make_canonical_response(certainty)
1215                }));
1216        }
1217
1218        Ok(())
1219    }
1220
1221    /// Assemble and merge candidates for goals which are related to an underlying trait
1222    /// goal. Right now, this is normalizes-to and host effect goals.
1223    ///
1224    /// We sadly can't simply take all possible candidates for normalization goals
1225    /// and check whether they result in the same constraints. We want to make sure
1226    /// that trying to normalize an alias doesn't result in constraints which aren't
1227    /// otherwise required.
1228    ///
1229    /// Most notably, when proving a trait goal by via a where-bound, we should not
1230    /// normalize via impls which have stricter region constraints than the where-bound:
1231    ///
1232    /// ```rust
1233    /// trait Trait<'a> {
1234    ///     type Assoc;
1235    /// }
1236    ///
1237    /// impl<'a, T: 'a> Trait<'a> for T {
1238    ///     type Assoc = u32;
1239    /// }
1240    ///
1241    /// fn with_bound<'a, T: Trait<'a>>(_value: T::Assoc) {}
1242    /// ```
1243    ///
1244    /// The where-bound of `with_bound` doesn't specify the associated type, so we would
1245    /// only be able to normalize `<T as Trait<'a>>::Assoc` by using the impl. This impl
1246    /// adds a `T: 'a` bound however, which would result in a region error. Given that the
1247    /// user explicitly wrote that `T: Trait<'a>` holds, this is undesirable and we instead
1248    /// treat the alias as rigid.
1249    ///
1250    /// See trait-system-refactor-initiative#124 for more details.
1251    x;#[instrument(level = "debug", skip_all, fields(proven_via, goal), ret)]
1252    pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1253        &mut self,
1254        proven_via: Option<TraitGoalProvenVia>,
1255        goal: Goal<I, G>,
1256        inject_forced_ambiguity_candidate: impl FnOnce(
1257            &mut EvalCtxt<'_, D>,
1258        ) -> Option<
1259            Result<CanonicalResponse<I>, NoSolutionOrRerunNonErased>,
1260        >,
1261        inject_normalize_to_rigid_candidate: impl FnOnce(
1262            &mut EvalCtxt<'_, D>,
1263        ) -> Result<
1264            CanonicalResponse<I>,
1265            NoSolutionOrRerunNonErased,
1266        >,
1267    ) -> QueryResultOrRerunNonErased<I> {
1268        let Some(proven_via) = proven_via else {
1269            // We don't care about overflow. If proving the trait goal overflowed, then
1270            // it's enough to report an overflow error for that, we don't also have to
1271            // overflow during normalization.
1272            //
1273            // We use `forced_ambiguity` here over `make_ambiguous_response_no_constraints`
1274            // because the former will also record a built-in candidate in the inspector.
1275            return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand| cand.result);
1276        };
1277
1278        match proven_via {
1279            TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1280                // Even when a trait bound has been proven using a where-bound, we
1281                // still need to consider alias-bounds for normalization, see
1282                // `tests/ui/next-solver/alias-bound-shadowed-by-env.rs`.
1283                let (mut candidates, _) = self
1284                    .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds)?;
1285                debug!(?candidates);
1286
1287                // If the trait goal has been proven by using the environment, we want to treat
1288                // aliases as rigid if there are no applicable projection bounds in the environment.
1289                if candidates.is_empty() {
1290                    return inject_normalize_to_rigid_candidate(self);
1291                }
1292
1293                // If we're normalizing an GAT, we bail if using a where-bound would constrain
1294                // its generic arguments.
1295                if let Some(result) = inject_forced_ambiguity_candidate(self) {
1296                    return result;
1297                }
1298
1299                // We still need to prefer where-bounds over alias-bounds however.
1300                // See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`.
1301                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1302                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1303                }
1304
1305                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1306                    Ok(response)
1307                } else {
1308                    self.flounder(&candidates).map_err(Into::into)
1309                }
1310            }
1311            TraitGoalProvenVia::Misc => {
1312                let (mut candidates, _) =
1313                    self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1314
1315                // Prefer "orphaned" param-env normalization predicates, which are used
1316                // (for example, and ideally only) when proving item bounds for an impl.
1317                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1318                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1319                }
1320
1321                // We drop specialized impls to allow normalization via a final impl here. In case
1322                // the specializing impl has different inference constraints from the specialized
1323                // impl, proving the trait goal is already ambiguous, so we never get here. This
1324                // means we can just ignore inference constraints and don't have to special-case
1325                // constraining the normalized-to `term`.
1326                self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1327                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1328                    Ok(response)
1329                } else {
1330                    self.flounder(&candidates).map_err(Into::into)
1331                }
1332            }
1333        }
1334    }
1335
1336    /// Compute whether a param-env assumption is global or non-global after normalizing it.
1337    ///
1338    /// This is necessary because, for example, given:
1339    ///
1340    /// ```ignore,rust
1341    /// where
1342    ///     T: Trait<Assoc = u32>,
1343    ///     i32: From<T::Assoc>,
1344    /// ```
1345    ///
1346    /// The `i32: From<T::Assoc>` bound is non-global before normalization, but is global after.
1347    /// Since the old trait solver normalized param-envs eagerly, we want to emulate this
1348    /// behavior lazily.
1349    fn characterize_param_env_assumption(
1350        &mut self,
1351        param_env: I::ParamEnv,
1352        assumption: I::Clause,
1353    ) -> Result<(CandidateSource<I>, Certainty), NoSolution> {
1354        // FIXME: This should be fixed, but it also requires changing the behavior
1355        // in the old solver which is currently relied on.
1356        if assumption.has_bound_vars() {
1357            return Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), Certainty::Yes));
1358        }
1359
1360        match assumption.visit_with(&mut FindParamInClause {
1361            ecx: self,
1362            param_env,
1363            universes: ::alloc::vec::Vec::new()vec![],
1364            recursion_depth: 0,
1365        }) {
1366            ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1367            ControlFlow::Break(Ok(certainty)) => {
1368                Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), certainty))
1369            }
1370            ControlFlow::Continue(()) => {
1371                Ok((CandidateSource::ParamEnv(ParamEnvSource::Global), Certainty::Yes))
1372            }
1373        }
1374    }
1375}
1376
1377struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1378    ecx: &'a mut EvalCtxt<'b, D>,
1379    param_env: I::ParamEnv,
1380    universes: Vec<Option<ty::UniverseIndex>>,
1381    recursion_depth: usize,
1382}
1383
1384impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1385where
1386    D: SolverDelegate<Interner = I>,
1387    I: Interner,
1388{
1389    // - `Continue(())`: no generic parameter was found, the type is global
1390    // - `Break(Ok(Certainty::Yes))`: a generic parameter was found, the type is non-global
1391    // - `Break(Ok(Certainty::Maybe(_)))`: the recursion limit reached, assume that the type is non-global
1392    // - `Break(Err(NoSolution))`: normalization failed
1393    type Result = ControlFlow<Result<Certainty, NoSolution>>;
1394
1395    fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1396        self.universes.push(None);
1397        t.super_visit_with(self)?;
1398        self.universes.pop();
1399        ControlFlow::Continue(())
1400    }
1401
1402    fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1403        let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1404        let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1405            return ControlFlow::Break(Err(NoSolution));
1406        };
1407
1408        match ty.kind() {
1409            ty::Placeholder(p) => {
1410                if p.universe() == ty::UniverseIndex::ROOT {
1411                    ControlFlow::Break(Ok(Certainty::Yes))
1412                } else {
1413                    ControlFlow::Continue(())
1414                }
1415            }
1416            ty::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1417            _ if ty.has_type_flags(
1418                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1419            ) =>
1420            {
1421                self.recursion_depth += 1;
1422                if self.recursion_depth > self.ecx.cx().recursion_limit() {
1423                    return ControlFlow::Break(Ok(Certainty::Maybe(MaybeInfo {
1424                        cause: MaybeCause::Overflow {
1425                            suggest_increasing_limit: true,
1426                            keep_constraints: false,
1427                        },
1428                        opaque_types_jank: OpaqueTypesJank::AllGood,
1429                        stalled_on_coroutines: StalledOnCoroutines::No,
1430                    })));
1431                }
1432                let result = ty.super_visit_with(self);
1433                self.recursion_depth -= 1;
1434                result
1435            }
1436            _ => ControlFlow::Continue(()),
1437        }
1438    }
1439
1440    fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1441        let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1442        let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1443            return ControlFlow::Break(Err(NoSolution));
1444        };
1445
1446        match ct.kind() {
1447            ty::ConstKind::Placeholder(p) => {
1448                if p.universe() == ty::UniverseIndex::ROOT {
1449                    ControlFlow::Break(Ok(Certainty::Yes))
1450                } else {
1451                    ControlFlow::Continue(())
1452                }
1453            }
1454            ty::ConstKind::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1455            _ if ct.has_type_flags(
1456                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1457            ) =>
1458            {
1459                // FIXME(mgca): we should also check the recursion limit here
1460                ct.super_visit_with(self)
1461            }
1462            _ => ControlFlow::Continue(()),
1463        }
1464    }
1465
1466    fn visit_region(&mut self, r: Region<I>) -> Self::Result {
1467        match self.ecx.eager_resolve_region(r).kind() {
1468            ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1469            ty::RePlaceholder(p) => {
1470                if p.universe() == ty::UniverseIndex::ROOT {
1471                    ControlFlow::Break(Ok(Certainty::Yes))
1472                } else {
1473                    ControlFlow::Continue(())
1474                }
1475            }
1476            ty::ReVar(_) => ControlFlow::Break(Ok(Certainty::Yes)),
1477            ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1478                {
    ::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")
1479            }
1480        }
1481    }
1482}