Fix incorrect trait bound restriction suggestion

Suggest

```
error[E0308]: mismatched types
  --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
   |
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
   |                        -           - expected `B` because of return type
   |                        |
   |                        expected this type parameter
LL |     return a.bar();
   |            ^^^^^^^ expected type parameter `B`, found associated type
   |
   = note: expected type parameter `B`
             found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
   |
LL | pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
   |                      +++++++
```

instead of

```
error[E0308]: mismatched types
  --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
   |
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
   |                        -           - expected `B` because of return type
   |                        |
   |                        expected this type parameter
LL |     return a.bar();
   |            ^^^^^^^ expected type parameter `B`, found associated type
   |
   = note: expected type parameter `B`
             found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
   |
LL | pub fn foo<A: MyTrait + <T = B>, B>(a: A) -> B {
   |                      +++++++++
```

Fix #117501.
This commit is contained in:
Esteban Küber 2023-11-02 02:20:04 +00:00
parent 75b064d269
commit 9e7345be1f
4 changed files with 44 additions and 0 deletions

View File

@ -274,6 +274,8 @@ pub fn suggest_constraining_type_params<'a>(
span,
if span_to_replace.is_some() {
constraint.clone()
} else if constraint.starts_with("<") {
constraint.to_string()
} else if bound_list_non_empty {
format!(" + {constraint}")
} else {

View File

@ -0,0 +1,11 @@
// run-rustfix
pub trait MyTrait {
type T;
fn bar(self) -> Self::T;
}
pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
return a.bar(); //~ ERROR mismatched types
}
fn main() {}

View File

@ -0,0 +1,11 @@
// run-rustfix
pub trait MyTrait {
type T;
fn bar(self) -> Self::T;
}
pub fn foo<A: MyTrait, B>(a: A) -> B {
return a.bar(); //~ ERROR mismatched types
}
fn main() {}

View File

@ -0,0 +1,20 @@
error[E0308]: mismatched types
--> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
|
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
| - - expected `B` because of return type
| |
| expected this type parameter
LL | return a.bar();
| ^^^^^^^ expected type parameter `B`, found associated type
|
= note: expected type parameter `B`
found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
|
LL | pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
| +++++++
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.