1use std::marker::PhantomData;
2use std::mem;
3use std::ops::ControlFlow;
45use rustc_hir::def_id::LocalDefId;
6use rustc_infer::infer::InferCtxt;
7use rustc_infer::traits::query::NoSolution;
8use rustc_infer::traits::{
9FromSolverError, PredicateObligation, PredicateObligations, TraitEngine,
10};
11use rustc_middle::ty::{
12self, DelayedSet, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
13TypingMode,
14};
15use rustc_next_trait_solver::delegate::SolverDelegateas _;
16use rustc_next_trait_solver::solve::{
17GoalEvaluation, GoalStalledOn, HasChanged, SolverDelegateEvalExtas _,
18};
19use rustc_span::Span;
20use thin_vec::ThinVec;
21use tracing::instrument;
2223use self::derive_errors::*;
24use super::Certainty;
25use super::delegate::SolverDelegate;
26use super::inspect::{self, InferCtxtProofTreeExt};
27use crate::traits::{FulfillmentError, ScrubbedTraitError};
2829mod derive_errors;
3031// FIXME: Do we need to use a `ThinVec` here?
32type PendingObligations<'tcx> =
33ThinVec<(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)>;
3435/// A trait engine using the new trait solver.
36///
37/// This is mostly identical to how `evaluate_all` works inside of the
38/// solver, except that the requirements are slightly different.
39///
40/// Unlike `evaluate_all` it is possible to add new obligations later on
41/// and we also have to track diagnostics information by using `Obligation`
42/// instead of `Goal`.
43///
44/// It is also likely that we want to use slightly different datastructures
45/// here as this will have to deal with far more root goals than `evaluate_all`.
46pub struct FulfillmentCtxt<'tcx, E: 'tcx> {
47 obligations: ObligationStorage<'tcx>,
4849/// The snapshot in which this context was created. Using the context
50 /// outside of this snapshot leads to subtle bugs if the snapshot
51 /// gets rolled back. Because of this we explicitly check that we only
52 /// use the context in exactly this snapshot.
53usable_in_snapshot: usize,
54 _errors: PhantomData<E>,
55}
5657#[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)]
58struct ObligationStorage<'tcx> {
59/// Obligations which resulted in an overflow in fulfillment itself.
60 ///
61 /// We cannot eagerly return these as error so we instead store them here
62 /// to avoid recomputing them each time `try_evaluate_obligations` is called.
63 /// This also allows us to return the correct `FulfillmentError` for them.
64overflowed: Vec<PredicateObligation<'tcx>>,
65 pending: PendingObligations<'tcx>,
66}
6768impl<'tcx> ObligationStorage<'tcx> {
69fn register(
70&mut self,
71 obligation: PredicateObligation<'tcx>,
72 stalled_on: Option<GoalStalledOn<TyCtxt<'tcx>>>,
73 ) {
74self.pending.push((obligation, stalled_on));
75 }
7677fn has_pending_obligations(&self) -> bool {
78 !self.pending.is_empty() || !self.overflowed.is_empty()
79 }
8081fn clone_pending(&self) -> PredicateObligations<'tcx> {
82let mut obligations: PredicateObligations<'tcx> =
83self.pending.iter().map(|(o, _)| o.clone()).collect();
84obligations.extend(self.overflowed.iter().cloned());
85obligations86 }
8788fn drain_pending(
89&mut self,
90 cond: impl Fn(&PredicateObligation<'tcx>) -> bool,
91 ) -> PendingObligations<'tcx> {
92let (unstalled, pending) =
93 mem::take(&mut self.pending).into_iter().partition(|(o, _)| cond(o));
94self.pending = pending;
95unstalled96 }
9798fn on_fulfillment_overflow(&mut self, infcx: &InferCtxt<'tcx>) {
99infcx.probe(|_| {
100// IMPORTANT: we must not use solve any inference variables in the obligations
101 // as this is all happening inside of a probe. We use a probe to make sure
102 // we get all obligations involved in the overflow. We pretty much check: if
103 // we were to do another step of `try_evaluate_obligations`, which goals would
104 // change.
105self.overflowed.extend(
106self.pending
107 .extract_if(.., |(o, stalled_on)| {
108let goal = o.as_goal();
109let result = <&SolverDelegate<'tcx>>::from(infcx).evaluate_root_goal(
110goal,
111o.cause.span,
112stalled_on.take(),
113 );
114#[allow(non_exhaustive_omitted_patterns)] match result {
Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }) => true,
_ => false,
}matches!(result, Ok(GoalEvaluation { has_changed: HasChanged::Yes, .. }))115 })
116 .map(|(o, _)| o),
117 );
118 })
119 }
120}
121122impl<'tcx, E: 'tcx> FulfillmentCtxt<'tcx, E> {
123pub fn new(infcx: &InferCtxt<'tcx>) -> FulfillmentCtxt<'tcx, E> {
124if !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!(
125 infcx.next_trait_solver(),
126"new trait solver fulfillment context created when \
127 infcx is set up for old trait solver"
128);
129FulfillmentCtxt {
130 obligations: Default::default(),
131 usable_in_snapshot: infcx.num_open_snapshots(),
132 _errors: PhantomData,
133 }
134 }
135136fn inspect_evaluated_obligation(
137&self,
138 infcx: &InferCtxt<'tcx>,
139 obligation: &PredicateObligation<'tcx>,
140 result: &Result<GoalEvaluation<TyCtxt<'tcx>>, NoSolution>,
141 ) {
142if let Some(inspector) = infcx.obligation_inspector.get() {
143let result = match result {
144Ok(GoalEvaluation { certainty, .. }) => Ok(*certainty),
145Err(NoSolution) => Err(NoSolution),
146 };
147 (inspector)(infcx, &obligation, result);
148 }
149 }
150}
151152impl<'tcx, E> TraitEngine<'tcx, E> for FulfillmentCtxt<'tcx, E>
153where
154E: FromSolverError<'tcx, NextSolverError<'tcx>>,
155{
156#[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(156u32),
::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))]157fn register_predicate_obligation(
158&mut self,
159 infcx: &InferCtxt<'tcx>,
160 obligation: PredicateObligation<'tcx>,
161 ) {
162assert_eq!(self.usable_in_snapshot, infcx.num_open_snapshots());
163self.obligations.register(obligation, None);
164 }
165166fn collect_remaining_errors(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
167self.obligations
168 .pending
169 .drain(..)
170 .map(|(obligation, _)| NextSolverError::Ambiguity(obligation))
171 .chain(
172self.obligations
173 .overflowed
174 .drain(..)
175 .map(|obligation| NextSolverError::Overflow(obligation)),
176 )
177 .map(|e| E::from_solver_error(infcx, e))
178 .collect()
179 }
180181fn try_evaluate_obligations(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<E> {
182match (&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());
183let mut errors = Vec::new();
184loop {
185let mut any_changed = false;
186for (mut obligation, stalled_on) in self.obligations.drain_pending(|_| true) {
187if !infcx.tcx.recursion_limit().value_within_limit(obligation.recursion_depth) {
188self.obligations.on_fulfillment_overflow(infcx);
189// Only return true errors that we have accumulated while processing.
190return errors;
191 }
192193let goal = obligation.as_goal();
194let delegate = <&SolverDelegate<'tcx>>::from(infcx);
195if let Some(certainty) =
196 delegate.compute_goal_fast_path(goal, obligation.cause.span)
197 {
198match certainty {
199// This fast path doesn't depend on region identity so it doesn't
200 // matter if the goal contains inference variables or not, so we
201 // don't need to call `push_hir_typeck_potentially_region_dependent_goal`
202 // here.
203 //
204 // Only goals proven via the trait solver should be region dependent.
205Certainty::Yes => {}
206 Certainty::Maybe { .. } => {
207self.obligations.register(obligation, None);
208 }
209 }
210continue;
211 }
212213let result = delegate.evaluate_root_goal(goal, obligation.cause.span, stalled_on);
214self.inspect_evaluated_obligation(infcx, &obligation, &result);
215let GoalEvaluation { goal, certainty, has_changed, stalled_on } = match result {
216Ok(result) => result,
217Err(NoSolution) => {
218 errors.push(E::from_solver_error(
219 infcx,
220 NextSolverError::TrueError(obligation),
221 ));
222continue;
223 }
224 };
225226// We've resolved the goal in `evaluate_root_goal`, avoid redoing this work
227 // in the next iteration. This does not resolve the inference variables
228 // constrained by evaluating the goal.
229obligation.predicate = goal.predicate;
230if has_changed == HasChanged::Yes {
231// We increment the recursion depth here to track the number of times
232 // this goal has resulted in inference progress. This doesn't precisely
233 // model the way that we track recursion depth in the old solver due
234 // to the fact that we only process root obligations, but it is a good
235 // approximation and should only result in fulfillment overflow in
236 // pathological cases.
237obligation.recursion_depth += 1;
238 any_changed = true;
239 }
240241match certainty {
242 Certainty::Yes => {
243// Goals may depend on structural identity. Region uniquification at the
244 // start of MIR borrowck may cause things to no longer be so, potentially
245 // causing an ICE.
246 //
247 // While we uniquify root goals in HIR this does not handle cases where
248 // regions are hidden inside of a type or const inference variable.
249 //
250 // FIXME(-Znext-solver): This does not handle inference variables hidden
251 // inside of an opaque type, e.g. if there's `Opaque = (?x, ?x)` in the
252 // storage, we can also rely on structural identity of `?x` even if we
253 // later uniquify it in MIR borrowck.
254if infcx.in_hir_typeck
255 && (obligation.has_non_region_infer() || obligation.has_free_regions())
256 {
257 infcx.push_hir_typeck_potentially_region_dependent_goal(obligation);
258 }
259 }
260 Certainty::Maybe { .. } => self.obligations.register(obligation, stalled_on),
261 }
262 }
263264if !any_changed {
265break;
266 }
267 }
268269errors270 }
271272fn has_pending_obligations(&self) -> bool {
273self.obligations.has_pending_obligations()
274 }
275276fn pending_obligations(&self) -> PredicateObligations<'tcx> {
277self.obligations.clone_pending()
278 }
279280fn drain_stalled_obligations_for_coroutines(
281&mut self,
282 infcx: &InferCtxt<'tcx>,
283 ) -> PredicateObligations<'tcx> {
284let stalled_coroutines = match infcx.typing_mode() {
285TypingMode::Analysis { defining_opaque_types_and_generators } => {
286defining_opaque_types_and_generators287 }
288TypingMode::Coherence289 | TypingMode::Borrowck { defining_opaque_types: _ }
290 | TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ }
291 | TypingMode::PostAnalysis => return Default::default(),
292 };
293294if stalled_coroutines.is_empty() {
295return Default::default();
296 }
297298self.obligations
299 .drain_pending(|obl| {
300infcx.probe(|_| {
301infcx302 .visit_proof_tree(
303obl.as_goal(),
304&mut StalledOnCoroutines {
305stalled_coroutines,
306 span: obl.cause.span,
307 cache: Default::default(),
308 },
309 )
310 .is_break()
311 })
312 })
313 .into_iter()
314 .map(|(o, _)| o)
315 .collect()
316 }
317}
318319/// Detect if a goal is stalled on a coroutine that is owned by the current typeck root.
320///
321/// This function can (erroneously) fail to detect a predicate, i.e. it doesn't need to
322/// be complete. However, this will lead to ambiguity errors, so we want to make it
323/// accurate.
324///
325/// This function can be also return false positives, which will lead to poor diagnostics
326/// so we want to keep this visitor *precise* too.
327pub struct StalledOnCoroutines<'tcx> {
328pub stalled_coroutines: &'tcx ty::List<LocalDefId>,
329pub span: Span,
330pub cache: DelayedSet<Ty<'tcx>>,
331}
332333impl<'tcx> inspect::ProofTreeVisitor<'tcx> for StalledOnCoroutines<'tcx> {
334type Result = ControlFlow<()>;
335336fn span(&self) -> rustc_span::Span {
337self.span
338 }
339340fn visit_goal(&mut self, inspect_goal: &super::inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
341inspect_goal.goal().predicate.visit_with(self)?;
342343if let Some(candidate) = inspect_goal.unique_applicable_candidate() {
344candidate.visit_nested_no_probe(self)
345 } else {
346 ControlFlow::Continue(())
347 }
348 }
349}
350351impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for StalledOnCoroutines<'tcx> {
352type Result = ControlFlow<()>;
353354fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
355if !self.cache.insert(ty) {
356return ControlFlow::Continue(());
357 }
358359if let ty::Coroutine(def_id, _) = *ty.kind()
360 && def_id.as_local().is_some_and(|def_id| self.stalled_coroutines.contains(&def_id))
361 {
362 ControlFlow::Break(())
363 } else if ty.has_coroutines() {
364ty.super_visit_with(self)
365 } else {
366 ControlFlow::Continue(())
367 }
368 }
369}
370371pub enum NextSolverError<'tcx> {
372 TrueError(PredicateObligation<'tcx>),
373 Ambiguity(PredicateObligation<'tcx>),
374 Overflow(PredicateObligation<'tcx>),
375}
376377impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for FulfillmentError<'tcx> {
378fn from_solver_error(infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
379match error {
380 NextSolverError::TrueError(obligation) => {
381fulfillment_error_for_no_solution(infcx, obligation)
382 }
383 NextSolverError::Ambiguity(obligation) => {
384fulfillment_error_for_stalled(infcx, obligation)
385 }
386 NextSolverError::Overflow(obligation) => {
387fulfillment_error_for_overflow(infcx, obligation)
388 }
389 }
390 }
391}
392393impl<'tcx> FromSolverError<'tcx, NextSolverError<'tcx>> for ScrubbedTraitError<'tcx> {
394fn from_solver_error(_infcx: &InferCtxt<'tcx>, error: NextSolverError<'tcx>) -> Self {
395match error {
396 NextSolverError::TrueError(_) => ScrubbedTraitError::TrueError,
397 NextSolverError::Ambiguity(_) | NextSolverError::Overflow(_) => {
398 ScrubbedTraitError::Ambiguity399 }
400 }
401 }
402}