]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/nonstandard_style.rs
Auto merge of #104431 - alistair23:alistair/rv64-profiler, r=Mark-Simulacrum
[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         }
187     }
188
189     fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
190         if let ast::AssocItemKind::Type(..) = it.kind {
191             self.check_case(cx, "associated type", &it.ident);
192         }
193     }
194
195     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
196         self.check_case(cx, "variant", &v.ident);
197     }
198
199     fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
200         if let ast::GenericParamKind::Type { .. } = param.kind {
201             self.check_case(cx, "type parameter", &param.ident);
202         }
203     }
204 }
205
206 declare_lint! {
207     /// The `non_snake_case` lint detects variables, methods, functions,
208     /// lifetime parameters and modules that don't have snake case names.
209     ///
210     /// ### Example
211     ///
212     /// ```rust
213     /// let MY_VALUE = 5;
214     /// ```
215     ///
216     /// {{produces}}
217     ///
218     /// ### Explanation
219     ///
220     /// The preferred style for these identifiers is to use "snake case",
221     /// where all the characters are in lowercase, with words separated with a
222     /// single underscore, such as `my_value`.
223     pub NON_SNAKE_CASE,
224     Warn,
225     "variables, methods, functions, lifetime parameters and modules should have snake case names"
226 }
227
228 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
229
230 impl NonSnakeCase {
231     fn to_snake_case(mut str: &str) -> String {
232         let mut words = vec![];
233         // Preserve leading underscores
234         str = str.trim_start_matches(|c: char| {
235             if c == '_' {
236                 words.push(String::new());
237                 true
238             } else {
239                 false
240             }
241         });
242         for s in str.split('_') {
243             let mut last_upper = false;
244             let mut buf = String::new();
245             if s.is_empty() {
246                 continue;
247             }
248             for ch in s.chars() {
249                 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
250                     words.push(buf);
251                     buf = String::new();
252                 }
253                 last_upper = ch.is_uppercase();
254                 buf.extend(ch.to_lowercase());
255             }
256             words.push(buf);
257         }
258         words.join("_")
259     }
260
261     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
262     fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
263         fn is_snake_case(ident: &str) -> bool {
264             if ident.is_empty() {
265                 return true;
266             }
267             let ident = ident.trim_start_matches('\'');
268             let ident = ident.trim_matches('_');
269
270             let mut allow_underscore = true;
271             ident.chars().all(|c| {
272                 allow_underscore = match c {
273                     '_' if !allow_underscore => return false,
274                     '_' => false,
275                     // It would be more obvious to use `c.is_lowercase()`,
276                     // but some characters do not have a lowercase form
277                     c if !c.is_uppercase() => true,
278                     _ => return false,
279                 };
280                 true
281             })
282         }
283
284         let name = ident.name.as_str();
285
286         if !is_snake_case(name) {
287             cx.struct_span_lint(NON_SNAKE_CASE, ident.span, fluent::lint_non_snake_case, |lint| {
288                 let sc = NonSnakeCase::to_snake_case(name);
289                 // We cannot provide meaningful suggestions
290                 // if the characters are in the category of "Uppercase Letter".
291                 if name != sc {
292                     // We have a valid span in almost all cases, but we don't have one when linting a crate
293                     // name provided via the command line.
294                     if !ident.span.is_dummy() {
295                         let sc_ident = Ident::from_str_and_span(&sc, ident.span);
296                         let (message, suggestion) = if sc_ident.is_reserved() {
297                             // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
298                             // Instead, recommend renaming the identifier entirely or, if permitted,
299                             // escaping it to create a raw identifier.
300                             if sc_ident.name.can_be_raw() {
301                                 (fluent::rename_or_convert_suggestion, sc_ident.to_string())
302                             } else {
303                                 lint.note(fluent::cannot_convert_note);
304                                 (fluent::rename_suggestion, String::new())
305                             }
306                         } else {
307                             (fluent::convert_suggestion, sc.clone())
308                         };
309
310                         lint.span_suggestion(
311                             ident.span,
312                             message,
313                             suggestion,
314                             Applicability::MaybeIncorrect,
315                         );
316                     } else {
317                         lint.help(fluent::help);
318                     }
319                 } else {
320                     lint.span_label(ident.span, fluent::label);
321                 }
322
323                 lint.set_arg("sort", sort);
324                 lint.set_arg("name", name);
325                 lint.set_arg("sc", sc);
326                 lint
327             });
328         }
329     }
330 }
331
332 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
333     fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) {
334         if id != hir::CRATE_HIR_ID {
335             return;
336         }
337
338         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
339             Some(Ident::from_str(name))
340         } else {
341             cx.sess()
342                 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
343                 .and_then(|attr| attr.meta())
344                 .and_then(|meta| {
345                     meta.name_value_literal().and_then(|lit| {
346                         if let ast::LitKind::Str(name, ..) = lit.kind {
347                             // Discard the double quotes surrounding the literal.
348                             let sp = cx
349                                 .sess()
350                                 .source_map()
351                                 .span_to_snippet(lit.span)
352                                 .ok()
353                                 .and_then(|snippet| {
354                                     let left = snippet.find('"')?;
355                                     let right =
356                                         snippet.rfind('"').map(|pos| snippet.len() - pos)?;
357
358                                     Some(
359                                         lit.span
360                                             .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
361                                             .with_hi(lit.span.hi() - BytePos(right as u32)),
362                                     )
363                                 })
364                                 .unwrap_or(lit.span);
365
366                             Some(Ident::new(name, sp))
367                         } else {
368                             None
369                         }
370                     })
371                 })
372         };
373
374         if let Some(ident) = &crate_ident {
375             self.check_snake_case(cx, "crate", ident);
376         }
377     }
378
379     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
380         if let GenericParamKind::Lifetime { .. } = param.kind {
381             self.check_snake_case(cx, "lifetime", &param.name.ident());
382         }
383     }
384
385     fn check_fn(
386         &mut self,
387         cx: &LateContext<'_>,
388         fk: FnKind<'_>,
389         _: &hir::FnDecl<'_>,
390         _: &hir::Body<'_>,
391         _: Span,
392         id: hir::HirId,
393     ) {
394         let attrs = cx.tcx.hir().attrs(id);
395         match &fk {
396             FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
397                 MethodLateContext::PlainImpl => {
398                     if sig.header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle)
399                     {
400                         return;
401                     }
402                     self.check_snake_case(cx, "method", ident);
403                 }
404                 MethodLateContext::TraitAutoImpl => {
405                     self.check_snake_case(cx, "trait method", ident);
406                 }
407                 _ => (),
408             },
409             FnKind::ItemFn(ident, _, header) => {
410                 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
411                 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
412                     return;
413                 }
414                 self.check_snake_case(cx, "function", ident);
415             }
416             FnKind::Closure => (),
417         }
418     }
419
420     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
421         if let hir::ItemKind::Mod(_) = it.kind {
422             self.check_snake_case(cx, "module", &it.ident);
423         }
424     }
425
426     fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
427         if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
428             self.check_snake_case(cx, "trait method", &item.ident);
429             for param_name in pnames {
430                 self.check_snake_case(cx, "variable", param_name);
431             }
432         }
433     }
434
435     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
436         if let PatKind::Binding(_, hid, ident, _) = p.kind {
437             if let hir::Node::PatField(field) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
438             {
439                 if !field.is_shorthand {
440                     // Only check if a new name has been introduced, to avoid warning
441                     // on both the struct definition and this pattern.
442                     self.check_snake_case(cx, "variable", &ident);
443                 }
444                 return;
445             }
446             self.check_snake_case(cx, "variable", &ident);
447         }
448     }
449
450     fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
451         for sf in s.fields() {
452             self.check_snake_case(cx, "structure field", &sf.ident);
453         }
454     }
455 }
456
457 declare_lint! {
458     /// The `non_upper_case_globals` lint detects static items that don't have
459     /// uppercase identifiers.
460     ///
461     /// ### Example
462     ///
463     /// ```rust
464     /// static max_points: i32 = 5;
465     /// ```
466     ///
467     /// {{produces}}
468     ///
469     /// ### Explanation
470     ///
471     /// The preferred style is for static item names to use all uppercase
472     /// letters such as `MAX_POINTS`.
473     pub NON_UPPER_CASE_GLOBALS,
474     Warn,
475     "static constants should have uppercase identifiers"
476 }
477
478 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
479
480 impl NonUpperCaseGlobals {
481     fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
482         let name = ident.name.as_str();
483         if name.chars().any(|c| c.is_lowercase()) {
484             cx.struct_span_lint(
485                 NON_UPPER_CASE_GLOBALS,
486                 ident.span,
487                 fluent::lint_non_upper_case_global,
488                 |lint| {
489                     let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
490                     // We cannot provide meaningful suggestions
491                     // if the characters are in the category of "Lowercase Letter".
492                     if *name != uc {
493                         lint.span_suggestion(
494                             ident.span,
495                             fluent::suggestion,
496                             uc,
497                             Applicability::MaybeIncorrect,
498                         );
499                     } else {
500                         lint.span_label(ident.span, fluent::label);
501                     }
502
503                     lint.set_arg("sort", sort);
504                     lint.set_arg("name", name);
505                     lint
506                 },
507             )
508         }
509     }
510 }
511
512 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
513     fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
514         let attrs = cx.tcx.hir().attrs(it.hir_id());
515         match it.kind {
516             hir::ItemKind::Static(..) if !cx.sess().contains_name(attrs, sym::no_mangle) => {
517                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
518             }
519             hir::ItemKind::Const(..) => {
520                 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
521             }
522             _ => {}
523         }
524     }
525
526     fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
527         if let hir::TraitItemKind::Const(..) = ti.kind {
528             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
529         }
530     }
531
532     fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
533         if let hir::ImplItemKind::Const(..) = ii.kind {
534             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
535         }
536     }
537
538     fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
539         // Lint for constants that look like binding identifiers (#7526)
540         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
541             if let Res::Def(DefKind::Const, _) = path.res {
542                 if path.segments.len() == 1 {
543                     NonUpperCaseGlobals::check_upper_case(
544                         cx,
545                         "constant in pattern",
546                         &path.segments[0].ident,
547                     );
548                 }
549             }
550         }
551     }
552
553     fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
554         if let GenericParamKind::Const { .. } = param.kind {
555             NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
556         }
557     }
558 }
559
560 #[cfg(test)]
561 mod tests;