rustc_lint/
nonstandard_style.rs

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