1 use lint::{EarlyContext, LateContext, LintArray, LintContext};
2 use lint::{EarlyLintPass, LateLintPass, LintPass};
3 use rustc::hir::def::{DefKind, Res};
4 use rustc::hir::intravisit::FnKind;
5 use rustc::hir::{self, GenericParamKind, PatKind};
8 use rustc_span::{symbol::Ident, BytePos, Span};
9 use rustc_target::spec::abi::Abi;
12 use syntax::errors::Applicability;
13 use syntax::symbol::sym;
16 pub enum MethodLateContext {
22 pub fn method_context(cx: &LateContext<'_, '_>, id: hir::HirId) -> MethodLateContext {
23 let def_id = cx.tcx.hir().local_def_id(id);
24 let item = cx.tcx.associated_item(def_id);
25 match item.container {
26 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
27 ty::ImplContainer(cid) => match cx.tcx.impl_trait_ref(cid) {
28 Some(_) => MethodLateContext::TraitImpl,
29 None => MethodLateContext::PlainImpl,
35 pub NON_CAMEL_CASE_TYPES,
37 "types, variants, traits and type parameters should have camel case names"
40 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
42 fn char_has_case(c: char) -> bool {
43 c.is_lowercase() || c.is_uppercase()
46 fn is_camel_case(name: &str) -> bool {
47 let name = name.trim_matches('_');
52 // start with a non-lowercase letter rather than non-uppercase
53 // ones (some scripts don't have a concept of upper/lowercase)
54 !name.chars().next().unwrap().is_lowercase()
55 && !name.contains("__")
56 && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
57 // contains a capitalisable character followed by, or preceded by, an underscore
58 char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_'
62 fn to_camel_case(s: &str) -> String {
65 .filter(|component| !component.is_empty())
67 let mut camel_cased_component = String::new();
69 let mut new_word = true;
70 let mut prev_is_lower_case = true;
72 for c in component.chars() {
73 // Preserve the case if an uppercase letter follows a lowercase letter, so that
74 // `camelCase` is converted to `CamelCase`.
75 if prev_is_lower_case && c.is_uppercase() {
80 camel_cased_component.push_str(&c.to_uppercase().to_string());
82 camel_cased_component.push_str(&c.to_lowercase().to_string());
85 prev_is_lower_case = c.is_lowercase();
91 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
92 // separate two components with an underscore if their boundary cannot
93 // be distinguished using a uppercase/lowercase case distinction
94 let join = if let Some(prev) = prev {
95 let l = prev.chars().last().unwrap();
96 let f = next.chars().next().unwrap();
97 !char_has_case(l) && !char_has_case(f)
101 (acc + if join { "_" } else { "" } + &next, Some(next))
106 impl NonCamelCaseTypes {
107 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
108 let name = &ident.name.as_str();
110 if !is_camel_case(name) {
111 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
112 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
115 "convert the identifier to upper camel case",
117 Applicability::MaybeIncorrect,
124 impl EarlyLintPass for NonCamelCaseTypes {
125 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
129 .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
136 ast::ItemKind::TyAlias(..)
137 | ast::ItemKind::Enum(..)
138 | ast::ItemKind::Struct(..)
139 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
140 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
145 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
146 self.check_case(cx, "variant", &v.ident);
149 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
150 if let ast::GenericParamKind::Type { .. } = param.kind {
151 self.check_case(cx, "type parameter", ¶m.ident);
159 "variables, methods, functions, lifetime parameters and modules should have snake case names"
162 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
165 fn to_snake_case(mut str: &str) -> String {
166 let mut words = vec![];
167 // Preserve leading underscores
168 str = str.trim_start_matches(|c: char| {
170 words.push(String::new());
176 for s in str.split('_') {
177 let mut last_upper = false;
178 let mut buf = String::new();
182 for ch in s.chars() {
183 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
187 last_upper = ch.is_uppercase();
188 buf.extend(ch.to_lowercase());
195 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
196 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
197 fn is_snake_case(ident: &str) -> bool {
198 if ident.is_empty() {
201 let ident = ident.trim_start_matches('\'');
202 let ident = ident.trim_matches('_');
204 let mut allow_underscore = true;
205 ident.chars().all(|c| {
206 allow_underscore = match c {
207 '_' if !allow_underscore => return false,
209 // It would be more obvious to use `c.is_lowercase()`,
210 // but some characters do not have a lowercase form
211 c if !c.is_uppercase() => true,
218 let name = &ident.name.as_str();
220 if !is_snake_case(name) {
221 let sc = NonSnakeCase::to_snake_case(name);
223 let msg = format!("{} `{}` should have a snake case name", sort, name);
224 let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
226 // We have a valid span in almost all cases, but we don't have one when linting a crate
227 // name provided via the command line.
228 if !ident.span.is_dummy() {
231 "convert the identifier to snake case",
233 Applicability::MaybeIncorrect,
236 err.help(&format!("convert the identifier to snake case: `{}`", sc));
244 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
247 cx: &LateContext<'_, '_>,
248 _: &'tcx hir::Mod<'tcx>,
252 if id != hir::CRATE_HIR_ID {
256 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
257 Some(Ident::from_str(name))
259 attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
260 .and_then(|attr| attr.meta())
262 meta.name_value_literal().and_then(|lit| {
263 if let ast::LitKind::Str(name, ..) = lit.kind {
264 // Discard the double quotes surrounding the literal.
268 .span_to_snippet(lit.span)
270 .and_then(|snippet| {
271 let left = snippet.find('"')?;
273 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
277 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
278 .with_hi(lit.span.hi() - BytePos(right as u32)),
281 .unwrap_or_else(|| lit.span);
283 Some(Ident::new(name, sp))
291 if let Some(ident) = &crate_ident {
292 self.check_snake_case(cx, "crate", ident);
296 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
297 if let GenericParamKind::Lifetime { .. } = param.kind {
298 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
304 cx: &LateContext<'_, '_>,
312 FnKind::Method(ident, ..) => match method_context(cx, id) {
313 MethodLateContext::PlainImpl => {
314 self.check_snake_case(cx, "method", ident);
316 MethodLateContext::TraitAutoImpl => {
317 self.check_snake_case(cx, "trait method", ident);
321 FnKind::ItemFn(ident, _, header, _, attrs) => {
322 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
323 if header.abi != Abi::Rust && attr::contains_name(attrs, sym::no_mangle) {
326 self.check_snake_case(cx, "function", ident);
328 FnKind::Closure(_) => (),
332 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
333 if let hir::ItemKind::Mod(_) = it.kind {
334 self.check_snake_case(cx, "module", &it.ident);
338 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) {
339 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = item.kind {
340 self.check_snake_case(cx, "trait method", &item.ident);
341 for param_name in pnames {
342 self.check_snake_case(cx, "variable", param_name);
347 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
348 if let &PatKind::Binding(_, _, ident, _) = &p.kind {
349 self.check_snake_case(cx, "variable", &ident);
353 fn check_struct_def(&mut self, cx: &LateContext<'_, '_>, s: &hir::VariantData<'_>) {
354 for sf in s.fields() {
355 self.check_snake_case(cx, "structure field", &sf.ident);
361 pub NON_UPPER_CASE_GLOBALS,
363 "static constants should have uppercase identifiers"
366 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
368 impl NonUpperCaseGlobals {
369 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
370 let name = &ident.name.as_str();
372 if name.chars().any(|c| c.is_lowercase()) {
373 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
375 let msg = format!("{} `{}` should have an upper case name", sort, name);
376 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
379 "convert the identifier to upper case",
381 Applicability::MaybeIncorrect,
388 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
389 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
391 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, sym::no_mangle) => {
392 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
394 hir::ItemKind::Const(..) => {
395 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
401 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem<'_>) {
402 if let hir::TraitItemKind::Const(..) = ti.kind {
403 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
407 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem<'_>) {
408 if let hir::ImplItemKind::Const(..) = ii.kind {
409 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
413 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
414 // Lint for constants that look like binding identifiers (#7526)
415 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
416 if let Res::Def(DefKind::Const, _) = path.res {
417 if path.segments.len() == 1 {
418 NonUpperCaseGlobals::check_upper_case(
420 "constant in pattern",
421 &path.segments[0].ident,
428 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
429 if let GenericParamKind::Const { .. } = param.kind {
430 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());