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,
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
25type PendingObligations<'tcx> =
27 ThinVec<(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)>;
28
29pub struct FulfillmentCtxt<'tcx, E: 'tcx> {
41 obligations: ObligationStorage<'tcx>,
42
43 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 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 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 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 self.obligations
187 .pending
188 .drain(..)
189 .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
190 .chain(
191 self.obligations
192 .overflowed
193 .drain(..)
194 .map(|obligation| NextSolverError::Overflow(obligation)),
195 )
196 .map(|e| E::from_solver_error(infcx, e))
197 .collect()
198 }
199
200 fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
201 {
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());
202 let mut errors = Vec::new();
203 loop {
204 let mut any_changed = false;
205 for (mut obligation, stalled_on) in self.obligations.drain_pending(|_, _| true) {
206 let goal = obligation.as_goal();
207 let delegate = <&SolverDelegate<'tcx>>::from(infcx);
208
209 let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
210 self.inspect_evaluated_obligation(infcx, &obligation, &result);
211 let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
212 Ok(result) => result,
213 Err(NoSolution) => {
214 errors.push(E::from_solver_error(
215 infcx,
216 NextSolverError::TrueError(obligation),
217 ));
218 continue;
219 }
220 };
221
222 obligation.predicate = goal.predicate;
226 if has_changed == HasChanged::Yes {
227 obligation.recursion_depth += 1;
234
235 if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
236 self.obligations.on_fulfillment_overflow(infcx);
237 return errors;
239 } else {
240 any_changed = true;
241 }
242 }
243
244 match certainty {
245 Certainty::Yes => {
246 if infcx.in_hir_typeck
258 && (obligation.has_non_region_infer() || obligation.has_free_regions())
259 {
260 infcx.push_hir_typeck_potentially_region_dependent_goal(obligation);
261 }
262 }
263 Certainty::Maybe(_) => self.obligations.register(obligation, stalled_on),
264 }
265 }
266
267 if !any_changed {
268 break;
269 }
270 }
271
272 errors
273 }
274
275 fn has_pending_obligations(&self) -> bool {
276 self.obligations.has_pending_obligations()
277 }
278
279 fn pending_obligations(&self) -> PredicateObligations<'tcx> {
280 self.obligations.clone_pending()
281 }
282
283 fn pending_obligations_potentially_referencing_sub_root(
284 &self,
285 infcx: &InferCtxt<'tcx>,
286 vid: ty::TyVid,
287 ) -> PredicateObligations<'tcx> {
288 if infcx.tcx.disable_trait_solver_fast_paths() {
290 return self.obligations.clone_pending();
291 }
292 self.obligations.clone_pending_filtered(|(_, stalled_on)| {
293 let Some(stalled_on) = stalled_on else { return true };
294 stalled_on.stalled_vars.iter().filter_map(|arg| arg.as_type()).any(|ty| {
303 match *infcx.shallow_resolve(ty).kind() {
304 ty::Infer(ty::TyVar(tv)) => infcx.sub_unification_table_root_var(tv) == vid,
305 _ => true,
306 }
307 })
308 })
309 }
310
311 fn pending_obligations_potentially_referencing_float_infer(
312 &self,
313 infcx: &InferCtxt<'tcx>,
314 ) -> PredicateObligations<'tcx> {
315 if infcx.tcx.disable_trait_solver_fast_paths() {
317 return self.obligations.clone_pending();
318 }
319
320 self.obligations.clone_pending_filtered(|(_, stalled_on)| {
321 let Some(stalled_on) = stalled_on else { return true };
322 stalled_on
325 .stalled_vars
326 .iter()
327 .filter_map(|arg| arg.as_type())
328 .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(_))))
329 })
330 }
331
332 fn drain_stalled_obligations_for_coroutines(
333 &mut self,
334 infcx: &InferCtxt<'tcx>,
335 ) -> PredicateObligations<'tcx> {
336 let stalled_coroutines = match infcx.typing_mode_raw().assert_not_erased() {
337 TypingMode::Typeck { defining_opaque_types_and_generators } => {
338 defining_opaque_types_and_generators
339 }
340 TypingMode::Coherence
341 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ }
342 | TypingMode::PostBorrowck { defined_opaque_types: _ }
343 | TypingMode::Reflection
344 | TypingMode::PostAnalysis
345 | TypingMode::Codegen => return Default::default(),
346 };
347
348 if stalled_coroutines.is_empty() {
349 return Default::default();
350 }
351
352 self.obligations
353 .drain_pending(|_, stalled_on| {
354 stalled_on.as_ref().is_some_and(|s| match s.stalled_certainty {
355 Certainty::Maybe(MaybeInfo {
356 cause: _,
357 opaque_types_jank: _,
358 stalled_on_coroutines: StalledOnCoroutines::Yes,
359 }) => true,
360 Certainty::Maybe(_) | Certainty::Yes => false,
361 })
362 })
363 .into_iter()
364 .map(|(o, _)| o)
365 .collect()
366 }
367}
368
369pub enum NextSolverError<'tcx> {
370 TrueError(PredicateObligation<'tcx>),
371 Ambiguity(PredicateObligation<'tcx>),
372 Overflow(PredicateObligation<'tcx>),
373}
374
375impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
376 fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
377 match error {
378 NextSolverError::TrueError(obligation) => {
379 fulfillment_error_for_no_solution(infcx, obligation)
380 }
381 NextSolverError::Ambiguity(obligation) => {
382 fulfillment_error_for_stalled(infcx, obligation)
383 }
384 NextSolverError::Overflow(obligation) => {
385 fulfillment_error_for_overflow(infcx, obligation)
386 }
387 }
388 }
389}
390
391impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
392 fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
393 match error {
394 NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
395 NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
396 ScrubbedTraitError::Ambiguity
397 }
398 }
399 }
400}