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),
183 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
184 if let ast::AssocItemKind::TyAlias(..) = it.kind {
185 self.check_case(cx, "associated type", &it.ident);
189 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
190 self.check_case(cx, "variant", &v.ident);
193 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
194 if let ast::GenericParamKind::Type { .. } = param.kind {
195 self.check_case(cx, "type parameter", ¶m.ident);
201 /// The `non_snake_case` lint detects variables, methods, functions,
202 /// lifetime parameters and modules that don't have snake case names.
207 /// let MY_VALUE = 5;
214 /// The preferred style for these identifiers is to use "snake case",
215 /// where all the characters are in lowercase, with words separated with a
216 /// single underscore, such as `my_value`.
219 "variables, methods, functions, lifetime parameters and modules should have snake case names"
222 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
225 fn to_snake_case(mut str: &str) -> String {
226 let mut words = vec![];
227 // Preserve leading underscores
228 str = str.trim_start_matches(|c: char| {
230 words.push(String::new());
236 for s in str.split('_') {
237 let mut last_upper = false;
238 let mut buf = String::new();
242 for ch in s.chars() {
243 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
247 last_upper = ch.is_uppercase();
248 buf.extend(ch.to_lowercase());
255 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
256 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
257 fn is_snake_case(ident: &str) -> bool {
258 if ident.is_empty() {
261 let ident = ident.trim_start_matches('\'');
262 let ident = ident.trim_matches('_');
264 let mut allow_underscore = true;
265 ident.chars().all(|c| {
266 allow_underscore = match c {
267 '_' if !allow_underscore => return false,
269 // It would be more obvious to use `c.is_lowercase()`,
270 // but some characters do not have a lowercase form
271 c if !c.is_uppercase() => true,
278 let name = &ident.name.as_str();
280 if !is_snake_case(name) {
281 cx.struct_span_lint(NON_SNAKE_CASE, ident.span, |lint| {
282 let sc = NonSnakeCase::to_snake_case(name);
283 let msg = format!("{} `{}` should have a snake case name", sort, name);
284 let mut err = lint.build(&msg);
285 // We cannot provide meaningful suggestions
286 // if the characters are in the category of "Uppercase Letter".
288 // We have a valid span in almost all cases, but we don't have one when linting a crate
289 // name provided via the command line.
290 if !ident.span.is_dummy() {
291 let sc_ident = Ident::from_str_and_span(&sc, ident.span);
292 let (message, suggestion) = if sc_ident.is_reserved() {
293 // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
294 // Instead, recommend renaming the identifier entirely or, if permitted,
295 // escaping it to create a raw identifier.
296 if sc_ident.name.can_be_raw() {
297 ("rename the identifier or convert it to a snake case raw identifier", sc_ident.to_string())
299 err.note(&format!("`{}` cannot be used as a raw identifier", sc));
300 ("rename the identifier", String::new())
303 ("convert the identifier to snake case", sc)
310 Applicability::MaybeIncorrect,
313 err.help(&format!("convert the identifier to snake case: `{}`", sc));
316 err.span_label(ident.span, "should have a snake_case name");
325 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
328 cx: &LateContext<'_>,
329 _: &'tcx hir::Mod<'tcx>,
333 if id != hir::CRATE_HIR_ID {
337 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
338 Some(Ident::from_str(name))
341 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
342 .and_then(|attr| attr.meta())
344 meta.name_value_literal().and_then(|lit| {
345 if let ast::LitKind::Str(name, ..) = lit.kind {
346 // Discard the double quotes surrounding the literal.
350 .span_to_snippet(lit.span)
352 .and_then(|snippet| {
353 let left = snippet.find('"')?;
355 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
359 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
360 .with_hi(lit.span.hi() - BytePos(right as u32)),
363 .unwrap_or(lit.span);
365 Some(Ident::new(name, sp))
373 if let Some(ident) = &crate_ident {
374 self.check_snake_case(cx, "crate", ident);
378 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
379 if let GenericParamKind::Lifetime { .. } = param.kind {
380 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
386 cx: &LateContext<'_>,
394 FnKind::Method(ident, ..) => match method_context(cx, id) {
395 MethodLateContext::PlainImpl => {
396 self.check_snake_case(cx, "method", ident);
398 MethodLateContext::TraitAutoImpl => {
399 self.check_snake_case(cx, "trait method", ident);
403 FnKind::ItemFn(ident, _, header, _, attrs) => {
404 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
405 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
408 self.check_snake_case(cx, "function", ident);
410 FnKind::Closure(_) => (),
414 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
415 if let hir::ItemKind::Mod(_) = it.kind {
416 self.check_snake_case(cx, "module", &it.ident);
420 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
421 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
422 self.check_snake_case(cx, "trait method", &item.ident);
423 for param_name in pnames {
424 self.check_snake_case(cx, "variable", param_name);
429 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
430 if let PatKind::Binding(_, hid, ident, _) = p.kind {
431 if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
433 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
434 for field in field_pats.iter() {
435 if field.ident != ident {
436 // Only check if a new name has been introduced, to avoid warning
437 // on both the struct definition and this pattern.
438 self.check_snake_case(cx, "variable", &ident);
444 self.check_snake_case(cx, "variable", &ident);
448 fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
449 for sf in s.fields() {
450 self.check_snake_case(cx, "structure field", &sf.ident);
456 /// The `non_upper_case_globals` lint detects static items that don't have
457 /// uppercase identifiers.
462 /// static max_points: i32 = 5;
469 /// The preferred style is for static item names to use all uppercase
470 /// letters such as `MAX_POINTS`.
471 pub NON_UPPER_CASE_GLOBALS,
473 "static constants should have uppercase identifiers"
476 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
478 impl NonUpperCaseGlobals {
479 fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
480 let name = &ident.name.as_str();
481 if name.chars().any(|c| c.is_lowercase()) {
482 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
483 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
485 lint.build(&format!("{} `{}` should have an upper case name", sort, name));
486 // We cannot provide meaningful suggestions
487 // if the characters are in the category of "Lowercase Letter".
491 "convert the identifier to upper case",
493 Applicability::MaybeIncorrect,
496 err.span_label(ident.span, "should have an UPPER_CASE name");
505 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
506 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
508 hir::ItemKind::Static(..) if !cx.sess().contains_name(&it.attrs, sym::no_mangle) => {
509 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
511 hir::ItemKind::Const(..) => {
512 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
518 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
519 if let hir::TraitItemKind::Const(..) = ti.kind {
520 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
524 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
525 if let hir::ImplItemKind::Const(..) = ii.kind {
526 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
530 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
531 // Lint for constants that look like binding identifiers (#7526)
532 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
533 if let Res::Def(DefKind::Const, _) = path.res {
534 if path.segments.len() == 1 {
535 NonUpperCaseGlobals::check_upper_case(
537 "constant in pattern",
538 &path.segments[0].ident,
545 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
546 if let GenericParamKind::Const { .. } = param.kind {
547 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());