]> git.proxmox.com Git - rustc.git/blob - src/librustc_lint/nonstandard_style.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_lint / nonstandard_style.rs
1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
2 use rustc_ast::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 pub NON_CAMEL_CASE_TYPES,
35 Warn,
36 "types, variants, traits and type parameters should have camel case names"
37 }
38
39 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
40
41 fn char_has_case(c: char) -> bool {
42 c.is_lowercase() || c.is_uppercase()
43 }
44
45 fn is_camel_case(name: &str) -> bool {
46 let name = name.trim_matches('_');
47 if name.is_empty() {
48 return true;
49 }
50
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;
86 }
87
88 camel_cased_component
89 })
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 })
102 .0
103 }
104
105 impl NonCamelCaseTypes {
106 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
107 let name = &ident.name.as_str();
108
109 if !is_camel_case(name) {
110 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, |lint| {
111 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
112 lint.build(&msg)
113 .span_suggestion(
114 ident.span,
115 "convert the identifier to upper camel case",
116 to_camel_case(name),
117 Applicability::MaybeIncorrect,
118 )
119 .emit()
120 })
121 }
122 }
123 }
124
125 impl EarlyLintPass for NonCamelCaseTypes {
126 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
127 let has_repr_c = it
128 .attrs
129 .iter()
130 .any(|attr| attr::find_repr_attrs(&cx.sess.parse_sess, attr).contains(&attr::ReprC));
131
132 if has_repr_c {
133 return;
134 }
135
136 match it.kind {
137 ast::ItemKind::TyAlias(..)
138 | ast::ItemKind::Enum(..)
139 | ast::ItemKind::Struct(..)
140 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
141 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
142 _ => (),
143 }
144 }
145
146 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
147 if let ast::AssocItemKind::TyAlias(..) = it.kind {
148 self.check_case(cx, "associated type", &it.ident);
149 }
150 }
151
152 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
153 self.check_case(cx, "variant", &v.ident);
154 }
155
156 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
157 if let ast::GenericParamKind::Type { .. } = param.kind {
158 self.check_case(cx, "type parameter", &param.ident);
159 }
160 }
161 }
162
163 declare_lint! {
164 pub NON_SNAKE_CASE,
165 Warn,
166 "variables, methods, functions, lifetime parameters and modules should have snake case names"
167 }
168
169 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
170
171 impl NonSnakeCase {
172 fn to_snake_case(mut str: &str) -> String {
173 let mut words = vec![];
174 // Preserve leading underscores
175 str = str.trim_start_matches(|c: char| {
176 if c == '_' {
177 words.push(String::new());
178 true
179 } else {
180 false
181 }
182 });
183 for s in str.split('_') {
184 let mut last_upper = false;
185 let mut buf = String::new();
186 if s.is_empty() {
187 continue;
188 }
189 for ch in s.chars() {
190 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
191 words.push(buf);
192 buf = String::new();
193 }
194 last_upper = ch.is_uppercase();
195 buf.extend(ch.to_lowercase());
196 }
197 words.push(buf);
198 }
199 words.join("_")
200 }
201
202 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
203 fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
204 fn is_snake_case(ident: &str) -> bool {
205 if ident.is_empty() {
206 return true;
207 }
208 let ident = ident.trim_start_matches('\'');
209 let ident = ident.trim_matches('_');
210
211 let mut allow_underscore = true;
212 ident.chars().all(|c| {
213 allow_underscore = match c {
214 '_' if !allow_underscore => return false,
215 '_' => false,
216 // It would be more obvious to use `c.is_lowercase()`,
217 // but some characters do not have a lowercase form
218 c if !c.is_uppercase() => true,
219 _ => return false,
220 };
221 true
222 })
223 }
224
225 let name = &ident.name.as_str();
226
227 if !is_snake_case(name) {
228 cx.struct_span_lint(NON_SNAKE_CASE, ident.span, |lint| {
229 let sc = NonSnakeCase::to_snake_case(name);
230 let msg = format!("{} `{}` should have a snake case name", sort, name);
231 let mut err = lint.build(&msg);
232 // We have a valid span in almost all cases, but we don't have one when linting a crate
233 // name provided via the command line.
234 if !ident.span.is_dummy() {
235 err.span_suggestion(
236 ident.span,
237 "convert the identifier to snake case",
238 sc,
239 Applicability::MaybeIncorrect,
240 );
241 } else {
242 err.help(&format!("convert the identifier to snake case: `{}`", sc));
243 }
244
245 err.emit();
246 });
247 }
248 }
249 }
250
251 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
252 fn check_mod(
253 &mut self,
254 cx: &LateContext<'_, '_>,
255 _: &'tcx hir::Mod<'tcx>,
256 _: Span,
257 id: hir::HirId,
258 ) {
259 if id != hir::CRATE_HIR_ID {
260 return;
261 }
262
263 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
264 Some(Ident::from_str(name))
265 } else {
266 attr::find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
267 .and_then(|attr| attr.meta())
268 .and_then(|meta| {
269 meta.name_value_literal().and_then(|lit| {
270 if let ast::LitKind::Str(name, ..) = lit.kind {
271 // Discard the double quotes surrounding the literal.
272 let sp = cx
273 .sess()
274 .source_map()
275 .span_to_snippet(lit.span)
276 .ok()
277 .and_then(|snippet| {
278 let left = snippet.find('"')?;
279 let right =
280 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
281
282 Some(
283 lit.span
284 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
285 .with_hi(lit.span.hi() - BytePos(right as u32)),
286 )
287 })
288 .unwrap_or_else(|| lit.span);
289
290 Some(Ident::new(name, sp))
291 } else {
292 None
293 }
294 })
295 })
296 };
297
298 if let Some(ident) = &crate_ident {
299 self.check_snake_case(cx, "crate", ident);
300 }
301 }
302
303 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
304 if let GenericParamKind::Lifetime { .. } = param.kind {
305 self.check_snake_case(cx, "lifetime", &param.name.ident());
306 }
307 }
308
309 fn check_fn(
310 &mut self,
311 cx: &LateContext<'_, '_>,
312 fk: FnKind<'_>,
313 _: &hir::FnDecl<'_>,
314 _: &hir::Body<'_>,
315 _: Span,
316 id: hir::HirId,
317 ) {
318 match &fk {
319 FnKind::Method(ident, ..) => match method_context(cx, id) {
320 MethodLateContext::PlainImpl => {
321 self.check_snake_case(cx, "method", ident);
322 }
323 MethodLateContext::TraitAutoImpl => {
324 self.check_snake_case(cx, "trait method", ident);
325 }
326 _ => (),
327 },
328 FnKind::ItemFn(ident, _, header, _, attrs) => {
329 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
330 if header.abi != Abi::Rust && attr::contains_name(attrs, sym::no_mangle) {
331 return;
332 }
333 self.check_snake_case(cx, "function", ident);
334 }
335 FnKind::Closure(_) => (),
336 }
337 }
338
339 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
340 if let hir::ItemKind::Mod(_) = it.kind {
341 self.check_snake_case(cx, "module", &it.ident);
342 }
343 }
344
345 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) {
346 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
347 self.check_snake_case(cx, "trait method", &item.ident);
348 for param_name in pnames {
349 self.check_snake_case(cx, "variable", param_name);
350 }
351 }
352 }
353
354 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
355 if let &PatKind::Binding(_, hid, ident, _) = &p.kind {
356 if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
357 {
358 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
359 for field in field_pats.iter() {
360 if field.ident != ident {
361 // Only check if a new name has been introduced, to avoid warning
362 // on both the struct definition and this pattern.
363 self.check_snake_case(cx, "variable", &ident);
364 }
365 }
366 return;
367 }
368 }
369 self.check_snake_case(cx, "variable", &ident);
370 }
371 }
372
373 fn check_struct_def(&mut self, cx: &LateContext<'_, '_>, s: &hir::VariantData<'_>) {
374 for sf in s.fields() {
375 self.check_snake_case(cx, "structure field", &sf.ident);
376 }
377 }
378 }
379
380 declare_lint! {
381 pub NON_UPPER_CASE_GLOBALS,
382 Warn,
383 "static constants should have uppercase identifiers"
384 }
385
386 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
387
388 impl NonUpperCaseGlobals {
389 fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
390 let name = &ident.name.as_str();
391 if name.chars().any(|c| c.is_lowercase()) {
392 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
393 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
394 lint.build(&format!("{} `{}` should have an upper case name", sort, name))
395 .span_suggestion(
396 ident.span,
397 "convert the identifier to upper case",
398 uc,
399 Applicability::MaybeIncorrect,
400 )
401 .emit();
402 })
403 }
404 }
405 }
406
407 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
408 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
409 match it.kind {
410 hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, sym::no_mangle) => {
411 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
412 }
413 hir::ItemKind::Const(..) => {
414 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
415 }
416 _ => {}
417 }
418 }
419
420 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem<'_>) {
421 if let hir::TraitItemKind::Const(..) = ti.kind {
422 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
423 }
424 }
425
426 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem<'_>) {
427 if let hir::ImplItemKind::Const(..) = ii.kind {
428 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
429 }
430 }
431
432 fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) {
433 // Lint for constants that look like binding identifiers (#7526)
434 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
435 if let Res::Def(DefKind::Const, _) = path.res {
436 if path.segments.len() == 1 {
437 NonUpperCaseGlobals::check_upper_case(
438 cx,
439 "constant in pattern",
440 &path.segments[0].ident,
441 );
442 }
443 }
444 }
445 }
446
447 fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) {
448 if let GenericParamKind::Const { .. } = param.kind {
449 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", &param.name.ident());
450 }
451 }
452 }
453
454 #[cfg(test)]
455 mod tests;