]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/upper_case_acronyms.rs
Rollup merge of #81363 - jonhoo:no-unpin-in-pin-future-impl, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / upper_case_acronyms.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use itertools::Itertools;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Item, ItemKind};
5 use rustc_lint::{LateContext, LateLintPass, LintContext};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::symbol::Ident;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for fully capitalized names and optionally names containing a capitalized acronym.
12     ///
13     /// **Why is this bad?** In CamelCase, acronyms count as one word.
14     /// See [naming conventions](https://rust-lang.github.io/api-guidelines/naming.html#casing-conforms-to-rfc-430-c-case)
15     /// for more.
16     ///
17     /// By default, the lint only triggers on fully-capitalized names.
18     /// You can use the `upper-case-acronyms-aggressive: true` config option to enable linting
19     /// on all camel case names
20     ///
21     /// **Known problems:** When two acronyms are contiguous, the lint can't tell where
22     /// the first acronym ends and the second starts, so it suggests to lowercase all of
23     /// the letters in the second acronym.
24     ///
25     /// **Example:**
26     ///
27     /// ```rust
28     /// struct HTTPResponse;
29     /// ```
30     /// Use instead:
31     /// ```rust
32     /// struct HttpResponse;
33     /// ```
34     pub UPPER_CASE_ACRONYMS,
35     style,
36     "capitalized acronyms are against the naming convention"
37 }
38
39 #[derive(Default)]
40 pub struct UpperCaseAcronyms {
41     avoid_breaking_exported_api: bool,
42     upper_case_acronyms_aggressive: bool,
43 }
44
45 impl UpperCaseAcronyms {
46     pub fn new(avoid_breaking_exported_api: bool, aggressive: bool) -> Self {
47         Self {
48             avoid_breaking_exported_api,
49             upper_case_acronyms_aggressive: aggressive,
50         }
51     }
52 }
53
54 impl_lint_pass!(UpperCaseAcronyms => [UPPER_CASE_ACRONYMS]);
55
56 fn correct_ident(ident: &str) -> String {
57     let ident = ident.chars().rev().collect::<String>();
58     let fragments = ident
59         .split_inclusive(|x: char| !x.is_ascii_lowercase())
60         .rev()
61         .map(|x| x.chars().rev().collect::<String>());
62
63     let mut ident = fragments.clone().next().unwrap();
64     for (ref prev, ref curr) in fragments.tuple_windows() {
65         if [prev, curr]
66             .iter()
67             .all(|s| s.len() == 1 && s.chars().next().unwrap().is_ascii_uppercase())
68         {
69             ident.push_str(&curr.to_ascii_lowercase());
70         } else {
71             ident.push_str(curr);
72         }
73     }
74     ident
75 }
76
77 fn check_ident(cx: &LateContext<'_>, ident: &Ident, be_aggressive: bool) {
78     let span = ident.span;
79     let ident = &ident.as_str();
80     let corrected = correct_ident(ident);
81     // warn if we have pure-uppercase idents
82     // assume that two-letter words are some kind of valid abbreviation like FP for false positive
83     // (and don't warn)
84     if (ident.chars().all(|c| c.is_ascii_uppercase()) && ident.len() > 2)
85     // otherwise, warn if we have SOmeTHING lIKE THIs but only warn with the aggressive
86     // upper-case-acronyms-aggressive config option enabled
87     || (be_aggressive && ident != &corrected)
88     {
89         span_lint_and_sugg(
90             cx,
91             UPPER_CASE_ACRONYMS,
92             span,
93             &format!("name `{}` contains a capitalized acronym", ident),
94             "consider making the acronym lowercase, except the initial letter",
95             corrected,
96             Applicability::MaybeIncorrect,
97         );
98     }
99 }
100
101 impl LateLintPass<'_> for UpperCaseAcronyms {
102     fn check_item(&mut self, cx: &LateContext<'_>, it: &Item<'_>) {
103         // do not lint public items or in macros
104         if in_external_macro(cx.sess(), it.span)
105             || (self.avoid_breaking_exported_api && cx.access_levels.is_exported(it.hir_id()))
106         {
107             return;
108         }
109         match it.kind {
110             ItemKind::TyAlias(..) | ItemKind::Struct(..) | ItemKind::Trait(..) => {
111                 check_ident(cx, &it.ident, self.upper_case_acronyms_aggressive);
112             },
113             ItemKind::Enum(ref enumdef, _) => {
114                 // check enum variants seperately because again we only want to lint on private enums and
115                 // the fn check_variant does not know about the vis of the enum of its variants
116                 enumdef
117                     .variants
118                     .iter()
119                     .for_each(|variant| check_ident(cx, &variant.ident, self.upper_case_acronyms_aggressive));
120             },
121             _ => {},
122         }
123     }
124 }