Skip to main content

rustc_trait_selection/solve/
delegate.rs

1use std::collections::hash_map::Entry;
2use std::fmt::Debug;
3use std::ops::{ControlFlow, Deref};
4
5use rustc_attr_ir::lang_items::LangItem;
6use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_hir::CRATE_HIR_ID;
8use rustc_hir::def::Namespace;
9use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE};
10use rustc_infer::infer::canonical::query_response::make_query_region_constraints;
11use rustc_infer::infer::canonical::{
12    Canonical, CanonicalExt as _, CanonicalQueryInput, CanonicalVarKind, CanonicalVarValues,
13    Canonicalized, QueryRegionConstraint, instantiate_value,
14};
15use rustc_infer::infer::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt};
16use rustc_infer::traits::solve::{
17    ComputeGoalFastPathOutcome, FetchEligibleAssocItemResponse, Goal, SucceededInErased,
18};
19use rustc_lint_defs::builtin::RECURSION_DEPTH_EXCEEDING_LIMIT;
20use rustc_middle::traits::query::NoSolution;
21use rustc_middle::traits::solve::MaybeInfo;
22use rustc_middle::ty::print::{FmtPrinter, Print};
23use rustc_middle::ty::transmute::Answer;
24use rustc_middle::ty::{
25    self, CanonicalizerState, MayBeErased, Region, Ty, TyCtxt, TypeFlags, TypeFoldable,
26    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
27};
28use rustc_next_trait_solver::solve::{GoalStalledOn, GoalStalledOnOpaques, TyOrConstInferVar};
29use rustc_span::{DUMMY_SP, Span};
30use rustc_structures::Limit;
31use rustc_transmute::TransmuteTypeEnv;
32use thin_vec::{ThinVec, thin_vec};
33
34use super::inspect::InferCtxtProofTreeExt;
35use crate::solve::inspect::{self, InspectConfig, ProofTreeVisitor};
36use crate::traits::{EvaluateConstErr, ObligationCause, implicit_fast_path, specialization_graph};
37
38#[repr(transparent)]
39pub struct SolverDelegate<'tcx>(InferCtxt<'tcx>);
40
41impl<'a, 'tcx> From<&'a InferCtxt<'tcx>> for &'a SolverDelegate<'tcx> {
42    fn from(infcx: &'a InferCtxt<'tcx>) -> Self {
43        // SAFETY: `repr(transparent)`
44        unsafe { std::mem::transmute(infcx) }
45    }
46}
47
48impl<'tcx> Deref for SolverDelegate<'tcx> {
49    type Target = InferCtxt<'tcx>;
50
51    fn deref(&self) -> &Self::Target {
52        &self.0
53    }
54}
55
56impl<'tcx> SolverDelegate<'tcx> {
57    fn known_no_opaque_types_in_storage(&self) -> bool {
58        self.inner.borrow_mut().opaque_types().is_empty()
59            // in erased mode, observing that opaques are empty aren't enough to give a result
60            // here, so let's try the slow path instead.
61            && !self.typing_mode_raw().is_erased_not_coherence()
62    }
63}
64
65/// Create a [`ComputeGoalFastPathOutcome`] signalling the goal is stalled
66/// on a list of [`ty::GenericArg`]
67fn goal_stalled_on_args<'tcx>(
68    stalled_vars: ThinVec<TyOrConstInferVar>,
69) -> ComputeGoalFastPathOutcome<'tcx> {
70    ComputeGoalFastPathOutcome::TriviallyStalled {
71        stalled_on: GoalStalledOn {
72            stalled_vars,
73            sub_roots: ThinVec::new(),
74            stalled_maybe_info: MaybeInfo::AMBIGUOUS,
75            opaques: GoalStalledOnOpaques::No,
76        },
77    }
78}
79
80/// Create a [`ComputeGoalFastPathOutcome`] signalling the  goal is stalled
81/// on a list of [`ty::GenericArg`] *or* the opaque type storage being nonempty.
82///
83fn goal_stalled_on_args_or_nonempty_opaques<'tcx>(
84    stalled_vars: ThinVec<TyOrConstInferVar>,
85) -> ComputeGoalFastPathOutcome<'tcx> {
86    ComputeGoalFastPathOutcome::TriviallyStalled {
87        stalled_on: GoalStalledOn {
88            stalled_vars,
89            sub_roots: ThinVec::new(),
90            stalled_maybe_info: MaybeInfo::AMBIGUOUS,
91            opaques: GoalStalledOnOpaques::Yes {
92                num_opaques_in_storage: 0,
93                // This function should only be called when not in erased mode,
94                // otherwise this is wrong. The `compute_goal_fast_path` does this
95                // through `known_no_opaque_types_in_storage`
96                previously_succeeded_in_erased: SucceededInErased::No,
97            },
98        },
99    }
100}
101
102struct CollectNonRegionInfer<'tcx> {
103    infers: ThinVec<ty::GenericArg<'tcx>>,
104    visited: FxHashSet<Ty<'tcx>>,
105}
106
107impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CollectNonRegionInfer<'tcx> {
108    fn visit_ty(&mut self, ty: Ty<'tcx>) {
109        if self.visited.contains(&ty) {
110            return;
111        }
112
113        match ty.kind() {
114            ty::Infer(_) => self.infers.push(ty.into()),
115            _ => ty.super_visit_with(self),
116        }
117
118        self.visited.insert(ty);
119    }
120
121    fn visit_const(&mut self, ct: ty::Const<'tcx>) {
122        match ct.kind() {
123            ty::ConstKind::Infer(_) => self.infers.push(ct.into()),
124            _ => ct.super_visit_with(self),
125        }
126    }
127}
128
129impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<'tcx> {
130    type Infcx = InferCtxt<'tcx>;
131    type Interner = TyCtxt<'tcx>;
132
133    fn cx(&self) -> TyCtxt<'tcx> {
134        self.0.tcx
135    }
136
137    fn build_with_canonical<V>(
138        interner: TyCtxt<'tcx>,
139        canonical: &CanonicalQueryInput<'tcx, V>,
140    ) -> (Self, V, CanonicalVarValues<'tcx>)
141    where
142        V: TypeFoldable<TyCtxt<'tcx>>,
143    {
144        let (infcx, value, vars) = interner
145            .infer_ctxt()
146            .with_next_trait_solver(true)
147            .build_with_canonical(DUMMY_SP, canonical);
148        (SolverDelegate(infcx), value, vars)
149    }
150
151    fn compute_goal_fast_path(
152        &self,
153        goal: Goal<'tcx, ty::Predicate<'tcx>>,
154        span: Span,
155    ) -> ComputeGoalFastPathOutcome<'tcx> {
156        use ComputeGoalFastPathOutcome as Outcome;
157
158        // FIXME(-Zassumptions-on-binders): actually handle fast path
159        if self.tcx.assumptions_on_binders() {
160            return Outcome::NoFastPath;
161        }
162
163        let pred = goal.predicate.kind();
164        match pred.skip_binder() {
165            ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
166                let trait_pred = pred.rebind(trait_pred);
167
168                let self_ty = self.shallow_resolve(trait_pred.self_ty().skip_binder());
169                if let Some(vid) = self_ty.ty_vid()
170                // We don't do this fast path when opaques are defined since we may
171                // eventually use opaques to incompletely guide inference via ty var
172                // self types.
173                // FIXME: Properly consider opaques here.
174                && self.known_no_opaque_types_in_storage()
175                {
176                    goal_stalled_on_args_or_nonempty_opaques({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(TyOrConstInferVar::Ty(vid));
    vec
}thin_vec![TyOrConstInferVar::Ty(vid)])
177                } else if trait_pred.polarity() == ty::ClausePolarity::Positive {
178                    match self.0.tcx.as_lang_item(trait_pred.def_id()) {
179                        Some(lang_item @ (LangItem::Sized | LangItem::MetaSized)) => {
180                            let sizedness = if lang_item == LangItem::Sized {
181                                ty::SizedTraitKind::Sized
182                            } else {
183                                ty::SizedTraitKind::MetaSized
184                            };
185
186                            // Avoid deep resolution when sizedness is already known.
187                            // Keep the fallback for error tainting and nontrivial goals.
188                            if !goal.predicate.references_error()
189                                && self_ty.has_trivial_sizedness(self.tcx, sizedness)
190                            {
191                                Outcome::TriviallyHolds
192                            } else {
193                                let predicate =
194                                    self.deeply_resolve_ignoring_regions(goal.predicate);
195                                if implicit_fast_path(self.tcx, predicate, goal.param_env) {
196                                    Outcome::TriviallyHolds
197                                } else {
198                                    Outcome::NoFastPath
199                                }
200                            }
201                        }
202                        Some(LangItem::Copy | LangItem::Clone) => {
203                            let self_ty = self.deeply_resolve_ignoring_regions(
204                                trait_pred.self_ty().skip_binder(),
205                            );
206                            // Unlike `Sized` traits, which always prefer the built-in impl,
207                            // `Copy`/`Clone` may be shadowed by a param-env candidate which
208                            // could force a lifetime error or guide inference. While that's
209                            // not generally desirable, it is observable, so for now let's
210                            // ignore this fast path for types that have regions or infer.
211                            if !self_ty
212                                .has_type_flags(TypeFlags::HAS_FREE_REGIONS | TypeFlags::HAS_INFER)
213                                && self_ty.is_trivially_pure_clone_copy()
214                            {
215                                Outcome::TriviallyHolds
216                            } else {
217                                Outcome::NoFastPath
218                            }
219                        }
220                        _ => Outcome::NoFastPath,
221                    }
222                } else {
223                    Outcome::NoFastPath
224                }
225            }
226            ty::PredicateKind::DynCompatible(def_id) if self.0.tcx.is_dyn_compatible(def_id) => {
227                Outcome::TriviallyHolds
228            }
229            ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(outlives)) => {
230                if outlives.has_escaping_bound_vars() {
231                    return Outcome::NoFastPath;
232                }
233
234                // We use `VisibleForLeakCheck::Yes` for `RegionOutlives` goals without
235                // the fast path. However, we always change region constraints from nested
236                // goals to `VisibleForLeakCheck::No`, so to be consistent with this
237                // behavior as we avoid the nested goal boundary, we have to manually
238                // set the flag.
239                self.0.sub_regions(
240                    SubregionOrigin::RelateRegionParamBound(span, None),
241                    outlives.1,
242                    outlives.0,
243                    ty::VisibleForLeakCheck::No,
244                );
245                Outcome::TriviallyHolds
246            }
247            ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(outlives)) => {
248                if outlives.has_escaping_bound_vars() {
249                    return Outcome::NoFastPath;
250                }
251
252                let ty = self.deeply_resolve_ignoring_regions(outlives.0);
253                if ty.has_non_rigid_aliases() {
254                    return Outcome::NoFastPath;
255                }
256
257                let mut infer_collector = CollectNonRegionInfer {
258                    infers: Default::default(),
259                    visited: Default::default(),
260                };
261                ty.visit_with(&mut infer_collector);
262                let infers = infer_collector.infers;
263                if !infers.is_empty() {
264                    return goal_stalled_on_args(
265                        infers
266                            .into_iter()
267                            .map(|i| {
268                                TyOrConstInferVar::maybe_from_generic_arg::<Self::Interner>(i)
269                                    .unwrap()
270                            })
271                            .collect(),
272                    );
273                }
274
275                self.0.register_type_outlives_constraint(
276                    outlives.0,
277                    outlives.1,
278                    &ObligationCause::dummy_with_span(span),
279                );
280
281                Outcome::TriviallyHolds
282            }
283            ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, .. })
284            | ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
285                if a.has_escaping_bound_vars() || b.has_escaping_bound_vars() {
286                    return Outcome::NoFastPath;
287                }
288
289                match (self.shallow_resolve(a).kind(), self.shallow_resolve(b).kind()) {
290                    (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
291                        self.sub_unify_ty_vids_raw(a_vid, b_vid);
292                        goal_stalled_on_args({
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(TyOrConstInferVar::Ty(a_vid));
    vec.push(TyOrConstInferVar::Ty(b_vid));
    vec
}thin_vec![
293                            TyOrConstInferVar::Ty(a_vid),
294                            TyOrConstInferVar::Ty(b_vid),
295                        ])
296                    }
297                    _ => Outcome::NoFastPath,
298                }
299            }
300            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _)) => {
301                if ct.has_escaping_bound_vars() {
302                    return Outcome::NoFastPath;
303                }
304
305                let arg = self.shallow_resolve_const(ct);
306                if let Some(vid) = arg.ct_vid() {
307                    goal_stalled_on_args({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(TyOrConstInferVar::Const(vid));
    vec
}thin_vec![TyOrConstInferVar::Const(vid)])
308                } else {
309                    Outcome::NoFastPath
310                }
311            }
312            ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
313                if arg.has_escaping_bound_vars() {
314                    return Outcome::NoFastPath;
315                }
316
317                let arg = self.shallow_resolve_term(arg);
318                if arg.is_trivially_wf(self.tcx) {
319                    Outcome::TriviallyHolds
320                } else if arg.is_infer() {
321                    goal_stalled_on_args({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(TyOrConstInferVar::maybe_from_term::<TyCtxt<'tcx>>(arg).expect("its an infer var"));
    vec
}thin_vec![
322                        TyOrConstInferVar::maybe_from_term::<TyCtxt<'tcx>>(arg)
323                            .expect("its an infer var"),
324                    ])
325                } else {
326                    Outcome::NoFastPath
327                }
328            }
329            _ => Outcome::NoFastPath,
330        }
331    }
332
333    fn fresh_var_for_kind(
334        &self,
335        arg: ty::GenericArg<'tcx>,
336        span: Span,
337        universe: ty::UniverseIndex,
338    ) -> ty::GenericArg<'tcx> {
339        match arg.kind() {
340            ty::GenericArgKind::Lifetime(_) => {
341                self.next_region_var_in_universe(RegionVariableOrigin::Misc(span), universe).into()
342            }
343            ty::GenericArgKind::Type(_) => self.next_ty_var_in_universe(span, universe).into(),
344            ty::GenericArgKind::Const(_) => self.next_const_var_in_universe(span, universe).into(),
345        }
346    }
347
348    fn leak_check(&self, max_input_universe: ty::UniverseIndex) -> Result<(), NoSolution> {
349        self.0.leak_check(max_input_universe, None).map_err(|_| NoSolution)
350    }
351
352    fn evaluate_const<E: Debug>(
353        &self,
354        param_env: ty::ParamEnv<'tcx>,
355        alias_const: ty::AliasConst<'tcx>,
356        normalize_ty: impl FnOnce(ty::Unnormalized<'tcx, Ty<'tcx>>) -> Result<Ty<'tcx>, E>,
357    ) -> Result<Option<ty::Const<'tcx>>, E> {
358        let ct = ty::Const::new_alias(self.tcx, ty::IsRigid::No, alias_const);
359
360        match crate::traits::try_evaluate_const(&self.0, ct, param_env, normalize_ty) {
361            Ok(ct) => Ok(Some(ct)),
362            Err(EvaluateConstErr::EvaluationFailure(e)) => {
363                Ok(Some(ty::Const::new_error(self.tcx, e)))
364            }
365            Err(
366                EvaluateConstErr::InvalidConstParamTy(_) | EvaluateConstErr::HasGenericsOrInfers,
367            ) => Ok(None),
368            Err(EvaluateConstErr::FailedNormalization(e)) => Err(e),
369        }
370    }
371
372    fn well_formed_goals(
373        &self,
374        param_env: ty::ParamEnv<'tcx>,
375        term: ty::Term<'tcx>,
376    ) -> Option<Vec<Goal<'tcx, ty::Predicate<'tcx>>>> {
377        crate::traits::wf::unnormalized_obligations(
378            &self.0,
379            param_env,
380            term,
381            DUMMY_SP,
382            CRATE_DEF_ID,
383        )
384        .map(|obligations| obligations.into_iter().map(|obligation| obligation.as_goal()).collect())
385    }
386
387    fn make_deduplicated_region_constraints(
388        &self,
389    ) -> Vec<(ty::RegionConstraint<'tcx>, ty::VisibleForLeakCheck)> {
390        // Cannot use `take_registered_type_outlives_constraints` as we may compute the response
391        // inside of a `probe` whenever we have multiple choices inside of the solver.
392        let type_outlives_constraints =
393            self.0.inner.borrow().type_outlives_constraints().to_owned();
394        let region_assumptions = self.0.inner.borrow().region_assumptions().to_owned();
395        let region_constraints = self.0.with_region_constraints(|region_constraints| {
396            make_query_region_constraints(
397                type_outlives_constraints,
398                region_constraints,
399                region_assumptions,
400            )
401        });
402
403        let mut seen = FxHashMap::default();
404        let mut constraints = ::alloc::vec::Vec::new()vec![];
405        for QueryRegionConstraint { constraint: outlives, visible_for_leak_check: vis, .. } in
406            region_constraints.constraints
407        {
408            match seen.entry(outlives) {
409                Entry::Occupied(occupied) => {
410                    let idx = occupied.get();
411                    let (_, prev_vis): &mut (_, ty::VisibleForLeakCheck) =
412                        constraints.get_mut(*idx).unwrap();
413                    *prev_vis = (*prev_vis).or(vis);
414                }
415                Entry::Vacant(vacant) => {
416                    vacant.insert(constraints.len());
417                    constraints.push((outlives, vis));
418                }
419            }
420        }
421        constraints
422    }
423
424    fn instantiate_value<V>(&self, value: Canonicalized<V>, values: CanonicalVarValues<'tcx>) -> V
425    where
426        V: TypeFoldable<TyCtxt<'tcx>>,
427    {
428        instantiate_value(self.tcx, &values, value.into_uninstantiated())
429    }
430
431    fn instantiate_canonical<V>(
432        &self,
433        canonical: Canonical<'tcx, V>,
434        values: CanonicalVarValues<'tcx>,
435    ) -> V
436    where
437        V: TypeFoldable<TyCtxt<'tcx>>,
438    {
439        canonical.instantiate(self.tcx, &values)
440    }
441
442    fn instantiate_canonical_var(
443        &self,
444        kind: CanonicalVarKind<'tcx>,
445        span: Span,
446        prev_var_values: &[ty::GenericArg<'tcx>],
447        universe_map: impl Fn(ty::UniverseIndex) -> ty::UniverseIndex,
448    ) -> ty::GenericArg<'tcx> {
449        self.0.instantiate_canonical_var(span, kind, prev_var_values, universe_map)
450    }
451
452    fn add_item_bounds_for_hidden_type(
453        &self,
454        def_id: DefId,
455        args: ty::GenericArgs<'tcx>,
456        param_env: ty::ParamEnv<'tcx>,
457        hidden_ty: Ty<'tcx>,
458        goals: &mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
459    ) {
460        self.0.add_item_bounds_for_hidden_type(def_id, args, param_env, hidden_ty, goals);
461    }
462
463    fn fetch_eligible_assoc_item(
464        &self,
465        goal_trait_ref: ty::TraitRef<'tcx>,
466        trait_assoc_def_id: DefId,
467        impl_def_id: DefId,
468    ) -> FetchEligibleAssocItemResponse<'tcx> {
469        let node_item =
470            match specialization_graph::assoc_def(self.tcx, impl_def_id, trait_assoc_def_id) {
471                Ok(i) => i,
472                Err(guar) => return FetchEligibleAssocItemResponse::Err(guar),
473            };
474
475        let typing_mode = self.typing_mode_raw();
476
477        let eligible = if node_item.is_final() {
478            // Non-specializable items are always projectable.
479            true
480        } else {
481            // Only reveal a specializable default if we're past type-checking
482            // and the obligation is monomorphic, otherwise passes such as
483            // transmute checking and polymorphic MIR optimizations could
484            // get a result which isn't correct for all monomorphizations.
485            match typing_mode {
486                TypingMode::Coherence
487                | TypingMode::Typeck { .. }
488                | TypingMode::PostTypeckThroughBorrowck { .. }
489                | TypingMode::Reflection
490                | TypingMode::PostBorrowck { .. } => false,
491                TypingMode::PostAnalysis | TypingMode::Codegen => {
492                    let poly_trait_ref = self.deeply_resolve_ignoring_regions(goal_trait_ref);
493                    !poly_trait_ref.still_further_specializable()
494                }
495                TypingMode::ErasedNotCoherence(MayBeErased) => {
496                    return FetchEligibleAssocItemResponse::NotFoundBecauseErased;
497                }
498            }
499        };
500
501        // FIXME: Check for defaultness here may cause diagnostics problems.
502        if eligible {
503            FetchEligibleAssocItemResponse::Found(node_item.item.def_id)
504        } else {
505            // We know it's not erased since then we'd have returned in the match above,
506            // or node_item.final() was true and eligible is always true.
507            FetchEligibleAssocItemResponse::NotFound(typing_mode.assert_not_erased())
508        }
509    }
510
511    // FIXME: This actually should destructure the `Result` we get from transmutability and
512    // register candidates. We probably need to register >1 since we may have an OR of ANDs.
513    fn is_transmutable(
514        &self,
515        src: Ty<'tcx>,
516        dst: Ty<'tcx>,
517        assume: ty::Const<'tcx>,
518    ) -> Result<Answer<Region<'tcx>, Ty<'tcx>>, NoSolution> {
519        rustc_transmute::Assume::from_const(self.tcx, assume)
520            .map(|assume| TransmuteTypeEnv::new(self.0.tcx).is_transmutable(src, dst, assume))
521            .ok_or(NoSolution)
522    }
523
524    fn obtain_canonicalizer_state(&self) -> Box<CanonicalizerState<Self::Interner>> {
525        // Get the top state, or create a new one if none are available.
526        self.cx()
527            .caches
528            .canonicalizer_states
529            .lock()
530            .pop()
531            .unwrap_or_else(|| Box::new(CanonicalizerState::default()))
532    }
533
534    fn release_canonicalizer_state(&self, mut state: Box<CanonicalizerState<Self::Interner>>) {
535        // Clear (don't deallocate) the state for later reuse.
536        state.clear();
537        self.cx().caches.canonicalizer_states.lock().push(state);
538    }
539
540    fn emit_next_solver_overflow_fcw(&self, goal: Goal<'tcx, ty::Predicate<'tcx>>, span: Span) {
541        let tcx = self.tcx;
542        tcx.emit_node_span_lint(
543            RECURSION_DEPTH_EXCEEDING_LIMIT,
544            CRATE_HIR_ID,
545            span,
546            rustc_errors::DiagDecorator(|diag| {
547                // We do this in the decorator as that avoids the work
548                // if we don't actually emit the lint.
549                let goal = self.deeply_resolve_ignoring_regions(goal);
550                let recursion_limit = if let Some(specified_limit) = tcx.next_solver_overflow_fcw_limit()
551                {
552                    // Double default limit allows us to see the whole chain.
553                    usize::min(specified_limit, tcx.recursion_limit().0 * 2)
554                } else {
555                    usize::min(16, tcx.recursion_limit().0)
556                };
557                let mut visitor = OverflowedGoalChain {
558                    span,
559                    predicates: ::alloc::vec::Vec::new()vec![],
560                    recursion_limit,
561                };
562
563                let _ = self.with_disabled_next_solver_overflow_fcw(|| {
564                    self.visit_proof_tree(goal, &mut visitor)
565                });
566
567                // FIXME: share this with overflow error in fulfillment instead of duplicating.
568                let pred_str = |pred: ty::Predicate<'tcx>| {
569                    let s = pred.to_string();
570                    if s.len() > 80 {
571                        let mut p: FmtPrinter<'_, '_> =
572                            FmtPrinter::new_with_limit(tcx, Namespace::TypeNS, Limit(10));
573                        pred.print(&mut p).unwrap();
574                        p.into_buffer()
575                    } else {
576                        s
577                    }
578                };
579                diag.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred_str(goal.predicate)))
    })format!(
580                    "overflow evaluating the requirement `{}`",
581                    pred_str(goal.predicate),
582                ));
583                for p in visitor.predicates.into_iter().skip(1) {
584                    diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("which requires `{0}`",
                pred_str(p)))
    })format!("which requires `{}`", pred_str(p)));
