]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/inherent_to_string.rs
Rollup merge of #104581 - notriddle:notriddle/js-iife-2, r=GuillaumeGomez
[rust.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_lang_item};
3 use clippy_utils::{return_ty, trait_ref_of_method};
4 use if_chain::if_chain;
5 use rustc_hir::{GenericParamKind, ImplItem, ImplItemKind, LangItem};
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     /// ### Example
18     /// ```rust
19     /// pub struct A;
20     ///
21     /// impl A {
22     ///     pub fn to_string(&self) -> String {
23     ///         "I am A".to_string()
24     ///     }
25     /// }
26     /// ```
27     ///
28     /// Use instead:
29     /// ```rust
30     /// use std::fmt;
31     ///
32     /// pub struct A;
33     ///
34     /// impl fmt::Display for A {
35     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36     ///         write!(f, "I am A")
37     ///     }
38     /// }
39     /// ```
40     #[clippy::version = "1.38.0"]
41     pub INHERENT_TO_STRING,
42     style,
43     "type implements inherent method `to_string()`, but should instead implement the `Display` trait"
44 }
45
46 declare_clippy_lint! {
47     /// ### What it does
48     /// 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.
49     ///
50     /// ### Why is this bad?
51     /// 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     /// ### Example
54     /// ```rust
55     /// use std::fmt;
56     ///
57     /// pub struct A;
58     ///
59     /// impl A {
60     ///     pub fn to_string(&self) -> String {
61     ///         "I am A".to_string()
62     ///     }
63     /// }
64     ///
65     /// impl fmt::Display for A {
66     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67     ///         write!(f, "I am A, too")
68     ///     }
69     /// }
70     /// ```
71     ///
72     /// Use instead:
73     /// ```rust
74     /// use std::fmt;
75     ///
76     /// pub struct A;
77     ///
78     /// impl fmt::Display for A {
79     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80     ///         write!(f, "I am A")
81     ///     }
82     /// }
83     /// ```
84     #[clippy::version = "1.38.0"]
85     pub INHERENT_TO_STRING_SHADOW_DISPLAY,
86     correctness,
87     "type implements inherent method `to_string()`, which gets shadowed by the implementation of the `Display` trait"
88 }
89
90 declare_lint_pass!(InherentToString => [INHERENT_TO_STRING, INHERENT_TO_STRING_SHADOW_DISPLAY]);
91
92 impl<'tcx> LateLintPass<'tcx> for InherentToString {
93     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
94         if impl_item.span.from_expansion() {
95             return;
96         }
97
98         if_chain! {
99             // Check if item is a method, called to_string and has a parameter 'self'
100             if let ImplItemKind::Fn(ref signature, _) = impl_item.kind;
101             if impl_item.ident.name == sym::to_string;
102             let decl = &signature.decl;
103             if decl.implicit_self.has_implicit_self();
104             if decl.inputs.len() == 1;
105             if impl_item.generics.params.iter().all(|p| matches!(p.kind, GenericParamKind::Lifetime { .. }));
106
107             // Check if return type is String
108             if is_type_lang_item(cx, return_ty(cx, impl_item.hir_id()), LangItem::String);
109
110             // Filters instances of to_string which are required by a trait
111             if trait_ref_of_method(cx, impl_item.owner_id.def_id).is_none();
112
113             then {
114                 show_lint(cx, impl_item);
115             }
116         }
117     }
118 }
119
120 fn show_lint(cx: &LateContext<'_>, item: &ImplItem<'_>) {
121     let display_trait_id = cx
122         .tcx
123         .get_diagnostic_item(sym::Display)
124         .expect("Failed to get trait ID of `Display`!");
125
126     // Get the real type of 'self'
127     let self_type = cx.tcx.fn_sig(item.owner_id).input(0);
128     let self_type = self_type.skip_binder().peel_refs();
129
130     // Emit either a warning or an error
131     if implements_trait(cx, self_type, display_trait_id, &[]) {
132         span_lint_and_help(
133             cx,
134             INHERENT_TO_STRING_SHADOW_DISPLAY,
135             item.span,
136             &format!(
137                 "type `{self_type}` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`"
138             ),
139             None,
140             &format!("remove the inherent method from type `{self_type}`"),
141         );
142     } else {
143         span_lint_and_help(
144             cx,
145             INHERENT_TO_STRING,
146             item.span,
147             &format!("implementation of inherent method `to_string(&self) -> String` for type `{self_type}`"),
148             None,
149             &format!("implement trait `Display` for type `{self_type}` instead"),
150         );
151     }
152 }