1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc_attr as attr;
4 use rustc_errors::Applicability;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::intravisit::FnKind;
8 use rustc_hir::{GenericParamKind, PatKind};
10 use rustc_span::symbol::sym;
11 use rustc_span::{symbol::Ident, BytePos, Span};
12 use rustc_target::spec::abi::Abi;
15 pub enum MethodLateContext {
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,
34 /// The `non_camel_case_types` lint detects types, variants, traits and
35 /// type parameters that don't have camel case names.
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,
54 "types, variants, traits and type parameters should have camel case names"
57 declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
59 fn char_has_case(c: char) -> bool {
60 c.is_lowercase() || c.is_uppercase()
63 fn is_camel_case(name: &str) -> bool {
64 let name = name.trim_matches('_');
69 // start with a non-lowercase letter rather than non-uppercase
70 // ones (some scripts don't have a concept of upper/lowercase)
71 !name.chars().next().unwrap().is_lowercase()
72 && !name.contains("__")
73 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
74 // contains a capitalisable character followed by, or preceded by, an underscore
75 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
79 fn to_camel_case(s: &str) -> String {
82 .filter(|component| !component.is_empty())
84 let mut camel_cased_component = String::new();
86 let mut new_word = true;
87 let mut prev_is_lower_case = true;
89 for c in component.chars() {
90 // Preserve the case if an uppercase letter follows a lowercase letter, so that
91 // `camelCase` is converted to `CamelCase`.
92 if prev_is_lower_case && c.is_uppercase() {
97 camel_cased_component.push_str(&c.to_uppercase().to_string());
99 camel_cased_component.push_str(&c.to_lowercase().to_string());
102 prev_is_lower_case = c.is_lowercase();
106 camel_cased_component
108 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
109 // separate two components with an underscore if their boundary cannot
110 // be distinguished using a uppercase/lowercase case distinction
111 let join = if let Some(prev) = prev {
112 let l = prev.chars().last().unwrap();
113 let f = next.chars().next().unwrap();
114 !char_has_case(l) && !char_has_case(f)
118 (acc + if join { "_" } else { "" } + &next, Some(next))
123 impl NonCamelCaseTypes {
124 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
125 let name = &ident.name.as_str();
127 if !is_camel_case(name) {
128 cx.struct_span_lint(NON_CAMEL_CASE_TYPES, ident.span, |lint| {
129 let msg = format!("{} `{}` should have an upper camel case name", sort, name);
133 "convert the identifier to upper camel case",
135 Applicability::MaybeIncorrect,
143 impl EarlyLintPass for NonCamelCaseTypes {
144 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
148 .any(|attr| attr::find_repr_attrs(&cx.sess, attr).contains(&attr::ReprC));
155 ast::ItemKind::TyAlias(..)
156 | ast::ItemKind::Enum(..)
157 | ast::ItemKind::Struct(..)
158 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
159 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
164 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
165 if let ast::AssocItemKind::TyAlias(..) = it.kind {
166 self.check_case(cx, "associated type", &it.ident);
170 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
171 self.check_case(cx, "variant", &v.ident);
174 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
175 if let ast::GenericParamKind::Type { .. } = param.kind {
176 self.check_case(cx, "type parameter", ¶m.ident);
182 /// The `non_snake_case` lint detects variables, methods, functions,
183 /// lifetime parameters and modules that don't have snake case names.
188 /// let MY_VALUE = 5;
195 /// The preferred style for these identifiers is to use "snake case",
196 /// where all the characters are in lowercase, with words separated with a
197 /// single underscore, such as `my_value`.
200 "variables, methods, functions, lifetime parameters and modules should have snake case names"
203 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
206 fn to_snake_case(mut str: &str) -> String {
207 let mut words = vec![];
208 // Preserve leading underscores
209 str = str.trim_start_matches(|c: char| {
211 words.push(String::new());
217 for s in str.split('_') {
218 let mut last_upper = false;
219 let mut buf = String::new();
223 for ch in s.chars() {
224 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
228 last_upper = ch.is_uppercase();
229 buf.extend(ch.to_lowercase());
236 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
237 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
238 fn is_snake_case(ident: &str) -> bool {
239 if ident.is_empty() {
242 let ident = ident.trim_start_matches('\'');
243 let ident = ident.trim_matches('_');
245 let mut allow_underscore = true;
246 ident.chars().all(|c| {
247 allow_underscore = match c {
248 '_' if !allow_underscore => return false,
250 // It would be more obvious to use `c.is_lowercase()`,
251 // but some characters do not have a lowercase form
252 c if !c.is_uppercase() => true,
259 let name = &ident.name.as_str();
261 if !is_snake_case(name) {
262 cx.struct_span_lint(NON_SNAKE_CASE, ident.span, |lint| {
263 let sc = NonSnakeCase::to_snake_case(name);
264 let msg = format!("{} `{}` should have a snake case name", sort, name);
265 let mut err = lint.build(&msg);
266 // We have a valid span in almost all cases, but we don't have one when linting a crate
267 // name provided via the command line.
268 if !ident.span.is_dummy() {
271 "convert the identifier to snake case",
273 Applicability::MaybeIncorrect,
276 err.help(&format!("convert the identifier to snake case: `{}`", sc));
285 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
288 cx: &LateContext<'_>,
289 _: &'tcx hir::Mod<'tcx>,
293 if id != hir::CRATE_HIR_ID {
297 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
298 Some(Ident::from_str(name))
301 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
302 .and_then(|attr| attr.meta())
304 meta.name_value_literal().and_then(|lit| {
305 if let ast::LitKind::Str(name, ..) = lit.kind {
306 // Discard the double quotes surrounding the literal.
310 .span_to_snippet(lit.span)
312 .and_then(|snippet| {
313 let left = snippet.find('"')?;
315 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
319 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
320 .with_hi(lit.span.hi() - BytePos(right as u32)),
323 .unwrap_or(lit.span);
325 Some(Ident::new(name, sp))
333 if let Some(ident) = &crate_ident {
334 self.check_snake_case(cx, "crate", ident);
338 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
339 if let GenericParamKind::Lifetime { .. } = param.kind {
340 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
346 cx: &LateContext<'_>,
354 FnKind::Method(ident, ..) => match method_context(cx, id) {
355 MethodLateContext::PlainImpl => {
356 self.check_snake_case(cx, "method", ident);
358 MethodLateContext::TraitAutoImpl => {
359 self.check_snake_case(cx, "trait method", ident);
363 FnKind::ItemFn(ident, _, header, _, attrs) => {
364 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
365 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
368 self.check_snake_case(cx, "function", ident);
370 FnKind::Closure(_) => (),
374 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
375 if let hir::ItemKind::Mod(_) = it.kind {
376 self.check_snake_case(cx, "module", &it.ident);
380 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
381 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
382 self.check_snake_case(cx, "trait method", &item.ident);
383 for param_name in pnames {
384 self.check_snake_case(cx, "variable", param_name);
389 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
390 if let &PatKind::Binding(_, hid, ident, _) = &p.kind {
391 if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
393 if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind {
394 for field in field_pats.iter() {
395 if field.ident != ident {
396 // Only check if a new name has been introduced, to avoid warning
397 // on both the struct definition and this pattern.
398 self.check_snake_case(cx, "variable", &ident);
404 self.check_snake_case(cx, "variable", &ident);
408 fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
409 for sf in s.fields() {
410 self.check_snake_case(cx, "structure field", &sf.ident);
416 /// The `non_upper_case_globals` lint detects static items that don't have
417 /// uppercase identifiers.
422 /// static max_points: i32 = 5;
429 /// The preferred style is for static item names to use all uppercase
430 /// letters such as `MAX_POINTS`.
431 pub NON_UPPER_CASE_GLOBALS,
433 "static constants should have uppercase identifiers"
436 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
438 impl NonUpperCaseGlobals {
439 fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
440 let name = &ident.name.as_str();
441 if name.chars().any(|c| c.is_lowercase()) {
442 cx.struct_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, |lint| {
443 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
444 lint.build(&format!("{} `{}` should have an upper case name", sort, name))
447 "convert the identifier to upper case",
449 Applicability::MaybeIncorrect,
457 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
458 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
460 hir::ItemKind::Static(..) if !cx.sess().contains_name(&it.attrs, sym::no_mangle) => {
461 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
463 hir::ItemKind::Const(..) => {
464 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
470 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
471 if let hir::TraitItemKind::Const(..) = ti.kind {
472 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
476 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
477 if let hir::ImplItemKind::Const(..) = ii.kind {
478 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
482 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
483 // Lint for constants that look like binding identifiers (#7526)
484 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
485 if let Res::Def(DefKind::Const, _) = path.res {
486 if path.segments.len() == 1 {
487 NonUpperCaseGlobals::check_upper_case(
489 "constant in pattern",
490 &path.segments[0].ident,
497 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
498 if let GenericParamKind::Const { .. } = param.kind {
499 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());