1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
3 use clippy_utils::{get_trait_def_id, paths, return_ty, trait_ref_of_method};
4 use if_chain::if_chain;
5 use rustc_hir::{ImplItem, ImplItemKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::sym;
9 
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`.
13     ///
14     /// ### Why is this bad?
15     /// This method is also implicitly defined if a type implements the `Display` trait. As the functionality of `Display` is much more versatile, it should be preferred.
16     ///
17     /// ### Known problems
18     /// None
19     ///
20     /// ### Example
21     /// ```rust
22     /// // Bad
23     /// pub struct A;
24     ///
25     /// impl A {
26     ///     pub fn to_string(&self) -> String {
27     ///         "I am A".to_string()
28     ///     }
29     /// }
30     /// ```
31     ///
32     /// ```rust
33     /// // Good
34     /// use std::fmt;
35     ///
36     /// pub struct A;
37     ///
38     /// impl fmt::Display for A {
39     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40     ///         write!(f, "I am A")
41     ///     }
42     /// }
43     /// ```
44     pub INHERENT_TO_STRING,
45     style,
46     "type implements inherent method `to_string()`, but should instead implement the `Display` trait"
47 }
48 
49 declare_clippy_lint! {
50     /// ### What it does
51     /// Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait.
52     ///
53     /// ### Why is this bad?
54     /// This method is also implicitly defined if a type implements the `Display` trait. The less versatile inherent method will then shadow the implementation introduced by `Display`.
55     ///
56     /// ### Known problems
57     /// None
58     ///
59     /// ### Example
60     /// ```rust
61     /// // Bad
62     /// use std::fmt;
63     ///
64     /// pub struct A;
65     ///
66     /// impl A {
67     ///     pub fn to_string(&self) -> String {
68     ///         "I am A".to_string()
69     ///     }
70     /// }
71     ///
72     /// impl fmt::Display for A {
73     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74     ///         write!(f, "I am A, too")
75     ///     }
76     /// }
77     /// ```
78     ///
79     /// ```rust
80     /// // Good
81     /// use std::fmt;
82     ///
83     /// pub struct A;
84     ///
85     /// impl fmt::Display for A {
86     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87     ///         write!(f, "I am A")
88     ///     }
89     /// }
90     /// ```
91     pub INHERENT_TO_STRING_SHADOW_DISPLAY,
92     correctness,
93     "type implements inherent method `to_string()`, which gets shadowed by the implementation of the `Display` trait"
94 }
95 
96 declare_lint_pass!(InherentToString => [INHERENT_TO_STRING, INHERENT_TO_STRING_SHADOW_DISPLAY]);
97 
98 impl<'tcx> LateLintPass<'tcx> for InherentToString {
check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>)99     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
100         if impl_item.span.from_expansion() {
101             return;
102         }
103 
104         if_chain! {
105             // Check if item is a method, called to_string and has a parameter 'self'
106             if let ImplItemKind::Fn(ref signature, _) = impl_item.kind;
107             if impl_item.ident.name.as_str() == "to_string";
108             let decl = &signature.decl;
109             if decl.implicit_self.has_implicit_self();
110             if decl.inputs.len() == 1;
111             if impl_item.generics.params.is_empty();
112 
113             // Check if return type is String
114             if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id()), sym::String);
115 
116             // Filters instances of to_string which are required by a trait
117             if trait_ref_of_method(cx, impl_item.hir_id()).is_none();
118 
119             then {
120                 show_lint(cx, impl_item);
121             }
122         }
123     }
124 }
125 
show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>)126 fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) {
127     let display_trait_id = get_trait_def_id(cx, &paths::DISPLAY_TRAIT).expect("Failed to get trait ID of `Display`!");
128 
129     // Get the real type of 'self'
130     let self_type = cx.tcx.fn_sig(item.def_id).input(0);
131     let self_type = self_type.skip_binder().peel_refs();
132 
133     // Emit either a warning or an error
134     if implements_trait(cx, self_type, display_trait_id, &[]) {
135         span_lint_and_help(
136             cx,
137             INHERENT_TO_STRING_SHADOW_DISPLAY,
138             item.span,
139             &format!(
140                 "type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`",
141                 self_type
142             ),
143             None,
144             &format!("remove the inherent method from type `{}`", self_type),
145         );
146     } else {
147         span_lint_and_help(
148             cx,
149             INHERENT_TO_STRING,
150             item.span,
151             &format!(
152                 "implementation of inherent method `to_string(&self) -> String` for type `{}`",
153                 self_type
154             ),
155             None,
156             &format!("implement trait `Display` for type `{}` instead", self_type),
157         );
158     }
159 }
160