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, TyVid, 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_potentially_referencing_sub_root(
83 &self,
84 infcx: &InferCtxt<'tcx>,
85 vid: TyVid,
86 ) -> PredicateObligations<'tcx> {
87 let mut obligations: PredicateObligations<'tcx> = self
88 .pending
89 .iter()
90 .filter(|(_, stalled_on)| {
91 let Some(stalled_on) = stalled_on else { return true };
92 stalled_on.stalled_vars.iter().filter_map(|arg| arg.as_type()).any(
101 |ty| match *infcx.shallow_resolve(ty).kind() {
102 ty::Infer(ty::TyVar(tv)) => infcx.sub_unification_table_root_var(tv) == vid,
103 _ => true,
104 },
105 )
106 })
107 .map(|(o, _)| o.clone())
108 .collect();
109 obligations.extend(self.overflowed.iter().cloned());
110 obligations
111 }
112
113 fn drain_pending(
114 &mut self,
115 cond: impl Fn(&PredicateObligation<'tcx>, &Option<GoalStalledOn<TyCtxt<'tcx>>>) -> bool,
116 ) -> PendingObligations<'tcx> {
117 let (unstalled, pending) =
118 mem::take(&mut self.pending).into_iter().partition(|(o, s)| cond(o, s));
119 self.pending = pending;
120 unstalled
121 }
122
123 fn on_fulfillment_overflow(&mut self, infcx: &InferCtxt<'tcx>) {
124 infcx.probe(|_| {
125 self.overflowed.extend(
131 self.pending
132 .extract_if(.., |(o, stalled_on)| {
133 let goal = o.as_goal();
134 let result = <&SolverDelegate<'tcx>>::from(infcx).evaluate_root_goal(
135 goal,
136 o.cause.span,
137 stalled_on.take(),
138 );
139 #[allow(non_exhaustive_omitted_patterns)] match result {
Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }) => true,
_ => false,
}matches!(result, Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }))
140 })
141 .map(|(o, _)| o),
142 );
143 })
144 }
145}
146
147impl<'tcx, E: 'tcx> FulfillmentCtxt<'tcx, E> {
148 pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx, E> {
149 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!(
150 infcx.next_trait_solver(),
151 "new trait solver fulfillment context created when \
152 infcx is set up for old trait solver"
153 );
154 FulfillmentCtxt {
155 obligations: Default::default(),
156 usable_in_snapshot: infcx.num_open_snapshots(),
157 _errors: PhantomData,
158 }
159 }
160
161 fn inspect_evaluated_obligation(
162 &self,
163 infcx: &InferCtxt<'tcx>,
164 obligation: &PredicateObligation<'tcx>,
165 result: &Result<GoalEvaluation<TyCtxt<'tcx>>, NoSolution>,
166 ) {
167 if let Some(inspector) = infcx.obligation_inspector.get() {
168 let result = match result {
169 Ok(GoalEvaluation { certainty, .. }) => Ok(*certainty),
170 Err(NoSolution) => Err(NoSolution),
171 };
172 (inspector)(infcx, &obligation, result);
173 }
174 }
175}
176
177impl<'tcx, E> TraitEngine<'tcx, E> for FulfillmentCtxt<'tcx, E>
178where
179 E: FromSolverError<'tcx, NextSolverError<'tcx>>,
180{
181 #[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(181u32),
::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))]
182 fn register_predicate_obligation(
183 &mut self,
184 infcx: &InferCtxt<'tcx>,
185 obligation: PredicateObligation<'tcx>,
186 ) {
187 assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
188
189 let delegate = <&SolverDelegate<'tcx>>::from(infcx);
190 if let Some(GoalEvaluation { goal: _, certainty, has_changed: _, stalled_on }) =
191 compute_goal_fast_path(delegate, obligation.as_goal(), obligation.cause.span)
192 {
193 match certainty {
196 Certainty::Yes => {}
197 Certainty::Maybe(_) => {
198 self.obligations.register(obligation, stalled_on);
199 }
200 }
201 } else {
202 self.obligations.register(obligation, None);
203 }
204 }
205
206 fn collect_remaining_errors(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
207 self.obligations
208 .pending
209 .drain(..)
210 .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
211 .chain(
212 self.obligations
213 .overflowed
214 .drain(..)
215 .map(|obligation| NextSolverError::Overflow(obligation)),
216 )
217 .map(|e| E::from_solver_error(infcx, e))
218 .collect()
219 }
220
221 fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
222 {
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());
223 let mut errors = Vec::new();
224 loop {
225 let mut any_changed = false;
226 for (mut obligation, stalled_on) in self.obligations.drain_pending(|_, _| true) {
227 let goal = obligation.as_goal();
228 let delegate = <&SolverDelegate<'tcx>>::from(infcx);
229
230 let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
231 self.inspect_evaluated_obligation(infcx, &obligation, &result);
232 let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
233 Ok(result) => result,
234 Err(NoSolution) => {
235 errors.push(E::from_solver_error(
236 infcx,
237 NextSolverError::TrueError(obligation),
238 ));
239 continue;
240 }
241 };
242
243 obligation.predicate = goal.predicate;
247 if has_changed == HasChanged::Yes {
248 obligation.recursion_depth += 1;
255
256 if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
257 self.obligations.on_fulfillment_overflow(infcx);
258 return errors;
260 } else {
261 any_changed = true;
262 }
263 }
264
265 match certainty {
266 Certainty::Yes => {
267 if infcx.in_hir_typeck
279 && (obligation.has_non_region_infer() || obligation.has_free_regions())
280 {
281 infcx.push_hir_typeck_potentially_region_dependent_goal(obligation);
282 }
283 }
284 Certainty::Maybe(_) => self.obligations.register(obligation, stalled_on),
285 }
286 }
287
288 if !any_changed {
289 break;
290 }
291 }
292
293 errors
294 }
295
296 fn has_pending_obligations(&self) -> bool {
297 self.obligations.has_pending_obligations()
298 }
299
300 fn pending_obligations(&self) -> PredicateObligations<'tcx> {
301 self.obligations.clone_pending()
302 }
303
304 fn pending_obligations_potentially_referencing_sub_root(
305 &self,
306 infcx: &InferCtxt<'tcx>,
307 vid: ty::TyVid,
308 ) -> PredicateObligations<'tcx> {
309 if infcx.tcx.disable_trait_solver_fast_paths() {
311 return self.obligations.clone_pending();
312 }
313 self.obligations.clone_pending_potentially_referencing_sub_root(infcx, vid)
314 }
315
316 fn drain_stalled_obligations_for_coroutines(
317 &mut self,
318 infcx: &InferCtxt<'tcx>,
319 ) -> PredicateObligations<'tcx> {
320 let stalled_coroutines = match infcx.typing_mode_raw().assert_not_erased() {
321 TypingMode::Typeck { defining_opaque_types_and_generators } => {
322 defining_opaque_types_and_generators
323 }
324 TypingMode::Coherence
325 | TypingMode::PostTypeckUntilBorrowck { defining_opaque_types: _ }
326 | TypingMode::PostBorrowck { defined_opaque_types: _ }
327 | TypingMode::PostAnalysis
328 | TypingMode::Codegen => return Default::default(),
329 };
330
331 if stalled_coroutines.is_empty() {
332 return Default::default();
333 }
334
335 self.obligations
336 .drain_pending(|_, stalled_on| {
337 stalled_on.as_ref().is_some_and(|s| match s.stalled_certainty {
338 Certainty::Maybe(MaybeInfo {
339 cause: _,
340 opaque_types_jank: _,
341 stalled_on_coroutines: StalledOnCoroutines::Yes,
342 }) => true,
343 Certainty::Maybe(_) | Certainty::Yes => false,
344 })
345 })
346 .into_iter()
347 .map(|(o, _)| o)
348 .collect()
349 }
350}
351
352pub enum NextSolverError<'tcx> {
353 TrueError(PredicateObligation<'tcx>),
354 Ambiguity(PredicateObligation<'tcx>),
355 Overflow(PredicateObligation<'tcx>),
356}
357
358impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
359 fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
360 match error {
361 NextSolverError::TrueError(obligation) => {
362 fulfillment_error_for_no_solution(infcx, obligation)
363 }
364 NextSolverError::Ambiguity(obligation) => {
365 fulfillment_error_for_stalled(infcx, obligation)
366 }
367 NextSolverError::Overflow(obligation) => {
368 fulfillment_error_for_overflow(infcx, obligation)
369 }
370 }
371 }
372}
373
374impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
375 fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
376 match error {
377 NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
378 NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
379 ScrubbedTraitError::Ambiguity
380 }
381 }
382 }
383}