Skip to main content

rustc_next_trait_solver/solve/assembly/
mod.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let cx = self.cx();
            let goal_trait_ref = goal.predicate.trait_ref(cx);
            cx.for_each_relevant_impl(goal_trait_ref,
                |impl_def_id| -> Result<_, _>
                    {
                        match G::consider_impl_candidate(self, goal, goal_trait_ref,
                                        impl_def_id,
                                        |ecx|
                                            {
                                                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
                                            }).map_err_to_rerun()? {
                            Ok(candidate) => candidates.push(candidate),
                            Err(NoSolution) => {}
                        }
                        Ok(())
                    })
        }
    }
}#[instrument(level = "trace", skip_all)]
548    fn assemble_impl_candidates<G: GoalKind<D>>(
549        &mut self,
550        goal: Goal<I, G>,
551        candidates: &mut Vec<Candidate<I>>,
552    ) -> Result<(), RerunNonErased> {
553        let cx = self.cx();
554        let goal_trait_ref = goal.predicate.trait_ref(cx);
555        cx.for_each_relevant_impl(goal_trait_ref, |impl_def_id| -> Result<_, _> {
556            match G::consider_impl_candidate(self, goal, goal_trait_ref, impl_def_id, |ecx| {
557                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
558            })
559            .map_err_to_rerun()?
560            {
561                Ok(candidate) => candidates.push(candidate),
562                Err(NoSolution) => {}
563            }
564
565            Ok(())
566        })
567    }
568
569    {}
#[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("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(569u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let cx = self.cx();
            let trait_def_id = goal.predicate.trait_def_id(cx);
            if self.typing_mode().is_reflection() { return Ok(()); }
            let result =
                if let ty::Error(guar) = goal.predicate.self_ty().kind() {
                    G::consider_error_guaranteed_candidate(self, goal, guar)
                } else if cx.trait_is_auto(trait_def_id) {
                    G::consider_auto_trait_candidate(self, goal)
                } else if cx.trait_is_alias(trait_def_id) {
                    G::consider_trait_alias_candidate(self, goal)
                } else {
                    match cx.as_trait_lang_item(trait_def_id) {
                        Some(SolverTraitLangItem::Sized) => {
                            G::consider_builtin_sizedness_candidates(self, goal,
                                SizedTraitKind::Sized)
                        }
                        Some(SolverTraitLangItem::MetaSized) => {
                            G::consider_builtin_sizedness_candidates(self, goal,
                                SizedTraitKind::MetaSized)
                        }
                        Some(SolverTraitLangItem::PointeeSized) => {
                            {
                                ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                        format_args!("`PointeeSized` is removed during lowering")));
                            };
                        }
                        Some(SolverTraitLangItem::Copy | SolverTraitLangItem::Clone
                            | SolverTraitLangItem::TrivialClone) =>
                            G::consider_builtin_copy_clone_candidate(self, goal),
                        Some(SolverTraitLangItem::Fn) => {
                            G::consider_builtin_fn_trait_candidates(self, goal,
                                ty::ClosureKind::Fn)
                        }
                        Some(SolverTraitLangItem::FnMut) => {
                            G::consider_builtin_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnMut)
                        }
                        Some(SolverTraitLangItem::FnOnce) => {
                            G::consider_builtin_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnOnce)
                        }
                        Some(SolverTraitLangItem::AsyncFn) => {
                            G::consider_builtin_async_fn_trait_candidates(self, goal,
                                ty::ClosureKind::Fn)
                        }
                        Some(SolverTraitLangItem::AsyncFnMut) => {
                            G::consider_builtin_async_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnMut)
                        }
                        Some(SolverTraitLangItem::AsyncFnOnce) => {
                            G::consider_builtin_async_fn_trait_candidates(self, goal,
                                ty::ClosureKind::FnOnce)
                        }
                        Some(SolverTraitLangItem::FnPtrTrait) => {
                            G::consider_builtin_fn_ptr_trait_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::AsyncFnKindHelper) => {
                            G::consider_builtin_async_fn_kind_helper_candidate(self,
                                goal)
                        }
                        Some(SolverTraitLangItem::Tuple) =>
                            G::consider_builtin_tuple_candidate(self, goal),
                        Some(SolverTraitLangItem::PointeeTrait) => {
                            G::consider_builtin_pointee_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Future) => {
                            G::consider_builtin_future_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Iterator) => {
                            G::consider_builtin_iterator_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::FusedIterator) => {
                            G::consider_builtin_fused_iterator_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::AsyncIterator) => {
                            G::consider_builtin_async_iterator_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Coroutine) => {
                            G::consider_builtin_coroutine_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::DiscriminantKind) => {
                            G::consider_builtin_discriminant_kind_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Destruct) => {
                            G::consider_builtin_destruct_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::TransmuteTrait) => {
                            G::consider_builtin_transmute_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
                            G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self,
                                goal)
                        }
                        Some(SolverTraitLangItem::TryAsDyn) => {
                            G::consider_builtin_try_as_dyn_candidate(self, goal)
                        }
                        Some(SolverTraitLangItem::Field) =>
                            G::consider_builtin_field_candidate(self, goal),
                        _ => Err(NoSolution.into()),
                    }
                };
            candidates.extend(result);
            if cx.is_trait_lang_item(trait_def_id,
                    SolverTraitLangItem::Unsize) {
                candidates.extend(G::consider_structural_builtin_unsize_candidates(self,
                            goal)?);
            }
            Ok(())
        }
    }
}#[instrument(level = "trace", skip_all)]
570    fn assemble_builtin_impl_candidates<G: GoalKind<D>>(
571        &mut self,
572        goal: Goal<I, G>,
573        candidates: &mut Vec<Candidate<I>>,
574    ) -> Result<(), RerunNonErased> {
575        let cx = self.cx();
576        let trait_def_id = goal.predicate.trait_def_id(cx);
577
578        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
579        // of trying to handle these manually, we just reject all builtin impls in reflection
580        // mode. We can probably lift this restriction for specific cases, but this is safer.
581        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
582        if self.typing_mode().is_reflection() {
583            return Ok(());
584        }
585
586        // N.B. When assembling built-in candidates for lang items that are also
587        // `auto` traits, then the auto trait candidate that is assembled in
588        // `consider_auto_trait_candidate` MUST be disqualified to remain sound.
589        //
590        // Instead of adding the logic here, it's a better idea to add it in
591        // `EvalCtxt::disqualify_auto_trait_candidate_due_to_possible_impl` in
592        // `solve::trait_goals` instead.
593        let result = if let ty::Error(guar) = goal.predicate.self_ty().kind() {
594            G::consider_error_guaranteed_candidate(self, goal, guar)
595        } else if cx.trait_is_auto(trait_def_id) {
596            G::consider_auto_trait_candidate(self, goal)
597        } else if cx.trait_is_alias(trait_def_id) {
598            G::consider_trait_alias_candidate(self, goal)
599        } else {
600            match cx.as_trait_lang_item(trait_def_id) {
601                Some(SolverTraitLangItem::Sized) => {
602                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::Sized)
603                }
604                Some(SolverTraitLangItem::MetaSized) => {
605                    G::consider_builtin_sizedness_candidates(self, goal, SizedTraitKind::MetaSized)
606                }
607                Some(SolverTraitLangItem::PointeeSized) => {
608                    unreachable!("`PointeeSized` is removed during lowering");
609                }
610                Some(
611                    SolverTraitLangItem::Copy
612                    | SolverTraitLangItem::Clone
613                    | SolverTraitLangItem::TrivialClone,
614                ) => G::consider_builtin_copy_clone_candidate(self, goal),
615                Some(SolverTraitLangItem::Fn) => {
616                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
617                }
618                Some(SolverTraitLangItem::FnMut) => {
619                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnMut)
620                }
621                Some(SolverTraitLangItem::FnOnce) => {
622                    G::consider_builtin_fn_trait_candidates(self, goal, ty::ClosureKind::FnOnce)
623                }
624                Some(SolverTraitLangItem::AsyncFn) => {
625                    G::consider_builtin_async_fn_trait_candidates(self, goal, ty::ClosureKind::Fn)
626                }
627                Some(SolverTraitLangItem::AsyncFnMut) => {
628                    G::consider_builtin_async_fn_trait_candidates(
629                        self,
630                        goal,
631                        ty::ClosureKind::FnMut,
632                    )
633                }
634                Some(SolverTraitLangItem::AsyncFnOnce) => {
635                    G::consider_builtin_async_fn_trait_candidates(
636                        self,
637                        goal,
638                        ty::ClosureKind::FnOnce,
639                    )
640                }
641                Some(SolverTraitLangItem::FnPtrTrait) => {
642                    G::consider_builtin_fn_ptr_trait_candidate(self, goal)
643                }
644                Some(SolverTraitLangItem::AsyncFnKindHelper) => {
645                    G::consider_builtin_async_fn_kind_helper_candidate(self, goal)
646                }
647                Some(SolverTraitLangItem::Tuple) => G::consider_builtin_tuple_candidate(self, goal),
648                Some(SolverTraitLangItem::PointeeTrait) => {
649                    G::consider_builtin_pointee_candidate(self, goal)
650                }
651                Some(SolverTraitLangItem::Future) => {
652                    G::consider_builtin_future_candidate(self, goal)
653                }
654                Some(SolverTraitLangItem::Iterator) => {
655                    G::consider_builtin_iterator_candidate(self, goal)
656                }
657                Some(SolverTraitLangItem::FusedIterator) => {
658                    G::consider_builtin_fused_iterator_candidate(self, goal)
659                }
660                Some(SolverTraitLangItem::AsyncIterator) => {
661                    G::consider_builtin_async_iterator_candidate(self, goal)
662                }
663                Some(SolverTraitLangItem::Coroutine) => {
664                    G::consider_builtin_coroutine_candidate(self, goal)
665                }
666                Some(SolverTraitLangItem::DiscriminantKind) => {
667                    G::consider_builtin_discriminant_kind_candidate(self, goal)
668                }
669                Some(SolverTraitLangItem::Destruct) => {
670                    G::consider_builtin_destruct_candidate(self, goal)
671                }
672                Some(SolverTraitLangItem::TransmuteTrait) => {
673                    G::consider_builtin_transmute_candidate(self, goal)
674                }
675                Some(SolverTraitLangItem::BikeshedGuaranteedNoDrop) => {
676                    G::consider_builtin_bikeshed_guaranteed_no_drop_candidate(self, goal)
677                }
678                Some(SolverTraitLangItem::TryAsDyn) => {
679                    G::consider_builtin_try_as_dyn_candidate(self, goal)
680                }
681                Some(SolverTraitLangItem::Field) => G::consider_builtin_field_candidate(self, goal),
682                _ => Err(NoSolution.into()),
683            }
684        };
685
686        candidates.extend(result);
687
688        // There may be multiple unsize candidates for a trait with several supertraits:
689        // `trait Foo: Bar<A> + Bar<B>` and `dyn Foo: Unsize<dyn Bar<_>>`
690        if cx.is_trait_lang_item(trait_def_id, SolverTraitLangItem::Unsize) {
691            candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)?);
692        }
693
694        Ok(())
695    }
696
697    {}
#[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("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(697u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            for assumption in goal.param_env.caller_bounds() {
                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)]
