]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/inherent_to_string.rs
Merge commit 'b20d4c155d2fe3a8391f86dcf9a8c49e17188703' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / inherent_to_string.rs
1 use if_chain::if_chain;
2 use rustc_hir::{ImplItem, ImplItemKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5 use rustc_span::sym;
6
7 use crate::utils::{
8     get_trait_def_id, implements_trait, is_type_diagnostic_item, paths, return_ty, span_lint_and_help,
9     trait_ref_of_method,
10 };
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`.
14     ///
15     /// **Why is this bad?** 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:** None
18     ///
19     /// ** Example:**
20     ///
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:** 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.
51     ///
52     /// **Why is this bad?** 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`.
53     ///
54     /// **Known problems:** None
55     ///
56     /// ** Example:**
57     ///
58     /// ```rust
59     /// // Bad
60     /// use std::fmt;
61     ///
62     /// pub struct A;
63     ///
64     /// impl A {
65     ///     pub fn to_string(&self) -> String {
66     ///         "I am A".to_string()
67     ///     }
68     /// }
69     ///
70     /// impl fmt::Display for A {
71     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72     ///         write!(f, "I am A, too")
73     ///     }
74     /// }
75     /// ```
76     ///
77     /// ```rust
78     /// // Good
79     /// use std::fmt;
80     ///
81     /// pub struct A;
82     ///
83     /// impl fmt::Display for A {
84     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85     ///         write!(f, "I am A")
86     ///     }
87     /// }
88     /// ```
89     pub INHERENT_TO_STRING_SHADOW_DISPLAY,
90     correctness,
91     "type implements inherent method `to_string()`, which gets shadowed by the implementation of the `Display` trait"
92 }
93
94 declare_lint_pass!(InherentToString => [INHERENT_TO_STRING, INHERENT_TO_STRING_SHADOW_DISPLAY]);
95
96 impl<'tcx> LateLintPass<'tcx> for InherentToString {
97     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
98         if impl_item.span.from_expansion() {
99             return;
100         }
101
102         if_chain! {
103             // Check if item is a method, called to_string and has a parameter 'self'
104             if let ImplItemKind::Fn(ref signature, _) = impl_item.kind;
105             if impl_item.ident.name.as_str() == "to_string";
106             let decl = &signature.decl;
107             if decl.implicit_self.has_implicit_self();
108             if decl.inputs.len() == 1;
109
110             // Check if return type is String
111             if is_type_diagnostic_item(cx, return_ty(cx, impl_item.hir_id), sym::string_type);
112
113             // Filters instances of to_string which are required by a trait
114             if trait_ref_of_method(cx, impl_item.hir_id).is_none();
115
116             then {
117                 show_lint(cx, impl_item);
118             }
119         }
120     }
121 }
122
123 fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) {
124     let display_trait_id = get_trait_def_id(cx, &paths::DISPLAY_TRAIT).expect("Failed to get trait ID of `Display`!");
125
126     // Get the real type of 'self'
127     let fn_def_id = cx.tcx.hir().local_def_id(item.hir_id);
128     let self_type = cx.tcx.fn_sig(fn_def_id).input(0);
129     let self_type = self_type.skip_binder().peel_refs();
130
131     // Emit either a warning or an error
132     if implements_trait(cx, self_type, display_trait_id, &[]) {
133         span_lint_and_help(
134             cx,
135             INHERENT_TO_STRING_SHADOW_DISPLAY,
136             item.span,
137             &format!(
138                 "type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`",
139                 self_type.to_string()
140             ),
141             None,
142             &format!("remove the inherent method from type `{}`", self_type.to_string())
143         );
144     } else {
145         span_lint_and_help(
146             cx,
147             INHERENT_TO_STRING,
148             item.span,
149             &format!(
150                 "implementation of inherent method `to_string(&self) -> String` for type `{}`",
151                 self_type.to_string()
152             ),
153             None,
154             &format!("implement trait `Display` for type `{}` instead", self_type.to_string()),
155         );
156     }
157 }