Skip to content

Commit 50f192f

Browse files
committed
Auto merge of #9649 - Alexendoo:from-over-into-suggestion, r=llogiq
Add a suggestion and a note about orphan rules for `from_over_into` Adds a machine applicable suggestion to convert the `Into` impl into a `From` one to `from_over_into` Also adds a note explaining that `impl From<Local> for Foreign` is fine if the `Into` type is foreign Closes #7444 Addresses half of #9638 changelog: [`from_over_into`] Add a suggestion and a note about orphan rules
2 parents b510557 + 4b8df8d commit 50f192f

6 files changed

+375
-25
lines changed

clippy_lints/src/from_over_into.rs

+154-22
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
1-
use clippy_utils::diagnostics::span_lint_and_help;
2-
use clippy_utils::{meets_msrv, msrvs};
3-
use if_chain::if_chain;
4-
use rustc_hir as hir;
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::macros::span_is_local;
3+
use clippy_utils::source::snippet_opt;
4+
use clippy_utils::{meets_msrv, msrvs, path_def_id};
5+
use rustc_errors::Applicability;
6+
use rustc_hir::intravisit::{walk_path, Visitor};
7+
use rustc_hir::{
8+
GenericArg, GenericArgs, HirId, Impl, ImplItemKind, ImplItemRef, Item, ItemKind, PatKind, Path, PathSegment, Ty,
9+
TyKind,
10+
};
511
use rustc_lint::{LateContext, LateLintPass};
12+
use rustc_middle::hir::nested_filter::OnlyBodies;
613
use rustc_semver::RustcVersion;
714
use rustc_session::{declare_tool_lint, impl_lint_pass};
8-
use rustc_span::symbol::sym;
15+
use rustc_span::symbol::{kw, sym};
16+
use rustc_span::{Span, Symbol};
917

