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;
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, None),
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(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            find_attr!(cx.tcx.hir_attrs(hir::CRATE_HIR_ID), AttributeKind::CrateName{name, name_span,..} => (name, name_span)).map(
347                |(&name, &span)| {
348                    // Discard the double quotes surrounding the literal.
349                    let sp = cx
350                        .sess()
351                        .source_map()
352                        .span_to_snippet(span)
353                        .ok()
354                        .and_then(|snippet| {
355                            let left = snippet.find('"')?;
356                            let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
357
358                            Some(
359                                span
360                                    .with_lo(span.lo() + BytePos(left as u32 + 1))
361                                    .with_hi(span.hi() - BytePos(right as u32)),
362                            )
363                        })
364                        .unwrap_or(span);
365
366                    Ident::new(name, sp)
367                },
368            )
369        };
370
371        if let Some(ident) = &crate_ident {
372            self.check_snake_case(cx, "crate", ident);
373        }
374    }
375
376    fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
377        if let GenericParamKind::Lifetime { .. } = param.kind {
378            self.check_snake_case(cx, "lifetime", &param.name.ident());
379        }
380    }
381
382    fn check_fn(
383        &mut self,
384        cx: &LateContext<'_>,
385        fk: FnKind<'_>,
386        _: &hir::FnDecl<'_>,
387        _: &hir::Body<'_>,
388        _: Span,
389        id: LocalDefId,
390    ) {
391        match &fk {
392            FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
393                MethodLateContext::PlainImpl => {
394                    if sig.header.abi != ExternAbi::Rust
395                        && find_attr!(cx.tcx.get_all_attrs(id), AttributeKind::NoMangle(..))
396                    {
397                        return;
398                    }
399                    self.check_snake_case(cx, "method", ident);
400                }
401                MethodLateContext::TraitAutoImpl => {
402                    self.check_snake_case(cx, "trait method", ident);
403                }
404                _ => (),
405            },
406            FnKind::ItemFn(ident, _, header) => {
407                // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
408                if header.abi != ExternAbi::Rust
409                    && find_attr!(cx.tcx.get_all_attrs(id), AttributeKind::NoMangle(..))
410                {
411                    return;
412                }
413                self.check_snake_case(cx, "function", ident);
414            }
415            FnKind::Closure => (),
416        }
417    }
418
419    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
420        if let hir::ItemKind::Mod(ident, _) = it.kind {
421            self.check_snake_case(cx, "module", &ident);
422        }
423    }
424
425    fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_, hir::AmbigArg>) {
426        if let hir::TyKind::FnPtr(hir::FnPtrTy { param_idents, .. }) = &ty.kind {
427            for param_ident in *param_idents {
428                if let Some(param_ident) = param_ident {
429                    self.check_snake_case(cx, "variable", param_ident);
430                }
431            }
432        }
433    }
434
435    fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
436        if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(param_idents)) = item.kind {
437            self.check_snake_case(cx, "trait method", &item.ident);
438            for param_ident in param_idents {
439                if let Some(param_ident) = param_ident {
440                    self.check_snake_case(cx, "variable", param_ident);
441                }
442            }
443        }
444    }
445
446    fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
447        if let PatKind::Binding(_, hid, ident, _) = p.kind {
448            if let hir::Node::PatField(field) = cx.tcx.parent_hir_node(hid) {
449                if !field.is_shorthand {
450                    // Only check if a new name has been introduced, to avoid warning
451                    // on both the struct definition and this pattern.
452                    self.check_snake_case(cx, "variable", &ident);
453                }
454                return;
455            }
456            self.check_snake_case(cx, "variable", &ident);
457        }
458    }
459
460    fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
461        for sf in s.fields() {
462            self.check_snake_case(cx, "structure field", &sf.ident);
463        }
464    }
465}
466
467declare_lint! {
468    /// The `non_upper_case_globals` lint detects static items that don't have
469    /// uppercase identifiers.
470    ///
471    /// ### Example
472    ///
473    /// ```rust
474    /// static max_points: i32 = 5;
475    /// ```
476    ///
477    /// {{produces}}
478    ///
479    /// ### Explanation
480    ///
481    /// The preferred style is for static item names to use all uppercase
482    /// letters such as `MAX_POINTS`.
483    pub NON_UPPER_CASE_GLOBALS,
484    Warn,
485    "static constants should have uppercase identifiers"
486}
487
488declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
489
490impl NonUpperCaseGlobals {
491    fn check_upper_case(cx: &LateContext<'_>, sort: &str, did: Option<LocalDefId>, ident: &Ident) {
492        let name = ident.name.as_str();
493        if name.chars().any(|c| c.is_lowercase()) {
494            let uc = NonSnakeCase::to_snake_case(name).to_uppercase();
495
496            // If the item is exported, suggesting changing it's name would be breaking-change
497            // and could break users without a "nice" applicable fix, so let's avoid it.
498            let can_change_usages = if let Some(did) = did {
499                !cx.tcx.effective_visibilities(()).is_exported(did)
500            } else {
501                false
502            };
503
504            // We cannot provide meaningful suggestions
505            // if the characters are in the category of "Lowercase Letter".
506            let sub = if *name != uc {
507                NonUpperCaseGlobalSub::Suggestion {
508                    span: ident.span,
509                    replace: uc.clone(),
510                    applicability: if can_change_usages {
511                        Applicability::MachineApplicable
512                    } else {
513                        Applicability::MaybeIncorrect
514                    },
515                }
516            } else {
517                NonUpperCaseGlobalSub::Label { span: ident.span }
518            };
519
520            struct UsageCollector<'a, 'tcx> {
521                cx: &'tcx LateContext<'a>,
522                did: DefId,
523                collected: Vec<Span>,
524            }
525
526            impl<'v, 'tcx> Visitor<'v> for UsageCollector<'v, 'tcx> {
527                type NestedFilter = All;
528
529                fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
530                    self.cx.tcx
531                }
532
533                fn visit_path(
534                    &mut self,
535                    path: &rustc_hir::Path<'v>,
536                    _id: rustc_hir::HirId,
537                ) -> Self::Result {
538                    if let Some(final_seg) = path.segments.last()
539                        && final_seg.res.opt_def_id() == Some(self.did)
540                    {
541                        self.collected.push(final_seg.ident.span);
542                    }
543                }
544            }
545
546            cx.emit_span_lint_lazy(NON_UPPER_CASE_GLOBALS, ident.span, || {
547                // Compute usages lazily as it can expansive and useless when the lint is allowed.
548                // cf. https://github.com/rust-lang/rust/pull/142645#issuecomment-2993024625
549                let usages = if can_change_usages
550                    && *name != uc
551                    && let Some(did) = did
552                {
553                    let mut usage_collector =
554                        UsageCollector { cx, did: did.to_def_id(), collected: Vec::new() };
555                    cx.tcx.hir_walk_toplevel_module(&mut usage_collector);
556                    usage_collector
557                        .collected
558                        .into_iter()
559                        .map(|span| NonUpperCaseGlobalSubTool { span, replace: uc.clone() })
560                        .collect()
561                } else {
562                    vec![]
563                };
564
565                NonUpperCaseGlobal { sort, name, sub, usages }
566            });
567        }
568    }
569}
570
571impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
572    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
573        let attrs = cx.tcx.hir_attrs(it.hir_id());
574        match it.kind {
575            hir::ItemKind::Static(_, ident, ..)
576                if !find_attr!(attrs, AttributeKind::NoMangle(..)) =>
577            {
578                NonUpperCaseGlobals::check_upper_case(
579                    cx,
580                    "static variable",
581                    Some(it.owner_id.def_id),
582                    &ident,
583                );
584            }
585            hir::ItemKind::Const(ident, ..) => {
586                NonUpperCaseGlobals::check_upper_case(
587                    cx,
588                    "constant",
589                    Some(it.owner_id.def_id),
590                    &ident,
591                );
592            }
593            _ => {}
594        }
595    }
596
597    fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
598        if let hir::TraitItemKind::Const(..) = ti.kind {
599            NonUpperCaseGlobals::check_upper_case(cx, "associated constant", None, &ti.ident);
600        }
601    }
602
603    fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
604        if let hir::ImplItemKind::Const(..) = ii.kind
605            && !assoc_item_in_trait_impl(cx, ii)
606        {
607            NonUpperCaseGlobals::check_upper_case(cx, "associated constant", None, &ii.ident);
608        }
609    }
610
611    fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
612        // Lint for constants that look like binding identifiers (#7526)
613        if let PatKind::Expr(hir::PatExpr {
614            kind: PatExprKind::Path(hir::QPath::Resolved(None, path)),
615            ..
616        }) = p.kind
617        {
618            if let Res::Def(DefKind::Const, _) = path.res
619                && let [segment] = path.segments
620            {
621                NonUpperCaseGlobals::check_upper_case(
622                    cx,
623                    "constant in pattern",
624                    None,
625                    &segment.ident,
626                );
627            }
628        }
629    }
630
631    fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
632        if let GenericParamKind::Const { .. } = param.kind {
633            NonUpperCaseGlobals::check_upper_case(
634                cx,
635                "const parameter",
636                Some(param.def_id),
637                &param.name.ident(),
638            );
639        }
640    }
641}
642
643#[cfg(test)]
644mod tests;