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