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, TypeFlags, TypeFoldable, TypeFolder,
18    TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
19    TypingMode, Unnormalized, Upcast, elaborate,
20};
21use tracing::{debug, instrument};
22
23use super::trait_goals::TraitGoalProvenVia;
24use super::{has_only_region_constraints, inspect};
25use crate::delegate::SolverDelegate;
26use crate::solve::inspect::ProbeKind;
27use crate::solve::{
28    BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource,
29    MaybeCause, NoSolution, OpaqueTypesJank, ParamEnvSource, QueryResult,
30    has_no_inference_or_external_constraints,
31};
32
33/// A candidate is a possible way to prove a goal.
34///
35/// It consists of both the `source`, which describes how that goal would be proven,
36/// and the `result` when using the given `source`.
37#[automatically_derived]
impl<I: Interner> ::core::fmt::Debug for Candidate<I> where I: Interner {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            Candidate {
                source: ref __field_source,
                result: ref __field_result,
                head_usages: ref __field_head_usages } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f, "Candidate");
                ::core::fmt::DebugStruct::field(&mut __builder, "source",
                    __field_source);
                ::core::fmt::DebugStruct::field(&mut __builder, "result",
                    __field_result);
                ::core::fmt::DebugStruct::field(&mut __builder, "head_usages",
                    __field_head_usages);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Debug; I: Interner)]
