aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_ty/src/diagnostics/decl_check.rs
diff options
context:
space:
mode:
authorIgor Aleksanov <[email protected]>2020-10-03 10:48:02 +0100
committerIgor Aleksanov <[email protected]>2020-10-12 08:59:54 +0100
commit4039176ec63e5c75d76398f2debe26ac6fa59cbc (patch)
tree8f2f2b6d22c57985fc6a8f1b40d84663d40b09f6 /crates/hir_ty/src/diagnostics/decl_check.rs
parent518f6d772482c7c58e59081f340947087a9b4800 (diff)
Create basic support for names case checks and implement function name case check
Diffstat (limited to 'crates/hir_ty/src/diagnostics/decl_check.rs')
-rw-r--r--crates/hir_ty/src/diagnostics/decl_check.rs173
1 files changed, 173 insertions, 0 deletions
diff --git a/crates/hir_ty/src/diagnostics/decl_check.rs b/crates/hir_ty/src/diagnostics/decl_check.rs
new file mode 100644
index 000000000..6c3cd65c5
--- /dev/null
+++ b/crates/hir_ty/src/diagnostics/decl_check.rs
@@ -0,0 +1,173 @@
1//! Provides validators for the item declarations.
2//! This includes the following items:
3//! - variable bindings (e.g. `let x = foo();`)
4//! - struct fields (e.g. `struct Foo { field: u8 }`)
5//! - enum fields (e.g. `enum Foo { Variant { field: u8 } }`)
6//! - function/method arguments (e.g. `fn foo(arg: u8)`)
7
8// TODO: Temporary, to not see warnings until module is somewhat complete.
9// If you see these lines in the pull request, feel free to call me stupid :P.
10#![allow(dead_code, unused_imports, unused_variables)]
11
12use std::sync::Arc;
13
14use hir_def::{
15 body::Body,
16 db::DefDatabase,
17 expr::{Expr, ExprId, UnaryOp},
18 item_tree::ItemTreeNode,
19 resolver::{resolver_for_expr, ResolveValueResult, ValueNs},
20 src::HasSource,
21 AdtId, FunctionId, Lookup, ModuleDefId,
22};
23use hir_expand::{diagnostics::DiagnosticSink, name::Name};
24use syntax::{ast::NameOwner, AstPtr};
25
26use crate::{
27 db::HirDatabase,
28 diagnostics::{CaseType, IncorrectCase},
29 lower::CallableDefId,
30 ApplicationTy, InferenceResult, Ty, TypeCtor,
31};
32
33pub(super) struct DeclValidator<'a, 'b: 'a> {
34 owner: ModuleDefId,
35 sink: &'a mut DiagnosticSink<'b>,
36}
37
38#[derive(Debug)]
39struct Replacement {
40 current_name: Name,
41 suggested_text: String,
42 expected_case: CaseType,
43}
44
45impl<'a, 'b> DeclValidator<'a, 'b> {
46 pub(super) fn new(
47 owner: ModuleDefId,
48 sink: &'a mut DiagnosticSink<'b>,
49 ) -> DeclValidator<'a, 'b> {
50 DeclValidator { owner, sink }
51 }
52
53 pub(super) fn validate_item(&mut self, db: &dyn HirDatabase) {
54 // let def = self.owner.into();
55 match self.owner {
56 ModuleDefId::FunctionId(func) => self.validate_func(db, func),
57 ModuleDefId::AdtId(adt) => self.validate_adt(db, adt),
58 _ => return,
59 }
60 }
61
62 fn validate_func(&mut self, db: &dyn HirDatabase, func: FunctionId) {
63 let data = db.function_data(func);
64
65 // 1. Check the function name.
66 let function_name = data.name.to_string();
67 let fn_name_replacement = if let Some(new_name) = to_lower_snake_case(&function_name) {
68 let replacement = Replacement {
69 current_name: data.name.clone(),
70 suggested_text: new_name,
71 expected_case: CaseType::LowerSnakeCase,
72 };
73 Some(replacement)
74 } else {
75 None
76 };
77
78 // 2. Check the param names.
79 let mut fn_param_replacements = Vec::new();
80
81 for param_name in data.param_names.iter().cloned().filter_map(|i| i) {
82 let name = param_name.to_string();
83 if let Some(new_name) = to_lower_snake_case(&name) {
84 let replacement = Replacement {
85 current_name: param_name,
86 suggested_text: new_name,
87 expected_case: CaseType::LowerSnakeCase,
88 };
89 fn_param_replacements.push(replacement);
90 }
91 }
92
93 // 3. If there is at least one element to spawn a warning on, go to the source map and generate a warning.
94 self.create_incorrect_case_diagnostic_for_func(
95 func,
96 db,
97 fn_name_replacement,
98 fn_param_replacements,
99 )
100 }
101
102 /// Given the information about incorrect names in the function declaration, looks up into the source code
103 /// for exact locations and adds diagnostics into the sink.
104 fn create_incorrect_case_diagnostic_for_func(
105 &mut self,
106 func: FunctionId,
107 db: &dyn HirDatabase,
108 fn_name_replacement: Option<Replacement>,
109 fn_param_replacements: Vec<Replacement>,
110 ) {
111 // XXX: only look at sources if we do have incorrect names
112 if fn_name_replacement.is_none() && fn_param_replacements.is_empty() {
113 return;
114 }
115
116 let fn_loc = func.lookup(db.upcast());
117 let fn_src = fn_loc.source(db.upcast());
118
119 if let Some(replacement) = fn_name_replacement {
120 let ast_ptr = if let Some(name) = fn_src.value.name() {
121 name
122 } else {
123 // We don't want rust-analyzer to panic over this, but it is definitely some kind of error in the logic.
124 log::error!(
125 "Replacement was generated for a function without a name: {:?}",
126 fn_src
127 );
128 return;
129 };
130
131 let diagnostic = IncorrectCase {
132 file: fn_src.file_id,
133 ident: AstPtr::new(&ast_ptr).into(),
134 expected_case: replacement.expected_case,
135 ident_text: replacement.current_name.to_string(),
136 suggested_text: replacement.suggested_text,
137 };
138
139 self.sink.push(diagnostic);
140 }
141
142 // let item_tree = db.item_tree(loc.id.file_id);
143 // let fn_def = &item_tree[fn_loc.id.value];
144 // let (_, source_map) = db.body_with_source_map(func.into());
145 }
146
147 fn validate_adt(&mut self, db: &dyn HirDatabase, adt: AdtId) {}
148}
149
150fn to_lower_snake_case(ident: &str) -> Option<String> {
151 let lower_snake_case = stdx::to_lower_snake_case(ident);
152
153 if lower_snake_case == ident {
154 None
155 } else {
156 Some(lower_snake_case)
157 }
158}
159
160#[cfg(test)]
161mod tests {
162 use crate::diagnostics::tests::check_diagnostics;
163
164 #[test]
165 fn incorrect_function_name() {
166 check_diagnostics(
167 r#"
168fn NonSnakeCaseName() {}
169// ^^^^^^^^^^^^^^^^ Argument `NonSnakeCaseName` should have a snake_case name, e.g. `non_snake_case_name`
170"#,
171 );
172 }
173}