Skip to main content

rustc_trait_selection/solve/
fulfill.rs

1use std::marker::PhantomData;
2use std::mem;
3
4use rustc_infer::infer::InferCtxt;
5use rustc_infer::traits::query::NoSolution;
6use rustc_infer::traits::{
7    FromSolverError, PredicateObligation, PredicateObligations, TraitEngine,
8};
9use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, TypingMode};
10use rustc_next_trait_solver::solve::fast_path::compute_goal_fast_path;
11use rustc_next_trait_solver::solve::{
12    GoalEvaluation, GoalStalledOn, HasChanged, MaybeInfo, SolverDelegateEvalExt as _,
13    StalledOnCoroutines,
14};
15use thin_vec::ThinVec;
16use tracing::instrument;
17
18use self::derive_errors::*;
19use super::Certainty;
20use super::delegate::SolverDelegate;
21use crate::traits::{FulfillmentError, ScrubbedTraitError};
22
23mod derive_errors;
24
25// FIXME: Do we need to use a `ThinVec` here?
26type PendingObligations<'tcx> =
27    ThinVec<(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)>;
28
29/// A trait engine using the new trait solver.
30///
31/// This is mostly identical to how `evaluate_all` works inside of the
32/// solver, except that the requirements are slightly different.
33///
34/// Unlike `evaluate_all` it is possible to add new obligations later on
35/// and we also have to track diagnostics information by using `Obligation`
36/// instead of `Goal`.
37///
38/// It is also likely that we want to use slightly different datastructures
39/// here as this will have to deal with far more root goals than `evaluate_all`.
40pub struct FulfillmentCtxt<'tcx, E: 'tcx> {
41    obligations: ObligationStorage<'tcx>,
42
43    /// The snapshot in which this context was created. Using the context
44    /// outside of this snapshot leads to subtle bugs if the snapshot
45    /// gets rolled back. Because of this we explicitly check that we only
46    /// use the context in exactly this snapshot.
47    usable_in_snapshot: usize,
48    _errors: PhantomData<E>,
49}
50
51#[derive(#[automatically_derived]
impl<'tcx> ::core::default::Default for ObligationStorage<'tcx> {
    #[inline]
    fn default() -> ObligationStorage<'tcx> {
        ObligationStorage {
            overflowed: ::core::default::Default::default(),
            pending: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ObligationStorage<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ObligationStorage", "overflowed", &self.overflowed, "pending",
            &&self.pending)
    }
}Debug)]
52struct ObligationStorage<'tcx> {
53    /// Obligations which resulted in an overflow in fulfillment itself.
54    ///
55    /// We cannot eagerly return these as error so we instead store them here
56    /// to avoid recomputing them each time `try_evaluate_obligations` is called.
57    /// This also allows us to return the correct `FulfillmentError` for them.
58    overflowed: Vec<PredicateObligation<'tcx>>,
59    pending: PendingObligations<'tcx>,
60}
61
62impl<'tcx> ObligationStorage<'tcx> {
63    fn register(
64        &mut self,
65        obligation: PredicateObligation<'tcx>,
66        stalled_on: Option<GoalStalledOn<TyCtxt<'tcx>>>,
67    ) {
68        self.pending.push((obligation, stalled_on));
69    }
70
71    fn has_pending_obligations(&self) -> bool {
72        !self.pending.is_empty() || !self.overflowed.is_empty()
73    }
74
75    fn clone_pending(&self) -> PredicateObligations<'tcx> {
76        let mut obligations: PredicateObligations<'tcx> =
77            self.pending.iter().map(|(o, _)| o.clone()).collect();
78        obligations.extend(self.overflowed.iter().cloned());
79        obligations
80    }
81
82    fn clone_pending_filtered<F>(&self, f: F) -> PredicateObligations<'tcx>
83    where
84        F: FnMut(&&(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)) -> bool,
85    {
86        let mut obligations: PredicateObligations<'tcx> =
87            self.pending.iter().filter(f).map(|(o, _)| o.clone()).collect();
88        obligations.extend(self.overflowed.iter().cloned());
89        obligations
90    }
91
92    fn drain_pending(
93        &mut self,
94        cond: impl Fn(&PredicateObligation<'tcx>, &Option<GoalStalledOn<TyCtxt<'tcx>>>) -> bool,
95    ) -> PendingObligations<'tcx> {
96        let (unstalled, pending) =
97            mem::take(&mut self.pending).into_iter().partition(|(o, s)| cond(o, s));
98        self.pending = pending;
99        unstalled
100    }
101
102    fn on_fulfillment_overflow(&mut self, infcx: &InferCtxt<'tcx>) {
103        infcx.probe(|_| {
104            // IMPORTANT: we must not use solve any inference variables in the obligations
105            // as this is all happening inside of a probe. We use a probe to make sure
106            // we get all obligations involved in the overflow. We pretty much check: if
107            // we were to do another step of `try_evaluate_obligations`, which goals would
108            // change.
109            self.overflowed.extend(
110                self.pending
111                    .extract_if(.., |(o, stalled_on)| {
112                        let goal = o.as_goal();
113                        let result = <&SolverDelegate<'tcx>>::from(infcx).evaluate_root_goal(
114                            goal,
115                            o.cause.span,
116                            stalled_on.take(),
117                        );
118                        #[allow(non_exhaustive_omitted_patterns)] match result {
    Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }) => true,
    _ => false,
}matches!(result, Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }))
119                    })
120                    .map(|(o, _)| o),
121            );
122        })
123    }
124}
125
126impl<'tcx, E: 'tcx> FulfillmentCtxt<'tcx, E> {
127    pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx, E> {
128        if !infcx.next_trait_solver() {
    {
        ::core::panicking::panic_fmt(format_args!("new trait solver fulfillment context created when infcx is set up for old trait solver"));
    }
};assert!(
129            infcx.next_trait_solver(),
130            "new trait solver fulfillment context created when \
131            infcx is set up for old trait solver"
132        );
133        FulfillmentCtxt {
134            obligations: Default::default(),
135            usable_in_snapshot: infcx.num_open_snapshots(),
136            _errors: PhantomData,
137        }
138    }
139
140    fn inspect_evaluated_obligation(
141        &self,
142        infcx: &InferCtxt<'tcx>,
143        obligation: &PredicateObligation<'tcx>,
144        result: &Result<GoalEvaluation<TyCtxt<'tcx>>, NoSolution>,
145    ) {
146        if let Some(inspector) = infcx.obligation_inspector.get() {
147            let result = match result {
148                Ok(GoalEvaluation { certainty, .. }) => Ok(*certainty),
149                Err(NoSolution) => Err(NoSolution),
150            };
151            (inspector)(infcx, &obligation, result);
152        }
153    }
154}
155
156impl<'tcx, E> TraitEngine<'tcx, E> for FulfillmentCtxt<'tcx, E>
157where
158    E: FromSolverError<'tcx, NextSolverError<'tcx>>,
159{
160    #[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("register_predicate_obligation",
                                    "rustc_trait_selection::solve::fulfill",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/solve/fulfill.rs"),
                                    ::tracing_core::__macro_support::Option::Some(160u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::solve::fulfill"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("obligation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("obligation");
                                                        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::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,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                match (&self.usable_in_snapshot, &infcx.num_open_snapshots())
                    {
                    (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);
                        }
                    }
                }
            };
            let delegate = <&SolverDelegate<'tcx>>::from(infcx);
            if let Some(GoalEvaluation {
                    goal: _, certainty, has_changed: _, stalled_on }) =
                    compute_goal_fast_path(delegate, obligation.as_goal(),
                        obligation.cause.span) {
                match certainty {
                    Certainty::Yes => {}
                    Certainty::Maybe(_) => {
                        self.obligations.register(obligation, stalled_on);
                    }
                }
            } else { self.obligations.register(obligation, None); }
        }
    }
}#[instrument(level = "trace", skip(self, infcx))]
161    fn register_predicate_obligation(
162        &mut self,
163        infcx: &InferCtxt<'tcx>,
164        obligation: PredicateObligation<'tcx>,
165    ) {
166        assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
167
168        let delegate = <&SolverDelegate<'tcx>>::from(infcx);
169        if let Some(GoalEvaluation { goal: _, certainty, has_changed: _, stalled_on }) =
170            compute_goal_fast_path(delegate, obligation.as_goal(), obligation.cause.span)
171        {
172            // If we can take the fast path, don't even bother adding the goal to obligations,
173            // or if `Certainty::Maybe`, add it with precise stalled_on information.
174            match certainty {
175                Certainty::Yes => {}
176                Certainty::Maybe(_) => {
177                    self.obligations.register(obligation, stalled_on);
178                }
179            }
180        } else {
181            self.obligations.register(obligation, None);
182        }
183    }
184
185    fn collect_remaining_errors(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
186        self.obligations
187            .pending
188            .drain(..)
189            .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
190            .chain(
191                self.obligations
192                    .overflowed
193                    .drain(..)
194                    .map(|obligation| NextSolverError::Overflow(obligation)),
195            )
196            .map(|e| E::from_solver_error(infcx, e))
197            .collect()
198    }
199
200    fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
201        {
    match (&self.usable_in_snapshot, &infcx.num_open_snapshots()) {
        (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);
            }
        }
    }
};assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
202        let mut errors = Vec::new();
203        loop {
204            let mut any_changed = false;
205            for (mut obligation, stalled_on) in self.obligations.drain_pending(|_, _| true) {
206                let goal = obligation.as_goal();
207                let delegate = <&SolverDelegate<'tcx>>::from(infcx);
208
209                let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
210                self.inspect_evaluated_obligation(infcx, &obligation, &result);
211                let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
212                    Ok(result) => result,
213                    Err(NoSolution) => {
214                        errors.push(E::from_solver_error(
215                            infcx,
216                            NextSolverError::TrueError(obligation),
217                        ));
218                        continue;
219                    }
220                };
221
222                // We've resolved the goal in `evaluate_root_goal`, avoid redoing this work
223                // in the next iteration. This does not resolve the inference variables
224                // constrained by evaluating the goal.
225                obligation.predicate = goal.predicate;
226                if has_changed == HasChanged::Yes {
227                    // We increment the recursion depth here to track the number of times
228                    // this goal has resulted in inference progress. This doesn't precisely
229                    // model the way that we track recursion depth in the old solver due
230                    // to the fact that we only process root obligations, but it is a good
231                    // approximation and should only result in fulfillment overflow in
232                    // pathological cases.
233                    obligation.recursion_depth += 1;
234
235                    if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
236                        self.obligations.on_fulfillment_overflow(infcx);
237                        // Only return true errors that we have accumulated while processing.
238                        return errors;
239                    } else {
240                        any_changed = true;
241                    }
242                }
243
244                match certainty {
245                    Certainty::Yes => {
246                        // Goals may depend on structural identity. Region uniquification at the
247                        // start of MIR borrowck may cause things to no longer be so, potentially
248                        // causing an ICE.
249                        //
250                        // While we uniquify root goals in HIR this does not handle cases where
251                        // regions are hidden inside of a type or const inference variable.
252                        //
253                        // FIXME(-Znext-solver): This does not handle inference variables hidden
254                        // inside of an opaque type, e.g. if there's `Opaque = (?x, ?x)` in the
255                        // storage, we can also rely on structural identity of `?x` even if we
256                        // later uniquify it in MIR borrowck.
257                        if infcx.in_hir_typeck
258                            && (obligation.has_non_region_infer() || obligation.has_free_regions())
259                        {
260                            infcx.push_hir_typeck_potentially_region_dependent_goal(obligation);
261                        }
262                    }
263                    Certainty::Maybe(_) => self.obligations.register(obligation, stalled_on),
264                }
265            }
266
267            if !any_changed {
268                break;
269            }
270        }
271
272        errors
273    }
274
275    fn has_pending_obligations(&self) -> bool {
276        self.obligations.has_pending_obligations()
277    }
278
279    fn pending_obligations(&self) -> PredicateObligations<'tcx> {
280        self.obligations.clone_pending()
281    }
282
283    fn pending_obligations_potentially_referencing_sub_root(
284        &self,
285        infcx: &InferCtxt<'tcx>,
286        vid: ty::TyVid,
287    ) -> PredicateObligations<'tcx> {
288        // `-Zdisable-fast-paths`: same gate as the other new-solver fast paths.
289        if infcx.tcx.disable_trait_solver_fast_paths() {
290            return self.obligations.clone_pending();
291        }
292        self.obligations.clone_pending_filtered(|(_, stalled_on)| {
293            let Some(stalled_on) = stalled_on else { return true };
294            // Don't reuse the sub-unification roots cached on `stalled_on`:
295            // a later sub-unification merge can have changed which root
296            // each stalled var belongs to, so the cached info can be stale.
297            // Walk `stalled_vars` and recompute the current root instead.
298            //
299            // Conservative here: if a stalled var no longer resolves to an
300            // infer var, some unification happened, so the goal is no longer
301            // stalled. Include it to be re-evaluated downstream.
302            stalled_on.stalled_vars.iter().filter_map(|arg| arg.as_type()).any(|ty| {
303                match *infcx.shallow_resolve(ty).kind() {
304                    ty::Infer(ty::TyVar(tv)) => infcx.sub_unification_table_root_var(tv) == vid,
305                    _ => true,
306                }
307            })
308        })
309    }
310
311    fn pending_obligations_potentially_referencing_float_infer(
312        &self,
313        infcx: &InferCtxt<'tcx>,
314    ) -> PredicateObligations<'tcx> {
315        // `-Zdisable-fast-paths`: same gate as the other new-solver fast paths.
316        if infcx.tcx.disable_trait_solver_fast_paths() {
317            return self.obligations.clone_pending();
318        }
319
320        self.obligations.clone_pending_filtered(|(_, stalled_on)| {
321            let Some(stalled_on) = stalled_on else { return true };
322            // If the stalled vars don't have float infers, the nested goals won't
323            // have them either. We only create float infers for user written literals.
324            stalled_on
325                .stalled_vars
326                .iter()
327                .filter_map(|arg| arg.as_type())
328                .any(|ty| #[allow(non_exhaustive_omitted_patterns)] match infcx.shallow_resolve(ty).kind()
    {
    ty::Infer(ty::FloatVar(_)) => true,
    _ => false,
}matches!(infcx.shallow_resolve(ty).kind(), ty::Infer(ty::FloatVar(_))))
329        })
330    }
331
332    fn drain_stalled_obligations_for_coroutines(
333        &mut self,
334        infcx: &InferCtxt<'tcx>,
335    ) -> PredicateObligations<'tcx> {
336        let stalled_coroutines = match infcx.typing_mode_raw().assert_not_erased() {
337            TypingMode::Typeck { defining_opaque_types_and_generators } => {
338                defining_opaque_types_and_generators
339            }
340            TypingMode::Coherence
341            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ }
342            | TypingMode::PostBorrowck { defined_opaque_types: _ }
343            | TypingMode::Reflection
344            | TypingMode::PostAnalysis
345            | TypingMode::Codegen => return Default::default(),
346        };
347
348        if stalled_coroutines.is_empty() {
349            return Default::default();
350        }
351
352        self.obligations
353            .drain_pending(|_, stalled_on| {
354                stalled_on.as_ref().is_some_and(|s| match s.stalled_certainty {
355                    Certainty::Maybe(MaybeInfo {
356                        cause: _,
357                        opaque_types_jank: _,
358                        stalled_on_coroutines: StalledOnCoroutines::Yes,
359                    }) => true,
360                    Certainty::Maybe(_) | Certainty::Yes => false,
361                })
362            })
363            .into_iter()
364            .map(|(o, _)| o)
365            .collect()
366    }
367}
368
369pub enum NextSolverError<'tcx> {
370    TrueError(PredicateObligation<'tcx>),
371    Ambiguity(PredicateObligation<'tcx>),
372    Overflow(PredicateObligation<'tcx>),
373}
374
375impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
376    fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
377        match error {
378            NextSolverError::TrueError(obligation) => {
379                fulfillment_error_for_no_solution(infcx, obligation)
380            }
381            NextSolverError::Ambiguity(obligation) => {
382                fulfillment_error_for_stalled(infcx, obligation)
383            }
384            NextSolverError::Overflow(obligation) => {
385                fulfillment_error_for_overflow(infcx, obligation)
386            }
387        }
388    }
389}
390
391impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
392    fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
393        match error {
394            NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
395            NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
396                ScrubbedTraitError::Ambiguity
397            }
398        }
399    }
400}