]> git.proxmox.com Git - rustc.git/blame - src/librustc_lint/nonstandard_style.rs
New upstream version 1.35.0+dfsg1
[rustc.git] / src / librustc_lint / nonstandard_style.rs
CommitLineData
0731742a 1use rustc::hir::{self, GenericParamKind, PatKind};
54a0048b 2use rustc::hir::def::Def;
0731742a 3use rustc::hir::intravisit::FnKind;
9fa01778 4use rustc::lint;
54a0048b 5use rustc::ty;
83c7162d 6use rustc_target::spec::abi::Abi;
0731742a
XL
7use lint::{EarlyContext, LateContext, LintContext, LintArray};
8use lint::{EarlyLintPass, LintPass, LateLintPass};
b039eaaf 9use syntax::ast;
9e0c209e 10use syntax::attr;
0731742a
XL
11use syntax::errors::Applicability;
12use syntax_pos::{BytePos, symbol::Ident, Span};
b039eaaf
SL
13
14#[derive(PartialEq)]
15pub enum MethodLateContext {
abe05a73 16 TraitAutoImpl,
b039eaaf 17 TraitImpl,
c30ab7b3 18 PlainImpl,
b039eaaf
SL
19}
20
9fa01778
XL
21pub fn method_context(cx: &LateContext<'_, '_>, id: hir::HirId) -> MethodLateContext {
22 let def_id = cx.tcx.hir().local_def_id_from_hir_id(id);
7cac9316
XL
23 let item = cx.tcx.associated_item(def_id);
24 match item.container {
abe05a73 25 ty::TraitContainer(..) => MethodLateContext::TraitAutoImpl,
7cac9316
XL
26 ty::ImplContainer(cid) => {
27 match cx.tcx.impl_trait_ref(cid) {
28 Some(_) => MethodLateContext::TraitImpl,
29 None => MethodLateContext::PlainImpl,
b039eaaf
SL
30 }
31 }
32 }
33}
34
35declare_lint! {
36 pub NON_CAMEL_CASE_TYPES,
37 Warn,
38 "types, variants, traits and type parameters should have camel case names"
39}
40
532ac7d7
XL
41declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
42
9fa01778
XL
43fn char_has_case(c: char) -> bool {
44 c.is_lowercase() || c.is_uppercase()
45}
b039eaaf 46
9fa01778
XL
47fn is_camel_case(name: &str) -> bool {
48 let name = name.trim_matches('_');
49 if name.is_empty() {
50 return true;
51 }
2c00a5a8 52
9fa01778
XL
53 // start with a non-lowercase letter rather than non-uppercase
54 // ones (some scripts don't have a concept of upper/lowercase)
55 !name.chars().next().unwrap().is_lowercase()
56 && !name.contains("__")
57 && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| {
58 // contains a capitalisable character followed by, or preceded by, an underscore
59 char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_'
60 })
61}
62
63fn to_camel_case(s: &str) -> String {
64 s.trim_matches('_')
65 .split('_')
66 .filter(|component| !component.is_empty())
67 .map(|component| {
68 let mut camel_cased_component = String::new();
69
70 let mut new_word = true;
71 let mut prev_is_lower_case = true;
72
73 for c in component.chars() {
74 // Preserve the case if an uppercase letter follows a lowercase letter, so that
75 // `camelCase` is converted to `CamelCase`.
76 if prev_is_lower_case && c.is_uppercase() {
77 new_word = true;
78 }
79
80 if new_word {
81 camel_cased_component.push_str(&c.to_uppercase().to_string());
82 } else {
83 camel_cased_component.push_str(&c.to_lowercase().to_string());
84 }
85
86 prev_is_lower_case = c.is_lowercase();
87 new_word = false;
b039eaaf 88 }
b039eaaf 89
9fa01778
XL
90 camel_cased_component
91 })
92 .fold(
93 (String::new(), None),
94 |(acc, prev): (String, Option<String>), next| {
95 // separate two components with an underscore if their boundary cannot
96 // be distinguished using a uppercase/lowercase case distinction
97 let join = if let Some(prev) = prev {
98 let l = prev.chars().last().unwrap();
99 let f = next.chars().next().unwrap();
100 !char_has_case(l) && !char_has_case(f)
101 } else {
102 false
103 };
104 (acc + if join { "_" } else { "" } + &next, Some(next))
105 },
106 )
107 .0
108}
b039eaaf 109
9fa01778
XL
110impl NonCamelCaseTypes {
111 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
0731742a
XL
112 let name = &ident.name.as_str();
113
b039eaaf 114 if !is_camel_case(name) {
9fa01778 115 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
0731742a 116 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, &msg)
9fa01778 117 .span_suggestion(
0731742a 118 ident.span,
9fa01778
XL
119 "convert the identifier to upper camel case",
120 to_camel_case(name),
0731742a
XL
121 Applicability::MaybeIncorrect,
122 )
123 .emit();
b039eaaf
SL
124 }
125 }
126}
127
0731742a 128impl EarlyLintPass for NonCamelCaseTypes {
9fa01778 129 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
2c00a5a8 130 let has_repr_c = it.attrs
c30ab7b3 131 .iter()
9fa01778 132 .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
b039eaaf 133
2c00a5a8 134 if has_repr_c {
b039eaaf
SL
135 return;
136 }
137
138 match it.node {
0731742a
XL
139 ast::ItemKind::Ty(..) |
140 ast::ItemKind::Enum(..) |
141 ast::ItemKind::Struct(..) |
142 ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
143 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
c30ab7b3 144 _ => (),
b039eaaf
SL
145 }
146 }
147
9fa01778 148 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
0731742a 149 self.check_case(cx, "variant", &v.node.ident);
8bb4bdeb
XL
150 }
151
9fa01778 152 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
0731742a
XL
153 if let ast::GenericParamKind::Type { .. } = param.kind {
154 self.check_case(cx, "type parameter", &param.ident);
b039eaaf
SL
155 }
156 }
157}
158
159declare_lint! {
160 pub NON_SNAKE_CASE,
161 Warn,
92a42be0 162 "variables, methods, functions, lifetime parameters and modules should have snake case names"
b039eaaf
SL
163}
164
532ac7d7 165declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
b039eaaf
SL
166
167impl NonSnakeCase {
168 fn to_snake_case(mut str: &str) -> String {
169 let mut words = vec![];
170 // Preserve leading underscores
0731742a 171 str = str.trim_start_matches(|c: char| {
b039eaaf
SL
172 if c == '_' {
173 words.push(String::new());
174 true
175 } else {
176 false
177 }
178 });
179 for s in str.split('_') {
180 let mut last_upper = false;
181 let mut buf = String::new();
182 if s.is_empty() {
183 continue;
184 }
185 for ch in s.chars() {
c30ab7b3 186 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
b039eaaf
SL
187 words.push(buf);
188 buf = String::new();
189 }
190 last_upper = ch.is_uppercase();
191 buf.extend(ch.to_lowercase());
192 }
193 words.push(buf);
194 }
195 words.join("_")
196 }
197
0731742a 198 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
9fa01778 199 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
b039eaaf
SL
200 fn is_snake_case(ident: &str) -> bool {
201 if ident.is_empty() {
202 return true;
203 }
0731742a 204 let ident = ident.trim_start_matches('\'');
b039eaaf
SL
205 let ident = ident.trim_matches('_');
206
207 let mut allow_underscore = true;
208 ident.chars().all(|c| {
209 allow_underscore = match c {
210 '_' if !allow_underscore => return false,
211 '_' => false,
212 // It would be more obvious to use `c.is_lowercase()`,
213 // but some characters do not have a lowercase form
214 c if !c.is_uppercase() => true,
215 _ => return false,
216 };
217 true
218 })
219 }
220
0731742a
XL
221 let name = &ident.name.as_str();
222
b039eaaf
SL
223 if !is_snake_case(name) {
224 let sc = NonSnakeCase::to_snake_case(name);
0731742a
XL
225
226 let msg = format!("{} `{}` should have a snake case name", sort, name);
227 let mut err = cx.struct_span_lint(NON_SNAKE_CASE, ident.span, &msg);
228
229 // We have a valid span in almost all cases, but we don't have one when linting a crate
230 // name provided via the command line.
231 if !ident.span.is_dummy() {
9fa01778 232 err.span_suggestion(
0731742a
XL
233 ident.span,
234 "convert the identifier to snake case",
235 sc,
236 Applicability::MaybeIncorrect,
237 );
b039eaaf 238 } else {
0731742a 239 err.help(&format!("convert the identifier to snake case: `{}`", sc));
b039eaaf 240 }
0731742a
XL
241
242 err.emit();
b039eaaf
SL
243 }
244 }
245}
246
476ff2be 247impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
532ac7d7
XL
248 fn check_mod(&mut self, cx: &LateContext<'_, '_>, _: &'tcx hir::Mod, _: Span, id: hir::HirId) {
249 if id != hir::CRATE_HIR_ID {
250 return;
251 }
252
0731742a
XL
253 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
254 Some(Ident::from_str(name))
255 } else {
532ac7d7 256 attr::find_by_name(&cx.tcx.hir().attrs_by_hir_id(hir::CRATE_HIR_ID), "crate_name")
0731742a
XL
257 .and_then(|attr| attr.meta())
258 .and_then(|meta| {
259 meta.name_value_literal().and_then(|lit| {
260 if let ast::LitKind::Str(name, ..) = lit.node {
261 // Discard the double quotes surrounding the literal.
262 let sp = cx.sess().source_map().span_to_snippet(lit.span)
263 .ok()
264 .and_then(|snippet| {
265 let left = snippet.find('"')?;
266 let right = snippet.rfind('"').map(|pos| snippet.len() - pos)?;
267
268 Some(
269 lit.span
270 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
271 .with_hi(lit.span.hi() - BytePos(right as u32)),
272 )
273 })
274 .unwrap_or_else(|| lit.span);
275
276 Some(Ident::new(name, sp))
277 } else {
278 None
279 }
280 })
281 })
282 };
283
284 if let Some(ident) = &crate_ident {
285 self.check_snake_case(cx, "crate", ident);
b039eaaf
SL
286 }
287 }
288
9fa01778 289 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
0731742a
XL
290 if let GenericParamKind::Lifetime { .. } = param.kind {
291 self.check_snake_case(cx, "lifetime", &param.name.ident());
ff7c6d11
XL
292 }
293 }
294
0731742a
XL
295 fn check_fn(
296 &mut self,
9fa01778
XL
297 cx: &LateContext<'_, '_>,
298 fk: FnKind<'_>,
0731742a
XL
299 _: &hir::FnDecl,
300 _: &hir::Body,
301 _: Span,
9fa01778 302 id: hir::HirId,
0731742a
XL
303 ) {
304 match &fk {
305 FnKind::Method(ident, ..) => {
7cac9316 306 match method_context(cx, id) {
c30ab7b3 307 MethodLateContext::PlainImpl => {
0731742a 308 self.check_snake_case(cx, "method", ident);
c30ab7b3 309 }
abe05a73 310 MethodLateContext::TraitAutoImpl => {
0731742a 311 self.check_snake_case(cx, "trait method", ident);
c30ab7b3
SL
312 }
313 _ => (),
314 }
315 }
0731742a 316 FnKind::ItemFn(ident, _, header, _, attrs) => {
ea8adc8c 317 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
0731742a 318 if header.abi != Abi::Rust && attr::contains_name(attrs, "no_mangle") {
ea8adc8c
XL
319 return;
320 }
0731742a 321 self.check_snake_case(cx, "function", ident);
c30ab7b3 322 }
54a0048b 323 FnKind::Closure(_) => (),
b039eaaf
SL
324 }
325 }
326
9fa01778 327 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
8faf50e0 328 if let hir::ItemKind::Mod(_) = it.node {
0731742a 329 self.check_snake_case(cx, "module", &it.ident);
b039eaaf
SL
330 }
331 }
332
9fa01778 333 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) {
0731742a
XL
334 if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node {
335 self.check_snake_case(cx, "trait method", &item.ident);
8faf50e0 336 for param_name in pnames {
0731742a 337 self.check_snake_case(cx, "variable", param_name);
32a655c1 338 }
b039eaaf
SL
339 }
340 }
341
9fa01778 342 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
532ac7d7 343 if let &PatKind::Binding(_, _, ident, _) = &p.node {
0731742a 344 self.check_snake_case(cx, "variable", &ident);
476ff2be 345 }
b039eaaf
SL
346 }
347
0731742a
XL
348 fn check_struct_def(
349 &mut self,
9fa01778 350 cx: &LateContext<'_, '_>,
0731742a
XL
351 s: &hir::VariantData,
352 _: ast::Name,
353 _: &hir::Generics,
9fa01778 354 _: hir::HirId,
0731742a 355 ) {
b039eaaf 356 for sf in s.fields() {
0731742a 357 self.check_snake_case(cx, "structure field", &sf.ident);
b039eaaf
SL
358 }
359 }
360}
361
362declare_lint! {
363 pub NON_UPPER_CASE_GLOBALS,
364 Warn,
365 "static constants should have uppercase identifiers"
366}
367
532ac7d7 368declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
b039eaaf
SL
369
370impl NonUpperCaseGlobals {
9fa01778 371 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
0731742a
XL
372 let name = &ident.name.as_str();
373
374 if name.chars().any(|c| c.is_lowercase()) {
375 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
376
377 let msg = format!("{} `{}` should have an upper case name", sort, name);
378 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, &msg)
9fa01778 379 .span_suggestion(
0731742a
XL
380 ident.span,
381 "convert the identifier to upper case",
382 uc,
383 Applicability::MaybeIncorrect,
384 )
385 .emit();
b039eaaf
SL
386 }
387 }
388}
389
476ff2be 390impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
9fa01778 391 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
b039eaaf 392 match it.node {
0731742a
XL
393 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
394 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
b039eaaf 395 }
8faf50e0 396 hir::ItemKind::Const(..) => {
0731742a 397 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
b039eaaf
SL
398 }
399 _ => {}
400 }
401 }
402
9fa01778 403 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
0731742a
XL
404 if let hir::TraitItemKind::Const(..) = ti.node {
405 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
b039eaaf
SL
406 }
407 }
408
9fa01778 409 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
0731742a
XL
410 if let hir::ImplItemKind::Const(..) = ii.node {
411 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
b039eaaf
SL
412 }
413 }
414
9fa01778 415 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
b039eaaf 416 // Lint for constants that look like binding identifiers (#7526)
476ff2be 417 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
32a655c1
SL
418 if let Def::Const(..) = path.def {
419 if path.segments.len() == 1 {
0731742a
XL
420 NonUpperCaseGlobals::check_upper_case(
421 cx,
422 "constant in pattern",
423 &path.segments[0].ident
424 );
3157f602 425 }
b039eaaf 426 }
b039eaaf
SL
427 }
428 }
9fa01778
XL
429
430 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
431 if let GenericParamKind::Const { .. } = param.kind {
432 NonUpperCaseGlobals::check_upper_case(
433 cx,
434 "const parameter",
435 &param.name.ident(),
436 );
437 }
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use super::{is_camel_case, to_camel_case};
444
445 #[test]
446 fn camel_case() {
447 assert!(!is_camel_case("userData"));
448 assert_eq!(to_camel_case("userData"), "UserData");
449
450 assert!(is_camel_case("X86_64"));
451
452 assert!(!is_camel_case("X86__64"));
453 assert_eq!(to_camel_case("X86__64"), "X86_64");
454
455 assert!(!is_camel_case("Abc_123"));
456 assert_eq!(to_camel_case("Abc_123"), "Abc123");
457
458 assert!(!is_camel_case("A1_b2_c3"));
459 assert_eq!(to_camel_case("A1_b2_c3"), "A1B2C3");
460
461 assert!(!is_camel_case("ONE_TWO_THREE"));
462 assert_eq!(to_camel_case("ONE_TWO_THREE"), "OneTwoThree");
463 }
b039eaaf 464}