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