]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
906f72a42abae64477aa65f43926a6f950a9a4d2
[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
9 use std::cell::RefCell;
10
11 use base_db::SourceDatabase;
12 use hir::{diagnostics::DiagnosticSinkBuilder, Semantics};
13 use ide_db::RootDatabase;
14 use itertools::Itertools;
15 use rustc_hash::FxHashSet;
16 use syntax::{
17     ast::{self, AstNode},
18     SyntaxNode, TextRange, T,
19 };
20 use text_edit::TextEdit;
21
22 use crate::{FileId, Label, SourceChange, SourceFileEdit};
23
24 use self::fixes::DiagnosticWithFix;
25
26 #[derive(Debug)]
27 pub struct Diagnostic {
28     // pub name: Option<String>,
29     pub message: String,
30     pub range: TextRange,
31     pub severity: Severity,
32     pub fix: Option<Fix>,
33 }
34
35 #[derive(Debug)]
36 pub struct Fix {
37     pub label: Label,
38     pub source_change: SourceChange,
39     /// Allows to trigger the fix only when the caret is in the range given
40     pub fix_trigger_range: TextRange,
41 }
42
43 impl Fix {
44     fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
45         let label = Label::new(label);
46         Self { label, source_change, fix_trigger_range }
47     }
48 }
49
50 #[derive(Debug, Copy, Clone)]
51 pub enum Severity {
52     Error,
53     WeakWarning,
54 }
55
56 #[derive(Default, Debug, Clone)]
57 pub struct DiagnosticsConfig {
58     pub disable_experimental: bool,
59     pub disabled: FxHashSet<String>,
60 }
61
62 pub(crate) fn diagnostics(
63     db: &RootDatabase,
64     config: &DiagnosticsConfig,
65     file_id: FileId,
66 ) -> Vec<Diagnostic> {
67     let _p = profile::span("diagnostics");
68     let sema = Semantics::new(db);
69     let parse = db.parse(file_id);
70     let mut res = Vec::new();
71
72     // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
73     res.extend(parse.errors().iter().take(128).map(|err| Diagnostic {
74         // name: None,
75         range: err.range(),
76         message: format!("Syntax Error: {}", err),
77         severity: Severity::Error,
78         fix: None,
79     }));
80
81     for node in parse.tree().syntax().descendants() {
82         check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
83         check_struct_shorthand_initialization(&mut res, file_id, &node);
84     }
85     let res = RefCell::new(res);
86     let sink_builder = DiagnosticSinkBuilder::new()
87         .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
88             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
89         })
90         .on::<hir::diagnostics::MissingFields, _>(|d| {
91             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
92         })
93         .on::<hir::diagnostics::MissingOkInTailExpr, _>(|d| {
94             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
95         })
96         .on::<hir::diagnostics::NoSuchField, _>(|d| {
97             res.borrow_mut().push(diagnostic_with_fix(d, &sema));
98         })
99         // Only collect experimental diagnostics when they're enabled.
100         .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
101         .filter(|diag| !config.disabled.contains(diag.code().as_str()));
102
103     // Finalize the `DiagnosticSink` building process.
104     let mut sink = sink_builder
105         // Diagnostics not handled above get no fix and default treatment.
106         .build(|d| {
107             res.borrow_mut().push(Diagnostic {
108                 // name: Some(d.name().into()),
109                 message: d.message(),
110                 range: sema.diagnostics_display_range(d).range,
111                 severity: Severity::Error,
112                 fix: None,
113             })
114         });
115
116     if let Some(m) = sema.to_module_def(file_id) {
117         m.diagnostics(db, &mut sink);
118     };
119     drop(sink);
120     res.into_inner()
121 }
122
123 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
124     Diagnostic {
125         // name: Some(d.name().into()),
126         range: sema.diagnostics_display_range(d).range,
127         message: d.message(),
128         severity: Severity::Error,
129         fix: d.fix(&sema),
130     }
131 }
132
133 fn check_unnecessary_braces_in_use_statement(
134     acc: &mut Vec<Diagnostic>,
135     file_id: FileId,
136     node: &SyntaxNode,
137 ) -> Option<()> {
138     let use_tree_list = ast::UseTreeList::cast(node.clone())?;
139     if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
140         let use_range = use_tree_list.syntax().text_range();
141         let edit =
142             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
143                 .unwrap_or_else(|| {
144                     let to_replace = single_use_tree.syntax().text().to_string();
145                     let mut edit_builder = TextEdit::builder();
146                     edit_builder.delete(use_range);
147                     edit_builder.insert(use_range.start(), to_replace);
148                     edit_builder.finish()
149                 });
150
151         acc.push(Diagnostic {
152             // name: None,
153             range: use_range,
154             message: "Unnecessary braces in use statement".to_string(),
155             severity: Severity::WeakWarning,
156             fix: Some(Fix::new(
157                 "Remove unnecessary braces",
158                 SourceFileEdit { file_id, edit }.into(),
159                 use_range,
160             )),
161         });
162     }
163
164     Some(())
165 }
166
167 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
168     single_use_tree: &ast::UseTree,
169 ) -> Option<TextEdit> {
170     let use_tree_list_node = single_use_tree.syntax().parent()?;
171     if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
172         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
173         let end = use_tree_list_node.text_range().end();
174         return Some(TextEdit::delete(TextRange::new(start, end)));
175     }
176     None
177 }
178
179 fn check_struct_shorthand_initialization(
180     acc: &mut Vec<Diagnostic>,
181     file_id: FileId,
182     node: &SyntaxNode,
183 ) -> Option<()> {
184     let record_lit = ast::RecordExpr::cast(node.clone())?;
185     let record_field_list = record_lit.record_expr_field_list()?;
186     for record_field in record_field_list.fields() {
187         if let (Some(name_ref), Some(expr)) = (record_field.name_ref(), record_field.expr()) {
188             let field_name = name_ref.syntax().text().to_string();
189             let field_expr = expr.syntax().text().to_string();
190             let field_name_is_tup_index = name_ref.as_tuple_field().is_some();
191             if field_name == field_expr && !field_name_is_tup_index {
192                 let mut edit_builder = TextEdit::builder();
193                 edit_builder.delete(record_field.syntax().text_range());
194                 edit_builder.insert(record_field.syntax().text_range().start(), field_name);
195                 let edit = edit_builder.finish();
196
197                 let field_range = record_field.syntax().text_range();
198                 acc.push(Diagnostic {
199                     // name: None,
200                     range: field_range,
201                     message: "Shorthand struct initialization".to_string(),
202                     severity: Severity::WeakWarning,
203                     fix: Some(Fix::new(
204                         "Use struct shorthand initialization",
205                         SourceFileEdit { file_id, edit }.into(),
206                         field_range,
207                     )),
208                 });
209             }
210         }
211     }
212     Some(())
213 }
214
215 #[cfg(test)]
216 mod tests {
217     use expect_test::{expect, Expect};
218     use stdx::trim_indent;
219     use test_utils::assert_eq_text;
220
221     use crate::{
222         mock_analysis::{analysis_and_position, many_files, single_file},
223         DiagnosticsConfig,
224     };
225
226     /// Takes a multi-file input fixture with annotated cursor positions,
227     /// and checks that:
228     ///  * a diagnostic is produced
229     ///  * this diagnostic fix trigger range touches the input cursor position
230     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
231     fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
232         let after = trim_indent(ra_fixture_after);
233
234         let (analysis, file_position) = analysis_and_position(ra_fixture_before);
235         let diagnostic = analysis
236             .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
237             .unwrap()
238             .pop()
239             .unwrap();
240         let mut fix = diagnostic.fix.unwrap();
241         let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
242         let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
243         let actual = {
244             let mut actual = target_file_contents.to_string();
245             edit.apply(&mut actual);
246             actual
247         };
248
249         assert_eq_text!(&after, &actual);
250         assert!(
251             fix.fix_trigger_range.start() <= file_position.offset
252                 && fix.fix_trigger_range.end() >= file_position.offset,
253             "diagnostic fix range {:?} does not touch cursor position {:?}",
254             fix.fix_trigger_range,
255             file_position.offset
256         );
257     }
258
259     /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
260     /// which has a fix that can apply to other files.
261     fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
262         let ra_fixture_after = &trim_indent(ra_fixture_after);
263         let (analysis, file_pos) = analysis_and_position(ra_fixture_before);
264         let current_file_id = file_pos.file_id;
265         let diagnostic = analysis
266             .diagnostics(&DiagnosticsConfig::default(), current_file_id)
267             .unwrap()
268             .pop()
269             .unwrap();
270         let mut fix = diagnostic.fix.unwrap();
271         let edit = fix.source_change.source_file_edits.pop().unwrap();
272         let changed_file_id = edit.file_id;
273         let before = analysis.file_text(changed_file_id).unwrap();
274         let actual = {
275             let mut actual = before.to_string();
276             edit.edit.apply(&mut actual);
277             actual
278         };
279         assert_eq_text!(ra_fixture_after, &actual);
280     }
281
282     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
283     /// apply to the file containing the cursor.
284     fn check_no_diagnostics(ra_fixture: &str) {
285         let (analysis, files) = many_files(ra_fixture);
286         let diagnostics = files
287             .into_iter()
288             .flat_map(|file_id| {
289                 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
290             })
291             .collect::<Vec<_>>();
292         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
293     }
294
295     fn check_expect(ra_fixture: &str, expect: Expect) {
296         let (analysis, file_id) = single_file(ra_fixture);
297         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
298         expect.assert_debug_eq(&diagnostics)
299     }
300
301     #[test]
302     fn test_wrap_return_type() {
303         check_fix(
304             r#"
305 //- /main.rs crate:main deps:core
306 use core::result::Result::{self, Ok, Err};
307
308 fn div(x: i32, y: i32) -> Result<i32, ()> {
309     if y == 0 {
310         return Err(());
311     }
312     x / y<|>
313 }
314 //- /core/lib.rs crate:core
315 pub mod result {
316     pub enum Result<T, E> { Ok(T), Err(E) }
317 }
318 "#,
319             r#"
320 use core::result::Result::{self, Ok, Err};
321
322 fn div(x: i32, y: i32) -> Result<i32, ()> {
323     if y == 0 {
324         return Err(());
325     }
326     Ok(x / y)
327 }
328 "#,
329         );
330     }
331
332     #[test]
333     fn test_wrap_return_type_handles_generic_functions() {
334         check_fix(
335             r#"
336 //- /main.rs crate:main deps:core
337 use core::result::Result::{self, Ok, Err};
338
339 fn div<T>(x: T) -> Result<T, i32> {
340     if x == 0 {
341         return Err(7);
342     }
343     <|>x
344 }
345 //- /core/lib.rs crate:core
346 pub mod result {
347     pub enum Result<T, E> { Ok(T), Err(E) }
348 }
349 "#,
350             r#"
351 use core::result::Result::{self, Ok, Err};
352
353 fn div<T>(x: T) -> Result<T, i32> {
354     if x == 0 {
355         return Err(7);
356     }
357     Ok(x)
358 }
359 "#,
360         );
361     }
362
363     #[test]
364     fn test_wrap_return_type_handles_type_aliases() {
365         check_fix(
366             r#"
367 //- /main.rs crate:main deps:core
368 use core::result::Result::{self, Ok, Err};
369
370 type MyResult<T> = Result<T, ()>;
371
372 fn div(x: i32, y: i32) -> MyResult<i32> {
373     if y == 0 {
374         return Err(());
375     }
376     x <|>/ y
377 }
378 //- /core/lib.rs crate:core
379 pub mod result {
380     pub enum Result<T, E> { Ok(T), Err(E) }
381 }
382 "#,
383             r#"
384 use core::result::Result::{self, Ok, Err};
385
386 type MyResult<T> = Result<T, ()>;
387
388 fn div(x: i32, y: i32) -> MyResult<i32> {
389     if y == 0 {
390         return Err(());
391     }
392     Ok(x / y)
393 }
394 "#,
395         );
396     }
397
398     #[test]
399     fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
400         check_no_diagnostics(
401             r#"
402 //- /main.rs crate:main deps:core
403 use core::result::Result::{self, Ok, Err};
404
405 fn foo() -> Result<(), i32> { 0 }
406
407 //- /core/lib.rs crate:core
408 pub mod result {
409     pub enum Result<T, E> { Ok(T), Err(E) }
410 }
411 "#,
412         );
413     }
414
415     #[test]
416     fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
417         check_no_diagnostics(
418             r#"
419 //- /main.rs crate:main deps:core
420 use core::result::Result::{self, Ok, Err};
421
422 enum SomeOtherEnum { Ok(i32), Err(String) }
423
424 fn foo() -> SomeOtherEnum { 0 }
425
426 //- /core/lib.rs crate:core
427 pub mod result {
428     pub enum Result<T, E> { Ok(T), Err(E) }
429 }
430 "#,
431         );
432     }
433
434     #[test]
435     fn test_fill_struct_fields_empty() {
436         check_fix(
437             r#"
438 struct TestStruct { one: i32, two: i64 }
439
440 fn test_fn() {
441     let s = TestStruct {<|>};
442 }
443 "#,
444             r#"
445 struct TestStruct { one: i32, two: i64 }
446
447 fn test_fn() {
448     let s = TestStruct { one: (), two: ()};
449 }
450 "#,
451         );
452     }
453
454     #[test]
455     fn test_fill_struct_fields_self() {
456         check_fix(
457             r#"
458 struct TestStruct { one: i32 }
459
460 impl TestStruct {
461     fn test_fn() { let s = Self {<|>}; }
462 }
463 "#,
464             r#"
465 struct TestStruct { one: i32 }
466
467 impl TestStruct {
468     fn test_fn() { let s = Self { one: ()}; }
469 }
470 "#,
471         );
472     }
473
474     #[test]
475     fn test_fill_struct_fields_enum() {
476         check_fix(
477             r#"
478 enum Expr {
479     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
480 }
481
482 impl Expr {
483     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
484         Expr::Bin {<|> }
485     }
486 }
487 "#,
488             r#"
489 enum Expr {
490     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
491 }
492
493 impl Expr {
494     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
495         Expr::Bin { lhs: (), rhs: () }
496     }
497 }
498 "#,
499         );
500     }
501
502     #[test]
503     fn test_fill_struct_fields_partial() {
504         check_fix(
505             r#"
506 struct TestStruct { one: i32, two: i64 }
507
508 fn test_fn() {
509     let s = TestStruct{ two: 2<|> };
510 }
511 "#,
512             r"
513 struct TestStruct { one: i32, two: i64 }
514
515 fn test_fn() {
516     let s = TestStruct{ two: 2, one: () };
517 }
518 ",
519         );
520     }
521
522     #[test]
523     fn test_fill_struct_fields_no_diagnostic() {
524         check_no_diagnostics(
525             r"
526             struct TestStruct { one: i32, two: i64 }
527
528             fn test_fn() {
529                 let one = 1;
530                 let s = TestStruct{ one, two: 2 };
531             }
532         ",
533         );
534     }
535
536     #[test]
537     fn test_fill_struct_fields_no_diagnostic_on_spread() {
538         check_no_diagnostics(
539             r"
540             struct TestStruct { one: i32, two: i64 }
541
542             fn test_fn() {
543                 let one = 1;
544                 let s = TestStruct{ ..a };
545             }
546         ",
547         );
548     }
549
550     #[test]
551     fn test_unresolved_module_diagnostic() {
552         check_expect(
553             r#"mod foo;"#,
554             expect![[r#"
555                 [
556                     Diagnostic {
557                         message: "unresolved module",
558                         range: 0..8,
559                         severity: Error,
560                         fix: Some(
561                             Fix {
562                                 label: "Create module",
563                                 source_change: SourceChange {
564                                     source_file_edits: [],
565                                     file_system_edits: [
566                                         CreateFile {
567                                             anchor: FileId(
568                                                 0,
569                                             ),
570                                             dst: "foo.rs",
571                                         },
572                                     ],
573                                     is_snippet: false,
574                                 },
575                                 fix_trigger_range: 0..8,
576                             },
577                         ),
578                     },
579                 ]
580             "#]],
581         );
582     }
583
584     #[test]
585     fn range_mapping_out_of_macros() {
586         // FIXME: this is very wrong, but somewhat tricky to fix.
587         check_fix(
588             r#"
589 fn some() {}
590 fn items() {}
591 fn here() {}
592
593 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
594
595 fn main() {
596     let _x = id![Foo { a: <|>42 }];
597 }
598
599 pub struct Foo { pub a: i32, pub b: i32 }
600 "#,
601             r#"
602 fn {a:42, b: ()} {}
603 fn items() {}
604 fn here() {}
605
606 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
607
608 fn main() {
609     let _x = id![Foo { a: 42 }];
610 }
611
612 pub struct Foo { pub a: i32, pub b: i32 }
613 "#,
614         );
615     }
616
617     #[test]
618     fn test_check_unnecessary_braces_in_use_statement() {
619         check_no_diagnostics(
620             r#"
621 use a;
622 use a::{c, d::e};
623
624 mod a {
625     mod c {}
626     mod d {
627         mod e {}
628     }
629 }
630 "#,
631         );
632         check_fix(
633             r"
634             mod b {}
635             use {<|>b};
636             ",
637             r"
638             mod b {}
639             use b;
640             ",
641         );
642         check_fix(
643             r"
644             mod b {}
645             use {b<|>};
646             ",
647             r"
648             mod b {}
649             use b;
650             ",
651         );
652         check_fix(
653             r"
654             mod a { mod c {} }
655             use a::{c<|>};
656             ",
657             r"
658             mod a { mod c {} }
659             use a::c;
660             ",
661         );
662         check_fix(
663             r"
664             mod a {}
665             use a::{self<|>};
666             ",
667             r"
668             mod a {}
669             use a;
670             ",
671         );
672         check_fix(
673             r"
674             mod a { mod c {} mod d { mod e {} } }
675             use a::{c, d::{e<|>}};
676             ",
677             r"
678             mod a { mod c {} mod d { mod e {} } }
679             use a::{c, d::e};
680             ",
681         );
682     }
683
684     #[test]
685     fn test_check_struct_shorthand_initialization() {
686         check_no_diagnostics(
687             r#"
688 struct A { a: &'static str }
689 fn main() { A { a: "hello" } }
690 "#,
691         );
692         check_no_diagnostics(
693             r#"
694 struct A(usize);
695 fn main() { A { 0: 0 } }
696 "#,
697         );
698
699         check_fix(
700             r#"
701 struct A { a: &'static str }
702 fn main() {
703     let a = "haha";
704     A { a<|>: a }
705 }
706 "#,
707             r#"
708 struct A { a: &'static str }
709 fn main() {
710     let a = "haha";
711     A { a }
712 }
713 "#,
714         );
715
716         check_fix(
717             r#"
718 struct A { a: &'static str, b: &'static str }
719 fn main() {
720     let a = "haha";
721     let b = "bb";
722     A { a<|>: a, b }
723 }
724 "#,
725             r#"
726 struct A { a: &'static str, b: &'static str }
727 fn main() {
728     let a = "haha";
729     let b = "bb";
730     A { a, b }
731 }
732 "#,
733         );
734     }
735
736     #[test]
737     fn test_add_field_from_usage() {
738         check_fix(
739             r"
740 fn main() {
741     Foo { bar: 3, baz<|>: false};
742 }
743 struct Foo {
744     bar: i32
745 }
746 ",
747             r"
748 fn main() {
749     Foo { bar: 3, baz: false};
750 }
751 struct Foo {
752     bar: i32,
753     baz: bool
754 }
755 ",
756         )
757     }
758
759     #[test]
760     fn test_add_field_in_other_file_from_usage() {
761         check_apply_diagnostic_fix_in_other_file(
762             r"
763             //- /main.rs
764             mod foo;
765
766             fn main() {
767                 <|>foo::Foo { bar: 3, baz: false};
768             }
769             //- /foo.rs
770             struct Foo {
771                 bar: i32
772             }
773             ",
774             r"
775             struct Foo {
776                 bar: i32,
777                 pub(crate) baz: bool
778             }
779             ",
780         )
781     }
782
783     #[test]
784     fn test_disabled_diagnostics() {
785         let mut config = DiagnosticsConfig::default();
786         config.disabled.insert("unresolved-module".into());
787
788         let (analysis, file_id) = single_file(r#"mod foo;"#);
789
790         let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
791         assert!(diagnostics.is_empty());
792
793         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
794         assert!(!diagnostics.is_empty());
795     }
796 }