698    fn assemble_param_env_candidates<G: GoalKind<D>>(
699        &mut self,
700        goal: Goal<I, G>,
701        candidates: &mut Vec<Candidate<I>>,
702        failed_candidate_info: &mut FailedCandidateInfo,
703    ) -> Result<(), RerunNonErased> {
704        for assumption in goal.param_env.caller_bounds() {
705            match G::probe_and_consider_param_env_candidate(self, goal, assumption)? {
706                Ok(candidate) => candidates.push(candidate),
707                Err(head_usages) => {
708                    failed_candidate_info.param_env_head_usages.merge_usages(head_usages)
709                }
710            }
711        }
712
713        Ok(())
714    }
715
716    {}
#[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("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(716u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res =
                self.probe(|_|
                            ProbeKind::NormalizedSelfTyAssembly).enter(|ecx|
                        {
                            ecx.assemble_alias_bound_candidates_recur(goal.predicate.self_ty(),
                                    goal, candidates, AliasBoundKind::SelfBounds)?;
                            Ok(())
                        });
            match res {
                Ok(_) => Ok(()),
                Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
                Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
                    ::core::panicking::panic("internal error: entered unreachable code")
                }
            }
        }
    }
}#[instrument(level = "trace", skip_all)]
717    fn assemble_alias_bound_candidates<G: GoalKind<D>>(
718        &mut self,
719        goal: Goal<I, G>,
720        candidates: &mut Vec<Candidate<I>>,
721    ) -> Result<(), RerunNonErased> {
722        let res = self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
723            ecx.assemble_alias_bound_candidates_recur(
724                goal.predicate.self_ty(),
725                goal,
726                candidates,
727                AliasBoundKind::SelfBounds,
728            )?;
729            Ok(())
730        });
731
732        // always returns Ok
733        match res {
734            Ok(_) => Ok(()),
735            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
736            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => {
737                unreachable!()
738            }
739        }
740    }
741
742    /// For some deeply nested `<T>::A::B::C::D` rigid associated type,
743    /// we should explore the item bounds for all levels, since the
744    /// `associated_type_bounds` feature means that a parent associated
745    /// type may carry bounds for a nested associated type.
746    ///
747    /// If we have a projection, check that its self type is a rigid projection.
748    /// If so, continue searching by recursively calling after normalization.
749    // FIXME: This may recurse infinitely, but I can't seem to trigger it without
750    // hitting another overflow error something. Add a depth parameter needed later.
751    fn assemble_alias_bound_candidates_recur<G: GoalKind<D>>(
752        &mut self,
753        self_ty: I::Ty,
754        goal: Goal<I, G>,
755        candidates: &mut Vec<Candidate<I>>,
756        consider_self_bounds: AliasBoundKind,
757    ) -> Result<(), RerunNonErased> {
758        let (alias_ty, def_id) = match self_ty.kind() {
759            ty::Bool
760            | ty::Char
761            | ty::Int(_)
762            | ty::Uint(_)
763            | ty::Float(_)
764            | ty::Adt(_, _)
765            | ty::Foreign(_)
766            | ty::Str
767            | ty::Array(_, _)
768            | ty::Pat(_, _)
769            | ty::Slice(_)
770            | ty::RawPtr(_, _)
771            | ty::Ref(_, _, _)
772            | ty::FnDef(_, _)
773            | ty::FnPtr(..)
774            | ty::UnsafeBinder(_)
775            | ty::Dynamic(..)
776            | ty::Closure(..)
777            | ty::CoroutineClosure(..)
778            | ty::Coroutine(..)
779            | ty::CoroutineWitness(..)
780            | ty::Never
781            | ty::Tuple(_)
782            | ty::Param(_)
783            | ty::Placeholder(..)
784            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
785            | ty::Error(_) => return Ok(()),
786            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => {
787                {
    ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
            goal));
}panic!("unexpected self type for `{goal:?}`")
788            }
789
790            ty::Infer(ty::TyVar(_)) => {
791                // If we hit infer when normalizing the self type of an alias,
792                // then bail with ambiguity. We should never encounter this on
793                // the *first* iteration of this recursive function.
794                if let Ok(result) =
795                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
796                {
797                    candidates.push(Candidate {
798                        source: CandidateSource::AliasBound(consider_self_bounds),
799                        result,
800                        head_usages: CandidateHeadUsages::default(),
801                    });
802                }
803                return Ok(());
804            }
805
806            ty::Alias(
807                ty::IsRigid::Yes,
808                alias_ty @ AliasTy { kind: ty::Projection { def_id }, .. },
809            ) => (alias_ty, def_id.into()),
810
811            ty::Alias(ty::IsRigid::Yes, alias_ty @ AliasTy { kind: ty::Opaque { def_id }, .. }) => {
812                (alias_ty, def_id.into())
813            }
814
815            ty::Alias(ty::IsRigid::No, _) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("non-rigid self type: {0:?}", self_ty)));
}unreachable!("non-rigid self type: {self_ty:?}"),
816
817            ty::Alias(
818                ty::IsRigid::Yes,
819                AliasTy { kind: ty::Inherent { .. } | ty::Free { .. }, .. },
820            ) => {
821                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"));
822                return Ok(());
823            }
824        };
825
826        match consider_self_bounds {
827            AliasBoundKind::SelfBounds => {
828                for assumption in self
829                    .cx()
830                    .item_self_bounds(def_id)
831                    .iter_instantiated(self.cx(), alias_ty.args)
832                    .map(Unnormalized::skip_norm_wip)
833                {
834                    candidates.extend(G::probe_and_consider_implied_clause(
835                        self,
836                        CandidateSource::AliasBound(consider_self_bounds),
837                        goal,
838                        assumption,
839                        [],
840                    ));
841                }
842            }
843            AliasBoundKind::NonSelfBounds => {
844                for assumption in self
845                    .cx()
846                    .item_non_self_bounds(def_id)
847                    .iter_instantiated(self.cx(), alias_ty.args)
848                    .map(Unnormalized::skip_norm_wip)
849                {
850                    candidates.extend(G::probe_and_consider_implied_clause(
851                        self,
852                        CandidateSource::AliasBound(consider_self_bounds),
853                        goal,
854                        assumption,
855                        [],
856                    ));
857                }
858            }
859        }
860
861        candidates.extend(G::consider_additional_alias_assumptions(self, goal, alias_ty));
862
863        let Some(projection_ty) = alias_ty.try_to_projection() else {
864            return Ok(());
865        };
866
867        // Recurse on the self type of the projection.
868        match self.structurally_normalize_ty(goal.param_env, projection_ty.projection_self_ty()) {
869            Ok(next_self_ty) => self.assemble_alias_bound_candidates_recur(
870                next_self_ty,
871                goal,
872                candidates,
873                AliasBoundKind::NonSelfBounds,
874            ),
875            Err(NoSolutionOrRerunNonErased::NoSolution(NoSolution)) => Ok(()),
876            Err(NoSolutionOrRerunNonErased::RerunNonErased(e)) => Err(e),
877        }
878    }
879
880    {}
#[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("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(880u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let cx = self.cx();
            if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
                return;
            }
            if self.typing_mode().is_reflection() { return; }
            let self_ty = goal.predicate.self_ty();
            let bounds =
                match self_ty.kind() {
                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) |
                        ty::Float(_) | ty::Adt(_, _) | ty::Foreign(_) | ty::Str |
                        ty::Array(_, _) | ty::Pat(_, _) | ty::Slice(_) |
                        ty::RawPtr(_, _) | ty::Ref(_, _, _) | ty::FnDef(_, _) |
                        ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::Alias(..) |
                        ty::Closure(..) | ty::CoroutineClosure(..) |
                        ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Never |
                        ty::Tuple(_) | ty::Param(_) | ty::Placeholder(..) |
                        ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Error(_) =>
                        return,
                    ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_)
                        | ty::FreshFloatTy(_)) | ty::Bound(..) => {
                        ::core::panicking::panic_fmt(format_args!("unexpected self type for `{0:?}`",
                                goal));
                    }
                    ty::Dynamic(bounds, ..) => bounds,
                };
            if bounds.principal_def_id().is_some_and(|def_id|
                        !cx.trait_is_dyn_compatible(def_id)) {
                return;
            }
            for bound in bounds.iter() {
                match bound.skip_binder() {
                    ty::ExistentialPredicate::Trait(_) => {}
                    ty::ExistentialPredicate::Projection(_) |
                        ty::ExistentialPredicate::AutoTrait(_) => {
                        candidates.extend(G::probe_and_consider_object_bound_candidate(self,
                                CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal,
                                bound.with_self_ty(cx, self_ty)));
                    }
                }
            }
            if let Some(principal) = bounds.principal() {
                let principal_trait_ref = principal.with_self_ty(cx, self_ty);
                for (idx, assumption) in
                    elaborate::supertraits(cx, principal_trait_ref).enumerate()
                    {
                    candidates.extend(G::probe_and_consider_object_bound_candidate(self,
                            CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
                            goal, assumption.upcast(cx)));
                }
            }
        }
    }
}#[instrument(level = "trace", skip_all)]
881    fn assemble_object_bound_candidates<G: GoalKind<D>>(
882        &mut self,
883        goal: Goal<I, G>,
884        candidates: &mut Vec<Candidate<I>>,
885    ) {
886        let cx = self.cx();
887        if cx.is_sizedness_trait(goal.predicate.trait_def_id(cx)) {
888            // `dyn MetaSized` is valid, but should get its `MetaSized` impl from
889            // being `dyn` (SizedCandidate), not from the object candidate.
890            return;
891        }
892
893        // Builtin impls regularly are not `is_fully_generic_for_reflection`, so instead
894        // of trying to handle these manually, we just reject all builtin impls in reflection
895        // mode. We can probably lift this restriction for specific cases, but this is safer.
896        // See `try_as_dyn_builtin_impl` for how just allowing all builtin impls is unsound.
897        if self.typing_mode().is_reflection() {
898            return;
899        }
900
901        let self_ty = goal.predicate.self_ty();
902        let bounds = match self_ty.kind() {
903            ty::Bool
904            | ty::Char
905            | ty::Int(_)
906            | ty::Uint(_)
907            | ty::Float(_)
908            | ty::Adt(_, _)
909            | ty::Foreign(_)
910            | ty::Str
911            | ty::Array(_, _)
912            | ty::Pat(_, _)
913            | ty::Slice(_)
914            | ty::RawPtr(_, _)
915            | ty::Ref(_, _, _)
916            | ty::FnDef(_, _)
917            | ty::FnPtr(..)
918            | ty::UnsafeBinder(_)
919            | ty::Alias(..)
920            | ty::Closure(..)
921            | ty::CoroutineClosure(..)
922            | ty::Coroutine(..)
923            | ty::CoroutineWitness(..)
924            | ty::Never
925            | ty::Tuple(_)
926            | ty::Param(_)
927            | ty::Placeholder(..)
928            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
929            | ty::Error(_) => return,
930            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
931            | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"),
932            ty::Dynamic(bounds, ..) => bounds,
933        };
934
935        // Do not consider built-in object impls for dyn-incompatible types.
936        if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_dyn_compatible(def_id)) {
937            return;
938        }
939
940        // Consider all of the auto-trait and projection bounds, which don't
941        // need to be recorded as a `BuiltinImplSource::Object` since they don't
942        // really have a vtable base...
943        for bound in bounds.iter() {
944            match bound.skip_binder() {
945                ty::ExistentialPredicate::Trait(_) => {
946                    // Skip principal
947                }
948                ty::ExistentialPredicate::Projection(_)
949                | ty::ExistentialPredicate::AutoTrait(_) => {
950                    candidates.extend(G::probe_and_consider_object_bound_candidate(
951                        self,
952                        CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
953                        goal,
954                        bound.with_self_ty(cx, self_ty),
955                    ));
956                }
957            }
958        }
959
960        // FIXME: We only need to do *any* of this if we're considering a trait goal,
961        // since we don't need to look at any supertrait or anything if we are doing
962        // a projection goal.
963        if let Some(principal) = bounds.principal() {
964            let principal_trait_ref = principal.with_self_ty(cx, self_ty);
965            for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
966                candidates.extend(G::probe_and_consider_object_bound_candidate(
967                    self,
968                    CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
969                    goal,
970                    assumption.upcast(cx),
971                ));
972            }
973        }
974    }
975
976    /// In coherence we have to not only care about all impls we know about, but
977    /// also consider impls which may get added in a downstream or sibling crate
978    /// or which an upstream impl may add in a minor release.
979    ///
980    /// To do so we return a single ambiguous candidate in case such an unknown
981    /// impl could apply to the current goal.
982    {}
#[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("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(982u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Candidate<I>, NoSolutionOrRerunNonErased> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx|
                    {
                        let cx = ecx.cx();
                        let trait_ref = goal.predicate.trait_ref(cx);
                        if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
                            Err(NoSolution.into())
                        } else {
                            let predicate: I::Predicate = trait_ref.upcast(cx);
                            ecx.add_goals(GoalSource::Misc,
                                    elaborate::elaborate(cx,
                                                [predicate]).skip(1).map(|predicate|
                                            goal.with(cx, predicate)))?;
                            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                        }
                    })
        }
    }
}#[instrument(level = "trace", skip_all)]
983    fn consider_coherence_unknowable_candidate<G: GoalKind<D>>(
984        &mut self,
985        goal: Goal<I, G>,
986    ) -> Result<Candidate<I>, NoSolutionOrRerunNonErased> {
987        self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter(|ecx| {
988            let cx = ecx.cx();
989            let trait_ref = goal.predicate.trait_ref(cx);
990            if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? {
991                Err(NoSolution.into())
992            } else {
993                // While the trait bound itself may be unknowable, we may be able to
994                // prove that a super trait is not implemented. For this, we recursively
995                // prove the super trait bounds of the current goal.
996                //
997                // We skip the goal itself as that one would cycle.
998                let predicate: I::Predicate = trait_ref.upcast(cx);
999                ecx.add_goals(
1000                    GoalSource::Misc,
1001                    elaborate::elaborate(cx, [predicate])
1002                        .skip(1)
1003                        .map(|predicate| goal.with(cx, predicate)),
1004                )?;
1005                ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1006            }
1007        })
1008    }
1009}
1010
1011pub(super) enum AllowInferenceConstraints {
1012    Yes,
1013    No,
1014}
1015
1016impl<D, I> EvalCtxt<'_, D>
1017where
1018    D: SolverDelegate<Interner = I>,
1019    I: Interner,
1020{
1021    /// Check whether we can ignore impl candidates due to specialization.
1022    ///
1023    /// This is only necessary for `feature(specialization)` and seems quite ugly.
1024    pub(super) fn filter_specialized_impls(
1025        &mut self,
1026        allow_inference_constraints: AllowInferenceConstraints,
1027        candidates: &mut Vec<Candidate<I>>,
1028    ) {
1029        if self.typing_mode().is_coherence() {
1030            return;
1031        }
1032
1033        let mut i = 0;
1034        'outer: while i < candidates.len() {
1035            let CandidateSource::Impl(victim_def_id) = candidates[i].source else {
1036                i += 1;
1037                continue;
1038            };
1039
1040            for (j, c) in candidates.iter().enumerate() {
1041                if i == j {
1042                    continue;
1043                }
1044
1045                let CandidateSource::Impl(other_def_id) = c.source else {
1046                    continue;
1047                };
1048
1049                // See if we can toss out `victim` based on specialization.
1050                //
1051                // While this requires us to know *for sure* that the `lhs` impl applies
1052                // we still use modulo regions here. This is fine as specialization currently
1053                // assumes that specializing impls have to be always applicable, meaning that
1054                // the only allowed region constraints may be constraints also present on the default impl.
1055                if #[allow(non_exhaustive_omitted_patterns)] match allow_inference_constraints {
    AllowInferenceConstraints::Yes => true,
    _ => false,
}matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
1056                    || has_only_region_constraints(c.result)
1057                {
1058                    if self.cx().impl_specializes(other_def_id, victim_def_id) {
1059                        candidates.remove(i);
1060                        continue 'outer;
1061                    }
1062                }
1063            }
1064
1065            i += 1;
1066        }
1067    }
1068
1069    /// If the self type is the hidden type of an opaque, try to assemble
1070    /// candidates for it by consider its item bounds and by using blanket
1071    /// impls. This is used to incompletely guide type inference when handling
1072    /// non-defining uses in the defining scope.
1073    ///
1074    /// We otherwise just fail fail with ambiguity. Even if we're using an
1075    /// opaque type item bound or a blank impls, we still force its certainty
1076    /// to be `Maybe` so that we properly prove this goal later.
1077    ///
1078    /// See <https://github.com/rust-lang/trait-system-refactor-initiative/issues/182>
1079    /// for why this is necessary.
1080    {}
#[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("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1080u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("goal")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("goal");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidates")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidates");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&goal)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), RerunNonErased> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let self_ty = goal.predicate.self_ty();
            let opaque_types =
                match self.typing_mode() {
                    TypingMode::Typeck { .. } =>
                        self.opaques_with_sub_unified_hidden_type(self_ty),
                    TypingMode::Coherence |
                        TypingMode::PostTypeckUntilBorrowck { .. } |
                        TypingMode::PostBorrowck { .. } | TypingMode::PostAnalysis |
                        TypingMode::Reflection | TypingMode::Codegen =>
                        ::alloc::vec::Vec::new(),
                    TypingMode::ErasedNotCoherence(MayBeErased) => {
                        self.opaque_accesses.rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
                        Vec::new()
                    }
                };
            if opaque_types.is_empty() {
                candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
                return Ok(());
            }
            for &opaque_ty in &opaque_types {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1110",
                                        "rustc_next_trait_solver::solve::assembly",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1110u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("self ty is sub unified with {0:?}",
                                                                    opaque_ty) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                struct ReplaceOpaque<I: Interner> {
                    cx: I,
                    opaque_ty: ty::OpaqueAliasTy<I>,
                    self_ty: I::Ty,
                }
                impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
                    fn cx(&self) -> I { self.cx }
                    fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
                        if let ty::Alias(is_rigid, alias_ty) = ty.kind() &&
                                let Some(opaque_ty) = alias_ty.try_to_opaque() {
                            if opaque_ty == self.opaque_ty {
                                if true {
                                    {
                                        match (&is_rigid, &ty::IsRigid::No) {
                                            (left_val, right_val) => {
                                                if !(*left_val == *right_val) {
                                                    let kind = ::core::panicking::AssertKind::Eq;
                                                    ::core::panicking::assert_failed(kind, &*left_val,
                                                        &*right_val, ::core::option::Option::None);
                                                }
                                            }
                                        }
                                    };
                                };
                                return self.self_ty;
                            }
                        }
                        ty.super_fold_with(self)
                    }
                }
                for item_bound in
                    self.cx().item_self_bounds(opaque_ty.kind.into()).iter_instantiated(self.cx(),
                            opaque_ty.args).map(Unnormalized::skip_norm_wip) {
                    let assumption =
                        item_bound.fold_with(&mut ReplaceOpaque {
                                    cx: self.cx(),
                                    opaque_ty,
                                    self_ty,
                                });
                    candidates.extend(G::probe_and_match_goal_against_assumption(self,
                            CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
                            goal, assumption,
                            |ecx|
                                {
                                    ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                                }));
                }
            }
            if assemble_from.should_assemble_impl_candidates() {
                let cx = self.cx();
                let goal_trait_ref = goal.predicate.trait_ref(cx);
                cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx),
                        |impl_def_id|
                            {
                                match G::consider_impl_candidate(self, goal, goal_trait_ref,
                                                impl_def_id,
                                                |ecx|
                                                    {
                                                        if ecx.shallow_resolve(self_ty).is_ty_var() {
                                                            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
                                                        } 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))]
