]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Merge #7027
[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::MissingOkInTailExpr, _>(|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         let use_range = use_tree_list.syntax().text_range();
203         let edit =
204             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
205                 .unwrap_or_else(|| {
206                     let to_replace = single_use_tree.syntax().text().to_string();
207                     let mut edit_builder = TextEdit::builder();
208                     edit_builder.delete(use_range);
209                     edit_builder.insert(use_range.start(), to_replace);
210                     edit_builder.finish()
211                 });
212
213         acc.push(
214             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
215                 .with_fix(Some(Fix::new(
216                     "Remove unnecessary braces",
217                     SourceFileEdit { file_id, edit }.into(),
218                     use_range,
219                 ))),
220         );
221     }
222
223     Some(())
224 }
225
226 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
227     single_use_tree: &ast::UseTree,
228 ) -> Option<TextEdit> {
229     let use_tree_list_node = single_use_tree.syntax().parent()?;
230     if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
231         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
232         let end = use_tree_list_node.text_range().end();
233         return Some(TextEdit::delete(TextRange::new(start, end)));
234     }
235     None
236 }
237
238 #[cfg(test)]
239 mod tests {
240     use expect_test::{expect, Expect};
241     use stdx::trim_indent;
242     use test_utils::assert_eq_text;
243
244     use crate::{fixture, DiagnosticsConfig};
245
246     /// Takes a multi-file input fixture with annotated cursor positions,
247     /// and checks that:
248     ///  * a diagnostic is produced
249     ///  * this diagnostic fix trigger range touches the input cursor position
250     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
251     pub(super) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
252         let after = trim_indent(ra_fixture_after);
253
254         let (analysis, file_position) = fixture::position(ra_fixture_before);
255         let diagnostic = analysis
256             .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
257             .unwrap()
258             .pop()
259             .unwrap();
260         let mut fix = diagnostic.fix.unwrap();
261         let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
262         let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
263         let actual = {
264             let mut actual = target_file_contents.to_string();
265             edit.apply(&mut actual);
266             actual
267         };
268
269         assert_eq_text!(&after, &actual);
270         assert!(
271             fix.fix_trigger_range.contains_inclusive(file_position.offset),
272             "diagnostic fix range {:?} does not touch cursor position {:?}",
273             fix.fix_trigger_range,
274             file_position.offset
275         );
276     }
277
278     /// Similar to `check_fix`, but applies all the available fixes.
279     fn check_fixes(ra_fixture_before: &str, ra_fixture_after: &str) {
280         let after = trim_indent(ra_fixture_after);
281
282         let (analysis, file_position) = fixture::position(ra_fixture_before);
283         let diagnostic = analysis
284             .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
285             .unwrap()
286             .pop()
287             .unwrap();
288         let fix = diagnostic.fix.unwrap();
289         let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
290         let actual = {
291             let mut actual = target_file_contents.to_string();
292             // Go from the last one to the first one, so that ranges won't be affected by previous edits.
293             for edit in fix.source_change.source_file_edits.iter().rev() {
294                 edit.edit.apply(&mut actual);
295             }
296             actual
297         };
298
299         assert_eq_text!(&after, &actual);
300         assert!(
301             fix.fix_trigger_range.contains_inclusive(file_position.offset),
302             "diagnostic fix range {:?} does not touch cursor position {:?}",
303             fix.fix_trigger_range,
304             file_position.offset
305         );
306     }
307
308     /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
309     /// which has a fix that can apply to other files.
310     fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
311         let ra_fixture_after = &trim_indent(ra_fixture_after);
312         let (analysis, file_pos) = fixture::position(ra_fixture_before);
313         let current_file_id = file_pos.file_id;
314         let diagnostic = analysis
315             .diagnostics(&DiagnosticsConfig::default(), current_file_id)
316             .unwrap()
317             .pop()
318             .unwrap();
319         let mut fix = diagnostic.fix.unwrap();
320         let edit = fix.source_change.source_file_edits.pop().unwrap();
321         let changed_file_id = edit.file_id;
322         let before = analysis.file_text(changed_file_id).unwrap();
323         let actual = {
324             let mut actual = before.to_string();
325             edit.edit.apply(&mut actual);
326             actual
327         };
328         assert_eq_text!(ra_fixture_after, &actual);
329     }
330
331     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
332     /// apply to the file containing the cursor.
333     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
334         let (analysis, files) = fixture::files(ra_fixture);
335         let diagnostics = files
336             .into_iter()
337             .flat_map(|file_id| {
338                 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
339             })
340             .collect::<Vec<_>>();
341         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
342     }
343
344     fn check_expect(ra_fixture: &str, expect: Expect) {
345         let (analysis, file_id) = fixture::file(ra_fixture);
346         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
347         expect.assert_debug_eq(&diagnostics)
348     }
349
350     #[test]
351     fn test_wrap_return_type() {
352         check_fix(
353             r#"
354 //- /main.rs crate:main deps:core
355 use core::result::Result::{self, Ok, Err};
356
357 fn div(x: i32, y: i32) -> Result<i32, ()> {
358     if y == 0 {
359         return Err(());
360     }
361     x / y<|>
362 }
363 //- /core/lib.rs crate:core
364 pub mod result {
365     pub enum Result<T, E> { Ok(T), Err(E) }
366 }
367 "#,
368             r#"
369 use core::result::Result::{self, Ok, Err};
370
371 fn div(x: i32, y: i32) -> Result<i32, ()> {
372     if y == 0 {
373         return Err(());
374     }
375     Ok(x / y)
376 }
377 "#,
378         );
379     }
380
381     #[test]
382     fn test_wrap_return_type_handles_generic_functions() {
383         check_fix(
384             r#"
385 //- /main.rs crate:main deps:core
386 use core::result::Result::{self, Ok, Err};
387
388 fn div<T>(x: T) -> Result<T, i32> {
389     if x == 0 {
390         return Err(7);
391     }
392     <|>x
393 }
394 //- /core/lib.rs crate:core
395 pub mod result {
396     pub enum Result<T, E> { Ok(T), Err(E) }
397 }
398 "#,
399             r#"
400 use core::result::Result::{self, Ok, Err};
401
402 fn div<T>(x: T) -> Result<T, i32> {
403     if x == 0 {
404         return Err(7);
405     }
406     Ok(x)
407 }
408 "#,
409         );
410     }
411
412     #[test]
413     fn test_wrap_return_type_handles_type_aliases() {
414         check_fix(
415             r#"
416 //- /main.rs crate:main deps:core
417 use core::result::Result::{self, Ok, Err};
418
419 type MyResult<T> = Result<T, ()>;
420
421 fn div(x: i32, y: i32) -> MyResult<i32> {
422     if y == 0 {
423         return Err(());
424     }
425     x <|>/ y
426 }
427 //- /core/lib.rs crate:core
428 pub mod result {
429     pub enum Result<T, E> { Ok(T), Err(E) }
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 "#,
461         );
462     }
463
464     #[test]
465     fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
466         check_no_diagnostics(
467             r#"
468 //- /main.rs crate:main deps:core
469 use core::result::Result::{self, Ok, Err};
470
471 enum SomeOtherEnum { Ok(i32), Err(String) }
472
473 fn foo() -> SomeOtherEnum { 0 }
474
475 //- /core/lib.rs crate:core
476 pub mod result {
477     pub enum Result<T, E> { Ok(T), Err(E) }
478 }
479 "#,
480         );
481     }
482
483     #[test]
484     fn test_fill_struct_fields_empty() {
485         check_fix(
486             r#"
487 struct TestStruct { one: i32, two: i64 }
488
489 fn test_fn() {
490     let s = TestStruct {<|>};
491 }
492 "#,
493             r#"
494 struct TestStruct { one: i32, two: i64 }
495
496 fn test_fn() {
497     let s = TestStruct { one: (), two: ()};
498 }
499 "#,
500         );
501     }
502
503     #[test]
504     fn test_fill_struct_fields_self() {
505         check_fix(
506             r#"
507 struct TestStruct { one: i32 }
508
509 impl TestStruct {
510     fn test_fn() { let s = Self {<|>}; }
511 }
512 "#,
513             r#"
514 struct TestStruct { one: i32 }
515
516 impl TestStruct {
517     fn test_fn() { let s = Self { one: ()}; }
518 }
519 "#,
520         );
521     }
522
523     #[test]
524     fn test_fill_struct_fields_enum() {
525         check_fix(
526             r#"
527 enum Expr {
528     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
529 }
530
531 impl Expr {
532     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
533         Expr::Bin {<|> }
534     }
535 }
536 "#,
537             r#"
538 enum Expr {
539     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
540 }
541
542 impl Expr {
543     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
544         Expr::Bin { lhs: (), rhs: () }
545     }
546 }
547 "#,
548         );
549     }
550
551     #[test]
552     fn test_fill_struct_fields_partial() {
553         check_fix(
554             r#"
555 struct TestStruct { one: i32, two: i64 }
556
557 fn test_fn() {
558     let s = TestStruct{ two: 2<|> };
559 }
560 "#,
561             r"
562 struct TestStruct { one: i32, two: i64 }
563
564 fn test_fn() {
565     let s = TestStruct{ two: 2, one: () };
566 }
567 ",
568         );
569     }
570
571     #[test]
572     fn test_fill_struct_fields_no_diagnostic() {
573         check_no_diagnostics(
574             r"
575             struct TestStruct { one: i32, two: i64 }
576
577             fn test_fn() {
578                 let one = 1;
579                 let s = TestStruct{ one, two: 2 };
580             }
581         ",
582         );
583     }
584
585     #[test]
586     fn test_fill_struct_fields_no_diagnostic_on_spread() {
587         check_no_diagnostics(
588             r"
589             struct TestStruct { one: i32, two: i64 }
590
591             fn test_fn() {
592                 let one = 1;
593                 let s = TestStruct{ ..a };
594             }
595         ",
596         );
597     }
598
599     #[test]
600     fn test_unresolved_module_diagnostic() {
601         check_expect(
602             r#"mod foo;"#,
603             expect![[r#"
604                 [
605                     Diagnostic {
606                         message: "unresolved module",
607                         range: 0..8,
608                         severity: Error,
609                         fix: Some(
610                             Fix {
611                                 label: "Create module",
612                                 source_change: SourceChange {
613                                     source_file_edits: [],
614                                     file_system_edits: [
615                                         CreateFile {
616                                             dst: AnchoredPathBuf {
617                                                 anchor: FileId(
618                                                     0,
619                                                 ),
620                                                 path: "foo.rs",
621                                             },
622                                             initial_contents: "",
623                                         },
624                                     ],
625                                     is_snippet: false,
626                                 },
627                                 fix_trigger_range: 0..8,
628                             },
629                         ),
630                         unused: false,
631                         code: Some(
632                             DiagnosticCode(
633                                 "unresolved-module",
634                             ),
635                         ),
636                     },
637                 ]
638             "#]],
639         );
640     }
641
642     #[test]
643     fn range_mapping_out_of_macros() {
644         // FIXME: this is very wrong, but somewhat tricky to fix.
645         check_fix(
646             r#"
647 fn some() {}
648 fn items() {}
649 fn here() {}
650
651 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
652
653 fn main() {
654     let _x = id![Foo { a: <|>42 }];
655 }
656
657 pub struct Foo { pub a: i32, pub b: i32 }
658 "#,
659             r#"
660 fn some(, b: ()) {}
661 fn items() {}
662 fn here() {}
663
664 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
665
666 fn main() {
667     let _x = id![Foo { a: 42 }];
668 }
669
670 pub struct Foo { pub a: i32, pub b: i32 }
671 "#,
672         );
673     }
674
675     #[test]
676     fn test_check_unnecessary_braces_in_use_statement() {
677         check_no_diagnostics(
678             r#"
679 use a;
680 use a::{c, d::e};
681
682 mod a {
683     mod c {}
684     mod d {
685         mod e {}
686     }
687 }
688 "#,
689         );
690         check_fix(
691             r"
692             mod b {}
693             use {<|>b};
694             ",
695             r"
696             mod b {}
697             use b;
698             ",
699         );
700         check_fix(
701             r"
702             mod b {}
703             use {b<|>};
704             ",
705             r"
706             mod b {}
707             use b;
708             ",
709         );
710         check_fix(
711             r"
712             mod a { mod c {} }
713             use a::{c<|>};
714             ",
715             r"
716             mod a { mod c {} }
717             use a::c;
718             ",
719         );
720         check_fix(
721             r"
722             mod a {}
723             use a::{self<|>};
724             ",
725             r"
726             mod a {}
727             use a;
728             ",
729         );
730         check_fix(
731             r"
732             mod a { mod c {} mod d { mod e {} } }
733             use a::{c, d::{e<|>}};
734             ",
735             r"
736             mod a { mod c {} mod d { mod e {} } }
737             use a::{c, d::e};
738             ",
739         );
740     }
741
742     #[test]
743     fn test_add_field_from_usage() {
744         check_fix(
745             r"
746 fn main() {
747     Foo { bar: 3, baz<|>: false};
748 }
749 struct Foo {
750     bar: i32
751 }
752 ",
753             r"
754 fn main() {
755     Foo { bar: 3, baz: false};
756 }
757 struct Foo {
758     bar: i32,
759     baz: bool
760 }
761 ",
762         )
763     }
764
765     #[test]
766     fn test_add_field_in_other_file_from_usage() {
767         check_apply_diagnostic_fix_in_other_file(
768             r"
769             //- /main.rs
770             mod foo;
771
772             fn main() {
773                 <|>foo::Foo { bar: 3, baz: false};
774             }
775             //- /foo.rs
776             struct Foo {
777                 bar: i32
778             }
779             ",
780             r"
781             struct Foo {
782                 bar: i32,
783                 pub(crate) baz: bool
784             }
785             ",
786         )
787     }
788
789     #[test]
790     fn test_disabled_diagnostics() {
791         let mut config = DiagnosticsConfig::default();
792         config.disabled.insert("unresolved-module".into());
793
794         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
795
796         let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
797         assert!(diagnostics.is_empty());
798
799         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
800         assert!(!diagnostics.is_empty());
801     }
802
803     #[test]
804     fn test_rename_incorrect_case() {
805         check_fixes(
806             r#"
807 pub struct test_struct<|> { one: i32 }
808
809 pub fn some_fn(val: test_struct) -> test_struct {
810     test_struct { one: val.one + 1 }
811 }
812 "#,
813             r#"
814 pub struct TestStruct { one: i32 }
815
816 pub fn some_fn(val: TestStruct) -> TestStruct {
817     TestStruct { one: val.one + 1 }
818 }
819 "#,
820         );
821
822         check_fixes(
823             r#"
824 pub fn some_fn(NonSnakeCase<|>: u8) -> u8 {
825     NonSnakeCase
826 }
827 "#,
828             r#"
829 pub fn some_fn(non_snake_case: u8) -> u8 {
830     non_snake_case
831 }
832 "#,
833         );
834
835         check_fixes(
836             r#"
837 pub fn SomeFn<|>(val: u8) -> u8 {
838     if val != 0 { SomeFn(val - 1) } else { val }
839 }
840 "#,
841             r#"
842 pub fn some_fn(val: u8) -> u8 {
843     if val != 0 { some_fn(val - 1) } else { val }
844 }
845 "#,
846         );
847
848         check_fixes(
849             r#"
850 fn some_fn() {
851     let whatAWeird_Formatting<|> = 10;
852     another_func(whatAWeird_Formatting);
853 }
854 "#,
855             r#"
856 fn some_fn() {
857     let what_a_weird_formatting = 10;
858     another_func(what_a_weird_formatting);
859 }
860 "#,
861         );
862     }
863
864     #[test]
865     fn test_uppercase_const_no_diagnostics() {
866         check_no_diagnostics(
867             r#"
868 fn foo() {
869     const ANOTHER_ITEM<|>: &str = "some_item";
870 }
871 "#,
872         );
873     }
874
875     #[test]
876     fn test_rename_incorrect_case_struct_method() {
877         check_fixes(
878             r#"
879 pub struct TestStruct;
880
881 impl TestStruct {
882     pub fn SomeFn<|>() -> TestStruct {
883         TestStruct
884     }
885 }
886 "#,
887             r#"
888 pub struct TestStruct;
889
890 impl TestStruct {
891     pub fn some_fn() -> TestStruct {
892         TestStruct
893     }
894 }
895 "#,
896         );
897     }
898
899     #[test]
900     fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
901         let input = r#"fn FOO<|>() {}"#;
902         let expected = r#"fn foo() {}"#;
903
904         let (analysis, file_position) = fixture::position(input);
905         let diagnostics =
906             analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
907         assert_eq!(diagnostics.len(), 1);
908
909         check_fixes(input, expected);
910     }
911 }