Skip to content

Commit

Permalink
Use a proof tree visitor to refine the Obligation for error reporting
Browse files Browse the repository at this point in the history
  • Loading branch information
compiler-errors committed May 1, 2024
1 parent 12d2e7c commit 4246ba0
Show file tree
Hide file tree
Showing 32 changed files with 406 additions and 69 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
} else {
self.infcx.enter_forall(kind, |kind| {
let goal = goal.with(self.tcx(), ty::Binder::dummy(kind));
self.add_goal(GoalSource::Misc, goal);
self.add_goal(GoalSource::ImplWhereBound, goal);
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
})
}
Expand Down
155 changes: 146 additions & 9 deletions compiler/rustc_trait_selection/src/solve/fulfill.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
use std::mem;
use std::ops::ControlFlow;

use rustc_infer::infer::InferCtxt;
use rustc_infer::traits::solve::MaybeCause;
use rustc_infer::traits::query::NoSolution;
use rustc_infer::traits::solve::inspect::ProbeKind;
use rustc_infer::traits::solve::{CandidateSource, GoalSource, MaybeCause};
use rustc_infer::traits::{
query::NoSolution, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes,
self, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, Obligation,
PredicateObligation, SelectionError, TraitEngine,
};
use rustc_middle::ty;
use rustc_middle::ty::error::{ExpectedFound, TypeError};

use super::eval_ctxt::GenerateProofTree;
use super::inspect::{ProofTreeInferCtxtExt, ProofTreeVisitor};
use super::{Certainty, InferCtxtEvalExt};

/// A trait engine using the new trait solver.
Expand Down Expand Up @@ -133,9 +137,9 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> {
.collect();

errors.extend(self.obligations.overflowed.drain(..).map(|obligation| FulfillmentError {
root_obligation: obligation.clone(),
obligation: find_best_leaf_obligation(infcx, &obligation),
code: FulfillmentErrorCode::Ambiguity { overflow: Some(true) },
obligation,
root_obligation: obligation,
}));

errors
Expand Down Expand Up @@ -192,8 +196,10 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> {

fn fulfillment_error_for_no_solution<'tcx>(
infcx: &InferCtxt<'tcx>,
obligation: PredicateObligation<'tcx>,
root_obligation: PredicateObligation<'tcx>,
) -> FulfillmentError<'tcx> {
let obligation = find_best_leaf_obligation(infcx, &root_obligation);

let code = match obligation.predicate.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(_)) => {
FulfillmentErrorCode::ProjectionError(
Expand All @@ -213,14 +219,14 @@ fn fulfillment_error_for_no_solution<'tcx>(
}
ty::PredicateKind::Subtype(pred) => {
let (a, b) = infcx.enter_forall_and_leak_universe(
obligation.predicate.kind().rebind((pred.a, pred.b)),
root_obligation.predicate.kind().rebind((pred.a, pred.b)),
);
let expected_found = ExpectedFound::new(true, a, b);
FulfillmentErrorCode::SubtypeError(expected_found, TypeError::Sorts(expected_found))
}
ty::PredicateKind::Coerce(pred) => {
let (a, b) = infcx.enter_forall_and_leak_universe(
obligation.predicate.kind().rebind((pred.a, pred.b)),
root_obligation.predicate.kind().rebind((pred.a, pred.b)),
);
let expected_found = ExpectedFound::new(false, a, b);
FulfillmentErrorCode::SubtypeError(expected_found, TypeError::Sorts(expected_found))
Expand All @@ -234,7 +240,8 @@ fn fulfillment_error_for_no_solution<'tcx>(
bug!("unexpected goal: {obligation:?}")
}
};
FulfillmentError { root_obligation: obligation.clone(), code, obligation }

FulfillmentError { obligation, code, root_obligation }
}

fn fulfillment_error_for_stalled<'tcx>(
Expand All @@ -258,5 +265,135 @@ fn fulfillment_error_for_stalled<'tcx>(
}
});

FulfillmentError { obligation: obligation.clone(), code, root_obligation: obligation }
FulfillmentError {
obligation: find_best_leaf_obligation(infcx, &obligation),
code,
root_obligation: obligation,
}
}

