1 //! Provides validators for names of declarations.
3 //! This includes the following items:
5 //! - variable bindings (e.g. `let x = foo();`)
6 //! - struct fields (e.g. `struct Foo { field: u8 }`)
7 //! - enum variants (e.g. `enum Foo { Variant { field: u8 } }`)
8 //! - function/method arguments (e.g. `fn foo(arg: u8)`)
9 //! - constants (e.g. `const FOO: u8 = 10;`)
10 //! - static items (e.g. `static FOO: u8 = 10;`)
11 //! - match arm bindings (e.g. `foo @ Some(_)`)
22 AdtId, AttrDefId, ConstId, EnumId, FunctionId, Lookup, ModuleDefId, StaticId, StructId,
28 use stdx::{always, never};
34 use crate::db::HirDatabase;
36 use self::case_conv::{to_camel_case, to_lower_snake_case, to_upper_snake_case};
39 pub(super) const BAD_STYLE: &str = "bad_style";
40 pub(super) const NONSTANDARD_STYLE: &str = "nonstandard_style";
41 pub(super) const NON_SNAKE_CASE: &str = "non_snake_case";
42 pub(super) const NON_UPPER_CASE_GLOBAL: &str = "non_upper_case_globals";
43 pub(super) const NON_CAMEL_CASE_TYPES: &str = "non_camel_case_types";
46 pub fn incorrect_case(
50 ) -> Vec<IncorrectCase> {
51 let _p = profile::span("validate_module_item");
52 let mut validator = DeclValidator::new(db, krate);
53 validator.validate_item(owner);
67 impl fmt::Display for CaseType {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 let repr = match self {
70 CaseType::LowerSnakeCase => "snake_case",
71 CaseType::UpperSnakeCase => "UPPER_SNAKE_CASE",
72 CaseType::UpperCamelCase => "CamelCase",
92 impl fmt::Display for IdentType {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 let repr = match self {
95 IdentType::Constant => "Constant",
96 IdentType::Enum => "Enum",
97 IdentType::Field => "Field",
98 IdentType::Function => "Function",
99 IdentType::Parameter => "Parameter",
100 IdentType::StaticVariable => "Static variable",
101 IdentType::Structure => "Structure",
102 IdentType::Variable => "Variable",
103 IdentType::Variant => "Variant",
106 write!(f, "{}", repr)
111 pub struct IncorrectCase {
113 pub ident: AstPtr<ast::Name>,
114 pub expected_case: CaseType,
115 pub ident_type: IdentType,
116 pub ident_text: String,
117 pub suggested_text: String,
120 pub(super) struct DeclValidator<'a> {
121 db: &'a dyn HirDatabase,
123 pub(super) sink: Vec<IncorrectCase>,
129 suggested_text: String,
130 expected_case: CaseType,
133 impl<'a> DeclValidator<'a> {
134 pub(super) fn new(db: &'a dyn HirDatabase, krate: CrateId) -> DeclValidator<'a> {
135 DeclValidator { db, krate, sink: Vec::new() }
138 pub(super) fn validate_item(&mut self, item: ModuleDefId) {
140 ModuleDefId::FunctionId(func) => self.validate_func(func),
141 ModuleDefId::AdtId(adt) => self.validate_adt(adt),
142 ModuleDefId::ConstId(const_id) => self.validate_const(const_id),
143 ModuleDefId::StaticId(static_id) => self.validate_static(static_id),
148 fn validate_adt(&mut self, adt: AdtId) {
150 AdtId::StructId(struct_id) => self.validate_struct(struct_id),
151 AdtId::EnumId(enum_id) => self.validate_enum(enum_id),
152 AdtId::UnionId(_) => {
153 // FIXME: Unions aren't yet supported by this validator.
158 /// Checks whether not following the convention is allowed for this item.
159 fn allowed(&self, id: AttrDefId, allow_name: &str, recursing: bool) -> bool {
160 let is_allowed = |def_id| {
161 let attrs = self.db.attrs(def_id);
162 // don't bug the user about directly no_mangle annotated stuff, they can't do anything about it
163 (!recursing && attrs.by_key("no_mangle").exists())
164 || attrs.by_key("allow").tt_values().any(|tt| {
165 let allows = tt.to_string();
166 allows.contains(allow_name)
167 || allows.contains(allow::BAD_STYLE)
168 || allows.contains(allow::NONSTANDARD_STYLE)
173 // go upwards one step or give up
175 AttrDefId::ModuleId(m) => m.containing_module(self.db.upcast()).map(|v| v.into()),
176 AttrDefId::FunctionId(f) => Some(f.lookup(self.db.upcast()).container.into()),
177 AttrDefId::StaticId(sid) => Some(sid.lookup(self.db.upcast()).container.into()),
178 AttrDefId::ConstId(cid) => Some(cid.lookup(self.db.upcast()).container.into()),
179 AttrDefId::TraitId(tid) => Some(tid.lookup(self.db.upcast()).container.into()),
180 AttrDefId::ImplId(iid) => Some(iid.lookup(self.db.upcast()).container.into()),
181 // These warnings should not explore macro definitions at all
182 AttrDefId::MacroDefId(_) => None,
183 // Will never occur under an enum/struct/union/type alias
184 AttrDefId::AdtId(_) => None,
185 AttrDefId::FieldId(_) => None,
186 AttrDefId::EnumVariantId(_) => None,
187 AttrDefId::TypeAliasId(_) => None,
188 AttrDefId::GenericParamId(_) => None,
190 .map(|mid| self.allowed(mid, allow_name, true))
194 fn validate_func(&mut self, func: FunctionId) {
195 let data = self.db.function_data(func);
196 if data.is_in_extern_block() {
197 cov_mark::hit!(extern_func_incorrect_case_ignored);
201 let body = self.db.body(func.into());
203 // Recursively validate inner scope items, such as static variables and constants.
204 for (_, block_def_map) in body.blocks(self.db.upcast()) {
205 for (_, module) in block_def_map.modules() {
206 for def_id in module.scope.declarations() {
207 let mut validator = DeclValidator::new(self.db, self.krate);
208 validator.validate_item(def_id);
213 // Check whether non-snake case identifiers are allowed for this function.
214 if self.allowed(func.into(), allow::NON_SNAKE_CASE, false) {
218 // Check the function name.
219 let function_name = data.name.to_string();
220 let fn_name_replacement = to_lower_snake_case(&function_name).map(|new_name| Replacement {
221 current_name: data.name.clone(),
222 suggested_text: new_name,
223 expected_case: CaseType::LowerSnakeCase,
226 // Check the patterns inside the function body.
227 // This includes function parameters.
228 let pats_replacements = body
231 .filter_map(|(id, pat)| match pat {
232 Pat::Bind { name, .. } => Some((id, name)),
235 .filter_map(|(id, bind_name)| {
239 current_name: bind_name.clone(),
240 suggested_text: to_lower_snake_case(&bind_name.to_string())?,
241 expected_case: CaseType::LowerSnakeCase,
247 // If there is at least one element to spawn a warning on, go to the source map and generate a warning.
248 if let Some(fn_name_replacement) = fn_name_replacement {
249 self.create_incorrect_case_diagnostic_for_func(func, fn_name_replacement);
252 self.create_incorrect_case_diagnostic_for_variables(func, pats_replacements);
255 /// Given the information about incorrect names in the function declaration, looks up into the source code
256 /// for exact locations and adds diagnostics into the sink.
257 fn create_incorrect_case_diagnostic_for_func(
260 fn_name_replacement: Replacement,
262 let fn_loc = func.lookup(self.db.upcast());
263 let fn_src = fn_loc.source(self.db.upcast());
265 // Diagnostic for function name.
266 let ast_ptr = match fn_src.value.name() {
270 "Replacement ({:?}) was generated for a function without a name: {:?}",
278 let diagnostic = IncorrectCase {
279 file: fn_src.file_id,
280 ident_type: IdentType::Function,
281 ident: AstPtr::new(&ast_ptr),
282 expected_case: fn_name_replacement.expected_case,
283 ident_text: fn_name_replacement.current_name.to_string(),
284 suggested_text: fn_name_replacement.suggested_text,
287 self.sink.push(diagnostic);
290 /// Given the information about incorrect variable names, looks up into the source code
291 /// for exact locations and adds diagnostics into the sink.
292 fn create_incorrect_case_diagnostic_for_variables(
295 pats_replacements: Vec<(PatId, Replacement)>,
297 // XXX: only look at source_map if we do have missing fields
298 if pats_replacements.is_empty() {
302 let (_, source_map) = self.db.body_with_source_map(func.into());
304 for (id, replacement) in pats_replacements {
305 if let Ok(source_ptr) = source_map.pat_syntax(id) {
306 if let Some(expr) = source_ptr.value.as_ref().left() {
307 let root = source_ptr.file_syntax(self.db.upcast());
308 if let ast::Pat::IdentPat(ident_pat) = expr.to_node(&root) {
309 let parent = match ident_pat.syntax().parent() {
310 Some(parent) => parent,
313 let name_ast = match ident_pat.name() {
314 Some(name_ast) => name_ast,
318 let is_param = ast::Param::can_cast(parent.kind());
320 // We have to check that it's either `let var = ...` or `var @ Variant(_)` statement,
321 // because e.g. match arms are patterns as well.
322 // In other words, we check that it's a named variable binding.
323 let is_binding = ast::LetStmt::can_cast(parent.kind())
324 || (ast::MatchArm::can_cast(parent.kind())
325 && ident_pat.at_token().is_some());
326 if !(is_param || is_binding) {
327 // This pattern is not an actual variable declaration, e.g. `Some(val) => {..}` match arm.
332 if is_param { IdentType::Parameter } else { IdentType::Variable };
334 let diagnostic = IncorrectCase {
335 file: source_ptr.file_id,
337 ident: AstPtr::new(&name_ast),
338 expected_case: replacement.expected_case,
339 ident_text: replacement.current_name.to_string(),
340 suggested_text: replacement.suggested_text,
343 self.sink.push(diagnostic);
350 fn validate_struct(&mut self, struct_id: StructId) {
351 let data = self.db.struct_data(struct_id);
353 let non_camel_case_allowed =
354 self.allowed(struct_id.into(), allow::NON_CAMEL_CASE_TYPES, false);
355 let non_snake_case_allowed = self.allowed(struct_id.into(), allow::NON_SNAKE_CASE, false);
357 // Check the structure name.
358 let struct_name = data.name.to_string();
359 let struct_name_replacement = if !non_camel_case_allowed {
360 to_camel_case(&struct_name).map(|new_name| Replacement {
361 current_name: data.name.clone(),
362 suggested_text: new_name,
363 expected_case: CaseType::UpperCamelCase,
369 // Check the field names.
370 let mut struct_fields_replacements = Vec::new();
372 if !non_snake_case_allowed {
373 if let VariantData::Record(fields) = data.variant_data.as_ref() {
374 for (_, field) in fields.iter() {
375 let field_name = field.name.to_string();
376 if let Some(new_name) = to_lower_snake_case(&field_name) {
377 let replacement = Replacement {
378 current_name: field.name.clone(),
379 suggested_text: new_name,
380 expected_case: CaseType::LowerSnakeCase,
382 struct_fields_replacements.push(replacement);
388 // If there is at least one element to spawn a warning on, go to the source map and generate a warning.
389 self.create_incorrect_case_diagnostic_for_struct(
391 struct_name_replacement,
392 struct_fields_replacements,
396 /// Given the information about incorrect names in the struct declaration, looks up into the source code
397 /// for exact locations and adds diagnostics into the sink.
398 fn create_incorrect_case_diagnostic_for_struct(
401 struct_name_replacement: Option<Replacement>,
402 struct_fields_replacements: Vec<Replacement>,
404 // XXX: Only look at sources if we do have incorrect names.
405 if struct_name_replacement.is_none() && struct_fields_replacements.is_empty() {
409 let struct_loc = struct_id.lookup(self.db.upcast());
410 let struct_src = struct_loc.source(self.db.upcast());
412 if let Some(replacement) = struct_name_replacement {
413 let ast_ptr = match struct_src.value.name() {
417 "Replacement ({:?}) was generated for a structure without a name: {:?}",
425 let diagnostic = IncorrectCase {
426 file: struct_src.file_id,
427 ident_type: IdentType::Structure,
428 ident: AstPtr::new(&ast_ptr),
429 expected_case: replacement.expected_case,
430 ident_text: replacement.current_name.to_string(),
431 suggested_text: replacement.suggested_text,
434 self.sink.push(diagnostic);
437 let struct_fields_list = match struct_src.value.field_list() {
438 Some(ast::FieldList::RecordFieldList(fields)) => fields,
441 struct_fields_replacements.is_empty(),
442 "Replacements ({:?}) were generated for a structure fields which had no fields list: {:?}",
443 struct_fields_replacements,
449 let mut struct_fields_iter = struct_fields_list.fields();
450 for field_to_rename in struct_fields_replacements {
451 // We assume that parameters in replacement are in the same order as in the
452 // actual params list, but just some of them (ones that named correctly) are skipped.
454 match struct_fields_iter.next().and_then(|field| field.name()) {
455 Some(field_name) => {
456 if field_name.as_name() == field_to_rename.current_name {
462 "Replacement ({:?}) was generated for a structure field which was not found: {:?}",
463 field_to_rename, struct_src
470 let diagnostic = IncorrectCase {
471 file: struct_src.file_id,
472 ident_type: IdentType::Field,
473 ident: AstPtr::new(&ast_ptr),
474 expected_case: field_to_rename.expected_case,
475 ident_text: field_to_rename.current_name.to_string(),
476 suggested_text: field_to_rename.suggested_text,
479 self.sink.push(diagnostic);
483 fn validate_enum(&mut self, enum_id: EnumId) {
484 let data = self.db.enum_data(enum_id);
486 // Check whether non-camel case names are allowed for this enum.
487 if self.allowed(enum_id.into(), allow::NON_CAMEL_CASE_TYPES, false) {
491 // Check the enum name.
492 let enum_name = data.name.to_string();
493 let enum_name_replacement = to_camel_case(&enum_name).map(|new_name| Replacement {
494 current_name: data.name.clone(),
495 suggested_text: new_name,
496 expected_case: CaseType::UpperCamelCase,
499 // Check the field names.
500 let enum_fields_replacements = data
503 .filter_map(|(_, variant)| {
505 current_name: variant.name.clone(),
506 suggested_text: to_camel_case(&variant.name.to_string())?,
507 expected_case: CaseType::UpperCamelCase,
512 // If there is at least one element to spawn a warning on, go to the source map and generate a warning.
513 self.create_incorrect_case_diagnostic_for_enum(
515 enum_name_replacement,
516 enum_fields_replacements,
520 /// Given the information about incorrect names in the struct declaration, looks up into the source code
521 /// for exact locations and adds diagnostics into the sink.
522 fn create_incorrect_case_diagnostic_for_enum(
525 enum_name_replacement: Option<Replacement>,
526 enum_variants_replacements: Vec<Replacement>,
528 // XXX: only look at sources if we do have incorrect names
529 if enum_name_replacement.is_none() && enum_variants_replacements.is_empty() {
533 let enum_loc = enum_id.lookup(self.db.upcast());
534 let enum_src = enum_loc.source(self.db.upcast());
536 if let Some(replacement) = enum_name_replacement {
537 let ast_ptr = match enum_src.value.name() {
541 "Replacement ({:?}) was generated for a enum without a name: {:?}",
549 let diagnostic = IncorrectCase {
550 file: enum_src.file_id,
551 ident_type: IdentType::Enum,
552 ident: AstPtr::new(&ast_ptr),
553 expected_case: replacement.expected_case,
554 ident_text: replacement.current_name.to_string(),
555 suggested_text: replacement.suggested_text,
558 self.sink.push(diagnostic);
561 let enum_variants_list = match enum_src.value.variant_list() {
562 Some(variants) => variants,
565 enum_variants_replacements.is_empty(),
566 "Replacements ({:?}) were generated for a enum variants which had no fields list: {:?}",
567 enum_variants_replacements,
573 let mut enum_variants_iter = enum_variants_list.variants();
574 for variant_to_rename in enum_variants_replacements {
575 // We assume that parameters in replacement are in the same order as in the
576 // actual params list, but just some of them (ones that named correctly) are skipped.
578 match enum_variants_iter.next().and_then(|v| v.name()) {
579 Some(variant_name) => {
580 if variant_name.as_name() == variant_to_rename.current_name {
586 "Replacement ({:?}) was generated for a enum variant which was not found: {:?}",
587 variant_to_rename, enum_src
594 let diagnostic = IncorrectCase {
595 file: enum_src.file_id,
596 ident_type: IdentType::Variant,
597 ident: AstPtr::new(&ast_ptr),
598 expected_case: variant_to_rename.expected_case,
599 ident_text: variant_to_rename.current_name.to_string(),
600 suggested_text: variant_to_rename.suggested_text,
603 self.sink.push(diagnostic);
607 fn validate_const(&mut self, const_id: ConstId) {
608 let data = self.db.const_data(const_id);
610 if self.allowed(const_id.into(), allow::NON_UPPER_CASE_GLOBAL, false) {
614 let name = match &data.name {
619 let const_name = name.to_string();
620 let replacement = if let Some(new_name) = to_upper_snake_case(&const_name) {
622 current_name: name.clone(),
623 suggested_text: new_name,
624 expected_case: CaseType::UpperSnakeCase,
627 // Nothing to do here.
631 let const_loc = const_id.lookup(self.db.upcast());
632 let const_src = const_loc.source(self.db.upcast());
634 let ast_ptr = match const_src.value.name() {
639 let diagnostic = IncorrectCase {
640 file: const_src.file_id,
641 ident_type: IdentType::Constant,
642 ident: AstPtr::new(&ast_ptr),
643 expected_case: replacement.expected_case,
644 ident_text: replacement.current_name.to_string(),
645 suggested_text: replacement.suggested_text,
648 self.sink.push(diagnostic);
651 fn validate_static(&mut self, static_id: StaticId) {
652 let data = self.db.static_data(static_id);
654 cov_mark::hit!(extern_static_incorrect_case_ignored);
658 if self.allowed(static_id.into(), allow::NON_UPPER_CASE_GLOBAL, false) {
662 let name = &data.name;
664 let static_name = name.to_string();
665 let replacement = if let Some(new_name) = to_upper_snake_case(&static_name) {
667 current_name: name.clone(),
668 suggested_text: new_name,
669 expected_case: CaseType::UpperSnakeCase,
672 // Nothing to do here.
676 let static_loc = static_id.lookup(self.db.upcast());
677 let static_src = static_loc.source(self.db.upcast());
679 let ast_ptr = match static_src.value.name() {
684 let diagnostic = IncorrectCase {
685 file: static_src.file_id,
686 ident_type: IdentType::StaticVariable,
687 ident: AstPtr::new(&ast_ptr),
688 expected_case: replacement.expected_case,
689 ident_text: replacement.current_name.to_string(),
690 suggested_text: replacement.suggested_text,
693 self.sink.push(diagnostic);