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        #[allow(clippy::iter_skip_zero)]
187        self.obligations
188            .pending
189            .drain(..)
190            .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
191            .chain(
192                self.obligations
193                    .overflowed
194                    .drain(..)
195                    .map(|obligation| NextSolverError::Overflow(obligation)),
196            )
197            .map(|e| E::from_solver_error(infcx, e))
198            // Skip doesn't implement TrustedLen, so we use it to
199            // avoid Vec::from_iter specialization that seems
200            // to optimize poorly in combination with ThinVec::drain
201            // on this particular sequence.
202            // See https://github.com/rust-lang/rust/pull/160073
203            .skip(0)
204            .collect()
205    }
206
207    fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
208        {
    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());
209        let mut errors = Vec::new();
210        loop {
211            let mut any_changed = false;
212            for (mut obligation, stalled_on) in mem::take(&mut self.obligations.pending) {
213                let goal = obligation.as_goal();
214                let delegate = <&SolverDelegate<'tcx>>::from(infcx);
215
216                let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
217                self.inspect_evaluated_obligation(infcx, &obligation, &result);
218                let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
219                    Ok(result) => result,
220                    Err(NoSolution) => {
221                        errors.push(E::from_solver_error(
222                            infcx,
223                            NextSolverError::TrueError(obligation),
224                        ));
225                        continue;
226                    }
227                };
228
229                // We've resolved the goal in `evaluate_root_goal`, avoid redoing this work
230                // in the next iteration. This does not resolve the inference variables
231                // constrained by evaluating the goal.
232                obligation.predicate = goal.predicate;
233                if has_changed == HasChanged::Yes {
234                    // We increment the recursion depth here to track the number of times
235                    // this goal has resulted in inference progress. This doesn't precisely
236                    // model the way that we track recursion depth in the old solver due
237                    // to the fact that we only process root obligations, but it is a good
238                    // approximation and should only result in fulfillment overflow in
239                    // pathological cases.
240                    obligation.recursion_depth += 1;
241
242                    if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
243                        self.obligations.on_fulfillment_overflow(infcx);
244                        // Only return true errors that we have accumulated while processing.
245                        return errors;
246                    } else {
247                        any_changed = true;
248                    }
249                }
250
251                match certainty {
252                    Certainty::Yes => {
253                        // Goals may depend on structural identity. Region uniquification at the
254                        // start of MIR borrowck may cause things to no longer be so, potentially
255                        // causing an ICE.
256                        //
257                        // While we uniquify root goals in HIR this does not handle cases where
258                        // regions are hidden inside of a type or const inference variable.
259                        //
260                        // FIXME(-Znext-solver): This does not handle inference variables hidden
261                        // inside of an opaque type, e.g. if there's `Opaque = (?x, ?x)` in the
262                        // storage, we can also rely on structural identity of `?x` even if we
263                        // later uniquify it in MIR borrowck.
264                        if infcx.in_hir_typeck
265                            && (obligation.has_non_region_infer() || obligation.has_free_regions())
266                        {
267                            infcx.push_hir_typeck_potentially_region_dependent_goal(obligation);
268                        }
269                    }
270                    Certainty::Maybe(_) => self.obligations.register(obligation, stalled_on),
271                }
272            }
273
274            if !any_changed {
275                break;
276            }
277        }
278
279        errors
280    }
281
282    fn has_pending_obligations(&self) -> bool {
283        self.obligations.has_pending_obligations()
284    }
285
286    fn pending_obligations(&self) -> PredicateObligations<'tcx> {
287        self.obligations.clone_pending()
288    }
289
290    fn pending_obligations_potentially_referencing_sub_root(
291        &self,
292        infcx: &InferCtxt<'tcx>,
293        vid: ty::TyVid,
294    ) -> PredicateObligations<'tcx> {
295        // `-Zdisable-fast-paths`: same gate as the other new-solver fast paths.
296        if infcx.tcx.disable_trait_solver_fast_paths() {
297            return self.obligations.clone_pending();
298        }
299        self.obligations.clone_pending_filtered(|(_, stalled_on)| {
300            let Some(stalled_on) = stalled_on else { return true };
301            // Don't reuse the sub-unification roots cached on `stalled_on`:
302            // a later sub-unification merge can have changed which root
303            // each stalled var belongs to, so the cached info can be stale.
304            // Walk `stalled_vars` and recompute the current root instead.
305            //
306            // Conservative here: if a stalled var no longer resolves to an
307            // infer var, some unification happened, so the goal is no longer
308            // stalled. Include it to be re-evaluated downstream.
309            stalled_on.stalled_vars.iter().filter_map(|arg| arg.as_type()).any(|ty| {
310                match *infcx.shallow_resolve(ty).kind() {
311                    ty::Infer(ty::TyVar(tv)) => infcx.sub_unification_table_root_var(tv) == vid,
312                    _ => true,
313                }
314            })
315        })
316    }
317
318    fn pending_obligations_potentially_referencing_float_infer(
319        &self,
320        infcx: &InferCtxt<'tcx>,
321    ) -> PredicateObligations<'tcx> {
322        // `-Zdisable-fast-paths`: same gate as the other new-solver fast paths.
323        if infcx.tcx.disable_trait_solver_fast_paths() {
324            return self.obligations.clone_pending();
325        }
326
327        self.obligations.clone_pending_filtered(|(_, stalled_on)| {
328            let Some(stalled_on) = stalled_on else { return true };
329            // If the stalled vars don't have float infers, the nested goals won't
330            // have them either. We only create float infers for user written literals.
331            stalled_on
332                .stalled_vars
333                .iter()
334                .filter_map(|arg| arg.as_type())
335                .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(_))))
336        })
337    }
338
339    fn drain_stalled_obligations_for_coroutines(
340        &mut self,
341        infcx: &InferCtxt<'tcx>,
342    ) -> PredicateObligations<'tcx> {
343        let stalled_coroutines = match infcx.typing_mode_raw().assert_not_erased() {
344            TypingMode::Typeck { defining_opaque_types_and_generators } => {
345                defining_opaque_types_and_generators
346            }
347            TypingMode::Coherence
348            | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ }
349            | TypingMode::PostBorrowck { defined_opaque_types: _ }
350            | TypingMode::Reflection
351            | TypingMode::PostAnalysis
352            | TypingMode::Codegen => return Default::default(),
353        };
354
355        if stalled_coroutines.is_empty() {
356            return Default::default();
357        }
358
359        self.obligations
360            .drain_pending(|_, stalled_on| {
361                stalled_on.as_ref().is_some_and(|s| match s.stalled_certainty {
362                    Certainty::Maybe(MaybeInfo {
363                        cause: _,
364                        opaque_types_jank: _,
365                        stalled_on_coroutines: StalledOnCoroutines::Yes,
366                    }) => true,
367                    Certainty::Maybe(_) | Certainty::Yes => false,
368                })
369            })
370            .into_iter()
371            .map(|(o, _)| o)
372            .collect()
373    }
374}
375
376pub enum NextSolverError<'tcx> {
377    TrueError(PredicateObligation<'tcx>),
378    Ambiguity(PredicateObligation<'tcx>),
379    Overflow(PredicateObligation<'tcx>),
380}
381
382impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
383    fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
384        match error {
385            NextSolverError::TrueError(obligation) => {
386                fulfillment_error_for_no_solution(infcx, obligation)
387            }
388            NextSolverError::Ambiguity(obligation) => {
389                fulfillment_error_for_stalled(infcx, obligation)
390            }
391            NextSolverError::Overflow(obligation) => {
392                fulfillment_error_for_overflow(infcx, obligation)
393            }
394        }
395    }
396}
397
398impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
399    fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
400        match error {
401            NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
402            NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
403                ScrubbedTraitError::Ambiguity
404            }
405        }
406    }
407}
408
409// Some types are used a lot. Make sure they don't unintentionally get bigger.
410#[cfg(target_pointer_width = "64")]
411mod size_asserts {
412    use rustc_data_structures::static_assert_size;
413
414    use super::*;
415    // tidy-alphabetical-start
416    // Before #160005 this pair was greater than 128 bytes, which triggered the use of (slow)
417    // `memcpy` for moving elements of `PendingObligations`.
418    const _: [(); 104] =
    [();
            ::std::mem::size_of::<(PredicateObligation<'_>,
                    Option<GoalStalledOn<TyCtxt<'_>>>)>()];static_assert_size!((PredicateObligation<'_>, Option<GoalStalledOn<TyCtxt<'_>>>), 104);
419    // tidy-alphabetical-end
420}