]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/from_over_into.rs
Merge commit '7248d06384c6a90de58c04c1f46be88821278d8b' into sync-from-clippy
[rust.git] / src / tools / clippy / clippy_lints / src / from_over_into.rs
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;
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_semver::RustcVersion;
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::symbol::sym;
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
13     ///
14     /// ### Why is this bad?
15     /// According the std docs implementing `From<..>` is preferred since it gives you `Into<..>` for free where the reverse isn't true.
16     ///
17     /// ### Example
18     /// ```rust
19     /// struct StringWrapper(String);
20     ///
21     /// impl Into<StringWrapper> for String {
22     ///     fn into(self) -> StringWrapper {
23     ///         StringWrapper(self)
24     ///     }
25     /// }
26     /// ```
27     /// Use instead:
28     /// ```rust
29     /// struct StringWrapper(String);
30     ///
31     /// impl From<String> for StringWrapper {
32     ///     fn from(s: String) -> StringWrapper {
33     ///         StringWrapper(s)
34     ///     }
35     /// }
36     /// ```
37     #[clippy::version = "1.51.0"]
38     pub FROM_OVER_INTO,
39     style,
40     "Warns on implementations of `Into<..>` to use `From<..>`"
41 }
42
43 pub struct FromOverInto {
44     msrv: Option<RustcVersion>,
45 }
46
47 impl FromOverInto {
48     #[must_use]
49     pub fn new(msrv: Option<RustcVersion>) -> Self {
50         FromOverInto { msrv }
51     }
52 }
53
54 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
55
56 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) {
59             return;
60         }
61
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             }
77         }
78     }
79
80     extract_msrv_attr!(LateContext);
81 }