]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/nonstandard_style.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustc_lint / nonstandard_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::{self, GenericParamKind, PatKind};
12 use rustc::hir::def::Def;
13 use rustc::hir::intravisit::FnKind;
14 use rustc::ty;
15 use rustc_target::spec::abi::Abi;
16 use lint::{LateContext, LintContext, LintArray};
17 use lint::{LintPass, LateLintPass};
18 use syntax::ast;
19 use syntax::attr;
20 use syntax_pos::Span;
21
22 #[derive(PartialEq)]
23 pub enum MethodLateContext {
24     TraitAutoImpl,
25     TraitImpl,
26     PlainImpl,
27 }
28
29 pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext {
30     let def_id = cx.tcx.hir().local_def_id(id);
31     let item = cx.tcx.associated_item(def_id);
32     match item.container {
33         ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
34         ty::ImplContainer(cid) => {
35             match cx.tcx.impl_trait_ref(cid) {
36                 Some(_) => MethodLateContext::TraitImpl,
37                 None => MethodLateContext::PlainImpl,
38             }
39         }
40     }
41 }
42
43 declare_lint! {
44     pub NON_CAMEL_CASE_TYPES,
45     Warn,
46     "types, variants, traits and type parameters should have camel case names"
47 }
48
49 #[derive(Copy, Clone)]
50 pub struct NonCamelCaseTypes;
51
52 impl NonCamelCaseTypes {
53     fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
54         fn char_has_case(c: char) -> bool {
55             c.is_lowercase() || c.is_uppercase()
56         }
57
58         fn is_camel_case(name: ast::Name) -> bool {
59             let name = name.as_str();
60             let name = name.trim_matches('_');
61             if name.is_empty() {
62                 return true;
63             }
64
65             // start with a non-lowercase letter rather than non-uppercase
66             // ones (some scripts don't have a concept of upper/lowercase)
67             !name.is_empty() && !name.chars().next().unwrap().is_lowercase() &&
68                 !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
69                     // contains a capitalisable character followed by, or preceded by, an underscore
70                     char_has_case(pair[0]) && pair[1] == '_' ||
71                     char_has_case(pair[1]) && pair[0] == '_'
72                 })
73         }
74
75         fn to_camel_case(s: &str) -> String {
76             s.trim_matches('_')
77                 .split('_')
78                 .map(|word| {
79                     word.chars().enumerate().map(|(i, c)| if i == 0 {
80                         c.to_uppercase().collect::<String>()
81                     } else {
82                         c.to_lowercase().collect()
83                     })
84                     .collect::<String>()
85                 })
86                 .filter(|x| !x.is_empty())
87                 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
88                     // separate two components with an underscore if their boundary cannot
89                     // be distinguished using a uppercase/lowercase case distinction
90                     let join = if let Some(prev) = prev {
91                                     let l = prev.chars().last().unwrap();
92                                     let f = next.chars().next().unwrap();
93                                     !char_has_case(l) && !char_has_case(f)
94                                 } else { false };
95                     (acc + if join { "_" } else { "" } + &next, Some(next))
96                 }).0
97         }
98
99         if !is_camel_case(name) {
100             let c = to_camel_case(&name.as_str());
101             let m = if c.is_empty() {
102                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
103             } else {
104                 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
105             };
106             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
107         }
108     }
109 }
110
111 impl LintPass for NonCamelCaseTypes {
112     fn get_lints(&self) -> LintArray {
113         lint_array!(NON_CAMEL_CASE_TYPES)
114     }
115 }
116
117 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
118     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
119         let has_repr_c = it.attrs
120             .iter()
121             .any(|attr| {
122                 attr::find_repr_attrs(&cx.tcx.sess.parse_sess, attr)
123                     .iter()
124                     .any(|r| r == &attr::ReprC)
125             });
126
127         if has_repr_c {
128             return;
129         }
130
131         match it.node {
132             hir::ItemKind::Ty(..) |
133             hir::ItemKind::Enum(..) |
134             hir::ItemKind::Struct(..) |
135             hir::ItemKind::Union(..) => self.check_case(cx, "type", it.name, it.span),
136             hir::ItemKind::Trait(..) => self.check_case(cx, "trait", it.name, it.span),
137             _ => (),
138         }
139     }
140
141     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
142         self.check_case(cx, "variant", v.node.name, v.span);
143     }
144
145     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
146         match param.kind {
147             GenericParamKind::Lifetime { .. } => {}
148             GenericParamKind::Type { synthetic, .. } => {
149                 if synthetic.is_none() {
150                     self.check_case(cx, "type parameter", param.name.ident().name, param.span);
151                 }
152             }
153         }
154     }
155 }
156
157 declare_lint! {
158     pub NON_SNAKE_CASE,
159     Warn,
160     "variables, methods, functions, lifetime parameters and modules should have snake case names"
161 }
162
163 #[derive(Copy, Clone)]
164 pub struct NonSnakeCase;
165
166 impl NonSnakeCase {
167     fn to_snake_case(mut str: &str) -> String {
168         let mut words = vec![];
169         // Preserve leading underscores
170         str = str.trim_left_matches(|c: char| {
171             if c == '_' {
172                 words.push(String::new());
173                 true
174             } else {
175                 false
176             }
177         });
178         for s in str.split('_') {
179             let mut last_upper = false;
180             let mut buf = String::new();
181             if s.is_empty() {
182                 continue;
183             }
184             for ch in s.chars() {
185                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
186                     words.push(buf);
187                     buf = String::new();
188                 }
189                 last_upper = ch.is_uppercase();
190                 buf.extend(ch.to_lowercase());
191             }
192             words.push(buf);
193         }
194         words.join("_")
195     }
196
197     fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
198         fn is_snake_case(ident: &str) -> bool {
199             if ident.is_empty() {
200                 return true;
201             }
202             let ident = ident.trim_left_matches('\'');
203             let ident = ident.trim_matches('_');
204
205             let mut allow_underscore = true;
206             ident.chars().all(|c| {
207                 allow_underscore = match c {
208                     '_' if !allow_underscore => return false,
209                     '_' => false,
210                     // It would be more obvious to use `c.is_lowercase()`,
211                     // but some characters do not have a lowercase form
212                     c if !c.is_uppercase() => true,
213                     _ => return false,
214                 };
215                 true
216             })
217         }
218
219         if !is_snake_case(name) {
220             let sc = NonSnakeCase::to_snake_case(name);
221             let msg = if sc != name {
222                 format!("{} `{}` should have a snake case name such as `{}`",
223                         sort,
224                         name,
225                         sc)
226             } else {
227                 format!("{} `{}` should have a snake case name", sort, name)
228             };
229             match span {
230                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
231                 None => cx.lint(NON_SNAKE_CASE, &msg),
232             }
233         }
234     }
235 }
236
237 impl LintPass for NonSnakeCase {
238     fn get_lints(&self) -> LintArray {
239         lint_array!(NON_SNAKE_CASE)
240     }
241 }
242
243 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
244     fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
245         let attr_crate_name = attr::find_by_name(&cr.attrs, "crate_name")
246             .and_then(|at| at.value_str().map(|s| (at, s)));
247         if let Some(ref name) = cx.tcx.sess.opts.crate_name {
248             self.check_snake_case(cx, "crate", name, None);
249         } else if let Some((attr, name)) = attr_crate_name {
250             self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
251         }
252     }
253
254     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
255         match param.kind {
256             GenericParamKind::Lifetime { .. } => {
257                 let name = param.name.ident().as_str();
258                 self.check_snake_case(cx, "lifetime", &name, Some(param.span));
259             }
260             GenericParamKind::Type { .. } => {}
261         }
262     }
263
264     fn check_fn(&mut self,
265                 cx: &LateContext,
266                 fk: FnKind,
267                 _: &hir::FnDecl,
268                 _: &hir::Body,
269                 span: Span,
270                 id: ast::NodeId) {
271         match fk {
272             FnKind::Method(name, ..) => {
273                 match method_context(cx, id) {
274                     MethodLateContext::PlainImpl => {
275                         self.check_snake_case(cx, "method", &name.as_str(), Some(span))
276                     }
277                     MethodLateContext::TraitAutoImpl => {
278                         self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
279                     }
280                     _ => (),
281                 }
282             }
283             FnKind::ItemFn(name, _, header, _, attrs) => {
284                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
285                 if header.abi != Abi::Rust && attr::find_by_name(attrs, "no_mangle").is_some() {
286                     return;
287                 }
288                 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
289             }
290             FnKind::Closure(_) => (),
291         }
292     }
293
294     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
295         if let hir::ItemKind::Mod(_) = it.node {
296             self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
297         }
298     }
299
300     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
301         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref pnames)) = item.node {
302             self.check_snake_case(cx,
303                                   "trait method",
304                                   &item.ident.as_str(),
305                                   Some(item.span));
306             for param_name in pnames {
307                 self.check_snake_case(cx, "variable", &param_name.as_str(), Some(param_name.span));
308             }
309         }
310     }
311
312     fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
313         if let &PatKind::Binding(_, _, ref ident, _) = &p.node {
314             self.check_snake_case(cx, "variable", &ident.as_str(), Some(p.span));
315         }
316     }
317
318     fn check_struct_def(&mut self,
319                         cx: &LateContext,
320                         s: &hir::VariantData,
321                         _: ast::Name,
322                         _: &hir::Generics,
323                         _: ast::NodeId) {
324         for sf in s.fields() {
325             self.check_snake_case(cx, "structure field", &sf.ident.as_str(), Some(sf.span));
326         }
327     }
328 }
329
330 declare_lint! {
331     pub NON_UPPER_CASE_GLOBALS,
332     Warn,
333     "static constants should have uppercase identifiers"
334 }
335
336 #[derive(Copy, Clone)]
337 pub struct NonUpperCaseGlobals;
338
339 impl NonUpperCaseGlobals {
340     fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
341         if name.as_str().chars().any(|c| c.is_lowercase()) {
342             let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
343             if name != &*uc {
344                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
345                              span,
346                              &format!("{} `{}` should have an upper case name such as `{}`",
347                                       sort,
348                                       name,
349                                       uc));
350             } else {
351                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
352                              span,
353                              &format!("{} `{}` should have an upper case name", sort, name));
354             }
355         }
356     }
357 }
358
359 impl LintPass for NonUpperCaseGlobals {
360     fn get_lints(&self) -> LintArray {
361         lint_array!(NON_UPPER_CASE_GLOBALS)
362     }
363 }
364
365 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
366     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
367         match it.node {
368             hir::ItemKind::Static(..) => {
369                 if attr::find_by_name(&it.attrs, "no_mangle").is_some() {
370                     return;
371                 }
372                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
373             }
374             hir::ItemKind::Const(..) => {
375                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
376             }
377             _ => {}
378         }
379     }
380
381     fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
382         match ti.node {
383             hir::TraitItemKind::Const(..) => {
384                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
385                                                       ti.ident.name, ti.span);
386             }
387             _ => {}
388         }
389     }
390
391     fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
392         match ii.node {
393             hir::ImplItemKind::Const(..) => {
394                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
395                                                       ii.ident.name, ii.span);
396             }
397             _ => {}
398         }
399     }
400
401     fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
402         // Lint for constants that look like binding identifiers (#7526)
403         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
404             if let Def::Const(..) = path.def {
405                 if path.segments.len() == 1 {
406                     NonUpperCaseGlobals::check_upper_case(cx,
407                                                           "constant in pattern",
408                                                           path.segments[0].ident.name,
409                                                           path.span);
410                 }
411             }
412         }
413     }
414 }