Skip to main content

rustc_lint/
nonstandard_style.rs

1use rustc_abi::ExternAbi;
2use rustc_ast as ast;
3use rustc_attr_parsing::AttributeParser;
4use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level};
5use rustc_hir as hir;
6use rustc_hir::attrs::{AttributeKind, ReprAttr};
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::DefId;
9use rustc_hir::intravisit::{FnKind, Visitor};
10use rustc_hir::{Attribute, GenericParamKind, PatExprKind, PatKind, find_attr};
11use rustc_middle::hir::nested_filter::All;
12use rustc_middle::ty::AssocContainer;
13use rustc_session::config::CrateType;
14use rustc_session::{declare_lint, declare_lint_pass};
15use rustc_span::def_id::LocalDefId;
16use rustc_span::{BytePos, Ident, Span, sym};
17
18use crate::lints::{
19    NonCamelCaseType, NonCamelCaseTypeSub, NonSnakeCaseDiag, NonSnakeCaseDiagSub,
20    NonUpperCaseGlobal, NonUpperCaseGlobalSub, NonUpperCaseGlobalSubTool,
21};
22use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
23
24#[doc =
r" The `non_camel_case_types` lint detects types, variants, traits and"]
#[doc = r" type parameters that don't have camel case names."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" struct my_struct;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r#" The preferred style for these identifiers is to use "camel case", such"#]
#[doc =
r" as `MyStruct`, where the first letter should not be lowercase, and"]
#[doc =
r" should not use underscores between letters. Underscores are allowed at"]
#[doc = r" the beginning and end of the identifier, as well as between"]
#[doc = r" non-letters (such as `X86_64`)."]
pub static NON_CAMEL_CASE_TYPES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NON_CAMEL_CASE_TYPES",
            default_level: ::rustc_lint_defs::Warn,
            desc: "types, variants, traits and type parameters should have camel case names",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
