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};
20 use rustc::hir::{self, PatKind};
21 use rustc::hir::intravisit::FnKind;
24 pub enum MethodLateContext {
30 pub fn method_context(cx: &LateContext, id: ast::NodeId, span: Span) -> MethodLateContext {
31 let def_id = cx.tcx.hir.local_def_id(id);
32 match cx.tcx.associated_items.borrow().get(&def_id) {
33 None => span_bug!(span, "missing method descriptor?!"),
35 match item.container {
36 ty::TraitContainer(..) => MethodLateContext::TraitDefaultImpl,
37 ty::ImplContainer(cid) => {
38 match cx.tcx.impl_trait_ref(cid) {
39 Some(_) => MethodLateContext::TraitImpl,
40 None => MethodLateContext::PlainImpl,
49 pub NON_CAMEL_CASE_TYPES,
51 "types, variants, traits and type parameters should have camel case names"
54 #[derive(Copy, Clone)]
55 pub struct NonCamelCaseTypes;
57 impl NonCamelCaseTypes {
58 fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
59 fn is_camel_case(name: ast::Name) -> bool {
60 let name = name.as_str();
64 let name = name.trim_matches('_');
66 // start with a non-lowercase letter rather than non-uppercase
67 // ones (some scripts don't have a concept of upper/lowercase)
68 !name.is_empty() && !name.chars().next().unwrap().is_lowercase() && !name.contains('_')
71 fn to_camel_case(s: &str) -> String {
74 word.chars().enumerate().map(|(i, c)| if i == 0 {
75 c.to_uppercase().collect::<String>()
77 c.to_lowercase().collect()
84 if !is_camel_case(name) {
85 let c = to_camel_case(&name.as_str());
86 let m = if c.is_empty() {
87 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
89 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
91 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
96 impl LintPass for NonCamelCaseTypes {
97 fn get_lints(&self) -> LintArray {
98 lint_array!(NON_CAMEL_CASE_TYPES)
102 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
103 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
104 let extern_repr_count = it.attrs
107 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr)
109 .any(|r| r == &attr::ReprExtern)
112 let has_extern_repr = extern_repr_count > 0;
120 hir::ItemStruct(..) |
121 hir::ItemUnion(..) => self.check_case(cx, "type", it.name, it.span),
122 hir::ItemTrait(..) => self.check_case(cx, "trait", it.name, it.span),
123 hir::ItemEnum(ref enum_definition, _) => {
127 self.check_case(cx, "type", it.name, it.span);
128 for variant in &enum_definition.variants {
129 self.check_case(cx, "variant", variant.node.name, variant.span);
136 fn check_generics(&mut self, cx: &LateContext, it: &hir::Generics) {
137 for gen in it.ty_params.iter() {
138 self.check_case(cx, "type parameter", gen.name, gen.span);
146 "variables, methods, functions, lifetime parameters and modules should have snake case names"
149 #[derive(Copy, Clone)]
150 pub struct NonSnakeCase;
153 fn to_snake_case(mut str: &str) -> String {
154 let mut words = vec![];
155 // Preserve leading underscores
156 str = str.trim_left_matches(|c: char| {
158 words.push(String::new());
164 for s in str.split('_') {
165 let mut last_upper = false;
166 let mut buf = String::new();
170 for ch in s.chars() {
171 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
175 last_upper = ch.is_uppercase();
176 buf.extend(ch.to_lowercase());
183 fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
184 fn is_snake_case(ident: &str) -> bool {
185 if ident.is_empty() {
188 let ident = ident.trim_left_matches('\'');
189 let ident = ident.trim_matches('_');
191 let mut allow_underscore = true;
192 ident.chars().all(|c| {
193 allow_underscore = match c {
194 '_' if !allow_underscore => return false,
196 // It would be more obvious to use `c.is_lowercase()`,
197 // but some characters do not have a lowercase form
198 c if !c.is_uppercase() => true,
205 if !is_snake_case(name) {
206 let sc = NonSnakeCase::to_snake_case(name);
207 let msg = if sc != name {
208 format!("{} `{}` should have a snake case name such as `{}`",
213 format!("{} `{}` should have a snake case name", sort, name)
216 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
217 None => cx.lint(NON_SNAKE_CASE, &msg),
223 impl LintPass for NonSnakeCase {
224 fn get_lints(&self) -> LintArray {
225 lint_array!(NON_SNAKE_CASE)
229 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
230 fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
231 let attr_crate_name = cr.attrs
233 .find(|at| at.check_name("crate_name"))
234 .and_then(|at| at.value_str().map(|s| (at, s)));
235 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
236 self.check_snake_case(cx, "crate", name, None);
237 } else if let Some((attr, name)) = attr_crate_name {
238 self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
242 fn check_fn(&mut self,
250 FnKind::Method(name, ..) => {
251 match method_context(cx, id, span) {
252 MethodLateContext::PlainImpl => {
253 self.check_snake_case(cx, "method", &name.as_str(), Some(span))
255 MethodLateContext::TraitDefaultImpl => {
256 self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
261 FnKind::ItemFn(name, ..) => {
262 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
264 FnKind::Closure(_) => (),
268 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
269 if let hir::ItemMod(_) = it.node {
270 self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
274 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
275 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref names)) = item.node {
276 self.check_snake_case(cx,
281 self.check_snake_case(cx, "variable", &name.node.as_str(), Some(name.span));
286 fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) {
287 self.check_snake_case(cx,
289 &t.lifetime.name.as_str(),
290 Some(t.lifetime.span));
293 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
294 if let &PatKind::Binding(_, _, ref path1, _) = &p.node {
295 self.check_snake_case(cx, "variable", &path1.node.as_str(), Some(p.span));
299 fn check_struct_def(&mut self,
301 s: &hir::VariantData,
305 for sf in s.fields() {
306 self.check_snake_case(cx, "structure field", &sf.name.as_str(), Some(sf.span));
312 pub NON_UPPER_CASE_GLOBALS,
314 "static constants should have uppercase identifiers"
317 #[derive(Copy, Clone)]
318 pub struct NonUpperCaseGlobals;
320 impl NonUpperCaseGlobals {
321 fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
322 if name.as_str().chars().any(|c| c.is_lowercase()) {
323 let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
325 cx.span_lint(NON_UPPER_CASE_GLOBALS,
327 &format!("{} `{}` should have an upper case name such as `{}`",
332 cx.span_lint(NON_UPPER_CASE_GLOBALS,
334 &format!("{} `{}` should have an upper case name", sort, name));
340 impl LintPass for NonUpperCaseGlobals {
341 fn get_lints(&self) -> LintArray {
342 lint_array!(NON_UPPER_CASE_GLOBALS)
346 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
347 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
349 hir::ItemStatic(..) => {
350 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
352 hir::ItemConst(..) => {
353 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
359 fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
361 hir::TraitItemKind::Const(..) => {
362 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.name, ti.span);
368 fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
370 hir::ImplItemKind::Const(..) => {
371 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.name, ii.span);
377 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
378 // Lint for constants that look like binding identifiers (#7526)
379 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
380 if let Def::Const(..) = path.def {
381 if path.segments.len() == 1 {
382 NonUpperCaseGlobals::check_upper_case(cx,
383 "constant in pattern",
384 path.segments[0].name,