1 use crate::utils::{match_def_path, match_trait_method, paths, span_lint};
2 use if_chain::if_chain;
3 use rustc_hir::def::Res;
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};
9 /// **What it does:** Checks for uses of `to_string()` in `Display` traits.
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.
15 /// **Known problems:** None.
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())
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)
41 pub TO_STRING_IN_DISPLAY,
43 "`to_string` method used while implementing `Display` trait"
47 pub struct ToStringInDisplay {
48 in_display_impl: bool,
49 self_hir_id: Option<HirId>,
52 impl ToStringInDisplay {
53 pub fn new() -> Self {
55 in_display_impl: false,
61 impl_lint_pass!(ToStringInDisplay => [TO_STRING_IN_DISPLAY]);
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;
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;
77 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &ImplItem<'_>) {
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();
84 let self_param = &body.params[0];
85 self.self_hir_id = Some(self_param.pat.hir_id);
90 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
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) = cx.qpath_res(qpath, args[0].hir_id);
98 if let Some(self_hir_id) = self.self_hir_id;
99 if hir_id == 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)