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