]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/from_over_into.rs
Fix FN in `iter_cloned_collect` with a large array
[rust.git] / clippy_lints / src / from_over_into.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::paths::INTO;
3 use clippy_utils::{match_def_path, meets_msrv};
4 use if_chain::if_chain;
5 use rustc_hir as hir;
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_semver::RustcVersion;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9
10 const FROM_OVER_INTO_MSRV: RustcVersion = RustcVersion::new(1, 41, 0);
11
12 declare_clippy_lint! {
13     /// **What it does:** Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
14     ///
15     /// **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.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     ///
21     /// ```rust
22     /// struct StringWrapper(String);
23     ///
24     /// impl Into<StringWrapper> for String {
25     ///     fn into(self) -> StringWrapper {
26     ///         StringWrapper(self)
27     ///     }
28     /// }
29     /// ```
30     /// Use instead:
31     /// ```rust
32     /// struct StringWrapper(String);
33     ///
34     /// impl From<String> for StringWrapper {
35     ///     fn from(s: String) -> StringWrapper {
36     ///         StringWrapper(s)
37     ///     }
38     /// }
39     /// ```
40     pub FROM_OVER_INTO,
41     style,
42     "Warns on implementations of `Into<..>` to use `From<..>`"
43 }
44
45 pub struct FromOverInto {
46     msrv: Option<RustcVersion>,
47 }
48
49 impl FromOverInto {
50     #[must_use]
51     pub fn new(msrv: Option<RustcVersion>) -> Self {
52         FromOverInto { msrv }
53     }
54 }
55
56 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
57
58 impl LateLintPass<'_> for FromOverInto {
59     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
60         if !meets_msrv(self.msrv.as_ref(), &FROM_OVER_INTO_MSRV) {
61             return;
62         }
63
64         if_chain! {
65             if let hir::ItemKind::Impl{ .. } = &item.kind;
66             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
67             if match_def_path(cx, impl_trait_ref.def_id, &INTO);
68
69             then {
70                 span_lint_and_help(
71                     cx,
72                     FROM_OVER_INTO,
73                     cx.tcx.sess.source_map().guess_head_span(item.span),
74                     "an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true",
75                     None,
76                     &format!("consider to implement `From<{}>` instead", impl_trait_ref.self_ty()),
77                 );
78             }
79         }
80     }
81
82     extract_msrv_attr!(LateContext);
83 }