Skip to content

Commit

Permalink
Rollup merge of rust-lang#120507 - estebank:issue-108428, r=davidtwco
Browse files Browse the repository at this point in the history
Account for non-overlapping unmet trait bounds in suggestion

When a method not found on a type parameter could have been provided by any
of multiple traits, suggest each trait individually, instead of a single
suggestion to restrict the type parameter with *all* of them.

Before:

```
error[E0599]: the method `cmp` exists for reference `&T`, but its trait bounds were not satisfied
  --> $DIR/method-on-unbounded-type-param.rs:5:10
   |
LL |     (&a).cmp(&b)
   |          ^^^ method cannot be called on `&T` due to unsatisfied trait bounds
   |
   = note: the following trait bounds were not satisfied:
           `T: Ord`
           which is required by `&T: Ord`
           `&T: Iterator`
           which is required by `&mut &T: Iterator`
           `T: Iterator`
           which is required by `&mut T: Iterator`
help: consider restricting the type parameters to satisfy the trait bounds
   |
LL | fn g<T>(a: T, b: T) -> std::cmp::Ordering where T: Iterator, T: Ord {
   |                                           +++++++++++++++++++++++++
```

After:

```
error[E0599]: the method `cmp` exists for reference `&T`, but its trait bounds were not satisfied
  --> $DIR/method-on-unbounded-type-param.rs:5:10
   |
LL |     (&a).cmp(&b)
   |          ^^^ method cannot be called on `&T` due to unsatisfied trait bounds
   |
   = note: the following trait bounds were not satisfied:
           `T: Ord`
           which is required by `&T: Ord`
           `&T: Iterator`
           which is required by `&mut &T: Iterator`
           `T: Iterator`
           which is required by `&mut T: Iterator`
   = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `cmp`, perhaps you need to restrict type parameter `T` with one of them:
   |
LL | fn g<T: Ord>(a: T, b: T) -> std::cmp::Ordering {
   |       +++++
LL | fn g<T: Iterator>(a: T, b: T) -> std::cmp::Ordering {
   |       ++++++++++
```

Fix rust-lang#108428.

Follow up to rust-lang#120396, only last commit is relevant.
  • Loading branch information
matthiaskrgr authored Feb 6, 2024
2 parents 2a488c4 + 5c41409 commit ab20137
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 52 deletions.
58 changes: 21 additions & 37 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

let mut bound_spans: SortedMap<Span, Vec<String>> = Default::default();
let mut restrict_type_params = false;
let mut suggested_derive = false;
let mut unsatisfied_bounds = false;
if item_name.name == sym::count && self.is_slice_ty(rcvr_ty, span) {
let msg = "consider using `len` instead";
Expand Down Expand Up @@ -928,20 +929,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.enumerate()
.collect::<Vec<(usize, String)>>();

for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
restrict_type_params = true;
// #74886: Sort here so that the output is always the same.
let obligations = obligations.into_sorted_stable_ord();
err.span_suggestion_verbose(
span,
format!(
"consider restricting the type parameter{s} to satisfy the \
trait bound{s}",
s = pluralize!(obligations.len())
),
format!("{} {}", add_where_or_comma, obligations.join(", ")),
Applicability::MaybeIncorrect,
);
if !matches!(rcvr_ty.peel_refs().kind(), ty::Param(_)) {
for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
restrict_type_params = true;
// #74886: Sort here so that the output is always the same.
let obligations = obligations.into_sorted_stable_ord();
err.span_suggestion_verbose(
span,
format!(
"consider restricting the type parameter{s} to satisfy the trait \
bound{s}",
s = pluralize!(obligations.len())
),
format!("{} {}", add_where_or_comma, obligations.join(", ")),
Applicability::MaybeIncorrect,
);
}
}

bound_list.sort_by(|(_, a), (_, b)| a.cmp(b)); // Sort alphabetically.
Expand Down Expand Up @@ -989,7 +992,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"the following trait bounds were not satisfied:\n{bound_list}"
));
}
self.suggest_derive(&mut err, unsatisfied_predicates);
suggested_derive = self.suggest_derive(&mut err, unsatisfied_predicates);

