]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/inherent_to_string.rs
Auto merge of #4591 - flip1995:rustup, r=flip1995
[rust.git] / 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, LintArray, LintPass};
4 use rustc::{declare_lint_pass, declare_tool_lint};
5
6 use crate::utils::{
7     get_trait_def_id, implements_trait, match_type, paths, return_ty, span_help_and_lint, trait_ref_of_method,
8     walk_ptrs_ty,
9 };
10
11 declare_clippy_lint! {
12     /// **What id does:** Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`.
13     ///
14     /// **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.
15     ///
16     /// **Known problems:** None
17     ///
18     /// ** Example:**
19     ///
20     /// ```rust
21     /// // Bad
22     /// pub struct A;
23     ///
24     /// impl A {
25     ///     pub fn to_string(&self) -> String {
26     ///         "I am A".to_string()
27     ///     }
28     /// }
29     /// ```
30     ///
31     /// ```rust
32     /// // Good
33     /// use std::fmt;
34     ///
35     /// pub struct A;
36     ///
37     /// impl fmt::Display for A {
38     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39     ///         write!(f, "I am A")
40     ///     }
41     /// }
42     /// ```
43     pub INHERENT_TO_STRING,
44     style,
45     "type implements inherent method `to_string()`, but should instead implement the `Display` trait"
46 }
47
48 declare_clippy_lint! {
49     /// **What id 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.
50     ///
51     /// **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`.
52     ///
53     /// **Known problems:** None
54     ///
55     /// ** Example:**
56     ///
57     /// ```rust
58     /// // Bad
59     /// use std::fmt;
60     ///
61     /// pub struct A;
62     ///
63     /// impl A {
64     ///     pub fn to_string(&self) -> String {
65     ///         "I am A".to_string()
66     ///     }
67     /// }
68     ///
69     /// impl fmt::Display for A {
70     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71     ///         write!(f, "I am A, too")
72     ///     }
73     /// }
74     /// ```
75     ///
76     /// ```rust
77     /// // Good
78     /// use std::fmt;
79     ///
80     /// pub struct A;
81     ///
82     /// impl fmt::Display for A {
83     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84     ///         write!(f, "I am A")
85     ///     }
86     /// }
87     /// ```
88     pub INHERENT_TO_STRING_SHADOW_DISPLAY,
89     correctness,
90     "type implements inherent method `to_string()`, which gets shadowed by the implementation of the `Display` trait "
91 }
92
93 declare_lint_pass!(InherentToString => [INHERENT_TO_STRING, INHERENT_TO_STRING_SHADOW_DISPLAY]);
94
95 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InherentToString {
96     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem) {
97         if impl_item.span.from_expansion() {
98             return;
99         }
100
101         if_chain! {
102             // Check if item is a method, called to_string and has a parameter 'self'
103             if let ImplItemKind::Method(ref signature, _) = impl_item.kind;
104             if impl_item.ident.name.as_str() == "to_string";
105             let decl = &signature.decl;
106             if decl.implicit_self.has_implicit_self();
107             if decl.inputs.len() == 1;
108
109             // Check if return type is String
110             if match_type(cx, return_ty(cx, impl_item.hir_id), &paths::STRING);
111
112             // Filters instances of to_string which are required by a trait
113             if trait_ref_of_method(cx, impl_item.hir_id).is_none();
114
115             then {
116                 show_lint(cx, impl_item);
117             }
118         }
119     }
120 }
121
122 fn show_lint(cx: &LateContext<'_, '_>, item: &ImplItem) {
123     let display_trait_id =
124         get_trait_def_id(cx, &["core", "fmt", "Display"]).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 = walk_ptrs_ty(self_type.skip_binder());
130
131     // Emit either a warning or an error
132     if implements_trait(cx, self_type, display_trait_id, &[]) {
133         span_help_and_lint(
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             &format!("remove the inherent method from type `{}`", self_type.to_string())
142         );
143     } else {
144         span_help_and_lint(
145             cx,
146             INHERENT_TO_STRING,
147             item.span,
148             &format!(
149                 "implementation of inherent method `to_string(&self) -> String` for type `{}`",
150                 self_type.to_string()
151             ),
152             &format!("implement trait `Display` for type `{}` instead", self_type.to_string()),
153         );
154     }
155 }