aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_ty/src/diagnostics/decl_check.rs
blob: 083df37726b50c344e0525b274739ad4bc0228ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//! Provides validators for the item declarations.
//! This includes the following items:
//! - variable bindings (e.g. `let x = foo();`)
//! - struct fields (e.g. `struct Foo { field: u8 }`)
//! - enum fields (e.g. `enum Foo { Variant { field: u8 } }`)
//! - function/method arguments (e.g. `fn foo(arg: u8)`)

// TODO: Temporary, to not see warnings until module is somewhat complete.
// If you see these lines in the pull request, feel free to call me stupid :P.
#![allow(dead_code, unused_imports, unused_variables)]

use std::sync::Arc;

use hir_def::{
    body::Body,
    db::DefDatabase,
    expr::{Expr, ExprId, UnaryOp},
    item_tree::ItemTreeNode,
    resolver::{resolver_for_expr, ResolveValueResult, ValueNs},
    src::HasSource,
    AdtId, FunctionId, Lookup, ModuleDefId,
};
use hir_expand::{diagnostics::DiagnosticSink, name::Name};
use syntax::{
    ast::{self, NameOwner},
    AstPtr,
};

use crate::{
    db::HirDatabase,
    diagnostics::{CaseType, IncorrectCase},
    lower::CallableDefId,
    ApplicationTy, InferenceResult, Ty, TypeCtor,
};

pub(super) struct DeclValidator<'a, 'b: 'a> {
    owner: ModuleDefId,
    sink: &'a mut DiagnosticSink<'b>,
}

#[derive(Debug)]
struct Replacement {
    current_name: Name,
    suggested_text: String,
    expected_case: CaseType,
}

impl<'a, 'b> DeclValidator<'a, 'b> {
    pub(super) fn new(
        owner: ModuleDefId,
        sink: &'a mut DiagnosticSink<'b>,
    ) -> DeclValidator<'a, 'b> {
        DeclValidator { owner, sink }
    }

    pub(super) fn validate_item(&mut self, db: &dyn HirDatabase) {
        // let def = self.owner.into();
        match self.owner {
            ModuleDefId::FunctionId(func) => self.validate_func(db, func),
            ModuleDefId::AdtId(adt) => self.validate_adt(db, adt),
            _ => return,
        }
    }

    fn validate_func(&mut self, db: &dyn HirDatabase, func: FunctionId) {
        let data = db.function_data(func);

        // 1. Check the function name.
        let function_name = data.name.to_string();
        let fn_name_replacement = if let Some(new_name) = to_lower_snake_case(&function_name) {
            let replacement = Replacement {
                current_name: data.name.clone(),
                suggested_text: new_name,
                expected_case: CaseType::LowerSnakeCase,
            };
            Some(replacement)
        } else {
            None
        };

        // 2. Check the param names.
        let mut fn_param_replacements = Vec::new();

        for param_name in data.param_names.iter().cloned().filter_map(|i| i) {
            let name = param_name.to_string();
            if let Some(new_name) = to_lower_snake_case(&name) {
                let replacement = Replacement {
                    current_name: param_name,
                    suggested_text: new_name,
                    expected_case: CaseType::LowerSnakeCase,
                };
                fn_param_replacements.push(replacement);
            }
        }

        // 3. If there is at least one element to spawn a warning on, go to the source map and generate a warning.
        self.create_incorrect_case_diagnostic_for_func(
            func,
            db,
            fn_name_replacement,
            fn_param_replacements,
        )
    }

