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