]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/single_char_lifetime_names.rs
Rollup merge of #106410 - clubby789:borrow-mut-self-mut-self-diag, r=compiler-errors
[rust.git] / src / tools / clippy / clippy_lints / src / single_char_lifetime_names.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use rustc_ast::ast::{GenericParam, GenericParamKind};
3 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
4 use rustc_middle::lint::in_external_macro;
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// ### What it does
9     /// Checks for lifetimes with names which are one character
10     /// long.
11     ///
12     /// ### Why is this bad?
13     /// A single character is likely not enough to express the
14     /// purpose of a lifetime. Using a longer name can make code
15     /// easier to understand, especially for those who are new to
16     /// Rust.
17     ///
18     /// ### Known problems
19     /// Rust programmers and learning resources tend to use single
20     /// character lifetimes, so this lint is at odds with the
21     /// ecosystem at large. In addition, the lifetime's purpose may
22     /// be obvious or, rarely, expressible in one character.
23     ///
24     /// ### Example
25     /// ```rust
26     /// struct DiagnosticCtx<'a> {
27     ///     source: &'a str,
28     /// }
29     /// ```
30     /// Use instead:
31     /// ```rust
32     /// struct DiagnosticCtx<'src> {
33     ///     source: &'src str,
34     /// }
35     /// ```
36     #[clippy::version = "1.60.0"]
37     pub SINGLE_CHAR_LIFETIME_NAMES,
38     restriction,
39     "warns against single-character lifetime names"
40 }
41
42 declare_lint_pass!(SingleCharLifetimeNames => [SINGLE_CHAR_LIFETIME_NAMES]);
43
44 impl EarlyLintPass for SingleCharLifetimeNames {
45     fn check_generic_param(&mut self, ctx: &EarlyContext<'_>, param: &GenericParam) {
46         if in_external_macro(ctx.sess(), param.ident.span) {
47             return;
48         }
49
50         if let GenericParamKind::Lifetime = param.kind {
51             if !param.is_placeholder && param.ident.as_str().len() <= 2 {
52                 span_lint_and_help(
53                     ctx,
54                     SINGLE_CHAR_LIFETIME_NAMES,
55                     param.ident.span,
56                     "single-character lifetime names are likely uninformative",
57                     None,
58                     "use a more informative name",
59                 );
60             }
61         }
62     }
63 }