rustc_trait_selection/solve/
fulfill.rs1use 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, TraitErrors,
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, SolverDelegateEvalExt as _, StalledOnCoroutines,
13};
14use thin_vec::ThinVec;
15use tracing::instrument;
16
17use self::derive_errors::*;
18use super::Certainty;
19use super::delegate::SolverDelegate;
20use crate::traits::{FulfillmentError, ScrubbedTraitError};
21
22mod derive_errors;
23
24type PendingObligations<'tcx> =
26 ThinVec<(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)>;
27
28pub struct FulfillmentCtxt<'tcx, E: 'tcx> {
40 obligations: ObligationStorage<'tcx>,
41
42 usable_in_snapshot: usize,
47 _errors: PhantomData<E>,
48}
49
50#[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)]
51struct ObligationStorage<'tcx> {
52 overflowed: Vec<PredicateObligation<'tcx>>,
58 pending: PendingObligations<'tcx>,
59}
60
61impl<'tcx> ObligationStorage<'tcx> {
62 fn register(
63 &mut self,
64 obligation: PredicateObligation<'tcx>,
65 stalled_on: Option<GoalStalledOn<TyCtxt<'tcx>>>,
66 ) {
67 self.pending.push((obligation, stalled_on));
68 }
69
70 fn has_pending_obligations(&self) -> bool {
71 !self.pending.is_empty() || !self.overflowed.is_empty()
72 }
73
74 fn clone_pending(&self) -> PredicateObligations<'tcx> {
75 let mut obligations: PredicateObligations<'tcx> =
76 self.pending.iter().map(|(o, _)| o.clone()).collect();
77 obligations.extend(self.overflowed.iter().cloned());
78 obligations
79 }
80
81 fn clone_pending_filtered<F>(&self, f: F) -> PredicateObligations<'tcx>
82 where
83 F: FnMut(&&(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)) -> bool,
84 {
85 let mut obligations: PredicateObligations<'tcx> =
86 self.pending.iter().filter(f).map(|(o, _)| o.clone()).collect();
87 obligations.extend(self.overflowed.iter().cloned());
88 obligations
89 }
90
91 fn drain_pending(
92 &mut self,
93 cond: impl Fn(&PredicateObligation<'tcx>, &Option<GoalStalledOn<TyCtxt<'tcx>>>) -> bool,
94 ) -> PendingObligations<'tcx> {
95 let (unstalled, pending) =
96 mem::take(&mut self.pending).into_iter().partition(|(o, s)| cond(o, s));
97 self.pending = pending;
98 unstalled
99 }
100
101 fn on_fulfillment_overflow(&mut self, infcx: &InferCtxt<'tcx>) {
102 infcx.probe(|_| {
103 self.overflowed.extend(
109 self.pending
110 .extract_if(.., |(o, stalled_on)| {
111 let goal = o.as_goal();
112 let result = <&SolverDelegate<'tcx>>::from(infcx).evaluate_root_goal(
113 goal,
114 o.cause.span,
115 stalled_on.take(),
116 );
117 #[allow(non_exhaustive_omitted_patterns)] match result {
Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }) => true,
_ => false,
}matches!(result, Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }))
118 })
119 .map(|(o, _)| o),
120 );
121 })
122 }
123}
124
125impl<'tcx, E: 'tcx> FulfillmentCtxt<'tcx, E> {
126 pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx, E> {
127 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!(
128 infcx.next_trait_solver(),
129 "new trait solver fulfillment context created when \
130 infcx is set up for old trait solver"
131 );
132 FulfillmentCtxt {
133 obligations: Default::default(),
134 usable_in_snapshot: infcx.num_open_snapshots(),
135 _errors: PhantomData,
136 }
137 }
138
139 fn inspect_evaluated_obligation(
140 infcx: &InferCtxt<'tcx>,
141 obligation: &PredicateObligation<'tcx>,
142 result: &Result<GoalEvaluation<TyCtxt<'tcx>>, NoSolution>,
143 ) {
144 if let Some(inspector) = infcx.obligation_inspector.get() {
145 let result = match result {
146 Ok(GoalEvaluation { certainty, .. }) => Ok(*certainty),
147 Err(NoSolution) => Err(NoSolution),
148 };
149 (inspector)(infcx, &obligation, result);
150 }
151 }
152}
153
154impl<'tcx, E> TraitEngine<'tcx, E> for FulfillmentCtxt<'tcx, E>
155where
156 E: FromSolverError<'tcx, NextSolverError<'tcx>>,
157{
158 #[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(158u32),
::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))]
159 fn register_predicate_obligation(
160 &mut self,
161 infcx: &InferCtxt<'tcx>,
162 obligation: PredicateObligation<'tcx>,
163 ) {
164 assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
165
166 let delegate = <&SolverDelegate<'tcx>>::from(infcx);
167 if let Some(GoalEvaluation { goal: _, certainty, has_changed: _, stalled_on }) =
168 compute_goal_fast_path(delegate, obligation.as_goal(), obligation.cause.span)
169 {
170 match certainty {
173 Certainty::Yes => {}
174 Certainty::Maybe(_) => {
175 self.obligations.register(obligation, stalled_on);
176 }
177 }
178 } else {
179 self.obligations.register(obligation, None);
180 }
181 }
182
183 #[inline]
184 fn collect_remaining_errors(&mut self, infcx: &InferCtxt<'tcx>) -> TraitErrors<E> {
185 if self.obligations.pending.is_empty() && self.obligations.overflowed.is_empty() {
186 TraitErrors::NoErrors
189 } else {
190 TraitErrors::HasErrors(collect_remaining_errors_impl(self, infcx))
191 }
192 }
193
194 fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> TraitErrors<E> {
195 {
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());
196 let mut errors = TraitErrors::NoErrors;
197 let delegate = <&SolverDelegate<'tcx>>::from(infcx);
198 loop {
199 let mut any_changed = false;
200 let mut overflowed = false;
201
202 self.obligations.pending.retain_mut(|(obligation, opt_stalled_on)| {
203 if overflowed {
204 return false;
205 }
206
207 if let Some(stalled_on) = opt_stalled_on
210 && delegate.goal_remains_stalled(stalled_on)
211 {
212 return true;
213 }
214
215 let result = delegate.evaluate_root_goal(
216 obligation.as_goal(),
217 obligation.cause.span,
218 opt_stalled_on.take(),
219 );
220 Self::inspect_evaluated_obligation(infcx, &obligation, &result);
221 let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
222 Ok(result) => result,
223 Err(NoSolution) => {
224 errors.push(E::from_solver_error(
225 infcx,
226 NextSolverError::TrueError(obligation.clone()),
227 ));
228 return false;
229 }
230 };
231
232 obligation.predicate = goal.predicate;
236 if has_changed == HasChanged::Yes {
237 obligation.recursion_depth += 1;
244
245 if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
246 overflowed = true;
250 return false;
251 } else {
252 any_changed = true;
253 }
254 }
255
256 match certainty {
257 Certainty::Yes => {
258 if infcx.in_hir_typeck
270 && (obligation.has_non_region_infer() || obligation.has_free_regions())
271 {
272 infcx.push_hir_typeck_potentially_region_dependent_goal(
273 obligation.clone(),
274 );
275 }
276 false
277 }
278 Certainty::Maybe(_) => {
279 *opt_stalled_on = stalled_on;
282 true
283 }
284 }
285 });
286 if overflowed {
287 self.obligations.on_fulfillment_overflow(infcx);
288 return errors;
290 }
291
292 if !any_changed {
293 break;
294 }
295 }
296
297 errors
298 }
299
300 fn has_pending_obligations(&self) -> bool {
301 self.obligations.has_pending_obligations()
302 }
303
304 fn pending_obligations(&self) -> PredicateObligations<'tcx> {
305 self.obligations.clone_pending()
306 }
307
308 fn pending_obligations_potentially_referencing_sub_root(
309 &self,
310 infcx: &InferCtxt<'tcx>,
311 vid: ty::TyVid,
312 ) -> PredicateObligations<'tcx> {
313 if infcx.tcx.disable_trait_solver_fast_paths() {
315 return self.obligations.clone_pending();
316 }
317 self.obligations.clone_pending_filtered(|(_, stalled_on)| {
318 let Some(stalled_on) = stalled_on else { return true };
319 stalled_on.stalled_vars.iter().filter_map(|arg| arg.as_type(infcx.tcx)).any(|ty| {
328 match *infcx.shallow_resolve(ty).kind() {
329 ty::Infer(ty::TyVar(tv)) => infcx.sub_unification_table_root_var(tv) == vid,
330 _ => true,
331 }
332 })
333 })
334 }
335
336 fn pending_obligations_potentially_referencing_float_infer(
337 &self,
338 infcx: &InferCtxt<'tcx>,
339 ) -> PredicateObligations<'tcx> {
340 if infcx.tcx.disable_trait_solver_fast_paths() {
342 return self.obligations.clone_pending();
343 }
344
345 self.obligations.clone_pending_filtered(|(_, stalled_on)| {
346 let Some(stalled_on) = stalled_on else { return true };
347 stalled_on
350 .stalled_vars
351 .iter()
352 .filter_map(|arg| arg.as_type(infcx.tcx))
353 .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(_))))
354 })
355 }
356
357 fn drain_stalled_obligations_for_coroutines(
358 &mut self,
359 infcx: &InferCtxt<'tcx>,
360 ) -> PredicateObligations<'tcx> {
361 let stalled_coroutines = match infcx.typing_mode_raw().assert_not_erased() {
362 TypingMode::Typeck { defining_opaque_types_and_generators } => {
363 defining_opaque_types_and_generators
364 }
365 TypingMode::Coherence
366 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ }
367 | TypingMode::PostBorrowck { defined_opaque_types: _ }
368 | TypingMode::Reflection
369 | TypingMode::PostAnalysis
370 | TypingMode::Codegen => return Default::default(),
371 };
372
373 if stalled_coroutines.is_empty() {
374 return Default::default();
375 }
376
377 self.obligations
378 .drain_pending(|_, stalled_on| {
379 stalled_on.as_ref().is_some_and(|s| {
380 match s.stalled_maybe_info.stalled_on_coroutines {
381 StalledOnCoroutines::Yes => true,
382 StalledOnCoroutines::No => false,
383 }
384 })
385 })
386 .into_iter()
387 .map(|(o, _)| o)
388 .collect()
389 }
390}
391
392#[cold]
393#[inline(never)]
394fn collect_remaining_errors_impl<'tcx, E>(
395 cx: &mut FulfillmentCtxt<'tcx, E>,
396 infcx: &InferCtxt<'tcx>,
397) -> ThinVec<E>
398where
399 E: FromSolverError<'tcx, NextSolverError<'tcx>>,
400{
401 cx.obligations
402 .pending
403 .drain(..)
404 .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
405 .chain(
406 cx.obligations
407 .overflowed
408 .drain(..)
409 .map(|obligation| NextSolverError::Overflow(obligation)),
410 )
411 .map(|e| E::from_solver_error(infcx, e))
412 .collect()
413}
414
415pub enum NextSolverError<'tcx> {
416 TrueError(PredicateObligation<'tcx>),
417 Ambiguity(PredicateObligation<'tcx>),
418 Overflow(PredicateObligation<'tcx>),
419}
420
421impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
422 fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
423 match error {
424 NextSolverError::TrueError(obligation) => {
425 fulfillment_error_for_no_solution(infcx, obligation)
426 }
427 NextSolverError::Ambiguity(obligation) => {
428 fulfillment_error_for_stalled(infcx, obligation)
429 }
430 NextSolverError::Overflow(obligation) => {
431 fulfillment_error_for_overflow(infcx, obligation)
432 }
433 }
434 }
435}
436
437impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
438 fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
439 match error {
440 NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
441 NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
442 ScrubbedTraitError::Ambiguity
443 }
444 }
445 }
446}
447
448#[cfg(target_pointer_width = "64")]
450mod size_asserts {
451 use rustc_data_structures::static_assert_size;
452
453 use super::*;
454 const _: [(); 104] =
[();
::std::mem::size_of::<(PredicateObligation<'_>,
Option<GoalStalledOn<TyCtxt<'_>>>)>()];static_assert_size!((PredicateObligation<'_>, Option<GoalStalledOn<TyCtxt<'_>>>), 104);
458 }