]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Merge #8720
[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 mod unlinked_file;
10
11 use std::cell::RefCell;
12
13 use hir::{
14     db::AstDatabase,
15     diagnostics::{Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
16     InFile, Semantics,
17 };
18 use ide_assists::AssistResolveStrategy;
19 use ide_db::{base_db::SourceDatabase, RootDatabase};
20 use itertools::Itertools;
21 use rustc_hash::FxHashSet;
22 use syntax::{
23     ast::{self, AstNode},
24     SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
25 };
26 use text_edit::TextEdit;
27 use unlinked_file::UnlinkedFile;
28
29 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
30
31 use self::fixes::DiagnosticWithFix;
32
33 #[derive(Debug)]
34 pub struct Diagnostic {
35     // pub name: Option<String>,
36     pub message: String,
37     pub range: TextRange,
38     pub severity: Severity,
39     pub fix: Option<Assist>,
40     pub unused: bool,
41     pub code: Option<DiagnosticCode>,
42 }
43
44 impl Diagnostic {
45     fn error(range: TextRange, message: String) -> Self {
46         Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
47     }
48
49     fn hint(range: TextRange, message: String) -> Self {
50         Self {
51             message,
52             range,
53             severity: Severity::WeakWarning,
54             fix: None,
55             unused: false,
56             code: None,
57         }
58     }
59
60     fn with_fix(self, fix: Option<Assist>) -> Self {
61         Self { fix, ..self }
62     }
63
64     fn with_unused(self, unused: bool) -> Self {
65         Self { unused, ..self }
66     }
67
68     fn with_code(self, code: Option<DiagnosticCode>) -> Self {
69         Self { code, ..self }
70     }
71 }
72
73 #[derive(Debug, Copy, Clone)]
74 pub enum Severity {
75     Error,
76     WeakWarning,
77 }
78
79 #[derive(Default, Debug, Clone)]
80 pub struct DiagnosticsConfig {
81     pub disable_experimental: bool,
82     pub disabled: FxHashSet<String>,
83 }
84
85 pub(crate) fn diagnostics(
86     db: &RootDatabase,
87     config: &DiagnosticsConfig,
88     resolve: &AssistResolveStrategy,
89     file_id: FileId,
90 ) -> Vec<Diagnostic> {
91     let _p = profile::span("diagnostics");
92     let sema = Semantics::new(db);
93     let parse = db.parse(file_id);
94     let mut res = Vec::new();
95
96     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
97     res.extend(
98         parse
99             .errors()
100             .iter()
101             .take(128)
102             .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
103     );
104
105     for node in parse.tree().syntax().descendants() {
106         check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
107         field_shorthand::check(&mut res, file_id, &node);
108     }
109     let res = RefCell::new(res);
110     let sink_builder = DiagnosticSinkBuilder::new()
111         .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
112             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
113         })
114         .on::<hir::diagnostics::MissingFields, _>(|d| {
115             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
116         })
117         .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
118             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
119         })
120         .on::<hir::diagnostics::NoSuchField, _>(|d| {
121             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
122         })
123         .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
124             res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
125         })
126         .on::<hir::diagnostics::IncorrectCase, _>(|d| {
127             res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
128         })
129         .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
130             res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
131         })
132         .on::<hir::diagnostics::InactiveCode, _>(|d| {
133             // If there's inactive code somewhere in a macro, don't propagate to the call-site.
134             if d.display_source().file_id.expansion_info(db).is_some() {
135                 return;
136             }
137
138             // Override severity and mark as unused.
139             res.borrow_mut().push(
140                 Diagnostic::hint(
141                     sema.diagnostics_display_range(d.display_source()).range,
142                     d.message(),
143                 )
144                 .with_unused(true)
145                 .with_code(Some(d.code())),
146             );
147         })
148         .on::<UnlinkedFile, _>(|d| {
149             // Limit diagnostic to the first few characters in the file. This matches how VS Code
150             // renders it with the full span, but on other editors, and is less invasive.
151             let range = sema.diagnostics_display_range(d.display_source()).range;
152             let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
153
154             // Override severity and mark as unused.
155             res.borrow_mut().push(
156                 Diagnostic::hint(range, d.message())
157                     .with_fix(d.fix(&sema, resolve))
158                     .with_code(Some(d.code())),
159             );
160         })
161         .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
162             // Use more accurate position if available.
163             let display_range = d
164                 .precise_location
165                 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
166
167             // FIXME: it would be nice to tell the user whether proc macros are currently disabled
168             res.borrow_mut()
169                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
170         })
171         .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
172             let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
173                 d.node
174                     .to_node(&root)
175                     .path()
176                     .and_then(|it| it.segment())
177                     .and_then(|it| it.name_ref())
178                     .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
179             });
180             let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
181             let display_range = sema.diagnostics_display_range(diagnostics).range;
182             res.borrow_mut()
183                 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
184         })
185         // Only collect experimental diagnostics when they're enabled.
186         .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
187         .filter(|diag| !config.disabled.contains(diag.code().as_str()));
188
189     // Finalize the `DiagnosticSink` building process.
190     let mut sink = sink_builder
191         // Diagnostics not handled above get no fix and default treatment.
192         .build(|d| {
193             res.borrow_mut().push(
194                 Diagnostic::error(
195                     sema.diagnostics_display_range(d.display_source()).range,
196                     d.message(),
197                 )
198                 .with_code(Some(d.code())),
199             );
200         });
201
202     match sema.to_module_def(file_id) {
203         Some(m) => m.diagnostics(db, &mut sink),
204         None => {
205             sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
206         }
207     }
208
209     drop(sink);
210     res.into_inner()
211 }
212
213 fn diagnostic_with_fix<D: DiagnosticWithFix>(
214     d: &D,
215     sema: &Semantics<RootDatabase>,
216     resolve: &AssistResolveStrategy,
217 ) -> Diagnostic {
218     Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
219         .with_fix(d.fix(&sema, resolve))
220         .with_code(Some(d.code()))
221 }
222
223 fn warning_with_fix<D: DiagnosticWithFix>(
224     d: &D,
225     sema: &Semantics<RootDatabase>,
226     resolve: &AssistResolveStrategy,
227 ) -> Diagnostic {
228     Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
229         .with_fix(d.fix(&sema, resolve))
230         .with_code(Some(d.code()))
231 }
232
233 fn check_unnecessary_braces_in_use_statement(
234     acc: &mut Vec<Diagnostic>,
235     file_id: FileId,
236     node: &SyntaxNode,
237 ) -> Option<()> {
238     let use_tree_list = ast::UseTreeList::cast(node.clone())?;
239     if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
240         // If there is a comment inside the bracketed `use`,
241         // assume it is a commented out module path and don't show diagnostic.
242         if use_tree_list.has_inner_comment() {
243             return Some(());
244         }
245
246         let use_range = use_tree_list.syntax().text_range();
247         let edit =
248             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
249                 .unwrap_or_else(|| {
250                     let to_replace = single_use_tree.syntax().text().to_string();
251                     let mut edit_builder = TextEdit::builder();
252                     edit_builder.delete(use_range);
253                     edit_builder.insert(use_range.start(), to_replace);
254                     edit_builder.finish()
255                 });
256
257         acc.push(
258             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
259                 .with_fix(Some(fix(
260                     "remove_braces",
261                     "Remove unnecessary braces",
262                     SourceChange::from_text_edit(file_id, edit),
263                     use_range,
264                 ))),
265         );
266     }
267
268     Some(())
269 }
270
271 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
272     single_use_tree: &ast::UseTree,
273 ) -> Option<TextEdit> {
274     let use_tree_list_node = single_use_tree.syntax().parent()?;
275     if single_use_tree.path()?.segment()?.self_token().is_some() {
276         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
277         let end = use_tree_list_node.text_range().end();
278         return Some(TextEdit::delete(TextRange::new(start, end)));
279     }
280     None
281 }
282
283 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
284     let mut res = unresolved_fix(id, label, target);
285     res.source_change = Some(source_change);
286     res
287 }
288
289 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
290     assert!(!id.contains(' '));
291     Assist {
292         id: AssistId(id, AssistKind::QuickFix),
293         label: Label::new(label),
294         group: None,
295         target,
296         source_change: None,
297     }
298 }
299
300 #[cfg(test)]
301 mod tests {
302     use expect_test::{expect, Expect};
303     use ide_assists::AssistResolveStrategy;
304     use stdx::trim_indent;
305     use test_utils::assert_eq_text;
306
307     use crate::{fixture, DiagnosticsConfig};
308
309     /// Takes a multi-file input fixture with annotated cursor positions,
310     /// and checks that:
311     ///  * a diagnostic is produced
312     ///  * this diagnostic fix trigger range touches the input cursor position
313     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
314     pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
315         let after = trim_indent(ra_fixture_after);
316
317         let (analysis, file_position) = fixture::position(ra_fixture_before);
318         let diagnostic = analysis
319             .diagnostics(
320                 &DiagnosticsConfig::default(),
321                 AssistResolveStrategy::All,
322                 file_position.file_id,
323             )
324             .unwrap()
325             .pop()
326             .unwrap();
327         let fix = diagnostic.fix.unwrap();
328         let actual = {
329             let source_change = fix.source_change.unwrap();
330             let file_id = *source_change.source_file_edits.keys().next().unwrap();
331             let mut actual = analysis.file_text(file_id).unwrap().to_string();
332
333             for edit in source_change.source_file_edits.values() {
334                 edit.apply(&mut actual);
335             }
336             actual
337         };
338
339         assert_eq_text!(&after, &actual);
340         assert!(
341             fix.target.contains_inclusive(file_position.offset),
342             "diagnostic fix range {:?} does not touch cursor position {:?}",
343             fix.target,
344             file_position.offset
345         );
346     }
347
348     /// Checks that there's a diagnostic *without* fix at `$0`.
349     fn check_no_fix(ra_fixture: &str) {
350         let (analysis, file_position) = fixture::position(ra_fixture);
351         let diagnostic = analysis
352             .diagnostics(
353                 &DiagnosticsConfig::default(),
354                 AssistResolveStrategy::All,
355                 file_position.file_id,
356             )
357             .unwrap()
358             .pop()
359             .unwrap();
360         assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
361     }
362
363     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
364     /// apply to the file containing the cursor.
365     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
366         let (analysis, files) = fixture::files(ra_fixture);
367         let diagnostics = files
368             .into_iter()
369             .flat_map(|file_id| {
370                 analysis
371                     .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
372                     .unwrap()
373             })
374             .collect::<Vec<_>>();
375         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
376     }
377
378     fn check_expect(ra_fixture: &str, expect: Expect) {
379         let (analysis, file_id) = fixture::file(ra_fixture);
380         let diagnostics = analysis
381             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
382             .unwrap();
383         expect.assert_debug_eq(&diagnostics)
384     }
385
386     #[test]
387     fn test_wrap_return_type_option() {
388         check_fix(
389             r#"
390 //- /main.rs crate:main deps:core
391 use core::option::Option::{self, Some, None};
392
393 fn div(x: i32, y: i32) -> Option<i32> {
394     if y == 0 {
395         return None;
396     }
397     x / y$0
398 }
399 //- /core/lib.rs crate:core
400 pub mod result {
401     pub enum Result<T, E> { Ok(T), Err(E) }
402 }
403 pub mod option {
404     pub enum Option<T> { Some(T), None }
405 }
406 "#,
407             r#"
408 use core::option::Option::{self, Some, None};
409
410 fn div(x: i32, y: i32) -> Option<i32> {
411     if y == 0 {
412         return None;
413     }
414     Some(x / y)
415 }
416 "#,
417         );
418     }
419
420     #[test]
421     fn test_wrap_return_type() {
422         check_fix(
423             r#"
424 //- /main.rs crate:main deps:core
425 use core::result::Result::{self, Ok, Err};
426
427 fn div(x: i32, y: i32) -> Result<i32, ()> {
428     if y == 0 {
429         return Err(());
430     }
431     x / y$0
432 }
433 //- /core/lib.rs crate:core
434 pub mod result {
435     pub enum Result<T, E> { Ok(T), Err(E) }
436 }
437 pub mod option {
438     pub enum Option<T> { Some(T), None }
439 }
440 "#,
441             r#"
442 use core::result::Result::{self, Ok, Err};
443
444 fn div(x: i32, y: i32) -> Result<i32, ()> {
445     if y == 0 {
446         return Err(());
447     }
448     Ok(x / y)
449 }
450 "#,
451         );
452     }
453
454     #[test]
455     fn test_wrap_return_type_handles_generic_functions() {
456         check_fix(
457             r#"
458 //- /main.rs crate:main deps:core
459 use core::result::Result::{self, Ok, Err};
460
461 fn div<T>(x: T) -> Result<T, i32> {
462     if x == 0 {
463         return Err(7);
464     }
465     $0x
466 }
467 //- /core/lib.rs crate:core
468 pub mod result {
469     pub enum Result<T, E> { Ok(T), Err(E) }
470 }
471 pub mod option {
472     pub enum Option<T> { Some(T), None }
473 }
474 "#,
475             r#"
476 use core::result::Result::{self, Ok, Err};
477
478 fn div<T>(x: T) -> Result<T, i32> {
479     if x == 0 {
480         return Err(7);
481     }
482     Ok(x)
483 }
484 "#,
485         );
486     }
487
488     #[test]
489     fn test_wrap_return_type_handles_type_aliases() {
490         check_fix(
491             r#"
492 //- /main.rs crate:main deps:core
493 use core::result::Result::{self, Ok, Err};
494
495 type MyResult<T> = Result<T, ()>;
496
497 fn div(x: i32, y: i32) -> MyResult<i32> {
498     if y == 0 {
499         return Err(());
500     }
501     x $0/ y
502 }
503 //- /core/lib.rs crate:core
504 pub mod result {
505     pub enum Result<T, E> { Ok(T), Err(E) }
506 }
507 pub mod option {
508     pub enum Option<T> { Some(T), None }
509 }
510 "#,
511             r#"
512 use core::result::Result::{self, Ok, Err};
513
514 type MyResult<T> = Result<T, ()>;
515
516 fn div(x: i32, y: i32) -> MyResult<i32> {
517     if y == 0 {
518         return Err(());
519     }
520     Ok(x / y)
521 }
522 "#,
523         );
524     }
525
526     #[test]
527     fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
528         check_no_diagnostics(
529             r#"
530 //- /main.rs crate:main deps:core
531 use core::result::Result::{self, Ok, Err};
532
533 fn foo() -> Result<(), i32> { 0 }
534
535 //- /core/lib.rs crate:core
536 pub mod result {
537     pub enum Result<T, E> { Ok(T), Err(E) }
538 }
539 pub mod option {
540     pub enum Option<T> { Some(T), None }
541 }
542 "#,
543         );
544     }
545
546     #[test]
547     fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
548         check_no_diagnostics(
549             r#"
550 //- /main.rs crate:main deps:core
551 use core::result::Result::{self, Ok, Err};
552
553 enum SomeOtherEnum { Ok(i32), Err(String) }
554
555 fn foo() -> SomeOtherEnum { 0 }
556
557 //- /core/lib.rs crate:core
558 pub mod result {
559     pub enum Result<T, E> { Ok(T), Err(E) }
560 }
561 pub mod option {
562     pub enum Option<T> { Some(T), None }
563 }
564 "#,
565         );
566     }
567
568     #[test]
569     fn test_fill_struct_fields_empty() {
570         check_fix(
571             r#"
572 struct TestStruct { one: i32, two: i64 }
573
574 fn test_fn() {
575     let s = TestStruct {$0};
576 }
577 "#,
578             r#"
579 struct TestStruct { one: i32, two: i64 }
580
581 fn test_fn() {
582     let s = TestStruct { one: (), two: ()};
583 }
584 "#,
585         );
586     }
587
588     #[test]
589     fn test_fill_struct_fields_self() {
590         check_fix(
591             r#"
592 struct TestStruct { one: i32 }
593
594 impl TestStruct {
595     fn test_fn() { let s = Self {$0}; }
596 }
597 "#,
598             r#"
599 struct TestStruct { one: i32 }
600
601 impl TestStruct {
602     fn test_fn() { let s = Self { one: ()}; }
603 }
604 "#,
605         );
606     }
607
608     #[test]
609     fn test_fill_struct_fields_enum() {
610         check_fix(
611             r#"
612 enum Expr {
613     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
614 }
615
616 impl Expr {
617     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
618         Expr::Bin {$0 }
619     }
620 }
621 "#,
622             r#"
623 enum Expr {
624     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
625 }
626
627 impl Expr {
628     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
629         Expr::Bin { lhs: (), rhs: () }
630     }
631 }
632 "#,
633         );
634     }
635
636     #[test]
637     fn test_fill_struct_fields_partial() {
638         check_fix(
639             r#"
640 struct TestStruct { one: i32, two: i64 }
641
642 fn test_fn() {
643     let s = TestStruct{ two: 2$0 };
644 }
645 "#,
646             r"
647 struct TestStruct { one: i32, two: i64 }
648
649 fn test_fn() {
650     let s = TestStruct{ two: 2, one: () };
651 }
652 ",
653         );
654     }
655
656     #[test]
657     fn test_fill_struct_fields_no_diagnostic() {
658         check_no_diagnostics(
659             r"
660             struct TestStruct { one: i32, two: i64 }
661
662             fn test_fn() {
663                 let one = 1;
664                 let s = TestStruct{ one, two: 2 };
665             }
666         ",
667         );
668     }
669
670     #[test]
671     fn test_fill_struct_fields_no_diagnostic_on_spread() {
672         check_no_diagnostics(
673             r"
674             struct TestStruct { one: i32, two: i64 }
675
676             fn test_fn() {
677                 let one = 1;
678                 let s = TestStruct{ ..a };
679             }
680         ",
681         );
682     }
683
684     #[test]
685     fn test_unresolved_module_diagnostic() {
686         check_expect(
687             r#"mod foo;"#,
688             expect![[r#"
689                 [
690                     Diagnostic {
691                         message: "unresolved module",
692                         range: 0..8,
693                         severity: Error,
694                         fix: Some(
695                             Assist {
696                                 id: AssistId(
697                                     "create_module",
698                                     QuickFix,
699                                 ),
700                                 label: "Create module",
701                                 group: None,
702                                 target: 0..8,
703                                 source_change: Some(
704                                     SourceChange {
705                                         source_file_edits: {},
706                                         file_system_edits: [
707                                             CreateFile {
708                                                 dst: AnchoredPathBuf {
709                                                     anchor: FileId(
710                                                         0,
711                                                     ),
712                                                     path: "foo.rs",
713                                                 },
714                                                 initial_contents: "",
715                                             },
716                                         ],
717                                         is_snippet: false,
718                                     },
719                                 ),
720                             },
721                         ),
722                         unused: false,
723                         code: Some(
724                             DiagnosticCode(
725                                 "unresolved-module",
726                             ),
727                         ),
728                     },
729                 ]
730             "#]],
731         );
732     }
733
734     #[test]
735     fn test_unresolved_macro_range() {
736         check_expect(
737             r#"foo::bar!(92);"#,
738             expect![[r#"
739                 [
740                     Diagnostic {
741                         message: "unresolved macro `foo::bar!`",
742                         range: 5..8,
743                         severity: Error,
744                         fix: None,
745                         unused: false,
746                         code: Some(
747                             DiagnosticCode(
748                                 "unresolved-macro-call",
749                             ),
750                         ),
751                     },
752                 ]
753             "#]],
754         );
755     }
756
757     #[test]
758     fn range_mapping_out_of_macros() {
759         // FIXME: this is very wrong, but somewhat tricky to fix.
760         check_fix(
761             r#"
762 fn some() {}
763 fn items() {}
764 fn here() {}
765
766 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
767
768 fn main() {
769     let _x = id![Foo { a: $042 }];
770 }
771
772 pub struct Foo { pub a: i32, pub b: i32 }
773 "#,
774             r#"
775 fn some(, b: ()) {}
776 fn items() {}
777 fn here() {}
778
779 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
780
781 fn main() {
782     let _x = id![Foo { a: 42 }];
783 }
784
785 pub struct Foo { pub a: i32, pub b: i32 }
786 "#,
787         );
788     }
789
790     #[test]
791     fn test_check_unnecessary_braces_in_use_statement() {
792         check_no_diagnostics(
793             r#"
794 use a;
795 use a::{c, d::e};
796
797 mod a {
798     mod c {}
799     mod d {
800         mod e {}
801     }
802 }
803 "#,
804         );
805         check_no_diagnostics(
806             r#"
807 use a;
808 use a::{
809     c,
810     // d::e
811 };
812
813 mod a {
814     mod c {}
815     mod d {
816         mod e {}
817     }
818 }
819 "#,
820         );
821         check_fix(
822             r"
823             mod b {}
824             use {$0b};
825             ",
826             r"
827             mod b {}
828             use b;
829             ",
830         );
831         check_fix(
832             r"
833             mod b {}
834             use {b$0};
835             ",
836             r"
837             mod b {}
838             use b;
839             ",
840         );
841         check_fix(
842             r"
843             mod a { mod c {} }
844             use a::{c$0};
845             ",
846             r"
847             mod a { mod c {} }
848             use a::c;
849             ",
850         );
851         check_fix(
852             r"
853             mod a {}
854             use a::{self$0};
855             ",
856             r"
857             mod a {}
858             use a;
859             ",
860         );
861         check_fix(
862             r"
863             mod a { mod c {} mod d { mod e {} } }
864             use a::{c, d::{e$0}};
865             ",
866             r"
867             mod a { mod c {} mod d { mod e {} } }
868             use a::{c, d::e};
869             ",
870         );
871     }
872
873     #[test]
874     fn test_add_field_from_usage() {
875         check_fix(
876             r"
877 fn main() {
878     Foo { bar: 3, baz$0: false};
879 }
880 struct Foo {
881     bar: i32
882 }
883 ",
884             r"
885 fn main() {
886     Foo { bar: 3, baz: false};
887 }
888 struct Foo {
889     bar: i32,
890     baz: bool
891 }
892 ",
893         )
894     }
895
896     #[test]
897     fn test_add_field_in_other_file_from_usage() {
898         check_fix(
899             r#"
900 //- /main.rs
901 mod foo;
902
903 fn main() {
904     foo::Foo { bar: 3, $0baz: false};
905 }
906 //- /foo.rs
907 struct Foo {
908     bar: i32
909 }
910 "#,
911             r#"
912 struct Foo {
913     bar: i32,
914     pub(crate) baz: bool
915 }
916 "#,
917         )
918     }
919
920     #[test]
921     fn test_disabled_diagnostics() {
922         let mut config = DiagnosticsConfig::default();
923         config.disabled.insert("unresolved-module".into());
924
925         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
926
927         let diagnostics =
928             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
929         assert!(diagnostics.is_empty());
930
931         let diagnostics = analysis
932             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
933             .unwrap();
934         assert!(!diagnostics.is_empty());
935     }
936
937     #[test]
938     fn test_rename_incorrect_case() {
939         check_fix(
940             r#"
941 pub struct test_struct$0 { one: i32 }
942
943 pub fn some_fn(val: test_struct) -> test_struct {
944     test_struct { one: val.one + 1 }
945 }
946 "#,
947             r#"
948 pub struct TestStruct { one: i32 }
949
950 pub fn some_fn(val: TestStruct) -> TestStruct {
951     TestStruct { one: val.one + 1 }
952 }
953 "#,
954         );
955
956         check_fix(
957             r#"
958 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
959     NonSnakeCase
960 }
961 "#,
962             r#"
963 pub fn some_fn(non_snake_case: u8) -> u8 {
964     non_snake_case
965 }
966 "#,
967         );
968
969         check_fix(
970             r#"
971 pub fn SomeFn$0(val: u8) -> u8 {
972     if val != 0 { SomeFn(val - 1) } else { val }
973 }
974 "#,
975             r#"
976 pub fn some_fn(val: u8) -> u8 {
977     if val != 0 { some_fn(val - 1) } else { val }
978 }
979 "#,
980         );
981
982         check_fix(
983             r#"
984 fn some_fn() {
985     let whatAWeird_Formatting$0 = 10;
986     another_func(whatAWeird_Formatting);
987 }
988 "#,
989             r#"
990 fn some_fn() {
991     let what_a_weird_formatting = 10;
992     another_func(what_a_weird_formatting);
993 }
994 "#,
995         );
996     }
997
998     #[test]
999     fn test_uppercase_const_no_diagnostics() {
1000         check_no_diagnostics(
1001             r#"
1002 fn foo() {
1003     const ANOTHER_ITEM$0: &str = "some_item";
1004 }
1005 "#,
1006         );
1007     }
1008
1009     #[test]
1010     fn test_rename_incorrect_case_struct_method() {
1011         check_fix(
1012             r#"
1013 pub struct TestStruct;
1014
1015 impl TestStruct {
1016     pub fn SomeFn$0() -> TestStruct {
1017         TestStruct
1018     }
1019 }
1020 "#,
1021             r#"
1022 pub struct TestStruct;
1023
1024 impl TestStruct {
1025     pub fn some_fn() -> TestStruct {
1026         TestStruct
1027     }
1028 }
1029 "#,
1030         );
1031     }
1032
1033     #[test]
1034     fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
1035         let input = r#"fn FOO$0() {}"#;
1036         let expected = r#"fn foo() {}"#;
1037
1038         let (analysis, file_position) = fixture::position(input);
1039         let diagnostics = analysis
1040             .diagnostics(
1041                 &DiagnosticsConfig::default(),
1042                 AssistResolveStrategy::All,
1043                 file_position.file_id,
1044             )
1045             .unwrap();
1046         assert_eq!(diagnostics.len(), 1);
1047
1048         check_fix(input, expected);
1049     }
1050
1051     #[test]
1052     fn unlinked_file_prepend_first_item() {
1053         cov_mark::check!(unlinked_file_prepend_before_first_item);
1054         check_fix(
1055             r#"
1056 //- /main.rs
1057 fn f() {}
1058 //- /foo.rs
1059 $0
1060 "#,
1061             r#"
1062 mod foo;
1063
1064 fn f() {}
1065 "#,
1066         );
1067     }
1068
1069     #[test]
1070     fn unlinked_file_append_mod() {
1071         cov_mark::check!(unlinked_file_append_to_existing_mods);
1072         check_fix(
1073             r#"
1074 //- /main.rs
1075 //! Comment on top
1076
1077 mod preexisting;
1078
1079 mod preexisting2;
1080
1081 struct S;
1082
1083 mod preexisting_bottom;)
1084 //- /foo.rs
1085 $0
1086 "#,
1087             r#"
1088 //! Comment on top
1089
1090 mod preexisting;
1091
1092 mod preexisting2;
1093 mod foo;
1094
1095 struct S;
1096
1097 mod preexisting_bottom;)
1098 "#,
1099         );
1100     }
1101
1102     #[test]
1103     fn unlinked_file_insert_in_empty_file() {
1104         cov_mark::check!(unlinked_file_empty_file);
1105         check_fix(
1106             r#"
1107 //- /main.rs
1108 //- /foo.rs
1109 $0
1110 "#,
1111             r#"
1112 mod foo;
1113 "#,
1114         );
1115     }
1116
1117     #[test]
1118     fn unlinked_file_old_style_modrs() {
1119         check_fix(
1120             r#"
1121 //- /main.rs
1122 mod submod;
1123 //- /submod/mod.rs
1124 // in mod.rs
1125 //- /submod/foo.rs
1126 $0
1127 "#,
1128             r#"
1129 // in mod.rs
1130 mod foo;
1131 "#,
1132         );
1133     }
1134
1135     #[test]
1136     fn unlinked_file_new_style_mod() {
1137         check_fix(
1138             r#"
1139 //- /main.rs
1140 mod submod;
1141 //- /submod.rs
1142 //- /submod/foo.rs
1143 $0
1144 "#,
1145             r#"
1146 mod foo;
1147 "#,
1148         );
1149     }
1150
1151     #[test]
1152     fn unlinked_file_with_cfg_off() {
1153         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1154         check_no_fix(
1155             r#"
1156 //- /main.rs
1157 #[cfg(never)]
1158 mod foo;
1159
1160 //- /foo.rs
1161 $0
1162 "#,
1163         );
1164     }
1165
1166     #[test]
1167     fn unlinked_file_with_cfg_on() {
1168         check_no_diagnostics(
1169             r#"
1170 //- /main.rs
1171 #[cfg(not(never))]
1172 mod foo;
1173
1174 //- /foo.rs
1175 "#,
1176         );
1177     }
1178 }