Skip to main content

rustc_trait_selection/solve/inspect/
analyse.rs

1//! An infrastructure to mechanically analyse proof trees.
2//!
3//! It is unavoidable that this representation is somewhat
4//! lossy as it should hide quite a few semantically relevant things,
5//! e.g. canonicalization and the order of nested goals.
6//!
7//! @lcnr: However, a lot of the weirdness here is not strictly necessary
8//! and could be improved in the future. This is mostly good enough for
9//! coherence right now and was annoying to implement, so I am leaving it
10//! as is until we start using it for something else.
11
12use std::assert_matches;
13
14use rustc_infer::infer::InferCtxt;
15use rustc_macros::extension;
16use rustc_middle::traits::solve::{Certainty, Goal, GoalSource, NoSolution, QueryResult};
17use rustc_middle::ty::{TyCtxt, VisitorResult, eager_resolve_vars, try_visit};
18use rustc_middle::{bug, ty};
19use rustc_next_trait_solver::canonical::instantiate_canonical_state;
20use rustc_next_trait_solver::solve::{MaybeCause, MaybeInfo, SolverDelegateEvalExt as _, inspect};
21use rustc_span::Span;
22use thin_vec::ThinVec;
23use tracing::instrument;
24
25use crate::solve::delegate::SolverDelegate;
26
27pub struct InspectConfig {
28    pub max_depth: usize,
29}
30
31pub struct InspectGoal<'a, 'tcx> {
32    infcx: &'a SolverDelegate<'tcx>,
33    depth: usize,
34    orig_values: ThinVec<ty::GenericArg<'tcx>>,
35    prev_universe: ty::UniverseIndex,
36    goal: Goal<'tcx, ty::Predicate<'tcx>>,
37    result: Result<Certainty, NoSolution>,
38    final_revision: &'tcx inspect::Probe<TyCtxt<'tcx>>,
39    source: GoalSource,
40}
41
42pub struct InspectCandidate<'a, 'tcx> {
43    goal: &'a InspectGoal<'a, 'tcx>,
44    kind: inspect::ProbeKind<TyCtxt<'tcx>>,
45    steps: Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
46    final_state: inspect::CanonicalState<TyCtxt<'tcx>, ()>,
47    result: QueryResult<'tcx>,
48    shallow_certainty: Certainty,
49}
50
51impl<'a, 'tcx> InspectCandidate<'a, 'tcx> {
52    pub fn kind(&self) -> inspect::ProbeKind<TyCtxt<'tcx>> {
53        self.kind
54    }
55
56    pub fn result(&self) -> Result<Certainty, NoSolution> {
57        self.result.map(|c| c.value.certainty)
58    }
59
60    pub fn goal(&self) -> &'a InspectGoal<'a, 'tcx> {
61        self.goal
62    }
63
64    /// Certainty passed into `evaluate_added_goals_and_make_canonical_response`.
65    ///
66    /// If this certainty is `Yes`, then we must be confident that the candidate
67    /// must hold iff it's nested goals hold. This is not true if the certainty is
68    /// `Maybe(..)`, which suggests we forced ambiguity instead.
69    ///
70    /// This is *not* the certainty of the candidate's full nested evaluation, which
71    /// can be accessed with [`Self::result`] instead.
72    pub fn shallow_certainty(&self) -> Certainty {
73        self.shallow_certainty
74    }
75
76    /// Visit all nested goals of this candidate without rolling
77    /// back their inference constraints. This function modifies
78    /// the state of the `infcx`.
79    pub fn visit_nested_no_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
80        for goal in self.instantiate_nested_goals(visitor.span()) {
81            match ::rustc_ast_ir::visit::VisitorResult::branch(goal.visit_with(visitor)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(goal.visit_with(visitor));
82        }
83
84        V::Result::output()
85    }
86
87    /// Instantiate the nested goals for the candidate without rolling back their
88    /// inference constraints. This function modifies the state of the `infcx`.
89    ///
90    /// See [`Self::instantiate_impl_args`] if you need the impl args too.
91    #[allow(clippy :: suspicious_else_formatting)]
{
    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("instantiate_nested_goals",
                                    "rustc_trait_selection::solve::inspect::analyse",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/solve/inspect/analyse.rs"),
                                    ::tracing_core::__macro_support::Option::Some(91u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::solve::inspect::analyse"),
                                    ::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("steps")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("steps");
                                                        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::debug(&self.goal.goal)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.steps)
                                                            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: Vec<InspectGoal<'a, 'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = self.goal.infcx;
            let param_env = self.goal.goal.param_env;
            let mut orig_values = self.goal.orig_values.clone();
            let mut instantiated_goals = ::alloc::vec::Vec::new();
            for step in &self.steps {
                match **step {
                    inspect::ProbeStep::AddGoal(source, goal) =>
                        instantiated_goals.push((source,
                                instantiate_canonical_state(infcx, span, param_env,
                                    self.goal.prev_universe, &mut orig_values, goal))),
                    inspect::ProbeStep::RecordImplArgs { .. } => {}
                    inspect::ProbeStep::MakeCanonicalResponse { .. } |
                        inspect::ProbeStep::NestedProbe(_) =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                }
            }
            let () =
                instantiate_canonical_state(infcx, span, param_env,
                    self.goal.prev_universe, &mut orig_values,
                    self.final_state);
            instantiated_goals.into_iter().map(|(source, goal)|
                        self.instantiate_proof_tree_for_nested_goal(source, goal,
                            span)).collect()
        }
    }
}#[instrument(
92        level = "debug",
93        skip_all,
94        fields(goal = ?self.goal.goal, steps = ?self.steps)
95    )]
96    pub fn instantiate_nested_goals(&self, span: Span) -> Vec<InspectGoal<'a, 'tcx>> {
97        let infcx = self.goal.infcx;
98        let param_env = self.goal.goal.param_env;
99        let mut orig_values = self.goal.orig_values.clone();
100
101        let mut instantiated_goals = vec![];
102        for step in &self.steps {
103            match **step {
104                inspect::ProbeStep::AddGoal(source, goal) => instantiated_goals.push((
105                    source,
106                    instantiate_canonical_state(
107                        infcx,
108                        span,
109                        param_env,
110                        self.goal.prev_universe,
111                        &mut orig_values,
112                        goal,
113                    ),
114                )),
115                inspect::ProbeStep::RecordImplArgs { .. } => {}
116                inspect::ProbeStep::MakeCanonicalResponse { .. }
117                | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
118            }
119        }
120
121        let () = instantiate_canonical_state(
122            infcx,
123            span,
124            param_env,
125            self.goal.prev_universe,
126            &mut orig_values,
127            self.final_state,
128        );
129
130        instantiated_goals
131            .into_iter()
132            .map(|(source, goal)| self.instantiate_proof_tree_for_nested_goal(source, goal, span))
133            .collect()
134    }
135
136    /// Instantiate the args of an impl if this candidate came from a
137    /// `CandidateSource::Impl`. This function modifies the state of the
138    /// `infcx`.
139    #[allow(clippy :: suspicious_else_formatting)]
{
    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("instantiate_impl_args",
                                    "rustc_trait_selection::solve::inspect::analyse",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/solve/inspect/analyse.rs"),
                                    ::tracing_core::__macro_support::Option::Some(139u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::solve::inspect::analyse"),
                                    ::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("steps")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("steps");
                                                        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::debug(&self.goal.goal)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.steps)
                                                            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: ty::GenericArgsRef<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let infcx = self.goal.infcx;
            let param_env = self.goal.goal.param_env;
            let mut orig_values = self.goal.orig_values.clone();
            for step in &self.steps {
                match **step {
                    inspect::ProbeStep::RecordImplArgs { impl_args } => {
                        let impl_args =
                            instantiate_canonical_state(infcx, span, param_env,
                                self.goal.prev_universe, &mut orig_values, impl_args);
                        let () =
                            instantiate_canonical_state(infcx, span, param_env,
                                self.goal.prev_universe, &mut orig_values,
                                self.final_state);
                        return eager_resolve_vars(&**infcx, impl_args);
                    }
                    inspect::ProbeStep::AddGoal(..) => {}
                    inspect::ProbeStep::MakeCanonicalResponse { .. } |
                        inspect::ProbeStep::NestedProbe(_) =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                }
            }
            ::rustc_middle::util::bug::bug_fmt(format_args!("expected impl args probe step for `instantiate_impl_args`"));
        }
    }
}#[instrument(
140        level = "debug",
141        skip_all,
142        fields(goal = ?self.goal.goal, steps = ?self.steps)
143    )]
144    pub fn instantiate_impl_args(&self, span: Span) -> ty::GenericArgsRef<'tcx> {
145        let infcx = self.goal.infcx;
146        let param_env = self.goal.goal.param_env;
147        let mut orig_values = self.goal.orig_values.clone();
148
149        for step in &self.steps {
150            match **step {
151                inspect::ProbeStep::RecordImplArgs { impl_args } => {
152                    let impl_args = instantiate_canonical_state(
153                        infcx,
154                        span,
155                        param_env,
156                        self.goal.prev_universe,
157                        &mut orig_values,
158                        impl_args,
159                    );
160
161                    let () = instantiate_canonical_state(
162                        infcx,
163                        span,
164                        param_env,
165                        self.goal.prev_universe,
166                        &mut orig_values,
167                        self.final_state,
168                    );
169
170                    return eager_resolve_vars(&**infcx, impl_args);
171                }
172                inspect::ProbeStep::AddGoal(..) => {}
173                inspect::ProbeStep::MakeCanonicalResponse { .. }
174                | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
175            }
176        }
177
178        bug!("expected impl args probe step for `instantiate_impl_args`");
179    }
180
181    pub fn instantiate_proof_tree_for_nested_goal(
182        &self,
183        source: GoalSource,
184        goal: Goal<'tcx, ty::Predicate<'tcx>>,
185        span: Span,
186    ) -> InspectGoal<'a, 'tcx> {
187        let infcx = self.goal.infcx;
188        match goal.predicate.kind().no_bound_vars() {
189            Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { .. })) => {
190                // We don't handle `NormalizesTo` as a nested goal
191                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
192            }
193            _ => {
194                // We're using a probe here as evaluating a goal could constrain
195                // inference variables by choosing one candidate. If we then recurse
196                // into another candidate who ends up with different inference
197                // constraints, we get an ICE if we already applied the constraints
198                // from the chosen candidate.
199                let proof_tree =
200                    infcx.probe(|_| infcx.evaluate_root_goal_for_proof_tree(goal, span).1);
201                InspectGoal::new(infcx, self.goal.depth + 1, proof_tree, source)
202            }
203        }
204    }
205
206    /// Visit all nested goals of this candidate, rolling back
207    /// all inference constraints.
208    pub fn visit_nested_in_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
209        self.goal.infcx.probe(|_| self.visit_nested_no_probe(visitor))
210    }
211}
212
213impl<'a, 'tcx> InspectGoal<'a, 'tcx> {
214    pub fn infcx(&self) -> &'a InferCtxt<'tcx> {
215        self.infcx
216    }
217
218    pub fn goal(&self) -> Goal<'tcx, ty::Predicate<'tcx>> {
219        self.goal
220    }
221
222    pub fn result(&self) -> Result<Certainty, NoSolution> {
223        self.result
224    }
225
226    pub fn source(&self) -> GoalSource {
227        self.source
228    }
229
230    pub fn depth(&self) -> usize {
231        self.depth
232    }
233
234    pub fn orig_values(&self) -> &[ty::GenericArg<'tcx>] {
235        &self.orig_values
236    }
237
238    fn candidates_recur(
239        &'a self,
240        candidates: &mut Vec<InspectCandidate<'a, 'tcx>>,
241        steps: &mut Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
242        probe: &'a inspect::Probe<TyCtxt<'tcx>>,
243    ) {
244        let mut shallow_certainty = None;
245        for step in &probe.steps {
246            match *step {
247                inspect::ProbeStep::AddGoal(..) | inspect::ProbeStep::RecordImplArgs { .. } => {
248                    steps.push(step)
249                }
250                inspect::ProbeStep::MakeCanonicalResponse { shallow_certainty: c } => {
251                    {
    match shallow_certainty.replace(c) {
        None |
            Some(Certainty::Maybe(MaybeInfo {
            cause: MaybeCause::Ambiguity,
            opaque_types_jank: _,
            stalled_on_coroutines: _ })) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "None |\nSome(Certainty::Maybe(MaybeInfo\n{\n    cause: MaybeCause::Ambiguity, opaque_types_jank: _, stalled_on_coroutines:\n    _,\n}))",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
252                        shallow_certainty.replace(c),
253                        None | Some(Certainty::Maybe(MaybeInfo {
254                            cause: MaybeCause::Ambiguity,
255                            opaque_types_jank: _,
256                            stalled_on_coroutines: _,
257                        }))
258                    );
259                }
260                inspect::ProbeStep::NestedProbe(ref probe) => {
261                    match probe.kind {
262                        // These never assemble candidates for the goal we're trying to solve.
263                        inspect::ProbeKind::ProjectionCompatibility
264                        | inspect::ProbeKind::ShadowedEnvProbing => continue,
265
266                        inspect::ProbeKind::NormalizedSelfTyAssembly
267                        | inspect::ProbeKind::UnsizeAssembly
268                        | inspect::ProbeKind::Root { .. }
269                        | inspect::ProbeKind::TraitCandidate { .. }
270                        | inspect::ProbeKind::OpaqueTypeStorageLookup { .. }
271                        | inspect::ProbeKind::RigidAlias { .. } => {
272                            // Nested probes have to prove goals added in their parent
273                            // but do not leak them, so we truncate the added goals
274                            // afterwards.
275                            let num_steps = steps.len();
276                            self.candidates_recur(candidates, steps, probe);
277                            steps.truncate(num_steps);
278                        }
279                    }
280                }
281            }
282        }
283
284        match probe.kind {
285            inspect::ProbeKind::ProjectionCompatibility
286            | inspect::ProbeKind::ShadowedEnvProbing => {
287                ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
288            }
289
290            inspect::ProbeKind::NormalizedSelfTyAssembly | inspect::ProbeKind::UnsizeAssembly => {}
291
292            // We add a candidate even for the root evaluation if there
293            // is only one way to prove a given goal, e.g. for `WellFormed`.
294            inspect::ProbeKind::Root { result }
295            | inspect::ProbeKind::TraitCandidate { source: _, result }
296            | inspect::ProbeKind::OpaqueTypeStorageLookup { result }
297            | inspect::ProbeKind::RigidAlias { result } => {
298                // We only add a candidate if `shallow_certainty` was set, which means
299                // that we ended up calling `evaluate_added_goals_and_make_canonical_response`.
300                if let Some(shallow_certainty) = shallow_certainty {
301                    candidates.push(InspectCandidate {
302                        goal: self,
303                        kind: probe.kind,
304                        steps: steps.clone(),
305                        final_state: probe.final_state,
306                        shallow_certainty,
307                        result,
308                    });
309                }
310            }
311        }
312    }
313
314    pub fn candidates(&'a self) -> Vec<InspectCandidate<'a, 'tcx>> {
315        let mut candidates = ::alloc::vec::Vec::new()vec![];
316        let mut nested_goals = ::alloc::vec::Vec::new()vec![];
317        self.candidates_recur(&mut candidates, &mut nested_goals, &self.final_revision);
318        candidates
319    }
320
321    /// Returns the single candidate applicable for the current goal, if it exists.
322    ///
323    /// Returns `None` if there are either no or multiple applicable candidates.
324    pub fn unique_applicable_candidate(&'a self) -> Option<InspectCandidate<'a, 'tcx>> {
325        // FIXME(-Znext-solver): This does not handle impl candidates
326        // hidden by env candidates.
327        let mut candidates = self.candidates();
328        candidates.retain(|c| c.result().is_ok());
329        candidates.pop().filter(|_| candidates.is_empty())
330    }
331
332    fn new(
333        infcx: &'a InferCtxt<'tcx>,
334        depth: usize,
335        root: inspect::GoalEvaluation<TyCtxt<'tcx>>,
336        source: GoalSource,
337    ) -> Self {
338        let infcx = <&SolverDelegate<'tcx>>::from(infcx);
339        let prev_universe = infcx.universe();
340
341        let inspect::GoalEvaluation { uncanonicalized_goal, orig_values, final_revision, result } =
342            root;
343        // If there's a normalizes-to goal, AND the evaluation result with the result of
344        // constraining the normalizes-to RHS and computing the nested goals.
345        let result = result.map(|ok| ok.value.certainty);
346
347        InspectGoal {
348            infcx,
349            depth,
350            orig_values,
351            prev_universe,
352            goal: eager_resolve_vars(&**infcx, uncanonicalized_goal),
353            result,
354            final_revision,
355            source,
356        }
357    }
358
359    pub(crate) fn visit_with<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
360        if self.depth < visitor.config().max_depth {
361            match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_goal(self)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(visitor.visit_goal(self));
362            V::Result::output()
363        } else {
364            visitor.on_recursion_limit()
365        }
366    }
367}
368
369/// The public API to interact with proof trees.
370pub trait ProofTreeVisitor<'tcx> {
371    type Result: VisitorResult = ();
372
373    fn span(&self) -> Span;
374
375    fn config(&self) -> InspectConfig {
376        InspectConfig { max_depth: 10 }
377    }
378
379    fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) -> Self::Result;
380
381    fn on_recursion_limit(&mut self) -> Self::Result {
382        Self::Result::output()
383    }
384}
385
386impl<'tcx> InferCtxtProofTreeExt<'tcx> for InferCtxt<'tcx> {
    fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(&self,
        goal: Goal<'tcx, ty::Predicate<'tcx>>, visitor: &mut V) -> V::Result {
        self.visit_proof_tree_at_depth(goal, 0, visitor)
    }
    fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(&self,
        goal: Goal<'tcx, ty::Predicate<'tcx>>, depth: usize, visitor: &mut V)
        -> V::Result {
        let (_, proof_tree) =
            <&SolverDelegate<'tcx>>::from(self).evaluate_root_goal_for_proof_tree(goal,
                visitor.span());
        visitor.visit_goal(&InspectGoal::new(self, depth, proof_tree,
                    GoalSource::Misc))
    }
}#[extension(pub trait InferCtxtProofTreeExt<'tcx>)]
387impl<'tcx> InferCtxt<'tcx> {
388    fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(
389        &self,
390        goal: Goal<'tcx, ty::Predicate<'tcx>>,
391        visitor: &mut V,
392    ) -> V::Result {
393        self.visit_proof_tree_at_depth(goal, 0, visitor)
394    }
395
396    fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(
397        &self,
398        goal: Goal<'tcx, ty::Predicate<'tcx>>,
399        depth: usize,
400        visitor: &mut V,
401    ) -> V::Result {
402        let (_, proof_tree) = <&SolverDelegate<'tcx>>::from(self)
403            .evaluate_root_goal_for_proof_tree(goal, visitor.span());
404        visitor.visit_goal(&InspectGoal::new(self, depth, proof_tree, GoalSource::Misc))
405    }
406}