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