1 use rustc::hir::{self, GenericParamKind, PatKind};
2 use rustc::hir::def::Def;
3 use rustc::hir::intravisit::FnKind;
5 use rustc_target::spec::abi::Abi;
6 use lint::{EarlyContext, LateContext, LintContext, LintArray};
7 use lint::{EarlyLintPass, LintPass, LateLintPass};
13 pub enum MethodLateContext {
19 pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext {
20 let def_id = cx.tcx.hir().local_def_id(id);
21 let item = cx.tcx.associated_item(def_id);
22 match item.container {
23 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
24 ty::ImplContainer(cid) => {
25 match cx.tcx.impl_trait_ref(cid) {
26 Some(_) => MethodLateContext::TraitImpl,
27 None => MethodLateContext::PlainImpl,
34 pub NON_CAMEL_CASE_TYPES,
36 "types, variants, traits and type parameters should have camel case names"
39 #[derive(Copy, Clone)]
40 pub struct NonCamelCaseTypes;
42 impl NonCamelCaseTypes {
43 fn check_case(&self, cx: &EarlyContext, sort: &str, name: ast::Name, span: Span) {
44 fn char_has_case(c: char) -> bool {
45 c.is_lowercase() || c.is_uppercase()
48 fn is_camel_case(name: ast::Name) -> bool {
49 let name = name.as_str();
50 let name = name.trim_matches('_');
55 // start with a non-lowercase letter rather than non-uppercase
56 // ones (some scripts don't have a concept of upper/lowercase)
57 !name.is_empty() && !name.chars().next().unwrap().is_lowercase() &&
58 !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
59 // contains a capitalisable character followed by, or preceded by, an underscore
60 char_has_case(pair[0]) && pair[1] == '_' ||
61 char_has_case(pair[1]) && pair[0] == '_'
65 fn to_camel_case(s: &str) -> String {
69 word.chars().enumerate().map(|(i, c)| if i == 0 {
70 c.to_uppercase().collect::<String>()
72 c.to_lowercase().collect()
76 .filter(|x| !x.is_empty())
77 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
78 // separate two components with an underscore if their boundary cannot
79 // be distinguished using a uppercase/lowercase case distinction
80 let join = if let Some(prev) = prev {
81 let l = prev.chars().last().unwrap();
82 let f = next.chars().next().unwrap();
83 !char_has_case(l) && !char_has_case(f)
85 (acc + if join { "_" } else { "" } + &next, Some(next))
89 if !is_camel_case(name) {
90 let c = to_camel_case(&name.as_str());
91 let m = if c.is_empty() {
92 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
94 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
96 cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
101 impl LintPass for NonCamelCaseTypes {
102 fn get_lints(&self) -> LintArray {
103 lint_array!(NON_CAMEL_CASE_TYPES)
107 impl EarlyLintPass for NonCamelCaseTypes {
108 fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
109 let has_repr_c = it.attrs
112 attr::find_repr_attrs(&cx.sess.parse_sess, attr)
114 .any(|r| r == &attr::ReprC)
122 ast::ItemKind::Ty(..) |
123 ast::ItemKind::Enum(..) |
124 ast::ItemKind::Struct(..) |
125 ast::ItemKind::Union(..) => self.check_case(cx, "type", it.ident.name, it.span),
126 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", it.ident.name, it.span),
131 fn check_variant(&mut self, cx: &EarlyContext, v: &ast::Variant, _: &ast::Generics) {
132 self.check_case(cx, "variant", v.node.ident.name, v.span);
135 fn check_generic_param(&mut self, cx: &EarlyContext, param: &ast::GenericParam) {
136 if let ast::GenericParamKind::Type { .. } = param.kind {
137 self.check_case(cx, "type parameter", param.ident.name, param.ident.span);
145 "variables, methods, functions, lifetime parameters and modules should have snake case names"
148 #[derive(Copy, Clone)]
149 pub struct NonSnakeCase;
152 fn to_snake_case(mut str: &str) -> String {
153 let mut words = vec![];
154 // Preserve leading underscores
155 str = str.trim_start_matches(|c: char| {
157 words.push(String::new());
163 for s in str.split('_') {
164 let mut last_upper = false;
165 let mut buf = String::new();
169 for ch in s.chars() {
170 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
174 last_upper = ch.is_uppercase();
175 buf.extend(ch.to_lowercase());
182 fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
183 fn is_snake_case(ident: &str) -> bool {
184 if ident.is_empty() {
187 let ident = ident.trim_start_matches('\'');
188 let ident = ident.trim_matches('_');
190 let mut allow_underscore = true;
191 ident.chars().all(|c| {
192 allow_underscore = match c {
193 '_' if !allow_underscore => return false,
195 // It would be more obvious to use `c.is_lowercase()`,
196 // but some characters do not have a lowercase form
197 c if !c.is_uppercase() => true,
204 if !is_snake_case(name) {
205 let sc = NonSnakeCase::to_snake_case(name);
206 let msg = if sc != name {
207 format!("{} `{}` should have a snake case name such as `{}`",
212 format!("{} `{}` should have a snake case name", sort, name)
215 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
216 None => cx.lint(NON_SNAKE_CASE, &msg),
222 impl LintPass for NonSnakeCase {
223 fn get_lints(&self) -> LintArray {
224 lint_array!(NON_SNAKE_CASE)
228 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
229 fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
230 let attr_crate_name = attr::find_by_name(&cr.attrs, "crate_name")
231 .and_then(|at| at.value_str().map(|s| (at, s)));
232 if let Some(ref name) = cx.tcx.sess.opts.crate_name {
233 self.check_snake_case(cx, "crate", name, None);
234 } else if let Some((attr, name)) = attr_crate_name {
235 self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
239 fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
241 GenericParamKind::Lifetime { .. } => {
242 let name = param.name.ident().as_str();
243 self.check_snake_case(cx, "lifetime", &name, Some(param.span));
245 GenericParamKind::Type { .. } => {}
249 fn check_fn(&mut self,
257 FnKind::Method(name, ..) => {
258 match method_context(cx, id) {
259 MethodLateContext::PlainImpl => {
260 self.check_snake_case(cx, "method", &name.as_str(), Some(span))
262 MethodLateContext::TraitAutoImpl => {
263 self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
268 FnKind::ItemFn(name, _, header, _, attrs) => {
269 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
270 if header.abi != Abi::Rust && attr::find_by_name(attrs, "no_mangle").is_some() {
273 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
275 FnKind::Closure(_) => (),
279 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
280 if let hir::ItemKind::Mod(_) = it.node {
281 self.check_snake_case(cx, "module", &it.ident.as_str(), Some(it.span));
285 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
286 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref pnames)) = item.node {
287 self.check_snake_case(cx,
289 &item.ident.as_str(),
291 for param_name in pnames {
292 self.check_snake_case(cx, "variable", ¶m_name.as_str(), Some(param_name.span));
297 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
298 if let &PatKind::Binding(_, _, ref ident, _) = &p.node {
299 self.check_snake_case(cx, "variable", &ident.as_str(), Some(p.span));
303 fn check_struct_def(&mut self,
305 s: &hir::VariantData,
309 for sf in s.fields() {
310 self.check_snake_case(cx, "structure field", &sf.ident.as_str(), Some(sf.span));
316 pub NON_UPPER_CASE_GLOBALS,
318 "static constants should have uppercase identifiers"
321 #[derive(Copy, Clone)]
322 pub struct NonUpperCaseGlobals;
324 impl NonUpperCaseGlobals {
325 fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
326 if name.as_str().chars().any(|c| c.is_lowercase()) {
327 let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
329 cx.span_lint(NON_UPPER_CASE_GLOBALS,
331 &format!("{} `{}` should have an upper case name such as `{}`",
336 cx.span_lint(NON_UPPER_CASE_GLOBALS,
338 &format!("{} `{}` should have an upper case name", sort, name));
344 impl LintPass for NonUpperCaseGlobals {
345 fn get_lints(&self) -> LintArray {
346 lint_array!(NON_UPPER_CASE_GLOBALS)
350 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
351 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
353 hir::ItemKind::Static(..) => {
354 if attr::find_by_name(&it.attrs, "no_mangle").is_some() {
357 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.ident.name,
360 hir::ItemKind::Const(..) => {
361 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident.name,
368 fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
370 hir::TraitItemKind::Const(..) => {
371 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
372 ti.ident.name, ti.span);
378 fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
380 hir::ImplItemKind::Const(..) => {
381 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
382 ii.ident.name, ii.span);
388 fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
389 // Lint for constants that look like binding identifiers (#7526)
390 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
391 if let Def::Const(..) = path.def {
392 if path.segments.len() == 1 {
393 NonUpperCaseGlobals::check_upper_case(cx,
394 "constant in pattern",
395 path.segments[0].ident.name,