25    /// The `non_camel_case_types` lint detects types, variants, traits and
26    /// type parameters that don't have camel case names.
27    ///
28    /// ### Example
29    ///
30    /// ```rust
31    /// struct my_struct;
32    /// ```
33    ///
34    /// {{produces}}
35    ///
36    /// ### Explanation
37    ///
38    /// The preferred style for these identifiers is to use "camel case", such
39    /// as `MyStruct`, where the first letter should not be lowercase, and
40    /// should not use underscores between letters. Underscores are allowed at
41    /// the beginning and end of the identifier, as well as between
42    /// non-letters (such as `X86_64`).
43    pub NON_CAMEL_CASE_TYPES,
44    Warn,
45    "types, variants, traits and type parameters should have camel case names"
46}
47
48pub struct NonCamelCaseTypes;
#[automatically_derived]
impl ::core::marker::Copy for NonCamelCaseTypes { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonCamelCaseTypes { }
#[automatically_derived]
impl ::core::clone::Clone for NonCamelCaseTypes {
    #[inline]
    fn clone(&self) -> NonCamelCaseTypes { *self }
}
impl ::rustc_lint_defs::LintPass for NonCamelCaseTypes {
    fn name(&self) -> &'static str { "NonCamelCaseTypes" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_CAMEL_CASE_TYPES]))
    }
}
impl NonCamelCaseTypes {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_CAMEL_CASE_TYPES]))
    }
}declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
49
50/// Some unicode characters *have* case, are considered upper, title, or lower case, but they *can't*
51/// be title cased or lower cased. For the purposes of the lint suggestion, we care about being able
52/// to change the char's case.
53fn char_has_case(c: char) -> bool {
54    !c.to_lowercase().eq(c.to_titlecase())
55}
56
57/// FIXME: we should add a more efficient version
58/// in the stdlib for this
59fn changes_when_titlecased(c: char) -> bool {
60    !c.to_titlecase().eq([c])
61}
62
63// contains a capitalisable character followed by, or preceded by, an underscore,
64// or contains an uppercase character that changes when titlecased,
65// or contains `__`
66fn not_camel_case(s: &str) -> bool {
67    let mut last = '\0';
68    s.chars().any(|snd| {
69        let fst = std::mem::replace(&mut last, snd);
70        match (fst, snd) {
71            ('_', '_') => return true,
72            ('_', _) if char_has_case(snd) => return true,
73            (_, '_') if char_has_case(fst) => return true,
74            _ => snd.is_uppercase() && changes_when_titlecased(snd),
75        }
76    })
77}
78
79fn is_upper_camel_case(name: &str) -> bool {
80    let name = name.trim_matches('_');
81    let Some(first) = name.chars().next() else {
82        return true;
83    };
84
85    // some scripts don't have a concept of upper/lowercase
86    !(changes_when_titlecased(first) || not_camel_case(name))
87}
88
89fn to_upper_camel_case(s: &str) -> String {
90    s.trim_matches('_')
91        .split('_')
92        .filter(|component| !component.is_empty())
93        .map(|component| {
94            let mut camel_cased_component = String::new();
95
96            let mut new_word = true;
97            let mut prev_is_lower_case = true;
98            let mut prev_is_lowercased_sigma = false;
99
100            for c in component.chars() {
101                // Preserve the case if an uppercase letter follows a lowercase letter, so that
102                // `camelCase` is converted to `CamelCase`.
103                if prev_is_lower_case && (c.is_uppercase() | c.is_titlecase()) {
104                    new_word = true;
105                }
106
107                if new_word {
108                    camel_cased_component.extend(c.to_titlecase());
109                } else {
110                    camel_cased_component.extend(c.to_lowercase());
111                }
112
113                prev_is_lower_case = c.is_lowercase() || c.is_titlecase();
114                prev_is_lowercased_sigma = !new_word && c == 'Σ';
115                new_word = false;
116            }
117
118            if prev_is_lowercased_sigma {
119                camel_cased_component.pop();
120                camel_cased_component.push('ς');
121            }
122
123            camel_cased_component
124        })
125        .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
126            // separate two components with an underscore if their boundary cannot
127            // be distinguished using an uppercase/lowercase case distinction
128            let join = if let Some(prev) = prev {
129                let l = prev.chars().last().unwrap();
130                let f = next.chars().next().unwrap();
131                !char_has_case(l) && !char_has_case(f)
132            } else {
133                false
134            };
135            (acc + if join { "_" } else { "" } + &next, Some(next))
136        })
137        .0
138}
139
140impl NonCamelCaseTypes {
141    fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
142        let name = ident.name.as_str();
143
144        if !is_upper_camel_case(name) {
145            let cc = to_upper_camel_case(name);
146            let sub = if *name != cc {
147                NonCamelCaseTypeSub::Suggestion { span: ident.span, replace: cc }
148            } else {
149                NonCamelCaseTypeSub::Label { span: ident.span }
150            };
151            cx.emit_span_lint(
152                NON_CAMEL_CASE_TYPES,
153                ident.span,
154                NonCamelCaseType { sort, name, sub },
155            );
156        }
157    }
158}
159
160impl EarlyLintPass for NonCamelCaseTypes {
161    fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
162        let has_repr_c = #[allow(non_exhaustive_omitted_patterns)] match AttributeParser::parse_limited(cx.sess(),
        &it.attrs, &[sym::repr]) {
    Some(Attribute::Parsed(AttributeKind::Repr { reprs, .. })) if
        reprs.iter().any(|(r, _)| r == &ReprAttr::ReprC) => true,
    _ => false,
}matches!(
163            AttributeParser::parse_limited(cx.sess(), &it.attrs, &[sym::repr]),
164            Some(Attribute::Parsed(AttributeKind::Repr { reprs, ..})) if reprs.iter().any(|(r, _)| r == &ReprAttr::ReprC)
165        );
166
167        if has_repr_c {
168            return;
169        }
170
171        match &it.kind {
172            ast::ItemKind::TyAlias(box ast::TyAlias { ident, .. })
173            | ast::ItemKind::Enum(ident, ..)
174            | ast::ItemKind::Struct(ident, ..)
175            | ast::ItemKind::Union(ident, ..) => self.check_case(cx, "type", ident),
176            ast::ItemKind::Trait(box ast::Trait { ident, .. }) => {
177                self.check_case(cx, "trait", ident)
178            }
179            ast::ItemKind::TraitAlias(box ast::TraitAlias { ident, .. }) => {
180                self.check_case(cx, "trait alias", ident)
181            }
182
183            // N.B. This check is only for inherent associated types, so that we don't lint against
184            // trait impls where we should have warned for the trait definition already.
185            ast::ItemKind::Impl(ast::Impl { of_trait: None, items, .. }) => {
186                for it in items {
187                    // FIXME: this doesn't respect `#[allow(..)]` on the item itself.
188                    if let ast::AssocItemKind::Type(alias) = &it.kind {
189                        self.check_case(cx, "associated type", &alias.ident);
190                    }
191                }
192            }
193            _ => (),
194        }
195    }
196
197    fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
198        if let ast::AssocItemKind::Type(alias) = &it.kind {
199            self.check_case(cx, "associated type", &alias.ident);
200        }
201    }
202
203    fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
204        self.check_case(cx, "variant", &v.ident);
205    }
206
207    fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
208        if let ast::GenericParamKind::Type { .. } = param.kind {
209            self.check_case(cx, "type parameter", &param.ident);
210        }
211    }
212}
213
214#[doc = r" The `non_snake_case` lint detects variables, methods, functions,"]
#[doc = r" lifetime parameters and modules that don't have snake case names."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" let MY_VALUE = 5;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r#" The preferred style for these identifiers is to use "snake case","#]
#[doc =
r" where all the characters are in lowercase, with words separated with a"]
#[doc = r" single underscore, such as `my_value`."]
pub static NON_SNAKE_CASE: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NON_SNAKE_CASE",
            default_level: ::rustc_lint_defs::Warn,
            desc: "variables, methods, functions, lifetime parameters and modules should have snake case names",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
