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;
11 /// Checks for uses of `to_string()` in `Display` traits.
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.
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())
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)
42 #[clippy::version = "1.48.0"]
43 pub TO_STRING_IN_DISPLAY,
45 "`to_string` method used while implementing `Display` trait"
49 pub struct ToStringInDisplay {
50 in_display_impl: bool,
51 self_hir_id: Option<HirId>,
54 impl ToStringInDisplay {
55 pub fn new() -> Self {
57 in_display_impl: false,
63 impl_lint_pass!(ToStringInDisplay => [TO_STRING_IN_DISPLAY]);
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;
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;
79 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &ImplItem<'_>) {
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();
86 let self_param = &body.params[0];
87 self.self_hir_id = Some(self_param.pat.hir_id);
92 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
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);
104 TO_STRING_IN_DISPLAY,
106 "using `to_string` in `fmt::Display` implementation might lead to infinite recursion",
113 fn is_display_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
115 if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), .. }) = &item.kind;
116 if let Some(did) = trait_ref.trait_def_id();
118 match_def_path(cx, did, &paths::DISPLAY_TRAIT)