-
-
Notifications
You must be signed in to change notification settings - Fork 15.4k
Move fulfillment into rustc_next_trait_solver #160485
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
amirHdev
wants to merge
1
commit into
rust-lang:main
Choose a base branch
from
amirHdev:move-fulfill-next-solver
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,304 @@ | ||
| use rustc_type_ir::solve::fulfill::FulfillmentObligation; | ||
| use rustc_type_ir::solve::{Certainty, Goal, NoSolution}; | ||
| use rustc_type_ir::{InferCtxtLike as _, Interner}; | ||
| use thin_vec::ThinVec; | ||
|
|
||
| use super::fast_path::compute_goal_fast_path; | ||
| use super::{ | ||
| GoalEvaluation, GoalStalledOn, HasChanged, SolverDelegate, SolverDelegateEvalExt as _, | ||
| }; | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub enum NextSolverError<O> { | ||
| TrueError(O), | ||
| Ambiguity(O), | ||
| Overflow(O), | ||
| } | ||
|
|
||
| /// Controls when fulfillment detects recursion overflow. | ||
| /// | ||
| /// rustc currently checks after a goal makes inference progress, while | ||
| /// rust-analyzer checks before evaluating an obligation which has already | ||
| /// reached the recursion limit. | ||
| #[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| pub enum FulfillmentOverflowMode { | ||
| /// Check after a goal makes inference progress. | ||
| AfterProgress, | ||
|
|
||
| /// Check before evaluating an obligation at the recursion limit. | ||
| BeforeEvaluation, | ||
| } | ||
|
|
||
| // FIXME: Do we need to use a `ThinVec` here? | ||
| type PendingObligations<I, O> = ThinVec<(O, Option<GoalStalledOn<I>>)>; | ||
|
|
||
| #[derive(Debug)] | ||
| struct ObligationStorage<I: Interner, O> { | ||
| /// Obligations which resulted in overflow in fulfillment itself. | ||
| /// | ||
| /// We cannot eagerly return these as errors, so we instead store them here | ||
| /// to avoid recomputing them each time `try_evaluate_obligations` is called. | ||
| /// This also allows the frontend to construct the correct error for them. | ||
| overflowed: Vec<O>, | ||
|
|
||
| pending: PendingObligations<I, O>, | ||
| } | ||
|
|
||
| impl<I: Interner, O> Default for ObligationStorage<I, O> { | ||
| fn default() -> Self { | ||
| Self { overflowed: Vec::new(), pending: ThinVec::new() } | ||
| } | ||
| } | ||
|
|
||
| impl<I: Interner, O> ObligationStorage<I, O> { | ||
| fn register(&mut self, obligation: O, stalled_on: Option<GoalStalledOn<I>>) { | ||
| self.pending.push((obligation, stalled_on)); | ||
| } | ||
|
|
||
| fn has_pending_obligations(&self) -> bool { | ||
| !self.pending.is_empty() || !self.overflowed.is_empty() | ||
| } | ||
|
|
||
| fn clone_pending(&self) -> ThinVec<O> | ||
| where | ||
| O: Clone, | ||
| { | ||
| let mut obligations = | ||
| self.pending.iter().map(|(obligation, _)| obligation.clone()).collect::<ThinVec<_>>(); | ||
|
|
||
| obligations.extend(self.overflowed.iter().cloned()); | ||
| obligations | ||
| } | ||
|
|
||
| fn clone_pending_filtered<F>(&self, mut filter: F) -> ThinVec<O> | ||
| where | ||
| O: Clone, | ||
| F: FnMut(&O, &Option<GoalStalledOn<I>>) -> bool, | ||
| { | ||
| let mut obligations = self | ||
| .pending | ||
| .iter() | ||
| .filter_map(|(obligation, stalled_on)| { | ||
| filter(obligation, stalled_on).then(|| obligation.clone()) | ||
| }) | ||
| .collect::<ThinVec<_>>(); | ||
|
|
||
| obligations.extend(self.overflowed.iter().cloned()); | ||
| obligations | ||
| } | ||
|
|
||
| fn drain_pending<F>(&mut self, mut filter: F) -> ThinVec<O> | ||
| where | ||
| F: FnMut(&O, &Option<GoalStalledOn<I>>) -> bool, | ||
| { | ||
| let (drained, pending): (PendingObligations<I, O>, PendingObligations<I, O>) = | ||
| std::mem::take(&mut self.pending) | ||
| .into_iter() | ||
| .partition(|(obligation, stalled_on)| filter(obligation, stalled_on)); | ||
|
|
||
| self.pending = pending; | ||
|
|
||
| drained.into_iter().map(|(obligation, _)| obligation).collect() | ||
| } | ||
|
|
||
| fn collect_remaining_errors<E>(&mut self, map: impl FnMut(NextSolverError<O>) -> E) -> Vec<E> { | ||
| #[allow(clippy::iter_skip_zero)] | ||
| self.pending | ||
| .drain(..) | ||
| .map(|(obligation, _)| NextSolverError::Ambiguity(obligation)) | ||
| .chain(self.overflowed.drain(..).map(NextSolverError::Overflow)) | ||
| .map(map) | ||
| // Avoid `Vec::from_iter` specialization, which performs poorly | ||
| // when draining a `ThinVec`. See rust-lang/rust#160073. | ||
| .skip(0) | ||
| .collect() | ||
| } | ||
| } | ||
|
|
||
| /// A fulfillment engine using the new trait solver. | ||
| /// | ||
| /// This is mostly identical to how `evaluate_all` works inside of the solver, | ||
| /// except that it is possible to add new obligations later and the frontend | ||
| /// needs to retain its obligation representation for diagnostics. | ||
| /// | ||
| /// It is also likely that we want to use different data structures here, as | ||
| /// fulfillment deals with far more root goals than `evaluate_all`. | ||
| #[derive(Debug)] | ||
| pub struct FulfillmentCtxt<I: Interner, O: FulfillmentObligation<I>> { | ||
| obligations: ObligationStorage<I, O>, | ||
| } | ||
|
|
||
| impl<I: Interner, O: FulfillmentObligation<I>> Default for FulfillmentCtxt<I, O> { | ||
| fn default() -> Self { | ||
| Self { obligations: ObligationStorage::default() } | ||
| } | ||
| } | ||
|
|
||
| impl<I: Interner, O: FulfillmentObligation<I>> FulfillmentCtxt<I, O> { | ||
| pub fn new() -> Self { | ||
| Self { obligations: Default::default() } | ||
| } | ||
|
|
||
| pub fn register<D>(&mut self, delegate: &D, obligation: O) | ||
| where | ||
| D: SolverDelegate<Interner = I>, | ||
| { | ||
| if let Some(GoalEvaluation { certainty, stalled_on, .. }) = | ||
| compute_goal_fast_path(delegate, obligation.as_goal(), obligation.span()) | ||
| { | ||
| // If we can take the fast path, do not add a successful goal to | ||
| // the pending obligations. For `Certainty::Maybe`, retain the | ||
| // precise `stalled_on` information for later re-evaluation. | ||
| match certainty { | ||
| Certainty::Yes => {} | ||
| Certainty::Maybe(_) => { | ||
| self.obligations.register(obligation, stalled_on); | ||
| } | ||
| } | ||
| } else { | ||
| self.obligations.register(obligation, None); | ||
| } | ||
| } | ||
|
|
||
| fn on_fulfillment_overflow<D>(&mut self, delegate: &D) | ||
| where | ||
| D: SolverDelegate<Interner = I>, | ||
| { | ||
| delegate.probe(|| { | ||
| // IMPORTANT: we must not resolve any inference variables in the | ||
| // obligations, as this is all happening inside of a probe. The | ||
| // probe makes sure we collect every obligation involved in the | ||
| // overflow. Conceptually, we check which goals would change if we | ||
| // performed one more fulfillment iteration. | ||
| let overflowed = self | ||
| .obligations | ||
| .pending | ||
| .extract_if(.., |(obligation, stalled_on)| { | ||
| let result = delegate.evaluate_root_goal( | ||
| obligation.as_goal(), | ||
| obligation.span(), | ||
| stalled_on.take(), | ||
| ); | ||
|
|
||
| matches!(result, Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. })) | ||
| }) | ||
| .map(|(obligation, _)| obligation) | ||
| .collect::<Vec<_>>(); | ||
|
|
||
| self.obligations.overflowed.extend(overflowed); | ||
| }); | ||
| } | ||
|
|
||
| pub fn try_evaluate_obligations<D, Inspect, OnSuccess>( | ||
| &mut self, | ||
| delegate: &D, | ||
| overflow_mode: FulfillmentOverflowMode, | ||
| mut inspect: Inspect, | ||
| mut on_success: OnSuccess, | ||
| ) -> Vec<NextSolverError<O>> | ||
| where | ||
| D: SolverDelegate<Interner = I>, | ||
| Inspect: FnMut(&O, Goal<I, I::Predicate>, &Result<GoalEvaluation<I>, NoSolution>), | ||
| OnSuccess: FnMut(O), | ||
| { | ||
| let mut errors = Vec::new(); | ||
|
|
||
| loop { | ||
| let mut any_changed = false; | ||
|
|
||
| for (mut obligation, stalled_on) in std::mem::take(&mut self.obligations.pending) { | ||
| if overflow_mode == FulfillmentOverflowMode::BeforeEvaluation | ||
| && obligation.recursion_depth() >= delegate.cx().recursion_limit() | ||
| { | ||
| self.on_fulfillment_overflow(delegate); | ||
| return errors; | ||
| } | ||
|
|
||
| let goal = obligation.as_goal(); | ||
| let result = delegate.evaluate_root_goal(goal, obligation.span(), stalled_on); | ||
|
|
||
| inspect(&obligation, goal, &result); | ||
|
|
||
| let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result { | ||
| Ok(result) => result, | ||
| Err(NoSolution) => { | ||
| errors.push(NextSolverError::TrueError(obligation)); | ||
| continue; | ||
| } | ||
| }; | ||
|
|
||
| // We resolved the goal in `evaluate_root_goal`; retain the | ||
| // eagerly resolved predicate to avoid repeating this work in | ||
| // the next iteration. This does not resolve the inference | ||
| // variables constrained by evaluating the goal. | ||
| obligation.set_predicate(goal.predicate); | ||
|
|
||
| if has_changed == HasChanged::Yes { | ||
| // Track the number of times this root goal has resulted in | ||
| // inference progress. This does not precisely model the old | ||
| // solver's recursion depth, as fulfillment only processes | ||
| // root obligations, but it is a good approximation and | ||
| // should only overflow in pathological cases. | ||
| let depth = obligation.recursion_depth() + 1; | ||
| obligation.set_recursion_depth(depth); | ||
|
|
||
| if overflow_mode == FulfillmentOverflowMode::AfterProgress | ||
| && depth > delegate.cx().recursion_limit() | ||
| { | ||
| self.on_fulfillment_overflow(delegate); | ||
| // Only return true errors accumulated while processing. | ||
| return errors; | ||
| } | ||
|
|
||
| any_changed = true; | ||
| } | ||
|
|
||
| match certainty { | ||
| Certainty::Yes => on_success(obligation), | ||
| Certainty::Maybe(_) => { | ||
| self.obligations.register(obligation, stalled_on); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if !any_changed { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| errors | ||
| } | ||
|
|
||
| pub fn has_pending_obligations(&self) -> bool { | ||
| self.obligations.has_pending_obligations() | ||
| } | ||
|
|
||
| pub fn pending_obligations(&self) -> ThinVec<O> | ||
| where | ||
| O: Clone, | ||
| { | ||
| self.obligations.clone_pending() | ||
| } | ||
|
|
||
| pub fn pending_obligations_filtered<F>(&self, filter: F) -> ThinVec<O> | ||
| where | ||
| O: Clone, | ||
| F: FnMut(&O, &Option<GoalStalledOn<I>>) -> bool, | ||
| { | ||
| self.obligations.clone_pending_filtered(filter) | ||
| } | ||
|
|
||
| pub fn drain_pending_obligations<F>(&mut self, filter: F) -> ThinVec<O> | ||
| where | ||
| F: FnMut(&O, &Option<GoalStalledOn<I>>) -> bool, | ||
| { | ||
| self.obligations.drain_pending(filter) | ||
| } | ||
|
|
||
| pub fn collect_remaining_errors<E>( | ||
| &mut self, | ||
| map: impl FnMut(NextSolverError<O>) -> E, | ||
| ) -> Vec<E> { | ||
| self.obligations.collect_remaining_errors(map) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Firstly I'm not overly familiar with this area of codebase, however, if I am not mistaken it looks like the type is
PredicateObligation<'tcx>? Or anObligationdo we have something thatOneeds to implement or be constrained by? This applies to all instances ofO, not exclusively this type definition.View changes since the review
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As shared engine only require the
<I>whilePredicateObligation<'tcx>not required.I moved that bound onto
FulfillmentCtxt<I, O>itself insteadThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you cut yourself off mid-sentence?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry for the unclear wording :)
for rustc
OisPredicateObligation<'tcx>but the shared engine only requiresO: FulfillmentObligation<I>which moved that bound onto FulfillmentCtxt<I, O> itself now and it applies to every instance of the context.