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