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::{RequiredDepth, 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,
35 required_depth: RequiredDepth,
37 orig_values: ThinVec<ty::GenericArg<'tcx>>,
38 prev_universe: ty::UniverseIndex,
39 goal: Goal<'tcx, ty::Predicate<'tcx>>,
40 result: Result<Certainty, NoSolution>,
41 final_revision: &'tcx inspect::Probe<TyCtxt<'tcx>>,
42 source: GoalSource,
43}
44
45pub struct InspectCandidate<'a, 'tcx> {
46 goal: &'a InspectGoal<'a, 'tcx>,
47 kind: inspect::ProbeKind<TyCtxt<'tcx>>,
48 steps: Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
49 final_state: inspect::CanonicalState<TyCtxt<'tcx>, ()>,
50 result: QueryResult<'tcx>,
51 shallow_certainty: Certainty,
52}
53
54impl<'a, 'tcx> InspectCandidate<'a, 'tcx> {
55 pub fn kind(&self) -> inspect::ProbeKind<TyCtxt<'tcx>> {
56 self.kind
57 }
58
59 pub fn result(&self) -> Result<Certainty, NoSolution> {
60 self.result.map(|c| c.value.certainty)
61 }
62
63 pub fn goal(&self) -> &'a InspectGoal<'a, 'tcx> {
64 self.goal
65 }
66
67 pub fn shallow_certainty(&self) -> Certainty {
76 self.shallow_certainty
77 }
78
79 pub fn visit_nested_no_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
83 for goal in self.instantiate_nested_goals(visitor.span()) {
84 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));
85 }
86
87 V::Result::output()
88 }
89
90 #[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(94u32),
::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(
95 level = "debug",
96 skip_all,
97 fields(goal = ?self.goal.goal, steps = ?self.steps)
98 )]
99 pub fn instantiate_nested_goals(&self, span: Span) -> Vec<InspectGoal<'a, 'tcx>> {
100 let infcx = self.goal.infcx;
101 let param_env = self.goal.goal.param_env;
102 let mut orig_values = self.goal.orig_values.clone();
103
104 let mut instantiated_goals = vec![];
105 for step in &self.steps {
106 match **step {
107 inspect::ProbeStep::AddGoal(source, goal) => instantiated_goals.push((
108 source,
109 instantiate_canonical_state(
110 infcx,
111 span,
112 param_env,
113 self.goal.prev_universe,
114 &mut orig_values,
115 goal,
116 ),
117 )),
118 inspect::ProbeStep::RecordImplArgs { .. } => {}
119 inspect::ProbeStep::MakeCanonicalResponse { .. }
120 | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
121 }
122 }
123
124 let () = instantiate_canonical_state(
125 infcx,
126 span,
127 param_env,
128 self.goal.prev_universe,
129 &mut orig_values,
130 self.final_state,
131 );
132
133 instantiated_goals
134 .into_iter()
135 .map(|(source, goal)| self.instantiate_proof_tree_for_nested_goal(source, goal, span))
136 .collect()
137 }
138
139 #[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(142u32),
::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(
143 level = "debug",
144 skip_all,
145 fields(goal = ?self.goal.goal, steps = ?self.steps)
146 )]
147 pub fn instantiate_impl_args(&self, span: Span) -> ty::GenericArgsRef<'tcx> {
148 let infcx = self.goal.infcx;
149 let param_env = self.goal.goal.param_env;
150 let mut orig_values = self.goal.orig_values.clone();
151
152 for step in &self.steps {
153 match **step {
154 inspect::ProbeStep::RecordImplArgs { impl_args } => {
155 let impl_args = instantiate_canonical_state(
156 infcx,
157 span,
158 param_env,
159 self.goal.prev_universe,
160 &mut orig_values,
161 impl_args,
162 );
163
164 let () = instantiate_canonical_state(
165 infcx,
166 span,
167 param_env,
168 self.goal.prev_universe,
169 &mut orig_values,
170 self.final_state,
171 );
172
173 return eager_resolve_vars(&**infcx, impl_args);
174 }
175 inspect::ProbeStep::AddGoal(..) => {}
176 inspect::ProbeStep::MakeCanonicalResponse { .. }
177 | inspect::ProbeStep::NestedProbe(_) => unreachable!(),
178 }
179 }
180
181 bug!("expected impl args probe step for `instantiate_impl_args`");
182 }
183
184 pub fn instantiate_proof_tree_for_nested_goal(
185 &self,
186 source: GoalSource,
187 goal: Goal<'tcx, ty::Predicate<'tcx>>,
188 span: Span,
189 ) -> InspectGoal<'a, 'tcx> {
190 let infcx = self.goal.infcx;
191 match goal.predicate.kind().no_bound_vars() {
192 Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { .. })) => {
193 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
195 }
196 _ => {
197 let proof_tree =
203 infcx.probe(|_| infcx.evaluate_root_goal_for_proof_tree(goal, span).1);
204 InspectGoal::new(infcx, self.goal.depth + 1, proof_tree, source)
205 }
206 }
207 }
208
209 pub fn visit_nested_in_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
212 self.goal.infcx.probe(|_| self.visit_nested_no_probe(visitor))
213 }
214}
215
216impl<'a, 'tcx> InspectGoal<'a, 'tcx> {
217 pub fn infcx(&self) -> &'a InferCtxt<'tcx> {
218 self.infcx
219 }
220
221 pub fn goal(&self) -> Goal<'tcx, ty::Predicate<'tcx>> {
222 self.goal
223 }
224
225 pub fn result(&self) -> Result<Certainty, NoSolution> {
226 self.result
227 }
228
229 pub fn source(&self) -> GoalSource {
230 self.source
231 }
232
233 pub fn depth(&self) -> usize {
234 self.depth
235 }
236
237 pub fn required_depth(&self) -> RequiredDepth {
238 self.required_depth
239 }
240
241 pub fn orig_values(&self) -> &[ty::GenericArg<'tcx>] {
242 &self.orig_values
243 }
244
245 fn candidates_recur(
246 &'a self,
247 candidates: &mut Vec<InspectCandidate<'a, 'tcx>>,
248 steps: &mut Vec<&'a inspect::ProbeStep<TyCtxt<'tcx>>>,
249 probe: &'a inspect::Probe<TyCtxt<'tcx>>,
250 ) {
251 let mut shallow_certainty = None;
252 for step in &probe.steps {
253 match *step {
254 inspect::ProbeStep::AddGoal(..) | inspect::ProbeStep::RecordImplArgs { .. } => {
255 steps.push(step)
256 }
257 inspect::ProbeStep::MakeCanonicalResponse { shallow_certainty: c } => {
258 {
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!(
259 shallow_certainty.replace(c),
260 None | Some(Certainty::Maybe(MaybeInfo {
261 cause: MaybeCause::Ambiguity,
262 opaque_types_jank: _,
263 stalled_on_coroutines: _,
264 }))
265 );
266 }
267 inspect::ProbeStep::NestedProbe(ref probe) => {
268 match probe.kind {
269 inspect::ProbeKind::ProjectionCompatibility
271 | inspect::ProbeKind::ShadowedEnvProbing => continue,
272
273 inspect::ProbeKind::NormalizedSelfTyAssembly
274 | inspect::ProbeKind::UnsizeAssembly
275 | inspect::ProbeKind::Root { .. }
276 | inspect::ProbeKind::TraitCandidate { .. }
277 | inspect::ProbeKind::OpaqueTypeStorageLookup { .. }
278 | inspect::ProbeKind::RigidAlias { .. } => {
279 let num_steps = steps.len();
283 self.candidates_recur(candidates, steps, probe);
284 steps.truncate(num_steps);
285 }
286 }
287 }
288 }
289 }
290
291 match probe.kind {
292 inspect::ProbeKind::ProjectionCompatibility
293 | inspect::ProbeKind::ShadowedEnvProbing => {
294 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
295 }
296
297 inspect::ProbeKind::NormalizedSelfTyAssembly | inspect::ProbeKind::UnsizeAssembly => {}
298
299 inspect::ProbeKind::Root { result }
302 | inspect::ProbeKind::TraitCandidate { source: _, result }
303 | inspect::ProbeKind::OpaqueTypeStorageLookup { result }
304 | inspect::ProbeKind::RigidAlias { result } => {
305 if let Some(shallow_certainty) = shallow_certainty {
308 candidates.push(InspectCandidate {
309 goal: self,
310 kind: probe.kind,
311 steps: steps.clone(),
312 final_state: probe.final_state,
313 shallow_certainty,
314 result,
315 });
316 }
317 }
318 }
319 }
320
321 pub fn candidates(&'a self) -> Vec<InspectCandidate<'a, 'tcx>> {
322 let mut candidates = ::alloc::vec::Vec::new()vec![];
323 let mut nested_goals = ::alloc::vec::Vec::new()vec![];
324 self.candidates_recur(&mut candidates, &mut nested_goals, &self.final_revision);
325 candidates
326 }
327
328 pub fn unique_applicable_candidate(&'a self) -> Option<InspectCandidate<'a, 'tcx>> {
332 let mut candidates = self.candidates();
335 candidates.retain(|c| c.result().is_ok());
336 candidates.pop().filter(|_| candidates.is_empty())
337 }
338
339 fn new(
340 infcx: &'a InferCtxt<'tcx>,
341 depth: usize,
342 root: inspect::GoalEvaluation<TyCtxt<'tcx>>,
343 source: GoalSource,
344 ) -> Self {
345 let infcx = <&SolverDelegate<'tcx>>::from(infcx);
346 let prev_universe = infcx.universe();
347
348 let inspect::GoalEvaluation {
349 uncanonicalized_goal,
350 orig_values,
351 final_revision,
352 result,
353 required_depth,
354 } = root;
355 let result = result.map(|ok| ok.value.certainty);
358
359 InspectGoal {
360 infcx,
361 depth,
362 orig_values,
363 prev_universe,
364 goal: eager_resolve_vars(&**infcx, uncanonicalized_goal),
365 result,
366 final_revision,
367 source,
368 required_depth,
369 }
370 }
371
372 pub(crate) fn visit_with<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {
373 if self.depth < visitor.config().max_depth {
374 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));
375 V::Result::output()
376 } else {
377 visitor.on_recursion_limit()
378 }
379 }
380}
381
382pub trait ProofTreeVisitor<'tcx> {
384 type Result: VisitorResult = ();
385
386 fn span(&self) -> Span;
387
388 fn config(&self) -> InspectConfig {
389 InspectConfig { max_depth: 10 }
390 }
391
392 fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) -> Self::Result;
393
394 fn on_recursion_limit(&mut self) -> Self::Result {
395 Self::Result::output()
396 }
397}
398
399impl<'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>)]
400impl<'tcx> InferCtxt<'tcx> {
401 fn visit_proof_tree<V: ProofTreeVisitor<'tcx>>(
402 &self,
403 goal: Goal<'tcx, ty::Predicate<'tcx>>,
404 visitor: &mut V,
405 ) -> V::Result {
406 self.visit_proof_tree_at_depth(goal, 0, visitor)
407 }
408
409 fn visit_proof_tree_at_depth<V: ProofTreeVisitor<'tcx>>(
410 &self,
411 goal: Goal<'tcx, ty::Predicate<'tcx>>,
412 depth: usize,
413 visitor: &mut V,
414 ) -> V::Result {
415 let (_, proof_tree) = <&SolverDelegate<'tcx>>::from(self)
416 .evaluate_root_goal_for_proof_tree(goal, visitor.span());
417 visitor.visit_goal(&InspectGoal::new(self, depth, proof_tree, GoalSource::Misc))
418 }
419}