]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_fn_self_type.rs
Lint against `Self` as an arbitrary self type
[rust.git] / clippy_lints / src / needless_fn_self_type.rs
1 use crate::utils::span_lint_and_help;
2 use if_chain::if_chain;
3 use rustc_ast::ast::{Param, TyKind};
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// **What it does:** The lint checks for `self` fn fn parameters that explicitly
9     /// specify the `Self`-type explicitly
10     /// **Why is this bad?** Increases the amount and decreases the readability of code
11     ///
12     /// **Known problems:** None
13     ///
14     /// **Example:**
15     /// ```rust
16     /// impl ValType {
17     ///     pub fn bytes(self: Self) -> usize {
18     ///         match self {
19     ///             Self::I32 | Self::F32 => 4,
20     ///             Self::I64 | Self::F64 => 8,
21     ///         }
22     ///     }
23     /// }
24     /// ```
25     ///
26     /// Could be rewritten as
27     ///
28     /// ```rust
29     /// impl ValType {
30     ///     pub fn bytes(self) -> usize {
31     ///         match self {
32     ///             Self::I32 | Self::F32 => 4,
33     ///             Self::I64 | Self::F64 => 8,
34     ///         }
35     ///     }
36     /// }
37     /// ```
38     pub NEEDLESS_FN_SELF_TYPE,
39     style,
40     "type of `self` parameter is already by default `Self`"
41 }
42
43 declare_lint_pass!(NeedlessFnSelfType => [NEEDLESS_FN_SELF_TYPE]);
44
45 impl EarlyLintPass for NeedlessFnSelfType {
46     fn check_param(&mut self, cx: &EarlyContext<'_>, p: &Param) {
47         if_chain! {
48             if p.is_self();
49             if let TyKind::Path(None, path) = &p.ty.kind;
50             if let Some(segment) = path.segments.first();
51             if segment.ident.as_str() == sym!(Self).as_str();
52             then {
53                 span_lint_and_help(
54                     cx,
55                     NEEDLESS_FN_SELF_TYPE,
56                     p.ty.span,
57                     "the type of the `self` parameter is already by default `Self`",
58                     None,
59                     "consider removing the type specification",
60                 );
61             }
62         }
63     }
64 }