]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/nonstandard_style.rs
39cebe7f969368dbea328e7e485cd54b690d4a4e
[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                                 ("rename the identifier", String::new())
287                             }
288                         } else {
289                             ("convert the identifier to snake case", sc)
290                         };
291
292                         err.span_suggestion(
293                             ident.span,
294                             message,
295                             suggestion,
296                             Applicability::MaybeIncorrect,
297                         );
298                     } else {
299                         err.help(&format!("convert the identifier to snake case: `{}`", sc));
300                     }
301                 }
302
303                 err.emit();
304             });
305         }
306     }
307 }
308
309 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
310     fn check_mod(
311         &mut self,
312         cx: &LateContext<'_>,
313         _: &'tcx hir::Mod<'tcx>,
314         _: Span,
315         id: hir::HirId,
316     ) {
317         if id != hir::CRATE_HIR_ID {
318             return;
319         }
320
321         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
322             Some(Ident::from_str(name))
323         } else {
324             cx.sess()
325                 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
326                 .and_then(|attr| attr.meta())
327                 .and_then(|meta| {
328                     meta.name_value_literal().and_then(|lit| {
329                         if let ast::LitKind::Str(name, ..) = lit.kind {
330                             // Discard the double quotes surrounding the literal.
331                             let sp = cx
332                                 .sess()
333                                 .source_map()
334                                 .span_to_snippet(lit.span)
335                                 .ok()
336                                 .and_then(|snippet| {
337                                     let left = snippet.find('"')?;
338                                     let right =
339                                         snippet.rfind('"').map(|pos| snippet.len() - pos)?;
340
341                                     Some(
342                                         lit.span
343                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
344                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
345                                     )
346                                 })
347                                 .unwrap_or(lit.span);
348
349                             Some(Ident::new(name, sp))
350                         } else {
351                             None
352                         }
353                     })
354                 })
355         };
356
357         if let Some(ident) = &crate_ident {
358             self.check_snake_case(cx, "crate", ident);
359         }
360     }
361
362     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
363         if let GenericParamKind::Lifetime { .. } = param.kind {
364             self.check_snake_case(cx, "lifetime", &param.name.ident());
365         }
366     }
367
368     fn check_fn(
369         &mut self,
370         cx: &LateContext<'_>,
371         fk: FnKind<'_>,
372         _: &hir::FnDecl<'_>,
373         _: &hir::Body<'_>,
374         _: Span,
375         id: hir::HirId,
376     ) {
377         match &fk {
378             FnKind::Method(ident, ..) => match method_context(cx, id) {
379                 MethodLateContext::PlainImpl => {
380                     self.check_snake_case(cx, "method", ident);
381                 }
382                 MethodLateContext::TraitAutoImpl => {
383                     self.check_snake_case(cx, "trait method", ident);
384                 }
385                 _ => (),
386             },
387             FnKind::ItemFn(ident, _, header, _, attrs) => {
388                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
389                 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
390                     return;
391                 }
392                 self.check_snake_case(cx, "function", ident);
393             }
394             FnKind::Closure(_) => (),
395         }
396     }
397
398     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
399         if let hir::ItemKind::Mod(_) = it.kind {
400             self.check_snake_case(cx, "module", &it.ident);
401         }
402     }
403
404     fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
405         if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
406             self.check_snake_case(cx, "trait method", &item.ident);
407             for param_name in pnames {
408                 self.check_snake_case(cx, "variable", param_name);
409             }
410         }
411     }
412
413     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
414         if let &PatKind::Binding(_, hid, ident, _) = &p.kind {
415             if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
416             {
417                 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
418                     for field in field_pats.iter() {
419                         if field.ident != ident {
420                             // Only check if a new name has been introduced, to avoid warning
421                             // on both the struct definition and this pattern.
422                             self.check_snake_case(cx, "variable", &ident);
423                         }
424                     }
425                     return;
426                 }
427             }
428             self.check_snake_case(cx, "variable", &ident);
429         }
430     }
431
432     fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
433         for sf in s.fields() {
434             self.check_snake_case(cx, "structure field", &sf.ident);
435         }
436     }
437 }
438
439 declare_lint! {
440     /// The `non_upper_case_globals` lint detects static items that don't have
441     /// uppercase identifiers.
442     ///
443     /// ### Example
444     ///
445     /// ```rust
446     /// static max_points: i32 = 5;
447     /// ```
448     ///
449     /// {{produces}}
450     ///
451     /// ### Explanation
452     ///
453     /// The preferred style is for static item names to use all uppercase
454     /// letters such as `MAX_POINTS`.
455     pub NON_UPPER_CASE_GLOBALS,
456     Warn,
457     "static constants should have uppercase identifiers"
458 }
459
460 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
461
462 impl NonUpperCaseGlobals {
463     fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
464         let name = &ident.name.as_str();
465         if name.chars().any(|c| c.is_lowercase()) {
466             cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
467                 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
468                 let mut err =
469                     lint.build(&format!("{} `{}` should have an upper case name", sort, name));
470                 // We cannot provide meaningful suggestions
471                 // if the characters are in the category of "Lowercase Letter".
472                 if *name != uc {
473                     err.span_suggestion(
474                         ident.span,
475                         "convert the identifier to upper case",
476                         uc,
477                         Applicability::MaybeIncorrect,
478                     );
479                 }
480
481                 err.emit();
482             })
483         }
484     }
485 }
486
487 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
488     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
489         match it.kind {
490             hir::ItemKind::Static(..) if !cx.sess().contains_name(&it.attrs, sym::no_mangle) => {
491                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
492             }
493             hir::ItemKind::Const(..) => {
494                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
495             }
496             _ => {}
497         }
498     }
499
500     fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
501         if let hir::TraitItemKind::Const(..) = ti.kind {
502             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
503         }
504     }
505
506     fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
507         if let hir::ImplItemKind::Const(..) = ii.kind {
508             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
509         }
510     }
511
512     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
513         // Lint for constants that look like binding identifiers (#7526)
514         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
515             if let Res::Def(DefKind::Const, _) = path.res {
516                 if path.segments.len() == 1 {
517                     NonUpperCaseGlobals::check_upper_case(
518                         cx,
519                         "constant in pattern",
520                         &path.segments[0].ident,
521                     );
522                 }
523             }
524         }
525     }
526
527     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
528         if let GenericParamKind::Const { .. } = param.kind {
529             NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
530         }
531     }
532 }
533
534 #[cfg(test)]
535 mod tests;