rustc_lint/
nonstandard_style.rs

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