]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/nonstandard_style.rs
Fix rebase issue
[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::lint;
5 use rustc::ty;
6 use rustc_target::spec::abi::Abi;
7 use lint::{EarlyContext, LateContext, LintContext, LintArray};
8 use lint::{EarlyLintPass, LintPass, LateLintPass};
9 use syntax::ast;
10 use syntax::attr;
11 use syntax::errors::Applicability;
12 use syntax_pos::{BytePos, symbol::Ident, Span};
13
14 #[derive(PartialEq)]
15 pub enum MethodLateContext {
16     TraitAutoImpl,
17     TraitImpl,
18     PlainImpl,
19 }
20
21 pub fn method_context(cx: &LateContext<'_, '_>, id: ast::NodeId) -> MethodLateContext {
22     let def_id = cx.tcx.hir().local_def_id(id);
23     let item = cx.tcx.associated_item(def_id);
24     match item.container {
25         ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
26         ty::ImplContainer(cid) => {
27             match cx.tcx.impl_trait_ref(cid) {
28                 Some(_) => MethodLateContext::TraitImpl,
29                 None => MethodLateContext::PlainImpl,
30             }
31         }
32     }
33 }
34
35 declare_lint! {
36     pub NON_CAMEL_CASE_TYPES,
37     Warn,
38     "types, variants, traits and type parameters should have camel case names"
39 }
40
41 fn char_has_case(c: char) -> bool {
42     c.is_lowercase() || c.is_uppercase()
43 }
44
45 fn is_camel_case(name: &str) -> bool {
46     let name = name.trim_matches('_');
47     if name.is_empty() {
48         return true;
49     }
50
51     // start with a non-lowercase letter rather than non-uppercase
52     // ones (some scripts don't have a concept of upper/lowercase)
53     !name.chars().next().unwrap().is_lowercase()
54         && !name.contains("__")
55         && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
56             // contains a capitalisable character followed by, or preceded by, an underscore
57             char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_'
58         })
59 }
60
61 fn to_camel_case(s: &str) -> String {
62     s.trim_matches('_')
63         .split('_')
64         .filter(|component| !component.is_empty())
65         .map(|component| {
66             let mut camel_cased_component = String::new();
67
68             let mut new_word = true;
69             let mut prev_is_lower_case = true;
70
71             for c in component.chars() {
72                 // Preserve the case if an uppercase letter follows a lowercase letter, so that
73                 // `camelCase` is converted to `CamelCase`.
74                 if prev_is_lower_case && c.is_uppercase() {
75                     new_word = true;
76                 }
77
78                 if new_word {
79                     camel_cased_component.push_str(&c.to_uppercase().to_string());
80                 } else {
81                     camel_cased_component.push_str(&c.to_lowercase().to_string());
82                 }
83
84                 prev_is_lower_case = c.is_lowercase();
85                 new_word = false;
86             }
87
88             camel_cased_component
89         })
90         .fold(
91             (String::new(), None),
92             |(acc, prev): (String, Option<String>), next| {
93                 // separate two components with an underscore if their boundary cannot
94                 // be distinguished using a uppercase/lowercase case distinction
95                 let join = if let Some(prev) = prev {
96                     let l = prev.chars().last().unwrap();
97                     let f = next.chars().next().unwrap();
98                     !char_has_case(l) && !char_has_case(f)
99                 } else {
100                     false
101                 };
102                 (acc + if join { "_" } else { "" } + &next, Some(next))
103             },
104         )
105         .0
106 }
107
108 #[derive(Copy, Clone)]
109 pub struct NonCamelCaseTypes;
110
111 impl NonCamelCaseTypes {
112     fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
113         let name = &ident.name.as_str();
114
115         if !is_camel_case(name) {
116             let msg = format!("{} `{}` should have an upper camel case name", sort, name);
117             cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
118                 .span_suggestion(
119                     ident.span,
120                     "convert the identifier to upper camel case",
121                     to_camel_case(name),
122                     Applicability::MaybeIncorrect,
123                 )
124                 .emit();
125         }
126     }
127 }
128
129 impl LintPass for NonCamelCaseTypes {
130     fn name(&self) -> &'static str {
131         "NonCamelCaseTypes"
132     }
133
134     fn get_lints(&self) -> LintArray {
135         lint_array!(NON_CAMEL_CASE_TYPES)
136     }
137 }
138
139 impl EarlyLintPass for NonCamelCaseTypes {
140     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
141         let has_repr_c = it.attrs
142             .iter()
143             .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
144
145         if has_repr_c {
146             return;
147         }
148
149         match it.node {
150             ast::ItemKind::Ty(..) |
151             ast::ItemKind::Enum(..) |
152             ast::ItemKind::Struct(..) |
153             ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
154             ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
155             _ => (),
156         }
157     }
158
159     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
160         self.check_case(cx, "variant", &v.node.ident);
161     }
162
163     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
164         if let ast::GenericParamKind::Type { .. } = param.kind {
165             self.check_case(cx, "type parameter", &param.ident);
166         }
167     }
168 }
169
170 declare_lint! {
171     pub NON_SNAKE_CASE,
172     Warn,
173     "variables, methods, functions, lifetime parameters and modules should have snake case names"
174 }
175
176 #[derive(Copy, Clone)]
177 pub struct NonSnakeCase;
178
179 impl NonSnakeCase {
180     fn to_snake_case(mut str: &str) -> String {
181         let mut words = vec![];
182         // Preserve leading underscores
183         str = str.trim_start_matches(|c: char| {
184             if c == '_' {
185                 words.push(String::new());
186                 true
187             } else {
188                 false
189             }
190         });
191         for s in str.split('_') {
192             let mut last_upper = false;
193             let mut buf = String::new();
194             if s.is_empty() {
195                 continue;
196             }
197             for ch in s.chars() {
198                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
199                     words.push(buf);
200                     buf = String::new();
201                 }
202                 last_upper = ch.is_uppercase();
203                 buf.extend(ch.to_lowercase());
204             }
205             words.push(buf);
206         }
207         words.join("_")
208     }
209
210     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
211     fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
212         fn is_snake_case(ident: &str) -> bool {
213             if ident.is_empty() {
214                 return true;
215             }
216             let ident = ident.trim_start_matches('\'');
217             let ident = ident.trim_matches('_');
218
219             let mut allow_underscore = true;
220             ident.chars().all(|c| {
221                 allow_underscore = match c {
222                     '_' if !allow_underscore => return false,
223                     '_' => false,
224                     // It would be more obvious to use `c.is_lowercase()`,
225                     // but some characters do not have a lowercase form
226                     c if !c.is_uppercase() => true,
227                     _ => return false,
228                 };
229                 true
230             })
231         }
232
233         let name = &ident.name.as_str();
234
235         if !is_snake_case(name) {
236             let sc = NonSnakeCase::to_snake_case(name);
237
238             let msg = format!("{} `{}` should have a snake case name", sort, name);
239             let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
240
241             // We have a valid span in almost all cases, but we don't have one when linting a crate
242             // name provided via the command line.
243             if !ident.span.is_dummy() {
244                 err.span_suggestion(
245                     ident.span,
246                     "convert the identifier to snake case",
247                     sc,
248                     Applicability::MaybeIncorrect,
249                 );
250             } else {
251                 err.help(&format!("convert the identifier to snake case: `{}`", sc));
252             }
253
254             err.emit();
255         }
256     }
257 }
258
259 impl LintPass for NonSnakeCase {
260     fn name(&self) -> &'static str {
261         "NonSnakeCase"
262     }
263
264     fn get_lints(&self) -> LintArray {
265         lint_array!(NON_SNAKE_CASE)
266     }
267 }
268
269 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
270     fn check_crate(&mut self, cx: &LateContext<'_, '_>, cr: &hir::Crate) {
271         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
272             Some(Ident::from_str(name))
273         } else {
274             attr::find_by_name(&cr.attrs, "crate_name")
275                 .and_then(|attr| attr.meta())
276                 .and_then(|meta| {
277                     meta.name_value_literal().and_then(|lit| {
278                         if let ast::LitKind::Str(name, ..) = lit.node {
279                             // Discard the double quotes surrounding the literal.
280                             let sp = cx.sess().source_map().span_to_snippet(lit.span)
281                                 .ok()
282                                 .and_then(|snippet| {
283                                     let left = snippet.find('"')?;
284                                     let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
285
286                                     Some(
287                                         lit.span
288                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
289                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
290                                     )
291                                 })
292                                 .unwrap_or_else(|| lit.span);
293
294                             Some(Ident::new(name, sp))
295                         } else {
296                             None
297                         }
298                     })
299                 })
300         };
301
302         if let Some(ident) = &crate_ident {
303             self.check_snake_case(cx, "crate", ident);
304         }
305     }
306
307     fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
308         if let GenericParamKind::Lifetime { .. } = param.kind {
309             self.check_snake_case(cx, "lifetime", &param.name.ident());
310         }
311     }
312
313     fn check_fn(
314         &mut self,
315         cx: &LateContext<'_, '_>,
316         fk: FnKind<'_>,
317         _: &hir::FnDecl,
318         _: &hir::Body,
319         _: Span,
320         id: ast::NodeId,
321     ) {
322         match &fk {
323             FnKind::Method(ident, ..) => {
324                 match method_context(cx, id) {
325                     MethodLateContext::PlainImpl => {
326                         self.check_snake_case(cx, "method", ident);
327                     }
328                     MethodLateContext::TraitAutoImpl => {
329                         self.check_snake_case(cx, "trait method", ident);
330                     }
331                     _ => (),
332                 }
333             }
334             FnKind::ItemFn(ident, _, header, _, attrs) => {
335                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
336                 if header.abi != Abi::Rust && attr::contains_name(attrs, "no_mangle") {
337                     return;
338                 }
339                 self.check_snake_case(cx, "function", ident);
340             }
341             FnKind::Closure(_) => (),
342         }
343     }
344
345     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
346         if let hir::ItemKind::Mod(_) = it.node {
347             self.check_snake_case(cx, "module", &it.ident);
348         }
349     }
350
351     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) {
352         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node {
353             self.check_snake_case(cx, "trait method", &item.ident);
354             for param_name in pnames {
355                 self.check_snake_case(cx, "variable", param_name);
356             }
357         }
358     }
359
360     fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
361         if let &PatKind::Binding(_, _, _, ident, _) = &p.node {
362             self.check_snake_case(cx, "variable", &ident);
363         }
364     }
365
366     fn check_struct_def(
367         &mut self,
368         cx: &LateContext<'_, '_>,
369         s: &hir::VariantData,
370         _: ast::Name,
371         _: &hir::Generics,
372         _: ast::NodeId,
373     ) {
374         for sf in s.fields() {
375             self.check_snake_case(cx, "structure field", &sf.ident);
376         }
377     }
378 }
379
380 declare_lint! {
381     pub NON_UPPER_CASE_GLOBALS,
382     Warn,
383     "static constants should have uppercase identifiers"
384 }
385
386 #[derive(Copy, Clone)]
387 pub struct NonUpperCaseGlobals;
388
389 impl NonUpperCaseGlobals {
390     fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
391         let name = &ident.name.as_str();
392
393         if name.chars().any(|c| c.is_lowercase()) {
394             let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
395
396             let msg = format!("{} `{}` should have an upper case name", sort, name);
397             cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
398                 .span_suggestion(
399                     ident.span,
400                     "convert the identifier to upper case",
401                     uc,
402                     Applicability::MaybeIncorrect,
403                 )
404                 .emit();
405         }
406     }
407 }
408
409 impl LintPass for NonUpperCaseGlobals {
410     fn name(&self) -> &'static str {
411         "NonUpperCaseGlobals"
412     }
413
414     fn get_lints(&self) -> LintArray {
415         lint_array!(NON_UPPER_CASE_GLOBALS)
416     }
417 }
418
419 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
420     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
421         match it.node {
422             hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
423                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
424             }
425             hir::ItemKind::Const(..) => {
426                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
427             }
428             _ => {}
429         }
430     }
431
432     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
433         if let hir::TraitItemKind::Const(..) = ti.node {
434             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
435         }
436     }
437
438     fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
439         if let hir::ImplItemKind::Const(..) = ii.node {
440             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
441         }
442     }
443
444     fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
445         // Lint for constants that look like binding identifiers (#7526)
446         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
447             if let Def::Const(..) = path.def {
448                 if path.segments.len() == 1 {
449                     NonUpperCaseGlobals::check_upper_case(
450                         cx,
451                         "constant in pattern",
452                         &path.segments[0].ident
453                     );
454                 }
455             }
456         }
457     }
458
459     fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
460         if let GenericParamKind::Const { .. } = param.kind {
461             NonUpperCaseGlobals::check_upper_case(
462                 cx,
463                 "const parameter",
464                 &param.name.ident(),
465             );
466         }
467     }
468 }
469
470 #[cfg(test)]
471 mod tests {
472     use super::{is_camel_case, to_camel_case};
473
474     #[test]
475     fn camel_case() {
476         assert!(!is_camel_case("userData"));
477         assert_eq!(to_camel_case("userData"), "UserData");
478
479         assert!(is_camel_case("X86_64"));
480
481         assert!(!is_camel_case("X86__64"));
482         assert_eq!(to_camel_case("X86__64"), "X86_64");
483
484         assert!(!is_camel_case("Abc_123"));
485         assert_eq!(to_camel_case("Abc_123"), "Abc123");
486
487         assert!(!is_camel_case("A1_b2_c3"));
488         assert_eq!(to_camel_case("A1_b2_c3"), "A1B2C3");
489
490         assert!(!is_camel_case("ONE_TWO_THREE"));
491         assert_eq!(to_camel_case("ONE_TWO_THREE"), "OneTwoThree");
492     }
493 }