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