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::{self, TyCtxt, TypeVisitableExt, TypingMode};
10use rustc_next_trait_solver::solve::fast_path::compute_goal_fast_path;
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 clone_pending_filtered<F>(&self, f: F) -> PredicateObligations<'tcx>
83where
84F: FnMut(&&(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)) -> bool,
85 {
86let mut obligations: PredicateObligations<'tcx> =
87self.pending.iter().filter(f).map(|(o, _)| o.clone()).collect();
88obligations.extend(self.overflowed.iter().cloned());
89obligations90 }
9192fn drain_pending(
93&mut self,
94 cond: impl Fn(&PredicateObligation<'tcx>, &Option<GoalStalledOn<TyCtxt<'tcx>>>) -> bool,
95 ) -> PendingObligations<'tcx> {
96let (unstalled, pending) =
97 mem::take(&mut self.pending).into_iter().partition(|(o, s)| cond(o, s));
98self.pending = pending;
99unstalled100 }
101102fn on_fulfillment_overflow(&mut self, infcx: &InferCtxt<'tcx>) {
103infcx.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.
109self.overflowed.extend(
110self.pending
111 .extract_if(.., |(o, stalled_on)| {
112let goal = o.as_goal();
113let result = <&SolverDelegate<'tcx>>::from(infcx).evaluate_root_goal(
114goal,
115o.cause.span,
116stalled_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}
125126impl<'tcx, E: 'tcx> FulfillmentCtxt<'tcx, E> {
127pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx, E> {
128if !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);
133FulfillmentCtxt {
134 obligations: Default::default(),
135 usable_in_snapshot: infcx.num_open_snapshots(),
136 _errors: PhantomData,
137 }
138 }
139140fn inspect_evaluated_obligation(
141&self,
142 infcx: &InferCtxt<'tcx>,
143 obligation: &PredicateObligation<'tcx>,
144 result: &Result<GoalEvaluation<TyCtxt<'tcx>>, NoSolution>,
145 ) {
146if let Some(inspector) = infcx.obligation_inspector.get() {
147let result = match result {
148Ok(GoalEvaluation { certainty, .. }) => Ok(*certainty),
149Err(NoSolution) => Err(NoSolution),
150 };
151 (inspector)(infcx, &obligation, result);
152 }
153 }
154}
155156impl<'tcx, E> TraitEngine<'tcx, E> for FulfillmentCtxt<'tcx, E>
157where
158E: 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))]161fn register_predicate_obligation(
162&mut self,
163 infcx: &InferCtxt<'tcx>,
164 obligation: PredicateObligation<'tcx>,
165 ) {
166assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
167168let delegate = <&SolverDelegate<'tcx>>::from(infcx);
169if 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.
174match certainty {
175 Certainty::Yes => {}
176 Certainty::Maybe(_) => {
177self.obligations.register(obligation, stalled_on);
178 }
179 }
180 } else {
181self.obligations.register(obligation, None);
182 }
183 }
184185fn collect_remaining_errors(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
186#[allow(clippy::iter_skip_zero)]
187self.obligations
188 .pending
189 .drain(..)
190 .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
191 .chain(
192self.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 }
206207fn 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());
209let mut errors = Vec::new();
210loop {
211let mut any_changed = false;
212for (mut obligation, stalled_on) in mem::take(&mut self.obligations.pending) {
213let goal = obligation.as_goal();
214let delegate = <&SolverDelegate<'tcx>>::from(infcx);
215216let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
217self.inspect_evaluated_obligation(infcx, &obligation, &result);
218let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
219Ok(result) => result,
220Err(NoSolution) => {
221 errors.push(E::from_solver_error(
222 infcx,
223 NextSolverError::TrueError(obligation),
224 ));
225continue;
226 }
227 };
228229// 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.
232obligation.predicate = goal.predicate;
233if 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.
240obligation.recursion_depth += 1;
241242if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
243self.obligations.on_fulfillment_overflow(infcx);
244// Only return true errors that we have accumulated while processing.
245return errors;
246 } else {
247 any_changed = true;
248 }
249 }
250251match 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.
264if 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 }
273274if !any_changed {
275break;
276 }
277 }
278279errors280 }
281282fn has_pending_obligations(&self) -> bool {
283self.obligations.has_pending_obligations()
284 }
285286fn pending_obligations(&self) -> PredicateObligations<'tcx> {
287self.obligations.clone_pending()
288 }
289290fn 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.
296if infcx.tcx.disable_trait_solver_fast_paths() {
297return self.obligations.clone_pending();
298 }
299self.obligations.clone_pending_filtered(|(_, stalled_on)| {
300let Some(stalled_on) = stalled_onelse { 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.
309stalled_on.stalled_vars.iter().filter_map(|arg| arg.as_type()).any(|ty| {
310match *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 }
317318fn 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.
323if infcx.tcx.disable_trait_solver_fast_paths() {
324return self.obligations.clone_pending();
325 }
326327self.obligations.clone_pending_filtered(|(_, stalled_on)| {
328let Some(stalled_on) = stalled_onelse { 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.
331stalled_on332 .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 }
338339fn drain_stalled_obligations_for_coroutines(
340&mut self,
341 infcx: &InferCtxt<'tcx>,
342 ) -> PredicateObligations<'tcx> {
343let stalled_coroutines = match infcx.typing_mode_raw().assert_not_erased() {
344TypingMode::Typeck { defining_opaque_types_and_generators } => {
345defining_opaque_types_and_generators346 }
347TypingMode::Coherence348 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ }
349 | TypingMode::PostBorrowck { defined_opaque_types: _ }
350 | TypingMode::Reflection351 | TypingMode::PostAnalysis352 | TypingMode::Codegen => return Default::default(),
353 };
354355if stalled_coroutines.is_empty() {
356return Default::default();
357 }
358359self.obligations
360 .drain_pending(|_, stalled_on| {
361stalled_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}
375376pub enum NextSolverError<'tcx> {
377 TrueError(PredicateObligation<'tcx>),
378 Ambiguity(PredicateObligation<'tcx>),
379 Overflow(PredicateObligation<'tcx>),
380}
381382impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
383fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
384match error {
385 NextSolverError::TrueError(obligation) => {
386fulfillment_error_for_no_solution(infcx, obligation)
387 }
388 NextSolverError::Ambiguity(obligation) => {
389fulfillment_error_for_stalled(infcx, obligation)
390 }
391 NextSolverError::Overflow(obligation) => {
392fulfillment_error_for_overflow(infcx, obligation)
393 }
394 }
395 }
396}
397398impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
399fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
400match error {
401 NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
402 NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
403 ScrubbedTraitError::Ambiguity404 }
405 }
406 }
407}
408409// Some types are used a lot. Make sure they don't unintentionally get bigger.
410#[cfg(target_pointer_width = "64")]
411mod size_asserts {
412use rustc_data_structures::static_assert_size;
413414use 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`.
418const _: [(); 104] =
[();
::std::mem::size_of::<(PredicateObligation<'_>,
Option<GoalStalledOn<TyCtxt<'_>>>)>()];static_assert_size!((PredicateObligation<'_>, Option<GoalStalledOn<TyCtxt<'_>>>), 104);
419// tidy-alphabetical-end
420}