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) -> MethodLateContext {
31 let def_id = cx.tcx.hir.local_def_id(id);
32 let item = cx.tcx.associated_item(def_id);
33 match item.container {
34 ty::TraitContainer(..) => MethodLateContext::TraitDefaultImpl,
35 ty::ImplContainer(cid) => {
36 match cx.tcx.impl_trait_ref(cid) {
37 Some(_) => MethodLateContext::TraitImpl,
38 None => MethodLateContext::PlainImpl,
45 pub NON_CAMEL_CASE_TYPES,
47 "types, variants, traits and type parameters should have camel case names"
50 #[derive(Copy, Clone)]
51 pub struct NonCamelCaseTypes;
53 impl NonCamelCaseTypes {
54 fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
55 fn is_camel_case(name: ast::Name) -> bool {
56 let name = name.as_str();
60 let name = name.trim_matches('_');
62 // start with a non-lowercase letter rather than non-uppercase
63 // ones (some scripts don't have a concept of upper/lowercase)
64 !name.is_empty() && !name.chars().next().unwrap().is_lowercase() && !name.contains('_')
67 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()
80 if !is_camel_case(name) {
81 let c = to_camel_case(&name.as_str());
82 let m = if c.is_empty() {
83 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
85 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
87 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
92 impl LintPass for NonCamelCaseTypes {
93 fn get_lints(&self) -> LintArray {
94 lint_array!(NON_CAMEL_CASE_TYPES)
98 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
99 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
100 let extern_repr_count = it.attrs
103 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr)
105 .any(|r| r == &attr::ReprExtern)
108 let has_extern_repr = extern_repr_count > 0;
117 hir::ItemStruct(..) |
118 hir::ItemUnion(..) => self.check_case(cx, "type", it.name, it.span),
119 hir::ItemTrait(..) => self.check_case(cx, "trait", it.name, it.span),
124 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
125 self.check_case(cx, "variant", v.node.name, v.span);
128 fn check_generics(&mut self, cx: &LateContext, it: &hir::Generics) {
129 for gen in it.ty_params.iter() {
130 self.check_case(cx, "type parameter", gen.name, gen.span);
138 "variables, methods, functions, lifetime parameters and modules should have snake case names"
141 #[derive(Copy, Clone)]
142 pub struct NonSnakeCase;
145 fn to_snake_case(mut str: &str) -> String {
146 let mut words = vec![];
147 // Preserve leading underscores
148 str = str.trim_left_matches(|c: char| {
150 words.push(String::new());
156 for s in str.split('_') {
157 let mut last_upper = false;
158 let mut buf = String::new();
162 for ch in s.chars() {
163 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
167 last_upper = ch.is_uppercase();
168 buf.extend(ch.to_lowercase());
175 fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
176 fn is_snake_case(ident: &str) -> bool {
177 if ident.is_empty() {
180 let ident = ident.trim_left_matches('\'');
181 let ident = ident.trim_matches('_');
183 let mut allow_underscore = true;
184 ident.chars().all(|c| {
185 allow_underscore = match c {
186 '_' if !allow_underscore => return false,
188 // It would be more obvious to use `c.is_lowercase()`,
189 // but some characters do not have a lowercase form
190 c if !c.is_uppercase() => true,
197 if !is_snake_case(name) {
198 let sc = NonSnakeCase::to_snake_case(name);
199 let msg = if sc != name {
200 format!("{} `{}` should have a snake case name such as `{}`",
205 format!("{} `{}` should have a snake case name", sort, name)
208 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
209 None => cx.lint(NON_SNAKE_CASE, &msg),
215 impl LintPass for NonSnakeCase {
216 fn get_lints(&self) -> LintArray {
217 lint_array!(NON_SNAKE_CASE)
221 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
222 fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
223 let attr_crate_name = cr.attrs
225 .find(|at| at.check_name("crate_name"))
226 .and_then(|at| at.value_str().map(|s| (at, s)));
227 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
228 self.check_snake_case(cx, "crate", name, None);
229 } else if let Some((attr, name)) = attr_crate_name {
230 self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
234 fn check_fn(&mut self,
242 FnKind::Method(name, ..) => {
243 match method_context(cx, id) {
244 MethodLateContext::PlainImpl => {
245 self.check_snake_case(cx, "method", &name.as_str(), Some(span))
247 MethodLateContext::TraitDefaultImpl => {
248 self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
253 FnKind::ItemFn(name, ..) => {
254 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
256 FnKind::Closure(_) => (),
260 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
261 if let hir::ItemMod(_) = it.node {
262 self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
266 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
267 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref names)) = item.node {
268 self.check_snake_case(cx,
273 self.check_snake_case(cx, "variable", &name.node.as_str(), Some(name.span));
278 fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) {
279 self.check_snake_case(cx,
281 &t.lifetime.name.name().as_str(),
282 Some(t.lifetime.span));
285 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
286 if let &PatKind::Binding(_, _, ref path1, _) = &p.node {
287 self.check_snake_case(cx, "variable", &path1.node.as_str(), Some(p.span));
291 fn check_struct_def(&mut self,
293 s: &hir::VariantData,
297 for sf in s.fields() {
298 self.check_snake_case(cx, "structure field", &sf.name.as_str(), Some(sf.span));
304 pub NON_UPPER_CASE_GLOBALS,
306 "static constants should have uppercase identifiers"
309 #[derive(Copy, Clone)]
310 pub struct NonUpperCaseGlobals;
312 impl NonUpperCaseGlobals {
313 fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
314 if name.as_str().chars().any(|c| c.is_lowercase()) {
315 let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
317 cx.span_lint(NON_UPPER_CASE_GLOBALS,
319 &format!("{} `{}` should have an upper case name such as `{}`",
324 cx.span_lint(NON_UPPER_CASE_GLOBALS,
326 &format!("{} `{}` should have an upper case name", sort, name));
332 impl LintPass for NonUpperCaseGlobals {
333 fn get_lints(&self) -> LintArray {
334 lint_array!(NON_UPPER_CASE_GLOBALS)
338 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
339 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
341 hir::ItemStatic(..) => {
342 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
344 hir::ItemConst(..) => {
345 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
351 fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
353 hir::TraitItemKind::Const(..) => {
354 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.name, ti.span);
360 fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
362 hir::ImplItemKind::Const(..) => {
363 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.name, ii.span);
369 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
370 // Lint for constants that look like binding identifiers (#7526)
371 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
372 if let Def::Const(..) = path.def {
373 if path.segments.len() == 1 {
374 NonUpperCaseGlobals::check_upper_case(cx,
375 "constant in pattern",
376 path.segments[0].name,