1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::paths::INTO;
3 use clippy_utils::{match_def_path, meets_msrv, msrvs};
4 use if_chain::if_chain;
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_semver::RustcVersion;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 declare_clippy_lint! {
11 /// **What it does:** Searches for implementations of the `Into<..>` trait and suggests to implement `From<..>` instead.
13 /// **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.
15 /// **Known problems:** None.
20 /// struct StringWrapper(String);
22 /// impl Into<StringWrapper> for String {
23 /// fn into(self) -> StringWrapper {
24 /// StringWrapper(self)
30 /// struct StringWrapper(String);
32 /// impl From<String> for StringWrapper {
33 /// fn from(s: String) -> StringWrapper {
40 "Warns on implementations of `Into<..>` to use `From<..>`"
43 pub struct FromOverInto {
44 msrv: Option<RustcVersion>,
49 pub fn new(msrv: Option<RustcVersion>) -> Self {
54 impl_lint_pass!(FromOverInto => [FROM_OVER_INTO]);
56 impl LateLintPass<'_> for FromOverInto {
57 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
58 if !meets_msrv(self.msrv.as_ref(), &msrvs::RE_REBALANCING_COHERENCE) {
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 match_def_path(cx, impl_trait_ref.def_id, &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",
74 &format!("consider to implement `From<{}>` instead", impl_trait_ref.self_ty()),
80 extract_msrv_attr!(LateContext);