1081    fn try_assemble_bounds_via_registered_opaques<G: GoalKind<D>>(
1082        &mut self,
1083        goal: Goal<I, G>,
1084        assemble_from: AssembleCandidatesFrom,
1085        candidates: &mut Vec<Candidate<I>>,
1086    ) -> Result<(), RerunNonErased> {
1087        let self_ty = goal.predicate.self_ty();
1088        // We only use this hack during HIR typeck.
1089        let opaque_types = match self.typing_mode() {
1090            TypingMode::Typeck { .. } => self.opaques_with_sub_unified_hidden_type(self_ty),
1091            TypingMode::Coherence
1092            | TypingMode::PostTypeckUntilBorrowck { .. }
1093            | TypingMode::PostBorrowck { .. }
1094            | TypingMode::PostAnalysis
1095            | TypingMode::Reflection
1096            | TypingMode::Codegen => vec![],
1097            TypingMode::ErasedNotCoherence(MayBeErased) => {
1098                self.opaque_accesses
1099                    .rerun_if_any_opaque_has_infer_as_hidden_type(RerunReason::SelfTyInfer)?;
1100                Vec::new()
1101            }
1102        };
1103
1104        if opaque_types.is_empty() {
1105            candidates.extend(self.forced_ambiguity(MaybeInfo::AMBIGUOUS));
1106            return Ok(());
1107        }
1108
1109        for &opaque_ty in &opaque_types {
1110            debug!("self ty is sub unified with {opaque_ty:?}");
1111
1112            struct ReplaceOpaque<I: Interner> {
1113                cx: I,
1114                opaque_ty: ty::OpaqueAliasTy<I>,
1115                self_ty: I::Ty,
1116            }
1117            impl<I: Interner> TypeFolder<I> for ReplaceOpaque<I> {
1118                fn cx(&self) -> I {
1119                    self.cx
1120                }
1121                fn fold_ty(&mut self, ty: I::Ty) -> I::Ty {
1122                    if let ty::Alias(is_rigid, alias_ty) = ty.kind()
1123                        && let Some(opaque_ty) = alias_ty.try_to_opaque()
1124                    {
1125                        if opaque_ty == self.opaque_ty {
1126                            debug_assert_eq!(is_rigid, ty::IsRigid::No);
1127                            return self.self_ty;
1128                        }
1129                    }
1130                    ty.super_fold_with(self)
1131                }
1132            }
1133
1134            // We look at all item-bounds of the opaque, replacing the
1135            // opaque with the current self type before considering
1136            // them as a candidate. Imagine we've got `?x: Trait<?y>`
1137            // and `?x` has been sub-unified with the hidden type of
1138            // `impl Trait<u32>`, We take the item bound `opaque: Trait<u32>`
1139            // and replace all occurrences of `opaque` with `?x`. This results
1140            // in a `?x: Trait<u32>` alias-bound candidate.
1141            for item_bound in self
1142                .cx()
1143                .item_self_bounds(opaque_ty.kind.into())
1144                .iter_instantiated(self.cx(), opaque_ty.args)
1145                .map(Unnormalized::skip_norm_wip)
1146            {
1147                let assumption =
1148                    item_bound.fold_with(&mut ReplaceOpaque { cx: self.cx(), opaque_ty, self_ty });
1149                candidates.extend(G::probe_and_match_goal_against_assumption(
1150                    self,
1151                    CandidateSource::AliasBound(AliasBoundKind::SelfBounds),
1152                    goal,
1153                    assumption,
1154                    |ecx| {
1155                        // We want to reprove this goal once we've inferred the
1156                        // hidden type, so we force the certainty to `Maybe`.
1157                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1158                    },
1159                ));
1160            }
1161        }
1162
1163        // If the self type is sub unified with any opaque type, we also look at blanket
1164        // impls for it.
1165        //
1166        // See tests/ui/impl-trait/non-defining-uses/use-blanket-impl.rs for an example.
1167        if assemble_from.should_assemble_impl_candidates() {
1168            let cx = self.cx();
1169            let goal_trait_ref = goal.predicate.trait_ref(cx);
1170
1171            cx.for_each_blanket_impl(goal.predicate.trait_def_id(cx), |impl_def_id| {
1172                match G::consider_impl_candidate(self, goal, goal_trait_ref, impl_def_id, |ecx| {
1173                    if ecx.shallow_resolve(self_ty).is_ty_var() {
1174                        // We force the certainty of impl candidates to be `Maybe`.
1175                        ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
1176                    } else {
1177                        // We don't want to use impls if they constrain the opaque.
1178                        //
1179                        // FIXME(trait-system-refactor-initiative#229): This isn't
1180                        // perfect yet as it still allows us to incorrectly constrain
1181                        // other inference variables.
1182                        Err(NoSolution.into())
1183                    }
1184                })
1185                .map_err_to_rerun()?
1186                {
1187                    Ok(candidate) => candidates.push(candidate),
1188                    Err(NoSolution) => {}
1189                }
1190
1191                Ok(())
1192            })?;
1193        }
1194
1195        if candidates.is_empty() {
1196            let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
1197            let certainty = Certainty::Maybe(MaybeInfo {
1198                cause: MaybeCause::Ambiguity,
1199                opaque_types_jank: OpaqueTypesJank::ErrorIfRigidSelfTy,
1200                stalled_on_coroutines: StalledOnCoroutines::No,
1201            });
1202            candidates
1203                .extend(self.probe_trait_candidate(source).enter(|this| {
1204                    this.evaluate_added_goals_and_make_canonical_response(certainty)
1205                }));
1206        }
1207
1208        Ok(())
1209    }
1210
1211    /// Assemble and merge candidates for goals which are related to an underlying trait
1212    /// goal. Right now, this is normalizes-to and host effect goals.
1213    ///
1214    /// We sadly can't simply take all possible candidates for normalization goals
1215    /// and check whether they result in the same constraints. We want to make sure
1216    /// that trying to normalize an alias doesn't result in constraints which aren't
1217    /// otherwise required.
1218    ///
1219    /// Most notably, when proving a trait goal by via a where-bound, we should not
1220    /// normalize via impls which have stricter region constraints than the where-bound:
1221    ///
1222    /// ```rust
1223    /// trait Trait<'a> {
1224    ///     type Assoc;
1225    /// }
1226    ///
1227    /// impl<'a, T: 'a> Trait<'a> for T {
1228    ///     type Assoc = u32;
1229    /// }
1230    ///
1231    /// fn with_bound<'a, T: Trait<'a>>(_value: T::Assoc) {}
1232    /// ```
1233    ///
1234    /// The where-bound of `with_bound` doesn't specify the associated type, so we would
1235    /// only be able to normalize `<T as Trait<'a>>::Assoc` by using the impl. This impl
1236    /// adds a `T: 'a` bound however, which would result in a region error. Given that the
1237    /// user explicitly wrote that `T: Trait<'a>` holds, this is undesirable and we instead
1238    /// treat the alias as rigid.
1239    ///
1240    /// See trait-system-refactor-initiative#124 for more details.
1241    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::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_and_merge_candidates",
                                "rustc_next_trait_solver::solve::assembly",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                ::tracing_core::__macro_support::Option::Some(1241u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("proven_via")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("proven_via");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("goal")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("goal");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::Empty
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::Empty
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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:
                                QueryResultOrRerunNonErased<I> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let Some(proven_via) =
                            proven_via else {
                                return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand|
                                            cand.result);
                            };
                        match proven_via {
                            TraitGoalProvenVia::ParamEnv |
                                TraitGoalProvenVia::AliasBound => {
                                let (mut candidates, _) =
                                    self.assemble_and_evaluate_candidates(goal,
                                            AssembleCandidatesFrom::EnvAndBounds)?;
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1275",
                                                        "rustc_next_trait_solver::solve::assembly",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1275u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                                                        ::tracing_core::field::FieldSet::new(&[{
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("candidates")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("candidates");
                                                                            NAME.as_str()
                                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                if candidates.is_empty() {
                                    return inject_normalize_to_rigid_candidate(self);
                                }
                                if let Some(result) =
                                        inject_forced_ambiguity_candidate(self) {
                                    return result;
                                }
                                if candidates.iter().any(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            }) {
                                    candidates.retain(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            });
                                }
                                if let Some((response, _)) =
                                        self.try_merge_candidates(&candidates) {
                                    Ok(response)
                                } else { self.flounder(&candidates).map_err(Into::into) }
                            }
                            TraitGoalProvenVia::Misc => {
                                let (mut candidates, _) =
                                    self.assemble_and_evaluate_candidates(goal,
                                            AssembleCandidatesFrom::All)?;
                                if candidates.iter().any(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            }) {
                                    candidates.retain(|c|
                                            #[allow(non_exhaustive_omitted_patterns)] match c.source {
                                                CandidateSource::ParamEnv(_) => true,
                                                _ => false,
                                            });
                                }
                                self.filter_specialized_impls(AllowInferenceConstraints::Yes,
                                    &mut candidates);
                                if let Some((response, _)) =
                                        self.try_merge_candidates(&candidates) {
                                    Ok(response)
                                } else { self.flounder(&candidates).map_err(Into::into) }
                            }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs:1241",
                        "rustc_next_trait_solver::solve::assembly",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/a36d05efab632d1ddf902b6a5c33b6d5d3b64131/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1241u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_next_trait_solver::solve::assembly"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip_all, fields(proven_via, goal), ret)]