struct BestObligation<'tcx> {
obligation: PredicateObligation<'tcx>,
}

impl<'tcx> BestObligation<'tcx> {
fn with_derived_obligation(
&mut self,
derive_obligation: impl FnOnce(&mut Self) -> PredicateObligation<'tcx>,
and_then: impl FnOnce(&mut Self) -> <Self as ProofTreeVisitor<'tcx>>::Result,
) -> <Self as ProofTreeVisitor<'tcx>>::Result {
let derived_obligation = derive_obligation(self);
let old_obligation = std::mem::replace(&mut self.obligation, derived_obligation);
let res = and_then(self);
self.obligation = old_obligation;
res
}
}

impl<'tcx> ProofTreeVisitor<'tcx> for BestObligation<'tcx> {
type Result = ControlFlow<PredicateObligation<'tcx>>;

fn span(&self) -> rustc_span::Span {
self.obligation.cause.span
}

fn visit_goal(&mut self, goal: &super::inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
let candidates = goal.candidates();
// FIXME: Throw out candidates that have no failing WC and >1 failing misc goal.

// HACK:
if self.obligation.recursion_depth > 3 {
return ControlFlow::Break(self.obligation.clone());
}

let [candidate] = candidates.as_slice() else {
return ControlFlow::Break(self.obligation.clone());
};

// FIXME: Could we extract a trait ref from a projection here too?
// FIXME: Also, what about considering >1 layer up the stack? May be necessary
// for normalizes-to.
let Some(parent_trait_pred) = goal.goal().predicate.to_opt_poly_trait_pred() else {
return ControlFlow::Break(self.obligation.clone());
};

let tcx = goal.infcx().tcx;
let mut impl_where_bound_count = 0;
for nested_goal in candidate.instantiate_nested_goals(self.span()) {
if matches!(nested_goal.source(), GoalSource::ImplWhereBound) {
impl_where_bound_count += 1;
} else {
continue;
}

// Skip nested goals that hold.
if matches!(nested_goal.result(), Ok(Certainty::Yes)) {
continue;
}

self.with_derived_obligation(
|self_| {
let mut cause = self_.obligation.cause.clone();
cause = match candidate.kind() {
ProbeKind::TraitCandidate {
source: CandidateSource::Impl(impl_def_id),
result: _,
} => {
let idx = impl_where_bound_count - 1;
if let Some((_, span)) = tcx
.predicates_of(impl_def_id)
.instantiate_identity(tcx)
.iter()
.nth(idx)
{
cause.derived_cause(parent_trait_pred, |derived| {
traits::ImplDerivedObligation(Box::new(
traits::ImplDerivedObligationCause {
derived,
impl_or_alias_def_id: impl_def_id,
impl_def_predicate_index: Some(idx),
span,
},
))
})
} else {
cause
}
}
ProbeKind::TraitCandidate {
source: CandidateSource::BuiltinImpl(..),
result: _,
} => {
cause.derived_cause(parent_trait_pred, traits::BuiltinDerivedObligation)
}
_ => cause,
};

Obligation {
cause,
param_env: nested_goal.goal().param_env,
predicate: nested_goal.goal().predicate,
recursion_depth: self_.obligation.recursion_depth + 1,
}
},
|self_| self_.visit_goal(&nested_goal),
)?;
}

ControlFlow::Break(self.obligation.clone())
}
}

