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