]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/bad_style.rs
Use assert_eq! in copy_from_slice
[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 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             if name.is_empty() {
63                 return true;
64             }
65             let name = name.trim_matches('_');
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::<Vec<_>>()
87                     .concat()
88                 })
89                 .filter(|x| !x.is_empty())
90                 .collect::<Vec<_>>()
91                 .iter().fold((String::new(), None), |(acc, prev): (String, Option<&String>), next| {
92                     // separate two components with an underscore if their boundary cannot
93                     // be distinguished using a uppercase/lowercase case distinction
94                     let join = if let Some(prev) = prev {
95                                     let l = prev.chars().last().unwrap();
96                                     let f = next.chars().next().unwrap();
97                                     !char_has_case(l) && !char_has_case(f)
98                                 } else { false };
99                     (acc + if join { "_" } else { "" } + next, Some(next))
100                 }).0
101         }
102
103         if !is_camel_case(name) {
104             let c = to_camel_case(&name.as_str());
105             let m = if c.is_empty() {
106                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, name)
107             } else {
108                 format!("{} `{}` should have a camel case name such as `{}`", sort, name, c)
109             };
110             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m);
111         }
112     }
113 }
114
115 impl LintPass for NonCamelCaseTypes {
116     fn get_lints(&self) -> LintArray {
117         lint_array!(NON_CAMEL_CASE_TYPES)
118     }
119 }
120
121 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes {
122     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
123         let has_repr_c = it.attrs
124             .iter()
125             .any(|attr| {
126                 attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr)
127                     .iter()
128                     .any(|r| r == &attr::ReprC)
129             });
130
131         if has_repr_c {
132             return;
133         }
134
135         match it.node {
136             hir::ItemTy(..) |
137             hir::ItemEnum(..) |
138             hir::ItemStruct(..) |
139             hir::ItemUnion(..) => self.check_case(cx, "type", it.name, it.span),
140             hir::ItemTrait(..) => self.check_case(cx, "trait", it.name, it.span),
141             _ => (),
142         }
143     }
144
145     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
146         self.check_case(cx, "variant", v.node.name, v.span);
147     }
148
149     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
150         match param.kind {
151             GenericParamKind::Lifetime { .. } => {}
152             GenericParamKind::Type { synthetic, .. } => {
153                 if synthetic.is_none() {
154                     self.check_case(cx, "type parameter", param.name.name(), param.span);
155                 }
156             }
157         }
158     }
159 }
160
161 declare_lint! {
162     pub NON_SNAKE_CASE,
163     Warn,
164     "variables, methods, functions, lifetime parameters and modules should have snake case names"
165 }
166
167 #[derive(Copy, Clone)]
168 pub struct NonSnakeCase;
169
170 impl NonSnakeCase {
171     fn to_snake_case(mut str: &str) -> String {
172         let mut words = vec![];
173         // Preserve leading underscores
174         str = str.trim_left_matches(|c: char| {
175             if c == '_' {
176                 words.push(String::new());
177                 true
178             } else {
179                 false
180             }
181         });
182         for s in str.split('_') {
183             let mut last_upper = false;
184             let mut buf = String::new();
185             if s.is_empty() {
186                 continue;
187             }
188             for ch in s.chars() {
189                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
190                     words.push(buf);
191                     buf = String::new();
192                 }
193                 last_upper = ch.is_uppercase();
194                 buf.extend(ch.to_lowercase());
195             }
196             words.push(buf);
197         }
198         words.join("_")
199     }
200
201     fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
202         fn is_snake_case(ident: &str) -> bool {
203             if ident.is_empty() {
204                 return true;
205             }
206             let ident = ident.trim_left_matches('\'');
207             let ident = ident.trim_matches('_');
208
209             let mut allow_underscore = true;
210             ident.chars().all(|c| {
211                 allow_underscore = match c {
212                     '_' if !allow_underscore => return false,
213                     '_' => false,
214                     // It would be more obvious to use `c.is_lowercase()`,
215                     // but some characters do not have a lowercase form
216                     c if !c.is_uppercase() => true,
217                     _ => return false,
218                 };
219                 true
220             })
221         }
222
223         if !is_snake_case(name) {
224             let sc = NonSnakeCase::to_snake_case(name);
225             let msg = if sc != name {
226                 format!("{} `{}` should have a snake case name such as `{}`",
227                         sort,
228                         name,
229                         sc)
230             } else {
231                 format!("{} `{}` should have a snake case name", sort, name)
232             };
233             match span {
234                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
235                 None => cx.lint(NON_SNAKE_CASE, &msg),
236             }
237         }
238     }
239 }
240
241 impl LintPass for NonSnakeCase {
242     fn get_lints(&self) -> LintArray {
243         lint_array!(NON_SNAKE_CASE)
244     }
245 }
246
247 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
248     fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
249         let attr_crate_name = attr::find_by_name(&cr.attrs, "crate_name")
250             .and_then(|at| at.value_str().map(|s| (at, s)));
251         if let Some(ref name) = cx.tcx.sess.opts.crate_name {
252             self.check_snake_case(cx, "crate", name, None);
253         } else if let Some((attr, name)) = attr_crate_name {
254             self.check_snake_case(cx, "crate", &name.as_str(), Some(attr.span));
255         }
256     }
257
258     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
259         match param.kind {
260             GenericParamKind::Lifetime { .. } => {
261                 let name = param.name.name().as_str();
262                 self.check_snake_case(cx, "lifetime", &name, Some(param.span));
263             }
264             GenericParamKind::Type { .. } => {}
265         }
266     }
267
268     fn check_fn(&mut self,
269                 cx: &LateContext,
270                 fk: FnKind,
271                 _: &hir::FnDecl,
272                 _: &hir::Body,
273                 span: Span,
274                 id: ast::NodeId) {
275         match fk {
276             FnKind::Method(name, ..) => {
277                 match method_context(cx, id) {
278                     MethodLateContext::PlainImpl => {
279                         self.check_snake_case(cx, "method", &name.as_str(), Some(span))
280                     }
281                     MethodLateContext::TraitAutoImpl => {
282                         self.check_snake_case(cx, "trait method", &name.as_str(), Some(span))
283                     }
284                     _ => (),
285                 }
286             }
287             FnKind::ItemFn(name, _, header, _, attrs) => {
288                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
289                 if header.abi != Abi::Rust && attr::find_by_name(attrs, "no_mangle").is_some() {
290                     return;
291                 }
292                 self.check_snake_case(cx, "function", &name.as_str(), Some(span))
293             }
294             FnKind::Closure(_) => (),
295         }
296     }
297
298     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
299         if let hir::ItemMod(_) = it.node {
300             self.check_snake_case(cx, "module", &it.name.as_str(), Some(it.span));
301         }
302     }
303
304     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
305         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(ref names)) = item.node {
306             self.check_snake_case(cx,
307                                   "trait method",
308                                   &item.name.as_str(),
309                                   Some(item.span));
310             for name in names {
311                 self.check_snake_case(cx, "variable", &name.node.as_str(), Some(name.span));
312             }
313         }
314     }
315
316     fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
317         if let &PatKind::Binding(_, _, ref path1, _) = &p.node {
318             self.check_snake_case(cx, "variable", &path1.node.as_str(), Some(p.span));
319         }
320     }
321
322     fn check_struct_def(&mut self,
323                         cx: &LateContext,
324                         s: &hir::VariantData,
325                         _: ast::Name,
326                         _: &hir::Generics,
327                         _: ast::NodeId) {
328         for sf in s.fields() {
329             self.check_snake_case(cx, "structure field", &sf.ident.as_str(), Some(sf.span));
330         }
331     }
332 }
333
334 declare_lint! {
335     pub NON_UPPER_CASE_GLOBALS,
336     Warn,
337     "static constants should have uppercase identifiers"
338 }
339
340 #[derive(Copy, Clone)]
341 pub struct NonUpperCaseGlobals;
342
343 impl NonUpperCaseGlobals {
344     fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) {
345         if name.as_str().chars().any(|c| c.is_lowercase()) {
346             let uc = NonSnakeCase::to_snake_case(&name.as_str()).to_uppercase();
347             if name != &*uc {
348                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
349                              span,
350                              &format!("{} `{}` should have an upper case name such as `{}`",
351                                       sort,
352                                       name,
353                                       uc));
354             } else {
355                 cx.span_lint(NON_UPPER_CASE_GLOBALS,
356                              span,
357                              &format!("{} `{}` should have an upper case name", sort, name));
358             }
359         }
360     }
361 }
362
363 impl LintPass for NonUpperCaseGlobals {
364     fn get_lints(&self) -> LintArray {
365         lint_array!(NON_UPPER_CASE_GLOBALS)
366     }
367 }
368
369 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
370     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
371         match it.node {
372             hir::ItemStatic(..) => {
373                 if attr::find_by_name(&it.attrs, "no_mangle").is_some() {
374                     return;
375                 }
376                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", it.name, it.span);
377             }
378             hir::ItemConst(..) => {
379                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.name, it.span);
380             }
381             _ => {}
382         }
383     }
384
385     fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
386         match ti.node {
387             hir::TraitItemKind::Const(..) => {
388                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.name, ti.span);
389             }
390             _ => {}
391         }
392     }
393
394     fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
395         match ii.node {
396             hir::ImplItemKind::Const(..) => {
397                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.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].name,
411                                                           path.span);
412                 }
413             }
414         }
415     }
416 }