2 NonCamelCaseType, NonCamelCaseTypeSub, NonSnakeCaseDiag, NonSnakeCaseDiagSub,
3 NonUpperCaseGlobal, NonUpperCaseGlobalSub,
5 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
7 use rustc_attr as attr;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::intravisit::FnKind;
11 use rustc_hir::{GenericParamKind, PatKind};
13 use rustc_span::symbol::sym;
14 use rustc_span::{symbol::Ident, BytePos, Span};
15 use rustc_target::spec::abi::Abi;
18 pub enum MethodLateContext {
24 pub fn method_context(cx: &LateContext<'_>, id: hir::HirId) -> MethodLateContext {
25 let def_id = cx.tcx.hir().local_def_id(id);
26 let item = cx.tcx.associated_item(def_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,
37 /// The `non_camel_case_types` lint detects types, variants, traits and
38 /// type parameters that don't have camel case names.
50 /// The preferred style for these identifiers is to use "camel case", such
51 /// as `MyStruct`, where the first letter should not be lowercase, and
52 /// should not use underscores between letters. Underscores are allowed at
53 /// the beginning and end of the identifier, as well as between
54 /// non-letters (such as `X86_64`).
55 pub NON_CAMEL_CASE_TYPES,
57 "types, variants, traits and type parameters should have camel case names"
60 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
62 /// Some unicode characters *have* case, are considered upper case or lower case, but they *can't*
63 /// be upper cased or lower cased. For the purposes of the lint suggestion, we care about being able
64 /// to change the char's case.
65 fn char_has_case(c: char) -> bool {
66 let mut l = c.to_lowercase();
67 let mut u = c.to_uppercase();
68 while let Some(l) = l.next() {
70 Some(u) if l != u => return true,
77 fn is_camel_case(name: &str) -> bool {
78 let name = name.trim_matches('_');
83 // start with a non-lowercase letter rather than non-uppercase
84 // ones (some scripts don't have a concept of upper/lowercase)
85 !name.chars().next().unwrap().is_lowercase()
86 && !name.contains("__")
87 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
88 // contains a capitalisable character followed by, or preceded by, an underscore
89 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
93 fn to_camel_case(s: &str) -> String {
96 .filter(|component| !component.is_empty())
98 let mut camel_cased_component = String::new();
100 let mut new_word = true;
101 let mut prev_is_lower_case = true;
103 for c in component.chars() {
104 // Preserve the case if an uppercase letter follows a lowercase letter, so that
105 // `camelCase` is converted to `CamelCase`.
106 if prev_is_lower_case && c.is_uppercase() {
111 camel_cased_component.extend(c.to_uppercase());
113 camel_cased_component.extend(c.to_lowercase());
116 prev_is_lower_case = c.is_lowercase();
120 camel_cased_component
122 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
123 // separate two components with an underscore if their boundary cannot
124 // be distinguished using an uppercase/lowercase case distinction
125 let join = if let Some(prev) = prev {
126 let l = prev.chars().last().unwrap();
127 let f = next.chars().next().unwrap();
128 !char_has_case(l) && !char_has_case(f)
132 (acc + if join { "_" } else { "" } + &next, Some(next))
137 impl NonCamelCaseTypes {
138 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
139 let name = ident.name.as_str();
141 if !is_camel_case(name) {
142 let cc = to_camel_case(name);
143 let sub = if *name != cc {
144 NonCamelCaseTypeSub::Suggestion { span: ident.span, replace: cc }
146 NonCamelCaseTypeSub::Label { span: ident.span }
148 cx.emit_spanned_lint(
149 NON_CAMEL_CASE_TYPES,
151 NonCamelCaseType { sort, name, sub },
157 impl EarlyLintPass for NonCamelCaseTypes {
158 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
162 .any(|attr| attr::find_repr_attrs(cx.sess(), attr).contains(&attr::ReprC));
169 ast::ItemKind::TyAlias(..)
170 | ast::ItemKind::Enum(..)
171 | ast::ItemKind::Struct(..)
172 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
173 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
174 ast::ItemKind::TraitAlias(..) => self.check_case(cx, "trait alias", &it.ident),
176 // N.B. This check is only for inherent associated types, so that we don't lint against
177 // trait impls where we should have warned for the trait definition already.
178 ast::ItemKind::Impl(box ast::Impl { of_trait: None, items, .. }) => {
180 if let ast::AssocItemKind::Type(..) = it.kind {
181 self.check_case(cx, "associated type", &it.ident);
189 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
190 if let ast::AssocItemKind::Type(..) = it.kind {
191 self.check_case(cx, "associated type", &it.ident);
195 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
196 self.check_case(cx, "variant", &v.ident);
199 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
200 if let ast::GenericParamKind::Type { .. } = param.kind {
201 self.check_case(cx, "type parameter", ¶m.ident);
207 /// The `non_snake_case` lint detects variables, methods, functions,
208 /// lifetime parameters and modules that don't have snake case names.
213 /// let MY_VALUE = 5;
220 /// The preferred style for these identifiers is to use "snake case",
221 /// where all the characters are in lowercase, with words separated with a
222 /// single underscore, such as `my_value`.
225 "variables, methods, functions, lifetime parameters and modules should have snake case names"
228 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
231 fn to_snake_case(mut str: &str) -> String {
232 let mut words = vec![];
233 // Preserve leading underscores
234 str = str.trim_start_matches(|c: char| {
236 words.push(String::new());
242 for s in str.split('_') {
243 let mut last_upper = false;
244 let mut buf = String::new();
248 for ch in s.chars() {
249 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
253 last_upper = ch.is_uppercase();
254 buf.extend(ch.to_lowercase());
261 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
262 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
263 fn is_snake_case(ident: &str) -> bool {
264 if ident.is_empty() {
267 let ident = ident.trim_start_matches('\'');
268 let ident = ident.trim_matches('_');
270 let mut allow_underscore = true;
271 ident.chars().all(|c| {
272 allow_underscore = match c {
273 '_' if !allow_underscore => return false,
275 // It would be more obvious to use `c.is_lowercase()`,
276 // but some characters do not have a lowercase form
277 c if !c.is_uppercase() => true,
284 let name = ident.name.as_str();
286 if !is_snake_case(name) {
287 let span = ident.span;
288 let sc = NonSnakeCase::to_snake_case(name);
289 // We cannot provide meaningful suggestions
290 // if the characters are in the category of "Uppercase Letter".
291 let sub = if name != sc {
292 // We have a valid span in almost all cases, but we don't have one when linting a crate
293 // name provided via the command line.
294 if !span.is_dummy() {
295 let sc_ident = Ident::from_str_and_span(&sc, span);
296 if sc_ident.is_reserved() {
297 // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
298 // Instead, recommend renaming the identifier entirely or, if permitted,
299 // escaping it to create a raw identifier.
300 if sc_ident.name.can_be_raw() {
301 NonSnakeCaseDiagSub::RenameOrConvertSuggestion {
303 suggestion: sc_ident,
306 NonSnakeCaseDiagSub::SuggestionAndNote { span }
309 NonSnakeCaseDiagSub::ConvertSuggestion { span, suggestion: sc.clone() }
312 NonSnakeCaseDiagSub::Help
315 NonSnakeCaseDiagSub::Label { span }
317 cx.emit_spanned_lint(NON_SNAKE_CASE, span, NonSnakeCaseDiag { sort, name, sc, sub });
322 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
323 fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) {
324 if id != hir::CRATE_HIR_ID {
328 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
329 Some(Ident::from_str(name))
332 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
333 .and_then(|attr| attr.meta())
335 meta.name_value_literal().and_then(|lit| {
336 if let ast::LitKind::Str(name, ..) = lit.kind {
337 // Discard the double quotes surrounding the literal.
341 .span_to_snippet(lit.span)
343 .and_then(|snippet| {
344 let left = snippet.find('"')?;
346 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
350 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
351 .with_hi(lit.span.hi() - BytePos(right as u32)),
354 .unwrap_or(lit.span);
356 Some(Ident::new(name, sp))
364 if let Some(ident) = &crate_ident {
365 self.check_snake_case(cx, "crate", ident);
369 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
370 if let GenericParamKind::Lifetime { .. } = param.kind {
371 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
377 cx: &LateContext<'_>,
384 let attrs = cx.tcx.hir().attrs(id);
386 FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
387 MethodLateContext::PlainImpl => {
388 if sig.header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle)
392 self.check_snake_case(cx, "method", ident);
394 MethodLateContext::TraitAutoImpl => {
395 self.check_snake_case(cx, "trait method", ident);
399 FnKind::ItemFn(ident, _, header) => {
400 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
401 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
404 self.check_snake_case(cx, "function", ident);
406 FnKind::Closure => (),
410 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
411 if let hir::ItemKind::Mod(_) = it.kind {
412 self.check_snake_case(cx, "module", &it.ident);
416 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
417 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
418 self.check_snake_case(cx, "trait method", &item.ident);
419 for param_name in pnames {
420 self.check_snake_case(cx, "variable", param_name);
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.hir().get_parent(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);
435 self.check_snake_case(cx, "variable", &ident);
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);
447 /// The `non_upper_case_globals` lint detects static items that don't have
448 /// uppercase identifiers.
453 /// static max_points: i32 = 5;
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,
464 "static constants should have uppercase identifiers"
467 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
469 impl NonUpperCaseGlobals {
470 fn check_upper_case(cx: &LateContext<'_>, sort: &str, 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 // We cannot provide meaningful suggestions
475 // if the characters are in the category of "Lowercase Letter".
476 let sub = if *name != uc {
477 NonUpperCaseGlobalSub::Suggestion { span: ident.span, replace: uc }
479 NonUpperCaseGlobalSub::Label { span: ident.span }
481 cx.emit_spanned_lint(
482 NON_UPPER_CASE_GLOBALS,
484 NonUpperCaseGlobal { sort, name, sub },
490 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
491 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
492 let attrs = cx.tcx.hir().attrs(it.hir_id());
494 hir::ItemKind::Static(..) if !cx.sess().contains_name(attrs, sym::no_mangle) => {
495 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
497 hir::ItemKind::Const(..) => {
498 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
504 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
505 if let hir::TraitItemKind::Const(..) = ti.kind {
506 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
510 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
511 if let hir::ImplItemKind::Const(..) = ii.kind {
512 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
516 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
517 // Lint for constants that look like binding identifiers (#7526)
518 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
519 if let Res::Def(DefKind::Const, _) = path.res {
520 if path.segments.len() == 1 {
521 NonUpperCaseGlobals::check_upper_case(
523 "constant in pattern",
524 &path.segments[0].ident,
531 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
532 if let GenericParamKind::Const { .. } = param.kind {
533 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());