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 fn char_has_case(c: char) -> bool {
60 c.is_lowercase() || c.is_uppercase()
63 fn is_camel_case(name: &str) -> bool {
64 let name = name.trim_matches('_');
69 // start with a non-lowercase letter rather than non-uppercase
70 // ones (some scripts don't have a concept of upper/lowercase)
71 !name.chars().next().unwrap().is_lowercase()
72 && !name.contains("__")
73 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
74 // contains a capitalisable character followed by, or preceded by, an underscore
75 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
79 fn to_camel_case(s: &str) -> String {
82 .filter(|component| !component.is_empty())
84 let mut camel_cased_component = String::new();
86 let mut new_word = true;
87 let mut prev_is_lower_case = true;
89 for c in component.chars() {
90 // Preserve the case if an uppercase letter follows a lowercase letter, so that
91 // `camelCase` is converted to `CamelCase`.
92 if prev_is_lower_case && c.is_uppercase() {
97 camel_cased_component.push_str(&c.to_uppercase().to_string());
99 camel_cased_component.push_str(&c.to_lowercase().to_string());
102 prev_is_lower_case = c.is_lowercase();
106 camel_cased_component
108 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
109 // separate two components with an underscore if their boundary cannot
110 // be distinguished using a uppercase/lowercase case distinction
111 let join = if let Some(prev) = prev {
112 let l = prev.chars().last().unwrap();
113 let f = next.chars().next().unwrap();
114 !char_has_case(l) && !char_has_case(f)
118 (acc + if join { "_" } else { "" } + &next, Some(next))
123 impl NonCamelCaseTypes {
124 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
125 let name = &ident.name.as_str();
127 if !is_camel_case(name) {
128 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, |lint| {
129 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
130 let mut err = lint.build(&msg);
131 let cc = to_camel_case(name);
132 // We cannot provide meaningful suggestions
133 // if the characters are in the category of "Lowercase Letter".
134 if name.to_string() != cc {
137 "convert the identifier to upper camel case",
139 Applicability::MaybeIncorrect,
149 impl EarlyLintPass for NonCamelCaseTypes {
150 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
154 .any(|attr| attr::find_repr_attrs(&cx.sess, attr).contains(&attr::ReprC));
161 ast::ItemKind::TyAlias(..)
162 | ast::ItemKind::Enum(..)
163 | ast::ItemKind::Struct(..)
164 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
165 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
170 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
171 if let ast::AssocItemKind::TyAlias(..) = it.kind {
172 self.check_case(cx, "associated type", &it.ident);
176 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
177 self.check_case(cx, "variant", &v.ident);
180 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
181 if let ast::GenericParamKind::Type { .. } = param.kind {
182 self.check_case(cx, "type parameter", ¶m.ident);
188 /// The `non_snake_case` lint detects variables, methods, functions,
189 /// lifetime parameters and modules that don't have snake case names.
194 /// let MY_VALUE = 5;
201 /// The preferred style for these identifiers is to use "snake case",
202 /// where all the characters are in lowercase, with words separated with a
203 /// single underscore, such as `my_value`.
206 "variables, methods, functions, lifetime parameters and modules should have snake case names"
209 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
212 fn to_snake_case(mut str: &str) -> String {
213 let mut words = vec![];
214 // Preserve leading underscores
215 str = str.trim_start_matches(|c: char| {
217 words.push(String::new());
223 for s in str.split('_') {
224 let mut last_upper = false;
225 let mut buf = String::new();
229 for ch in s.chars() {
230 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
234 last_upper = ch.is_uppercase();
235 buf.extend(ch.to_lowercase());
242 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
243 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
244 fn is_snake_case(ident: &str) -> bool {
245 if ident.is_empty() {
248 let ident = ident.trim_start_matches('\'');
249 let ident = ident.trim_matches('_');
251 let mut allow_underscore = true;
252 ident.chars().all(|c| {
253 allow_underscore = match c {
254 '_' if !allow_underscore => return false,
256 // It would be more obvious to use `c.is_lowercase()`,
257 // but some characters do not have a lowercase form
258 c if !c.is_uppercase() => true,
265 let name = &ident.name.as_str();
267 if !is_snake_case(name) {
268 cx.struct_span_lint(NON_SNAKE_CASE, ident.span, |lint| {
269 let sc = NonSnakeCase::to_snake_case(name);
270 let msg = format!("{} `{}` should have a snake case name", sort, name);
271 let mut err = lint.build(&msg);
272 // We cannot provide meaningful suggestions
273 // if the characters are in the category of "Uppercase Letter".
274 if name.to_string() != sc {
275 // We have a valid span in almost all cases, but we don't have one when linting a crate
276 // name provided via the command line.
277 if !ident.span.is_dummy() {
280 "convert the identifier to snake case",
282 Applicability::MaybeIncorrect,
285 err.help(&format!("convert the identifier to snake case: `{}`", sc));
295 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
298 cx: &LateContext<'_>,
299 _: &'tcx hir::Mod<'tcx>,
303 if id != hir::CRATE_HIR_ID {
307 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
308 Some(Ident::from_str(name))
311 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
312 .and_then(|attr| attr.meta())
314 meta.name_value_literal().and_then(|lit| {
315 if let ast::LitKind::Str(name, ..) = lit.kind {
316 // Discard the double quotes surrounding the literal.
320 .span_to_snippet(lit.span)
322 .and_then(|snippet| {
323 let left = snippet.find('"')?;
325 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
329 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
330 .with_hi(lit.span.hi() - BytePos(right as u32)),
333 .unwrap_or(lit.span);
335 Some(Ident::new(name, sp))
343 if let Some(ident) = &crate_ident {
344 self.check_snake_case(cx, "crate", ident);
348 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
349 if let GenericParamKind::Lifetime { .. } = param.kind {
350 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
356 cx: &LateContext<'_>,
364 FnKind::Method(ident, ..) => match method_context(cx, id) {
365 MethodLateContext::PlainImpl => {
366 self.check_snake_case(cx, "method", ident);
368 MethodLateContext::TraitAutoImpl => {
369 self.check_snake_case(cx, "trait method", ident);
373 FnKind::ItemFn(ident, _, header, _, attrs) => {
374 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
375 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
378 self.check_snake_case(cx, "function", ident);
380 FnKind::Closure(_) => (),
384 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
385 if let hir::ItemKind::Mod(_) = it.kind {
386 self.check_snake_case(cx, "module", &it.ident);
390 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
391 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
392 self.check_snake_case(cx, "trait method", &item.ident);
393 for param_name in pnames {
394 self.check_snake_case(cx, "variable", param_name);
399 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
400 if let &PatKind::Binding(_, hid, ident, _) = &p.kind {
401 if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
403 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
404 for field in field_pats.iter() {
405 if field.ident != ident {
406 // Only check if a new name has been introduced, to avoid warning
407 // on both the struct definition and this pattern.
408 self.check_snake_case(cx, "variable", &ident);
414 self.check_snake_case(cx, "variable", &ident);
418 fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
419 for sf in s.fields() {
420 self.check_snake_case(cx, "structure field", &sf.ident);
426 /// The `non_upper_case_globals` lint detects static items that don't have
427 /// uppercase identifiers.
432 /// static max_points: i32 = 5;
439 /// The preferred style is for static item names to use all uppercase
440 /// letters such as `MAX_POINTS`.
441 pub NON_UPPER_CASE_GLOBALS,
443 "static constants should have uppercase identifiers"
446 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
448 impl NonUpperCaseGlobals {
449 fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
450 let name = &ident.name.as_str();
451 if name.chars().any(|c| c.is_lowercase()) {
452 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
453 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
455 lint.build(&format!("{} `{}` should have an upper case name", sort, name));
456 // We cannot provide meaningful suggestions
457 // if the characters are in the category of "Lowercase Letter".
458 if name.to_string() != uc {
461 "convert the identifier to upper case",
463 Applicability::MaybeIncorrect,
473 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
474 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
476 hir::ItemKind::Static(..) if !cx.sess().contains_name(&it.attrs, sym::no_mangle) => {
477 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
479 hir::ItemKind::Const(..) => {
480 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
486 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
487 if let hir::TraitItemKind::Const(..) = ti.kind {
488 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
492 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
493 if let hir::ImplItemKind::Const(..) = ii.kind {
494 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
498 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
499 // Lint for constants that look like binding identifiers (#7526)
500 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
501 if let Res::Def(DefKind::Const, _) = path.res {
502 if path.segments.len() == 1 {
503 NonUpperCaseGlobals::check_upper_case(
505 "constant in pattern",
506 &path.segments[0].ident,
513 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
514 if let GenericParamKind::Const { .. } = param.kind {
515 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());