]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/to_string_in_display.rs
Rollup merge of #75954 - ArekPiekarz:unstable_book_ffi_tracking_issues, r=steveklabnik
[rust.git] / src / tools / clippy / clippy_lints / src / to_string_in_display.rs
1 use crate::utils::{match_def_path, match_trait_method, paths, qpath_res, span_lint};
2 use if_chain::if_chain;
3 use rustc_hir::def::Res;
4 use rustc_hir::{Expr, ExprKind, HirId, ImplItem, ImplItemKind, Item, ItemKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
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 let ExprKind::MethodCall(ref path, _, args, _) = expr.kind;
93             if path.ident.name == sym!(to_string);
94             if match_trait_method(cx, expr, &paths::TO_STRING);
95             if self.in_display_impl;
96             if let ExprKind::Path(ref qpath) = args[0].kind;
97             if let Res::Local(hir_id) = qpath_res(cx, qpath, args[0].hir_id);
98             if let Some(self_hir_id) = self.self_hir_id;
99             if hir_id == self_hir_id;
100             then {
101                 span_lint(
102                     cx,
103                     TO_STRING_IN_DISPLAY,
104                     expr.span,
105                     "using `to_string` in `fmt::Display` implementation might lead to infinite recursion",
106                 );
107             }
108         }
109     }
110 }
111
112 fn is_display_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
113     if_chain! {
114         if let ItemKind::Impl { of_trait: Some(trait_ref), .. } = &item.kind;
115         if let Some(did) = trait_ref.trait_def_id();
116         then {
117             match_def_path(cx, did, &paths::DISPLAY_TRAIT)
118         } else {
119             false
120         }
121     }
122 }