Skip to content

Commit 977bf18

Browse files
Manually walk into WF obligations in BestObligation proof tree visitor
1 parent 6c86840 commit 977bf18

File tree

13 files changed

+138
-85
lines changed

13 files changed

+138
-85
lines changed

compiler/rustc_trait_selection/src/solve/delegate.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::ops::Deref;
22

33
use rustc_data_structures::fx::FxHashSet;
4-
use rustc_hir::def_id::DefId;
4+
use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
55
use rustc_infer::infer::canonical::query_response::make_query_region_constraints;
66
use rustc_infer::infer::canonical::{
77
Canonical, CanonicalExt as _, CanonicalQueryInput, CanonicalVarInfo, CanonicalVarValues,
@@ -98,9 +98,10 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<
9898
param_env: ty::ParamEnv<'tcx>,
9999
arg: ty::GenericArg<'tcx>,
100100
) -> Option<Vec<Goal<'tcx, ty::Predicate<'tcx>>>> {
101-
crate::traits::wf::unnormalized_obligations(&self.0, param_env, arg).map(|obligations| {
102-
obligations.into_iter().map(|obligation| obligation.into()).collect()
103-
})
101+
crate::traits::wf::unnormalized_obligations(&self.0, param_env, arg, DUMMY_SP, CRATE_DEF_ID)
102+
.map(|obligations| {
103+
obligations.into_iter().map(|obligation| obligation.into()).collect()
104+
})
104105
}
105106

106107
fn clone_opaque_types_for_query_response(&self) -> Vec<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)> {

compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ use rustc_middle::ty::error::{ExpectedFound, TypeError};
1010
use rustc_middle::ty::{self, TyCtxt};
1111
use rustc_middle::{bug, span_bug};
1212
use rustc_next_trait_solver::solve::{GenerateProofTree, SolverDelegateEvalExt as _};
13+
use rustc_type_ir::solve::Goal;
1314
use tracing::{instrument, trace};
1415

1516
use crate::solve::Certainty;
1617
use crate::solve::delegate::SolverDelegate;
1718
use crate::solve::inspect::{self, ProofTreeInferCtxtExt, ProofTreeVisitor};
18-
use crate::traits::{FulfillmentError, FulfillmentErrorCode};
19+
use crate::traits::{FulfillmentError, FulfillmentErrorCode, wf};
1920

2021
pub(super) fn fulfillment_error_for_no_solution<'tcx>(
2122
infcx: &InferCtxt<'tcx>,
@@ -232,6 +233,40 @@ impl<'tcx> BestObligation<'tcx> {
232233

233234
candidates
234235
}
236+
237+
fn visit_well_formed_goal(
238+
&mut self,
239+
candidate: &inspect::InspectCandidate<'_, 'tcx>,
240+
arg: ty::GenericArg<'tcx>,
241+
) -> ControlFlow<PredicateObligation<'tcx>> {
242+
let infcx = candidate.goal().infcx();
243+
let param_env = candidate.goal().goal().param_env;
244+
let body_id = self.obligation.cause.body_id;
245+
246+
for obligation in wf::unnormalized_obligations(infcx, param_env, arg, self.span(), body_id)
247+
.into_iter()
248+
.flatten()
249+
{
250+
let nested_goal = candidate.instantiate_proof_tree_for_nested_goal(
251+
GoalSource::Misc,
252+
Goal::new(infcx.tcx, obligation.param_env, obligation.predicate),
253+
self.span(),
254+
);
255+
// Skip nested goals that aren't the *reason* for our goal's failure.
256+
match self.consider_ambiguities {
257+
true if matches!(
258+
nested_goal.result(),
259+
Ok(Certainty::Maybe(MaybeCause::Ambiguity))
260+
) => {}
261+
false if matches!(nested_goal.result(), Err(_)) => {}
262+
_ => continue,
263+
}
264+
265+
self.with_derived_obligation(obligation, |this| nested_goal.visit_with(this))?;
266+
}
267+
268+
ControlFlow::Break(self.obligation.clone())
269+
}
235270
}
236271