    /// Given the information about incorrect names in the function declaration, looks up into the source code
    /// for exact locations and adds diagnostics into the sink.
    fn create_incorrect_case_diagnostic_for_func(
        &mut self,
        func: FunctionId,
        db: &dyn HirDatabase,
        fn_name_replacement: Option<Replacement>,
        fn_param_replacements: Vec<Replacement>,
    ) {
        // XXX: only look at sources if we do have incorrect names
        if fn_name_replacement.is_none() && fn_param_replacements.is_empty() {
            return;
        }

        let fn_loc = func.lookup(db.upcast());
        let fn_src = fn_loc.source(db.upcast());

        if let Some(replacement) = fn_name_replacement {
            let ast_ptr = if let Some(name) = fn_src.value.name() {
                name
            } else {
                // We don't want rust-analyzer to panic over this, but it is definitely some kind of error in the logic.
                log::error!(
                    "Replacement ({:?}) was generated for a function without a name: {:?}",
                    replacement,
                    fn_src
                );
                return;
            };

            let diagnostic = IncorrectCase {
                file: fn_src.file_id,
                ident_type: "Function".to_string(),
                ident: AstPtr::new(&ast_ptr).into(),
                expected_case: replacement.expected_case,
                ident_text: replacement.current_name.to_string(),
                suggested_text: replacement.suggested_text,
            };

            self.sink.push(diagnostic);
        }

        let fn_params_list = match fn_src.value.param_list() {
            Some(params) => params,
            None => {
                if !fn_param_replacements.is_empty() {
                    log::error!(
                        "Replacements ({:?}) were generated for a function parameters which had no parameters list: {:?}",
                        fn_param_replacements, fn_src
                    );
                }
                return;
            }
        };
        let mut fn_params_iter = fn_params_list.params();
        for param_to_rename in fn_param_replacements {
            // We assume that parameters in replacement are in the same order as in the
            // actual params list, but just some of them (ones that named correctly) are skipped.
            let ast_ptr = loop {
                match fn_params_iter.next() {
                    Some(element)
                        if pat_equals_to_name(element.pat(), &param_to_rename.current_name) =>
                    {
                        break element.pat().unwrap()
                    }
                    Some(_) => {}
                    None => {
                        log::error!(
                            "Replacement ({:?}) was generated for a function parameter which was not found: {:?}",
                            param_to_rename, fn_src
                        );
                        return;
                    }
                }
            };

            let diagnostic = IncorrectCase {
                file: fn_src.file_id,
                ident_type: "Argument".to_string(),
                ident: AstPtr::new(&ast_ptr).into(),
                expected_case: param_to_rename.expected_case,
                ident_text: param_to_rename.current_name.to_string(),
                suggested_text: param_to_rename.suggested_text,
            };

            self.sink.push(diagnostic);
        }
    }

    fn validate_adt(&mut self, db: &dyn HirDatabase, adt: AdtId) {}
}

fn pat_equals_to_name(pat: Option<ast::Pat>, name: &Name) -> bool {
    if let Some(ast::Pat::IdentPat(ident)) = pat {
        ident.to_string() == name.to_string()
    } else {
        false
    }
}

fn to_lower_snake_case(ident: &str) -> Option<String> {
    // First, assume that it's UPPER_SNAKE_CASE.
    if let Some(normalized) = to_lower_snake_case_from_upper_snake_case(ident) {
        return Some(normalized);
    }

    // Otherwise, assume that it's CamelCase.
    let lower_snake_case = stdx::to_lower_snake_case(ident);

    if lower_snake_case == ident {
        None
    } else {
        Some(lower_snake_case)
    }
}

fn to_lower_snake_case_from_upper_snake_case(ident: &str) -> Option<String> {
    let is_upper_snake_case = ident.chars().all(|c| c.is_ascii_uppercase() || c == '_');

    if is_upper_snake_case {
        let string = ident.chars().map(|c| c.to_ascii_lowercase()).collect();
        Some(string)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use crate::diagnostics::tests::check_diagnostics;

    #[test]
    fn incorrect_function_name() {
        check_diagnostics(
            r#"
fn NonSnakeCaseName() {}
// ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have a snake_case name, e.g. `non_snake_case_name`
"#,
        );
    }

    #[test]
    fn incorrect_function_params() {
        check_diagnostics(
            r#"
fn foo(SomeParam: u8) {}
    // ^^^^^^^^^ Argument `SomeParam` should have a snake_case name, e.g. `some_param`

fn foo2(ok_param: &str, CAPS_PARAM: u8) {}
                     // ^^^^^^^^^^ Argument `CAPS_PARAM` should have a snake_case name, e.g. `caps_param`
"#,
        );
    }
}