1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc_attr as attr;
4 use rustc_errors::Applicability;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::intravisit::FnKind;
8 use rustc_hir::{GenericParamKind, PatKind};
10 use rustc_span::symbol::sym;
11 use rustc_span::{symbol::Ident, BytePos, Span};
12 use rustc_target::spec::abi::Abi;
15 pub enum MethodLateContext {
21 pub fn method_context(cx: &LateContext<'_>, id: hir::HirId) -> MethodLateContext {
22 let def_id = cx.tcx.hir().local_def_id(id);
23 let item = cx.tcx.associated_item(def_id);
24 match item.container {
25 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
26 ty::ImplContainer(cid) => match cx.tcx.impl_trait_ref(cid) {
27 Some(_) => MethodLateContext::TraitImpl,
28 None => MethodLateContext::PlainImpl,
34 /// The `non_camel_case_types` lint detects types, variants, traits and
35 /// type parameters that don't have camel case names.
47 /// The preferred style for these identifiers is to use "camel case", such
48 /// as `MyStruct`, where the first letter should not be lowercase, and
49 /// should not use underscores between letters. Underscores are allowed at
50 /// the beginning and end of the identifier, as well as between
51 /// non-letters (such as `X86_64`).
52 pub NON_CAMEL_CASE_TYPES,
54 "types, variants, traits and type parameters should have camel case names"
57 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
59 /// Some unicode characters *have* case, are considered upper case or lower case, but they *can't*
60 /// be upper cased or lower cased. For the purposes of the lint suggestion, we care about being able
61 /// to change the char's case.
62 fn char_has_case(c: char) -> bool {
63 let mut l = c.to_lowercase();
64 let mut u = c.to_uppercase();
65 while let Some(l) = l.next() {
67 Some(u) if l != u => return true,
74 fn is_camel_case(name: &str) -> bool {
75 let name = name.trim_matches('_');
80 // start with a non-lowercase letter rather than non-uppercase
81 // ones (some scripts don't have a concept of upper/lowercase)
82 !name.chars().next().unwrap().is_lowercase()
83 && !name.contains("__")
84 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
85 // contains a capitalisable character followed by, or preceded by, an underscore
86 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
90 fn to_camel_case(s: &str) -> String {
93 .filter(|component| !component.is_empty())
95 let mut camel_cased_component = String::new();
97 let mut new_word = true;
98 let mut prev_is_lower_case = true;
100 for c in component.chars() {
101 // Preserve the case if an uppercase letter follows a lowercase letter, so that
102 // `camelCase` is converted to `CamelCase`.
103 if prev_is_lower_case && c.is_uppercase() {
108 camel_cased_component.extend(c.to_uppercase());
110 camel_cased_component.extend(c.to_lowercase());
113 prev_is_lower_case = c.is_lowercase();
117 camel_cased_component
119 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
120 // separate two components with an underscore if their boundary cannot
121 // be distinguished using a uppercase/lowercase case distinction
122 let join = if let Some(prev) = prev {
123 let l = prev.chars().last().unwrap();
124 let f = next.chars().next().unwrap();
125 !char_has_case(l) && !char_has_case(f)
129 (acc + if join { "_" } else { "" } + &next, Some(next))
134 impl NonCamelCaseTypes {
135 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
136 let name = &ident.name.as_str();
138 if !is_camel_case(name) {
139 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, |lint| {
140 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
141 let mut err = lint.build(&msg);
142 let cc = to_camel_case(name);
143 // We cannot provide meaningful suggestions
144 // if the characters are in the category of "Lowercase Letter".
148 "convert the identifier to upper camel case",
150 Applicability::MaybeIncorrect,
153 err.span_label(ident.span, "should have an UpperCamelCase name");
162 impl EarlyLintPass for NonCamelCaseTypes {
163 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
167 .any(|attr| attr::find_repr_attrs(&cx.sess, attr).contains(&attr::ReprC));
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),
184 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
185 if let ast::AssocItemKind::TyAlias(..) = it.kind {
186 self.check_case(cx, "associated type", &it.ident);
190 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
191 self.check_case(cx, "variant", &v.ident);
194 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
195 if let ast::GenericParamKind::Type { .. } = param.kind {
196 self.check_case(cx, "type parameter", ¶m.ident);
202 /// The `non_snake_case` lint detects variables, methods, functions,
203 /// lifetime parameters and modules that don't have snake case names.
208 /// let MY_VALUE = 5;
215 /// The preferred style for these identifiers is to use "snake case",
216 /// where all the characters are in lowercase, with words separated with a
217 /// single underscore, such as `my_value`.
220 "variables, methods, functions, lifetime parameters and modules should have snake case names"
223 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
226 fn to_snake_case(mut str: &str) -> String {
227 let mut words = vec![];
228 // Preserve leading underscores
229 str = str.trim_start_matches(|c: char| {
231 words.push(String::new());
237 for s in str.split('_') {
238 let mut last_upper = false;
239 let mut buf = String::new();
243 for ch in s.chars() {
244 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
248 last_upper = ch.is_uppercase();
249 buf.extend(ch.to_lowercase());
256 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
257 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
258 fn is_snake_case(ident: &str) -> bool {
259 if ident.is_empty() {
262 let ident = ident.trim_start_matches('\'');
263 let ident = ident.trim_matches('_');
265 let mut allow_underscore = true;
266 ident.chars().all(|c| {
267 allow_underscore = match c {
268 '_' if !allow_underscore => return false,
270 // It would be more obvious to use `c.is_lowercase()`,
271 // but some characters do not have a lowercase form
272 c if !c.is_uppercase() => true,
279 let name = &ident.name.as_str();
281 if !is_snake_case(name) {
282 cx.struct_span_lint(NON_SNAKE_CASE, ident.span, |lint| {
283 let sc = NonSnakeCase::to_snake_case(name);
284 let msg = format!("{} `{}` should have a snake case name", sort, name);
285 let mut err = lint.build(&msg);
286 // We cannot provide meaningful suggestions
287 // if the characters are in the category of "Uppercase Letter".
289 // We have a valid span in almost all cases, but we don't have one when linting a crate
290 // name provided via the command line.
291 if !ident.span.is_dummy() {
292 let sc_ident = Ident::from_str_and_span(&sc, ident.span);
293 let (message, suggestion) = if sc_ident.is_reserved() {
294 // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
295 // Instead, recommend renaming the identifier entirely or, if permitted,
296 // escaping it to create a raw identifier.
297 if sc_ident.name.can_be_raw() {
298 ("rename the identifier or convert it to a snake case raw identifier", sc_ident.to_string())
300 err.note(&format!("`{}` cannot be used as a raw identifier", sc));
301 ("rename the identifier", String::new())
304 ("convert the identifier to snake case", sc)
311 Applicability::MaybeIncorrect,
314 err.help(&format!("convert the identifier to snake case: `{}`", sc));
317 err.span_label(ident.span, "should have a snake_case name");
326 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
329 cx: &LateContext<'_>,
330 _: &'tcx hir::Mod<'tcx>,
334 if id != hir::CRATE_HIR_ID {
338 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
339 Some(Ident::from_str(name))
342 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
343 .and_then(|attr| attr.meta())
345 meta.name_value_literal().and_then(|lit| {
346 if let ast::LitKind::Str(name, ..) = lit.kind {
347 // Discard the double quotes surrounding the literal.
351 .span_to_snippet(lit.span)
353 .and_then(|snippet| {
354 let left = snippet.find('"')?;
356 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
360 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
361 .with_hi(lit.span.hi() - BytePos(right as u32)),
364 .unwrap_or(lit.span);
366 Some(Ident::new(name, sp))
374 if let Some(ident) = &crate_ident {
375 self.check_snake_case(cx, "crate", ident);
379 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
380 if let GenericParamKind::Lifetime { .. } = param.kind {
381 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
387 cx: &LateContext<'_>,
394 let attrs = cx.tcx.hir().attrs(id);
396 FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
397 MethodLateContext::PlainImpl => {
398 if sig.header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle)
402 self.check_snake_case(cx, "method", ident);
404 MethodLateContext::TraitAutoImpl => {
405 self.check_snake_case(cx, "trait method", ident);
409 FnKind::ItemFn(ident, _, header, _) => {
410 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
411 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
414 self.check_snake_case(cx, "function", ident);
416 FnKind::Closure => (),
420 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
421 if let hir::ItemKind::Mod(_) = it.kind {
422 self.check_snake_case(cx, "module", &it.ident);
426 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
427 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
428 self.check_snake_case(cx, "trait method", &item.ident);
429 for param_name in pnames {
430 self.check_snake_case(cx, "variable", param_name);
435 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
436 if let PatKind::Binding(_, hid, ident, _) = p.kind {
437 if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
439 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
440 for field in field_pats.iter() {
441 if field.ident != ident {
442 // Only check if a new name has been introduced, to avoid warning
443 // on both the struct definition and this pattern.
444 self.check_snake_case(cx, "variable", &ident);
450 self.check_snake_case(cx, "variable", &ident);
454 fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
455 for sf in s.fields() {
456 self.check_snake_case(cx, "structure field", &sf.ident);
462 /// The `non_upper_case_globals` lint detects static items that don't have
463 /// uppercase identifiers.
468 /// static max_points: i32 = 5;
475 /// The preferred style is for static item names to use all uppercase
476 /// letters such as `MAX_POINTS`.
477 pub NON_UPPER_CASE_GLOBALS,
479 "static constants should have uppercase identifiers"
482 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
484 impl NonUpperCaseGlobals {
485 fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
486 let name = &ident.name.as_str();
487 if name.chars().any(|c| c.is_lowercase()) {
488 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
489 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
491 lint.build(&format!("{} `{}` should have an upper case name", sort, name));
492 // We cannot provide meaningful suggestions
493 // if the characters are in the category of "Lowercase Letter".
497 "convert the identifier to upper case",
499 Applicability::MaybeIncorrect,
502 err.span_label(ident.span, "should have an UPPER_CASE name");
511 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
512 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
513 let attrs = cx.tcx.hir().attrs(it.hir_id());
515 hir::ItemKind::Static(..) if !cx.sess().contains_name(attrs, sym::no_mangle) => {
516 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
518 hir::ItemKind::Const(..) => {
519 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
525 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
526 if let hir::TraitItemKind::Const(..) = ti.kind {
527 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
531 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
532 if let hir::ImplItemKind::Const(..) = ii.kind {
533 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
537 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
538 // Lint for constants that look like binding identifiers (#7526)
539 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
540 if let Res::Def(DefKind::Const, _) = path.res {
541 if path.segments.len() == 1 {
542 NonUpperCaseGlobals::check_upper_case(
544 "constant in pattern",
545 &path.segments[0].ident,
552 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
553 if let GenericParamKind::Const { .. } = param.kind {
554 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());