1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::macros::span_is_local;
3 use clippy_utils::msrvs::{self, Msrv};
4 use clippy_utils::path_def_id;
5 use clippy_utils::source::snippet_opt;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::{walk_path, Visitor};
9 GenericArg, GenericArgs, HirId, Impl, ImplItemKind, ImplItemRef, Item, ItemKind, PatKind, Path, PathSegment, Ty,
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::hir::nested_filter::OnlyBodies;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::symbol::{kw, sym};
16 use rustc_span::{Span, Symbol};
18 declare_clippy_lint! {
20 /// Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
22 /// ### Why is this bad?
23 /// According the std docs implementing `From<..>` is preferred since it gives you `Into<..>` for free where the reverse isn't true.
27 /// struct StringWrapper(String);
29 /// impl Into<StringWrapper> for String {
30 /// fn into(self) -> StringWrapper {
31 /// StringWrapper(self)
37 /// struct StringWrapper(String);
39 /// impl From<String> for StringWrapper {
40 /// fn from(s: String) -> StringWrapper {
45 #[clippy::version = "1.51.0"]
48 "Warns on implementations of `Into<..>` to use `From<..>`"
51 pub struct FromOverInto {
57 pub fn new(msrv: Msrv) -> Self {
62 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
64 impl<'tcx> LateLintPass<'tcx> for FromOverInto {
65 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
66 if !self.msrv.meets(msrvs::RE_REBALANCING_COHERENCE) || !span_is_local(item.span) {
70 if let ItemKind::Impl(Impl {
71 of_trait: Some(hir_trait_ref),
73 items: [impl_item_ref],
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.owner_id)
80 && cx.tcx.is_diagnostic_item(sym::Into, middle_trait_ref.def_id)
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",
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()) {
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"
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);
107 extract_msrv_attr!(LateContext);
110 /// Finds the occurences of `Self` and `self`
111 struct SelfFinder<'a, 'tcx> {
112 cx: &'a LateContext<'tcx>,
113 /// Occurences of `Self`
115 /// Occurences of `self`
117 /// If any of the `self`/`Self` usages were from an expansion, or the body contained a binding
118 /// already named `val`
122 impl<'a, 'tcx> Visitor<'tcx> for SelfFinder<'a, 'tcx> {
123 type NestedFilter = OnlyBodies;
125 fn nested_visit_map(&mut self) -> Self::Map {
129 fn visit_path(&mut self, path: &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),
138 self.invalid |= path.span.from_expansion();
140 walk_path(self, path);
144 fn visit_name(&mut self, name: Symbol) {
145 if name == sym::val {
152 cx: &LateContext<'_>,
153 into_trait_seg: &PathSegment<'_>,
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 };
164 let from = snippet_opt(cx, self_ty.span)?;
165 let into = snippet_opt(cx, target_ty.span)?;
167 let mut suggestions = vec![
168 // impl Into<T> for U -> impl From<T> for U
170 (into_trait_seg.ident.span, String::from("From")),
171 // impl Into<T> for U -> impl Into<U> for U
173 (target_ty.span, from.clone()),
174 // impl Into<T> for U -> impl Into<T> for T
176 (self_ty.span, into),
177 // fn into(self) -> T -> fn from(self) -> T
179 (impl_item.ident.span, String::from("from")),
180 // fn into([mut] self) -> T -> fn into([mut] v: T) -> T
182 (self_ident.span, format!("val: {from}")),
183 // fn into(self) -> T -> fn into(self) -> Self
185 (sig.decl.output.span(), String::from("Self")),
188 let mut finder = SelfFinder {
194 finder.visit_expr(body.value);
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(_)) {
205 for span in finder.upper {
206 suggestions.push((span, from.clone()));
208 for span in finder.lower {
209 suggestions.push((span, String::from("val")));