]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/from_over_into.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.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, LintContext};
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 pub FROM_OVER_INTO,
38 style,
39 "Warns on implementations of `Into<..>` to use `From<..>`"
40 }
41
42 pub struct FromOverInto {
43 msrv: Option<RustcVersion>,
44 }
45
46 impl FromOverInto {
47 #[must_use]
48 pub fn new(msrv: Option<RustcVersion>) -> Self {
49 FromOverInto { msrv }
50 }
51 }
52
53 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
54
55 impl LateLintPass<'_> for FromOverInto {
56 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
57 if !meets_msrv(self.msrv.as_ref(), &msrvs::RE_REBALANCING_COHERENCE) {
58 return;
59 }
60
61 if_chain! {
62 if let hir::ItemKind::Impl{ .. } = &item.kind;
63 if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
64 if cx.tcx.is_diagnostic_item(sym::into_trait, impl_trait_ref.def_id);
65
66 then {
67 span_lint_and_help(
68 cx,
69 FROM_OVER_INTO,
70 cx.tcx.sess.source_map().guess_head_span(item.span),
71 "an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true",
72 None,
73 &format!("consider to implement `From<{}>` instead", impl_trait_ref.self_ty()),
74 );
75 }
76 }
77 }
78
79 extract_msrv_attr!(LateContext);
80 }