]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Switch test marker
[rust.git] / crates / ide / src / diagnostics.rs
1 //! Collects diagnostics & fixits  for a single file.
2 //!
3 //! The tricky bit here is that diagnostics are produced by hir in terms of
4 //! macro-expanded files, but we need to present them to the users in terms of
5 //! original files. So we need to map the ranges.
6
7 mod fixes;
8 mod field_shorthand;
9
10 use std::cell::RefCell;
11
12 use hir::{
13     diagnostics::{Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
14     Semantics,
15 };
16 use ide_db::base_db::SourceDatabase;
17 use ide_db::RootDatabase;
18 use itertools::Itertools;
19 use rustc_hash::FxHashSet;
20 use syntax::{
21     ast::{self, AstNode},
22     SyntaxNode, TextRange, T,
23 };
24 use text_edit::TextEdit;
25
26 use crate::{FileId, Label, SourceChange, SourceFileEdit};
27
28 use self::fixes::DiagnosticWithFix;
29
30 #[derive(Debug)]
31 pub struct Diagnostic {
32     // pub name: Option<String>,
33     pub message: String,
34     pub range: TextRange,
35     pub severity: Severity,
36     pub fix: Option<Fix>,
37     pub unused: bool,
38     pub code: Option<DiagnosticCode>,
39 }
40
41 impl Diagnostic {
42     fn error(range: TextRange, message: String) -> Self {
43         Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
44     }
45
46     fn hint(range: TextRange, message: String) -> Self {
47         Self {
48             message,
49             range,
50             severity: Severity::WeakWarning,
51             fix: None,
52             unused: false,
53             code: None,
54         }
55     }
56
57     fn with_fix(self, fix: Option<Fix>) -> Self {
58         Self { fix, ..self }
59     }
60
61     fn with_unused(self, unused: bool) -> Self {
62         Self { unused, ..self }
63     }
64
65     fn with_code(self, code: Option<DiagnosticCode>) -> Self {
66         Self { code, ..self }
67     }
68 }
69
70 #[derive(Debug)]
71 pub struct Fix {
72     pub label: Label,
73     pub source_change: SourceChange,
74     /// Allows to trigger the fix only when the caret is in the range given
75     pub fix_trigger_range: TextRange,
76 }
77
78 impl Fix {
79     fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
80         let label = Label::new(label);
81         Self { label, source_change, fix_trigger_range }
82     }
83 }
84
85 #[derive(Debug, Copy, Clone)]
86 pub enum Severity {
87     Error,
88     WeakWarning,
89 }
90
91 #[derive(Default, Debug, Clone)]
92 pub struct DiagnosticsConfig {
93     pub disable_experimental: bool,
94     pub disabled: FxHashSet<String>,
95 }
96
97 pub(crate) fn diagnostics(
98     db: &RootDatabase,
99     config: &DiagnosticsConfig,
100     file_id: FileId,
101 ) -> Vec<Diagnostic> {
102     let _p = profile::span("diagnostics");
103     let sema = Semantics::new(db);
104     let parse = db.parse(file_id);
105     let mut res = Vec::new();
106
107     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
108     res.extend(
109         parse
110             .errors()
111             .iter()
112             .take(128)
113             .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
114     );
115
116     for node in parse.tree().syntax().descendants() {
117         check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
118         field_shorthand::check(&mut res, file_id, &node);
119     }
120     let res = RefCell::new(res);
121     let sink_builder = DiagnosticSinkBuilder::new()
122         .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
123             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
124         })
125         .on::<hir::diagnostics::MissingFields, _>(|d| {
126             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
127         })
128         .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
129             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
130         })
131         .on::<hir::diagnostics::NoSuchField, _>(|d| {
132             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
133         })
134         .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
135             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
136         })
137         .on::<hir::diagnostics::IncorrectCase, _>(|d| {
138             res.borrow_mut().push(warning_with_fix(d, &sema));
139         })
140         .on::<hir::diagnostics::InactiveCode, _>(|d| {
141             // If there's inactive code somewhere in a macro, don't propagate to the call-site.
142             if d.display_source().file_id.expansion_info(db).is_some() {
143                 return;
144             }
145
146             // Override severity and mark as unused.
147             res.borrow_mut().push(
148                 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
149                     .with_unused(true)
150                     .with_code(Some(d.code())),
151             );
152         })
153         .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
154             // Use more accurate position if available.
155             let display_range =
156                 d.precise_location.unwrap_or_else(|| sema.diagnostics_display_range(d).range);
157
158             // FIXME: it would be nice to tell the user whether proc macros are currently disabled
159             res.borrow_mut()
160                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
161         })
162         // Only collect experimental diagnostics when they're enabled.
163         .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
164         .filter(|diag| !config.disabled.contains(diag.code().as_str()));
165
166     // Finalize the `DiagnosticSink` building process.
167     let mut sink = sink_builder
168         // Diagnostics not handled above get no fix and default treatment.
169         .build(|d| {
170             res.borrow_mut().push(
171                 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
172                     .with_code(Some(d.code())),
173             );
174         });
175
176     if let Some(m) = sema.to_module_def(file_id) {
177         m.diagnostics(db, &mut sink);
178     };
179     drop(sink);
180     res.into_inner()
181 }
182
183 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
184     Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
185         .with_fix(d.fix(&sema))
186         .with_code(Some(d.code()))
187 }
188
189 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
190     Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
191         .with_fix(d.fix(&sema))
192         .with_code(Some(d.code()))
193 }
194
195 fn check_unnecessary_braces_in_use_statement(
196     acc: &mut Vec<Diagnostic>,
197     file_id: FileId,
198     node: &SyntaxNode,
199 ) -> Option<()> {
200     let use_tree_list = ast::UseTreeList::cast(node.clone())?;
201     if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
202         // If there is a comment inside the bracketed `use`,
203         // assume it is a commented out module path and don't show diagnostic.
204         if use_tree_list.has_inner_comment() {
205             return Some(());
206         }
207
208         let use_range = use_tree_list.syntax().text_range();
209         let edit =
210             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
211                 .unwrap_or_else(|| {
212                     let to_replace = single_use_tree.syntax().text().to_string();
213                     let mut edit_builder = TextEdit::builder();
214                     edit_builder.delete(use_range);
215                     edit_builder.insert(use_range.start(), to_replace);
216                     edit_builder.finish()
217                 });
218
219         acc.push(
220             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
221                 .with_fix(Some(Fix::new(
222                     "Remove unnecessary braces",
223                     SourceFileEdit { file_id, edit }.into(),
224                     use_range,
225                 ))),
226         );
227     }
228
229     Some(())
230 }
231
232 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
233     single_use_tree: &ast::UseTree,
234 ) -> Option<TextEdit> {
235     let use_tree_list_node = single_use_tree.syntax().parent()?;
236     if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
237         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
238         let end = use_tree_list_node.text_range().end();
239         return Some(TextEdit::delete(TextRange::new(start, end)));
240     }
241     None
242 }
243
244 #[cfg(test)]
245 mod tests {
246     use expect_test::{expect, Expect};
247     use stdx::trim_indent;
248     use test_utils::assert_eq_text;
249
250     use crate::{fixture, DiagnosticsConfig};
251
252     /// Takes a multi-file input fixture with annotated cursor positions,
253     /// and checks that:
254     ///  * a diagnostic is produced
255     ///  * this diagnostic fix trigger range touches the input cursor position
256     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
257     pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
258         let after = trim_indent(ra_fixture_after);
259
260         let (analysis, file_position) = fixture::position(ra_fixture_before);
261         let diagnostic = analysis
262             .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
263             .unwrap()
264             .pop()
265             .unwrap();
266         let fix = diagnostic.fix.unwrap();
267         let actual = {
268             let file_id = fix.source_change.source_file_edits.first().unwrap().file_id;
269             let mut actual = analysis.file_text(file_id).unwrap().to_string();
270
271             // Go from the last one to the first one, so that ranges won't be affected by previous edits.
272             // FIXME: https://github.com/rust-analyzer/rust-analyzer/issues/4901#issuecomment-644675309
273             for edit in fix.source_change.source_file_edits.iter().rev() {
274                 edit.edit.apply(&mut actual);
275             }
276             actual
277         };
278
279         assert_eq_text!(&after, &actual);
280         assert!(
281             fix.fix_trigger_range.contains_inclusive(file_position.offset),
282             "diagnostic fix range {:?} does not touch cursor position {:?}",
283             fix.fix_trigger_range,
284             file_position.offset
285         );
286     }
287
288     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
289     /// apply to the file containing the cursor.
290     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
291         let (analysis, files) = fixture::files(ra_fixture);
292         let diagnostics = files
293             .into_iter()
294             .flat_map(|file_id| {
295                 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
296             })
297             .collect::<Vec<_>>();
298         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
299     }
300
301     fn check_expect(ra_fixture: &str, expect: Expect) {
302         let (analysis, file_id) = fixture::file(ra_fixture);
303         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
304         expect.assert_debug_eq(&diagnostics)
305     }
306
307     #[test]
308     fn test_wrap_return_type_option() {
309         check_fix(
310             r#"
311 //- /main.rs crate:main deps:core
312 use core::option::Option::{self, Some, None};
313
314 fn div(x: i32, y: i32) -> Option<i32> {
315     if y == 0 {
316         return None;
317     }
318     x / y$0
319 }
320 //- /core/lib.rs crate:core
321 pub mod result {
322     pub enum Result<T, E> { Ok(T), Err(E) }
323 }
324 pub mod option {
325     pub enum Option<T> { Some(T), None }
326 }
327 "#,
328             r#"
329 use core::option::Option::{self, Some, None};
330
331 fn div(x: i32, y: i32) -> Option<i32> {
332     if y == 0 {
333         return None;
334     }
335     Some(x / y)
336 }
337 "#,
338         );
339     }
340
341     #[test]
342     fn test_wrap_return_type() {
343         check_fix(
344             r#"
345 //- /main.rs crate:main deps:core
346 use core::result::Result::{self, Ok, Err};
347
348 fn div(x: i32, y: i32) -> Result<i32, ()> {
349     if y == 0 {
350         return Err(());
351     }
352     x / y$0
353 }
354 //- /core/lib.rs crate:core
355 pub mod result {
356     pub enum Result<T, E> { Ok(T), Err(E) }
357 }
358 pub mod option {
359     pub enum Option<T> { Some(T), None }
360 }
361 "#,
362             r#"
363 use core::result::Result::{self, Ok, Err};
364
365 fn div(x: i32, y: i32) -> Result<i32, ()> {
366     if y == 0 {
367         return Err(());
368     }
369     Ok(x / y)
370 }
371 "#,
372         );
373     }
374
375     #[test]
376     fn test_wrap_return_type_handles_generic_functions() {
377         check_fix(
378             r#"
379 //- /main.rs crate:main deps:core
380 use core::result::Result::{self, Ok, Err};
381
382 fn div<T>(x: T) -> Result<T, i32> {
383     if x == 0 {
384         return Err(7);
385     }
386     $0x
387 }
388 //- /core/lib.rs crate:core
389 pub mod result {
390     pub enum Result<T, E> { Ok(T), Err(E) }
391 }
392 pub mod option {
393     pub enum Option<T> { Some(T), None }
394 }
395 "#,
396             r#"
397 use core::result::Result::{self, Ok, Err};
398
399 fn div<T>(x: T) -> Result<T, i32> {
400     if x == 0 {
401         return Err(7);
402     }
403     Ok(x)
404 }
405 "#,
406         );
407     }
408
409     #[test]
410     fn test_wrap_return_type_handles_type_aliases() {
411         check_fix(
412             r#"
413 //- /main.rs crate:main deps:core
414 use core::result::Result::{self, Ok, Err};
415
416 type MyResult<T> = Result<T, ()>;
417
418 fn div(x: i32, y: i32) -> MyResult<i32> {
419     if y == 0 {
420         return Err(());
421     }
422     x $0/ y
423 }
424 //- /core/lib.rs crate:core
425 pub mod result {
426     pub enum Result<T, E> { Ok(T), Err(E) }
427 }
428 pub mod option {
429     pub enum Option<T> { Some(T), None }
430 }
431 "#,
432             r#"
433 use core::result::Result::{self, Ok, Err};
434
435 type MyResult<T> = Result<T, ()>;
436
437 fn div(x: i32, y: i32) -> MyResult<i32> {
438     if y == 0 {
439         return Err(());
440     }
441     Ok(x / y)
442 }
443 "#,
444         );
445     }
446
447     #[test]
448     fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
449         check_no_diagnostics(
450             r#"
451 //- /main.rs crate:main deps:core
452 use core::result::Result::{self, Ok, Err};
453
454 fn foo() -> Result<(), i32> { 0 }
455
456 //- /core/lib.rs crate:core
457 pub mod result {
458     pub enum Result<T, E> { Ok(T), Err(E) }
459 }
460 pub mod option {
461     pub enum Option<T> { Some(T), None }
462 }
463 "#,
464         );
465     }
466
467     #[test]
468     fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
469         check_no_diagnostics(
470             r#"
471 //- /main.rs crate:main deps:core
472 use core::result::Result::{self, Ok, Err};
473
474 enum SomeOtherEnum { Ok(i32), Err(String) }
475
476 fn foo() -> SomeOtherEnum { 0 }
477
478 //- /core/lib.rs crate:core
479 pub mod result {
480     pub enum Result<T, E> { Ok(T), Err(E) }
481 }
482 pub mod option {
483     pub enum Option<T> { Some(T), None }
484 }
485 "#,
486         );
487     }
488
489     #[test]
490     fn test_fill_struct_fields_empty() {
491         check_fix(
492             r#"
493 struct TestStruct { one: i32, two: i64 }
494
495 fn test_fn() {
496     let s = TestStruct {$0};
497 }
498 "#,
499             r#"
500 struct TestStruct { one: i32, two: i64 }
501
502 fn test_fn() {
503     let s = TestStruct { one: (), two: ()};
504 }
505 "#,
506         );
507     }
508
509     #[test]
510     fn test_fill_struct_fields_self() {
511         check_fix(
512             r#"
513 struct TestStruct { one: i32 }
514
515 impl TestStruct {
516     fn test_fn() { let s = Self {$0}; }
517 }
518 "#,
519             r#"
520 struct TestStruct { one: i32 }
521
522 impl TestStruct {
523     fn test_fn() { let s = Self { one: ()}; }
524 }
525 "#,
526         );
527     }
528
529     #[test]
530     fn test_fill_struct_fields_enum() {
531         check_fix(
532             r#"
533 enum Expr {
534     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
535 }
536
537 impl Expr {
538     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
539         Expr::Bin {$0 }
540     }
541 }
542 "#,
543             r#"
544 enum Expr {
545     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
546 }
547
548 impl Expr {
549     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
550         Expr::Bin { lhs: (), rhs: () }
551     }
552 }
553 "#,
554         );
555     }
556
557     #[test]
558     fn test_fill_struct_fields_partial() {
559         check_fix(
560             r#"
561 struct TestStruct { one: i32, two: i64 }
562
563 fn test_fn() {
564     let s = TestStruct{ two: 2$0 };
565 }
566 "#,
567             r"
568 struct TestStruct { one: i32, two: i64 }
569
570 fn test_fn() {
571     let s = TestStruct{ two: 2, one: () };
572 }
573 ",
574         );
575     }
576
577     #[test]
578     fn test_fill_struct_fields_no_diagnostic() {
579         check_no_diagnostics(
580             r"
581             struct TestStruct { one: i32, two: i64 }
582
583             fn test_fn() {
584                 let one = 1;
585                 let s = TestStruct{ one, two: 2 };
586             }
587         ",
588         );
589     }
590
591     #[test]
592     fn test_fill_struct_fields_no_diagnostic_on_spread() {
593         check_no_diagnostics(
594             r"
595             struct TestStruct { one: i32, two: i64 }
596
597             fn test_fn() {
598                 let one = 1;
599                 let s = TestStruct{ ..a };
600             }
601         ",
602         );
603     }
604
605     #[test]
606     fn test_unresolved_module_diagnostic() {
607         check_expect(
608             r#"mod foo;"#,
609             expect![[r#"
610                 [
611                     Diagnostic {
612                         message: "unresolved module",
613                         range: 0..8,
614                         severity: Error,
615                         fix: Some(
616                             Fix {
617                                 label: "Create module",
618                                 source_change: SourceChange {
619                                     source_file_edits: [],
620                                     file_system_edits: [
621                                         CreateFile {
622                                             dst: AnchoredPathBuf {
623                                                 anchor: FileId(
624                                                     0,
625                                                 ),
626                                                 path: "foo.rs",
627                                             },
628                                             initial_contents: "",
629                                         },
630                                     ],
631                                     is_snippet: false,
632                                 },
633                                 fix_trigger_range: 0..8,
634                             },
635                         ),
636                         unused: false,
637                         code: Some(
638                             DiagnosticCode(
639                                 "unresolved-module",
640                             ),
641                         ),
642                     },
643                 ]
644             "#]],
645         );
646     }
647
648     #[test]
649     fn range_mapping_out_of_macros() {
650         // FIXME: this is very wrong, but somewhat tricky to fix.
651         check_fix(
652             r#"
653 fn some() {}
654 fn items() {}
655 fn here() {}
656
657 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
658
659 fn main() {
660     let _x = id![Foo { a: $042 }];
661 }
662
663 pub struct Foo { pub a: i32, pub b: i32 }
664 "#,
665             r#"
666 fn some(, b: ()) {}
667 fn items() {}
668 fn here() {}
669
670 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
671
672 fn main() {
673     let _x = id![Foo { a: 42 }];
674 }
675
676 pub struct Foo { pub a: i32, pub b: i32 }
677 "#,
678         );
679     }
680
681     #[test]
682     fn test_check_unnecessary_braces_in_use_statement() {
683         check_no_diagnostics(
684             r#"
685 use a;
686 use a::{c, d::e};
687
688 mod a {
689     mod c {}
690     mod d {
691         mod e {}
692     }
693 }
694 "#,
695         );
696         check_no_diagnostics(
697             r#"
698 use a;
699 use a::{
700     c,
701     // d::e
702 };
703
704 mod a {
705     mod c {}
706     mod d {
707         mod e {}
708     }
709 }
710 "#,
711         );
712         check_fix(
713             r"
714             mod b {}
715             use {$0b};
716             ",
717             r"
718             mod b {}
719             use b;
720             ",
721         );
722         check_fix(
723             r"
724             mod b {}
725             use {b$0};
726             ",
727             r"
728             mod b {}
729             use b;
730             ",
731         );
732         check_fix(
733             r"
734             mod a { mod c {} }
735             use a::{c$0};
736             ",
737             r"
738             mod a { mod c {} }
739             use a::c;
740             ",
741         );
742         check_fix(
743             r"
744             mod a {}
745             use a::{self$0};
746             ",
747             r"
748             mod a {}
749             use a;
750             ",
751         );
752         check_fix(
753             r"
754             mod a { mod c {} mod d { mod e {} } }
755             use a::{c, d::{e$0}};
756             ",
757             r"
758             mod a { mod c {} mod d { mod e {} } }
759             use a::{c, d::e};
760             ",
761         );
762     }
763
764     #[test]
765     fn test_add_field_from_usage() {
766         check_fix(
767             r"
768 fn main() {
769     Foo { bar: 3, baz$0: false};
770 }
771 struct Foo {
772     bar: i32
773 }
774 ",
775             r"
776 fn main() {
777     Foo { bar: 3, baz: false};
778 }
779 struct Foo {
780     bar: i32,
781     baz: bool
782 }
783 ",
784         )
785     }
786
787     #[test]
788     fn test_add_field_in_other_file_from_usage() {
789         check_fix(
790             r#"
791 //- /main.rs
792 mod foo;
793
794 fn main() {
795     foo::Foo { bar: 3, $0baz: false};
796 }
797 //- /foo.rs
798 struct Foo {
799     bar: i32
800 }
801 "#,
802             r#"
803 struct Foo {
804     bar: i32,
805     pub(crate) baz: bool
806 }
807 "#,
808         )
809     }
810
811     #[test]
812     fn test_disabled_diagnostics() {
813         let mut config = DiagnosticsConfig::default();
814         config.disabled.insert("unresolved-module".into());
815
816         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
817
818         let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
819         assert!(diagnostics.is_empty());
820
821         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
822         assert!(!diagnostics.is_empty());
823     }
824
825     #[test]
826     fn test_rename_incorrect_case() {
827         check_fix(
828             r#"
829 pub struct test_struct$0 { one: i32 }
830
831 pub fn some_fn(val: test_struct) -> test_struct {
832     test_struct { one: val.one + 1 }
833 }
834 "#,
835             r#"
836 pub struct TestStruct { one: i32 }
837
838 pub fn some_fn(val: TestStruct) -> TestStruct {
839     TestStruct { one: val.one + 1 }
840 }
841 "#,
842         );
843
844         check_fix(
845             r#"
846 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
847     NonSnakeCase
848 }
849 "#,
850             r#"
851 pub fn some_fn(non_snake_case: u8) -> u8 {
852     non_snake_case
853 }
854 "#,
855         );
856
857         check_fix(
858             r#"
859 pub fn SomeFn$0(val: u8) -> u8 {
860     if val != 0 { SomeFn(val - 1) } else { val }
861 }
862 "#,
863             r#"
864 pub fn some_fn(val: u8) -> u8 {
865     if val != 0 { some_fn(val - 1) } else { val }
866 }
867 "#,
868         );
869
870         check_fix(
871             r#"
872 fn some_fn() {
873     let whatAWeird_Formatting$0 = 10;
874     another_func(whatAWeird_Formatting);
875 }
876 "#,
877             r#"
878 fn some_fn() {
879     let what_a_weird_formatting = 10;
880     another_func(what_a_weird_formatting);
881 }
882 "#,
883         );
884     }
885
886     #[test]
887     fn test_uppercase_const_no_diagnostics() {
888         check_no_diagnostics(
889             r#"
890 fn foo() {
891     const ANOTHER_ITEM$0: &str = "some_item";
892 }
893 "#,
894         );
895     }
896
897     #[test]
898     fn test_rename_incorrect_case_struct_method() {
899         check_fix(
900             r#"
901 pub struct TestStruct;
902
903 impl TestStruct {
904     pub fn SomeFn$0() -> TestStruct {
905         TestStruct
906     }
907 }
908 "#,
909             r#"
910 pub struct TestStruct;
911
912 impl TestStruct {
913     pub fn some_fn() -> TestStruct {
914         TestStruct
915     }
916 }
917 "#,
918         );
919     }
920
921     #[test]
922     fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
923         let input = r#"fn FOO$0() {}"#;
924         let expected = r#"fn foo() {}"#;
925
926         let (analysis, file_position) = fixture::position(input);
927         let diagnostics =
928             analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
929         assert_eq!(diagnostics.len(), 1);
930
931         check_fix(input, expected);
932     }
933 }