1018
declare_clippy_lint! {
1119
/// ### What it does
@@ -54,28 +62,152 @@ impl FromOverInto {
5462
impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
5563

5664
impl<'tcx> LateLintPass<'tcx> for FromOverInto {
57-
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
58-
if !meets_msrv(self.msrv, msrvs::RE_REBALANCING_COHERENCE) {
65+
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
66+
if !meets_msrv(self.msrv, msrvs::RE_REBALANCING_COHERENCE) || !span_is_local(item.span) {
5967
return;
6068
}
6169

62-
if_chain! {
63-
if let hir::ItemKind::Impl{ .. } = &item.kind;
64-
if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
65-
if cx.tcx.is_diagnostic_item(sym::Into, impl_trait_ref.def_id);
66-
67-
then {
68-
span_lint_and_help(
69-
cx,
70-
FROM_OVER_INTO,
71-
cx.tcx.sess.source_map().guess_head_span(item.span),
72-
"an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true",
73-
None,
74-
&format!("consider to implement `From<{}>` instead", impl_trait_ref.self_ty()),
75-
);
76-
}
70+
if let ItemKind::Impl(Impl {
71+
of_trait: Some(hir_trait_ref),
72+
self_ty,
73+
items: [impl_item_ref],
74+
..
75+
}) = item.kind
76+
&& let Some(into_trait_seg) = hir_trait_ref.path.segments.last()
77+
// `impl Into<target_ty> for self_ty`
78+
&& let Some(GenericArgs { args: [GenericArg::Type(target_ty)], .. }) = into_trait_seg.args
79+
&& let Some(middle_trait_ref) = cx.tcx.impl_trait_ref(item.def_id)
80+
&& cx.tcx.is_diagnostic_item(sym::Into, middle_trait_ref.def_id)
81+
{
82+
span_lint_and_then(
83+
cx,
84+
FROM_OVER_INTO,
85+
cx.tcx.sess.source_map().guess_head_span(item.span),
86+
"an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true",
87+
|diag| {
88+
// If the target type is likely foreign mention the orphan rules as it's a common source of confusion
89+
if path_def_id(cx, target_ty.peel_refs()).map_or(true, |id| !id.is_local()) {
90+
diag.help(
91+
"`impl From<Local> for Foreign` is allowed by the orphan rules, for more information see\n\
92+
https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence"
93+
);
94+
}
95+
96+
let message = format!("replace the `Into` implentation with `From<{}>`", middle_trait_ref.self_ty());
97+
if let Some(suggestions) = convert_to_from(cx, into_trait_seg, target_ty, self_ty, impl_item_ref) {
98+
diag.multipart_suggestion(message, suggestions, Applicability::MachineApplicable);
99+
} else {
100+
diag.help(message);
101+
}
102+
},
103+
);
77104
}
78105
}
79106

80107
extract_msrv_attr!(LateContext);
81108
}
109+
110+
/// Finds the occurences of `Self` and `self`
111+
struct SelfFinder<'a, 'tcx> {
112+
cx: &'a LateContext<'tcx>,
113+
/// Occurences of `Self`
114+
upper: Vec<Span>,
115+
/// Occurences of `self`
116+
lower: Vec<Span>,
117+
/// If any of the `self`/`Self` usages were from an expansion, or the body contained a binding
118+
/// already named `val`
119+
invalid: bool,
120+
}
121+
122+
impl<'a, 'tcx> Visitor<'tcx> for SelfFinder<'a, 'tcx> {
123+
type NestedFilter = OnlyBodies;
124+
125+
fn nested_visit_map(&mut self) -> Self::Map {
126+
self.cx.tcx.hir()
127+
}
128+
129+
fn visit_path(&mut self, path: &'tcx Path<'tcx>, _id: HirId) {
130+
for segment in path.segments {
131+
match segment.ident.name {
132+
kw::SelfLower => self.lower.push(segment.ident.span),
133+
kw::SelfUpper => self.upper.push(segment.ident.span),
134+
_ => continue,
135+
}
136+
}
137+
138+
self.invalid |= path.span.from_expansion();
139+
if !self.invalid {
140+
walk_path(self, path);
141+
}
142+
}
143+
144+
fn visit_name(&mut self, name: Symbol) {
145+
if name == sym::val {
146+
self.invalid = true;
147+
}
148+
}
149+
}
150+
151+
fn convert_to_from(
152+
cx: &LateContext<'_>,
153+
into_trait_seg: &PathSegment<'_>,
154+
target_ty: &Ty<'_>,
155+
self_ty: &Ty<'_>,
156+
impl_item_ref: &ImplItemRef,
157+
) -> Option<Vec<(Span, String)>> {
158+
let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
159+
let ImplItemKind::Fn(ref sig, body_id) = impl_item.kind else { return None };
160+
let body = cx.tcx.hir().body(body_id);
161+
let [input] = body.params else { return None };
162+
let PatKind::Binding(.., self_ident, None) = input.pat.kind else { return None };
163+
164+
let from = snippet_opt(cx, self_ty.span)?;
165+
let into = snippet_opt(cx, target_ty.span)?;
166+
167+
let mut suggestions = vec![
168+
// impl Into<T> for U -> impl From<T> for U
169+
// ~~~~ ~~~~
170+
(into_trait_seg.ident.span, String::from("From")),
171+
// impl Into<T> for U -> impl Into<U> for U
172+
// ~ ~
173+
(target_ty.span, from.clone()),
174+
// impl Into<T> for U -> impl Into<T> for T
175+
// ~ ~
176+
(self_ty.span, into),
177+
// fn into(self) -> T -> fn from(self) -> T
178+
// ~~~~ ~~~~
179+
(impl_item.ident.span, String::from("from")),
180+
// fn into([mut] self) -> T -> fn into([mut] v: T) -> T
181+
// ~~~~ ~~~~
182+
(self_ident.span, format!("val: {from}")),
183+
// fn into(self) -> T -> fn into(self) -> Self
184+
// ~ ~~~~
185+
(sig.decl.output.span(), String::from("Self")),
186+
];
187+
188+
let mut finder = SelfFinder {
189+
cx,
190+
upper: Vec::new(),
191+
lower: Vec::new(),
192+
invalid: false,
193+
};
194+
finder.visit_expr(body.value);
195+
196+
if finder.invalid {
197+
return None;
198+
}
199+
200+
// don't try to replace e.g. `Self::default()` with `&[T]::default()`
201+
if !finder.upper.is_empty() && !matches!(self_ty.kind, TyKind::Path(_)) {
202+
return None;
203+
}
204+
205+
for span in finder.upper {
206+
suggestions.push((span, from.clone()));
207+
}
208+
for span in finder.lower {
209+
suggestions.push((span, String::from("val")));
210+
}
211+
212+
Some(suggestions)
213+
}

tests/ui/from_over_into.fixed

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::from_over_into)]
4+
#![allow(unused)]
5+
6+
// this should throw an error
7+
struct StringWrapper(String);
8+
9+
impl From<String> for StringWrapper {
10+
fn from(val: String) -> Self {
11+
StringWrapper(val)
12+
}
13+
}
14+
15+
struct SelfType(String);
16+
17+
impl From<String> for SelfType {
18+
fn from(val: String) -> Self {
19+
SelfType(String::new())
20+
}
21+
}
22+
23+
#[derive(Default)]
24+
struct X;
25+
26+
impl X {
27+
const FOO: &'static str = "a";
28+
}
29+
30+
struct SelfKeywords;
31+
32+
impl From<X> for SelfKeywords {
33+
fn from(val: X) -> Self {
34+
let _ = X::default();
35+
let _ = X::FOO;
36+
let _: X = val;
37+
38+
SelfKeywords
39+
}
40+
}
41+
42+
struct ExplicitPaths(bool);
43+
44+
impl core::convert::From<crate::ExplicitPaths> for bool {
45+
fn from(mut val: crate::ExplicitPaths) -> Self {
46+
let in_closure = || val.0;
47+
48+
val.0 = false;
49+
val.0
50+
}
51+
}
52+
53+
// this is fine
54+
struct A(String);
55+
56+
impl From<String> for A {
57+
fn from(s: String) -> A {
58+
A(s)
59+
}
60+
}
61+
62+
fn main() {}

