1 use rustc::hir::{self, GenericParamKind, PatKind};
2 use rustc::hir::def::Def;
3 use rustc::hir::intravisit::FnKind;
6 use rustc_target::spec::abi::Abi;
7 use lint::{EarlyContext, LateContext, LintContext, LintArray};
8 use lint::{EarlyLintPass, LintPass, LateLintPass};
11 use syntax::errors::Applicability;
12 use syntax_pos::{BytePos, symbol::Ident, Span};
15 pub enum MethodLateContext {
21 pub fn method_context(cx: &LateContext<'_, '_>, id: ast::NodeId) -> 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) => {
27 match cx.tcx.impl_trait_ref(cid) {
28 Some(_) => MethodLateContext::TraitImpl,
29 None => MethodLateContext::PlainImpl,
36 pub NON_CAMEL_CASE_TYPES,
38 "types, variants, traits and type parameters should have camel case names"
41 fn char_has_case(c: char) -> bool {
42 c.is_lowercase() || c.is_uppercase()
45 fn is_camel_case(name: &str) -> bool {
46 let name = name.trim_matches('_');
51 // start with a non-lowercase letter rather than non-uppercase
52 // ones (some scripts don't have a concept of upper/lowercase)
53 !name.chars().next().unwrap().is_lowercase()
54 && !name.contains("__")
55 && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
56 // contains a capitalisable character followed by, or preceded by, an underscore
57 char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_'
61 fn to_camel_case(s: &str) -> String {
64 .filter(|component| !component.is_empty())
66 let mut camel_cased_component = String::new();
68 let mut new_word = true;
69 let mut prev_is_lower_case = true;
71 for c in component.chars() {
72 // Preserve the case if an uppercase letter follows a lowercase letter, so that
73 // `camelCase` is converted to `CamelCase`.
74 if prev_is_lower_case && c.is_uppercase() {
79 camel_cased_component.push_str(&c.to_uppercase().to_string());
81 camel_cased_component.push_str(&c.to_lowercase().to_string());
84 prev_is_lower_case = c.is_lowercase();
91 (String::new(), None),
92 |(acc, prev): (String, Option<String>), next| {
93 // separate two components with an underscore if their boundary cannot
94 // be distinguished using a uppercase/lowercase case distinction
95 let join = if let Some(prev) = prev {
96 let l = prev.chars().last().unwrap();
97 let f = next.chars().next().unwrap();
98 !char_has_case(l) && !char_has_case(f)
102 (acc + if join { "_" } else { "" } + &next, Some(next))
108 #[derive(Copy, Clone)]
109 pub struct NonCamelCaseTypes;
111 impl NonCamelCaseTypes {
112 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
113 let name = &ident.name.as_str();
115 if !is_camel_case(name) {
116 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
117 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
120 "convert the identifier to upper camel case",
122 Applicability::MaybeIncorrect,
129 impl LintPass for NonCamelCaseTypes {
130 fn name(&self) -> &'static str {
134 fn get_lints(&self) -> LintArray {
135 lint_array!(NON_CAMEL_CASE_TYPES)
139 impl EarlyLintPass for NonCamelCaseTypes {
140 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
141 let has_repr_c = it.attrs
143 .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
150 ast::ItemKind::Ty(..) |
151 ast::ItemKind::Enum(..) |
152 ast::ItemKind::Struct(..) |
153 ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
154 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
159 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
160 self.check_case(cx, "variant", &v.node.ident);
163 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
164 if let ast::GenericParamKind::Type { .. } = param.kind {
165 self.check_case(cx, "type parameter", ¶m.ident);
173 "variables, methods, functions, lifetime parameters and modules should have snake case names"
176 #[derive(Copy, Clone)]
177 pub struct NonSnakeCase;
180 fn to_snake_case(mut str: &str) -> String {
181 let mut words = vec![];
182 // Preserve leading underscores
183 str = str.trim_start_matches(|c: char| {
185 words.push(String::new());
191 for s in str.split('_') {
192 let mut last_upper = false;
193 let mut buf = String::new();
197 for ch in s.chars() {
198 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
202 last_upper = ch.is_uppercase();
203 buf.extend(ch.to_lowercase());
210 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
211 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
212 fn is_snake_case(ident: &str) -> bool {
213 if ident.is_empty() {
216 let ident = ident.trim_start_matches('\'');
217 let ident = ident.trim_matches('_');
219 let mut allow_underscore = true;
220 ident.chars().all(|c| {
221 allow_underscore = match c {
222 '_' if !allow_underscore => return false,
224 // It would be more obvious to use `c.is_lowercase()`,
225 // but some characters do not have a lowercase form
226 c if !c.is_uppercase() => true,
233 let name = &ident.name.as_str();
235 if !is_snake_case(name) {
236 let sc = NonSnakeCase::to_snake_case(name);
238 let msg = format!("{} `{}` should have a snake case name", sort, name);
239 let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
241 // We have a valid span in almost all cases, but we don't have one when linting a crate
242 // name provided via the command line.
243 if !ident.span.is_dummy() {
246 "convert the identifier to snake case",
248 Applicability::MaybeIncorrect,
251 err.help(&format!("convert the identifier to snake case: `{}`", sc));
259 impl LintPass for NonSnakeCase {
260 fn name(&self) -> &'static str {
264 fn get_lints(&self) -> LintArray {
265 lint_array!(NON_SNAKE_CASE)
269 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
270 fn check_crate(&mut self, cx: &LateContext<'_, '_>, cr: &hir::Crate) {
271 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
272 Some(Ident::from_str(name))
274 attr::find_by_name(&cr.attrs, "crate_name")
275 .and_then(|attr| attr.meta())
277 meta.name_value_literal().and_then(|lit| {
278 if let ast::LitKind::Str(name, ..) = lit.node {
279 // Discard the double quotes surrounding the literal.
280 let sp = cx.sess().source_map().span_to_snippet(lit.span)
282 .and_then(|snippet| {
283 let left = snippet.find('"')?;
284 let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
288 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
289 .with_hi(lit.span.hi() - BytePos(right as u32)),
292 .unwrap_or_else(|| lit.span);
294 Some(Ident::new(name, sp))
302 if let Some(ident) = &crate_ident {
303 self.check_snake_case(cx, "crate", ident);
307 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
308 if let GenericParamKind::Lifetime { .. } = param.kind {
309 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
315 cx: &LateContext<'_, '_>,
323 FnKind::Method(ident, ..) => {
324 match method_context(cx, id) {
325 MethodLateContext::PlainImpl => {
326 self.check_snake_case(cx, "method", ident);
328 MethodLateContext::TraitAutoImpl => {
329 self.check_snake_case(cx, "trait method", ident);
334 FnKind::ItemFn(ident, _, header, _, attrs) => {
335 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
336 if header.abi != Abi::Rust && attr::contains_name(attrs, "no_mangle") {
339 self.check_snake_case(cx, "function", ident);
341 FnKind::Closure(_) => (),
345 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
346 if let hir::ItemKind::Mod(_) = it.node {
347 self.check_snake_case(cx, "module", &it.ident);
351 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) {
352 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node {
353 self.check_snake_case(cx, "trait method", &item.ident);
354 for param_name in pnames {
355 self.check_snake_case(cx, "variable", param_name);
360 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
361 if let &PatKind::Binding(_, _, _, ident, _) = &p.node {
362 self.check_snake_case(cx, "variable", &ident);
368 cx: &LateContext<'_, '_>,
369 s: &hir::VariantData,
374 for sf in s.fields() {
375 self.check_snake_case(cx, "structure field", &sf.ident);
381 pub NON_UPPER_CASE_GLOBALS,
383 "static constants should have uppercase identifiers"
386 #[derive(Copy, Clone)]
387 pub struct NonUpperCaseGlobals;
389 impl NonUpperCaseGlobals {
390 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
391 let name = &ident.name.as_str();
393 if name.chars().any(|c| c.is_lowercase()) {
394 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
396 let msg = format!("{} `{}` should have an upper case name", sort, name);
397 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
400 "convert the identifier to upper case",
402 Applicability::MaybeIncorrect,
409 impl LintPass for NonUpperCaseGlobals {
410 fn name(&self) -> &'static str {
411 "NonUpperCaseGlobals"
414 fn get_lints(&self) -> LintArray {
415 lint_array!(NON_UPPER_CASE_GLOBALS)
419 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
420 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
422 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
423 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
425 hir::ItemKind::Const(..) => {
426 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
432 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
433 if let hir::TraitItemKind::Const(..) = ti.node {
434 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
438 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
439 if let hir::ImplItemKind::Const(..) = ii.node {
440 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
444 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
445 // Lint for constants that look like binding identifiers (#7526)
446 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
447 if let Def::Const(..) = path.def {
448 if path.segments.len() == 1 {
449 NonUpperCaseGlobals::check_upper_case(
451 "constant in pattern",
452 &path.segments[0].ident
459 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
460 if let GenericParamKind::Const { .. } = param.kind {
461 NonUpperCaseGlobals::check_upper_case(
472 use super::{is_camel_case, to_camel_case};
476 assert!(!is_camel_case("userData"));
477 assert_eq!(to_camel_case("userData"), "UserData");
479 assert!(is_camel_case("X86_64"));
481 assert!(!is_camel_case("X86__64"));
482 assert_eq!(to_camel_case("X86__64"), "X86_64");
484 assert!(!is_camel_case("Abc_123"));
485 assert_eq!(to_camel_case("Abc_123"), "Abc123");
487 assert!(!is_camel_case("A1_b2_c3"));
488 assert_eq!(to_camel_case("A1_b2_c3"), "A1B2C3");
490 assert!(!is_camel_case("ONE_TWO_THREE"));
491 assert_eq!(to_camel_case("ONE_TWO_THREE"), "OneTwoThree");