237272
impl<'tcx> ProofTreeVisitor<'tcx> for BestObligation<'tcx> {
@@ -282,6 +317,12 @@ impl<'tcx> ProofTreeVisitor<'tcx> for BestObligation<'tcx> {
282317
polarity: ty::PredicatePolarity::Positive,
283318
}))
284319
}
320+
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
321+
// HACK: We walk the nested obligations for a well-formed arg manually,
322+
// since there's nontrivial logic in `wf.rs` to set up an obligation cause.
323+
// Ideally we'd be able to track this better.
324+
return self.visit_well_formed_goal(candidate, arg);
325+
}
285326
_ => ChildMode::PassThrough,
286327
};
287328

@@ -387,7 +428,6 @@ enum ChildMode<'tcx> {
387428
// and skip all `GoalSource::Misc`, which represent useless obligations
388429
// such as alias-eq which may not hold.
389430
Host(ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>),
390-
WellFormed,
391431
// Skip trying to derive an `ObligationCause` from this obligation, and
392432
// report *all* sub-obligations as if they came directly from the parent
393433
// obligation.

compiler/rustc_trait_selection/src/solve/inspect/analyse.rs

Lines changed: 46 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -194,47 +194,57 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> {
194194

195195
let goals = instantiated_goals
196196
.into_iter()
197-
.map(|(source, goal)| match goal.predicate.kind().no_bound_vars() {
198-
Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })) => {
199-
let unconstrained_term = match term.unpack() {
200-
ty::TermKind::Ty(_) => infcx.next_ty_var(span).into(),
201-
ty::TermKind::Const(_) => infcx.next_const_var(span).into(),
202-
};
203-
let goal =
204-
goal.with(infcx.tcx, ty::NormalizesTo { alias, term: unconstrained_term });
205-
// We have to use a `probe` here as evaluating a `NormalizesTo` can constrain the
206-
// expected term. This means that candidates which only fail due to nested goals
207-
// and which normalize to a different term then the final result could ICE: when
208-
// building their proof tree, the expected term was unconstrained, but when
209-
// instantiating the candidate it is already constrained to the result of another
210-
// candidate.
211-
let proof_tree = infcx
212-
.probe(|_| infcx.evaluate_root_goal_raw(goal, GenerateProofTree::Yes).1);
213-
InspectGoal::new(
214-
infcx,
215-
self.goal.depth + 1,
216-
proof_tree.unwrap(),
217-
Some(NormalizesToTermHack { term, unconstrained_term }),
218-
source,
219-
)
220-
}
221-
_ => {
222-
// We're using a probe here as evaluating a goal could constrain
223-
// inference variables by choosing one candidate. If we then recurse
224-
// into another candidate who ends up with different inference
225-
// constraints, we get an ICE if we already applied the constraints
226-
// from the chosen candidate.
227-
let proof_tree = infcx
228-
.probe(|_| infcx.evaluate_root_goal(goal, GenerateProofTree::Yes).1)
229-
.unwrap();
230-
InspectGoal::new(infcx, self.goal.depth + 1, proof_tree, None, source)
231-
}
232-
})
197+
.map(|(source, goal)| self.instantiate_proof_tree_for_nested_goal(source, goal, span))
233198
.collect();
234199

235200
(goals, opt_impl_args)
236201
}
237202

203+
pub fn instantiate_proof_tree_for_nested_goal(
204+
&self,
205+
source: GoalSource,
206+
goal: Goal<'tcx, ty::Predicate<'tcx>>,
207+
span: Span,
208+
) -> InspectGoal<'a, 'tcx> {
209+
let infcx = self.goal.infcx;
210+
match goal.predicate.kind().no_bound_vars() {
211+
Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })) => {
212+
let unconstrained_term = match term.unpack() {
213+
ty::TermKind::Ty(_) => infcx.next_ty_var(span).into(),
214+
ty::TermKind::Const(_) => infcx.next_const_var(span).into(),
215+
};
216+
let goal =
217+
goal.with(infcx.tcx, ty::NormalizesTo { alias, term: unconstrained_term });
218+
// We have to use a `probe` here as evaluating a `NormalizesTo` can constrain the
219+
// expected term. This means that candidates which only fail due to nested goals
220+
// and which normalize to a different term then the final result could ICE: when
221+
// building their proof tree, the expected term was unconstrained, but when
222+
// instantiating the candidate it is already constrained to the result of another
223+
// candidate.
224+
let proof_tree =
225+
infcx.probe(|_| infcx.evaluate_root_goal_raw(goal, GenerateProofTree::Yes).1);
226+
InspectGoal::new(
227+
infcx,
228+
self.goal.depth + 1,
229+
proof_tree.unwrap(),
230+
Some(NormalizesToTermHack { term, unconstrained_term }),
231+
source,
232+
)
233+
}
234+
_ => {
235+
// We're using a probe here as evaluating a goal could constrain
236+
// inference variables by choosing one candidate. If we then recurse
237+
// into another candidate who ends up with different inference
238+
// constraints, we get an ICE if we already applied the constraints
239+
// from the chosen candidate.
240+
let proof_tree = infcx
241+
.probe(|_| infcx.evaluate_root_goal(goal, GenerateProofTree::Yes).1)
242+
.unwrap();
243+
InspectGoal::new(infcx, self.goal.depth + 1, proof_tree, None, source)
244+
}
245+
}
246+
}
247+
238248
/// Visit all nested goals of this candidate, rolling back
239249
/// all inference constraints.
240250
pub fn visit_nested_in_probe<V: ProofTreeVisitor<'tcx>>(&self, visitor: &mut V) -> V::Result {

compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ pub fn compute_implied_outlives_bounds_inner<'tcx>(
9090

9191
// From the full set of obligations, just filter down to the region relationships.
9292
for obligation in
93-
wf::unnormalized_obligations(ocx.infcx, param_env, arg).into_iter().flatten()
93+
wf::unnormalized_obligations(ocx.infcx, param_env, arg, DUMMY_SP, CRATE_DEF_ID)
94+
.into_iter()
95+
.flatten()
9496
{
9597
assert!(!obligation.has_escaping_bound_vars());
9698
let Some(pred) = obligation.predicate.kind().no_bound_vars() else {

compiler/rustc_trait_selection/src/traits/wf.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use rustc_middle::ty::{
88
self, GenericArg, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable,
99
TypeVisitable, TypeVisitableExt, TypeVisitor,
1010
};
11-
use rustc_span::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
12-
use rustc_span::{DUMMY_SP, Span};
11+
use rustc_span::Span;
12+
use rustc_span::def_id::{DefId, LocalDefId};
1313
use tracing::{debug, instrument, trace};
1414

1515
use crate::infer::InferCtxt;
@@ -89,6 +89,8 @@ pub fn unnormalized_obligations<'tcx>(
8989
infcx: &InferCtxt<'tcx>,
9090
param_env: ty::ParamEnv<'tcx>,
9191
arg: GenericArg<'tcx>,
92+
span: Span,
93+
body_id: LocalDefId,
9294
) -> Option<PredicateObligations<'tcx>> {
9395
debug_assert_eq!(arg, infcx.resolve_vars_if_possible(arg));
9496

@@ -106,8 +108,8 @@ pub fn unnormalized_obligations<'tcx>(
106108
let mut wf = WfPredicates {
107109
infcx,
108110
param_env,
109-
body_id: CRATE_DEF_ID,
110-
span: DUMMY_SP,
111+
body_id,
112+
span,
111113
out: PredicateObligations::new(),
112114
recursion_depth: 0,
113115
item: None,

tests/ui/associated-inherent-types/bugs/wf-check-skipped.next.stderr

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ LL | fn main() -> Foo::Bar::<Vec<[u32]>> {}
55
| ^^^^^^^^^^ doesn't have a size known at compile-time
66
|
77
= help: the trait `Sized` is not implemented for `[u32]`
8+
note: required by an implicit `Sized` bound in `Vec`
9+
--> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
810

911
error: aborting due to 1 previous error
1012

tests/ui/const-generics/issues/issue-88119.stderr

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,35 +6,29 @@ LL | #![feature(const_trait_impl, generic_const_exprs)]
66
|
77
= help: remove one of these features
88

9-
error[E0284]: type annotations needed: cannot normalize `<&T as ConstName>::{constant#0}`
10-
--> $DIR/issue-88119.rs:19:49
9+
error[E0284]: type annotations needed: cannot satisfy `the constant `name_len::<T>()` can be evaluated`
10+
--> $DIR/issue-88119.rs:21:5
1111
|
12-
LL | impl<T: ?Sized + ConstName> const ConstName for &T
13-
| ^^ cannot normalize `<&T as ConstName>::{constant#0}`
12+
LL | [(); name_len::<T>()]:,
13+
| ^^^^^^^^^^^^^^^^^^^^^ cannot satisfy `the constant `name_len::<T>()` can be evaluated`
1414
|
15-
note: required for `&T` to implement `~const ConstName`
16-
--> $DIR/issue-88119.rs:19:35
15+
note: required by a bound in `<&T as ConstName>`
16+
--> $DIR/issue-88119.rs:21:10
1717
|
18-
LL | impl<T: ?Sized + ConstName> const ConstName for &T
19-
| ^^^^^^^^^ ^^
20-
LL | where
2118
LL | [(); name_len::<T>()]:,
22-
| --------------------- unsatisfied trait bound introduced here
19+
| ^^^^^^^^^^^^^^^ required by this bound in `<&T as ConstName>`
2320

24-
error[E0284]: type annotations needed: cannot normalize `<&mut T as ConstName>::{constant#0}`
25-
--> $DIR/issue-88119.rs:26:49
21+
error[E0284]: type annotations needed: cannot satisfy `the constant `name_len::<T>()` can be evaluated`
22+
--> $DIR/issue-88119.rs:28:5
2623
|
27-
LL | impl<T: ?Sized + ConstName> const ConstName for &mut T
28-
| ^^^^^^ cannot normalize `<&mut T as ConstName>::{constant#0}`
24+
LL | [(); name_len::<T>()]:,
25+
| ^^^^^^^^^^^^^^^^^^^^^ cannot satisfy `the constant `name_len::<T>()` can be evaluated`
2926
|
30-
note: required for `&mut T` to implement `~const ConstName`
31-
--> $DIR/issue-88119.rs:26:35
27+
note: required by a bound in `<&mut T as ConstName>`
28+
--> $DIR/issue-88119.rs:28:10
3229
|
33-
LL | impl<T: ?Sized + ConstName> const ConstName for &mut T
34-
| ^^^^^^^^^ ^^^^^^
35-
LL | where
3630
LL | [(); name_len::<T>()]:,
37-
| --------------------- unsatisfied trait bound introduced here
31+
| ^^^^^^^^^^^^^^^ required by this bound in `<&mut T as ConstName>`
3832

3933
error: aborting due to 3 previous errors
4034

tests/ui/diagnostic_namespace/do_not_recommend/as_expression.next.stderr

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,13 @@ LL | where
1616
LL | T: AsExpression<Self::SqlType>,
1717
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Foo::check`
1818

19-
error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
20-
--> $DIR/as_expression.rs:55:15
21-
|
22-
LL | SelectInt.check("bar");
23-
| ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
24-
|
25-
= help: the trait `AsExpression<Integer>` is not implemented for `&str`
26-
but trait `AsExpression<Text>` is implemented for it
27-
= help: for that trait implementation, expected `Text`, found `Integer`
28-
2919
error[E0271]: type mismatch resolving `<SelectInt as Expression>::SqlType == Text`
3020
--> $DIR/as_expression.rs:55:5
3121
|
3222
LL | SelectInt.check("bar");
3323
| ^^^^^^^^^^^^^^^^^^^^^^ expected `Text`, found `Integer`
3424

35-
error: aborting due to 3 previous errors
25+
error: aborting due to 2 previous errors
3626

3727
Some errors have detailed explanations: E0271, E0277.
3828
For more information about an error, try `rustc --explain E0271`.

tests/ui/diagnostic_namespace/do_not_recommend/as_expression.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ impl<T> Foo for T where T: Expression {}
5353

5454
fn main() {
5555
SelectInt.check("bar");
56-
//~^ ERROR the trait bound `&str: AsExpression<Integer>` is not satisfied
57-
//[next]~| the trait bound `&str: AsExpression<<SelectInt as Expression>::SqlType>` is not satisfied
56+
//[current]~^ ERROR the trait bound `&str: AsExpression<Integer>` is not satisfied
57+
//[next]~^^ the trait bound `&str: AsExpression<<SelectInt as Expression>::SqlType>` is not satisfied
5858
//[next]~| type mismatch
5959
}

tests/ui/impl-trait/in-trait/alias-bounds-when-not-wf.stderr

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ help: this trait has no implementations, consider adding one
1818
|
1919
LL | trait Foo {}
2020
| ^^^^^^^^^
21+
note: required by a bound in `A`
22+
--> $DIR/alias-bounds-when-not-wf.rs:8:11
23+
|
24+
LL | type A<T: Foo> = T;
25+
| ^^^ required by this bound in `A`
2126

2227
error[E0277]: the trait bound `usize: Foo` is not satisfied
2328
--> $DIR/alias-bounds-when-not-wf.rs:16:10

0 commit comments

Comments
 (0)