1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc_attr as attr;
4 use rustc_errors::{fluent, 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 => match cx.tcx.impl_trait_ref(item.container_id(cx.tcx)) {
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 /// Some unicode characters *have* case, are considered upper case or lower case, but they *can't*
60 /// be upper cased or lower cased. For the purposes of the lint suggestion, we care about being able
61 /// to change the char's case.
62 fn char_has_case(c: char) -> bool {
63 let mut l = c.to_lowercase();
64 let mut u = c.to_uppercase();
65 while let Some(l) = l.next() {
67 Some(u) if l != u => return true,
74 fn is_camel_case(name: &str) -> bool {
75 let name = name.trim_matches('_');
80 // start with a non-lowercase letter rather than non-uppercase
81 // ones (some scripts don't have a concept of upper/lowercase)
82 !name.chars().next().unwrap().is_lowercase()
83 && !name.contains("__")
84 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
85 // contains a capitalisable character followed by, or preceded by, an underscore
86 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
90 fn to_camel_case(s: &str) -> String {
93 .filter(|component| !component.is_empty())
95 let mut camel_cased_component = String::new();
97 let mut new_word = true;
98 let mut prev_is_lower_case = true;
100 for c in component.chars() {
101 // Preserve the case if an uppercase letter follows a lowercase letter, so that
102 // `camelCase` is converted to `CamelCase`.
103 if prev_is_lower_case && c.is_uppercase() {
108 camel_cased_component.extend(c.to_uppercase());
110 camel_cased_component.extend(c.to_lowercase());
113 prev_is_lower_case = c.is_lowercase();
117 camel_cased_component
119 .fold((String::new(), None), |(acc, prev): (String, Option<String>), next| {
120 // separate two components with an underscore if their boundary cannot
121 // be distinguished using an uppercase/lowercase case distinction
122 let join = if let Some(prev) = prev {
123 let l = prev.chars().last().unwrap();
124 let f = next.chars().next().unwrap();
125 !char_has_case(l) && !char_has_case(f)
129 (acc + if join { "_" } else { "" } + &next, Some(next))
134 impl NonCamelCaseTypes {
135 fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
136 let name = ident.name.as_str();
138 if !is_camel_case(name) {
140 NON_CAMEL_CASE_TYPES,
142 fluent::lint_non_camel_case_type,
144 let cc = to_camel_case(name);
145 // We cannot provide meaningful suggestions
146 // if the characters are in the category of "Lowercase Letter".
148 lint.span_suggestion(
152 Applicability::MaybeIncorrect,
155 lint.span_label(ident.span, fluent::label);
158 lint.set_arg("sort", sort);
159 lint.set_arg("name", name);
167 impl EarlyLintPass for NonCamelCaseTypes {
168 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
172 .any(|attr| attr::find_repr_attrs(cx.sess(), attr).contains(&attr::ReprC));
179 ast::ItemKind::TyAlias(..)
180 | ast::ItemKind::Enum(..)
181 | ast::ItemKind::Struct(..)
182 | ast::ItemKind::Union(..) => self.check_case(cx, "type", &it.ident),
183 ast::ItemKind::Trait(..) => self.check_case(cx, "trait", &it.ident),
184 ast::ItemKind::TraitAlias(..) => self.check_case(cx, "trait alias", &it.ident),
189 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
190 if let ast::AssocItemKind::Type(..) = it.kind {
191 self.check_case(cx, "associated type", &it.ident);
195 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
196 self.check_case(cx, "variant", &v.ident);
199 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
200 if let ast::GenericParamKind::Type { .. } = param.kind {
201 self.check_case(cx, "type parameter", ¶m.ident);
207 /// The `non_snake_case` lint detects variables, methods, functions,
208 /// lifetime parameters and modules that don't have snake case names.
213 /// let MY_VALUE = 5;
220 /// The preferred style for these identifiers is to use "snake case",
221 /// where all the characters are in lowercase, with words separated with a
222 /// single underscore, such as `my_value`.
225 "variables, methods, functions, lifetime parameters and modules should have snake case names"
228 declare_lint_pass!(NonSnakeCase => [NON_SNAKE_CASE]);
231 fn to_snake_case(mut str: &str) -> String {
232 let mut words = vec![];
233 // Preserve leading underscores
234 str = str.trim_start_matches(|c: char| {
236 words.push(String::new());
242 for s in str.split('_') {
243 let mut last_upper = false;
244 let mut buf = String::new();
248 for ch in s.chars() {
249 if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper {
253 last_upper = ch.is_uppercase();
254 buf.extend(ch.to_lowercase());
261 /// Checks if a given identifier is snake case, and reports a diagnostic if not.
262 fn check_snake_case(&self, cx: &LateContext<'_>, sort: &str, ident: &Ident) {
263 fn is_snake_case(ident: &str) -> bool {
264 if ident.is_empty() {
267 let ident = ident.trim_start_matches('\'');
268 let ident = ident.trim_matches('_');
270 let mut allow_underscore = true;
271 ident.chars().all(|c| {
272 allow_underscore = match c {
273 '_' if !allow_underscore => return false,
275 // It would be more obvious to use `c.is_lowercase()`,
276 // but some characters do not have a lowercase form
277 c if !c.is_uppercase() => true,
284 let name = ident.name.as_str();
286 if !is_snake_case(name) {
287 cx.struct_span_lint(NON_SNAKE_CASE, ident.span, fluent::lint_non_snake_case, |lint| {
288 let sc = NonSnakeCase::to_snake_case(name);
289 // We cannot provide meaningful suggestions
290 // if the characters are in the category of "Uppercase Letter".
292 // We have a valid span in almost all cases, but we don't have one when linting a crate
293 // name provided via the command line.
294 if !ident.span.is_dummy() {
295 let sc_ident = Ident::from_str_and_span(&sc, ident.span);
296 let (message, suggestion) = if sc_ident.is_reserved() {
297 // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers.
298 // Instead, recommend renaming the identifier entirely or, if permitted,
299 // escaping it to create a raw identifier.
300 if sc_ident.name.can_be_raw() {
301 (fluent::rename_or_convert_suggestion, sc_ident.to_string())
303 lint.note(fluent::cannot_convert_note);
304 (fluent::rename_suggestion, String::new())
307 (fluent::convert_suggestion, sc.clone())
310 lint.span_suggestion(
314 Applicability::MaybeIncorrect,
317 lint.help(fluent::help);
320 lint.span_label(ident.span, fluent::label);
323 lint.set_arg("sort", sort);
324 lint.set_arg("name", name);
325 lint.set_arg("sc", sc);
332 impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
333 fn check_mod(&mut self, cx: &LateContext<'_>, _: &'tcx hir::Mod<'tcx>, id: hir::HirId) {
334 if id != hir::CRATE_HIR_ID {
338 let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
339 Some(Ident::from_str(name))
342 .find_by_name(&cx.tcx.hir().attrs(hir::CRATE_HIR_ID), sym::crate_name)
343 .and_then(|attr| attr.meta())
345 meta.name_value_literal().and_then(|lit| {
346 if let ast::LitKind::Str(name, ..) = lit.kind {
347 // Discard the double quotes surrounding the literal.
351 .span_to_snippet(lit.span)
353 .and_then(|snippet| {
354 let left = snippet.find('"')?;
356 snippet.rfind('"').map(|pos| snippet.len() - pos)?;
360 .with_lo(lit.span.lo() + BytePos(left as u32 + 1))
361 .with_hi(lit.span.hi() - BytePos(right as u32)),
364 .unwrap_or(lit.span);
366 Some(Ident::new(name, sp))
374 if let Some(ident) = &crate_ident {
375 self.check_snake_case(cx, "crate", ident);
379 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
380 if let GenericParamKind::Lifetime { .. } = param.kind {
381 self.check_snake_case(cx, "lifetime", ¶m.name.ident());
387 cx: &LateContext<'_>,
394 let attrs = cx.tcx.hir().attrs(id);
396 FnKind::Method(ident, sig, ..) => match method_context(cx, id) {
397 MethodLateContext::PlainImpl => {
398 if sig.header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle)
402 self.check_snake_case(cx, "method", ident);
404 MethodLateContext::TraitAutoImpl => {
405 self.check_snake_case(cx, "trait method", ident);
409 FnKind::ItemFn(ident, _, header) => {
410 // Skip foreign-ABI #[no_mangle] functions (Issue #31924)
411 if header.abi != Abi::Rust && cx.sess().contains_name(attrs, sym::no_mangle) {
414 self.check_snake_case(cx, "function", ident);
416 FnKind::Closure => (),
420 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
421 if let hir::ItemKind::Mod(_) = it.kind {
422 self.check_snake_case(cx, "module", &it.ident);
426 fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &hir::TraitItem<'_>) {
427 if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind {
428 self.check_snake_case(cx, "trait method", &item.ident);
429 for param_name in pnames {
430 self.check_snake_case(cx, "variable", param_name);
435 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
436 if let PatKind::Binding(_, hid, ident, _) = p.kind {
437 if let hir::Node::PatField(field) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid))
439 if !field.is_shorthand {
440 // Only check if a new name has been introduced, to avoid warning
441 // on both the struct definition and this pattern.
442 self.check_snake_case(cx, "variable", &ident);
446 self.check_snake_case(cx, "variable", &ident);
450 fn check_struct_def(&mut self, cx: &LateContext<'_>, s: &hir::VariantData<'_>) {
451 for sf in s.fields() {
452 self.check_snake_case(cx, "structure field", &sf.ident);
458 /// The `non_upper_case_globals` lint detects static items that don't have
459 /// uppercase identifiers.
464 /// static max_points: i32 = 5;
471 /// The preferred style is for static item names to use all uppercase
472 /// letters such as `MAX_POINTS`.
473 pub NON_UPPER_CASE_GLOBALS,
475 "static constants should have uppercase identifiers"
478 declare_lint_pass!(NonUpperCaseGlobals => [NON_UPPER_CASE_GLOBALS]);
480 impl NonUpperCaseGlobals {
481 fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) {
482 let name = ident.name.as_str();
483 if name.chars().any(|c| c.is_lowercase()) {
485 NON_UPPER_CASE_GLOBALS,
487 fluent::lint_non_upper_case_global,
489 let uc = NonSnakeCase::to_snake_case(&name).to_uppercase();
490 // We cannot provide meaningful suggestions
491 // if the characters are in the category of "Lowercase Letter".
493 lint.span_suggestion(
497 Applicability::MaybeIncorrect,
500 lint.span_label(ident.span, fluent::label);
503 lint.set_arg("sort", sort);
504 lint.set_arg("name", name);
512 impl<'tcx> LateLintPass<'tcx> for NonUpperCaseGlobals {
513 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
514 let attrs = cx.tcx.hir().attrs(it.hir_id());
516 hir::ItemKind::Static(..) if !cx.sess().contains_name(attrs, sym::no_mangle) => {
517 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
519 hir::ItemKind::Const(..) => {
520 NonUpperCaseGlobals::check_upper_case(cx, "constant", &it.ident);
526 fn check_trait_item(&mut self, cx: &LateContext<'_>, ti: &hir::TraitItem<'_>) {
527 if let hir::TraitItemKind::Const(..) = ti.kind {
528 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
532 fn check_impl_item(&mut self, cx: &LateContext<'_>, ii: &hir::ImplItem<'_>) {
533 if let hir::ImplItemKind::Const(..) = ii.kind {
534 NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
538 fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) {
539 // Lint for constants that look like binding identifiers (#7526)
540 if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.kind {
541 if let Res::Def(DefKind::Const, _) = path.res {
542 if path.segments.len() == 1 {
543 NonUpperCaseGlobals::check_upper_case(
545 "constant in pattern",
546 &path.segments[0].ident,
553 fn check_generic_param(&mut self, cx: &LateContext<'_>, param: &hir::GenericParam<'_>) {
554 if let GenericParamKind::Const { .. } = param.kind {
555 NonUpperCaseGlobals::check_upper_case(cx, "const parameter", ¶m.name.ident());