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::def::Def;
13 use lint::{LateContext, LintContext, LintArray};
14 use lint::{LintPass, LateLintPass};
21 use rustc::hir::{self, PatKind};
22 use rustc::hir::intravisit::FnKind;
25 pub enum MethodLateContext {
31 pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext {
32 let def_id = cx.tcx.hir.local_def_id(id);
33 let item = cx.tcx.associated_item(def_id);
34 match item.container {
35 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
36 ty::ImplContainer(cid) => {
37 match cx.tcx.impl_trait_ref(cid) {
38 Some(_) => MethodLateContext::TraitImpl,
39 None => MethodLateContext::PlainImpl,
46 pub NON_CAMEL_CASE_TYPES,
48 "types, variants, traits and type parameters should have camel case names"
51 #[derive(Copy, Clone)]
52 pub struct NonCamelCaseTypes;
54 impl NonCamelCaseTypes {
55 fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
56 fn char_has_case(c: char) -> bool {
57 c.is_lowercase() || c.is_uppercase()
60 fn is_camel_case(name: ast::Name) -> bool {
61 let name = name.as_str();
65 let name = name.trim_matches('_');
67 // start with a non-lowercase letter rather than non-uppercase
68 // ones (some scripts don't have a concept of upper/lowercase)
69 !name.is_empty() && !name.chars().next().unwrap().is_lowercase() &&
70 !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
71 // contains a capitalisable character followed by, or preceded by, an underscore
72 char_has_case(pair[0]) && pair[1] == '_' ||
73 char_has_case(pair[1]) && pair[0] == '_'
77 fn to_camel_case(s: &str) -> String {
81 word.chars().enumerate().map(|(i, c)| if i == 0 {
82 c.to_uppercase().collect::<String>()
84 c.to_lowercase().collect()
89 .filter(|x| !x.is_empty())
91 .iter().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)
99 (acc + if join { "_" } else { "" } + next, Some(next))
103 if !is_camel_case(name) {
104 let c = to_camel_case(&name.as_str());
105 let m = if c.is_empty() {
106 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
108 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
110 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
115 impl LintPass for NonCamelCaseTypes {
116 fn get_lints(&self) -> LintArray {
117 lint_array!(NON_CAMEL_CASE_TYPES)
121 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
122 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
123 let has_repr_c = it.attrs
126 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr)
128 .any(|r| r == &attr::ReprC)
138 hir::ItemStruct(..) |
139 hir::ItemUnion(..) => self.check_case(cx, "type", it.name, it.span),
140 hir::ItemTrait(..) => self.check_case(cx, "trait", it.name, it.span),
145 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
146 self.check_case(cx, "variant", v.node.name, v.span);
149 fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
150 if let hir::GenericParam::Type(ref gen) = *param {
151 if gen.synthetic.is_none() {
152 self.check_case(cx, "type parameter", gen.name, gen.span);
161 "variables, methods, functions, lifetime parameters and modules should have snake case names"
164 #[derive(Copy, Clone)]
165 pub struct NonSnakeCase;
168 fn to_snake_case(mut str: &str) -> String {
169 let mut words = vec![];
170 // Preserve leading underscores
171 str = str.trim_left_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 fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
199 fn is_snake_case(ident: &str) -> bool {
200 if ident.is_empty() {
203 let ident = ident.trim_left_matches('\'');
204 let ident = ident.trim_matches('_');
206 let mut allow_underscore = true;
207 ident.chars().all(|c| {
208 allow_underscore = match c {
209 '_' if !allow_underscore => return false,
211 // It would be more obvious to use `c.is_lowercase()`,
212 // but some characters do not have a lowercase form
213 c if !c.is_uppercase() => true,
220 if !is_snake_case(name) {
221 let sc = NonSnakeCase::to_snake_case(name);
222 let msg = if sc != name {
223 format!("{} `{}` should have a snake case name such as `{}`",
228 format!("{} `{}` should have a snake case name", sort, name)
231 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
232 None => cx.lint(NON_SNAKE_CASE, &msg),
238 impl LintPass for NonSnakeCase {
239 fn get_lints(&self) -> LintArray {
240 lint_array!(NON_SNAKE_CASE)
244 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
245 fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
246 let attr_crate_name = attr::find_by_name(&cr.attrs, "crate_name")
247 .and_then(|at| at.value_str().map(|s| (at, s)));
248 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
249 self.check_snake_case(cx, "crate", name, None);
250 } else if let Some((attr, name)) = attr_crate_name {
251 self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
255 fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
256 if let hir::GenericParam::Lifetime(ref ld) = *param {
257 self.check_snake_case(
260 &ld.lifetime.name.name().as_str(),
261 Some(ld.lifetime.span)
266 fn check_fn(&mut self,
274 FnKind::Method(name, ..) => {
275 match method_context(cx, id) {
276 MethodLateContext::PlainImpl => {
277 self.check_snake_case(cx, "method", &name.as_str(), Some(span))
279 MethodLateContext::TraitAutoImpl => {
280 self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
285 FnKind::ItemFn(name, _, _, _, abi, _, attrs) => {
286 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
287 if abi != Abi::Rust && attr::find_by_name(attrs, "no_mangle").is_some() {
290 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
292 FnKind::Closure(_) => (),
296 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
297 if let hir::ItemMod(_) = it.node {
298 self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
302 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
303 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref names)) = item.node {
304 self.check_snake_case(cx,
309 self.check_snake_case(cx, "variable", &name.node.as_str(), Some(name.span));
314 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
315 if let &PatKind::Binding(_, _, ref path1, _) = &p.node {
316 self.check_snake_case(cx, "variable", &path1.node.as_str(), Some(p.span));
320 fn check_struct_def(&mut self,
322 s: &hir::VariantData,
326 for sf in s.fields() {
327 self.check_snake_case(cx, "structure field", &sf.name.as_str(), Some(sf.span));
333 pub NON_UPPER_CASE_GLOBALS,
335 "static constants should have uppercase identifiers"
338 #[derive(Copy, Clone)]
339 pub struct NonUpperCaseGlobals;
341 impl NonUpperCaseGlobals {
342 fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
343 if name.as_str().chars().any(|c| c.is_lowercase()) {
344 let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
346 cx.span_lint(NON_UPPER_CASE_GLOBALS,
348 &format!("{} `{}` should have an upper case name such as `{}`",
353 cx.span_lint(NON_UPPER_CASE_GLOBALS,
355 &format!("{} `{}` should have an upper case name", sort, name));
361 impl LintPass for NonUpperCaseGlobals {
362 fn get_lints(&self) -> LintArray {
363 lint_array!(NON_UPPER_CASE_GLOBALS)
367 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
368 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
370 hir::ItemStatic(..) => {
371 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
373 hir::ItemConst(..) => {
374 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
380 fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
382 hir::TraitItemKind::Const(..) => {
383 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.name, ti.span);
389 fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
391 hir::ImplItemKind::Const(..) => {
392 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.name, ii.span);
398 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
399 // Lint for constants that look like binding identifiers (#7526)
400 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
401 if let Def::Const(..) = path.def {
402 if path.segments.len() == 1 {
403 NonUpperCaseGlobals::check_upper_case(cx,
404 "constant in pattern",
405 path.segments[0].name,