fn find_best_leaf_obligation<'tcx>(
infcx: &InferCtxt<'tcx>,
obligation: &PredicateObligation<'tcx>,
) -> PredicateObligation<'tcx> {
let obligation = infcx.resolve_vars_if_possible(obligation.clone());
infcx
.visit_proof_tree(
obligation.clone().into(),
&mut BestObligation { obligation: obligation.clone() },
)
.break_value()
.unwrap_or(obligation)
}
2 changes: 1 addition & 1 deletion tests/ui/coherence/occurs-check/opaques.next.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ error[E0282]: type annotations needed
--> $DIR/opaques.rs:13:20
|
LL | pub fn cast<T>(x: Container<Alias<T>, T>) -> Container<T, T> {
| ^ cannot infer type for struct `Container<T, T>`
| ^ cannot infer type for associated type `<T as Trait<T>>::Assoc`

error: aborting due to 2 previous errors

Expand Down
9 changes: 7 additions & 2 deletions tests/ui/for/issue-20605.next.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ error[E0277]: `dyn Iterator<Item = &'a mut u8>` is not an iterator
--> $DIR/issue-20605.rs:6:17
|
LL | for item in *things { *item = 0 }
| ^^^^^^^ `dyn Iterator<Item = &'a mut u8>` is not an iterator
| ^^^^^^^ the trait `IntoIterator` is not implemented for `dyn Iterator<Item = &'a mut u8>`
|
= help: the trait `IntoIterator` is not implemented for `dyn Iterator<Item = &'a mut u8>`
= note: the trait bound `dyn Iterator<Item = &'a mut u8>: IntoIterator` is not satisfied
= note: required for `dyn Iterator<Item = &'a mut u8>` to implement `IntoIterator`
help: consider mutably borrowing here
|
LL | for item in &mut *things { *item = 0 }
| ++++

error: the type `<dyn Iterator<Item = &'a mut u8> as IntoIterator>::IntoIter` is not well-formed
--> $DIR/issue-20605.rs:6:17
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,20 @@ error[E0283]: type annotations needed
LL | impls_indirect_leak::<Box<_>>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the function `impls_indirect_leak`
|
= note: cannot satisfy `for<'a> Box<_>: IndirectLeak<'a>`
note: multiple `impl`s satisfying `for<'a> Box<_>: Leak<'a>` found
--> $DIR/leak-check-in-selection-3.rs:9:1
|
LL | impl Leak<'_> for Box<u32> {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
LL | impl Leak<'static> for Box<u16> {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: required for `Box<_>` to implement `for<'a> IndirectLeak<'a>`
--> $DIR/leak-check-in-selection-3.rs:23:23
|
LL | impl<'a, T: Leak<'a>> IndirectLeak<'a> for T {}
| -------- ^^^^^^^^^^^^^^^^ ^
| |
| unsatisfied trait bound introduced here
note: required by a bound in `impls_indirect_leak`
--> $DIR/leak-check-in-selection-3.rs:25:27
|
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
error[E0277]: `impl Future<Output = ()>` cannot be sent between threads safely
error: future cannot be sent between threads safely
--> $DIR/auto-with-drop_tracking_mir.rs:25:13
|
LL | is_send(foo());
| ------- ^^^^^ `impl Future<Output = ()>` cannot be sent between threads safely
| |
| required by a bound introduced by this call
| ^^^^^ future returned by `foo` is not `Send`
|
= help: the trait `Send` is not implemented for `impl Future<Output = ()>`
= help: the trait `Sync` is not implemented for `impl Future<Output = ()>`, which is required by `impl Future<Output = ()>: Send`
note: future is not `Send` as this value is used across an await
--> $DIR/auto-with-drop_tracking_mir.rs:16:11
|
LL | let x = &NotSync;
| - has type `&NotSync` which is not `Send`
LL | bar().await;
| ^^^^^ await occurs here, with `x` maybe used later
note: required by a bound in `is_send`
--> $DIR/auto-with-drop_tracking_mir.rs:24:24
|
LL | fn is_send(_: impl Send) {}
| ^^^^ required by this bound in `is_send`
help: consider dereferencing here
|
LL | is_send(*foo());
| +

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.
2 changes: 1 addition & 1 deletion tests/ui/traits/next-solver/auto-with-drop_tracking_mir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ async fn bar() {}
fn main() {
fn is_send(_: impl Send) {}
is_send(foo());
//[fail]~^ ERROR `impl Future<Output = ()>` cannot be sent between threads safely
//[fail]~^ ERROR future cannot be sent between threads safely
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ fn foo<F: Fn<T>, T: Tuple>(f: Option<F>, t: T) {

fn main() {
foo::<fn() -> str, _>(None, ());
//~^ expected a `Fn<_>` closure, found `fn() -> str`
//~^ the size for values of type `str` cannot be known at compilation time
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
error[E0277]: expected a `Fn<_>` closure, found `fn() -> str`
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> $DIR/builtin-fn-must-return-sized.rs:15:11
|
LL | foo::<fn() -> str, _>(None, ());
| ^^^^^^^^^^^ expected an `Fn<_>` closure, found `fn() -> str`
| ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Fn<_>` is not implemented for `fn() -> str`
= help: within `fn() -> str`, the trait `Sized` is not implemented for `str`, which is required by `fn() -> str: Fn<_>`
= note: required because it appears within the type `fn() -> str`
note: required by a bound in `foo`
--> $DIR/builtin-fn-must-return-sized.rs:10:11
|
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
error[E0119]: conflicting implementations of trait `Trait` for type `W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<_>>>>>>>>>>>>>>>>>>>>>`
error[E0119]: conflicting implementations of trait `Trait` for type `W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<_>>>>>>>>>>>>>>>>>>>>>>`
--> $DIR/coherence-fulfill-overflow.rs:12:1
|
LL | impl<T: ?Sized + TwoW> Trait for W<T> {}
| ------------------------------------- first implementation here
LL | impl<T: ?Sized + TwoW> Trait for T {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<_>>>>>>>>>>>>>>>>>>>>>`
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<_>>>>>>>>>>>>>>>>>>>>>>`
|
= note: overflow evaluating the requirement `W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<_>>>>>>>>>>>>>>>>>>>>>: TwoW`
= note: overflow evaluating the requirement `W<W<W<W<W<W<W<W<W<W<W<W<W<W<_>>>>>>>>>>>>>>: TwoW`
= help: consider increasing the recursion limit by adding a `#![recursion_limit = "20"]` attribute to your crate (`coherence_fulfill_overflow`)

error: aborting due to 1 previous error
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
error[E0275]: overflow evaluating the requirement `W<_>: Trait`
error[E0275]: overflow evaluating the requirement `_: Sized`
--> $DIR/fixpoint-exponential-growth.rs:33:13
|
LL | impls::<W<_>>();
| ^^^^
|
note: required for `W<(W<_>, W<_>)>` to implement `Trait`
--> $DIR/fixpoint-exponential-growth.rs:23:12
|
LL | impl<T, U> Trait for W<(W<T>, W<U>)>
| - ^^^^^ ^^^^^^^^^^^^^^^
| |
| unsatisfied trait bound introduced here
note: required by a bound in `impls`
--> $DIR/fixpoint-exponential-growth.rs:30:13
|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ where
// entering the cycle from `A` fails, but would work if we were to use the cache
// result of `B<X>`.
impls_trait::<A<X>, _, _, _>();
//~^ ERROR the trait bound `A<X>: Trait<_, _, _>` is not satisfied
//~^ ERROR the trait bound `X: IncompleteGuidance<_, _>` is not satisfied
}

fn main() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
error[E0277]: the trait bound `A<X>: Trait<_, _, _>` is not satisfied
error[E0277]: the trait bound `X: IncompleteGuidance<_, _>` is not satisfied
--> $DIR/incompleteness-unstable-result.rs:63:19
|
LL | impls_trait::<A<X>, _, _, _>();
| ^^^^ the trait `Trait<_, _, _>` is not implemented for `A<X>`
| ^^^^ the trait `IncompleteGuidance<_, _>` is not implemented for `X`, which is required by `A<X>: Trait<_, _, _>`
|
= help: the trait `Trait<U, V, D>` is implemented for `A<T>`
= help: the following other types implement trait `IncompleteGuidance<T, V>`:
<T as IncompleteGuidance<U, i16>>
<T as IncompleteGuidance<U, i8>>
<T as IncompleteGuidance<U, u8>>
note: required for `A<X>` to implement `Trait<_, _, u8>`
--> $DIR/incompleteness-unstable-result.rs:32:50
|
LL | impl<T: ?Sized, U: ?Sized, V: ?Sized, D: ?Sized> Trait<U, V, D> for A<T>
| ^^^^^^^^^^^^^^ ^^^^
LL | where
LL | T: IncompleteGuidance<U, V>,
| ------------------------ unsatisfied trait bound introduced here
note: required by a bound in `impls_trait`
--> $DIR/incompleteness-unstable-result.rs:51:28
|
Expand Down

0 comments on commit 4246ba0

Please sign in to comment.