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::{TyCtxt, VisitorResult, eager_resolve_vars, try_visit};
18use rustc_middle::{bug, ty};
19use rustc_next_trait_solver::canonical::instantiate_canonical_state;
20use rustc_next_trait_solver::solve::{MaybeCause, MaybeInfo, SolverDelegateEvalExt as _, inspect};
21use rustc_span::Span;
22use thin_vec::ThinVec;
23use tracing::instrument;
24
25use crate::solve::delegate::SolverDelegate;
26
27pub struct InspectConfig {
28 pub max_depth: usize,
29}
30
31pub struct InspectGoal<'a, 'tcx> {
32 infcx: &'a SolverDelegate<'tcx>,
33 depth: usize,
34 orig_values: ThinVec<ty::GenericArg<'tcx>>,
35 prev_universe: ty::UniverseIndex,
36 goal: Goal<'tcx, ty::Predicate<'tcx>>,
37 result: Result<Certainty, NoSolution>,
38 final_revision: &'tcx inspect::Probe<TyCtxt<'tcx>>,
39 source: GoalSource,
40}
41
42pub struct InspectCandidate<'a, 'tcx> {
43 goal: &'a InspectGoal<'a, 'tcx>,
44 kind: inspect::ProbeKind<TyCtxt<'tcx>>,
45 steps: Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
46 final_state: inspect::CanonicalState<TyCtxt<'tcx>, ()>,
47 result: QueryResult<'tcx>,
48 shallow_certainty: Certainty,
49}
50
51impl<'a, 'tcx> InspectCandidate<'a, 'tcx> {
52 pub fn kind(&self) -> inspect::ProbeKind<TyCtxt<'tcx>> {
53 self.kind
54 }
55
56 pub fn result(&self) -> Result<Certainty, NoSolution> {
57 self.result.map(|c| c.value.certainty)
58 }
59
60 pub fn goal(&self) -> &'a InspectGoal<'a, 'tcx> {
61 self.goal
62 }
63
64 pub fn shallow_certainty(&self) -> Certainty {
73 self.shallow_certainty
74 }
75
76 pub fn visit_nested_no_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
80 for goal in self.instantiate_nested_goals(visitor.span()) {
81 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));
82 }
83
84 V::Result::output()
85 }
86
87 #[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("compiler/rustc_trait_selection/src/solve/inspect/analyse.rs"),
::tracing_core::__macro_support::Option::Some(91u32),
::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 param_env = self.goal.goal.param_env;
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, param_env,
self.goal.prev_universe, &mut orig_values, goal))),
inspect::ProbeStep::RecordImplArgs { .. } => {}
inspect::ProbeStep::MakeCanonicalResponse { .. } |
inspect::ProbeStep::NestedProbe(_) =>
::core::panicking::panic("internal error: entered unreachable code"),
}
}
let () =
instantiate_canonical_state(infcx, span, param_env,
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(
92 level = "debug",
93 skip_all,
94 fields(goal = ?self.goal.goal, steps = ?self.steps)
95 )]
96 pub fn instantiate_nested_goals(&self, span: Span) -> Vec<InspectGoal<'a, 'tcx>> {
97 let infcx = self.goal.infcx;
98 let param_env = self.goal.goal.param_env;
99 let mut orig_values = self.goal.orig_values.clone();
100
101 let mut instantiated_goals = vec![];
102 for step in &self.steps {
103 match **step {
104 inspect::ProbeStep::AddGoal(source, goal) => instantiated_goals.push((
105 source,
106 instantiate_canonical_state(
107 infcx,
108 span,
109 param_env,
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 param_env,
125 self.goal.prev_universe,
126 &mut orig_values,
127 self.final_state,
128 );
129
130 instantiated_goals
131 .into_iter()
132 .map(|(source, goal)| self.instantiate_proof_tree_for_nested_goal(source, goal, span))
133 .collect()
134 }
135
136 #[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("compiler/rustc_trait_selection/src/solve/inspect/analyse.rs"),
::tracing_core::__macro_support::Option::Some(139u32),
::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::GenericArgsRef<'tcx> =
loop {};
return __tracing_attr_fake_return;
}
{
let infcx = self.goal.infcx;
let param_env = self.goal.goal.param_env;
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, param_env,
self.goal.prev_universe, &mut orig_values, impl_args);
let () =
instantiate_canonical_state(infcx, span, param_env,
self.goal.prev_universe, &mut orig_values,
self.final_state);
return eager_resolve_vars(&**infcx, impl_args);
}
inspect::ProbeStep::AddGoal(..) => {}
inspect::ProbeStep::MakeCanonicalResponse { .. } |
inspect::ProbeStep::NestedProbe(_) =>
::core::panicking::panic("internal error: entered unreachable code"),
}
}
::rustc_middle::util::bug::bug_fmt(format_args!("expected impl args probe step for `instantiate_impl_args`"));
}
}
}#[instrument(
140 level = "debug",
141 skip_all,
142 fields(goal = ?self.goal.goal, steps = ?self.steps)
143 )]
144 pub fn instantiate_impl_args(&self, span: Span) -> ty::GenericArgsRef<'tcx> {
145 let infcx = self.goal.infcx;
146 let param_env = self.goal.goal.param_env;
147 let mut orig_values = self.goal.orig_values.clone();
148
149 for step in &self.steps {
150 match **step {
151 inspect::ProbeStep::RecordImplArgs { impl_args } => {
152 let impl_args = instantiate_canonical_state(
153 infcx,
154 span,
155 param_env,
156 self.goal.prev_universe,
157 &mut orig_values,
158 impl_args,
159 );
160
161 let () = instantiate_canonical_state(
162 infcx,
163 span,
164 param_env,
165 self.goal.prev_universe,
166 &mut orig_values,
167 self.final_state,
168 );
169
170 return eager_resolve_vars(&**infcx, impl_args);
171 }
172 inspect::ProbeStep::AddGoal(..) => {}
173 inspect::ProbeStep::MakeCanonicalResponse { .. }
174 | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
175 }
176 }
177
178 bug!("expected impl args probe step for `instantiate_impl_args`");
179 }
180
181 pub fn instantiate_proof_tree_for_nested_goal(
182 &self,
183 source: GoalSource,
184 goal: Goal<'tcx, ty::Predicate<'tcx>>,
185 span: Span,
186 ) -> InspectGoal<'a, 'tcx> {
187 let infcx = self.goal.infcx;
188 match goal.predicate.kind().no_bound_vars() {
189 Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { .. })) => {
190 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
192 }
193 _ => {
194 let proof_tree =
200 infcx.probe(|_| infcx.evaluate_root_goal_for_proof_tree(goal, span).1);
201 InspectGoal::new(infcx, self.goal.depth + 1, proof_tree, source)
202 }
203 }
204 }
205
206 pub fn visit_nested_in_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
209 self.goal.infcx.probe(|_| self.visit_nested_no_probe(visitor))
210 }
211}
212
213impl<'a, 'tcx> InspectGoal<'a, 'tcx> {
214 pub fn infcx(&self) -> &'a InferCtxt<'tcx> {
215 self.infcx
216 }
217
218 pub fn goal(&self) -> Goal<'tcx, ty::Predicate<'tcx>> {
219 self.goal
220 }
221
222 pub fn result(&self) -> Result<Certainty, NoSolution> {
223 self.result
224 }
225
226 pub fn source(&self) -> GoalSource {
227 self.source
228 }
229
230 pub fn depth(&self) -> usize {
231 self.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_middle::util::bug::bug_fmt(format_args!("impossible case reached"))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 { uncanonicalized_goal, orig_values, final_revision, result } =
342 root;
343 let result = result.map(|ok| ok.value.certainty);
346
347 InspectGoal {
348 infcx,
349 depth,
350 orig_values,
351 prev_universe,
352 goal: eager_resolve_vars(&**infcx, uncanonicalized_goal),
353 result,
354 final_revision,
355 source,
356 }
357 }
358
359 pub(crate) fn visit_with<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
360 if self.depth < visitor.config().max_depth {
361 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));
362 V::Result::output()
363 } else {
364 visitor.on_recursion_limit()
365 }
366 }
367}
368
369pub trait ProofTreeVisitor<'tcx> {
371 type Result: VisitorResult = ();
372
373 fn span(&self) -> Span;
374
375 fn config(&self) -> InspectConfig {
376 InspectConfig { max_depth: 10 }
377 }
378
379 fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) -> Self::Result;
380
381 fn on_recursion_limit(&mut self) -> Self::Result {
382 Self::Result::output()
383 }
384}
385
386impl<'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>)]
387impl<'tcx> InferCtxt<'tcx> {
388 fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(
389 &self,
390 goal: Goal<'tcx, ty::Predicate<'tcx>>,
391 visitor: &mut V,
392 ) -> V::Result {
393 self.visit_proof_tree_at_depth(goal, 0, visitor)
394 }
395
396 fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(
397 &self,
398 goal: Goal<'tcx, ty::Predicate<'tcx>>,
399 depth: usize,
400 visitor: &mut V,
401 ) -> V::Result {
402 let (_, proof_tree) = <&SolverDelegate<'tcx>>::from(self)
403 .evaluate_root_goal_for_proof_tree(goal, visitor.span());
404 visitor.visit_goal(&InspectGoal::new(self, depth, proof_tree, GoalSource::Misc))
405 }
406}