1 use lint::{EarlyContext, LateContext, LintArray, LintContext};
2 use lint::{EarlyLintPass, LateLintPass, LintPass};
3 use rustc::hir::intravisit::FnKind;
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::{GenericParamKind, PatKind};
9 use rustc_span::symbol::sym;
10 use rustc_span::{symbol::Ident, BytePos, Span};
11 use rustc_target::spec::abi::Abi;
14 use syntax::errors::Applicability;
17 pub enum MethodLateContext {
23 pub fn method_context(cx: &LateContext<'_, '_>, id: hir::HirId) -> MethodLateContext {
24 let def_id = cx.tcx.hir().local_def_id(id);
25 let item = cx.tcx.associated_item(def_id);
26 match item.container {
27 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
28 ty::ImplContainer(cid) => match cx.tcx.impl_trait_ref(cid) {
29 Some(_) => MethodLateContext::TraitImpl,
30 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();
92 .fold((String::new(), None), |(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))
107 impl NonCamelCaseTypes {
108 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
109 let name = &ident.name.as_str();
111 if !is_camel_case(name) {
112 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
113 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
116 "convert the identifier to upper camel case",
118 Applicability::MaybeIncorrect,
125 impl EarlyLintPass for NonCamelCaseTypes {
126 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
130 .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
137 ast::ItemKind::TyAlias(..)
138 | ast::ItemKind::Enum(..)
139 | ast::ItemKind::Struct(..)
140 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
141 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
146 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
147 self.check_case(cx, "variant", &v.ident);
150 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
151 if let ast::GenericParamKind::Type { .. } = param.kind {
152 self.check_case(cx, "type parameter", ¶m.ident);
160 "variables, methods, functions, lifetime parameters and modules should have snake case names"
163 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
166 fn to_snake_case(mut str: &str) -> String {
167 let mut words = vec![];
168 // Preserve leading underscores
169 str = str.trim_start_matches(|c: char| {
171 words.push(String::new());
177 for s in str.split('_') {
178 let mut last_upper = false;
179 let mut buf = String::new();
183 for ch in s.chars() {
184 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
188 last_upper = ch.is_uppercase();
189 buf.extend(ch.to_lowercase());
196 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
197 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
198 fn is_snake_case(ident: &str) -> bool {
199 if ident.is_empty() {
202 let ident = ident.trim_start_matches('\'');
203 let ident = ident.trim_matches('_');
205 let mut allow_underscore = true;
206 ident.chars().all(|c| {
207 allow_underscore = match c {
208 '_' if !allow_underscore => return false,
210 // It would be more obvious to use `c.is_lowercase()`,
211 // but some characters do not have a lowercase form
212 c if !c.is_uppercase() => true,
219 let name = &ident.name.as_str();
221 if !is_snake_case(name) {
222 let sc = NonSnakeCase::to_snake_case(name);
224 let msg = format!("{} `{}` should have a snake case name", sort, name);
225 let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
227 // We have a valid span in almost all cases, but we don't have one when linting a crate
228 // name provided via the command line.
229 if !ident.span.is_dummy() {
232 "convert the identifier to snake case",
234 Applicability::MaybeIncorrect,
237 err.help(&format!("convert the identifier to snake case: `{}`", sc));
245 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
248 cx: &LateContext<'_, '_>,
249 _: &'tcx hir::Mod<'tcx>,
253 if id != hir::CRATE_HIR_ID {
257 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
258 Some(Ident::from_str(name))
260 attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
261 .and_then(|attr| attr.meta())
263 meta.name_value_literal().and_then(|lit| {
264 if let ast::LitKind::Str(name, ..) = lit.kind {
265 // Discard the double quotes surrounding the literal.
269 .span_to_snippet(lit.span)
271 .and_then(|snippet| {
272 let left = snippet.find('"')?;
274 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
278 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
279 .with_hi(lit.span.hi() - BytePos(right as u32)),
282 .unwrap_or_else(|| lit.span);
284 Some(Ident::new(name, sp))
292 if let Some(ident) = &crate_ident {
293 self.check_snake_case(cx, "crate", ident);
297 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
298 if let GenericParamKind::Lifetime { .. } = param.kind {
299 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
305 cx: &LateContext<'_, '_>,
313 FnKind::Method(ident, ..) => match method_context(cx, id) {
314 MethodLateContext::PlainImpl => {
315 self.check_snake_case(cx, "method", ident);
317 MethodLateContext::TraitAutoImpl => {
318 self.check_snake_case(cx, "trait method", ident);
322 FnKind::ItemFn(ident, _, header, _, attrs) => {
323 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
324 if header.abi != Abi::Rust && attr::contains_name(attrs, sym::no_mangle) {
327 self.check_snake_case(cx, "function", ident);
329 FnKind::Closure(_) => (),
333 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
334 if let hir::ItemKind::Mod(_) = it.kind {
335 self.check_snake_case(cx, "module", &it.ident);
339 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) {
340 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = item.kind {
341 self.check_snake_case(cx, "trait method", &item.ident);
342 for param_name in pnames {
343 self.check_snake_case(cx, "variable", param_name);
348 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
349 if let &PatKind::Binding(_, _, ident, _) = &p.kind {
350 self.check_snake_case(cx, "variable", &ident);
354 fn check_struct_def(&mut self, cx: &LateContext<'_, '_>, s: &hir::VariantData<'_>) {
355 for sf in s.fields() {
356 self.check_snake_case(cx, "structure field", &sf.ident);
362 pub NON_UPPER_CASE_GLOBALS,
364 "static constants should have uppercase identifiers"
367 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
369 impl NonUpperCaseGlobals {
370 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
371 let name = &ident.name.as_str();
373 if name.chars().any(|c| c.is_lowercase()) {
374 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
376 let msg = format!("{} `{}` should have an upper case name", sort, name);
377 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
380 "convert the identifier to upper case",
382 Applicability::MaybeIncorrect,
389 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
390 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
392 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, sym::no_mangle) => {
393 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
395 hir::ItemKind::Const(..) => {
396 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
402 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem<'_>) {
403 if let hir::TraitItemKind::Const(..) = ti.kind {
404 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
408 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem<'_>) {
409 if let hir::ImplItemKind::Const(..) = ii.kind {
410 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
414 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
415 // Lint for constants that look like binding identifiers (#7526)
416 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
417 if let Res::Def(DefKind::Const, _) = path.res {
418 if path.segments.len() == 1 {
419 NonUpperCaseGlobals::check_upper_case(
421 "constant in pattern",
422 &path.segments[0].ident,
429 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
430 if let GenericParamKind::Const { .. } = param.kind {
431 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());