]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/nonstandard_style.rs
Rollup merge of #67812 - ssomers:btreemap_internal_doc, r=rkruppe
[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::def::{DefKind, Res};
4 use rustc::hir::intravisit::FnKind;
5 use rustc::hir::{self, GenericParamKind, PatKind};
6 use rustc::lint;
7 use rustc::ty;
8 use rustc_span::symbol::sym;
9 use rustc_span::{symbol::Ident, BytePos, Span};
10 use rustc_target::spec::abi::Abi;
11 use syntax::ast;
12 use syntax::attr;
13 use syntax::errors::Applicability;
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) => match cx.tcx.impl_trait_ref(cid) {
28             Some(_) => MethodLateContext::TraitImpl,
29             None => MethodLateContext::PlainImpl,
30         },
31     }
32 }
33
34 declare_lint! {
35     pub NON_CAMEL_CASE_TYPES,
36     Warn,
37     "types, variants, traits and type parameters should have camel case names"
38 }
39
40 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
41
42 fn char_has_case(c: char) -> bool {
43     c.is_lowercase() || c.is_uppercase()
44 }
45
46 fn is_camel_case(name: &str) -> bool {
47     let name = name.trim_matches('_');
48     if name.is_empty() {
49         return true;
50     }
51
52     // start with a non-lowercase letter rather than non-uppercase
53     // ones (some scripts don't have a concept of upper/lowercase)
54     !name.chars().next().unwrap().is_lowercase()
55         && !name.contains("__")
56         && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
57             // contains a capitalisable character followed by, or preceded by, an underscore
58             char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_'
59         })
60 }
61
62 fn to_camel_case(s: &str) -> String {
63     s.trim_matches('_')
64         .split('_')
65         .filter(|component| !component.is_empty())
66         .map(|component| {
67             let mut camel_cased_component = String::new();
68
69             let mut new_word = true;
70             let mut prev_is_lower_case = true;
71
72             for c in component.chars() {
73                 // Preserve the case if an uppercase letter follows a lowercase letter, so that
74                 // `camelCase` is converted to `CamelCase`.
75                 if prev_is_lower_case && c.is_uppercase() {
76                     new_word = true;
77                 }
78
79                 if new_word {
80                     camel_cased_component.push_str(&c.to_uppercase().to_string());
81                 } else {
82                     camel_cased_component.push_str(&c.to_lowercase().to_string());
83                 }
84
85                 prev_is_lower_case = c.is_lowercase();
86                 new_word = false;
87             }
88
89             camel_cased_component
90         })
91         .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
92             // separate two components with an underscore if their boundary cannot
93             // be distinguished using a uppercase/lowercase case distinction
94             let join = if let Some(prev) = prev {
95                 let l = prev.chars().last().unwrap();
96                 let f = next.chars().next().unwrap();
97                 !char_has_case(l) && !char_has_case(f)
98             } else {
99                 false
100             };
101             (acc + if join { "_" } else { "" } + &next, Some(next))
102         })
103         .0
104 }
105
106 impl NonCamelCaseTypes {
107     fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
108         let name = &ident.name.as_str();
109
110         if !is_camel_case(name) {
111             let msg = format!("{} `{}` should have an upper camel case name", sort, name);
112             cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
113                 .span_suggestion(
114                     ident.span,
115                     "convert the identifier to upper camel case",
116                     to_camel_case(name),
117                     Applicability::MaybeIncorrect,
118                 )
119                 .emit();
120         }
121     }
122 }
123
124 impl EarlyLintPass for NonCamelCaseTypes {
125     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
126         let has_repr_c = it
127             .attrs
128             .iter()
129             .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
130
131         if has_repr_c {
132             return;
133         }
134
135         match it.kind {
136             ast::ItemKind::TyAlias(..)
137             | ast::ItemKind::Enum(..)
138             | ast::ItemKind::Struct(..)
139             | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
140             ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
141             _ => (),
142         }
143     }
144
145     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
146         self.check_case(cx, "variant", &v.ident);
147     }
148
149     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
150         if let ast::GenericParamKind::Type { .. } = param.kind {
151             self.check_case(cx, "type parameter", &param.ident);
152         }
153     }
154 }
155
156 declare_lint! {
157     pub NON_SNAKE_CASE,
158     Warn,
159     "variables, methods, functions, lifetime parameters and modules should have snake case names"
160 }
161
162 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
163
164 impl NonSnakeCase {
165     fn to_snake_case(mut str: &str) -> String {
166         let mut words = vec![];
167         // Preserve leading underscores
168         str = str.trim_start_matches(|c: char| {
169             if c == '_' {
170                 words.push(String::new());
171                 true
172             } else {
173                 false
174             }
175         });
176         for s in str.split('_') {
177             let mut last_upper = false;
178             let mut buf = String::new();
179             if s.is_empty() {
180                 continue;
181             }
182             for ch in s.chars() {
183                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
184                     words.push(buf);
185                     buf = String::new();
186                 }
187                 last_upper = ch.is_uppercase();
188                 buf.extend(ch.to_lowercase());
189             }
190             words.push(buf);
191         }
192         words.join("_")
193     }
194
195     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
196     fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
197         fn is_snake_case(ident: &str) -> bool {
198             if ident.is_empty() {
199                 return true;
200             }
201             let ident = ident.trim_start_matches('\'');
202             let ident = ident.trim_matches('_');
203
204             let mut allow_underscore = true;
205             ident.chars().all(|c| {
206                 allow_underscore = match c {
207                     '_' if !allow_underscore => return false,
208                     '_' => false,
209                     // It would be more obvious to use `c.is_lowercase()`,
210                     // but some characters do not have a lowercase form
211                     c if !c.is_uppercase() => true,
212                     _ => return false,
213                 };
214                 true
215             })
216         }
217
218         let name = &ident.name.as_str();
219
220         if !is_snake_case(name) {
221             let sc = NonSnakeCase::to_snake_case(name);
222
223             let msg = format!("{} `{}` should have a snake case name", sort, name);
224             let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
225
226             // We have a valid span in almost all cases, but we don't have one when linting a crate
227             // name provided via the command line.
228             if !ident.span.is_dummy() {
229                 err.span_suggestion(
230                     ident.span,
231                     "convert the identifier to snake case",
232                     sc,
233                     Applicability::MaybeIncorrect,
234                 );
235             } else {
236                 err.help(&format!("convert the identifier to snake case: `{}`", sc));
237             }
238
239             err.emit();
240         }
241     }
242 }
243
244 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
245     fn check_mod(
246         &mut self,
247         cx: &LateContext<'_, '_>,
248         _: &'tcx hir::Mod<'tcx>,
249         _: Span,
250         id: hir::HirId,
251     ) {
252         if id != hir::CRATE_HIR_ID {
253             return;
254         }
255
256         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
257             Some(Ident::from_str(name))
258         } else {
259             attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
260                 .and_then(|attr| attr.meta())
261                 .and_then(|meta| {
262                     meta.name_value_literal().and_then(|lit| {
263                         if let ast::LitKind::Str(name, ..) = lit.kind {
264                             // Discard the double quotes surrounding the literal.
265                             let sp = cx
266                                 .sess()
267                                 .source_map()
268                                 .span_to_snippet(lit.span)
269                                 .ok()
270                                 .and_then(|snippet| {
271                                     let left = snippet.find('"')?;
272                                     let right =
273                                         snippet.rfind('"').map(|pos| snippet.len() - pos)?;
274
275                                     Some(
276                                         lit.span
277                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
278                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
279                                     )
280                                 })
281                                 .unwrap_or_else(|| lit.span);
282
283                             Some(Ident::new(name, sp))
284                         } else {
285                             None
286                         }
287                     })
288                 })
289         };
290
291         if let Some(ident) = &crate_ident {
292             self.check_snake_case(cx, "crate", ident);
293         }
294     }
295
296     fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
297         if let GenericParamKind::Lifetime { .. } = param.kind {
298             self.check_snake_case(cx, "lifetime", &param.name.ident());
299         }
300     }
301
302     fn check_fn(
303         &mut self,
304         cx: &LateContext<'_, '_>,
305         fk: FnKind<'_>,
306         _: &hir::FnDecl<'_>,
307         _: &hir::Body<'_>,
308         _: Span,
309         id: hir::HirId,
310     ) {
311         match &fk {
312             FnKind::Method(ident, ..) => match method_context(cx, id) {
313                 MethodLateContext::PlainImpl => {
314                     self.check_snake_case(cx, "method", ident);
315                 }
316                 MethodLateContext::TraitAutoImpl => {
317                     self.check_snake_case(cx, "trait method", ident);
318                 }
319                 _ => (),
320             },
321             FnKind::ItemFn(ident, _, header, _, attrs) => {
322                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
323                 if header.abi != Abi::Rust && attr::contains_name(attrs, sym::no_mangle) {
324                     return;
325                 }
326                 self.check_snake_case(cx, "function", ident);
327             }
328             FnKind::Closure(_) => (),
329         }
330     }
331
332     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
333         if let hir::ItemKind::Mod(_) = it.kind {
334             self.check_snake_case(cx, "module", &it.ident);
335         }
336     }
337
338     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) {
339         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = item.kind {
340             self.check_snake_case(cx, "trait method", &item.ident);
341             for param_name in pnames {
342                 self.check_snake_case(cx, "variable", param_name);
343             }
344         }
345     }
346
347     fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
348         if let &PatKind::Binding(_, _, ident, _) = &p.kind {
349             self.check_snake_case(cx, "variable", &ident);
350         }
351     }
352
353     fn check_struct_def(&mut self, cx: &LateContext<'_, '_>, s: &hir::VariantData<'_>) {
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(cx, "const parameter", &param.name.ident());
431         }
432     }
433 }
434
435 #[cfg(test)]
436 mod tests;