]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_lint/src/nonstandard_style.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_lint / src / nonstandard_style.rs
CommitLineData
9c376795
FG
1use crate::lints::{
2 NonCamelCaseType, NonCamelCaseTypeSub, NonSnakeCaseDiag, NonSnakeCaseDiagSub,
3 NonUpperCaseGlobal, NonUpperCaseGlobalSub,
4};
dfeec247 5use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3dfed10e 6use rustc_ast as ast;
74b04a01 7use rustc_attr as attr;
dfeec247
XL
8use rustc_hir as hir;
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::intravisit::FnKind;
11use rustc_hir::{GenericParamKind, PatKind};
ba9703b0 12use rustc_middle::ty;
9ffffee4
FG
13use rustc_span::def_id::LocalDefId;
14use rustc_span::symbol::{sym, Ident};
15use rustc_span::{BytePos, Span};
83c7162d 16use rustc_target::spec::abi::Abi;
b039eaaf
SL
17
18#[derive(PartialEq)]
19pub enum MethodLateContext {
abe05a73 20 TraitAutoImpl,
b039eaaf 21 TraitImpl,
c30ab7b3 22 PlainImpl,
b039eaaf
SL
23}
24
9ffffee4
FG
25pub fn method_context(cx: &LateContext<'_>, id: LocalDefId) -> MethodLateContext {
26 let item = cx.tcx.associated_item(id);
7cac9316 27 match item.container {
064997fb
FG
28 ty::TraitContainer => MethodLateContext::TraitAutoImpl,
29 ty::ImplContainer => match cx.tcx.impl_trait_ref(item.container_id(cx.tcx)) {
dfeec247
XL
30 Some(_) => MethodLateContext::TraitImpl,
31 None => MethodLateContext::PlainImpl,
32 },
b039eaaf
SL
33 }
34}
35
49aad941
FG
36fn assoc_item_in_trait_impl(cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) -> bool {
37 let item = cx.tcx.associated_item(ii.owner_id);
38 item.trait_item_def_id.is_some()
39}
40
b039eaaf 41declare_lint! {
1b1a35ee
XL
42 /// The `non_camel_case_types` lint detects types, variants, traits and
43 /// type parameters that don't have camel case names.
44 ///
45 /// ### Example
46 ///
47 /// ```rust
48 /// struct my_struct;
49 /// ```
50 ///
51 /// {{produces}}
52 ///
53 /// ### Explanation
54 ///
55 /// The preferred style for these identifiers is to use "camel case", such
56 /// as `MyStruct`, where the first letter should not be lowercase, and
57 /// should not use underscores between letters. Underscores are allowed at
58 /// the beginning and end of the identifier, as well as between
59 /// non-letters (such as `X86_64`).
b039eaaf
SL
60 pub NON_CAMEL_CASE_TYPES,
61 Warn,
62 "types, variants, traits and type parameters should have camel case names"
63}
64
532ac7d7
XL
65declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
66
5869c6ff
XL
67/// Some unicode characters *have* case, are considered upper case or lower case, but they *can't*
68/// be upper cased or lower cased. For the purposes of the lint suggestion, we care about being able
69/// to change the char's case.
9fa01778 70fn char_has_case(c: char) -> bool {
5869c6ff
XL
71 let mut l = c.to_lowercase();
72 let mut u = c.to_uppercase();
73 while let Some(l) = l.next() {
74 match u.next() {
75 Some(u) if l != u => return true,
76 _ => {}
77 }
78 }
79 u.next().is_some()
9fa01778 80}
b039eaaf 81
9fa01778
XL
82fn is_camel_case(name: &str) -> bool {
83 let name = name.trim_matches('_');
84 if name.is_empty() {
85 return true;
86 }
2c00a5a8 87
9fa01778
XL
88 // start with a non-lowercase letter rather than non-uppercase
89 // ones (some scripts don't have a concept of upper/lowercase)
90 !name.chars().next().unwrap().is_lowercase()
91 && !name.contains("__")
1b1a35ee 92 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
9fa01778 93 // contains a capitalisable character followed by, or preceded by, an underscore
1b1a35ee 94 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
9fa01778
XL
95 })
96}
97
98fn to_camel_case(s: &str) -> String {
99 s.trim_matches('_')
100 .split('_')
101 .filter(|component| !component.is_empty())
102 .map(|component| {
103 let mut camel_cased_component = String::new();
104
105 let mut new_word = true;
106 let mut prev_is_lower_case = true;
107
108 for c in component.chars() {
109 // Preserve the case if an uppercase letter follows a lowercase letter, so that
110 // `camelCase` is converted to `CamelCase`.
111 if prev_is_lower_case && c.is_uppercase() {
112 new_word = true;
113 }
114
115 if new_word {
fc512014 116 camel_cased_component.extend(c.to_uppercase());
9fa01778 117 } else {
fc512014 118 camel_cased_component.extend(c.to_lowercase());
9fa01778
XL
119 }
120
121 prev_is_lower_case = c.is_lowercase();
122 new_word = false;
b039eaaf 123 }
b039eaaf 124
9fa01778
XL
125 camel_cased_component
126 })
dfeec247
XL
127 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
128 // separate two components with an underscore if their boundary cannot
94222f64 129 // be distinguished using an uppercase/lowercase case distinction
dfeec247
XL
130 let join = if let Some(prev) = prev {
131 let l = prev.chars().last().unwrap();
132 let f = next.chars().next().unwrap();
133 !char_has_case(l) && !char_has_case(f)
134 } else {
135 false
136 };
137 (acc + if join { "_" } else { "" } + &next, Some(next))
138 })
9fa01778
XL
139 .0
140}
b039eaaf 141
9fa01778
XL
142impl NonCamelCaseTypes {
143 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
a2a8927a 144 let name = ident.name.as_str();
0731742a 145
b039eaaf 146 if !is_camel_case(name) {
9c376795
FG
147 let cc = to_camel_case(name);
148 let sub = if *name != cc {
149 NonCamelCaseTypeSub::Suggestion { span: ident.span, replace: cc }
150 } else {
151 NonCamelCaseTypeSub::Label { span: ident.span }
152 };
153 cx.emit_spanned_lint(
2b03887a
FG
154 NON_CAMEL_CASE_TYPES,
155 ident.span,
9c376795
FG
156 NonCamelCaseType { sort, name, sub },
157 );
b039eaaf
SL
158 }
159 }
160}
161
0731742a 162impl EarlyLintPass for NonCamelCaseTypes {
9fa01778 163 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
dfeec247
XL
164 let has_repr_c = it
165 .attrs
c30ab7b3 166 .iter()
5099ac24 167 .any(|attr| attr::find_repr_attrs(cx.sess(), attr).contains(&attr::ReprC));
b039eaaf 168
2c00a5a8 169 if has_repr_c {
b039eaaf
SL
170 return;
171 }
172
9c376795 173 match &it.kind {
dfeec247
XL
174 ast::ItemKind::TyAlias(..)
175 | ast::ItemKind::Enum(..)
176 | ast::ItemKind::Struct(..)
177 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
0731742a 178 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
17df50a5 179 ast::ItemKind::TraitAlias(..) => self.check_case(cx, "trait alias", &it.ident),
9c376795
FG
180
181 // N.B. This check is only for inherent associated types, so that we don't lint against
182 // trait impls where we should have warned for the trait definition already.
183 ast::ItemKind::Impl(box ast::Impl { of_trait: None, items, .. }) => {
184 for it in items {
49aad941 185 // FIXME: this doesn't respect `#[allow(..)]` on the item itself.
9c376795
FG
186 if let ast::AssocItemKind::Type(..) = it.kind {
187 self.check_case(cx, "associated type", &it.ident);
188 }
189 }
190 }
c30ab7b3 191 _ => (),
b039eaaf
SL
192 }
193 }
194
dfeec247 195 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
2b03887a 196 if let ast::AssocItemKind::Type(..) = it.kind {
dfeec247
XL
197 self.check_case(cx, "associated type", &it.ident);
198 }
199 }
200
e1599b0c
XL
201 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
202 self.check_case(cx, "variant", &v.ident);
8bb4bdeb
XL
203 }
204
9fa01778 205 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
0731742a
XL
206 if let ast::GenericParamKind::Type { .. } = param.kind {
207 self.check_case(cx, "type parameter", &param.ident);
b039eaaf
SL
208 }
209 }
210}
211
212declare_lint! {
1b1a35ee
XL
213 /// The `non_snake_case` lint detects variables, methods, functions,
214 /// lifetime parameters and modules that don't have snake case names.
215 ///
216 /// ### Example
217 ///
218 /// ```rust
219 /// let MY_VALUE = 5;
220 /// ```
221 ///
222 /// {{produces}}
223 ///
224 /// ### Explanation
225 ///
226 /// The preferred style for these identifiers is to use "snake case",
227 /// where all the characters are in lowercase, with words separated with a
228 /// single underscore, such as `my_value`.
b039eaaf
SL
229 pub NON_SNAKE_CASE,
230 Warn,
92a42be0 231 "variables, methods, functions, lifetime parameters and modules should have snake case names"
b039eaaf
SL
232}
233
532ac7d7 234declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
b039eaaf
SL
235
236impl NonSnakeCase {
237 fn to_snake_case(mut str: &str) -> String {
238 let mut words = vec![];
239 // Preserve leading underscores
0731742a 240 str = str.trim_start_matches(|c: char| {
b039eaaf
SL
241 if c == '_' {
242 words.push(String::new());
243 true
244 } else {
245 false
246 }
247 });
248 for s in str.split('_') {
249 let mut last_upper = false;
250 let mut buf = String::new();
251 if s.is_empty() {
252 continue;
253 }
254 for ch in s.chars() {
c30ab7b3 255 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
b039eaaf
SL
256 words.push(buf);
257 buf = String::new();
258 }
259 last_upper = ch.is_uppercase();
260 buf.extend(ch.to_lowercase());
261 }
262 words.push(buf);
263 }
264 words.join("_")
265 }
266
0731742a 267 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
f035d41b 268 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
b039eaaf
SL
269 fn is_snake_case(ident: &str) -> bool {
270 if ident.is_empty() {
271 return true;
272 }
0731742a 273 let ident = ident.trim_start_matches('\'');
b039eaaf
SL
274 let ident = ident.trim_matches('_');
275
276 let mut allow_underscore = true;
277 ident.chars().all(|c| {
278 allow_underscore = match c {
279 '_' if !allow_underscore => return false,
280 '_' => false,
281 // It would be more obvious to use `c.is_lowercase()`,
282 // but some characters do not have a lowercase form
283 c if !c.is_uppercase() => true,
284 _ => return false,
285 };
286 true
287 })
288 }
289
a2a8927a 290 let name = ident.name.as_str();
0731742a 291
b039eaaf 292 if !is_snake_case(name) {
9c376795
FG
293 let span = ident.span;
294 let sc = NonSnakeCase::to_snake_case(name);
295 // We cannot provide meaningful suggestions
296 // if the characters are in the category of "Uppercase Letter".
297 let sub = if name != sc {
298 // We have a valid span in almost all cases, but we don't have one when linting a crate
299 // name provided via the command line.
300 if !span.is_dummy() {
301 let sc_ident = Ident::from_str_and_span(&sc, span);
302 if sc_ident.is_reserved() {
303 // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
304 // Instead, recommend renaming the identifier entirely or, if permitted,
305 // escaping it to create a raw identifier.
306 if sc_ident.name.can_be_raw() {
307 NonSnakeCaseDiagSub::RenameOrConvertSuggestion {
308 span,
309 suggestion: sc_ident,
5869c6ff
XL
310 }
311 } else {
9c376795
FG
312 NonSnakeCaseDiagSub::SuggestionAndNote { span }
313 }
fc512014 314 } else {
9c376795 315 NonSnakeCaseDiagSub::ConvertSuggestion { span, suggestion: sc.clone() }
fc512014 316 }
5869c6ff 317 } else {
9c376795 318 NonSnakeCaseDiagSub::Help
74b04a01 319 }
9c376795
FG
320 } else {
321 NonSnakeCaseDiagSub::Label { span }
322 };
323 cx.emit_spanned_lint(NON_SNAKE_CASE, span, NonSnakeCaseDiag { sort, name, sc, sub });
b039eaaf
SL
324 }
325 }
326}
327
f035d41b 328impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
f2b60f7d 329 fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) {
532ac7d7
XL
330 if id != hir::CRATE_HIR_ID {
331 return;
332 }
333
0731742a
XL
334 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
335 Some(Ident::from_str(name))
336 } else {
353b0b11 337 attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
0731742a
XL
338 .and_then(|attr| attr.meta())
339 .and_then(|meta| {
340 meta.name_value_literal().and_then(|lit| {
e74abb32 341 if let ast::LitKind::Str(name, ..) = lit.kind {
0731742a 342 // Discard the double quotes surrounding the literal.
dfeec247
XL
343 let sp = cx
344 .sess()
345 .source_map()
346 .span_to_snippet(lit.span)
0731742a
XL
347 .ok()
348 .and_then(|snippet| {
349 let left = snippet.find('"')?;
dfeec247
XL
350 let right =
351 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
0731742a
XL
352
353 Some(
354 lit.span
355 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
356 .with_hi(lit.span.hi() - BytePos(right as u32)),
357 )
358 })
29967ef6 359 .unwrap_or(lit.span);
0731742a
XL
360
361 Some(Ident::new(name, sp))
362 } else {
363 None
364 }
365 })
366 })
367 };
368
369 if let Some(ident) = &crate_ident {
370 self.check_snake_case(cx, "crate", ident);
b039eaaf
SL
371 }
372 }
373
f035d41b 374 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
0731742a
XL
375 if let GenericParamKind::Lifetime { .. } = param.kind {
376 self.check_snake_case(cx, "lifetime", &param.name.ident());
ff7c6d11
XL
377 }
378 }
379
0731742a
XL
380 fn check_fn(
381 &mut self,
f035d41b 382 cx: &LateContext<'_>,
9fa01778 383 fk: FnKind<'_>,
dfeec247
XL
384 _: &hir::FnDecl<'_>,
385 _: &hir::Body<'_>,
0731742a 386 _: Span,
9ffffee4 387 id: LocalDefId,
0731742a
XL
388 ) {
389 match &fk {
94222f64 390 FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
dfeec247 391 MethodLateContext::PlainImpl => {
353b0b11 392 if sig.header.abi != Abi::Rust && cx.tcx.has_attr(id, sym::no_mangle) {
94222f64
XL
393 return;
394 }
dfeec247 395 self.check_snake_case(cx, "method", ident);
c30ab7b3 396 }
dfeec247
XL
397 MethodLateContext::TraitAutoImpl => {
398 self.check_snake_case(cx, "trait method", ident);
399 }
400 _ => (),
401 },
04454e1e 402 FnKind::ItemFn(ident, _, header) => {
ea8adc8c 403 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
353b0b11 404 if header.abi != Abi::Rust && cx.tcx.has_attr(id, sym::no_mangle) {
ea8adc8c
XL
405 return;
406 }
0731742a 407 self.check_snake_case(cx, "function", ident);
c30ab7b3 408 }
6a06907d 409 FnKind::Closure => (),
b039eaaf
SL
410 }
411 }
412
f035d41b 413 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
e74abb32 414 if let hir::ItemKind::Mod(_) = it.kind {
0731742a 415 self.check_snake_case(cx, "module", &it.ident);
b039eaaf
SL
416 }
417 }
418
f035d41b 419 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
ba9703b0 420 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
0731742a 421 self.check_snake_case(cx, "trait method", &item.ident);
8faf50e0 422 for param_name in pnames {
0731742a 423 self.check_snake_case(cx, "variable", param_name);
32a655c1 424 }
b039eaaf
SL
425 }
426 }
427
f035d41b 428 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
5869c6ff 429 if let PatKind::Binding(_, hid, ident, _) = p.kind {
9c376795 430 if let hir::Node::PatField(field) = cx.tcx.hir().get_parent(hid) {
f2b60f7d
FG
431 if !field.is_shorthand {
432 // Only check if a new name has been introduced, to avoid warning
433 // on both the struct definition and this pattern.
434 self.check_snake_case(cx, "variable", &ident);
dfeec247 435 }
f2b60f7d 436 return;
dfeec247 437 }
0731742a 438 self.check_snake_case(cx, "variable", &ident);
476ff2be 439 }
b039eaaf
SL
440 }
441
f035d41b 442 fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
b039eaaf 443 for sf in s.fields() {
0731742a 444 self.check_snake_case(cx, "structure field", &sf.ident);
b039eaaf
SL
445 }
446 }
447}
448
449declare_lint! {
1b1a35ee
XL
450 /// The `non_upper_case_globals` lint detects static items that don't have
451 /// uppercase identifiers.
452 ///
453 /// ### Example
454 ///
455 /// ```rust
456 /// static max_points: i32 = 5;
457 /// ```
458 ///
459 /// {{produces}}
460 ///
461 /// ### Explanation
462 ///
463 /// The preferred style is for static item names to use all uppercase
464 /// letters such as `MAX_POINTS`.
b039eaaf
SL
465 pub NON_UPPER_CASE_GLOBALS,
466 Warn,
467 "static constants should have uppercase identifiers"
468}
469
532ac7d7 470declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
b039eaaf
SL
471
472impl NonUpperCaseGlobals {
f035d41b 473 fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
a2a8927a 474 let name = ident.name.as_str();
0731742a 475 if name.chars().any(|c| c.is_lowercase()) {
9c376795
FG
476 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
477 // We cannot provide meaningful suggestions
478 // if the characters are in the category of "Lowercase Letter".
479 let sub = if *name != uc {
480 NonUpperCaseGlobalSub::Suggestion { span: ident.span, replace: uc }
481 } else {
482 NonUpperCaseGlobalSub::Label { span: ident.span }
483 };
484 cx.emit_spanned_lint(
2b03887a
FG
485 NON_UPPER_CASE_GLOBALS,
486 ident.span,
9c376795
FG
487 NonUpperCaseGlobal { sort, name, sub },
488 );
b039eaaf
SL
489 }
490 }
491}
492
f035d41b
XL
493impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
494 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
6a06907d 495 let attrs = cx.tcx.hir().attrs(it.hir_id());
e74abb32 496 match it.kind {
353b0b11 497 hir::ItemKind::Static(..) if !attr::contains_name(attrs, sym::no_mangle) => {
0731742a 498 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
b039eaaf 499 }
8faf50e0 500 hir::ItemKind::Const(..) => {
0731742a 501 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
b039eaaf
SL
502 }
503 _ => {}
504 }
505 }
506
f035d41b 507 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
e74abb32 508 if let hir::TraitItemKind::Const(..) = ti.kind {
0731742a 509 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
b039eaaf
SL
510 }
511 }
512
f035d41b 513 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
49aad941 514 if let hir::ImplItemKind::Const(..) = ii.kind && !assoc_item_in_trait_impl(cx, ii) {
0731742a 515 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
b039eaaf
SL
516 }
517 }
518
f035d41b 519 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
b039eaaf 520 // Lint for constants that look like binding identifiers (#7526)
e74abb32 521 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
48663c56 522 if let Res::Def(DefKind::Const, _) = path.res {
32a655c1 523 if path.segments.len() == 1 {
0731742a
XL
524 NonUpperCaseGlobals::check_upper_case(
525 cx,
526 "constant in pattern",
dfeec247 527 &path.segments[0].ident,
0731742a 528 );
3157f602 529 }
b039eaaf 530 }
b039eaaf
SL
531 }
532 }
9fa01778 533
f035d41b 534 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
9fa01778 535 if let GenericParamKind::Const { .. } = param.kind {
dfeec247 536 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
9fa01778
XL
537 }
538 }
539}
540
541#[cfg(test)]
dc9dc135 542mod tests;