• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::lints::{
2     NonCamelCaseType, NonCamelCaseTypeSub, NonSnakeCaseDiag, NonSnakeCaseDiagSub,
3     NonUpperCaseGlobal, NonUpperCaseGlobalSub,
4 };
5 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
6 use rustc_ast as ast;
7 use rustc_attr as attr;
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::intravisit::FnKind;
11 use rustc_hir::{GenericParamKind, PatKind};
12 use rustc_middle::ty;
13 use rustc_span::def_id::LocalDefId;
14 use rustc_span::symbol::{sym, Ident};
15 use rustc_span::{BytePos, Span};
16 use rustc_target::spec::abi::Abi;
17 
18 #[derive(PartialEq)]
19 pub enum MethodLateContext {
20     TraitAutoImpl,
21     TraitImpl,
22     PlainImpl,
23 }
24 
method_context(cx: &LateContext<'_>, id: LocalDefId) -> MethodLateContext25 pub fn method_context(cx: &LateContext<'_>, id: LocalDefId) -> MethodLateContext {
26     let item = cx.tcx.associated_item(id);
27     match item.container {
28         ty::TraitContainer => MethodLateContext::TraitAutoImpl,
29         ty::ImplContainer => match cx.tcx.impl_trait_ref(item.container_id(cx.tcx)) {
30             Some(_) => MethodLateContext::TraitImpl,
31             None => MethodLateContext::PlainImpl,
32         },
33     }
34 }
35 
assoc_item_in_trait_impl(cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) -> bool36 fn assoc_item_in_trait_impl(cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) -> bool {
37     let item = cx.tcx.associated_item(ii.owner_id);
38     item.trait_item_def_id.is_some()
39 }
40 
41 declare_lint! {
42     /// The `non_camel_case_types` lint detects types, variants, traits and
43     /// type parameters that don't have camel case names.
44     ///
45     /// ### Example
46     ///
47     /// ```rust
48     /// struct my_struct;
49     /// ```
50     ///
51     /// {{produces}}
52     ///
53     /// ### Explanation
54     ///
55     /// The preferred style for these identifiers is to use "camel case", such
56     /// as `MyStruct`, where the first letter should not be lowercase, and
57     /// should not use underscores between letters. Underscores are allowed at
58     /// the beginning and end of the identifier, as well as between
59     /// non-letters (such as `X86_64`).
60     pub NON_CAMEL_CASE_TYPES,
61     Warn,
62     "types, variants, traits and type parameters should have camel case names"
63 }
64 
65 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
66 
67 /// Some unicode characters *have* case, are considered upper case or lower case, but they *can't*
68 /// be upper cased or lower cased. For the purposes of the lint suggestion, we care about being able
69 /// to change the char's case.
char_has_case(c: char) -> bool70 fn char_has_case(c: char) -> bool {
71     let mut l = c.to_lowercase();
72     let mut u = c.to_uppercase();
73     while let Some(l) = l.next() {
74         match u.next() {
75             Some(u) if l != u => return true,
76             _ => {}
77         }
78     }
79     u.next().is_some()
80 }
81 
is_camel_case(name: &str) -> bool82 fn is_camel_case(name: &str) -> bool {
83     let name = name.trim_matches('_');
84     if name.is_empty() {
85         return true;
86     }
87 
88     // start with a non-lowercase letter rather than non-uppercase
89     // ones (some scripts don't have a concept of upper/lowercase)
90     !name.chars().next().unwrap().is_lowercase()
91         && !name.contains("__")
92         && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
93             // contains a capitalisable character followed by, or preceded by, an underscore
94             char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
95         })
96 }
97 
to_camel_case(s: &str) -> String98 fn to_camel_case(s: &str) -> String {
99     s.trim_matches('_')
100         .split('_')
101         .filter(|component| !component.is_empty())
102         .map(|component| {
103             let mut camel_cased_component = String::new();
104 
105             let mut new_word = true;
106             let mut prev_is_lower_case = true;
107 
108             for c in component.chars() {
109                 // Preserve the case if an uppercase letter follows a lowercase letter, so that
110                 // `camelCase` is converted to `CamelCase`.
111                 if prev_is_lower_case && c.is_uppercase() {
112                     new_word = true;
113                 }
114 
115                 if new_word {
116                     camel_cased_component.extend(c.to_uppercase());
117                 } else {
118                     camel_cased_component.extend(c.to_lowercase());
119                 }
120 
121                 prev_is_lower_case = c.is_lowercase();
122                 new_word = false;
123             }
124 
125             camel_cased_component
126         })
127         .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
128             // separate two components with an underscore if their boundary cannot
129             // be distinguished using an uppercase/lowercase case distinction
130             let join = if let Some(prev) = prev {
131                 let l = prev.chars().last().unwrap();
132                 let f = next.chars().next().unwrap();
133                 !char_has_case(l) && !char_has_case(f)
134             } else {
135                 false
136             };
137             (acc + if join { "_" } else { "" } + &next, Some(next))
138         })
139         .0
140 }
141 
142 impl NonCamelCaseTypes {
check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident)143     fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
144         let name = ident.name.as_str();
145 
146         if !is_camel_case(name) {
147             let cc = to_camel_case(name);
148             let sub = if *name != cc {
149                 NonCamelCaseTypeSub::Suggestion { span: ident.span, replace: cc }
150             } else {
151                 NonCamelCaseTypeSub::Label { span: ident.span }
152             };
153             cx.emit_spanned_lint(
154                 NON_CAMEL_CASE_TYPES,
155                 ident.span,
156                 NonCamelCaseType { sort, name, sub },
157             );
158         }
159     }
160 }
161 
162 impl EarlyLintPass for NonCamelCaseTypes {
check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item)163     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
164         let has_repr_c = it
165             .attrs
166             .iter()
167             .any(|attr| attr::find_repr_attrs(cx.sess(), attr).contains(&attr::ReprC));
168 
169         if has_repr_c {
170             return;
171         }
172 
173         match &it.kind {
174             ast::ItemKind::TyAlias(..)
175             | ast::ItemKind::Enum(..)
176             | ast::ItemKind::Struct(..)
177             | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
178             ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
179             ast::ItemKind::TraitAlias(..) => self.check_case(cx, "trait alias", &it.ident),
180 
181             // N.B. This check is only for inherent associated types, so that we don't lint against
182             // trait impls where we should have warned for the trait definition already.
183             ast::ItemKind::Impl(box ast::Impl { of_trait: None, items, .. }) => {
184                 for it in items {
185                     // FIXME: this doesn't respect `#[allow(..)]` on the item itself.
186                     if let ast::AssocItemKind::Type(..) = it.kind {
187                         self.check_case(cx, "associated type", &it.ident);
188                     }
189                 }
190             }
191             _ => (),
192         }
193     }
194 
check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem)195     fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
196         if let ast::AssocItemKind::Type(..) = it.kind {
197             self.check_case(cx, "associated type", &it.ident);
198         }
199     }
200 
check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant)201     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
202         self.check_case(cx, "variant", &v.ident);
203     }
204 
check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam)205     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
206         if let ast::GenericParamKind::Type { .. } = param.kind {
207             self.check_case(cx, "type parameter", &param.ident);
208         }
209     }
210 }
211 
212 declare_lint! {
213     /// The `non_snake_case` lint detects variables, methods, functions,
214     /// lifetime parameters and modules that don't have snake case names.
215     ///
216     /// ### Example
217     ///
218     /// ```rust
219     /// let MY_VALUE = 5;
220     /// ```
221     ///
222     /// {{produces}}
223     ///
224     /// ### Explanation
225     ///
226     /// The preferred style for these identifiers is to use "snake case",
227     /// where all the characters are in lowercase, with words separated with a
228     /// single underscore, such as `my_value`.
229     pub NON_SNAKE_CASE,
230     Warn,
231     "variables, methods, functions, lifetime parameters and modules should have snake case names"
232 }
233 
234 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
235 
236 impl NonSnakeCase {
to_snake_case(mut str: &str) -> String237     fn to_snake_case(mut str: &str) -> String {
238         let mut words = vec![];
239         // Preserve leading underscores
240         str = str.trim_start_matches(|c: char| {
241             if c == '_' {
242                 words.push(String::new());
243                 true
244             } else {
245                 false
246             }
247         });
248         for s in str.split('_') {
249             let mut last_upper = false;
250             let mut buf = String::new();
251             if s.is_empty() {
252                 continue;
253             }
254             for ch in s.chars() {
255                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
256                     words.push(buf);
257                     buf = String::new();
258                 }
259                 last_upper = ch.is_uppercase();
260                 buf.extend(ch.to_lowercase());
261             }
262             words.push(buf);
263         }
264         words.join("_")
265     }
266 
267     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident)268     fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
269         fn is_snake_case(ident: &str) -> bool {
270             if ident.is_empty() {
271                 return true;
272             }
273             let ident = ident.trim_start_matches('\'');
274             let ident = ident.trim_matches('_');
275 
276             let mut allow_underscore = true;
277             ident.chars().all(|c| {
278                 allow_underscore = match c {
279                     '_' if !allow_underscore => return false,
280                     '_' => false,
281                     // It would be more obvious to use `c.is_lowercase()`,
282                     // but some characters do not have a lowercase form
283                     c if !c.is_uppercase() => true,
284                     _ => return false,
285                 };
286                 true
287             })
288         }
289 
290         let name = ident.name.as_str();
291 
292         if !is_snake_case(name) {
293             let span = ident.span;
294             let sc = NonSnakeCase::to_snake_case(name);
295             // We cannot provide meaningful suggestions
296             // if the characters are in the category of "Uppercase Letter".
297             let sub = if name != sc {
298                 // We have a valid span in almost all cases, but we don't have one when linting a crate
299                 // name provided via the command line.
300                 if !span.is_dummy() {
301                     let sc_ident = Ident::from_str_and_span(&sc, span);
302                     if sc_ident.is_reserved() {
303                         // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
304                         // Instead, recommend renaming the identifier entirely or, if permitted,
305                         // escaping it to create a raw identifier.
306                         if sc_ident.name.can_be_raw() {
307                             NonSnakeCaseDiagSub::RenameOrConvertSuggestion {
308                                 span,
309                                 suggestion: sc_ident,
310                             }
311                         } else {
312                             NonSnakeCaseDiagSub::SuggestionAndNote { span }
313                         }
314                     } else {
315                         NonSnakeCaseDiagSub::ConvertSuggestion { span, suggestion: sc.clone() }
316                     }
317                 } else {
318                     NonSnakeCaseDiagSub::Help
319                 }
320             } else {
321                 NonSnakeCaseDiagSub::Label { span }
322             };
323             cx.emit_spanned_lint(NON_SNAKE_CASE, span, NonSnakeCaseDiag { sort, name, sc, sub });
324         }
325     }
326 }
327 
328 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId)329     fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) {
330         if id != hir::CRATE_HIR_ID {
331             return;
332         }
333 
334         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
335             Some(Ident::from_str(name))
336         } else {
337             attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
338                 .and_then(|attr| attr.meta())
339                 .and_then(|meta| {
340                     meta.name_value_literal().and_then(|lit| {
341                         if let ast::LitKind::Str(name, ..) = lit.kind {
342                             // Discard the double quotes surrounding the literal.
343                             let sp = cx
344                                 .sess()
345                                 .source_map()
346                                 .span_to_snippet(lit.span)
347                                 .ok()
348                                 .and_then(|snippet| {
349                                     let left = snippet.find('"')?;
350                                     let right =
351                                         snippet.rfind('"').map(|pos| snippet.len() - pos)?;
352 
353                                     Some(
354                                         lit.span
355                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
356                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
357                                     )
358                                 })
359                                 .unwrap_or(lit.span);
360 
361                             Some(Ident::new(name, sp))
362                         } else {
363                             None
364                         }
365                     })
366                 })
367         };
368 
369         if let Some(ident) = &crate_ident {
370             self.check_snake_case(cx, "crate", ident);
371         }
372     }
373 
check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>)374     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
375         if let GenericParamKind::Lifetime { .. } = param.kind {
376             self.check_snake_case(cx, "lifetime", &param.name.ident());
377         }
378     }
379 
check_fn( &mut self, cx: &LateContext<'_>, fk: FnKind<'_>, _: &hir::FnDecl<'_>, _: &hir::Body<'_>, _: Span, id: LocalDefId, )380     fn check_fn(
381         &mut self,
382         cx: &LateContext<'_>,
383         fk: FnKind<'_>,
384         _: &hir::FnDecl<'_>,
385         _: &hir::Body<'_>,
386         _: Span,
387         id: LocalDefId,
388     ) {
389         match &fk {
390             FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
391                 MethodLateContext::PlainImpl => {
392                     if sig.header.abi != Abi::Rust && cx.tcx.has_attr(id, sym::no_mangle) {
393                         return;
394                     }
395                     self.check_snake_case(cx, "method", ident);
396                 }
397                 MethodLateContext::TraitAutoImpl => {
398                     self.check_snake_case(cx, "trait method", ident);
399                 }
400                 _ => (),
401             },
402             FnKind::ItemFn(ident, _, header) => {
403                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
404                 if header.abi != Abi::Rust && cx.tcx.has_attr(id, sym::no_mangle) {
405                     return;
406                 }
407                 self.check_snake_case(cx, "function", ident);
408             }
409             FnKind::Closure => (),
410         }
411     }
412 
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)413     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
414         if let hir::ItemKind::Mod(_) = it.kind {
415             self.check_snake_case(cx, "module", &it.ident);
416         }
417     }
418 
check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>)419     fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
420         if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
421             self.check_snake_case(cx, "trait method", &item.ident);
422             for param_name in pnames {
423                 self.check_snake_case(cx, "variable", param_name);
424             }
425         }
426     }
427 
check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>)428     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
429         if let PatKind::Binding(_, hid, ident, _) = p.kind {
430             if let hir::Node::PatField(field) = cx.tcx.hir().get_parent(hid) {
431                 if !field.is_shorthand {
432                     // Only check if a new name has been introduced, to avoid warning
433                     // on both the struct definition and this pattern.
434                     self.check_snake_case(cx, "variable", &ident);
435                 }
436                 return;
437             }
438             self.check_snake_case(cx, "variable", &ident);
439         }
440     }
441 
check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>)442     fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
443         for sf in s.fields() {
444             self.check_snake_case(cx, "structure field", &sf.ident);
445         }
446     }
447 }
448 
449 declare_lint! {
450     /// The `non_upper_case_globals` lint detects static items that don't have
451     /// uppercase identifiers.
452     ///
453     /// ### Example
454     ///
455     /// ```rust
456     /// static max_points: i32 = 5;
457     /// ```
458     ///
459     /// {{produces}}
460     ///
461     /// ### Explanation
462     ///
463     /// The preferred style is for static item names to use all uppercase
464     /// letters such as `MAX_POINTS`.
465     pub NON_UPPER_CASE_GLOBALS,
466     Warn,
467     "static constants should have uppercase identifiers"
468 }
469 
470 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
471 
472 impl NonUpperCaseGlobals {
check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident)473     fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
474         let name = ident.name.as_str();
475         if name.chars().any(|c| c.is_lowercase()) {
476             let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
477             // We cannot provide meaningful suggestions
478             // if the characters are in the category of "Lowercase Letter".
479             let sub = if *name != uc {
480                 NonUpperCaseGlobalSub::Suggestion { span: ident.span, replace: uc }
481             } else {
482                 NonUpperCaseGlobalSub::Label { span: ident.span }
483             };
484             cx.emit_spanned_lint(
485                 NON_UPPER_CASE_GLOBALS,
486                 ident.span,
487                 NonUpperCaseGlobal { sort, name, sub },
488             );
489         }
490     }
491 }
492 
493 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>)494     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
495         let attrs = cx.tcx.hir().attrs(it.hir_id());
496         match it.kind {
497             hir::ItemKind::Static(..) if !attr::contains_name(attrs, sym::no_mangle) => {
498                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
499             }
500             hir::ItemKind::Const(..) => {
501                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
502             }
503             _ => {}
504         }
505     }
506 
check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>)507     fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
508         if let hir::TraitItemKind::Const(..) = ti.kind {
509             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
510         }
511     }
512 
check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>)513     fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
514         if let hir::ImplItemKind::Const(..) = ii.kind && !assoc_item_in_trait_impl(cx, ii) {
515             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
516         }
517     }
518 
check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>)519     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
520         // Lint for constants that look like binding identifiers (#7526)
521         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
522             if let Res::Def(DefKind::Const, _) = path.res {
523                 if path.segments.len() == 1 {
524                     NonUpperCaseGlobals::check_upper_case(
525                         cx,
526                         "constant in pattern",
527                         &path.segments[0].ident,
528                     );
529                 }
530             }
531         }
532     }
533 
check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>)534     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
535         if let GenericParamKind::Const { .. } = param.kind {
536             // `rustc_host` params are explicitly allowed to be lowercase.
537             if cx.tcx.has_attr(param.def_id, sym::rustc_host) {
538                 return;
539             }
540             NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
541         }
542     }
543 }
544 
545 #[cfg(test)]
546 mod tests;
547