]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/nonstandard_style.rs
Rollup merge of #67566 - Mark-Simulacrum:thread-id-u64, r=alexcrichton
[rust.git] / src / librustc_lint / nonstandard_style.rs
1 use lint::{EarlyContext, LateContext, LintArray, LintContext};
2 use lint::{EarlyLintPass, LateLintPass, LintPass};
3 use rustc::hir::intravisit::FnKind;
4 use rustc::lint;
5 use rustc::ty;
6 use rustc_hir as hir;
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::{GenericParamKind, PatKind};
9 use rustc_span::symbol::sym;
10 use rustc_span::{symbol::Ident, BytePos, Span};
11 use rustc_target::spec::abi::Abi;
12 use syntax::ast;
13 use syntax::attr;
14 use syntax::errors::Applicability;
15
16 #[derive(PartialEq)]
17 pub enum MethodLateContext {
18     TraitAutoImpl,
19     TraitImpl,
20     PlainImpl,
21 }
22
23 pub fn method_context(cx: &LateContext<'_, '_>, id: hir::HirId) -> MethodLateContext {
24     let def_id = cx.tcx.hir().local_def_id(id);
25     let item = cx.tcx.associated_item(def_id);
26     match item.container {
27         ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
28         ty::ImplContainer(cid) => match cx.tcx.impl_trait_ref(cid) {
29             Some(_) => MethodLateContext::TraitImpl,
30             None => MethodLateContext::PlainImpl,
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((String::new(), None), |(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         .0
105 }
106
107 impl NonCamelCaseTypes {
108     fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
109         let name = &ident.name.as_str();
110
111         if !is_camel_case(name) {
112             let msg = format!("{} `{}` should have an upper camel case name", sort, name);
113             cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
114                 .span_suggestion(
115                     ident.span,
116                     "convert the identifier to upper camel case",
117                     to_camel_case(name),
118                     Applicability::MaybeIncorrect,
119                 )
120                 .emit();
121         }
122     }
123 }
124
125 impl EarlyLintPass for NonCamelCaseTypes {
126     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
127         let has_repr_c = it
128             .attrs
129             .iter()
130             .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
131
132         if has_repr_c {
133             return;
134         }
135
136         match it.kind {
137             ast::ItemKind::TyAlias(..)
138             | ast::ItemKind::Enum(..)
139             | ast::ItemKind::Struct(..)
140             | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
141             ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
142             _ => (),
143         }
144     }
145
146     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
147         self.check_case(cx, "variant", &v.ident);
148     }
149
150     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
151         if let ast::GenericParamKind::Type { .. } = param.kind {
152             self.check_case(cx, "type parameter", &param.ident);
153         }
154     }
155 }
156
157 declare_lint! {
158     pub NON_SNAKE_CASE,
159     Warn,
160     "variables, methods, functions, lifetime parameters and modules should have snake case names"
161 }
162
163 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
164
165 impl NonSnakeCase {
166     fn to_snake_case(mut str: &str) -> String {
167         let mut words = vec![];
168         // Preserve leading underscores
169         str = str.trim_start_matches(|c: char| {
170             if c == '_' {
171                 words.push(String::new());
172                 true
173             } else {
174                 false
175             }
176         });
177         for s in str.split('_') {
178             let mut last_upper = false;
179             let mut buf = String::new();
180             if s.is_empty() {
181                 continue;
182             }
183             for ch in s.chars() {
184                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
185                     words.push(buf);
186                     buf = String::new();
187                 }
188                 last_upper = ch.is_uppercase();
189                 buf.extend(ch.to_lowercase());
190             }
191             words.push(buf);
192         }
193         words.join("_")
194     }
195
196     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
197     fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
198         fn is_snake_case(ident: &str) -> bool {
199             if ident.is_empty() {
200                 return true;
201             }
202             let ident = ident.trim_start_matches('\'');
203             let ident = ident.trim_matches('_');
204
205             let mut allow_underscore = true;
206             ident.chars().all(|c| {
207                 allow_underscore = match c {
208                     '_' if !allow_underscore => return false,
209                     '_' => false,
210                     // It would be more obvious to use `c.is_lowercase()`,
211                     // but some characters do not have a lowercase form
212                     c if !c.is_uppercase() => true,
213                     _ => return false,
214                 };
215                 true
216             })
217         }
218
219         let name = &ident.name.as_str();
220
221         if !is_snake_case(name) {
222             let sc = NonSnakeCase::to_snake_case(name);
223
224             let msg = format!("{} `{}` should have a snake case name", sort, name);
225             let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
226
227             // We have a valid span in almost all cases, but we don't have one when linting a crate
228             // name provided via the command line.
229             if !ident.span.is_dummy() {
230                 err.span_suggestion(
231                     ident.span,
232                     "convert the identifier to snake case",
233                     sc,
234                     Applicability::MaybeIncorrect,
235                 );
236             } else {
237                 err.help(&format!("convert the identifier to snake case: `{}`", sc));
238             }
239
240             err.emit();
241         }
242     }
243 }
244
245 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
246     fn check_mod(
247         &mut self,
248         cx: &LateContext<'_, '_>,
249         _: &'tcx hir::Mod<'tcx>,
250         _: Span,
251         id: hir::HirId,
252     ) {
253         if id != hir::CRATE_HIR_ID {
254             return;
255         }
256
257         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
258             Some(Ident::from_str(name))
259         } else {
260             attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
261                 .and_then(|attr| attr.meta())
262                 .and_then(|meta| {
263                     meta.name_value_literal().and_then(|lit| {
264                         if let ast::LitKind::Str(name, ..) = lit.kind {
265                             // Discard the double quotes surrounding the literal.
266                             let sp = cx
267                                 .sess()
268                                 .source_map()
269                                 .span_to_snippet(lit.span)
270                                 .ok()
271                                 .and_then(|snippet| {
272                                     let left = snippet.find('"')?;
273                                     let right =
274                                         snippet.rfind('"').map(|pos| snippet.len() - pos)?;
275
276                                     Some(
277                                         lit.span
278                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
279                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
280                                     )
281                                 })
282                                 .unwrap_or_else(|| lit.span);
283
284                             Some(Ident::new(name, sp))
285                         } else {
286                             None
287                         }
288                     })
289                 })
290         };
291
292         if let Some(ident) = &crate_ident {
293             self.check_snake_case(cx, "crate", ident);
294         }
295     }
296
297     fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
298         if let GenericParamKind::Lifetime { .. } = param.kind {
299             self.check_snake_case(cx, "lifetime", &param.name.ident());
300         }
301     }
302
303     fn check_fn(
304         &mut self,
305         cx: &LateContext<'_, '_>,
306         fk: FnKind<'_>,
307         _: &hir::FnDecl<'_>,
308         _: &hir::Body<'_>,
309         _: Span,
310         id: hir::HirId,
311     ) {
312         match &fk {
313             FnKind::Method(ident, ..) => match method_context(cx, id) {
314                 MethodLateContext::PlainImpl => {
315                     self.check_snake_case(cx, "method", ident);
316                 }
317                 MethodLateContext::TraitAutoImpl => {
318                     self.check_snake_case(cx, "trait method", ident);
319                 }
320                 _ => (),
321             },
322             FnKind::ItemFn(ident, _, header, _, attrs) => {
323                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
324                 if header.abi != Abi::Rust && attr::contains_name(attrs, sym::no_mangle) {
325                     return;
326                 }
327                 self.check_snake_case(cx, "function", ident);
328             }
329             FnKind::Closure(_) => (),
330         }
331     }
332
333     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
334         if let hir::ItemKind::Mod(_) = it.kind {
335             self.check_snake_case(cx, "module", &it.ident);
336         }
337     }
338
339     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) {
340         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = item.kind {
341             self.check_snake_case(cx, "trait method", &item.ident);
342             for param_name in pnames {
343                 self.check_snake_case(cx, "variable", param_name);
344             }
345         }
346     }
347
348     fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
349         if let &PatKind::Binding(_, _, ident, _) = &p.kind {
350             self.check_snake_case(cx, "variable", &ident);
351         }
352     }
353
354     fn check_struct_def(&mut self, cx: &LateContext<'_, '_>, s: &hir::VariantData<'_>) {
355         for sf in s.fields() {
356             self.check_snake_case(cx, "structure field", &sf.ident);
357         }
358     }
359 }
360
361 declare_lint! {
362     pub NON_UPPER_CASE_GLOBALS,
363     Warn,
364     "static constants should have uppercase identifiers"
365 }
366
367 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
368
369 impl NonUpperCaseGlobals {
370     fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
371         let name = &ident.name.as_str();
372
373         if name.chars().any(|c| c.is_lowercase()) {
374             let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
375
376             let msg = format!("{} `{}` should have an upper case name", sort, name);
377             cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
378                 .span_suggestion(
379                     ident.span,
380                     "convert the identifier to upper case",
381                     uc,
382                     Applicability::MaybeIncorrect,
383                 )
384                 .emit();
385         }
386     }
387 }
388
389 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
390     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
391         match it.kind {
392             hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, sym::no_mangle) => {
393                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
394             }
395             hir::ItemKind::Const(..) => {
396                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
397             }
398             _ => {}
399         }
400     }
401
402     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem<'_>) {
403         if let hir::TraitItemKind::Const(..) = ti.kind {
404             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
405         }
406     }
407
408     fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem<'_>) {
409         if let hir::ImplItemKind::Const(..) = ii.kind {
410             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
411         }
412     }
413
414     fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
415         // Lint for constants that look like binding identifiers (#7526)
416         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
417             if let Res::Def(DefKind::Const, _) = path.res {
418                 if path.segments.len() == 1 {
419                     NonUpperCaseGlobals::check_upper_case(
420                         cx,
421                         "constant in pattern",
422                         &path.segments[0].ident,
423                     );
424                 }
425             }
426         }
427     }
428
429     fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
430         if let GenericParamKind::Const { .. } = param.kind {
431             NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
432         }
433     }
434 }
435
436 #[cfg(test)]
437 mod tests;