1use std::assert_matches;
13
14use rustc_infer::infer::InferCtxt;
15use rustc_macros::extension;
16use rustc_middle::traits::solve::{Certainty, Goal, GoalSource, NoSolution, QueryResult};
17use rustc_middle::ty;
18use rustc_middle::ty::{RequiredDepth, TyCtxt, VisitorResult, try_visit};
19use rustc_next_trait_solver::canonical::instantiate_canonical_state;
20use rustc_next_trait_solver::solve::{MaybeCause, MaybeInfo, SolverDelegateEvalExt as _, inspect};
21use rustc_span::{Span, bug};
22use tracing::instrument;
23
24use crate::solve::delegate::SolverDelegate;
25
26pub struct InspectConfig {
27 pub max_depth: usize,
28}
29
30pub struct InspectGoal<'a, 'tcx> {
31 infcx: &'a SolverDelegate<'tcx>,
32 depth: usize,
34 required_depth: RequiredDepth,
36 orig_values: Vec<ty::GenericArg<'tcx>>,
37 prev_universe: ty::UniverseIndex,
38 goal: Goal<'tcx, ty::Predicate<'tcx>>,
39 result: Result<Certainty, NoSolution>,
40 final_revision: &'tcx inspect::Probe<TyCtxt<'tcx>>,
41 source: GoalSource,
42}
43
44pub struct InspectCandidate<'a, 'tcx> {
45 goal: &'a InspectGoal<'a, 'tcx>,
46 kind: inspect::ProbeKind<TyCtxt<'tcx>>,
47 steps: Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
48 final_state: inspect::CanonicalState<TyCtxt<'tcx>, ()>,
49 result: QueryResult<'tcx>,
50 shallow_certainty: Certainty,
51}
52
53impl<'a, 'tcx> InspectCandidate<'a, 'tcx> {
54 pub fn kind(&self) -> inspect::ProbeKind<TyCtxt<'tcx>> {
55 self.kind
56 }
57
58 pub fn result(&self) -> Result<Certainty, NoSolution> {
59 self.result.map(|c| c.value.certainty)
60 }
61
62 pub fn goal(&self) -> &'a InspectGoal<'a, 'tcx> {
63 self.goal
64 }
65
66 pub fn shallow_certainty(&self) -> Certainty {
75 self.shallow_certainty
76 }
77
78 pub fn visit_nested_no_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
82 for goal in self.instantiate_nested_goals(visitor.span()) {
83 match ::rustc_ast_ir::visit::VisitorResult::branch(goal.visit_with(visitor)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(goal.visit_with(visitor));
84 }
85
86 V::Result::output()
87 }
88
89 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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("instantiate_nested_goals",
"rustc_trait_selection::solve::inspect::analyse",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs"),
::tracing_core::__macro_support::Option::Some(93u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::solve::inspect::analyse"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("goal")
}> =
::tracing::__macro_support::FieldName::new("goal");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("steps")
}> =
::tracing::__macro_support::FieldName::new("steps");
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::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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(&self.goal.goal)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.steps)
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: Vec<InspectGoal<'a, 'tcx>> =
loop {};
return __tracing_attr_fake_return;
}
{
let infcx = self.goal.infcx;
let mut orig_values = self.goal.orig_values.clone();
let mut instantiated_goals = ::alloc::vec::Vec::new();
for step in &self.steps {
match **step {
inspect::ProbeStep::AddGoal(source, goal) =>
instantiated_goals.push((source,
instantiate_canonical_state(infcx, span,
self.goal.prev_universe, &mut orig_values, goal))),
inspect::ProbeStep::RecordImplArgs { .. } => {}
inspect::ProbeStep::MakeCanonicalResponse { .. } |
inspect::ProbeStep::NestedProbe(_) =>
::core::panicking::unreachable_default_msg(),
}
}
let () =
instantiate_canonical_state(infcx, span,
self.goal.prev_universe, &mut orig_values,
self.final_state);
instantiated_goals.into_iter().map(|(source, goal)|
self.instantiate_proof_tree_for_nested_goal(source, goal,
span)).collect()
}
}
}#[instrument(
94 level = "debug",
95 skip_all,
96 fields(goal = ?self.goal.goal, steps = ?self.steps)
97 )]
98 pub fn instantiate_nested_goals(&self, span: Span) -> Vec<InspectGoal<'a, 'tcx>> {
99 let infcx = self.goal.infcx;
100 let mut orig_values = self.goal.orig_values.clone();
101
102 let mut instantiated_goals = vec![];
103 for step in &self.steps {
104 match **step {
105 inspect::ProbeStep::AddGoal(source, goal) => instantiated_goals.push((
106 source,
107 instantiate_canonical_state(
108 infcx,
109 span,
110 self.goal.prev_universe,
111 &mut orig_values,
112 goal,
113 ),
114 )),
115 inspect::ProbeStep::RecordImplArgs { .. } => {}
116 inspect::ProbeStep::MakeCanonicalResponse { .. }
117 | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
118 }
119 }
120
121 let () = instantiate_canonical_state(
122 infcx,
123 span,
124 self.goal.prev_universe,
125 &mut orig_values,
126 self.final_state,
127 );
128
129 instantiated_goals
130 .into_iter()
131 .map(|(source, goal)| self.instantiate_proof_tree_for_nested_goal(source, goal, span))
132 .collect()
133 }
134
135 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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("instantiate_impl_args",
"rustc_trait_selection::solve::inspect::analyse",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs"),
::tracing_core::__macro_support::Option::Some(138u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::solve::inspect::analyse"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("goal")
}> =
::tracing::__macro_support::FieldName::new("goal");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("steps")
}> =
::tracing::__macro_support::FieldName::new("steps");
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::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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(&self.goal.goal)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.steps)
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: ty::GenericArgs<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let infcx = self.goal.infcx;
let mut orig_values = self.goal.orig_values.clone();
for step in &self.steps {
match **step {
inspect::ProbeStep::RecordImplArgs { impl_args } => {
let impl_args =
instantiate_canonical_state(infcx, span,
self.goal.prev_universe, &mut orig_values, impl_args);
let () =
instantiate_canonical_state(infcx, span,
self.goal.prev_universe, &mut orig_values,
self.final_state);
return infcx.deeply_resolve_via_unification_table(impl_args);
}
inspect::ProbeStep::AddGoal(..) => {}
inspect::ProbeStep::MakeCanonicalResponse { .. } |
inspect::ProbeStep::NestedProbe(_) =>
::core::panicking::unreachable_default_msg(),
}
}
::rustc_span::macros::bug_impl(None,
format_args!("expected impl args probe step for `instantiate_impl_args`"),
Location::caller());
}
}
}#[instrument(
139 level = "debug",
140 skip_all,
141 fields(goal = ?self.goal.goal, steps = ?self.steps)
142 )]
143 pub fn instantiate_impl_args(&self, span: Span) -> ty::GenericArgs<'tcx> {
144 let infcx = self.goal.infcx;
145 let mut orig_values = self.goal.orig_values.clone();
146
147 for step in &self.steps {
148 match **step {
149 inspect::ProbeStep::RecordImplArgs { impl_args } => {
150 let impl_args = instantiate_canonical_state(
151 infcx,
152 span,
153 self.goal.prev_universe,
154 &mut orig_values,
155 impl_args,
156 );
157
158 let () = instantiate_canonical_state(
159 infcx,
160 span,
161 self.goal.prev_universe,
162 &mut orig_values,
163 self.final_state,
164 );
165
166 return infcx.deeply_resolve_via_unification_table(impl_args);
167 }
168 inspect::ProbeStep::AddGoal(..) => {}
169 inspect::ProbeStep::MakeCanonicalResponse { .. }
170 | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
171 }
172 }
173
174 bug!("expected impl args probe step for `instantiate_impl_args`");
175 }
176
177 pub fn instantiate_proof_tree_for_nested_goal(
178 &self,
179 source: GoalSource,
180 goal: Goal<'tcx, ty::Predicate<'tcx>>,
181 span: Span,
182 ) -> InspectGoal<'a, 'tcx> {
183 let infcx = self.goal.infcx;
184 match goal.predicate.kind().no_bound_vars() {
185 Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { .. })) => {
186 ::core::panicking::unreachable_default_msg()unreachable!()
188 }
189 _ => {
190 let proof_tree =
196 infcx.probe(|_| infcx.evaluate_root_goal_for_proof_tree(goal, span).1);
197 InspectGoal::new(infcx, self.goal.depth + 1, proof_tree, source)
198 }
199 }
200 }
201
202 pub fn visit_nested_in_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
205 self.goal.infcx.probe(|_| self.visit_nested_no_probe(visitor))
206 }
207}
208
209impl<'a, 'tcx> InspectGoal<'a, 'tcx> {
210 pub fn infcx(&self) -> &'a InferCtxt<'tcx> {
211 self.infcx
212 }
213
214 pub fn goal(&self) -> Goal<'tcx, ty::Predicate<'tcx>> {
215 self.goal
216 }
217
218 pub fn result(&self) -> Result<Certainty, NoSolution> {
219 self.result
220 }
221
222 pub fn source(&self) -> GoalSource {
223 self.source
224 }
225
226 pub fn depth(&self) -> usize {
227 self.depth
228 }
229
230 pub fn required_depth(&self) -> RequiredDepth {
231 self.required_depth
232 }
233
234 pub fn orig_values(&self) -> &[ty::GenericArg<'tcx>] {
235 &self.orig_values
236 }
237
238 fn candidates_recur(
239 &'a self,
240 candidates: &mut Vec<InspectCandidate<'a, 'tcx>>,
241 steps: &mut Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
242 probe: &'a inspect::Probe<TyCtxt<'tcx>>,
243 ) {
244 let mut shallow_certainty = None;
245 for step in &probe.steps {
246 match *step {
247 inspect::ProbeStep::AddGoal(..) | inspect::ProbeStep::RecordImplArgs { .. } => {
248 steps.push(step)
249 }
250 inspect::ProbeStep::MakeCanonicalResponse { shallow_certainty: c } => {
251 {
match shallow_certainty.replace(c) {
None |
Some(Certainty::Maybe(MaybeInfo {
cause: MaybeCause::Ambiguity,
opaque_types_jank: _,
stalled_on_coroutines: _ })) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"None |\nSome(Certainty::Maybe(MaybeInfo\n{\n cause: MaybeCause::Ambiguity, opaque_types_jank: _, stalled_on_coroutines:\n _,\n}))",
::core::option::Option::None);
}
}
};assert_matches!(
252 shallow_certainty.replace(c),
253 None | Some(Certainty::Maybe(MaybeInfo {
254 cause: MaybeCause::Ambiguity,
255 opaque_types_jank: _,
256 stalled_on_coroutines: _,
257 }))
258 );
259 }
260 inspect::ProbeStep::NestedProbe(ref probe) => {
261 match probe.kind {
262 inspect::ProbeKind::ProjectionCompatibility
264 | inspect::ProbeKind::ShadowedEnvProbing => continue,
265
266 inspect::ProbeKind::NormalizedSelfTyAssembly
267 | inspect::ProbeKind::UnsizeAssembly
268 | inspect::ProbeKind::Root { .. }
269 | inspect::ProbeKind::TraitCandidate { .. }
270 | inspect::ProbeKind::OpaqueTypeStorageLookup { .. }
271 | inspect::ProbeKind::RigidAlias { .. } => {
272 let num_steps = steps.len();
276 self.candidates_recur(candidates, steps, probe);
277 steps.truncate(num_steps);
278 }
279 }
280 }
281 }
282 }
283
284 match probe.kind {
285 inspect::ProbeKind::ProjectionCompatibility
286 | inspect::ProbeKind::ShadowedEnvProbing => {
287 ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!()
288 }
289
290 inspect::ProbeKind::NormalizedSelfTyAssembly | inspect::ProbeKind::UnsizeAssembly => {}
291
292 inspect::ProbeKind::Root { result }
295 | inspect::ProbeKind::TraitCandidate { source: _, result }
296 | inspect::ProbeKind::OpaqueTypeStorageLookup { result }
297 | inspect::ProbeKind::RigidAlias { result } => {
298 if let Some(shallow_certainty) = shallow_certainty {
301 candidates.push(InspectCandidate {
302 goal: self,
303 kind: probe.kind,
304 steps: steps.clone(),
305 final_state: probe.final_state,
306 shallow_certainty,
307 result,
308 });
309 }
310 }
311 }
312 }
313
314 pub fn candidates(&'a self) -> Vec<InspectCandidate<'a, 'tcx>> {
315 let mut candidates = ::alloc::vec::Vec::new()vec![];
316 let mut nested_goals = ::alloc::vec::Vec::new()vec![];
317 self.candidates_recur(&mut candidates, &mut nested_goals, &self.final_revision);
318 candidates
319 }
320
321 pub fn unique_applicable_candidate(&'a self) -> Option<InspectCandidate<'a, 'tcx>> {
325 let mut candidates = self.candidates();
328 candidates.retain(|c| c.result().is_ok());
329 candidates.pop().filter(|_| candidates.is_empty())
330 }
331
332 fn new(
333 infcx: &'a InferCtxt<'tcx>,
334 depth: usize,
335 root: inspect::GoalEvaluation<TyCtxt<'tcx>>,
336 source: GoalSource,
337 ) -> Self {
338 let infcx = <&SolverDelegate<'tcx>>::from(infcx);
339 let prev_universe = infcx.universe();
340
341 let inspect::GoalEvaluation {
342 uncanonicalized_goal,
343 orig_values,
344 final_revision,
345 result,
346 required_depth,
347 } = root;
348 let result = result.map(|ok| ok.value.certainty);
351
352 InspectGoal {
353 infcx,
354 depth,
355 orig_values,
356 prev_universe,
357 goal: infcx.deeply_resolve_via_unification_table(uncanonicalized_goal),
358 result,
359 final_revision,
360 source,
361 required_depth,
362 }
363 }
364
365 pub(crate) fn visit_with<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
366 if self.depth < visitor.config().max_depth {
367 match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_goal(self)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(visitor.visit_goal(self));
368 V::Result::output()
369 } else {
370 visitor.on_recursion_limit()
371 }
372 }
373}
374
375pub trait ProofTreeVisitor<'tcx> {
377 type Result: VisitorResult = ();
378
379 fn span(&self) -> Span;
380
381 fn config(&self) -> InspectConfig {
382 InspectConfig { max_depth: 10 }
383 }
384
385 fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) -> Self::Result;
386
387 fn on_recursion_limit(&mut self) -> Self::Result {
388 Self::Result::output()
389 }
390}
391
392pub trait InferCtxtProofTreeExt<'tcx> {
fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(&self,
goal: Goal<'tcx, ty::Predicate<'tcx>>, visitor: &mut V)
-> V::Result;
fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(&self,
goal: Goal<'tcx, ty::Predicate<'tcx>>, depth: usize, visitor: &mut V)
-> V::Result;
}
impl<'tcx> InferCtxtProofTreeExt<'tcx> for InferCtxt<'tcx> {
fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(&self,
goal: Goal<'tcx, ty::Predicate<'tcx>>, visitor: &mut V) -> V::Result {
self.visit_proof_tree_at_depth(goal, 0, visitor)
}
fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(&self,
goal: Goal<'tcx, ty::Predicate<'tcx>>, depth: usize, visitor: &mut V)
-> V::Result {
let (_, proof_tree) =
<&SolverDelegate<'tcx>>::from(self).evaluate_root_goal_for_proof_tree(goal,
visitor.span());
visitor.visit_goal(&InspectGoal::new(self, depth, proof_tree,
GoalSource::Misc))
}
}#[extension(pub trait InferCtxtProofTreeExt<'tcx>)]
393impl<'tcx> InferCtxt<'tcx> {
394 fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(
395 &self,
396 goal: Goal<'tcx, ty::Predicate<'tcx>>,
397 visitor: &mut V,
398 ) -> V::Result {
399 self.visit_proof_tree_at_depth(goal, 0, visitor)
400 }
401
402 fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(
403 &self,
404 goal: Goal<'tcx, ty::Predicate<'tcx>>,
405 depth: usize,
406 visitor: &mut V,
407 ) -> V::Result {
408 let (_, proof_tree) = <&SolverDelegate<'tcx>>::from(self)
409 .evaluate_root_goal_for_proof_tree(goal, visitor.span());
410 visitor.visit_goal(&InspectGoal::new(self, depth, proof_tree, GoalSource::Misc))
411 }
412}