Auto merge of #10853 - MarcusGrass:fix-from-over-into-self, r=Alexendoo

Ignore fix for `from_over_into` if the target type contains a `Self` reference

Fixes https://github.com/rust-lang/rust-clippy/issues/10838.

This is my first time contributing here, and the fix is kind of ugly.
I've worked a bit with `quote` and was trying to figure out a way to replace the type in a better way than just a raw string-replace but couldn't quite figure out how to.

The only thing really required to fix this, is to replace all `Self` references with the type stated in the `from` variable, this isn't entirely simple to do with raw strings without creating a mess though.

We need to find and replace all `Self`'s in a variable with `from` but there could be an arbitrary amount, in a lot of different positions. As well as some type that contains the name self, like `SelfVarSelf` which shouldn't be replaced.

The strategy is essentially, if `"Self"` is surrounded on both sides by something that isn't alphanumeric, then we're golden, then trying to make that reasonably efficient.

I would not be offended if the solution is too messy to accept!

changelog: [from_over_into]: Replace Self with the indicated variable in suggestion and fix.
This commit is contained in:
bors 2023-06-04 17:53:54 +00:00
commit 4886937212
3 changed files with 24 additions and 1 deletions

View File

@ -156,6 +156,11 @@ fn convert_to_from(
self_ty: &Ty<'_>,
impl_item_ref: &ImplItemRef,
) -> Option<Vec<(Span, String)>> {
if !target_ty.find_self_aliases().is_empty() {
// It's tricky to expand self-aliases correctly, we'll ignore it to not cause a
// bad suggestion/fix.
return None;
}
let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
let ImplItemKind::Fn(ref sig, body_id) = impl_item.kind else { return None };
let body = cx.tcx.hir().body(body_id);

View File

@ -32,4 +32,14 @@ impl Into<u8> for ContainsVal {
}
}
pub struct Lval<T>(T);
pub struct Rval<T>(T);
impl<T> Into<Rval<Self>> for Lval<T> {
fn into(self) -> Rval<Self> {
Rval(self)
}
}
fn main() {}

View File

@ -25,5 +25,13 @@ LL | impl Into<u8> for ContainsVal {
https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence
= help: replace the `Into` implementation with `From<ContainsVal>`
error: aborting due to 3 previous errors
error: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
--> $DIR/from_over_into_unfixable.rs:39:1
|
LL | impl<T> Into<Rval<Self>> for Lval<T> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: replace the `Into` implementation with `From<Lval<T>>`
error: aborting due to 4 previous errors