]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/to_string_in_display.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / to_string_in_display.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{is_diag_trait_item, match_def_path, path_to_local_id, paths};
3 use if_chain::if_chain;
4 use rustc_hir::{Expr, ExprKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::symbol::sym;
8
9 declare_clippy_lint! {
10     /// ### What it does
11     /// Checks for uses of `to_string()` in `Display` traits.
12     ///
13     /// ### Why is this bad?
14     /// Usually `to_string` is implemented indirectly
15     /// via `Display`. Hence using it while implementing `Display` would
16     /// lead to infinite recursion.
17     ///
18     /// ### Example
19     ///
20     /// ```rust
21     /// use std::fmt;
22     ///
23     /// struct Structure(i32);
24     /// impl fmt::Display for Structure {
25     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26     ///         write!(f, "{}", self.to_string())
27     ///     }
28     /// }
29     ///
30     /// ```
31     /// Use instead:
32     /// ```rust
33     /// use std::fmt;
34     ///
35     /// struct Structure(i32);
36     /// impl fmt::Display for Structure {
37     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
38     ///         write!(f, "{}", self.0)
39     ///     }
40     /// }
41     /// ```
42     #[clippy::version = "1.48.0"]
43     pub TO_STRING_IN_DISPLAY,
44     correctness,
45     "`to_string` method used while implementing `Display` trait"
46 }
47
48 #[derive(Default)]
49 pub struct ToStringInDisplay {
50     in_display_impl: bool,
51     self_hir_id: Option<HirId>,
52 }
53
54 impl ToStringInDisplay {
55     pub fn new() -> Self {
56         Self {
57             in_display_impl: false,
58             self_hir_id: None,
59         }
60     }
61 }
62
63 impl_lint_pass!(ToStringInDisplay => [TO_STRING_IN_DISPLAY]);
64
65 impl LateLintPass<'_> for ToStringInDisplay {
66     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
67         if is_display_impl(cx, item) {
68             self.in_display_impl = true;
69         }
70     }
71
72     fn check_item_post(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
73         if is_display_impl(cx, item) {
74             self.in_display_impl = false;
75             self.self_hir_id = None;
76         }
77     }
78
79     fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &ImplItem<'_>) {
80         if_chain! {
81             if self.in_display_impl;
82             if let ImplItemKind::Fn(.., body_id) = &impl_item.kind;
83             let body = cx.tcx.hir().body(*body_id);
84             if !body.params.is_empty();
85             then {
86                 let self_param = &body.params[0];
87                 self.self_hir_id = Some(self_param.pat.hir_id);
88             }
89         }
90     }
91
92     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
93         if_chain! {
94             if self.in_display_impl;
95             if let Some(self_hir_id) = self.self_hir_id;
96             if let ExprKind::MethodCall(path, _, [ref self_arg, ..], _) = expr.kind;
97             if path.ident.name == sym!(to_string);
98             if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
99             if is_diag_trait_item(cx, expr_def_id, sym::ToString);
100             if path_to_local_id(self_arg, self_hir_id);
101             then {
102                 span_lint(
103                     cx,
104                     TO_STRING_IN_DISPLAY,
105                     expr.span,
106                     "using `to_string` in `fmt::Display` implementation might lead to infinite recursion",
107                 );
108             }
109         }
110     }
111 }
112
113 fn is_display_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
114     if_chain! {
115         if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), .. }) = &item.kind;
116         if let Some(did) = trait_ref.trait_def_id();
117         then {
118             match_def_path(cx, did, &paths::DISPLAY_TRAIT)
119         } else {
120             false
121         }
122     }
123 }