1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::hir::{self, GenericParamKind, PatKind};
12 use rustc::hir::def::Def;
13 use rustc::hir::intravisit::FnKind;
15 use rustc_target::spec::abi::Abi;
16 use lint::{LateContext, LintContext, LintArray};
17 use lint::{LintPass, LateLintPass};
23 pub enum MethodLateContext {
29 pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext {
30 let def_id = cx.tcx.hir().local_def_id(id);
31 let item = cx.tcx.associated_item(def_id);
32 match item.container {
33 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
34 ty::ImplContainer(cid) => {
35 match cx.tcx.impl_trait_ref(cid) {
36 Some(_) => MethodLateContext::TraitImpl,
37 None => MethodLateContext::PlainImpl,
44 pub NON_CAMEL_CASE_TYPES,
46 "types, variants, traits and type parameters should have camel case names"
49 #[derive(Copy, Clone)]
50 pub struct NonCamelCaseTypes;
52 impl NonCamelCaseTypes {
53 fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
54 fn char_has_case(c: char) -> bool {
55 c.is_lowercase() || c.is_uppercase()
58 fn is_camel_case(name: ast::Name) -> bool {
59 let name = name.as_str();
60 let name = name.trim_matches('_');
65 // start with a non-lowercase letter rather than non-uppercase
66 // ones (some scripts don't have a concept of upper/lowercase)
67 !name.is_empty() && !name.chars().next().unwrap().is_lowercase() &&
68 !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
69 // contains a capitalisable character followed by, or preceded by, an underscore
70 char_has_case(pair[0]) && pair[1] == '_' ||
71 char_has_case(pair[1]) && pair[0] == '_'
75 fn to_camel_case(s: &str) -> String {
79 word.chars().enumerate().map(|(i, c)| if i == 0 {
80 c.to_uppercase().collect::<String>()
82 c.to_lowercase().collect()
86 .filter(|x| !x.is_empty())
87 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
88 // separate two components with an underscore if their boundary cannot
89 // be distinguished using a uppercase/lowercase case distinction
90 let join = if let Some(prev) = prev {
91 let l = prev.chars().last().unwrap();
92 let f = next.chars().next().unwrap();
93 !char_has_case(l) && !char_has_case(f)
95 (acc + if join { "_" } else { "" } + &next, Some(next))
99 if !is_camel_case(name) {
100 let c = to_camel_case(&name.as_str());
101 let m = if c.is_empty() {
102 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
104 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
106 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
111 impl LintPass for NonCamelCaseTypes {
112 fn get_lints(&self) -> LintArray {
113 lint_array!(NON_CAMEL_CASE_TYPES)
117 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
118 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
119 let has_repr_c = it.attrs
122 attr::find_repr_attrs(&cx.tcx.sess.parse_sess, attr)
124 .any(|r| r == &attr::ReprC)
132 hir::ItemKind::Ty(..) |
133 hir::ItemKind::Enum(..) |
134 hir::ItemKind::Struct(..) |
135 hir::ItemKind::Union(..) => self.check_case(cx, "type", it.name, it.span),
136 hir::ItemKind::Trait(..) => self.check_case(cx, "trait", it.name, it.span),
141 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
142 self.check_case(cx, "variant", v.node.name, v.span);
145 fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
147 GenericParamKind::Lifetime { .. } => {}
148 GenericParamKind::Type { synthetic, .. } => {
149 if synthetic.is_none() {
150 self.check_case(cx, "type parameter", param.name.ident().name, param.span);
160 "variables, methods, functions, lifetime parameters and modules should have snake case names"
163 #[derive(Copy, Clone)]
164 pub struct NonSnakeCase;
167 fn to_snake_case(mut str: &str) -> String {
168 let mut words = vec![];
169 // Preserve leading underscores
170 str = str.trim_left_matches(|c: char| {
172 words.push(String::new());
178 for s in str.split('_') {
179 let mut last_upper = false;
180 let mut buf = String::new();
184 for ch in s.chars() {
185 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
189 last_upper = ch.is_uppercase();
190 buf.extend(ch.to_lowercase());
197 fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
198 fn is_snake_case(ident: &str) -> bool {
199 if ident.is_empty() {
202 let ident = ident.trim_left_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 if !is_snake_case(name) {
220 let sc = NonSnakeCase::to_snake_case(name);
221 let msg = if sc != name {
222 format!("{} `{}` should have a snake case name such as `{}`",
227 format!("{} `{}` should have a snake case name", sort, name)
230 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
231 None => cx.lint(NON_SNAKE_CASE, &msg),
237 impl LintPass for NonSnakeCase {
238 fn get_lints(&self) -> LintArray {
239 lint_array!(NON_SNAKE_CASE)
243 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
244 fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
245 let attr_crate_name = attr::find_by_name(&cr.attrs, "crate_name")
246 .and_then(|at| at.value_str().map(|s| (at, s)));
247 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
248 self.check_snake_case(cx, "crate", name, None);
249 } else if let Some((attr, name)) = attr_crate_name {
250 self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
254 fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
256 GenericParamKind::Lifetime { .. } => {
257 let name = param.name.ident().as_str();
258 self.check_snake_case(cx, "lifetime", &name, Some(param.span));
260 GenericParamKind::Type { .. } => {}
264 fn check_fn(&mut self,
272 FnKind::Method(name, ..) => {
273 match method_context(cx, id) {
274 MethodLateContext::PlainImpl => {
275 self.check_snake_case(cx, "method", &name.as_str(), Some(span))
277 MethodLateContext::TraitAutoImpl => {
278 self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
283 FnKind::ItemFn(name, _, header, _, attrs) => {
284 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
285 if header.abi != Abi::Rust && attr::find_by_name(attrs, "no_mangle").is_some() {
288 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
290 FnKind::Closure(_) => (),
294 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
295 if let hir::ItemKind::Mod(_) = it.node {
296 self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
300 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
301 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref pnames)) = item.node {
302 self.check_snake_case(cx,
304 &item.ident.as_str(),
306 for param_name in pnames {
307 self.check_snake_case(cx, "variable", ¶m_name.as_str(), Some(param_name.span));
312 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
313 if let &PatKind::Binding(_, _, ref ident, _) = &p.node {
314 self.check_snake_case(cx, "variable", &ident.as_str(), Some(p.span));
318 fn check_struct_def(&mut self,
320 s: &hir::VariantData,
324 for sf in s.fields() {
325 self.check_snake_case(cx, "structure field", &sf.ident.as_str(), Some(sf.span));
331 pub NON_UPPER_CASE_GLOBALS,
333 "static constants should have uppercase identifiers"
336 #[derive(Copy, Clone)]
337 pub struct NonUpperCaseGlobals;
339 impl NonUpperCaseGlobals {
340 fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
341 if name.as_str().chars().any(|c| c.is_lowercase()) {
342 let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
344 cx.span_lint(NON_UPPER_CASE_GLOBALS,
346 &format!("{} `{}` should have an upper case name such as `{}`",
351 cx.span_lint(NON_UPPER_CASE_GLOBALS,
353 &format!("{} `{}` should have an upper case name", sort, name));
359 impl LintPass for NonUpperCaseGlobals {
360 fn get_lints(&self) -> LintArray {
361 lint_array!(NON_UPPER_CASE_GLOBALS)
365 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
366 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
368 hir::ItemKind::Static(..) => {
369 if attr::find_by_name(&it.attrs, "no_mangle").is_some() {
372 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
374 hir::ItemKind::Const(..) => {
375 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
381 fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
383 hir::TraitItemKind::Const(..) => {
384 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
385 ti.ident.name, ti.span);
391 fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
393 hir::ImplItemKind::Const(..) => {
394 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
395 ii.ident.name, ii.span);
401 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
402 // Lint for constants that look like binding identifiers (#7526)
403 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
404 if let Def::Const(..) = path.def {
405 if path.segments.len() == 1 {
406 NonUpperCaseGlobals::check_upper_case(cx,
407 "constant in pattern",
408 path.segments[0].ident.name,