]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/bad_style.rs
rustc: always include elidable lifetimes in HIR types.
[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, span: Span) -> MethodLateContext {
31     let def_id = cx.tcx.hir.local_def_id(id);
32     match cx.tcx.associated_items.borrow().get(&def_id) {
33         None => span_bug!(span, "missing method descriptor?!"),
34         Some(item) => {
35             match item.container {
36                 ty::TraitContainer(..) => MethodLateContext::TraitDefaultImpl,
37                 ty::ImplContainer(cid) => {
38                     match cx.tcx.impl_trait_ref(cid) {
39                         Some(_) => MethodLateContext::TraitImpl,
40                         None => MethodLateContext::PlainImpl,
41                     }
42                 }
43             }
44         }
45     }
46 }
47
48 declare_lint! {
49     pub NON_CAMEL_CASE_TYPES,
50     Warn,
51     "types, variants, traits and type parameters should have camel case names"
52 }
53
54 #[derive(Copy, Clone)]
55 pub struct NonCamelCaseTypes;
56
57 impl NonCamelCaseTypes {
58     fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
59         fn is_camel_case(name: ast::Name) -> bool {
60             let name = name.as_str();
61             if name.is_empty() {
62                 return true;
63             }
64             let name = name.trim_matches('_');
65
66             // start with a non-lowercase letter rather than non-uppercase
67             // ones (some scripts don't have a concept of upper/lowercase)
68             !name.is_empty() && !name.chars().next().unwrap().is_lowercase() && !name.contains('_')
69         }
70
71         fn to_camel_case(s: &str) -> String {
72             s.split('_')
73                 .flat_map(|word| {
74                     word.chars().enumerate().map(|(i, c)| if i == 0 {
75                         c.to_uppercase().collect::<String>()
76                     } else {
77                         c.to_lowercase().collect()
78                     })
79                 })
80                 .collect::<Vec<_>>()
81                 .concat()
82         }
83
84         if !is_camel_case(name) {
85             let c = to_camel_case(&name.as_str());
86             let m = if c.is_empty() {
87                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
88             } else {
89                 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
90             };
91             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
92         }
93     }
94 }
95
96 impl LintPass for NonCamelCaseTypes {
97     fn get_lints(&self) -> LintArray {
98         lint_array!(NON_CAMEL_CASE_TYPES)
99     }
100 }
101
102 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
103     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
104         let extern_repr_count = it.attrs
105             .iter()
106             .filter(|attr| {
107                 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr)
108                     .iter()
109                     .any(|r| r == &attr::ReprExtern)
110             })
111             .count();
112         let has_extern_repr = extern_repr_count > 0;
113
114         if has_extern_repr {
115             return;
116         }
117
118         match it.node {
119             hir::ItemTy(..) |
120             hir::ItemStruct(..) |
121             hir::ItemUnion(..) => self.check_case(cx, "type", it.name, it.span),
122             hir::ItemTrait(..) => self.check_case(cx, "trait", it.name, it.span),
123             hir::ItemEnum(ref enum_definition, _) => {
124                 if has_extern_repr {
125                     return;
126                 }
127                 self.check_case(cx, "type", it.name, it.span);
128                 for variant in &enum_definition.variants {
129                     self.check_case(cx, "variant", variant.node.name, variant.span);
130                 }
131             }
132             _ => (),
133         }
134     }
135
136     fn check_generics(&mut self, cx: &LateContext, it: &hir::Generics) {
137         for gen in it.ty_params.iter() {
138             self.check_case(cx, "type parameter", gen.name, gen.span);
139         }
140     }
141 }
142
143 declare_lint! {
144     pub NON_SNAKE_CASE,
145     Warn,
146     "variables, methods, functions, lifetime parameters and modules should have snake case names"
147 }
148
149 #[derive(Copy, Clone)]
150 pub struct NonSnakeCase;
151
152 impl NonSnakeCase {
153     fn to_snake_case(mut str: &str) -> String {
154         let mut words = vec![];
155         // Preserve leading underscores
156         str = str.trim_left_matches(|c: char| {
157             if c == '_' {
158                 words.push(String::new());
159                 true
160             } else {
161                 false
162             }
163         });
164         for s in str.split('_') {
165             let mut last_upper = false;
166             let mut buf = String::new();
167             if s.is_empty() {
168                 continue;
169             }
170             for ch in s.chars() {
171                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
172                     words.push(buf);
173                     buf = String::new();
174                 }
175                 last_upper = ch.is_uppercase();
176                 buf.extend(ch.to_lowercase());
177             }
178             words.push(buf);
179         }
180         words.join("_")
181     }
182
183     fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
184         fn is_snake_case(ident: &str) -> bool {
185             if ident.is_empty() {
186                 return true;
187             }
188             let ident = ident.trim_left_matches('\'');
189             let ident = ident.trim_matches('_');
190
191             let mut allow_underscore = true;
192             ident.chars().all(|c| {
193                 allow_underscore = match c {
194                     '_' if !allow_underscore => return false,
195                     '_' => false,
196                     // It would be more obvious to use `c.is_lowercase()`,
197                     // but some characters do not have a lowercase form
198                     c if !c.is_uppercase() => true,
199                     _ => return false,
200                 };
201                 true
202             })
203         }
204
205         if !is_snake_case(name) {
206             let sc = NonSnakeCase::to_snake_case(name);
207             let msg = if sc != name {
208                 format!("{} `{}` should have a snake case name such as `{}`",
209                         sort,
210                         name,
211                         sc)
212             } else {
213                 format!("{} `{}` should have a snake case name", sort, name)
214             };
215             match span {
216                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
217                 None => cx.lint(NON_SNAKE_CASE, &msg),
218             }
219         }
220     }
221 }
222
223 impl LintPass for NonSnakeCase {
224     fn get_lints(&self) -> LintArray {
225         lint_array!(NON_SNAKE_CASE)
226     }
227 }
228
229 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
230     fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
231         let attr_crate_name = cr.attrs
232             .iter()
233             .find(|at| at.check_name("crate_name"))
234             .and_then(|at| at.value_str().map(|s| (at, s)));
235         if let Some(ref name) = cx.tcx.sess.opts.crate_name {
236             self.check_snake_case(cx, "crate", name, None);
237         } else if let Some((attr, name)) = attr_crate_name {
238             self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
239         }
240     }
241
242     fn check_fn(&mut self,
243                 cx: &LateContext,
244                 fk: FnKind,
245                 _: &hir::FnDecl,
246                 _: &hir::Body,
247                 span: Span,
248                 id: ast::NodeId) {
249         match fk {
250             FnKind::Method(name, ..) => {
251                 match method_context(cx, id, span) {
252                     MethodLateContext::PlainImpl => {
253                         self.check_snake_case(cx, "method", &name.as_str(), Some(span))
254                     }
255                     MethodLateContext::TraitDefaultImpl => {
256                         self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
257                     }
258                     _ => (),
259                 }
260             }
261             FnKind::ItemFn(name, ..) => {
262                 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
263             }
264             FnKind::Closure(_) => (),
265         }
266     }
267
268     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
269         if let hir::ItemMod(_) = it.node {
270             self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
271         }
272     }
273
274     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
275         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref names)) = item.node {
276             self.check_snake_case(cx,
277                                   "trait method",
278                                   &item.name.as_str(),
279                                   Some(item.span));
280             for name in names {
281                 self.check_snake_case(cx, "variable", &name.node.as_str(), Some(name.span));
282             }
283         }
284     }
285
286     fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) {
287         self.check_snake_case(cx,
288                               "lifetime",
289                               &t.lifetime.name.as_str(),
290                               Some(t.lifetime.span));
291     }
292
293     fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
294         if let &PatKind::Binding(_, _, ref path1, _) = &p.node {
295             self.check_snake_case(cx, "variable", &path1.node.as_str(), Some(p.span));
296         }
297     }
298
299     fn check_struct_def(&mut self,
300                         cx: &LateContext,
301                         s: &hir::VariantData,
302                         _: ast::Name,
303                         _: &hir::Generics,
304                         _: ast::NodeId) {
305         for sf in s.fields() {
306             self.check_snake_case(cx, "structure field", &sf.name.as_str(), Some(sf.span));
307         }
308     }
309 }
310
311 declare_lint! {
312     pub NON_UPPER_CASE_GLOBALS,
313     Warn,
314     "static constants should have uppercase identifiers"
315 }
316
317 #[derive(Copy, Clone)]
318 pub struct NonUpperCaseGlobals;
319
320 impl NonUpperCaseGlobals {
321     fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
322         if name.as_str().chars().any(|c| c.is_lowercase()) {
323             let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
324             if name != &*uc {
325                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
326                              span,
327                              &format!("{} `{}` should have an upper case name such as `{}`",
328                                       sort,
329                                       name,
330                                       uc));
331             } else {
332                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
333                              span,
334                              &format!("{} `{}` should have an upper case name", sort, name));
335             }
336         }
337     }
338 }
339
340 impl LintPass for NonUpperCaseGlobals {
341     fn get_lints(&self) -> LintArray {
342         lint_array!(NON_UPPER_CASE_GLOBALS)
343     }
344 }
345
346 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
347     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
348         match it.node {
349             hir::ItemStatic(..) => {
350                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
351             }
352             hir::ItemConst(..) => {
353                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
354             }
355             _ => {}
356         }
357     }
358
359     fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
360         match ti.node {
361             hir::TraitItemKind::Const(..) => {
362                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.name, ti.span);
363             }
364             _ => {}
365         }
366     }
367
368     fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
369         match ii.node {
370             hir::ImplItemKind::Const(..) => {
371                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.name, ii.span);
372             }
373             _ => {}
374         }
375     }
376
377     fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
378         // Lint for constants that look like binding identifiers (#7526)
379         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
380             if let Def::Const(..) = path.def {
381                 if path.segments.len() == 1 {
382                     NonUpperCaseGlobals::check_upper_case(cx,
383                                                           "constant in pattern",
384                                                           path.segments[0].name,
385                                                           path.span);
386                 }
387             }
388         }
389     }
390 }