tests/ui/from_over_into.rs

+41
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
// run-rustfix
2+
13
#![warn(clippy::from_over_into)]
4+
#![allow(unused)]
25

36
// this should throw an error
47
struct StringWrapper(String);
@@ -9,6 +12,44 @@ impl Into<StringWrapper> for String {
912
}
1013
}
1114

15+
struct SelfType(String);
16+
17+
impl Into<SelfType> for String {
18+
fn into(self) -> SelfType {
19+
SelfType(Self::new())
20+
}
21+
}
22+
23+
#[derive(Default)]
24+
struct X;
25+
26+
impl X {
27+
const FOO: &'static str = "a";
28+
}
29+
30+
struct SelfKeywords;
31+
32+
impl Into<SelfKeywords> for X {
33+
fn into(self) -> SelfKeywords {
34+
let _ = Self::default();
35+
let _ = Self::FOO;
36+
let _: Self = self;
37+
38+
SelfKeywords
39+
}
40+
}
41+
42+
struct ExplicitPaths(bool);
43+
44+
impl core::convert::Into<bool> for crate::ExplicitPaths {
45+
fn into(mut self) -> bool {
46+
let in_closure = || self.0;
47+
48+
self.0 = false;
49+
self.0
50+
}
51+
}
52+
1253
// this is fine
1354
struct A(String);
1455

tests/ui/from_over_into.stderr

+54-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,62 @@
11
error: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
2-
--> $DIR/from_over_into.rs:6:1
2+
--> $DIR/from_over_into.rs:9:1
33
|
44
LL | impl Into<StringWrapper> for String {
55
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66
|
7-
= help: consider to implement `From<std::string::String>` instead
87
= note: `-D clippy::from-over-into` implied by `-D warnings`
8+
help: replace the `Into` implentation with `From<std::string::String>`
9+
|
10+
LL ~ impl From<String> for StringWrapper {
11+
LL ~ fn from(val: String) -> Self {
12+
LL ~ StringWrapper(val)
13+
|
14+
15+
error: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
16+
--> $DIR/from_over_into.rs:17:1
17+
|
18+
LL | impl Into<SelfType> for String {
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
|
21+
help: replace the `Into` implentation with `From<std::string::String>`
22+
|
23+
LL ~ impl From<String> for SelfType {
24+
LL ~ fn from(val: String) -> Self {
25+
LL ~ SelfType(String::new())
26+
|
27+
28+
error: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
29+
--> $DIR/from_over_into.rs:32:1
30+
|
31+
LL | impl Into<SelfKeywords> for X {
32+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33+
|
34+
help: replace the `Into` implentation with `From<X>`
35+
|
36+
LL ~ impl From<X> for SelfKeywords {
37+
LL ~ fn from(val: X) -> Self {
38+
LL ~ let _ = X::default();
39+
LL ~ let _ = X::FOO;
40+
LL ~ let _: X = val;
41+
|
42+
43+
error: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
44+
--> $DIR/from_over_into.rs:44:1
45+
|
46+
LL | impl core::convert::Into<bool> for crate::ExplicitPaths {
47+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
48+
|
49+
= help: `impl From<Local> for Foreign` is allowed by the orphan rules, for more information see
50+
https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence
51+
help: replace the `Into` implentation with `From<ExplicitPaths>`
52+
|
53+
LL ~ impl core::convert::From<crate::ExplicitPaths> for bool {
54+
LL ~ fn from(mut val: crate::ExplicitPaths) -> Self {
55+
LL ~ let in_closure = || val.0;
56+
LL |
57+
LL ~ val.0 = false;
58+
LL ~ val.0
59+
|
960

10-
error: aborting due to previous error
61+
error: aborting due to 4 previous errors
1162

0 commit comments

Comments
 (0)