]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/from_over_into.rs
Added from_over_into lint
[rust.git] / clippy_lints / src / from_over_into.rs
1 use crate::utils::paths::INTO;
2 use crate::utils::{match_def_path, span_lint_and_help};
3 use if_chain::if_chain;
4 use rustc_hir as hir;
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
10     ///
11     /// **Why is this bad?** According the std docs implementing `From<..>` is preferred since it gives you `Into<..>` for free where the reverse isn't true.
12     ///
13     /// **Known problems:** None.
14     ///
15     /// **Example:**
16     ///
17     /// ```rust
18     /// struct StringWrapper(String);
19     ///
20     /// impl Into<StringWrapper> for String {
21     ///     fn into(self) -> StringWrapper {
22     ///         StringWrapper(self)
23     ///     }
24     /// }
25     /// ```
26     /// Use instead:
27     /// ```rust
28     /// struct StringWrapper(String);
29     ///
30     /// impl From<String> for StringWrapper {
31     ///     fn from(s: String) -> StringWrapper {
32     ///         StringWrapper(s)
33     ///     }
34     /// }
35     /// ```
36     pub FROM_OVER_INTO,
37     style,
38     "Warns on implementations of `Into<..>` to use `From<..>`"
39 }
40
41 declare_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
42
43 impl LateLintPass<'_> for FromOverInto {
44     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
45         let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
46         if_chain! {
47             if let hir::ItemKind::Impl{ .. } = &item.kind;
48             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id);
49             if match_def_path(cx, impl_trait_ref.def_id, &INTO);
50
51             then {
52                 span_lint_and_help(
53                     cx,
54                     FROM_OVER_INTO,
55                     item.span,
56                     "An implementation of From is preferred since it gives you Into<..> for free where the reverse isn't true.",
57                     None,
58                     "consider implement From instead",
59                 );
60             }
61         }
62     }
63 }