]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/from_over_into.rs
a92f7548ff254d16a2f51b255675650d139e8734
[rust.git] / clippy_lints / src / from_over_into.rs
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};
8 use rustc_hir::{
9     GenericArg, GenericArgs, HirId, Impl, ImplItemKind, ImplItemRef, Item, ItemKind, PatKind, Path, PathSegment, Ty,
10     TyKind,
11 };
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::{hir::nested_filter::OnlyBodies, ty};
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::symbol::{kw, sym};
16 use rustc_span::{Span, Symbol};
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
21     ///
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.
24     ///
25     /// ### Example
26     /// ```rust
27     /// struct StringWrapper(String);
28     ///
29     /// impl Into<StringWrapper> for String {
30     ///     fn into(self) -> StringWrapper {
31     ///         StringWrapper(self)
32     ///     }
33     /// }
34     /// ```
35     /// Use instead:
36     /// ```rust
37     /// struct StringWrapper(String);
38     ///
39     /// impl From<String> for StringWrapper {
40     ///     fn from(s: String) -> StringWrapper {
41     ///         StringWrapper(s)
42     ///     }
43     /// }
44     /// ```
45     #[clippy::version = "1.51.0"]
46     pub FROM_OVER_INTO,
47     style,
48     "Warns on implementations of `Into<..>` to use `From<..>`"
49 }
50
51 pub struct FromOverInto {
52     msrv: Msrv,
53 }
54
55 impl FromOverInto {
56     #[must_use]
57     pub fn new(msrv: Msrv) -> Self {
58         FromOverInto { msrv }
59     }
60 }
61
62 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
63
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) {
67             return;
68         }
69
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.owner_id)
80             && cx.tcx.is_diagnostic_item(sym::Into, middle_trait_ref.def_id)
81             && !matches!(middle_trait_ref.substs.type_at(1).kind(), ty::Alias(ty::Opaque, _))
82         {
83             span_lint_and_then(
84                 cx,
85                 FROM_OVER_INTO,
86                 cx.tcx.sess.source_map().guess_head_span(item.span),
87                 "an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true",
88                 |diag| {
89                     // If the target type is likely foreign mention the orphan rules as it's a common source of confusion
90                     if path_def_id(cx, target_ty.peel_refs()).map_or(true, |id| !id.is_local()) {
91                         diag.help(
92                             "`impl From<Local> for Foreign` is allowed by the orphan rules, for more information see\n\
93                             https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence"
94                         );
95                     }
96
97                     let message = format!("replace the `Into` implentation with `From<{}>`", middle_trait_ref.self_ty());
98                     if let Some(suggestions) = convert_to_from(cx, into_trait_seg, target_ty, self_ty, impl_item_ref) {
99                         diag.multipart_suggestion(message, suggestions, Applicability::MachineApplicable);
100                     } else {
101                         diag.help(message);
102                     }
103                 },
104             );
105         }
106     }
107
108     extract_msrv_attr!(LateContext);
109 }
110
111 /// Finds the occurences of `Self` and `self`
112 struct SelfFinder<'a, 'tcx> {
113     cx: &'a LateContext<'tcx>,
114     /// Occurences of `Self`
115     upper: Vec<Span>,
116     /// Occurences of `self`
117     lower: Vec<Span>,
118     /// If any of the `self`/`Self` usages were from an expansion, or the body contained a binding
119     /// already named `val`
120     invalid: bool,
121 }
122
123 impl<'a, 'tcx> Visitor<'tcx> for SelfFinder<'a, 'tcx> {
124     type NestedFilter = OnlyBodies;
125
126     fn nested_visit_map(&mut self) -> Self::Map {
127         self.cx.tcx.hir()
128     }
129
130     fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
131         for segment in path.segments {
132             match segment.ident.name {
133                 kw::SelfLower => self.lower.push(segment.ident.span),
134                 kw::SelfUpper => self.upper.push(segment.ident.span),
135                 _ => continue,
136             }
137         }
138
139         self.invalid |= path.span.from_expansion();
140         if !self.invalid {
141             walk_path(self, path);
142         }
143     }
144
145     fn visit_name(&mut self, name: Symbol) {
146         if name == sym::val {
147             self.invalid = true;
148         }
149     }
150 }
151
152 fn convert_to_from(
153     cx: &LateContext<'_>,
154     into_trait_seg: &PathSegment<'_>,
155     target_ty: &Ty<'_>,
156     self_ty: &Ty<'_>,
157     impl_item_ref: &ImplItemRef,
158 ) -> Option<Vec<(Span, String)>> {
159     let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
160     let ImplItemKind::Fn(ref sig, body_id) = impl_item.kind else { return None };
161     let body = cx.tcx.hir().body(body_id);
162     let [input] = body.params else { return None };
163     let PatKind::Binding(.., self_ident, None) = input.pat.kind else { return None };
164
165     let from = snippet_opt(cx, self_ty.span)?;
166     let into = snippet_opt(cx, target_ty.span)?;
167
168     let mut suggestions = vec![
169         // impl Into<T> for U  ->  impl From<T> for U
170         //      ~~~~                    ~~~~
171         (into_trait_seg.ident.span, String::from("From")),
172         // impl Into<T> for U  ->  impl Into<U> for U
173         //           ~                       ~
174         (target_ty.span, from.clone()),
175         // impl Into<T> for U  ->  impl Into<T> for T
176         //                  ~                       ~
177         (self_ty.span, into),
178         // fn into(self) -> T  ->  fn from(self) -> T
179         //    ~~~~                    ~~~~
180         (impl_item.ident.span, String::from("from")),
181         // fn into([mut] self) -> T  ->  fn into([mut] v: T) -> T
182         //               ~~~~                          ~~~~
183         (self_ident.span, format!("val: {from}")),
184         // fn into(self) -> T  ->  fn into(self) -> Self
185         //                  ~                       ~~~~
186         (sig.decl.output.span(), String::from("Self")),
187     ];
188
189     let mut finder = SelfFinder {
190         cx,
191         upper: Vec::new(),
192         lower: Vec::new(),
193         invalid: false,
194     };
195     finder.visit_expr(body.value);
196
197     if finder.invalid {
198         return None;
199     }
200
201     // don't try to replace e.g. `Self::default()` with `&[T]::default()`
202     if !finder.upper.is_empty() && !matches!(self_ty.kind, TyKind::Path(_)) {
203         return None;
204     }
205
206     for span in finder.upper {
207         suggestions.push((span, from.clone()));
208     }
209     for span in finder.lower {
210         suggestions.push((span, String::from("val")));
211     }
212
213     Some(suggestions)
214 }