]>
Commit | Line | Data |
---|---|---|
5099ac24 FG |
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; | |
4b012472 | 5 | use rustc_session::declare_lint_pass; |
5099ac24 FG |
6 | |
7 | declare_clippy_lint! { | |
8 | /// ### What it does | |
9 | /// Checks for lifetimes with names which are one character | |
10 | /// long. | |
11 | /// | |
31ef2f64 | 12 | /// ### Why restrict this? |
5099ac24 FG |
13 | /// A single character is likely not enough to express the |
14 | /// purpose of a lifetime. Using a longer name can make code | |
31ef2f64 | 15 | /// easier to understand. |
5099ac24 FG |
16 | /// |
17 | /// ### Known problems | |
18 | /// Rust programmers and learning resources tend to use single | |
19 | /// character lifetimes, so this lint is at odds with the | |
20 | /// ecosystem at large. In addition, the lifetime's purpose may | |
21 | /// be obvious or, rarely, expressible in one character. | |
22 | /// | |
23 | /// ### Example | |
ed00b5ec | 24 | /// ```no_run |
5099ac24 FG |
25 | /// struct DiagnosticCtx<'a> { |
26 | /// source: &'a str, | |
27 | /// } | |
28 | /// ``` | |
29 | /// Use instead: | |
ed00b5ec | 30 | /// ```no_run |
5099ac24 FG |
31 | /// struct DiagnosticCtx<'src> { |
32 | /// source: &'src str, | |
33 | /// } | |
34 | /// ``` | |
923072b8 | 35 | #[clippy::version = "1.60.0"] |
5099ac24 FG |
36 | pub SINGLE_CHAR_LIFETIME_NAMES, |
37 | restriction, | |
38 | "warns against single-character lifetime names" | |
39 | } | |
40 | ||
41 | declare_lint_pass!(SingleCharLifetimeNames => [SINGLE_CHAR_LIFETIME_NAMES]); | |
42 | ||
43 | impl EarlyLintPass for SingleCharLifetimeNames { | |
44 | fn check_generic_param(&mut self, ctx: &EarlyContext<'_>, param: &GenericParam) { | |
45 | if in_external_macro(ctx.sess(), param.ident.span) { | |
46 | return; | |
47 | } | |
48 | ||
49 | if let GenericParamKind::Lifetime = param.kind { | |
50 | if !param.is_placeholder && param.ident.as_str().len() <= 2 { | |
51 | span_lint_and_help( | |
52 | ctx, | |
53 | SINGLE_CHAR_LIFETIME_NAMES, | |
54 | param.ident.span, | |
55 | "single-character lifetime names are likely uninformative", | |
56 | None, | |
57 | "use a more informative name", | |
58 | ); | |
59 | } | |
60 | } | |
61 | } | |
62 | } |