215    /// The `non_snake_case` lint detects variables, methods, functions,
216    /// lifetime parameters and modules that don't have snake case names.
217    ///
218    /// ### Example
219    ///
220    /// ```rust
221    /// let MY_VALUE = 5;
222    /// ```
223    ///
224    /// {{produces}}
225    ///
226    /// ### Explanation
227    ///
228    /// The preferred style for these identifiers is to use "snake case",
229    /// where all the characters are in lowercase, with words separated with a
230    /// single underscore, such as `my_value`.
231    pub NON_SNAKE_CASE,
232    Warn,
233    "variables, methods, functions, lifetime parameters and modules should have snake case names"
234}
235
236pub struct NonSnakeCase;
#[automatically_derived]
impl ::core::marker::Copy for NonSnakeCase { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonSnakeCase { }
#[automatically_derived]
impl ::core::clone::Clone for NonSnakeCase {
    #[inline]
    fn clone(&self) -> NonSnakeCase { *self }
}
impl ::rustc_lint_defs::LintPass for NonSnakeCase {
    fn name(&self) -> &'static str { "NonSnakeCase" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_SNAKE_CASE]))
    }
}
impl NonSnakeCase {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_SNAKE_CASE]))
    }
}declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
237
238impl NonSnakeCase {
239    fn to_snake_case(mut name: &str) -> String {
240        let mut words = ::alloc::vec::Vec::new()vec![];
241        // Preserve leading underscores
242        name = name.trim_start_matches(|c: char| {
243            if c == '_' {
244                words.push(String::new());
245                true
246            } else {
247                false
248            }
249        });
250        for s in name.split('_') {
251            let mut last_upper = false;
252            let mut buf = String::new();
253            if s.is_empty() {
254                continue;
255            }
256            for ch in s.chars() {
257                if !buf.is_empty()
258                    && buf != "'"
259                    && (ch.is_uppercase() || ch.is_titlecase())
260                    && !last_upper
261                {
262                    // We lowercase only at the end, to handle final sigma correctly
263                    words.push(buf.to_lowercase());
264                    buf = String::new();
265                }
266                last_upper = ch.is_uppercase() || ch.is_titlecase();
267                buf.push(ch);
268            }
269            // We lowercase only at the end, to handle final sigma correctly
270            words.push(buf.to_lowercase());
271        }
272        words.join("_")
273    }
274
275    /// Checks if a given identifier is snake case, and reports a diagnostic if not.
276    fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
277        fn is_snake_case(ident: &str) -> bool {
278            if ident.is_empty() {
279                return true;
280            }
281            let ident = ident.trim_start_matches('\'');
282            let ident = ident.trim_matches('_');
283
284            if ident.contains("__") {
285                return false;
286            }
287
288            // This correctly handles letters in languages with and without
289            // cases, as well as numbers and underscores.
290            // FIXME: we should add a standard library impl of `c.to_lowercase().eq([c])`
291            ident.chars().all(|c| c.to_lowercase().eq([c]))
292        }
293
294        let name = ident.name.as_str();
295
296        if !is_snake_case(name) {
297            let span = ident.span;
298            let sc = NonSnakeCase::to_snake_case(name);
299            // We cannot provide meaningful suggestions
300            // if the characters are in the category of "Uppercase Letter".
301            let sub = if name != sc {
302                // We have a valid span in almost all cases, but we don't have one when linting a
303                // crate name provided via the command line.
304                if !span.is_dummy() {
305                    let sc_ident = Ident::from_str_and_span(&sc, span);
306                    if sc_ident.is_reserved() {
307                        // We shouldn't suggest a reserved identifier to fix non-snake-case
308                        // identifiers. Instead, recommend renaming the identifier entirely or, if
309                        // permitted, escaping it to create a raw identifier.
310                        if sc_ident.name.can_be_raw() {
311                            NonSnakeCaseDiagSub::RenameOrConvertSuggestion {
312                                span,
313                                suggestion: sc_ident,
314                            }
315                        } else {
316                            NonSnakeCaseDiagSub::SuggestionAndNote { span }
317                        }
318                    } else {
319                        NonSnakeCaseDiagSub::ConvertSuggestion { span, suggestion: sc.clone() }
320                    }
321                } else {
322                    NonSnakeCaseDiagSub::Help
323                }
324            } else {
325                NonSnakeCaseDiagSub::Label { span }
326            };
327            cx.emit_span_lint(NON_SNAKE_CASE, span, NonSnakeCaseDiag { sort, name, sc, sub });
328        }
329    }
330}
331
332impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
333    fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) {
334        if id != hir::CRATE_HIR_ID {
335            return;
336        }
337
338        // Issue #45127: don't enforce `snake_case` for binary crates as binaries are not intended
339        // to be distributed and depended on like libraries. The lint is not suppressed for cdylib
340        // or staticlib because it's not clear what the desired lint behavior for those are.
341        if cx.tcx.crate_types().iter().all(|&crate_type| crate_type == CrateType::Executable) {
342            return;
343        }
344
345        let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
346            Some(Ident::from_str(name))
347        } else {
348            {
    'done:
        {
        for i in cx.tcx.hir_krate_attrs() {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(CrateName { name, name_span, ..
                    }) => {
                    break 'done Some((name, name_span));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(cx.tcx, crate, CrateName{name, name_span,..} => (name, name_span)).map(
349                |(&name, &span)| {
350                    // Discard the double quotes surrounding the literal.
351                    let sp = cx
352                        .sess()
353                        .source_map()
354                        .span_to_snippet(span)
355                        .ok()
356                        .and_then(|snippet| {
357                            let left = snippet.find('"')?;
358                            let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
359
360                            Some(
361                                span.with_lo(span.lo() + BytePos(left as u32 + 1))
362                                    .with_hi(span.hi() - BytePos(right as u32)),
363                            )
364                        })
365                        .unwrap_or(span);
366
367                    Ident::new(name, sp)
368                },
369            )
370        };
371
372        if let Some(ident) = &crate_ident {
373            self.check_snake_case(cx, "crate", ident);
374        }
375    }
376
377    fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
378        if let GenericParamKind::Lifetime { .. } = param.kind {
379            self.check_snake_case(cx, "lifetime", &param.name.ident());
380        }
381    }
382
383    fn check_fn(
384        &mut self,
385        cx: &LateContext<'_>,
386        fk: FnKind<'_>,
387        _: &hir::FnDecl<'_>,
388        _: &hir::Body<'_>,
389        _: Span,
390        id: LocalDefId,
391    ) {
392        match &fk {
393            FnKind::Method(ident, sig, ..) => match cx.tcx.associated_item(id).container {
394                AssocContainer::InherentImpl => {
395                    if sig.header.abi != ExternAbi::Rust && {
        {
            'done:
                {
                for i in ::rustc_hir::attrs::HasAttrs::get_attrs(id, &cx.tcx)
                    {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(NoMangle(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(cx.tcx, id, NoMangle(..)) {
396                        return;
397                    }
398                    self.check_snake_case(cx, "method", ident);
399                }
400                AssocContainer::Trait => {
401                    self.check_snake_case(cx, "trait method", ident);
402                }
403                AssocContainer::TraitImpl(_) => {}
404            },
405            FnKind::ItemFn(ident, _, header) => {
406                // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
407                if header.abi != ExternAbi::Rust && {
        {
            'done:
                {
                for i in ::rustc_hir::attrs::HasAttrs::get_attrs(id, &cx.tcx)
                    {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(NoMangle(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(cx.tcx, id, NoMangle(..)) {
408                    return;
409                }
410                self.check_snake_case(cx, "function", ident);
411            }
412            FnKind::Closure => (),
413        }
414    }
415
416    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
417        if let hir::ItemKind::Mod(ident, _) = it.kind {
418            self.check_snake_case(cx, "module", &ident);
419        }
420    }
421
422    fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_, hir::AmbigArg>) {
423        if let hir::TyKind::FnPtr(hir::FnPtrTy { param_idents, .. }) = &ty.kind {
424            for param_ident in *param_idents {
425                if let Some(param_ident) = param_ident {
426                    self.check_snake_case(cx, "variable", param_ident);
427                }
428            }
429        }
430    }
431
432    fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
433        if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(param_idents)) = item.kind {
434            self.check_snake_case(cx, "trait method", &item.ident);
435            for param_ident in param_idents {
436                if let Some(param_ident) = param_ident {
437                    self.check_snake_case(cx, "variable", param_ident);
438                }
439            }
440        }
441    }
442
443    fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
444        if let PatKind::Binding(_, hid, ident, _) = p.kind {
445            if let hir::Node::PatField(field) = cx.tcx.parent_hir_node(hid) {
446                if !field.is_shorthand {
447                    // Only check if a new name has been introduced, to avoid warning
448                    // on both the struct definition and this pattern.
449                    self.check_snake_case(cx, "variable", &ident);
450                }
451                return;
452            }
453            self.check_snake_case(cx, "variable", &ident);
454        }
455    }
456
457    fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
458        for sf in s.fields() {
459            self.check_snake_case(cx, "structure field", &sf.ident);
460        }
461    }
462}
463
464#[doc =
r" The `non_upper_case_globals` lint detects static items that don't have"]
#[doc = r" uppercase identifiers."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" static max_points: i32 = 5;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The preferred style is for static item names to use all uppercase"]
#[doc = r" letters such as `MAX_POINTS`."]
pub static NON_UPPER_CASE_GLOBALS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NON_UPPER_CASE_GLOBALS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "static constants should have uppercase identifiers",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
465    /// The `non_upper_case_globals` lint detects static items that don't have
466    /// uppercase identifiers.
467    ///
468    /// ### Example
469    ///
470    /// ```rust
471    /// static max_points: i32 = 5;
472    /// ```
473    ///
474    /// {{produces}}
475    ///
476    /// ### Explanation
477    ///
478    /// The preferred style is for static item names to use all uppercase
479    /// letters such as `MAX_POINTS`.
480    pub NON_UPPER_CASE_GLOBALS,
481    Warn,
482    "static constants should have uppercase identifiers"
483}
484
485pub struct NonUpperCaseGlobals;
#[automatically_derived]
impl ::core::marker::Copy for NonUpperCaseGlobals { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonUpperCaseGlobals { }
#[automatically_derived]
impl ::core::clone::Clone for NonUpperCaseGlobals {
    #[inline]
    fn clone(&self) -> NonUpperCaseGlobals { *self }
}
impl ::rustc_lint_defs::LintPass for NonUpperCaseGlobals {
    fn name(&self) -> &'static str { "NonUpperCaseGlobals" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_UPPER_CASE_GLOBALS]))
    }
}
impl NonUpperCaseGlobals {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_UPPER_CASE_GLOBALS]))
    }
}declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
486
487struct NonUpperCaseGlobalGenerator<'a, F: FnOnce() -> NonUpperCaseGlobal<'a>> {
488    callback: F,
489}
490
491impl<'a, 'b, F: FnOnce() -> NonUpperCaseGlobal<'b>> Diagnostic<'a, ()>
492    for NonUpperCaseGlobalGenerator<'b, F>
493{
494    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
495        let Self { callback } = self;
496        callback().into_diag(dcx, level)
497    }
498}
499
500impl NonUpperCaseGlobals {
501    fn check_upper_case(cx: &LateContext<'_>, sort: &str, did: Option<LocalDefId>, ident: &Ident) {
502        let name = ident.name.as_str();
503        // FIXME: we should add a more efficient version
504        // in the stdlib for `c.to_uppercase().eq([c])`
505        if !name.chars().all(|c| c.to_uppercase().eq([c])) {
506            let uc = NonSnakeCase::to_snake_case(name).to_uppercase();
507
508            // If the item is exported, suggesting changing its name would be a breaking change
509            // and could break users without a "nice" applicable fix, so let's avoid it.
510            let can_change_usages = if let Some(did) = did {
511                !cx.tcx.effective_visibilities(()).is_exported(did)
512            } else {
513                false
514            };
515
516            // We cannot provide meaningful suggestions
517            // if the characters are in the category of "Lowercase Letter".
518            let sub = if *name != uc {
519                NonUpperCaseGlobalSub::Suggestion {
520                    span: ident.span,
521                    replace: uc.clone(),
522                    applicability: if can_change_usages {
523                        Applicability::MachineApplicable
524                    } else {
525                        Applicability::MaybeIncorrect
526                    },
527                }
528            } else {
529                NonUpperCaseGlobalSub::Label { span: ident.span }
530            };
531
532            struct UsageCollector<'a, 'tcx> {
533                cx: &'tcx LateContext<'a>,
534                did: DefId,
535                collected: Vec<Span>,
536            }
537
538            impl<'v, 'tcx> Visitor<'v> for UsageCollector<'v, 'tcx> {
539                type NestedFilter = All;
540
541                fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
542                    self.cx.tcx
543                }
544
545                fn visit_path(
546                    &mut self,
547                    path: &rustc_hir::Path<'v>,
548                    _id: rustc_hir::HirId,
549                ) -> Self::Result {
550                    if let Some(final_seg) = path.segments.last()
551                        && final_seg.res.opt_def_id() == Some(self.did)
552                    {
553                        self.collected.push(final_seg.ident.span);
554                    }
555                }
556            }
557
558            let callback = || {
559                // Compute usages lazily as it can expansive and useless when the lint is allowed.
560                // cf. https://github.com/rust-lang/rust/pull/142645#issuecomment-2993024625
561                let usages = if can_change_usages
562                    && *name != uc
563                    && let Some(did) = did
564                {
565                    let mut usage_collector =
566                        UsageCollector { cx, did: did.to_def_id(), collected: Vec::new() };
567                    cx.tcx.hir_walk_toplevel_module(&mut usage_collector);
568                    usage_collector
569                        .collected
570                        .into_iter()
571                        .map(|span| NonUpperCaseGlobalSubTool { span, replace: uc.clone() })
572                        .collect()
573                } else {
574                    ::alloc::vec::Vec::new()vec![]
575                };
576
577                NonUpperCaseGlobal { sort, name, sub, usages }
578            };
579            cx.emit_span_lint(
580                NON_UPPER_CASE_GLOBALS,
581                ident.span,
582                NonUpperCaseGlobalGenerator { callback },
583            );
584        }
585    }
586}
587
588impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
589    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
590        let attrs = cx.tcx.hir_attrs(it.hir_id());
591        match it.kind {
592            hir::ItemKind::Static(_, ident, ..) if !{
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(NoMangle(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, NoMangle(..)) => {
593                NonUpperCaseGlobals::check_upper_case(
594                    cx,
595                    "static variable",
596                    Some(it.owner_id.def_id),
597                    &ident,
598                );
599            }
600            hir::ItemKind::Const(ident, ..) => {
601                NonUpperCaseGlobals::check_upper_case(
602                    cx,
603                    "constant",
604                    Some(it.owner_id.def_id),
605                    &ident,
606                );
607            }
608            _ => {}
609        }
610    }
611
612    fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
613        if let hir::TraitItemKind::Const(..) = ti.kind {
614            NonUpperCaseGlobals::check_upper_case(cx, "associated constant", None, &ti.ident);
615        }
616    }
617
618    fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
619        if let hir::ImplItemKind::Const(..) = ii.kind
620            && let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind
621        {
622            NonUpperCaseGlobals::check_upper_case(cx, "associated constant", None, &ii.ident);
623        }
624    }
625
626    fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
627        // Lint for constants that look like binding identifiers (#7526)
628        if let PatKind::Expr(hir::PatExpr {
629            kind: PatExprKind::Path(hir::QPath::Resolved(None, path)),
630            ..
631        }) = p.kind
632        {
633            if let Res::Def(DefKind::Const { .. }, _) = path.res
634                && let [segment] = path.segments
635            {
636                NonUpperCaseGlobals::check_upper_case(
637                    cx,
638                    "constant in pattern",
639                    None,
640                    &segment.ident,
641                );
642            }
643        }
644    }
645
646    fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
647        if let GenericParamKind::Const { .. } = param.kind {
648            NonUpperCaseGlobals::check_upper_case(
649                cx,
650                "const parameter",
651                Some(param.def_id),
652                &param.name.ident(),
653            );
654        }
655    }
656}
657
658#[cfg(test)]
659mod tests;