]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Merge #8854
[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_raw_ident() {
658         check_fix(
659             r#"
660 struct TestStruct { r#type: u8 }
661
662 fn test_fn() {
663     TestStruct { $0 };
664 }
665 "#,
666             r"
667 struct TestStruct { r#type: u8 }
668
669 fn test_fn() {
670     TestStruct { r#type: ()  };
671 }
672 ",
673         );
674     }
675
676     #[test]
677     fn test_fill_struct_fields_no_diagnostic() {
678         check_no_diagnostics(
679             r"
680             struct TestStruct { one: i32, two: i64 }
681
682             fn test_fn() {
683                 let one = 1;
684                 let s = TestStruct{ one, two: 2 };
685             }
686         ",
687         );
688     }
689
690     #[test]
691     fn test_fill_struct_fields_no_diagnostic_on_spread() {
692         check_no_diagnostics(
693             r"
694             struct TestStruct { one: i32, two: i64 }
695
696             fn test_fn() {
697                 let one = 1;
698                 let s = TestStruct{ ..a };
699             }
700         ",
701         );
702     }
703
704     #[test]
705     fn test_unresolved_module_diagnostic() {
706         check_expect(
707             r#"mod foo;"#,
708             expect![[r#"
709                 [
710                     Diagnostic {
711                         message: "unresolved module",
712                         range: 0..8,
713                         severity: Error,
714                         fix: Some(
715                             Assist {
716                                 id: AssistId(
717                                     "create_module",
718                                     QuickFix,
719                                 ),
720                                 label: "Create module",
721                                 group: None,
722                                 target: 0..8,
723                                 source_change: Some(
724                                     SourceChange {
725                                         source_file_edits: {},
726                                         file_system_edits: [
727                                             CreateFile {
728                                                 dst: AnchoredPathBuf {
729                                                     anchor: FileId(
730                                                         0,
731                                                     ),
732                                                     path: "foo.rs",
733                                                 },
734                                                 initial_contents: "",
735                                             },
736                                         ],
737                                         is_snippet: false,
738                                     },
739                                 ),
740                             },
741                         ),
742                         unused: false,
743                         code: Some(
744                             DiagnosticCode(
745                                 "unresolved-module",
746                             ),
747                         ),
748                     },
749                 ]
750             "#]],
751         );
752     }
753
754     #[test]
755     fn test_unresolved_macro_range() {
756         check_expect(
757             r#"foo::bar!(92);"#,
758             expect![[r#"
759                 [
760                     Diagnostic {
761                         message: "unresolved macro `foo::bar!`",
762                         range: 5..8,
763                         severity: Error,
764                         fix: None,
765                         unused: false,
766                         code: Some(
767                             DiagnosticCode(
768                                 "unresolved-macro-call",
769                             ),
770                         ),
771                     },
772                 ]
773             "#]],
774         );
775     }
776
777     #[test]
778     fn range_mapping_out_of_macros() {
779         // FIXME: this is very wrong, but somewhat tricky to fix.
780         check_fix(
781             r#"
782 fn some() {}
783 fn items() {}
784 fn here() {}
785
786 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
787
788 fn main() {
789     let _x = id![Foo { a: $042 }];
790 }
791
792 pub struct Foo { pub a: i32, pub b: i32 }
793 "#,
794             r#"
795 fn some(, b: () ) {}
796 fn items() {}
797 fn here() {}
798
799 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
800
801 fn main() {
802     let _x = id![Foo { a: 42 }];
803 }
804
805 pub struct Foo { pub a: i32, pub b: i32 }
806 "#,
807         );
808     }
809
810     #[test]
811     fn test_check_unnecessary_braces_in_use_statement() {
812         check_no_diagnostics(
813             r#"
814 use a;
815 use a::{c, d::e};
816
817 mod a {
818     mod c {}
819     mod d {
820         mod e {}
821     }
822 }
823 "#,
824         );
825         check_no_diagnostics(
826             r#"
827 use a;
828 use a::{
829     c,
830     // d::e
831 };
832
833 mod a {
834     mod c {}
835     mod d {
836         mod e {}
837     }
838 }
839 "#,
840         );
841         check_fix(
842             r"
843             mod b {}
844             use {$0b};
845             ",
846             r"
847             mod b {}
848             use b;
849             ",
850         );
851         check_fix(
852             r"
853             mod b {}
854             use {b$0};
855             ",
856             r"
857             mod b {}
858             use b;
859             ",
860         );
861         check_fix(
862             r"
863             mod a { mod c {} }
864             use a::{c$0};
865             ",
866             r"
867             mod a { mod c {} }
868             use a::c;
869             ",
870         );
871         check_fix(
872             r"
873             mod a {}
874             use a::{self$0};
875             ",
876             r"
877             mod a {}
878             use a;
879             ",
880         );
881         check_fix(
882             r"
883             mod a { mod c {} mod d { mod e {} } }
884             use a::{c, d::{e$0}};
885             ",
886             r"
887             mod a { mod c {} mod d { mod e {} } }
888             use a::{c, d::e};
889             ",
890         );
891     }
892
893     #[test]
894     fn test_add_field_from_usage() {
895         check_fix(
896             r"
897 fn main() {
898     Foo { bar: 3, baz$0: false};
899 }
900 struct Foo {
901     bar: i32
902 }
903 ",
904             r"
905 fn main() {
906     Foo { bar: 3, baz: false};
907 }
908 struct Foo {
909     bar: i32,
910     baz: bool
911 }
912 ",
913         )
914     }
915
916     #[test]
917     fn test_add_field_in_other_file_from_usage() {
918         check_fix(
919             r#"
920 //- /main.rs
921 mod foo;
922
923 fn main() {
924     foo::Foo { bar: 3, $0baz: false};
925 }
926 //- /foo.rs
927 struct Foo {
928     bar: i32
929 }
930 "#,
931             r#"
932 struct Foo {
933     bar: i32,
934     pub(crate) baz: bool
935 }
936 "#,
937         )
938     }
939
940     #[test]
941     fn test_disabled_diagnostics() {
942         let mut config = DiagnosticsConfig::default();
943         config.disabled.insert("unresolved-module".into());
944
945         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
946
947         let diagnostics =
948             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
949         assert!(diagnostics.is_empty());
950
951         let diagnostics = analysis
952             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
953             .unwrap();
954         assert!(!diagnostics.is_empty());
955     }
956
957     #[test]
958     fn test_rename_incorrect_case() {
959         check_fix(
960             r#"
961 pub struct test_struct$0 { one: i32 }
962
963 pub fn some_fn(val: test_struct) -> test_struct {
964     test_struct { one: val.one + 1 }
965 }
966 "#,
967             r#"
968 pub struct TestStruct { one: i32 }
969
970 pub fn some_fn(val: TestStruct) -> TestStruct {
971     TestStruct { one: val.one + 1 }
972 }
973 "#,
974         );
975
976         check_fix(
977             r#"
978 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
979     NonSnakeCase
980 }
981 "#,
982             r#"
983 pub fn some_fn(non_snake_case: u8) -> u8 {
984     non_snake_case
985 }
986 "#,
987         );
988
989         check_fix(
990             r#"
991 pub fn SomeFn$0(val: u8) -> u8 {
992     if val != 0 { SomeFn(val - 1) } else { val }
993 }
994 "#,
995             r#"
996 pub fn some_fn(val: u8) -> u8 {
997     if val != 0 { some_fn(val - 1) } else { val }
998 }
999 "#,
1000         );
1001
1002         check_fix(
1003             r#"
1004 fn some_fn() {
1005     let whatAWeird_Formatting$0 = 10;
1006     another_func(whatAWeird_Formatting);
1007 }
1008 "#,
1009             r#"
1010 fn some_fn() {
1011     let what_a_weird_formatting = 10;
1012     another_func(what_a_weird_formatting);
1013 }
1014 "#,
1015         );
1016     }
1017
1018     #[test]
1019     fn test_uppercase_const_no_diagnostics() {
1020         check_no_diagnostics(
1021             r#"
1022 fn foo() {
1023     const ANOTHER_ITEM$0: &str = "some_item";
1024 }
1025 "#,
1026         );
1027     }
1028
1029     #[test]
1030     fn test_rename_incorrect_case_struct_method() {
1031         check_fix(
1032             r#"
1033 pub struct TestStruct;
1034
1035 impl TestStruct {
1036     pub fn SomeFn$0() -> TestStruct {
1037         TestStruct
1038     }
1039 }
1040 "#,
1041             r#"
1042 pub struct TestStruct;
1043
1044 impl TestStruct {
1045     pub fn some_fn() -> TestStruct {
1046         TestStruct
1047     }
1048 }
1049 "#,
1050         );
1051     }
1052
1053     #[test]
1054     fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
1055         let input = r#"fn FOO$0() {}"#;
1056         let expected = r#"fn foo() {}"#;
1057
1058         let (analysis, file_position) = fixture::position(input);
1059         let diagnostics = analysis
1060             .diagnostics(
1061                 &DiagnosticsConfig::default(),
1062                 AssistResolveStrategy::All,
1063                 file_position.file_id,
1064             )
1065             .unwrap();
1066         assert_eq!(diagnostics.len(), 1);
1067
1068         check_fix(input, expected);
1069     }
1070
1071     #[test]
1072     fn unlinked_file_prepend_first_item() {
1073         cov_mark::check!(unlinked_file_prepend_before_first_item);
1074         check_fix(
1075             r#"
1076 //- /main.rs
1077 fn f() {}
1078 //- /foo.rs
1079 $0
1080 "#,
1081             r#"
1082 mod foo;
1083
1084 fn f() {}
1085 "#,
1086         );
1087     }
1088
1089     #[test]
1090     fn unlinked_file_append_mod() {
1091         cov_mark::check!(unlinked_file_append_to_existing_mods);
1092         check_fix(
1093             r#"
1094 //- /main.rs
1095 //! Comment on top
1096
1097 mod preexisting;
1098
1099 mod preexisting2;
1100
1101 struct S;
1102
1103 mod preexisting_bottom;)
1104 //- /foo.rs
1105 $0
1106 "#,
1107             r#"
1108 //! Comment on top
1109
1110 mod preexisting;
1111
1112 mod preexisting2;
1113 mod foo;
1114
1115 struct S;
1116
1117 mod preexisting_bottom;)
1118 "#,
1119         );
1120     }
1121
1122     #[test]
1123     fn unlinked_file_insert_in_empty_file() {
1124         cov_mark::check!(unlinked_file_empty_file);
1125         check_fix(
1126             r#"
1127 //- /main.rs
1128 //- /foo.rs
1129 $0
1130 "#,
1131             r#"
1132 mod foo;
1133 "#,
1134         );
1135     }
1136
1137     #[test]
1138     fn unlinked_file_old_style_modrs() {
1139         check_fix(
1140             r#"
1141 //- /main.rs
1142 mod submod;
1143 //- /submod/mod.rs
1144 // in mod.rs
1145 //- /submod/foo.rs
1146 $0
1147 "#,
1148             r#"
1149 // in mod.rs
1150 mod foo;
1151 "#,
1152         );
1153     }
1154
1155     #[test]
1156     fn unlinked_file_new_style_mod() {
1157         check_fix(
1158             r#"
1159 //- /main.rs
1160 mod submod;
1161 //- /submod.rs
1162 //- /submod/foo.rs
1163 $0
1164 "#,
1165             r#"
1166 mod foo;
1167 "#,
1168         );
1169     }
1170
1171     #[test]
1172     fn unlinked_file_with_cfg_off() {
1173         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1174         check_no_fix(
1175             r#"
1176 //- /main.rs
1177 #[cfg(never)]
1178 mod foo;
1179
1180 //- /foo.rs
1181 $0
1182 "#,
1183         );
1184     }
1185
1186     #[test]
1187     fn unlinked_file_with_cfg_on() {
1188         check_no_diagnostics(
1189             r#"
1190 //- /main.rs
1191 #[cfg(not(never))]
1192 mod foo;
1193
1194 //- /foo.rs
1195 "#,
1196         );
1197     }
1198 }