Skip to content

Commit 9fa165d

Browse files
committed
Point at impl blocks when they introduce unmet obligations
Group obligations by `impl` block that introduced them.
1 parent 8f433ad commit 9fa165d

File tree

9 files changed

+184
-59
lines changed

9 files changed

+184
-59
lines changed

compiler/rustc_typeck/src/check/method/mod.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub use self::CandidateSource::*;
1212
pub use self::MethodError::*;
1313

1414
use crate::check::FnCtxt;
15+
use crate::ObligationCause;
1516
use rustc_data_structures::sync::Lrc;
1617
use rustc_errors::{Applicability, DiagnosticBuilder};
1718
use rustc_hir as hir;
@@ -71,7 +72,8 @@ pub enum MethodError<'tcx> {
7172
#[derive(Debug)]
7273
pub struct NoMatchData<'tcx> {
7374
pub static_candidates: Vec<CandidateSource>,
74-
pub unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
75+
pub unsatisfied_predicates:
76+
Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
7577
pub out_of_scope_traits: Vec<DefId>,
7678
pub lev_candidate: Option<ty::AssocItem>,
7779
pub mode: probe::Mode,
@@ -80,7 +82,11 @@ pub struct NoMatchData<'tcx> {
8082
impl<'tcx> NoMatchData<'tcx> {
8183
pub fn new(
8284
static_candidates: Vec<CandidateSource>,
83-
unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
85+
unsatisfied_predicates: Vec<(
86+
ty::Predicate<'tcx>,
87+
Option<ty::Predicate<'tcx>>,
88+
Option<ObligationCause<'tcx>>,
89+
)>,
8490
out_of_scope_traits: Vec<DefId>,
8591
lev_candidate: Option<ty::AssocItem>,
8692
mode: probe::Mode,

compiler/rustc_typeck/src/check/method/probe.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ struct ProbeContext<'a, 'tcx> {
7878

7979
/// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
8080
/// for error reporting
81-
unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
81+
unsatisfied_predicates:
82+
Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
8283

8384
is_suggestion: IsSuggestion,
8485

@@ -1351,6 +1352,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
13511352
possibly_unsatisfied_predicates: &mut Vec<(
13521353
ty::Predicate<'tcx>,
13531354
Option<ty::Predicate<'tcx>>,
1355+
Option<ObligationCause<'tcx>>,
13541356
)>,
13551357
unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>,
13561358
) -> Option<PickResult<'tcx>>
@@ -1497,6 +1499,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
14971499
possibly_unsatisfied_predicates: &mut Vec<(
14981500
ty::Predicate<'tcx>,
14991501
Option<ty::Predicate<'tcx>>,
1502+
Option<ObligationCause<'tcx>>,
15001503
)>,
15011504
) -> ProbeResult {
15021505
debug!("consider_probe: self_ty={:?} probe={:?}", self_ty, probe);
@@ -1508,8 +1511,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
15081511
.sup(probe.xform_self_ty, self_ty)
15091512
{
15101513
Ok(InferOk { obligations, value: () }) => obligations,
1511-
Err(_) => {
1512-
debug!("--> cannot relate self-types");
1514+
Err(err) => {
1515+
debug!("--> cannot relate self-types {:?}", err);
15131516
return ProbeResult::NoMatch;
15141517
}
15151518
};
@@ -1558,7 +1561,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
15581561
let o = self.resolve_vars_if_possible(o);
15591562
if !self.predicate_may_hold(&o) {
15601563
result = ProbeResult::NoMatch;
1561-
possibly_unsatisfied_predicates.push((o.predicate, None));
1564+
possibly_unsatisfied_predicates.push((
1565+
o.predicate,
1566+
None,
1567+
Some(o.cause),
1568+
));
15621569
}
15631570
}
15641571
}
@@ -1604,16 +1611,19 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
16041611
} else {
16051612
Some(predicate)
16061613
};
1607-
possibly_unsatisfied_predicates
1608-
.push((nested_predicate, p));
1614+
possibly_unsatisfied_predicates.push((
1615+
nested_predicate,
1616+
p,
1617+
Some(obligation.cause.clone()),
1618+
));
16091619
}
16101620
}
16111621
}
16121622
_ => {
16131623
// Some nested subobligation of this predicate
16141624
// failed.
16151625
let predicate = self.resolve_vars_if_possible(predicate);
1616-
possibly_unsatisfied_predicates.push((predicate, None));
1626+
possibly_unsatisfied_predicates.push((predicate, None, None));
16171627
}
16181628
}
16191629
false
@@ -1632,7 +1642,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
16321642
let o = self.resolve_vars_if_possible(o);
16331643
if !self.predicate_may_hold(&o) {
16341644
result = ProbeResult::NoMatch;
1635-
possibly_unsatisfied_predicates.push((o.predicate, None));
1645+
possibly_unsatisfied_predicates.push((o.predicate, None, Some(o.cause)));
16361646
}
16371647
}
16381648

compiler/rustc_typeck/src/check/method/suggest.rs

