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