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