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