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 #[derive(Copy, Clone)]
42 pub struct NonCamelCaseTypes;
44 impl NonCamelCaseTypes {
45 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
46 fn char_has_case(c: char) -> bool {
47 c.is_lowercase() || c.is_uppercase()
50 fn is_camel_case(name: &str) -> bool {
51 let name = name.trim_matches('_');
56 // start with a non-lowercase letter rather than non-uppercase
57 // ones (some scripts don't have a concept of upper/lowercase)
58 !name.is_empty() && !name.chars().next().unwrap().is_lowercase() &&
59 !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
60 // contains a capitalisable character followed by, or preceded by, an underscore
61 char_has_case(pair[0]) && pair[1] == '_' ||
62 char_has_case(pair[1]) && pair[0] == '_'
66 fn to_camel_case(s: &str) -> String {
70 word.chars().enumerate().map(|(i, c)| if i == 0 {
71 c.to_uppercase().collect::<String>()
73 c.to_lowercase().collect()
77 .filter(|x| !x.is_empty())
78 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
79 // separate two components with an underscore if their boundary cannot
80 // be distinguished using a uppercase/lowercase case distinction
81 let join = if let Some(prev) = prev {
82 let l = prev.chars().last().unwrap();
83 let f = next.chars().next().unwrap();
84 !char_has_case(l) && !char_has_case(f)
86 (acc + if join { "_" } else { "" } + &next, Some(next))
90 let name = &ident.name.as_str();
92 if !is_camel_case(name) {
93 let c = to_camel_case(name);
95 let msg = format!("{} `{}` should have a camel case name", sort, name);
96 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
99 "convert the identifier to camel case",
101 Applicability::MaybeIncorrect,
108 impl LintPass for NonCamelCaseTypes {
109 fn name(&self) -> &'static str {
113 fn get_lints(&self) -> LintArray {
114 lint_array!(NON_CAMEL_CASE_TYPES)
118 impl EarlyLintPass for NonCamelCaseTypes {
119 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
120 let has_repr_c = it.attrs
123 attr::find_repr_attrs(&cx.sess.parse_sess, attr)
125 .any(|r| r == &attr::ReprC)
133 ast::ItemKind::Ty(..) |
134 ast::ItemKind::Enum(..) |
135 ast::ItemKind::Struct(..) |
136 ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
137 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
142 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
143 self.check_case(cx, "variant", &v.node.ident);
146 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
147 if let ast::GenericParamKind::Type { .. } = param.kind {
148 self.check_case(cx, "type parameter", ¶m.ident);
156 "variables, methods, functions, lifetime parameters and modules should have snake case names"
159 #[derive(Copy, Clone)]
160 pub struct NonSnakeCase;
163 fn to_snake_case(mut str: &str) -> String {
164 let mut words = vec![];
165 // Preserve leading underscores
166 str = str.trim_start_matches(|c: char| {
168 words.push(String::new());
174 for s in str.split('_') {
175 let mut last_upper = false;
176 let mut buf = String::new();
180 for ch in s.chars() {
181 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
185 last_upper = ch.is_uppercase();
186 buf.extend(ch.to_lowercase());
193 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
194 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
195 fn is_snake_case(ident: &str) -> bool {
196 if ident.is_empty() {
199 let ident = ident.trim_start_matches('\'');
200 let ident = ident.trim_matches('_');
202 let mut allow_underscore = true;
203 ident.chars().all(|c| {
204 allow_underscore = match c {
205 '_' if !allow_underscore => return false,
207 // It would be more obvious to use `c.is_lowercase()`,
208 // but some characters do not have a lowercase form
209 c if !c.is_uppercase() => true,
216 let name = &ident.name.as_str();
218 if !is_snake_case(name) {
219 let sc = NonSnakeCase::to_snake_case(name);
221 let msg = format!("{} `{}` should have a snake case name", sort, name);
222 let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
224 // We have a valid span in almost all cases, but we don't have one when linting a crate
225 // name provided via the command line.
226 if !ident.span.is_dummy() {
229 "convert the identifier to snake case",
231 Applicability::MaybeIncorrect,
234 err.help(&format!("convert the identifier to snake case: `{}`", sc));
242 impl LintPass for NonSnakeCase {
243 fn name(&self) -> &'static str {
247 fn get_lints(&self) -> LintArray {
248 lint_array!(NON_SNAKE_CASE)
252 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
253 fn check_crate(&mut self, cx: &LateContext<'_, '_>, cr: &hir::Crate) {
254 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
255 Some(Ident::from_str(name))
257 attr::find_by_name(&cr.attrs, "crate_name")
258 .and_then(|attr| attr.meta())
260 meta.name_value_literal().and_then(|lit| {
261 if let ast::LitKind::Str(name, ..) = lit.node {
262 // Discard the double quotes surrounding the literal.
263 let sp = cx.sess().source_map().span_to_snippet(lit.span)
265 .and_then(|snippet| {
266 let left = snippet.find('"')?;
267 let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
271 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
272 .with_hi(lit.span.hi() - BytePos(right as u32)),
275 .unwrap_or_else(|| lit.span);
277 Some(Ident::new(name, sp))
285 if let Some(ident) = &crate_ident {
286 self.check_snake_case(cx, "crate", ident);
290 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
291 if let GenericParamKind::Lifetime { .. } = param.kind {
292 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
298 cx: &LateContext<'_, '_>,
306 FnKind::Method(ident, ..) => {
307 match method_context(cx, id) {
308 MethodLateContext::PlainImpl => {
309 self.check_snake_case(cx, "method", ident);
311 MethodLateContext::TraitAutoImpl => {
312 self.check_snake_case(cx, "trait method", ident);
317 FnKind::ItemFn(ident, _, header, _, attrs) => {
318 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
319 if header.abi != Abi::Rust && attr::contains_name(attrs, "no_mangle") {
322 self.check_snake_case(cx, "function", ident);
324 FnKind::Closure(_) => (),
328 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
329 if let hir::ItemKind::Mod(_) = it.node {
330 self.check_snake_case(cx, "module", &it.ident);
334 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) {
335 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node {
336 self.check_snake_case(cx, "trait method", &item.ident);
337 for param_name in pnames {
338 self.check_snake_case(cx, "variable", param_name);
343 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
344 if let &PatKind::Binding(_, _, _, ident, _) = &p.node {
345 self.check_snake_case(cx, "variable", &ident);
351 cx: &LateContext<'_, '_>,
352 s: &hir::VariantData,
357 for sf in s.fields() {
358 self.check_snake_case(cx, "structure field", &sf.ident);
364 pub NON_UPPER_CASE_GLOBALS,
366 "static constants should have uppercase identifiers"
369 #[derive(Copy, Clone)]
370 pub struct NonUpperCaseGlobals;
372 impl NonUpperCaseGlobals {
373 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
374 let name = &ident.name.as_str();
376 if name.chars().any(|c| c.is_lowercase()) {
377 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
379 let msg = format!("{} `{}` should have an upper case name", sort, name);
380 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
383 "convert the identifier to upper case",
385 Applicability::MaybeIncorrect,
392 impl LintPass for NonUpperCaseGlobals {
393 fn name(&self) -> &'static str {
394 "NonUpperCaseGlobals"
397 fn get_lints(&self) -> LintArray {
398 lint_array!(NON_UPPER_CASE_GLOBALS)
402 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
403 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
405 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
406 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
408 hir::ItemKind::Const(..) => {
409 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
415 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
416 if let hir::TraitItemKind::Const(..) = ti.node {
417 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
421 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
422 if let hir::ImplItemKind::Const(..) = ii.node {
423 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
427 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
428 // Lint for constants that look like binding identifiers (#7526)
429 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
430 if let Def::Const(..) = path.def {
431 if path.segments.len() == 1 {
432 NonUpperCaseGlobals::check_upper_case(
434 "constant in pattern",
435 &path.segments[0].ident