unsatisfied_bounds = true;
}
Expand Down Expand Up @@ -1212,7 +1215,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
}

if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params {
if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params || suggested_derive {
} else {
self.suggest_traits_to_import(
&mut err,
Expand All @@ -1222,7 +1225,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
args.map(|args| args.len() + 1),
source,
no_match_data.out_of_scope_traits.clone(),
unsatisfied_predicates,
static_candidates,
unsatisfied_bounds,
expected.only_has_type(self),
Expand Down Expand Up @@ -2482,7 +2484,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Option<ty::Predicate<'tcx>>,
Option<ObligationCause<'tcx>>,
)],
) {
) -> bool {
let mut derives = self.note_predicate_source_and_get_derives(err, unsatisfied_predicates);
derives.sort();
derives.dedup();
Expand All @@ -2507,6 +2509,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Applicability::MaybeIncorrect,
);
}
!derives_grouped.is_empty()
}

fn note_derefed_ty_has_method(
Expand Down Expand Up @@ -2709,11 +2712,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
inputs_len: Option<usize>,
source: SelfSource<'tcx>,
valid_out_of_scope_traits: Vec<DefId>,
unsatisfied_predicates: &[(
ty::Predicate<'tcx>,
Option<ty::Predicate<'tcx>>,
Option<ObligationCause<'tcx>>,
)],
static_candidates: &[CandidateSource],
unsatisfied_bounds: bool,
return_type: Option<Ty<'tcx>>,
Expand Down Expand Up @@ -2978,20 +2976,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
item.visibility(self.tcx).is_public() || info.def_id.is_local()
})
.is_some()
&& (matches!(rcvr_ty.kind(), ty::Param(_))
|| unsatisfied_predicates.iter().all(|(p, _, _)| {
match p.kind().skip_binder() {
// Hide traits if they are present in predicates as they can be fixed without
// having to implement them.
ty::PredicateKind::Clause(ty::ClauseKind::Trait(t)) => {
t.def_id() == info.def_id
}
ty::PredicateKind::Clause(ty::ClauseKind::Projection(p)) => {
p.projection_ty.def_id == info.def_id
}
_ => false,
}
}))
})
.collect::<Vec<_>>();
for span in &arbitrary_rcvr {
Expand Down
3 changes: 3 additions & 0 deletions tests/ui/box/unit/unique-object-noncopyable.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ LL | let _z = y.clone();
which is required by `Box<dyn Foo>: Clone`
`dyn Foo: Clone`
which is required by `Box<dyn Foo>: Clone`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `clone`, perhaps you need to implement it:
candidate #1: `Clone`

error: aborting due to 1 previous error

Expand Down
3 changes: 0 additions & 3 deletions tests/ui/box/unit/unique-pinned-nocopy.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ LL | let _j = i.clone();
= note: the following trait bounds were not satisfied:
`R: Clone`
which is required by `Box<R>: Clone`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `clone`, perhaps you need to implement it:
candidate #1: `Clone`
help: consider annotating `R` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
Expand Down
3 changes: 0 additions & 3 deletions tests/ui/derives/derive-assoc-type-not-impl.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ note: trait bound `NotClone: Clone` was not satisfied
|
LL | #[derive(Clone)]
| ^^^^^ unsatisfied trait bound introduced in this `derive` macro
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `clone`, perhaps you need to implement it:
candidate #1: `Clone`
help: consider annotating `NotClone` with `#[derive(Clone)]`
|
LL + #[derive(Clone)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ trait X {
type Y<T>;
}

