1 use rustc::hir::{self, GenericParamKind, PatKind};
2 use rustc::hir::def::{Res, DefKind};
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: hir::HirId) -> MethodLateContext {
22 let def_id = cx.tcx.hir().local_def_id_from_hir_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 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
43 fn char_has_case(c: char) -> bool {
44 c.is_lowercase() || c.is_uppercase()
47 fn is_camel_case(name: &str) -> bool {
48 let name = name.trim_matches('_');
53 // start with a non-lowercase letter rather than non-uppercase
54 // ones (some scripts don't have a concept of upper/lowercase)
55 !name.chars().next().unwrap().is_lowercase()
56 && !name.contains("__")
57 && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
58 // contains a capitalisable character followed by, or preceded by, an underscore
59 char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_'
63 fn to_camel_case(s: &str) -> String {
66 .filter(|component| !component.is_empty())
68 let mut camel_cased_component = String::new();
70 let mut new_word = true;
71 let mut prev_is_lower_case = true;
73 for c in component.chars() {
74 // Preserve the case if an uppercase letter follows a lowercase letter, so that
75 // `camelCase` is converted to `CamelCase`.
76 if prev_is_lower_case && c.is_uppercase() {
81 camel_cased_component.push_str(&c.to_uppercase().to_string());
83 camel_cased_component.push_str(&c.to_lowercase().to_string());
86 prev_is_lower_case = c.is_lowercase();
93 (String::new(), None),
94 |(acc, prev): (String, Option<String>), next| {
95 // separate two components with an underscore if their boundary cannot
96 // be distinguished using a uppercase/lowercase case distinction
97 let join = if let Some(prev) = prev {
98 let l = prev.chars().last().unwrap();
99 let f = next.chars().next().unwrap();
100 !char_has_case(l) && !char_has_case(f)
104 (acc + if join { "_" } else { "" } + &next, Some(next))
110 impl NonCamelCaseTypes {
111 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
112 let name = &ident.name.as_str();
114 if !is_camel_case(name) {
115 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
116 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
119 "convert the identifier to upper camel case",
121 Applicability::MaybeIncorrect,
128 impl EarlyLintPass for NonCamelCaseTypes {
129 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
130 let has_repr_c = it.attrs
132 .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
139 ast::ItemKind::Ty(..) |
140 ast::ItemKind::Enum(..) |
141 ast::ItemKind::Struct(..) |
142 ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
143 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
148 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
149 self.check_case(cx, "variant", &v.node.ident);
152 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
153 if let ast::GenericParamKind::Type { .. } = param.kind {
154 self.check_case(cx, "type parameter", ¶m.ident);
162 "variables, methods, functions, lifetime parameters and modules should have snake case names"
165 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
168 fn to_snake_case(mut str: &str) -> String {
169 let mut words = vec![];
170 // Preserve leading underscores
171 str = str.trim_start_matches(|c: char| {
173 words.push(String::new());
179 for s in str.split('_') {
180 let mut last_upper = false;
181 let mut buf = String::new();
185 for ch in s.chars() {
186 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
190 last_upper = ch.is_uppercase();
191 buf.extend(ch.to_lowercase());
198 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
199 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
200 fn is_snake_case(ident: &str) -> bool {
201 if ident.is_empty() {
204 let ident = ident.trim_start_matches('\'');
205 let ident = ident.trim_matches('_');
207 let mut allow_underscore = true;
208 ident.chars().all(|c| {
209 allow_underscore = match c {
210 '_' if !allow_underscore => return false,
212 // It would be more obvious to use `c.is_lowercase()`,
213 // but some characters do not have a lowercase form
214 c if !c.is_uppercase() => true,
221 let name = &ident.name.as_str();
223 if !is_snake_case(name) {
224 let sc = NonSnakeCase::to_snake_case(name);
226 let msg = format!("{} `{}` should have a snake case name", sort, name);
227 let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
229 // We have a valid span in almost all cases, but we don't have one when linting a crate
230 // name provided via the command line.
231 if !ident.span.is_dummy() {
234 "convert the identifier to snake case",
236 Applicability::MaybeIncorrect,
239 err.help(&format!("convert the identifier to snake case: `{}`", sc));
247 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
248 fn check_mod(&mut self, cx: &LateContext<'_, '_>, _: &'tcx hir::Mod, _: Span, id: hir::HirId) {
249 if id != hir::CRATE_HIR_ID {
253 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
254 Some(Ident::from_str(name))
256 attr::find_by_name(&cx.tcx.hir().attrs_by_hir_id(hir::CRATE_HIR_ID), "crate_name")
257 .and_then(|attr| attr.meta())
259 meta.name_value_literal().and_then(|lit| {
260 if let ast::LitKind::Str(name, ..) = lit.node {
261 // Discard the double quotes surrounding the literal.
262 let sp = cx.sess().source_map().span_to_snippet(lit.span)
264 .and_then(|snippet| {
265 let left = snippet.find('"')?;
266 let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
270 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
271 .with_hi(lit.span.hi() - BytePos(right as u32)),
274 .unwrap_or_else(|| lit.span);
276 Some(Ident::new(name, sp))
284 if let Some(ident) = &crate_ident {
285 self.check_snake_case(cx, "crate", ident);
289 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
290 if let GenericParamKind::Lifetime { .. } = param.kind {
291 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
297 cx: &LateContext<'_, '_>,
305 FnKind::Method(ident, ..) => {
306 match method_context(cx, id) {
307 MethodLateContext::PlainImpl => {
308 self.check_snake_case(cx, "method", ident);
310 MethodLateContext::TraitAutoImpl => {
311 self.check_snake_case(cx, "trait method", ident);
316 FnKind::ItemFn(ident, _, header, _, attrs) => {
317 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
318 if header.abi != Abi::Rust && attr::contains_name(attrs, "no_mangle") {
321 self.check_snake_case(cx, "function", ident);
323 FnKind::Closure(_) => (),
327 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
328 if let hir::ItemKind::Mod(_) = it.node {
329 self.check_snake_case(cx, "module", &it.ident);
333 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) {
334 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node {
335 self.check_snake_case(cx, "trait method", &item.ident);
336 for param_name in pnames {
337 self.check_snake_case(cx, "variable", param_name);
342 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
343 if let &PatKind::Binding(_, _, ident, _) = &p.node {
344 self.check_snake_case(cx, "variable", &ident);
350 cx: &LateContext<'_, '_>,
351 s: &hir::VariantData,
356 for sf in s.fields() {
357 self.check_snake_case(cx, "structure field", &sf.ident);
363 pub NON_UPPER_CASE_GLOBALS,
365 "static constants should have uppercase identifiers"
368 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
370 impl NonUpperCaseGlobals {
371 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
372 let name = &ident.name.as_str();
374 if name.chars().any(|c| c.is_lowercase()) {
375 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
377 let msg = format!("{} `{}` should have an upper case name", sort, name);
378 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
381 "convert the identifier to upper case",
383 Applicability::MaybeIncorrect,
390 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
391 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
393 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
394 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
396 hir::ItemKind::Const(..) => {
397 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
403 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
404 if let hir::TraitItemKind::Const(..) = ti.node {
405 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
409 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
410 if let hir::ImplItemKind::Const(..) = ii.node {
411 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
415 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
416 // Lint for constants that look like binding identifiers (#7526)
417 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
418 if let Res::Def(DefKind::Const, _) = path.res {
419 if path.segments.len() == 1 {
420 NonUpperCaseGlobals::check_upper_case(
422 "constant in pattern",
423 &path.segments[0].ident
430 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
431 if let GenericParamKind::Const { .. } = param.kind {
432 NonUpperCaseGlobals::check_upper_case(
443 use super::{is_camel_case, to_camel_case};
447 assert!(!is_camel_case("userData"));
448 assert_eq!(to_camel_case("userData"), "UserData");
450 assert!(is_camel_case("X86_64"));
452 assert!(!is_camel_case("X86__64"));
453 assert_eq!(to_camel_case("X86__64"), "X86_64");
455 assert!(!is_camel_case("Abc_123"));
456 assert_eq!(to_camel_case("Abc_123"), "Abc123");
458 assert!(!is_camel_case("A1_b2_c3"));
459 assert_eq!(to_camel_case("A1_b2_c3"), "A1B2C3");
461 assert!(!is_camel_case("ONE_TWO_THREE"));
462 assert_eq!(to_camel_case("ONE_TWO_THREE"), "OneTwoThree");