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