1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::{meets_msrv, msrvs};
3 use if_chain::if_chain;
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;
10 declare_clippy_lint! {
12 /// Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
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.
19 /// struct StringWrapper(String);
21 /// impl Into<StringWrapper> for String {
22 /// fn into(self) -> StringWrapper {
23 /// StringWrapper(self)
29 /// struct StringWrapper(String);
31 /// impl From<String> for StringWrapper {
32 /// fn from(s: String) -> StringWrapper {
39 "Warns on implementations of `Into<..>` to use `From<..>`"
42 pub struct FromOverInto {
43 msrv: Option<RustcVersion>,
48 pub fn new(msrv: Option<RustcVersion>) -> Self {
53 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
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) {
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);
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",
73 &format!("consider to implement `From<{}>` instead", impl_trait_ref.self_ty()),
79 extract_msrv_attr!(LateContext);