Lines changed: 105 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ use rustc_span::lev_distance;
1717
use rustc_span::symbol::{kw, sym, Ident};
1818
use rustc_span::{source_map, FileName, MultiSpan, Span, Symbol};
1919
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
20-
use rustc_trait_selection::traits::{FulfillmentError, Obligation};
20+
use rustc_trait_selection::traits::{
21+
FulfillmentError, Obligation, ObligationCause, ObligationCauseCode,
22+
};
2123

2224
use std::cmp::Ordering;
2325
use std::iter;
@@ -791,9 +793,88 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
791793
_ => None,
792794
}
793795
};
796+
797+
// Find all the requirements that come from a local `impl` block.
798+
let mut skip_list: FxHashSet<_> = Default::default();
799+
let mut spanned_predicates: FxHashMap<MultiSpan, _> = Default::default();
800+
for (data, p, parent_p) in unsatisfied_predicates
801+
.iter()
802+
.filter_map(|(p, parent, c)| c.as_ref().map(|c| (p, parent, c)))
803+
.filter_map(|(p, parent, c)| match c.code {
804+
ObligationCauseCode::ImplDerivedObligation(ref data) => {
805+
Some((data, p, parent))
806+
}
807+
_ => None,
808+
})
809+
{
810+
let parent_trait_ref = data.parent_trait_ref;
811+
let parent_def_id = parent_trait_ref.def_id();
812+
let path = parent_trait_ref.print_only_trait_path();
813+
let tr_self_ty = parent_trait_ref.skip_binder().self_ty();
814+
let mut candidates = vec![];
815+
self.tcx.for_each_relevant_impl(
816+
parent_def_id,
817+
parent_trait_ref.self_ty().skip_binder(),
818+
|impl_def_id| match self.tcx.hir().get_if_local(impl_def_id) {
819+
Some(Node::Item(hir::Item {
820+
kind: hir::ItemKind::Impl(hir::Impl { .. }),
821+
..
822+
})) => {
823+
candidates.push(impl_def_id);
824+
}
825+
_ => {}
826+
},
827+
);
828+
if let [def_id] = &candidates[..] {
829+
match self.tcx.hir().get_if_local(*def_id) {
830+
Some(Node::Item(hir::Item {
831+
kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
832+
..
833+
})) => {
834+
if let Some(pred) = parent_p {
835+
// Done to add the "doesn't satisfy" `span_label`.
836+
let _ = format_pred(*pred);
837+
}
838+
skip_list.insert(p);
839+
let mut spans = Vec::with_capacity(2);
840+
if let Some(trait_ref) = of_trait {
841+
spans.push(trait_ref.path.span);
842+
}
843+
spans.push(self_ty.span);
844+
let entry = spanned_predicates.entry(spans.into());
845+
entry
846+
.or_insert_with(|| (path, tr_self_ty, Vec::new()))
847+
.2
848+
.push(p);
849+
}
850+
_ => {}
851+
}
852+
}
853+
}
854+
for (span, (path, self_ty, preds)) in spanned_predicates {
855+
err.span_note(
856+
span,
857+
&format!(
858+
"the following trait bounds were not satisfied because of the \
859+
requirements of the implementation of `{}` for `{}`:\n{}",
860+
path,
861+
self_ty,
862+
preds
863+
.into_iter()
864+
// .map(|pred| format!("{:?}", pred))
865+
.filter_map(|pred| format_pred(*pred))
866+
.map(|(p, _)| format!("`{}`", p))
867+
.collect::<Vec<_>>()
868+
.join("\n"),
869+
),
870+
);
871+
}
872+
873+
// The requirements that didn't have an `impl` span to show.
794874
let mut bound_list = unsatisfied_predicates
795875
.iter()
796-
.filter_map(|(pred, parent_pred)| {
876+
.filter(|(pred, _, _parent_pred)| !skip_list.contains(&pred))
877+
.filter_map(|(pred, parent_pred, _cause)| {
797878
format_pred(*pred).map(|(p, self_ty)| match parent_pred {
798879
None => format!("`{}`", &p),
799880
Some(parent_pred) => match format_pred(*parent_pred) {
@@ -836,7 +917,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
836917
for (span, msg) in bound_spans.into_iter() {
837918
err.span_label(span, &msg);
838919
}
839-
if !bound_list.is_empty() {
920+
if !bound_list.is_empty() || !skip_list.is_empty() {
840921
let bound_list = bound_list
841922
.into_iter()
842923
.map(|(_, path)| path)
@@ -846,9 +927,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
846927
err.set_primary_message(&format!(
847928
"the {item_kind} `{item_name}` exists for {actual_prefix} `{ty_str}`, but its trait bounds were not satisfied"
848929
));
849-
err.note(&format!(
850-
"the following trait bounds were not satisfied:\n{bound_list}"
851-
));
930+
if !bound_list.is_empty() {
931+
err.note(&format!(
932+
"the following trait bounds were not satisfied:\n{bound_list}"
933+
));
934+
}
852935
self.suggest_derive(&mut err, &unsatisfied_predicates);
853936

854937
unsatisfied_bounds = true;
@@ -1062,18 +1145,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
10621145
err.span_note(spans, &msg);
10631146
}
10641147

1065-
let preds: Vec<_> = errors.iter().map(|e| (e.obligation.predicate, None)).collect();
1148+
let preds: Vec<_> = errors
1149+
.iter()
1150+
.map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
1151+
.collect();
10661152
self.suggest_derive(err, &preds);
10671153
}
10681154

10691155
fn suggest_derive(
10701156
&self,
10711157
err: &mut DiagnosticBuilder<'_>,
1072-
unsatisfied_predicates: &Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
1158+
unsatisfied_predicates: &Vec<(
1159+
ty::Predicate<'tcx>,
1160+
Option<ty::Predicate<'tcx>>,
1161+
Option<ObligationCause<'tcx>>,
1162+
)>,
10731163
) {
10741164
let mut derives = Vec::<(String, Span, String)>::new();
10751165
let mut traits = Vec::<Span>::new();
1076-
for (pred, _) in unsatisfied_predicates {
1166+
for (pred, _, _) in unsatisfied_predicates {
10771167
let trait_pred = match pred.kind().skip_binder() {
10781168
ty::PredicateKind::Trait(trait_pred) => trait_pred,
10791169
_ => continue,
@@ -1264,7 +1354,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12641354
item_name: Ident,
12651355
source: SelfSource<'tcx>,
12661356
valid_out_of_scope_traits: Vec<DefId>,
1267-
unsatisfied_predicates: &[(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)],
1357+
unsatisfied_predicates: &[(
1358+
ty::Predicate<'tcx>,
1359+
Option<ty::Predicate<'tcx>>,
1360+
Option<ObligationCause<'tcx>>,
1361+
)],
12681362
unsatisfied_bounds: bool,
12691363
) {
12701364
let mut alt_rcvr_sugg = false;
@@ -1380,7 +1474,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
13801474
// this isn't perfect (that is, there are cases when
13811475
// implementing a trait would be legal but is rejected
13821476
// here).
1383-
unsatisfied_predicates.iter().all(|(p, _)| {
1477+
unsatisfied_predicates.iter().all(|(p, _, _)| {
13841478
match p.kind().skip_binder() {
13851479
// Hide traits if they are present in predicates as they can be fixed without
13861480
// having to implement them.

src/test/ui/derives/derive-assoc-type-not-impl.stderr

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,16 @@ LL | struct NotClone;
1313
LL | Bar::<NotClone> { x: 1 }.clone();
1414
| ^^^^^ method cannot be called on `Bar<NotClone>` due to unsatisfied trait bounds
1515
|
16-
= note: the following trait bounds were not satisfied:
17-
`NotClone: Clone`
18-
which is required by `Bar<NotClone>: Clone`
16+
note: the following trait bounds were not satisfied because of the requirements of the implementation of `Clone` for `_`:
17+
`NotClone: Clone`
18+
--> $DIR/derive-assoc-type-not-impl.rs:6:10
19+
|
20+
LL | #[derive(Clone)]
21+
| ^^^^^
1922
= help: items from traits can only be used if the trait is implemented and in scope
2023
= note: the following trait defines an item `clone`, perhaps you need to implement it:
2124
candidate #1: `Clone`
25+
= note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info)
2226
help: consider annotating `NotClone` with `#[derive(Clone)]`
2327
|
2428
LL | #[derive(Clone)]

src/test/ui/generic-associated-types/method-unsatified-assoc-type-predicate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ trait M {
1212
}
1313

1414
impl<T: X<Y<i32> = i32>> M for T {}
15+
//~^ NOTE the following trait bounds were not satisfied
1516

1617
struct S;
1718
//~^ NOTE method `f` not found for this
@@ -26,7 +27,6 @@ fn f(a: S) {
2627
a.f();
2728
//~^ ERROR the method `f` exists for struct `S`, but its trait bounds were not satisfied
2829
//~| NOTE method cannot be called on `S` due to unsatisfied trait bounds
29-
//~| NOTE the following trait bounds were not satisfied:
3030
}
3131

3232
fn main() {}

src/test/ui/generic-associated-types/method-unsatified-assoc-type-predicate.stderr

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error[E0599]: the method `f` exists for struct `S`, but its trait bounds were not satisfied
2-
--> $DIR/method-unsatified-assoc-type-predicate.rs:26:7
2+
--> $DIR/method-unsatified-assoc-type-predicate.rs:27:7
33
|
44
LL | struct S;
55
| ---------
@@ -11,9 +11,12 @@ LL | struct S;
1111
LL | a.f();
1212
| ^ method cannot be called on `S` due to unsatisfied trait bounds
1313
|
14-
= note: the following trait bounds were not satisfied:
15-
`<S as X>::Y<i32> = i32`
16-
which is required by `S: M`
14+
note: the following trait bounds were not satisfied because of the requirements of the implementation of `M` for `_`:
15+
`<S as X>::Y<i32> = i32`
16+
--> $DIR/method-unsatified-assoc-type-predicate.rs:14:26
17+
|
18+
LL | impl<T: X<Y<i32> = i32>> M for T {}
19+
| ^ ^
1720

1821
error: aborting due to previous error
1922

0 commit comments

Comments
 (0)