]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/nonstandard_style.rs
Add snake case lint note about keyword identifiers which cannot be raw
[rust.git] / compiler / rustc_lint / src / nonstandard_style.rs
1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
2 use rustc_ast as ast;
3 use rustc_attr as attr;
4 use rustc_errors::Applicability;
5 use rustc_hir as hir;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::intravisit::FnKind;
8 use rustc_hir::{GenericParamKind, PatKind};
9 use rustc_middle::ty;
10 use rustc_span::symbol::sym;
11 use rustc_span::{symbol::Ident, BytePos, Span};
12 use rustc_target::spec::abi::Abi;
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(id);
23     let item = cx.tcx.associated_item(def_id);
24     match item.container {
25         ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
26         ty::ImplContainer(cid) => match cx.tcx.impl_trait_ref(cid) {
27             Some(_) => MethodLateContext::TraitImpl,
28             None => MethodLateContext::PlainImpl,
29         },
30     }
31 }
32
33 declare_lint! {
34     /// The `non_camel_case_types` lint detects types, variants, traits and
35     /// type parameters that don't have camel case names.
36     ///
37     /// ### Example
38     ///
39     /// ```rust
40     /// struct my_struct;
41     /// ```
42     ///
43     /// {{produces}}
44     ///
45     /// ### Explanation
46     ///
47     /// The preferred style for these identifiers is to use "camel case", such
48     /// as `MyStruct`, where the first letter should not be lowercase, and
49     /// should not use underscores between letters. Underscores are allowed at
50     /// the beginning and end of the identifier, as well as between
51     /// non-letters (such as `X86_64`).
52     pub NON_CAMEL_CASE_TYPES,
53     Warn,
54     "types, variants, traits and type parameters should have camel case names"
55 }
56
57 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
58
59 fn char_has_case(c: char) -> bool {
60     c.is_lowercase() || c.is_uppercase()
61 }
62
63 fn is_camel_case(name: &str) -> bool {
64     let name = name.trim_matches('_');
65     if name.is_empty() {
66         return true;
67     }
68
69     // start with a non-lowercase letter rather than non-uppercase
70     // ones (some scripts don't have a concept of upper/lowercase)
71     !name.chars().next().unwrap().is_lowercase()
72         && !name.contains("__")
73         && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
74             // contains a capitalisable character followed by, or preceded by, an underscore
75             char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
76         })
77 }
78
79 fn to_camel_case(s: &str) -> String {
80     s.trim_matches('_')
81         .split('_')
82         .filter(|component| !component.is_empty())
83         .map(|component| {
84             let mut camel_cased_component = String::new();
85
86             let mut new_word = true;
87             let mut prev_is_lower_case = true;
88
89             for c in component.chars() {
90                 // Preserve the case if an uppercase letter follows a lowercase letter, so that
91                 // `camelCase` is converted to `CamelCase`.
92                 if prev_is_lower_case && c.is_uppercase() {
93                     new_word = true;
94                 }
95
96                 if new_word {
97                     camel_cased_component.extend(c.to_uppercase());
98                 } else {
99                     camel_cased_component.extend(c.to_lowercase());
100                 }
101
102                 prev_is_lower_case = c.is_lowercase();
103                 new_word = false;
104             }
105
106             camel_cased_component
107         })
108         .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
109             // separate two components with an underscore if their boundary cannot
110             // be distinguished using a uppercase/lowercase case distinction
111             let join = if let Some(prev) = prev {
112                 let l = prev.chars().last().unwrap();
113                 let f = next.chars().next().unwrap();
114                 !char_has_case(l) && !char_has_case(f)
115             } else {
116                 false
117             };
118             (acc + if join { "_" } else { "" } + &next, Some(next))
119         })
120         .0
121 }
122
123 impl NonCamelCaseTypes {
124     fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
125         let name = &ident.name.as_str();
126
127         if !is_camel_case(name) {
128             cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, |lint| {
129                 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
130                 let mut err = lint.build(&msg);
131                 let cc = to_camel_case(name);
132                 // We cannot provide meaningful suggestions
133                 // if the characters are in the category of "Lowercase Letter".
134                 if *name != cc {
135                     err.span_suggestion(
136                         ident.span,
137                         "convert the identifier to upper camel case",
138                         to_camel_case(name),
139                         Applicability::MaybeIncorrect,
140                     );
141                 }
142
143                 err.emit();
144             })
145         }
146     }
147 }
148
149 impl EarlyLintPass for NonCamelCaseTypes {
150     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
151         let has_repr_c = it
152             .attrs
153             .iter()
154             .any(|attr| attr::find_repr_attrs(&cx.sess, attr).contains(&attr::ReprC));
155
156         if has_repr_c {
157             return;
158         }
159
160         match it.kind {
161             ast::ItemKind::TyAlias(..)
162             | ast::ItemKind::Enum(..)
163             | ast::ItemKind::Struct(..)
164             | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
165             ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
166             _ => (),
167         }
168     }
169
170     fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
171         if let ast::AssocItemKind::TyAlias(..) = it.kind {
172             self.check_case(cx, "associated type", &it.ident);
173         }
174     }
175
176     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
177         self.check_case(cx, "variant", &v.ident);
178     }
179
180     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
181         if let ast::GenericParamKind::Type { .. } = param.kind {
182             self.check_case(cx, "type parameter", &param.ident);
183         }
184     }
185 }
186
187 declare_lint! {
188     /// The `non_snake_case` lint detects variables, methods, functions,
189     /// lifetime parameters and modules that don't have snake case names.
190     ///
191     /// ### Example
192     ///
193     /// ```rust
194     /// let MY_VALUE = 5;
195     /// ```
196     ///
197     /// {{produces}}
198     ///
199     /// ### Explanation
200     ///
201     /// The preferred style for these identifiers is to use "snake case",
202     /// where all the characters are in lowercase, with words separated with a
203     /// single underscore, such as `my_value`.
204     pub NON_SNAKE_CASE,
205     Warn,
206     "variables, methods, functions, lifetime parameters and modules should have snake case names"
207 }
208
209 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
210
211 impl NonSnakeCase {
212     fn to_snake_case(mut str: &str) -> String {
213         let mut words = vec![];
214         // Preserve leading underscores
215         str = str.trim_start_matches(|c: char| {
216             if c == '_' {
217                 words.push(String::new());
218                 true
219             } else {
220                 false
221             }
222         });
223         for s in str.split('_') {
224             let mut last_upper = false;
225             let mut buf = String::new();
226             if s.is_empty() {
227                 continue;
228             }
229             for ch in s.chars() {
230                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
231                     words.push(buf);
232                     buf = String::new();
233                 }
234                 last_upper = ch.is_uppercase();
235                 buf.extend(ch.to_lowercase());
236             }
237             words.push(buf);
238         }
239         words.join("_")
240     }
241
242     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
243     fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
244         fn is_snake_case(ident: &str) -> bool {
245             if ident.is_empty() {
246                 return true;
247             }
248             let ident = ident.trim_start_matches('\'');
249             let ident = ident.trim_matches('_');
250
251             let mut allow_underscore = true;
252             ident.chars().all(|c| {
253                 allow_underscore = match c {
254                     '_' if !allow_underscore => return false,
255                     '_' => false,
256                     // It would be more obvious to use `c.is_lowercase()`,
257                     // but some characters do not have a lowercase form
258                     c if !c.is_uppercase() => true,
259                     _ => return false,
260                 };
261                 true
262             })
263         }
264
265         let name = &ident.name.as_str();
266
267         if !is_snake_case(name) {
268             cx.struct_span_lint(NON_SNAKE_CASE, ident.span, |lint| {
269                 let sc = NonSnakeCase::to_snake_case(name);
270                 let msg = format!("{} `{}` should have a snake case name", sort, name);
271                 let mut err = lint.build(&msg);
272                 // We cannot provide meaningful suggestions
273                 // if the characters are in the category of "Uppercase Letter".
274                 if *name != sc {
275                     // We have a valid span in almost all cases, but we don't have one when linting a crate
276                     // name provided via the command line.
277                     if !ident.span.is_dummy() {
278                         let sc_ident = Ident::from_str_and_span(&sc, ident.span);
279                         let (message, suggestion) = if sc_ident.is_reserved() {
280                             // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
281                             // Instead, recommend renaming the identifier entirely or, if permitted,
282                             // escaping it to create a raw identifier.
283                             if sc_ident.name.can_be_raw() {
284                                 ("rename the identifier or convert it to a snake case raw identifier", sc_ident.to_string())
285                             } else {
286                                 err.note(&format!("`{}` cannot be used as a raw identifier", sc));
287                                 ("rename the identifier", String::new())
288                             }
289                         } else {
290                             ("convert the identifier to snake case", sc)
291                         };
292
293                         err.span_suggestion(
294                             ident.span,
295                             message,
296                             suggestion,
297                             Applicability::MaybeIncorrect,
298                         );
299                     } else {
300                         err.help(&format!("convert the identifier to snake case: `{}`", sc));
301                     }
302                 }
303
304                 err.emit();
305             });
306         }
307     }
308 }
309
310 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
311     fn check_mod(
312         &mut self,
313         cx: &LateContext<'_>,
314         _: &'tcx hir::Mod<'tcx>,
315         _: Span,
316         id: hir::HirId,
317     ) {
318         if id != hir::CRATE_HIR_ID {
319             return;
320         }
321
322         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
323             Some(Ident::from_str(name))
324         } else {
325             cx.sess()
326                 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
327                 .and_then(|attr| attr.meta())
328                 .and_then(|meta| {
329                     meta.name_value_literal().and_then(|lit| {
330                         if let ast::LitKind::Str(name, ..) = lit.kind {
331                             // Discard the double quotes surrounding the literal.
332                             let sp = cx
333                                 .sess()
334                                 .source_map()
335                                 .span_to_snippet(lit.span)
336                                 .ok()
337                                 .and_then(|snippet| {
338                                     let left = snippet.find('"')?;
339                                     let right =
340                                         snippet.rfind('"').map(|pos| snippet.len() - pos)?;
341
342                                     Some(
343                                         lit.span
344                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
345                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
346                                     )
347                                 })
348                                 .unwrap_or(lit.span);
349
350                             Some(Ident::new(name, sp))
351                         } else {
352                             None
353                         }
354                     })
355                 })
356         };
357
358         if let Some(ident) = &crate_ident {
359             self.check_snake_case(cx, "crate", ident);
360         }
361     }
362
363     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
364         if let GenericParamKind::Lifetime { .. } = param.kind {
365             self.check_snake_case(cx, "lifetime", &param.name.ident());
366         }
367     }
368
369     fn check_fn(
370         &mut self,
371         cx: &LateContext<'_>,
372         fk: FnKind<'_>,
373         _: &hir::FnDecl<'_>,
374         _: &hir::Body<'_>,
375         _: Span,
376         id: hir::HirId,
377     ) {
378         match &fk {
379             FnKind::Method(ident, ..) => match method_context(cx, id) {
380                 MethodLateContext::PlainImpl => {
381                     self.check_snake_case(cx, "method", ident);
382                 }
383                 MethodLateContext::TraitAutoImpl => {
384                     self.check_snake_case(cx, "trait method", ident);
385                 }
386                 _ => (),
387             },
388             FnKind::ItemFn(ident, _, header, _, attrs) => {
389                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
390                 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
391                     return;
392                 }
393                 self.check_snake_case(cx, "function", ident);
394             }
395             FnKind::Closure(_) => (),
396         }
397     }
398
399     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
400         if let hir::ItemKind::Mod(_) = it.kind {
401             self.check_snake_case(cx, "module", &it.ident);
402         }
403     }
404
405     fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
406         if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
407             self.check_snake_case(cx, "trait method", &item.ident);
408             for param_name in pnames {
409                 self.check_snake_case(cx, "variable", param_name);
410             }
411         }
412     }
413
414     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
415         if let &PatKind::Binding(_, hid, ident, _) = &p.kind {
416             if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
417             {
418                 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
419                     for field in field_pats.iter() {
420                         if field.ident != ident {
421                             // Only check if a new name has been introduced, to avoid warning
422                             // on both the struct definition and this pattern.
423                             self.check_snake_case(cx, "variable", &ident);
424                         }
425                     }
426                     return;
427                 }
428             }
429             self.check_snake_case(cx, "variable", &ident);
430         }
431     }
432
433     fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
434         for sf in s.fields() {
435             self.check_snake_case(cx, "structure field", &sf.ident);
436         }
437     }
438 }
439
440 declare_lint! {
441     /// The `non_upper_case_globals` lint detects static items that don't have
442     /// uppercase identifiers.
443     ///
444     /// ### Example
445     ///
446     /// ```rust
447     /// static max_points: i32 = 5;
448     /// ```
449     ///
450     /// {{produces}}
451     ///
452     /// ### Explanation
453     ///
454     /// The preferred style is for static item names to use all uppercase
455     /// letters such as `MAX_POINTS`.
456     pub NON_UPPER_CASE_GLOBALS,
457     Warn,
458     "static constants should have uppercase identifiers"
459 }
460
461 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
462
463 impl NonUpperCaseGlobals {
464     fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
465         let name = &ident.name.as_str();
466         if name.chars().any(|c| c.is_lowercase()) {
467             cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
468                 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
469                 let mut err =
470                     lint.build(&format!("{} `{}` should have an upper case name", sort, name));
471                 // We cannot provide meaningful suggestions
472                 // if the characters are in the category of "Lowercase Letter".
473                 if *name != uc {
474                     err.span_suggestion(
475                         ident.span,
476                         "convert the identifier to upper case",
477                         uc,
478                         Applicability::MaybeIncorrect,
479                     );
480                 }
481
482                 err.emit();
483             })
484         }
485     }
486 }
487
488 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
489     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
490         match it.kind {
491             hir::ItemKind::Static(..) if !cx.sess().contains_name(&it.attrs, sym::no_mangle) => {
492                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
493             }
494             hir::ItemKind::Const(..) => {
495                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
496             }
497             _ => {}
498         }
499     }
500
501     fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
502         if let hir::TraitItemKind::Const(..) = ti.kind {
503             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
504         }
505     }
506
507     fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
508         if let hir::ImplItemKind::Const(..) = ii.kind {
509             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
510         }
511     }
512
513     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
514         // Lint for constants that look like binding identifiers (#7526)
515         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
516             if let Res::Def(DefKind::Const, _) = path.res {
517                 if path.segments.len() == 1 {
518                     NonUpperCaseGlobals::check_upper_case(
519                         cx,
520                         "constant in pattern",
521                         &path.segments[0].ident,
522                     );
523                 }
524             }
525         }
526     }
527
528     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
529         if let GenericParamKind::Const { .. } = param.kind {
530             NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
531         }
532     }
533 }
534
535 #[cfg(test)]
536 mod tests;