-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathto_string_trait_impl.rs
67 lines (64 loc) · 2.01 KB
/
to_string_trait_impl.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for direct implementations of `ToString`.
/// ### Why is this bad?
/// This trait is automatically implemented for any type which implements the `Display` trait.
/// As such, `ToString` shouldn’t be implemented directly: `Display` should be implemented instead,
/// and you get the `ToString` implementation for free.
/// ### Example
/// ```no_run
/// struct Point {
/// x: usize,
/// y: usize,
/// }
///
/// impl ToString for Point {
/// fn to_string(&self) -> String {
/// format!("({}, {})", self.x, self.y)
/// }
/// }
/// ```
/// Use instead:
/// ```no_run
/// struct Point {
/// x: usize,
/// y: usize,
/// }
///
/// impl std::fmt::Display for Point {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "({}, {})", self.x, self.y)
/// }
/// }
/// ```
#[clippy::version = "1.78.0"]
pub TO_STRING_TRAIT_IMPL,
style,
"check for direct implementations of `ToString`"
}
declare_lint_pass!(ToStringTraitImpl => [TO_STRING_TRAIT_IMPL]);
impl<'tcx> LateLintPass<'tcx> for ToStringTraitImpl {
fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'tcx>) {
if let ItemKind::Impl(Impl {
of_trait: Some(trait_ref),
..
}) = it.kind
&& let Some(trait_did) = trait_ref.trait_def_id()
&& cx.tcx.is_diagnostic_item(sym::ToString, trait_did)
{
span_lint_and_help(
cx,
TO_STRING_TRAIT_IMPL,
it.span,
"direct implementation of `ToString`",
None,
"prefer implementing `Display` instead",
);
}
}
}