]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/inherent_to_string.rs
150a9ea9c96735fc646d0e4faac928334007c65c
[rust.git] / clippy_lints / src / inherent_to_string.rs
1 use if_chain::if_chain;
2 use rustc::declare_lint_pass;
3 use rustc::hir::{ImplItem, ImplItemKind};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc_session::declare_tool_lint;
6
7 use crate::utils::{
8     get_trait_def_id, implements_trait, match_type, paths, return_ty, span_help_and_lint, trait_ref_of_method,
9     walk_ptrs_ty,
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<'a, 'tcx> LateLintPass<'a, 'tcx> for InherentToString {
97     fn check_impl_item(&mut self, cx: &LateContext<'a, '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::Method(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 match_type(cx, return_ty(cx, impl_item.hir_id), &paths::STRING);
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 =
125         get_trait_def_id(cx, &["core", "fmt", "Display"]).expect("Failed to get trait ID of `Display`!");
126
127     // Get the real type of 'self'
128     let fn_def_id = cx.tcx.hir().local_def_id(item.hir_id);
129     let self_type = cx.tcx.fn_sig(fn_def_id).input(0);
130     let self_type = walk_ptrs_ty(self_type.skip_binder());
131
132     // Emit either a warning or an error
133     if implements_trait(cx, self_type, display_trait_id, &[]) {
134         span_help_and_lint(
135             cx,
136             INHERENT_TO_STRING_SHADOW_DISPLAY,
137             item.span,
138             &format!(
139                 "type `{}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`",
140                 self_type.to_string()
141             ),
142             &format!("remove the inherent method from type `{}`", self_type.to_string())
143         );
144     } else {
145         span_help_and_lint(
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             &format!("implement trait `Display` for type `{}` instead", self_type.to_string()),
154         );
155     }
156 }