]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/nonstandard_style.rs
Add riscv64gc-unknown-none-elf target
[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 #[derive(Copy, Clone)]
42 pub struct NonCamelCaseTypes;
43
44 impl NonCamelCaseTypes {
45     fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
46         fn char_has_case(c: char) -> bool {
47             c.is_lowercase() || c.is_uppercase()
48         }
49
50         fn is_camel_case(name: &str) -> bool {
51             let name = name.trim_matches('_');
52             if name.is_empty() {
53                 return true;
54             }
55
56             // start with a non-lowercase letter rather than non-uppercase
57             // ones (some scripts don't have a concept of upper/lowercase)
58             !name.is_empty() && !name.chars().next().unwrap().is_lowercase() &&
59                 !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
60                     // contains a capitalisable character followed by, or preceded by, an underscore
61                     char_has_case(pair[0]) && pair[1] == '_' ||
62                     char_has_case(pair[1]) && pair[0] == '_'
63                 })
64         }
65
66         fn to_camel_case(s: &str) -> String {
67             s.trim_matches('_')
68                 .split('_')
69                 .map(|word| {
70                     word.chars().enumerate().map(|(i, c)| if i == 0 {
71                         c.to_uppercase().collect::<String>()
72                     } else {
73                         c.to_lowercase().collect()
74                     })
75                     .collect::<String>()
76                 })
77                 .filter(|x| !x.is_empty())
78                 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
79                     // separate two components with an underscore if their boundary cannot
80                     // be distinguished using a uppercase/lowercase case distinction
81                     let join = if let Some(prev) = prev {
82                                     let l = prev.chars().last().unwrap();
83                                     let f = next.chars().next().unwrap();
84                                     !char_has_case(l) && !char_has_case(f)
85                                 } else { false };
86                     (acc + if join { "_" } else { "" } + &next, Some(next))
87                 }).0
88         }
89
90         let name = &ident.name.as_str();
91
92         if !is_camel_case(name) {
93             let c = to_camel_case(name);
94
95             let msg = format!("{} `{}` should have a camel case name", sort, name);
96             cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
97                 .span_suggestion(
98                     ident.span,
99                     "convert the identifier to camel case",
100                     c,
101                     Applicability::MaybeIncorrect,
102                 )
103                 .emit();
104         }
105     }
106 }
107
108 impl LintPass for NonCamelCaseTypes {
109     fn name(&self) -> &'static str {
110         "NonCamelCaseTypes"
111     }
112
113     fn get_lints(&self) -> LintArray {
114         lint_array!(NON_CAMEL_CASE_TYPES)
115     }
116 }
117
118 impl EarlyLintPass for NonCamelCaseTypes {
119     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
120         let has_repr_c = it.attrs
121             .iter()
122             .any(|attr| {
123                 attr::find_repr_attrs(&cx.sess.parse_sess, attr)
124                     .iter()
125                     .any(|r| r == &attr::ReprC)
126             });
127
128         if has_repr_c {
129             return;
130         }
131
132         match it.node {
133             ast::ItemKind::Ty(..) |
134             ast::ItemKind::Enum(..) |
135             ast::ItemKind::Struct(..) |
136             ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
137             ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
138             _ => (),
139         }
140     }
141
142     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
143         self.check_case(cx, "variant", &v.node.ident);
144     }
145
146     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
147         if let ast::GenericParamKind::Type { .. } = param.kind {
148             self.check_case(cx, "type parameter", &param.ident);
149         }
150     }
151 }
152
153 declare_lint! {
154     pub NON_SNAKE_CASE,
155     Warn,
156     "variables, methods, functions, lifetime parameters and modules should have snake case names"
157 }
158
159 #[derive(Copy, Clone)]
160 pub struct NonSnakeCase;
161
162 impl NonSnakeCase {
163     fn to_snake_case(mut str: &str) -> String {
164         let mut words = vec![];
165         // Preserve leading underscores
166         str = str.trim_start_matches(|c: char| {
167             if c == '_' {
168                 words.push(String::new());
169                 true
170             } else {
171                 false
172             }
173         });
174         for s in str.split('_') {
175             let mut last_upper = false;
176             let mut buf = String::new();
177             if s.is_empty() {
178                 continue;
179             }
180             for ch in s.chars() {
181                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
182                     words.push(buf);
183                     buf = String::new();
184                 }
185                 last_upper = ch.is_uppercase();
186                 buf.extend(ch.to_lowercase());
187             }
188             words.push(buf);
189         }
190         words.join("_")
191     }
192
193     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
194     fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
195         fn is_snake_case(ident: &str) -> bool {
196             if ident.is_empty() {
197                 return true;
198             }
199             let ident = ident.trim_start_matches('\'');
200             let ident = ident.trim_matches('_');
201
202             let mut allow_underscore = true;
203             ident.chars().all(|c| {
204                 allow_underscore = match c {
205                     '_' if !allow_underscore => return false,
206                     '_' => false,
207                     // It would be more obvious to use `c.is_lowercase()`,
208                     // but some characters do not have a lowercase form
209                     c if !c.is_uppercase() => true,
210                     _ => return false,
211                 };
212                 true
213             })
214         }
215
216         let name = &ident.name.as_str();
217
218         if !is_snake_case(name) {
219             let sc = NonSnakeCase::to_snake_case(name);
220
221             let msg = format!("{} `{}` should have a snake case name", sort, name);
222             let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
223
224             // We have a valid span in almost all cases, but we don't have one when linting a crate
225             // name provided via the command line.
226             if !ident.span.is_dummy() {
227                 err.span_suggestion(
228                     ident.span,
229                     "convert the identifier to snake case",
230                     sc,
231                     Applicability::MaybeIncorrect,
232                 );
233             } else {
234                 err.help(&format!("convert the identifier to snake case: `{}`", sc));
235             }
236
237             err.emit();
238         }
239     }
240 }
241
242 impl LintPass for NonSnakeCase {
243     fn name(&self) -> &'static str {
244         "NonSnakeCase"
245     }
246
247     fn get_lints(&self) -> LintArray {
248         lint_array!(NON_SNAKE_CASE)
249     }
250 }
251
252 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
253     fn check_crate(&mut self, cx: &LateContext<'_, '_>, cr: &hir::Crate) {
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(&cr.attrs, "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.node {
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: ast::NodeId,
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, "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.node {
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.node {
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.node {
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         _: ast::Name,
354         _: &hir::Generics,
355         _: ast::NodeId,
356     ) {
357         for sf in s.fields() {
358             self.check_snake_case(cx, "structure field", &sf.ident);
359         }
360     }
361 }
362
363 declare_lint! {
364     pub NON_UPPER_CASE_GLOBALS,
365     Warn,
366     "static constants should have uppercase identifiers"
367 }
368
369 #[derive(Copy, Clone)]
370 pub struct NonUpperCaseGlobals;
371
372 impl NonUpperCaseGlobals {
373     fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
374         let name = &ident.name.as_str();
375
376         if name.chars().any(|c| c.is_lowercase()) {
377             let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
378
379             let msg = format!("{} `{}` should have an upper case name", sort, name);
380             cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
381                 .span_suggestion(
382                     ident.span,
383                     "convert the identifier to upper case",
384                     uc,
385                     Applicability::MaybeIncorrect,
386                 )
387                 .emit();
388         }
389     }
390 }
391
392 impl LintPass for NonUpperCaseGlobals {
393     fn name(&self) -> &'static str {
394         "NonUpperCaseGlobals"
395     }
396
397     fn get_lints(&self) -> LintArray {
398         lint_array!(NON_UPPER_CASE_GLOBALS)
399     }
400 }
401
402 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
403     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
404         match it.node {
405             hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
406                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
407             }
408             hir::ItemKind::Const(..) => {
409                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
410             }
411             _ => {}
412         }
413     }
414
415     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
416         if let hir::TraitItemKind::Const(..) = ti.node {
417             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
418         }
419     }
420
421     fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
422         if let hir::ImplItemKind::Const(..) = ii.node {
423             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
424         }
425     }
426
427     fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
428         // Lint for constants that look like binding identifiers (#7526)
429         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
430             if let Def::Const(..) = path.def {
431                 if path.segments.len() == 1 {
432                     NonUpperCaseGlobals::check_upper_case(
433                         cx,
434                         "constant in pattern",
435                         &path.segments[0].ident
436                     );
437                 }
438             }
439         }
440     }
441 }