38pub(super) struct Candidate<I: Interner> {
39    pub(super) source: CandidateSource<I>,
40    pub(super) result: CanonicalResponse<I>,
41    pub(super) head_usages: CandidateHeadUsages,
42}
43
44/// Methods used to assemble candidates for either trait or projection goals.
45pub(super) trait GoalKind<D, I = <D as SolverDelegate>::Interner>:
46    TypeFoldable<I> + Copy + Eq + std::fmt::Display
47where
48    D: SolverDelegate<Interner = I>,
49    I: Interner,
50{
51    fn self_ty(self) -> I::Ty;
52
53    fn trait_ref(self, cx: I) -> ty::TraitRef<I>;
54
55    fn with_replaced_self_ty(self, cx: I, self_ty: I::Ty) -> Self;
56
57    fn trait_def_id(self, cx: I) -> I::TraitId;
58
59    /// Consider a clause, which consists of a "assumption" and some "requirements",
60    /// to satisfy a goal. If the requirements hold, then attempt to satisfy our
61    /// goal by equating it with the assumption.
62    fn probe_and_consider_implied_clause(
63        ecx: &mut EvalCtxt<'_, D>,
64        parent_source: CandidateSource<I>,
65        goal: Goal<I, Self>,
66        assumption: I::Clause,
67        requirements: impl IntoIterator<Item = (GoalSource, Goal<I, I::Predicate>)>,
68    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
69        Self::probe_and_match_goal_against_assumption(ecx, parent_source, goal, assumption, |ecx| {
70            for (nested_source, goal) in requirements {
71                ecx.add_goal(nested_source, goal)?;
72            }
73            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
74        })
75    }
76
77    /// Consider a clause specifically for a `dyn Trait` self type. This requires
78    /// additionally checking all of the supertraits and object bounds to hold,
79    /// since they're not implied by the well-formedness of the object type.
80    /// `NormalizesTo` overrides this to not check the supertraits for backwards
81    /// compatibility with the old solver. cc trait-system-refactor-initiative#245.
82    fn probe_and_consider_object_bound_candidate(
83        ecx: &mut EvalCtxt<'_, D>,
84        source: CandidateSource<I>,
85        goal: Goal<I, Self>,
86        assumption: I::Clause,
87    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
88        Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| {
89            let cx = ecx.cx();
90            let ty::Dynamic(bounds, _) = goal.predicate.self_ty().kind() else {
91                {
    ::core::panicking::panic_fmt(format_args!("expected object type in `probe_and_consider_object_bound_candidate`"));
};panic!("expected object type in `probe_and_consider_object_bound_candidate`");
92            };
93
94            let trait_ref = assumption.kind().map_bound(|clause| match clause {
95                ty::ClauseKind::Trait(pred) => pred.trait_ref,
96                ty::ClauseKind::Projection(proj) => proj.projection_term.trait_ref(cx),
97
98                ty::ClauseKind::RegionOutlives(..)
99                | ty::ClauseKind::TypeOutlives(..)
100                | ty::ClauseKind::ConstArgHasType(..)
101                | ty::ClauseKind::WellFormed(..)
102                | ty::ClauseKind::ConstEvaluatable(..)
103                | ty::ClauseKind::HostEffect(..)
104                | ty::ClauseKind::UnstableFeature(..) => {
105                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("expected trait or projection predicate as an assumption")));
}unreachable!("expected trait or projection predicate as an assumption")
106                }
107            });
108
109            match structural_traits::predicates_for_object_candidate(
110                ecx,
111                goal.param_env,
112                trait_ref,
113                bounds,
114            ) {
115                Ok(requirements) => {
116                    ecx.add_goals(GoalSource::ImplWhereBound, requirements)?;
117                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
118                }
119                Err(_) => {
120                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
121                }
122            }
123        })
124    }
125
126    /// Assemble additional assumptions for an alias that are not included
127    /// in the item bounds of the alias. For now, this is limited to the
128    /// `explicit_implied_const_bounds` for an associated type.
129    fn consider_additional_alias_assumptions(
130        ecx: &mut EvalCtxt<'_, D>,
131        goal: Goal<I, Self>,
132        alias_ty: ty::AliasTy<I>,
133    ) -> Vec<Candidate<I>>;
134
135    fn probe_and_consider_param_env_candidate(
136        ecx: &mut EvalCtxt<'_, D>,
137        goal: Goal<I, Self>,
138        assumption: I::Clause,
139    ) -> Result<Result<Candidate<I>, CandidateHeadUsages>, RerunNonErased> {
140        match Self::fast_reject_assumption(ecx, goal, assumption) {
141            Ok(()) => {}
142            Err(NoSolution) => return Ok(Err(CandidateHeadUsages::default())),
143        }
144
145        // Dealing with `ParamEnv` candidates is a bit of a mess as we need to lazily
146        // check whether the candidate is global while considering normalization.
147        //
148        // We need to write into `source` inside of `match_assumption`, but need to access it
149        // in `probe` even if the candidate does not apply before we get there. We handle this
150        // by using a `Cell` here. We only ever write into it inside of `match_assumption`.
151        let source = Cell::new(CandidateSource::ParamEnv(ParamEnvSource::Global));
152        let (result, head_usages) = ecx
153            .probe(|result: &QueryResult<I>| inspect::ProbeKind::TraitCandidate {
154                source: source.get(),
155                result: *result,
156            })
157            .enter_single_candidate(|ecx| {
158                Self::match_assumption(
159                    ecx,
160                    goal,
161                    assumption,
162                    |ecx| -> Result<_, NoSolutionOrRerunNonErased> {
163                        ecx.try_evaluate_added_goals()?;
164                        let (src, certainty) =
165                            ecx.characterize_param_env_assumption(goal.param_env, assumption)?;
166                        source.set(src);
167                        ecx.evaluate_added_goals_and_make_canonical_response(certainty)
168                    },
169                )
170                .map_err(Into::into)
171            });
172
173        Ok(match result.map_err_to_rerun()? {
174            Ok(result) => Ok(Candidate { source: source.get(), result, head_usages }),
175            Err(NoSolution) => Err(head_usages),
176        })
177    }
178
179    /// Try equating an assumption predicate against a goal's predicate. If it
180    /// holds, then execute the `then` callback, which should do any additional
181    /// work, then produce a response (typically by executing
182    /// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
183    fn probe_and_match_goal_against_assumption(
184        ecx: &mut EvalCtxt<'_, D>,
185        source: CandidateSource<I>,
186        goal: Goal<I, Self>,
187        assumption: I::Clause,
188        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
189    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
190        Self::fast_reject_assumption(ecx, goal, assumption)?;
191
192        ecx.probe_trait_candidate(source)
193            .enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
194    }
195
196    /// Try to reject the assumption based off of simple heuristics, such as [`ty::ClauseKind`]
197    /// and `DefId`.
198    fn fast_reject_assumption(
199        ecx: &mut EvalCtxt<'_, D>,
200        goal: Goal<I, Self>,
201        assumption: I::Clause,
202    ) -> Result<(), NoSolution>;
203
204    /// Relate the goal and assumption.
205    fn match_assumption(
206        ecx: &mut EvalCtxt<'_, D>,
207        goal: Goal<I, Self>,
208        assumption: I::Clause,
209        then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResultOrRerunNonErased<I>,
210    ) -> QueryResultOrRerunNonErased<I>;
211
212    fn consider_impl_candidate(
213        ecx: &mut EvalCtxt<'_, D>,
214        goal: Goal<I, Self>,
215        impl_def_id: I::ImplId,
216        then: impl FnOnce(&mut EvalCtxt<'_, D>, Certainty) -> QueryResultOrRerunNonErased<I>,
217    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
218
219    /// If the predicate contained an error, we want to avoid emitting unnecessary trait
220    /// errors but still want to emit errors for other trait goals. We have some special
221    /// handling for this case.
222    ///
223    /// Trait goals always hold while projection goals never do. This is a bit arbitrary
224    /// but prevents incorrect normalization while hiding any trait errors.
225    fn consider_error_guaranteed_candidate(
226        ecx: &mut EvalCtxt<'_, D>,
227        goal: Goal<I, Self>,
228        guar: I::ErrorGuaranteed,
229    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
230
231    /// A type implements an `auto trait` if its components do as well.
232    ///
233    /// These components are given by built-in rules from
234    /// [`structural_traits::instantiate_constituent_tys_for_auto_trait`].
235    fn consider_auto_trait_candidate(
236        ecx: &mut EvalCtxt<'_, D>,
237        goal: Goal<I, Self>,
238    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
239
240    /// A trait alias holds if the RHS traits and `where` clauses hold.
241    fn consider_trait_alias_candidate(
242        ecx: &mut EvalCtxt<'_, D>,
243        goal: Goal<I, Self>,
244    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
245
246    /// A type is `Sized` if its tail component is `Sized` and a type is `MetaSized` if its tail
247    /// component is `MetaSized`.
248    ///
249    /// These components are given by built-in rules from
250    /// [`structural_traits::instantiate_constituent_tys_for_sizedness_trait`].
251    fn consider_builtin_sizedness_candidates(
252        ecx: &mut EvalCtxt<'_, D>,
253        goal: Goal<I, Self>,
254        sizedness: SizedTraitKind,
255    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
256
257    /// A type is `Copy` or `Clone` if its components are `Copy` or `Clone`.
258    ///
259    /// These components are given by built-in rules from
260    /// [`structural_traits::instantiate_constituent_tys_for_copy_clone_trait`].
261    fn consider_builtin_copy_clone_candidate(
262        ecx: &mut EvalCtxt<'_, D>,
263        goal: Goal<I, Self>,
264    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
265
266    /// A type is a `FnPtr` if it is of `FnPtr` type.
267    fn consider_builtin_fn_ptr_trait_candidate(
268        ecx: &mut EvalCtxt<'_, D>,
269        goal: Goal<I, Self>,
270    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
271
272    /// A callable type (a closure, fn def, or fn ptr) is known to implement the `Fn<A>`
273    /// family of traits where `A` is given by the signature of the type.
274    fn consider_builtin_fn_trait_candidates(
275        ecx: &mut EvalCtxt<'_, D>,
276        goal: Goal<I, Self>,
277        kind: ty::ClosureKind,
278    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
279
280    /// An async closure is known to implement the `AsyncFn<A>` family of traits
281    /// where `A` is given by the signature of the type.
282    fn consider_builtin_async_fn_trait_candidates(
283        ecx: &mut EvalCtxt<'_, D>,
284        goal: Goal<I, Self>,
285        kind: ty::ClosureKind,
286    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
287
288    /// Compute the built-in logic of the `AsyncFnKindHelper` helper trait, which
289    /// is used internally to delay computation for async closures until after
290    /// upvar analysis is performed in HIR typeck.
291    fn consider_builtin_async_fn_kind_helper_candidate(
292        ecx: &mut EvalCtxt<'_, D>,
293        goal: Goal<I, Self>,
294    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
295
296    /// `Tuple` is implemented if the `Self` type is a tuple.
297    fn consider_builtin_tuple_candidate(
298        ecx: &mut EvalCtxt<'_, D>,
299        goal: Goal<I, Self>,
300    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
301
302    /// `Pointee` is always implemented.
303    ///
304    /// See the projection implementation for the `Metadata` types for all of
305    /// the built-in types. For structs, the metadata type is given by the struct
306    /// tail.
307    fn consider_builtin_pointee_candidate(
308        ecx: &mut EvalCtxt<'_, D>,
309        goal: Goal<I, Self>,
310    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
311
312    /// A coroutine (that comes from an `async` desugaring) is known to implement
313    /// `Future<Output = O>`, where `O` is given by the coroutine's return type
314    /// that was computed during type-checking.
315    fn consider_builtin_future_candidate(
316        ecx: &mut EvalCtxt<'_, D>,
317        goal: Goal<I, Self>,
318    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
319
320    /// A coroutine (that comes from a `gen` desugaring) is known to implement
321    /// `Iterator<Item = O>`, where `O` is given by the generator's yield type
322    /// that was computed during type-checking.
323    fn consider_builtin_iterator_candidate(
324        ecx: &mut EvalCtxt<'_, D>,
325        goal: Goal<I, Self>,
326    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
327
328    /// A coroutine (that comes from a `gen` desugaring) is known to implement
329    /// `FusedIterator`
330    fn consider_builtin_fused_iterator_candidate(
331        ecx: &mut EvalCtxt<'_, D>,
332        goal: Goal<I, Self>,
333    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
334
335    fn consider_builtin_async_iterator_candidate(
336        ecx: &mut EvalCtxt<'_, D>,
337        goal: Goal<I, Self>,
338    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
339
340    /// A coroutine (that doesn't come from an `async` or `gen` desugaring) is known to
341    /// implement `Coroutine<R, Yield = Y, Return = O>`, given the resume, yield,
342    /// and return types of the coroutine computed during type-checking.
343    fn consider_builtin_coroutine_candidate(
344        ecx: &mut EvalCtxt<'_, D>,
345        goal: Goal<I, Self>,
346    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
347
348    fn consider_builtin_discriminant_kind_candidate(
349        ecx: &mut EvalCtxt<'_, D>,
350        goal: Goal<I, Self>,
351    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
352
353    fn consider_builtin_destruct_candidate(
354        ecx: &mut EvalCtxt<'_, D>,
355        goal: Goal<I, Self>,
356    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
357
358    fn consider_builtin_transmute_candidate(
359        ecx: &mut EvalCtxt<'_, D>,
360        goal: Goal<I, Self>,
361    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
362
363    fn consider_builtin_bikeshed_guaranteed_no_drop_candidate(
364        ecx: &mut EvalCtxt<'_, D>,
365        goal: Goal<I, Self>,
366    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
367
368    /// Consider (possibly several) candidates to upcast or unsize a type to another
369    /// type, excluding the coercion of a sized type into a `dyn Trait`.
370    ///
371    /// We return the `BuiltinImplSource` for each candidate as it is needed
372    /// for unsize coercion in hir typeck and because it is difficult to
373    /// otherwise recompute this for codegen. This is a bit of a mess but the
374    /// easiest way to maintain the existing behavior for now.
375    fn consider_structural_builtin_unsize_candidates(
376        ecx: &mut EvalCtxt<'_, D>,
377        goal: Goal<I, Self>,
378    ) -> Result<Vec<Candidate<I>>, RerunNonErased>;
379
380    fn consider_builtin_field_candidate(
381        ecx: &mut EvalCtxt<'_, D>,
382        goal: Goal<I, Self>,
383    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased>;
384}
385
386/// Allows callers of `assemble_and_evaluate_candidates` to choose whether to limit
387/// candidate assembly to param-env and alias-bound candidates.
388///
389/// On top of being a micro-optimization, as it avoids doing unnecessary work when
390/// a param-env trait bound candidate shadows impls for normalization, this is also
391/// required to prevent query cycles due to RPITIT inference. See the issue at:
392/// <https://github.com/rust-lang/trait-system-refactor-initiative/issues/173>.
393pub(super) enum AssembleCandidatesFrom {
394    All,
395    /// Only assemble candidates from the environment and alias bounds, ignoring
396    /// user-written and built-in impls. We only expect `ParamEnv` and `AliasBound`
397    /// candidates to be assembled.
398    EnvAndBounds,
399}
400
401impl AssembleCandidatesFrom {
402    fn should_assemble_impl_candidates(&self) -> bool {
403        match self {
404            AssembleCandidatesFrom::All => true,
405            AssembleCandidatesFrom::EnvAndBounds => false,
406        }
407    }
408}
409
410/// This is currently used to track the [CandidateHeadUsages] of all failed `ParamEnv`
411/// candidates. This is then used to ignore their head usages in case there's another
412/// always applicable `ParamEnv` candidate. Look at how `param_env_head_usages` is
413/// used in the code for more details.
414///
415/// We could easily extend this to also ignore head usages of other ignored candidates.
416/// However, we currently don't have any tests where this matters and the complexity of
417/// doing so does not feel worth it for now.
418#[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)]
419pub(super) struct FailedCandidateInfo {
420    pub param_env_head_usages: CandidateHeadUsages,
421}
422
423impl<D, I> EvalCtxt<'_, D>
424where
425    D: SolverDelegate<Interner = I>,
426    I: Interner,
427{
428    // FIXME(#155443): This function should only ever return an error
429    // as we want to force a rerun when accessing opaques. We should change
430    // this file to revert all the newly added places which return `NoSolution`.
431    pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<D>>(
432        &mut self,
433        goal: Goal<I, G>,
434        assemble_from: AssembleCandidatesFrom,
435    ) -> Result<(Vec<Candidate<I>>, FailedCandidateInfo), RerunNonErased> {
436        let mut candidates = ::alloc::vec::Vec::new()vec![];
437        let mut failed_candidate_info =
438            FailedCandidateInfo { param_env_head_usages: CandidateHeadUsages::default() };
439        let Ok(normalized_self_ty) =
440            self.structurally_normalize_ty(goal.param_env, goal.predicate.self_ty())
441        else {
442            return Ok((candidates, failed_candidate_info));
443        };
444
445        let goal: Goal<I, G> = goal
446            .with(self.cx(), goal.predicate.with_replaced_self_ty(self.cx(), normalized_self_ty));
447
448        if normalized_self_ty.is_ty_var() {
449            {
    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:449",
                        "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(449u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("self type has been normalized to infer")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("self type has been normalized to infer");
450            self.try_assemble_bounds_via_registered_opaques(goal, assemble_from, &mut candidates)?;
451            return Ok((candidates, failed_candidate_info));
452        }
453
454        // Vars that show up in the rest of the goal substs may have been constrained by
455        // normalizing the self type as well, since type variables are not uniquified.
456        let goal = self.resolve_vars_if_possible(goal);
457
458        if self.typing_mode().is_coherence()
459            && let Ok(candidate) = self.consider_coherence_unknowable_candidate(goal)
460        {
461            candidates.push(candidate);
462            return Ok((candidates, failed_candidate_info));
463        }
464
465        self.assemble_alias_bound_candidates(goal, &mut candidates)?;
466        self.assemble_param_env_candidates(goal, &mut candidates, &mut failed_candidate_info)?;
467
468        match assemble_from {
469            AssembleCandidatesFrom::All => {
470                self.assemble_builtin_impl_candidates(goal, &mut candidates)?;
471                // For performance we only assemble impls if there are no candidates
472                // which would shadow them. This is necessary to avoid hangs in rayon,
473                // see trait-system-refactor-initiative#109 for more details.
474                //
475                // We always assemble builtin impls as trivial builtin impls have a higher
476                // priority than where-clauses.
477                //
478                // We only do this if any such candidate applies without any constraints
479                // as we may want to weaken inference guidance in the future and don't want
480                // to worry about causing major performance regressions when doing so.
481                // See trait-system-refactor-initiative#226 for some ideas here.
482                let assemble_impls = match self.typing_mode() {
483                    TypingMode::Coherence => true,
484                    TypingMode::Typeck { .. }
485                    | TypingMode::PostTypeckUntilBorrowck { .. }
486                    | TypingMode::PostBorrowck { .. }
487                    | TypingMode::PostAnalysis
488                    | TypingMode::Codegen
489                    | TypingMode::ErasedNotCoherence(MayBeErased) => !candidates.iter().any(|c| {
490                        #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(ParamEnvSource::NonGlobal) |
        CandidateSource::AliasBound(_) => true,
    _ => false,
}matches!(
491                            c.source,
492                            CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)
493                                | CandidateSource::AliasBound(_)
494                        ) && has_no_inference_or_external_constraints(c.result)
495                    }),
496                };
497                if assemble_impls {
498                    self.assemble_impl_candidates(goal, &mut candidates)?;
499                    self.assemble_object_bound_candidates(goal, &mut candidates);
500                }
501            }
502            AssembleCandidatesFrom::EnvAndBounds => {
503                // This is somewhat inconsistent and may make #57893 slightly easier to exploit.
504                // However, it matches the behavior of the old solver. See
505                // `tests/ui/traits/next-solver/normalization-shadowing/use_object_if_empty_env.rs`.
506                if #[allow(non_exhaustive_omitted_patterns)] match normalized_self_ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(normalized_self_ty.kind(), ty::Dynamic(..))
507                    && !candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.source {
    CandidateSource::ParamEnv(_) => true,
    _ => false,
}matches!(c.source, CandidateSource::ParamEnv(_)))
508                {
509                    self.assemble_object_bound_candidates(goal, &mut candidates);
510                }
511            }
512        }
513
514        Ok((candidates, failed_candidate_info))
515    }
516
517    pub(super) fn forced_ambiguity(
518        &mut self,
519        maybe: MaybeInfo,
520    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
521        // This may fail if `try_evaluate_added_goals` overflows because it
522        // fails to reach a fixpoint but ends up getting an error after
523        // running for some additional step.
524        //
525        // FIXME(@lcnr): While I believe an error here to be possible, we
526        // currently don't have any test which actually triggers it. @lqd
527        // created a minimization for an ICE in typenum, but that one no
528        // longer fails here. cc trait-system-refactor-initiative#105.
529        let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
530        let certainty = Certainty::Maybe(maybe);
531        self.probe_trait_candidate(source)
532            .enter(|this| this.evaluate_added_goals_and_make_canonical_response(certainty))
533    }
534
535    #[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(535u32),
                                    ::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(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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