1242    pub(super) fn assemble_and_merge_candidates<G: GoalKind<D>>(
1243        &mut self,
1244        proven_via: Option<TraitGoalProvenVia>,
1245        goal: Goal<I, G>,
1246        inject_forced_ambiguity_candidate: impl FnOnce(
1247            &mut EvalCtxt<'_, D>,
1248        ) -> Option<
1249            Result<CanonicalResponse<I>, NoSolutionOrRerunNonErased>,
1250        >,
1251        inject_normalize_to_rigid_candidate: impl FnOnce(
1252            &mut EvalCtxt<'_, D>,
1253        ) -> Result<
1254            CanonicalResponse<I>,
1255            NoSolutionOrRerunNonErased,
1256        >,
1257    ) -> QueryResultOrRerunNonErased<I> {
1258        let Some(proven_via) = proven_via else {
1259            // We don't care about overflow. If proving the trait goal overflowed, then
1260            // it's enough to report an overflow error for that, we don't also have to
1261            // overflow during normalization.
1262            //
1263            // We use `forced_ambiguity` here over `make_ambiguous_response_no_constraints`
1264            // because the former will also record a built-in candidate in the inspector.
1265            return self.forced_ambiguity(MaybeInfo::AMBIGUOUS).map(|cand| cand.result);
1266        };
1267
1268        match proven_via {
1269            TraitGoalProvenVia::ParamEnv | TraitGoalProvenVia::AliasBound => {
1270                // Even when a trait bound has been proven using a where-bound, we
1271                // still need to consider alias-bounds for normalization, see
1272                // `tests/ui/next-solver/alias-bound-shadowed-by-env.rs`.
1273                let (mut candidates, _) = self
1274                    .assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::EnvAndBounds)?;
1275                debug!(?candidates);
1276
1277                // If the trait goal has been proven by using the environment, we want to treat
1278                // aliases as rigid if there are no applicable projection bounds in the environment.
1279                if candidates.is_empty() {
1280                    return inject_normalize_to_rigid_candidate(self);
1281                }
1282
1283                // If we're normalizing an GAT, we bail if using a where-bound would constrain
1284                // its generic arguments.
1285                if let Some(result) = inject_forced_ambiguity_candidate(self) {
1286                    return result;
1287                }
1288
1289                // We still need to prefer where-bounds over alias-bounds however.
1290                // See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`.
1291                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1292                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1293                }
1294
1295                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1296                    Ok(response)
1297                } else {
1298                    self.flounder(&candidates).map_err(Into::into)
1299                }
1300            }
1301            TraitGoalProvenVia::Misc => {
1302                let (mut candidates, _) =
1303                    self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1304
1305                // Prefer "orphaned" param-env normalization predicates, which are used
1306                // (for example, and ideally only) when proving item bounds for an impl.
1307                if candidates.iter().any(|c| matches!(c.source, CandidateSource::ParamEnv(_))) {
1308                    candidates.retain(|c| matches!(c.source, CandidateSource::ParamEnv(_)));
1309                }
1310
1311                // We drop specialized impls to allow normalization via a final impl here. In case
1312                // the specializing impl has different inference constraints from the specialized
1313                // impl, proving the trait goal is already ambiguous, so we never get here. This
1314                // means we can just ignore inference constraints and don't have to special-case
1315                // constraining the normalized-to `term`.
1316                self.filter_specialized_impls(AllowInferenceConstraints::Yes, &mut candidates);
1317                if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1318                    Ok(response)
1319                } else {
1320                    self.flounder(&candidates).map_err(Into::into)
1321                }
1322            }
1323        }
1324    }
1325
1326    /// Compute whether a param-env assumption is global or non-global after normalizing it.
1327    ///
1328    /// This is necessary because, for example, given:
1329    ///
1330    /// ```ignore,rust
1331    /// where
1332    ///     T: Trait<Assoc = u32>,
1333    ///     i32: From<T::Assoc>,
1334    /// ```
1335    ///
1336    /// The `i32: From<T::Assoc>` bound is non-global before normalization, but is global after.
1337    /// Since the old trait solver normalized param-envs eagerly, we want to emulate this
1338    /// behavior lazily.
1339    fn characterize_param_env_assumption(
1340        &mut self,
1341        param_env: I::ParamEnv,
1342        assumption: I::Clause,
1343    ) -> Result<(CandidateSource<I>, Certainty), NoSolution> {
1344        // FIXME: This should be fixed, but it also requires changing the behavior
1345        // in the old solver which is currently relied on.
1346        if assumption.has_bound_vars() {
1347            return Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), Certainty::Yes));
1348        }
1349
1350        match assumption.visit_with(&mut FindParamInClause {
1351            ecx: self,
1352            param_env,
1353            universes: ::alloc::vec::Vec::new()vec![],
1354            recursion_depth: 0,
1355        }) {
1356            ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1357            ControlFlow::Break(Ok(certainty)) => {
1358                Ok((CandidateSource::ParamEnv(ParamEnvSource::NonGlobal), certainty))
1359            }
1360            ControlFlow::Continue(()) => {
1361                Ok((CandidateSource::ParamEnv(ParamEnvSource::Global), Certainty::Yes))
1362            }
1363        }
1364    }
1365}
1366
1367struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1368    ecx: &'a mut EvalCtxt<'b, D>,
1369    param_env: I::ParamEnv,
1370    universes: Vec<Option<ty::UniverseIndex>>,
1371    recursion_depth: usize,
1372}
1373
1374impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1375where
1376    D: SolverDelegate<Interner = I>,
1377    I: Interner,
1378{
1379    // - `Continue(())`: no generic parameter was found, the type is global
1380    // - `Break(Ok(Certainty::Yes))`: a generic parameter was found, the type is non-global
1381    // - `Break(Ok(Certainty::Maybe(_)))`: the recursion limit reached, assume that the type is non-global
1382    // - `Break(Err(NoSolution))`: normalization failed
1383    type Result = ControlFlow<Result<Certainty, NoSolution>>;
1384
1385    fn visit_binder<T: TypeVisitable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1386        self.universes.push(None);
1387        t.super_visit_with(self)?;
1388        self.universes.pop();
1389        ControlFlow::Continue(())
1390    }
1391
1392    fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1393        let ty = self.ecx.replace_bound_vars(ty, &mut self.universes);
1394        let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1395            return ControlFlow::Break(Err(NoSolution));
1396        };
1397
1398        match ty.kind() {
1399            ty::Placeholder(p) => {
1400                if p.universe() == ty::UniverseIndex::ROOT {
1401                    ControlFlow::Break(Ok(Certainty::Yes))
1402                } else {
1403                    ControlFlow::Continue(())
1404                }
1405            }
1406            ty::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1407            _ if ty.has_type_flags(
1408                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1409            ) =>
1410            {
1411                self.recursion_depth += 1;
1412                if self.recursion_depth > self.ecx.cx().recursion_limit() {
1413                    return ControlFlow::Break(Ok(Certainty::Maybe(MaybeInfo {
1414                        cause: MaybeCause::Overflow {
1415                            suggest_increasing_limit: true,
1416                            keep_constraints: false,
1417                        },
1418                        opaque_types_jank: OpaqueTypesJank::AllGood,
1419                        stalled_on_coroutines: StalledOnCoroutines::No,
1420                    })));
1421                }
1422                let result = ty.super_visit_with(self);
1423                self.recursion_depth -= 1;
1424                result
1425            }
1426            _ => ControlFlow::Continue(()),
1427        }
1428    }
1429
1430    fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1431        let ct = self.ecx.replace_bound_vars(ct, &mut self.universes);
1432        let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1433            return ControlFlow::Break(Err(NoSolution));
1434        };
1435
1436        match ct.kind() {
1437            ty::ConstKind::Placeholder(p) => {
1438                if p.universe() == ty::UniverseIndex::ROOT {
1439                    ControlFlow::Break(Ok(Certainty::Yes))
1440                } else {
1441                    ControlFlow::Continue(())
1442                }
1443            }
1444            ty::ConstKind::Infer(_) => ControlFlow::Break(Ok(Certainty::AMBIGUOUS)),
1445            _ if ct.has_type_flags(
1446                TypeFlags::HAS_PLACEHOLDER | TypeFlags::HAS_INFER | TypeFlags::HAS_ALIAS,
1447            ) =>
1448            {
1449                // FIXME(mgca): we should also check the recursion limit here
1450                ct.super_visit_with(self)
1451            }
1452            _ => ControlFlow::Continue(()),
1453        }
1454    }
1455
1456    fn visit_region(&mut self, r: Region<I>) -> Self::Result {
1457        match self.ecx.eager_resolve_region(r).kind() {
1458            ty::ReStatic | ty::ReError(_) | ty::ReBound(..) => ControlFlow::Continue(()),
1459            ty::RePlaceholder(p) => {
1460                if p.universe() == ty::UniverseIndex::ROOT {
1461                    ControlFlow::Break(Ok(Certainty::Yes))
1462                } else {
1463                    ControlFlow::Continue(())
1464                }
1465            }
1466            ty::ReVar(_) => ControlFlow::Break(Ok(Certainty::Yes)),
1467            ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
1468                {
    ::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")
1469            }
1470        }
1471    }
1472}