]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/nonstandard_style.rs
Auto merge of #57542 - Centril:rollup, r=Centril
[rust.git] / src / librustc_lint / nonstandard_style.rs
1 use rustc::hir::{self, GenericParamKind, PatKind};
2 use rustc::hir::def::Def;
3 use rustc::hir::intravisit::FnKind;
4 use rustc::ty;
5 use rustc_target::spec::abi::Abi;
6 use lint::{EarlyContext, LateContext, LintContext, LintArray};
7 use lint::{EarlyLintPass, LintPass, LateLintPass};
8 use syntax::ast;
9 use syntax::attr;
10 use syntax_pos::Span;
11
12 #[derive(PartialEq)]
13 pub enum MethodLateContext {
14     TraitAutoImpl,
15     TraitImpl,
16     PlainImpl,
17 }
18
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,
28             }
29         }
30     }
31 }
32
33 declare_lint! {
34     pub NON_CAMEL_CASE_TYPES,
35     Warn,
36     "types, variants, traits and type parameters should have camel case names"
37 }
38
39 #[derive(Copy, Clone)]
40 pub struct NonCamelCaseTypes;
41
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()
46         }
47
48         fn is_camel_case(name: ast::Name) -> bool {
49             let name = name.as_str();
50             let name = name.trim_matches('_');
51             if name.is_empty() {
52                 return true;
53             }
54
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] == '_'
62                 })
63         }
64
65         fn to_camel_case(s: &str) -> String {
66             s.trim_matches('_')
67                 .split('_')
68                 .map(|word| {
69                     word.chars().enumerate().map(|(i, c)| if i == 0 {
70                         c.to_uppercase().collect::<String>()
71                     } else {
72                         c.to_lowercase().collect()
73                     })
74                     .collect::<String>()
75                 })
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)
84                                 } else { false };
85                     (acc + if join { "_" } else { "" } + &next, Some(next))
86                 }).0
87         }
88
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)
93             } else {
94                 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
95             };
96             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
97         }
98     }
99 }
100
101 impl LintPass for NonCamelCaseTypes {
102     fn get_lints(&self) -> LintArray {
103         lint_array!(NON_CAMEL_CASE_TYPES)
104     }
105 }
106
107 impl EarlyLintPass for NonCamelCaseTypes {
108     fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
109         let has_repr_c = it.attrs
110             .iter()
111             .any(|attr| {
112                 attr::find_repr_attrs(&cx.sess.parse_sess, attr)
113                     .iter()
114                     .any(|r| r == &attr::ReprC)
115             });
116
117         if has_repr_c {
118             return;
119         }
120
121         match it.node {
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),
127             _ => (),
128         }
129     }
130
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);
133     }
134
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);
138         }
139     }
140 }
141
142 declare_lint! {
143     pub NON_SNAKE_CASE,
144     Warn,
145     "variables, methods, functions, lifetime parameters and modules should have snake case names"
146 }
147
148 #[derive(Copy, Clone)]
149 pub struct NonSnakeCase;
150
151 impl 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| {
156             if c == '_' {
157                 words.push(String::new());
158                 true
159             } else {
160                 false
161             }
162         });
163         for s in str.split('_') {
164             let mut last_upper = false;
165             let mut buf = String::new();
166             if s.is_empty() {
167                 continue;
168             }
169             for ch in s.chars() {
170                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
171                     words.push(buf);
172                     buf = String::new();
173                 }
174                 last_upper = ch.is_uppercase();
175                 buf.extend(ch.to_lowercase());
176             }
177             words.push(buf);
178         }
179         words.join("_")
180     }
181
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() {
185                 return true;
186             }
187             let ident = ident.trim_start_matches('\'');
188             let ident = ident.trim_matches('_');
189
190             let mut allow_underscore = true;
191             ident.chars().all(|c| {
192                 allow_underscore = match c {
193                     '_' if !allow_underscore => return false,
194                     '_' => 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,
198                     _ => return false,
199                 };
200                 true
201             })
202         }
203
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 `{}`",
208                         sort,
209                         name,
210                         sc)
211             } else {
212                 format!("{} `{}` should have a snake case name", sort, name)
213             };
214             match span {
215                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
216                 None => cx.lint(NON_SNAKE_CASE, &msg),
217             }
218         }
219     }
220 }
221
222 impl LintPass for NonSnakeCase {
223     fn get_lints(&self) -> LintArray {
224         lint_array!(NON_SNAKE_CASE)
225     }
226 }
227
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));
236         }
237     }
238
239     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
240         match param.kind {
241             GenericParamKind::Lifetime { .. } => {
242                 let name = param.name.ident().as_str();
243                 self.check_snake_case(cx, "lifetime", &name, Some(param.span));
244             }
245             GenericParamKind::Type { .. } => {}
246         }
247     }
248
249     fn check_fn(&mut self,
250                 cx: &LateContext,
251                 fk: FnKind,
252                 _: &hir::FnDecl,
253                 _: &hir::Body,
254                 span: Span,
255                 id: ast::NodeId) {
256         match fk {
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))
261                     }
262                     MethodLateContext::TraitAutoImpl => {
263                         self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
264                     }
265                     _ => (),
266                 }
267             }
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() {
271                     return;
272                 }
273                 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
274             }
275             FnKind::Closure(_) => (),
276         }
277     }
278
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));
282         }
283     }
284
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,
288                                   "trait method",
289                                   &item.ident.as_str(),
290                                   Some(item.span));
291             for param_name in pnames {
292                 self.check_snake_case(cx, "variable", &param_name.as_str(), Some(param_name.span));
293             }
294         }
295     }
296
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));
300         }
301     }
302
303     fn check_struct_def(&mut self,
304                         cx: &LateContext,
305                         s: &hir::VariantData,
306                         _: ast::Name,
307                         _: &hir::Generics,
308                         _: ast::NodeId) {
309         for sf in s.fields() {
310             self.check_snake_case(cx, "structure field", &sf.ident.as_str(), Some(sf.span));
311         }
312     }
313 }
314
315 declare_lint! {
316     pub NON_UPPER_CASE_GLOBALS,
317     Warn,
318     "static constants should have uppercase identifiers"
319 }
320
321 #[derive(Copy, Clone)]
322 pub struct NonUpperCaseGlobals;
323
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();
328             if name != &*uc {
329                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
330                              span,
331                              &format!("{} `{}` should have an upper case name such as `{}`",
332                                       sort,
333                                       name,
334                                       uc));
335             } else {
336                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
337                              span,
338                              &format!("{} `{}` should have an upper case name", sort, name));
339             }
340         }
341     }
342 }
343
344 impl LintPass for NonUpperCaseGlobals {
345     fn get_lints(&self) -> LintArray {
346         lint_array!(NON_UPPER_CASE_GLOBALS)
347     }
348 }
349
350 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
351     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
352         match it.node {
353             hir::ItemKind::Static(..) => {
354                 if attr::find_by_name(&it.attrs, "no_mangle").is_some() {
355                     return;
356                 }
357                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.ident.name,
358                                                       it.span);
359             }
360             hir::ItemKind::Const(..) => {
361                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident.name,
362                                                       it.span);
363             }
364             _ => {}
365         }
366     }
367
368     fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
369         match ti.node {
370             hir::TraitItemKind::Const(..) => {
371                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
372                                                       ti.ident.name, ti.span);
373             }
374             _ => {}
375         }
376     }
377
378     fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
379         match ii.node {
380             hir::ImplItemKind::Const(..) => {
381                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
382                                                       ii.ident.name, ii.span);
383             }
384             _ => {}
385         }
386     }
387
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,
396                                                           path.span);
397                 }
398             }
399         }
400     }
401 }