trait M {
trait M { //~ NOTE
fn f(&self) {}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ LL | impl<T: X<Y<i32> = i32>> M for T {}
| ^^^^^^^^^^^^ - -
| |
| unsatisfied trait bound introduced here
= help: items from traits can only be used if the trait is implemented and in scope
note: `M` defines an item `f`, perhaps you need to implement it
--> $DIR/method-unsatisfied-assoc-type-predicate.rs:8:1
|
LL | trait M {
| ^^^^^^^

error: aborting due to 1 previous error

Expand Down
12 changes: 12 additions & 0 deletions tests/ui/higher-ranked/trait-bounds/issue-30786.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ note: the following trait bounds were not satisfied:
|
LL | impl<T> StreamExt for T where for<'a> &'a mut T: Stream {}
| --------- - ^^^^^^ unsatisfied trait bound introduced here
= help: items from traits can only be used if the trait is implemented and in scope
note: `StreamExt` defines an item `filterx`, perhaps you need to implement it
--> $DIR/issue-30786.rs:66:1
|
LL | pub trait StreamExt
| ^^^^^^^^^^^^^^^^^^^

error[E0599]: the method `countx` exists for struct `Filter<Map<Repeat, fn(&u64) -> &u64 {identity::<u64>}>, {closure@issue-30786.rs:131:30}>`, but its trait bounds were not satisfied
--> $DIR/issue-30786.rs:132:24
Expand All @@ -33,6 +39,12 @@ note: the following trait bounds were not satisfied:
|
LL | impl<T> StreamExt for T where for<'a> &'a mut T: Stream {}
| --------- - ^^^^^^ unsatisfied trait bound introduced here
= help: items from traits can only be used if the trait is implemented and in scope
note: `StreamExt` defines an item `countx`, perhaps you need to implement it
--> $DIR/issue-30786.rs:66:1
|
LL | pub trait StreamExt
| ^^^^^^^^^^^^^^^^^^^

error: aborting due to 2 previous errors

Expand Down
5 changes: 3 additions & 2 deletions tests/ui/methods/method-call-err-msg.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ LL | | .take()
note: the trait `Iterator` must be implemented
--> $SRC_DIR/core/src/iter/traits/iterator.rs:LL:COL
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `take`, perhaps you need to implement it:
candidate #1: `Iterator`
= note: the following traits define an item `take`, perhaps you need to implement one of them:
candidate #1: `std::io::Read`
candidate #2: `Iterator`

error[E0061]: this method takes 3 arguments but 0 arguments were supplied
--> $DIR/method-call-err-msg.rs:21:7
Expand Down
22 changes: 16 additions & 6 deletions tests/ui/traits/method-on-unbounded-type-param.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,13 @@ LL | (&a).cmp(&b)
which is required by `&mut &T: Iterator`
`T: Iterator`
which is required by `&mut T: Iterator`
help: consider restricting the type parameters to satisfy the trait bounds
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `cmp`, perhaps you need to restrict type parameter `T` with one of them:
|
LL | fn g<T>(a: T, b: T) -> std::cmp::Ordering where T: Iterator, T: Ord {
| +++++++++++++++++++++++++
LL | fn g<T: Ord>(a: T, b: T) -> std::cmp::Ordering {
| +++++
LL | fn g<T: Iterator>(a: T, b: T) -> std::cmp::Ordering {
| ++++++++++

error[E0599]: the method `cmp` exists for reference `&T`, but its trait bounds were not satisfied
--> $DIR/method-on-unbounded-type-param.rs:8:7
Expand All @@ -45,10 +48,13 @@ LL | a.cmp(&b)
which is required by `&mut &T: Iterator`
`T: Iterator`
which is required by `&mut T: Iterator`
help: consider restricting the type parameters to satisfy the trait bounds
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `cmp`, perhaps you need to restrict type parameter `T` with one of them:
|
LL | fn h<T>(a: &T, b: T) -> std::cmp::Ordering where T: Iterator, T: Ord {
| +++++++++++++++++++++++++
LL | fn h<T: Ord>(a: &T, b: T) -> std::cmp::Ordering {
| +++++
LL | fn h<T: Iterator>(a: &T, b: T) -> std::cmp::Ordering {
| ++++++++++

error[E0599]: the method `cmp` exists for struct `Box<dyn T>`, but its trait bounds were not satisfied
--> $DIR/method-on-unbounded-type-param.rs:14:7
Expand All @@ -68,6 +74,10 @@ LL | x.cmp(&x);
which is required by `&mut Box<dyn T>: Iterator`
`dyn T: Iterator`
which is required by `&mut dyn T: Iterator`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following traits define an item `cmp`, perhaps you need to implement one of them:
candidate #1: `Ord`
candidate #2: `Iterator`

error: aborting due to 4 previous errors

Expand Down

0 comments on commit ab20137

Please sign in to comment.