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