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 pub TO_STRING_IN_DISPLAY,
44 "`to_string` method used while implementing `Display` trait"
48 pub struct ToStringInDisplay {
49 in_display_impl: bool,
50 self_hir_id: Option<HirId>,
53 impl ToStringInDisplay {
54 pub fn new() -> Self {
56 in_display_impl: false,
62 impl_lint_pass!(ToStringInDisplay => [TO_STRING_IN_DISPLAY]);
64 impl LateLintPass<'_> for ToStringInDisplay {
65 fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
66 if is_display_impl(cx, item) {
67 self.in_display_impl = true;
71 fn check_item_post(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
72 if is_display_impl(cx, item) {
73 self.in_display_impl = false;
74 self.self_hir_id = None;
78 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &ImplItem<'_>) {
80 if self.in_display_impl;
81 if let ImplItemKind::Fn(.., body_id) = &impl_item.kind;
82 let body = cx.tcx.hir().body(*body_id);
83 if !body.params.is_empty();
85 let self_param = &body.params[0];
86 self.self_hir_id = Some(self_param.pat.hir_id);
91 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
93 if self.in_display_impl;
94 if let Some(self_hir_id) = self.self_hir_id;
95 if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
96 if path.ident.name == sym!(to_string);
97 if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
98 if is_diag_trait_item(cx, expr_def_id, sym::ToString);
99 if path_to_local_id(&args[0], self_hir_id);
103 TO_STRING_IN_DISPLAY,
105 "using `to_string` in `fmt::Display` implementation might lead to infinite recursion",
112 fn is_display_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
114 if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), .. }) = &item.kind;
115 if let Some(did) = trait_ref.trait_def_id();
117 match_def_path(cx, did, &paths::DISPLAY_TRAIT)