1use std::marker::PhantomData;
2use std::mem;
34use rustc_infer::infer::InferCtxt;
5use rustc_infer::traits::query::NoSolution;
6use rustc_infer::traits::{
7FromSolverError, PredicateObligation, PredicateObligations, TraitEngine,
8};
9use rustc_middle::ty::{TyCtxt, TypeVisitableExt, TypingMode};
10use rustc_next_trait_solver::delegate::SolverDelegateas _;
11use rustc_next_trait_solver::solve::{
12GoalEvaluation, GoalStalledOn, HasChanged, MaybeInfo, SolverDelegateEvalExtas _,
13StalledOnCoroutines,
14};
15use thin_vec::ThinVec;
16use tracing::instrument;
1718use self::derive_errors::*;
19use super::Certainty;
20use super::delegate::SolverDelegate;
21use crate::traits::{FulfillmentError, ScrubbedTraitError};
2223mod derive_errors;
2425// FIXME: Do we need to use a `ThinVec` here?
26type PendingObligations<'tcx> =
27ThinVec<(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)>;
2829/// 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>,
4243/// 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.
47usable_in_snapshot: usize,
48 _errors: PhantomData<E>,
49}
5051#[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.
58overflowed: Vec<PredicateObligation<'tcx>>,
59 pending: PendingObligations<'tcx>,
60}
6162impl<'tcx> ObligationStorage<'tcx> {
63fn register(
64&mut self,
65 obligation: PredicateObligation<'tcx>,
66 stalled_on: Option<GoalStalledOn<TyCtxt<'tcx>>>,
67 ) {
68self.pending.push((obligation, stalled_on));
69 }
7071fn has_pending_obligations(&self) -> bool {
72 !self.pending.is_empty() || !self.overflowed.is_empty()
73 }
7475fn clone_pending(&self) -> PredicateObligations<'tcx> {
76let mut obligations: PredicateObligations<'tcx> =
77self.pending.iter().map(|(o, _)| o.clone()).collect();
78obligations.extend(self.overflowed.iter().cloned());
79obligations80 }
8182fn drain_pending(
83&mut self,
84 cond: impl Fn(&PredicateObligation<'tcx>, &Option<GoalStalledOn<TyCtxt<'tcx>>>) -> bool,
85 ) -> PendingObligations<'tcx> {
86let (unstalled, pending) =
87 mem::take(&mut self.pending).into_iter().partition(|(o, s)| cond(o, s));
88self.pending = pending;
89unstalled90 }
9192fn on_fulfillment_overflow(&mut self, infcx: &InferCtxt<'tcx>) {
93infcx.probe(|_| {
94// IMPORTANT: we must not use solve any inference variables in the obligations
95 // as this is all happening inside of a probe. We use a probe to make sure
96 // we get all obligations involved in the overflow. We pretty much check: if
97 // we were to do another step of `try_evaluate_obligations`, which goals would
98 // change.
99self.overflowed.extend(
100self.pending
101 .extract_if(.., |(o, stalled_on)| {
102let goal = o.as_goal();
103let result = <&SolverDelegate<'tcx>>::from(infcx).evaluate_root_goal(
104goal,
105o.cause.span,
106stalled_on.take(),
107 );
108#[allow(non_exhaustive_omitted_patterns)] match result {
Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }) => true,
_ => false,
}matches!(result, Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }))109 })
110 .map(|(o, _)| o),
111 );
112 })
113 }
114}
115116impl<'tcx, E: 'tcx> FulfillmentCtxt<'tcx, E> {
117pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx, E> {
118if !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!(
119 infcx.next_trait_solver(),
120"new trait solver fulfillment context created when \
121 infcx is set up for old trait solver"
122);
123FulfillmentCtxt {
124 obligations: Default::default(),
125 usable_in_snapshot: infcx.num_open_snapshots(),
126 _errors: PhantomData,
127 }
128 }
129130fn inspect_evaluated_obligation(
131&self,
132 infcx: &InferCtxt<'tcx>,
133 obligation: &PredicateObligation<'tcx>,
134 result: &Result<GoalEvaluation<TyCtxt<'tcx>>, NoSolution>,
135 ) {
136if let Some(inspector) = infcx.obligation_inspector.get() {
137let result = match result {
138Ok(GoalEvaluation { certainty, .. }) => Ok(*certainty),
139Err(NoSolution) => Err(NoSolution),
140 };
141 (inspector)(infcx, &obligation, result);
142 }
143 }
144}
145146impl<'tcx, E> TraitEngine<'tcx, E> for FulfillmentCtxt<'tcx, E>
147where
148E: FromSolverError<'tcx, NextSolverError<'tcx>>,
149{
150#[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(150u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::solve::fulfill"),
::tracing_core::field::FieldSet::new(&["obligation"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
as &dyn 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);
}
}
};
self.obligations.register(obligation, None);
}
}
}#[instrument(level = "trace", skip(self, infcx))]151fn register_predicate_obligation(
152&mut self,
153 infcx: &InferCtxt<'tcx>,
154 obligation: PredicateObligation<'tcx>,
155 ) {
156assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
157self.obligations.register(obligation, None);
158 }
159160fn collect_remaining_errors(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
161self.obligations
162 .pending
163 .drain(..)
164 .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
165 .chain(
166self.obligations
167 .overflowed
168 .drain(..)
169 .map(|obligation| NextSolverError::Overflow(obligation)),
170 )
171 .map(|e| E::from_solver_error(infcx, e))
172 .collect()
173 }
174175fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
176match (&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());
177let mut errors = Vec::new();
178loop {
179let mut any_changed = false;
180for (mut obligation, stalled_on) in self.obligations.drain_pending(|_, _| true) {
181if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
182self.obligations.on_fulfillment_overflow(infcx);
183// Only return true errors that we have accumulated while processing.
184return errors;
185 }
186187let goal = obligation.as_goal();
188let delegate = <&SolverDelegate<'tcx>>::from(infcx);
189if let Some(certainty) =
190 delegate.compute_goal_fast_path(goal, obligation.cause.span)
191 {
192match certainty {
193// This fast path doesn't depend on region identity so it doesn't
194 // matter if the goal contains inference variables or not, so we
195 // don't need to call `push_hir_typeck_potentially_region_dependent_goal`
196 // here.
197 //
198 // Only goals proven via the trait solver should be region dependent.
199Certainty::Yes => {}
200 Certainty::Maybe(_) => {
201self.obligations.register(obligation, None);
202 }
203 }
204continue;
205 }
206207let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
208self.inspect_evaluated_obligation(infcx, &obligation, &result);
209let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
210Ok(result) => result,
211Err(NoSolution) => {
212 errors.push(E::from_solver_error(
213 infcx,
214 NextSolverError::TrueError(obligation),
215 ));
216continue;
217 }
218 };
219220// We've resolved the goal in `evaluate_root_goal`, avoid redoing this work
221 // in the next iteration. This does not resolve the inference variables
222 // constrained by evaluating the goal.
223obligation.predicate = goal.predicate;
224if has_changed == HasChanged::Yes {
225// We increment the recursion depth here to track the number of times
226 // this goal has resulted in inference progress. This doesn't precisely
227 // model the way that we track recursion depth in the old solver due
228 // to the fact that we only process root obligations, but it is a good
229 // approximation and should only result in fulfillment overflow in
230 // pathological cases.
231obligation.recursion_depth += 1;
232 any_changed = true;
233 }
234235match certainty {
236 Certainty::Yes => {
237// Goals may depend on structural identity. Region uniquification at the
238 // start of MIR borrowck may cause things to no longer be so, potentially
239 // causing an ICE.
240 //
241 // While we uniquify root goals in HIR this does not handle cases where
242 // regions are hidden inside of a type or const inference variable.
243 //
244 // FIXME(-Znext-solver): This does not handle inference variables hidden
245 // inside of an opaque type, e.g. if there's `Opaque = (?x, ?x)` in the
246 // storage, we can also rely on structural identity of `?x` even if we
247 // later uniquify it in MIR borrowck.
248if infcx.in_hir_typeck
249 && (obligation.has_non_region_infer() || obligation.has_free_regions())
250 {
251 infcx.push_hir_typeck_potentially_region_dependent_goal(obligation);
252 }
253 }
254 Certainty::Maybe(_) => self.obligations.register(obligation, stalled_on),
255 }
256 }
257258if !any_changed {
259break;
260 }
261 }
262263errors264 }
265266fn has_pending_obligations(&self) -> bool {
267self.obligations.has_pending_obligations()
268 }
269270fn pending_obligations(&self) -> PredicateObligations<'tcx> {
271self.obligations.clone_pending()
272 }
273274fn drain_stalled_obligations_for_coroutines(
275&mut self,
276 infcx: &InferCtxt<'tcx>,
277 ) -> PredicateObligations<'tcx> {
278let stalled_coroutines = match infcx.typing_mode() {
279TypingMode::Analysis { defining_opaque_types_and_generators } => {
280defining_opaque_types_and_generators281 }
282TypingMode::Coherence283 | TypingMode::Borrowck { defining_opaque_types: _ }
284 | TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ }
285 | TypingMode::PostAnalysis => return Default::default(),
286 };
287288if stalled_coroutines.is_empty() {
289return Default::default();
290 }
291292self.obligations
293 .drain_pending(|_, stalled_on| {
294stalled_on.as_ref().is_some_and(|s| match s.stalled_certainty {
295 Certainty::Maybe(MaybeInfo {
296 cause: _,
297 opaque_types_jank: _,
298 stalled_on_coroutines: StalledOnCoroutines::Yes,
299 }) => true,
300 Certainty::Maybe(_) | Certainty::Yes => false,
301 })
302 })
303 .into_iter()
304 .map(|(o, _)| o)
305 .collect()
306 }
307}
308309pub enum NextSolverError<'tcx> {
310 TrueError(PredicateObligation<'tcx>),
311 Ambiguity(PredicateObligation<'tcx>),
312 Overflow(PredicateObligation<'tcx>),
313}
314315impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
316fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
317match error {
318 NextSolverError::TrueError(obligation) => {
319fulfillment_error_for_no_solution(infcx, obligation)
320 }
321 NextSolverError::Ambiguity(obligation) => {
322fulfillment_error_for_stalled(infcx, obligation)
323 }
324 NextSolverError::Overflow(obligation) => {
325fulfillment_error_for_overflow(infcx, obligation)
326 }
327 }
328 }
329}
330331impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
332fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
333match error {
334 NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
335 NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
336 ScrubbedTraitError::Ambiguity337 }
338 }
339 }
340}