]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/bad_style.rs
Refactor lifetime name into an enum
[rust.git] / src / librustc_lint / bad_style.rs
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.
4 //
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.
10
11 use rustc::hir::def::Def;
12 use rustc::ty;
13 use lint::{LateContext, LintContext, LintArray};
14 use lint::{LintPass, LateLintPass};
15
16 use syntax::ast;
17 use syntax::attr;
18 use syntax_pos::Span;
19
20 use rustc::hir::{self, PatKind};
21 use rustc::hir::intravisit::FnKind;
22
23 #[derive(PartialEq)]
24 pub enum MethodLateContext {
25     TraitDefaultImpl,
26     TraitImpl,
27     PlainImpl,
28 }
29
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,
39             }
40         }
41     }
42 }
43
44 declare_lint! {
45     pub NON_CAMEL_CASE_TYPES,
46     Warn,
47     "types, variants, traits and type parameters should have camel case names"
48 }
49
50 #[derive(Copy, Clone)]
51 pub struct NonCamelCaseTypes;
52
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();
57             if name.is_empty() {
58                 return true;
59             }
60             let name = name.trim_matches('_');
61
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('_')
65         }
66
67         fn to_camel_case(s: &str) -> String {
68             s.split('_')
69                 .flat_map(|word| {
70                     word.chars().enumerate().map(|(i, c)| if i == 0 {
71                         c.to_uppercase().collect::<String>()
72                     } else {
73                         c.to_lowercase().collect()
74                     })
75                 })
76                 .collect::<Vec<_>>()
77                 .concat()
78         }
79
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)
84             } else {
85                 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
86             };
87             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
88         }
89     }
90 }
91
92 impl LintPass for NonCamelCaseTypes {
93     fn get_lints(&self) -> LintArray {
94         lint_array!(NON_CAMEL_CASE_TYPES)
95     }
96 }
97
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
101             .iter()
102             .filter(|attr| {
103                 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr)
104                     .iter()
105                     .any(|r| r == &attr::ReprExtern)
106             })
107             .count();
108         let has_extern_repr = extern_repr_count > 0;
109
110         if has_extern_repr {
111             return;
112         }
113
114         match it.node {
115             hir::ItemTy(..) |
116             hir::ItemEnum(..) |
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),
120             _ => (),
121         }
122     }
123
124     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
125         self.check_case(cx, "variant", v.node.name, v.span);
126     }
127
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);
131         }
132     }
133 }
134
135 declare_lint! {
136     pub NON_SNAKE_CASE,
137     Warn,
138     "variables, methods, functions, lifetime parameters and modules should have snake case names"
139 }
140
141 #[derive(Copy, Clone)]
142 pub struct NonSnakeCase;
143
144 impl 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| {
149             if c == '_' {
150                 words.push(String::new());
151                 true
152             } else {
153                 false
154             }
155         });
156         for s in str.split('_') {
157             let mut last_upper = false;
158             let mut buf = String::new();
159             if s.is_empty() {
160                 continue;
161             }
162             for ch in s.chars() {
163                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
164                     words.push(buf);
165                     buf = String::new();
166                 }
167                 last_upper = ch.is_uppercase();
168                 buf.extend(ch.to_lowercase());
169             }
170             words.push(buf);
171         }
172         words.join("_")
173     }
174
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() {
178                 return true;
179             }
180             let ident = ident.trim_left_matches('\'');
181             let ident = ident.trim_matches('_');
182
183             let mut allow_underscore = true;
184             ident.chars().all(|c| {
185                 allow_underscore = match c {
186                     '_' if !allow_underscore => return false,
187                     '_' => 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,
191                     _ => return false,
192                 };
193                 true
194             })
195         }
196
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 `{}`",
201                         sort,
202                         name,
203                         sc)
204             } else {
205                 format!("{} `{}` should have a snake case name", sort, name)
206             };
207             match span {
208                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
209                 None => cx.lint(NON_SNAKE_CASE, &msg),
210             }
211         }
212     }
213 }
214
215 impl LintPass for NonSnakeCase {
216     fn get_lints(&self) -> LintArray {
217         lint_array!(NON_SNAKE_CASE)
218     }
219 }
220
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
224             .iter()
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));
231         }
232     }
233
234     fn check_fn(&mut self,
235                 cx: &LateContext,
236                 fk: FnKind,
237                 _: &hir::FnDecl,
238                 _: &hir::Body,
239                 span: Span,
240                 id: ast::NodeId) {
241         match fk {
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))
246                     }
247                     MethodLateContext::TraitDefaultImpl => {
248                         self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
249                     }
250                     _ => (),
251                 }
252             }
253             FnKind::ItemFn(name, ..) => {
254                 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
255             }
256             FnKind::Closure(_) => (),
257         }
258     }
259
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));
263         }
264     }
265
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,
269                                   "trait method",
270                                   &item.name.as_str(),
271                                   Some(item.span));
272             for name in names {
273                 self.check_snake_case(cx, "variable", &name.node.as_str(), Some(name.span));
274             }
275         }
276     }
277
278     fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) {
279         self.check_snake_case(cx,
280                               "lifetime",
281                               &t.lifetime.name.name().as_str(),
282                               Some(t.lifetime.span));
283     }
284
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));
288         }
289     }
290
291     fn check_struct_def(&mut self,
292                         cx: &LateContext,
293                         s: &hir::VariantData,
294                         _: ast::Name,
295                         _: &hir::Generics,
296                         _: ast::NodeId) {
297         for sf in s.fields() {
298             self.check_snake_case(cx, "structure field", &sf.name.as_str(), Some(sf.span));
299         }
300     }
301 }
302
303 declare_lint! {
304     pub NON_UPPER_CASE_GLOBALS,
305     Warn,
306     "static constants should have uppercase identifiers"
307 }
308
309 #[derive(Copy, Clone)]
310 pub struct NonUpperCaseGlobals;
311
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();
316             if name != &*uc {
317                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
318                              span,
319                              &format!("{} `{}` should have an upper case name such as `{}`",
320                                       sort,
321                                       name,
322                                       uc));
323             } else {
324                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
325                              span,
326                              &format!("{} `{}` should have an upper case name", sort, name));
327             }
328         }
329     }
330 }
331
332 impl LintPass for NonUpperCaseGlobals {
333     fn get_lints(&self) -> LintArray {
334         lint_array!(NON_UPPER_CASE_GLOBALS)
335     }
336 }
337
338 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
339     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
340         match it.node {
341             hir::ItemStatic(..) => {
342                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
343             }
344             hir::ItemConst(..) => {
345                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
346             }
347             _ => {}
348         }
349     }
350
351     fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
352         match ti.node {
353             hir::TraitItemKind::Const(..) => {
354                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.name, ti.span);
355             }
356             _ => {}
357         }
358     }
359
360     fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
361         match ii.node {
362             hir::ImplItemKind::Const(..) => {
363                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.name, ii.span);
364             }
365             _ => {}
366         }
367     }
368
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,
377                                                           path.span);
378                 }
379             }
380         }
381     }
382 }