585                }
586                diag.note("and so on...");
587                diag.help(
588                    "consider adding a manual `impl` of auto traits like `Send` for intermediate types, if auto traits are involved",
589                );
590                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("or consider increasing the recursion limit by adding a `#![recursion_limit = \"{0}\"]` attribute to your crate (`{1}`)",
                tcx.recursion_limit() * 2, tcx.crate_name(LOCAL_CRATE)))
    })format!(
591                    "or consider increasing the recursion limit by adding a \
592                     `#![recursion_limit = \"{}\"]` attribute to your crate (`{}`)",
593                    tcx.recursion_limit() * 2,
594                    tcx.crate_name(LOCAL_CRATE),
595                ));
596                diag.note("this lint is attached to the whole crate and can't be disabled on a per-function basis");
597            }),
598        )
599    }
600}
601
602struct OverflowedGoalChain<'tcx> {
603    span: Span,
604    predicates: Vec<ty::Predicate<'tcx>>,
605    recursion_limit: usize,
606}
607
608impl<'tcx> ProofTreeVisitor<'tcx> for OverflowedGoalChain<'tcx> {
609    type Result = ControlFlow<()>;
610
611    fn span(&self) -> Span {
612        self.span
613    }
614
615    fn config(&self) -> InspectConfig {
616        InspectConfig { max_depth: self.recursion_limit }
617    }
618
619    fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
620        self.predicates.push(goal.goal().predicate);
621        if let Some(cand) = goal.unique_applicable_candidate() {
622            goal.infcx().probe(|_| {
623                if let Some(nested_goal_with_largest_required_depth) = cand
624                    .instantiate_nested_goals(self.span)
625                    .into_iter()
626                    .max_by_key(|g| g.required_depth())
627                {
628                    nested_goal_with_largest_required_depth.visit_with(self)
629                } else {
630                    ControlFlow::Continue(())
631                }
632            })?;
633        }
634        ControlFlow::Continue(())
635    }
636
637    fn on_recursion_limit(&mut self) -> Self::Result {
638        ControlFlow::Break(())
639    }
640}