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};
8 /// **What it does:** Checks for uses of `to_string()` in `Display` traits.
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.
14 /// **Known problems:** None.
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())
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)
40 pub TO_STRING_IN_DISPLAY,
42 "`to_string` method used while implementing `Display` trait"
46 pub struct ToStringInDisplay {
47 in_display_impl: bool,
48 self_hir_id: Option<HirId>,
51 impl ToStringInDisplay {
52 pub fn new() -> Self {
54 in_display_impl: false,
60 impl_lint_pass!(ToStringInDisplay => [TO_STRING_IN_DISPLAY]);
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;
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;
76 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &ImplItem<'_>) {
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();
83 let self_param = &body.params[0];
84 self.self_hir_id = Some(self_param.pat.hir_id);
89 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
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);
100 TO_STRING_IN_DISPLAY,
102 "using `to_string` in `fmt::Display` implementation might lead to infinite recursion",
109 fn is_display_impl(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
111 if let ItemKind::Impl(Impl { of_trait: Some(trait_ref), .. }) = &item.kind;
112 if let Some(did) = trait_ref.trait_def_id();
114 match_def_path(cx, did, &paths::DISPLAY_TRAIT)