]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
rename mock_analysis -> fixture
[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::{fixture, DiagnosticsConfig};
222
223     /// Takes a multi-file input fixture with annotated cursor positions,
224     /// and checks that:
225     ///  * a diagnostic is produced
226     ///  * this diagnostic fix trigger range touches the input cursor position
227     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
228     fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
229         let after = trim_indent(ra_fixture_after);
230
231         let (analysis, file_position) = fixture::position(ra_fixture_before);
232         let diagnostic = analysis
233             .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
234             .unwrap()
235             .pop()
236             .unwrap();
237         let mut fix = diagnostic.fix.unwrap();
238         let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
239         let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
240         let actual = {
241             let mut actual = target_file_contents.to_string();
242             edit.apply(&mut actual);
243             actual
244         };
245
246         assert_eq_text!(&after, &actual);
247         assert!(
248             fix.fix_trigger_range.start() <= file_position.offset
249                 && fix.fix_trigger_range.end() >= file_position.offset,
250             "diagnostic fix range {:?} does not touch cursor position {:?}",
251             fix.fix_trigger_range,
252             file_position.offset
253         );
254     }
255
256     /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
257     /// which has a fix that can apply to other files.
258     fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
259         let ra_fixture_after = &trim_indent(ra_fixture_after);
260         let (analysis, file_pos) = fixture::position(ra_fixture_before);
261         let current_file_id = file_pos.file_id;
262         let diagnostic = analysis
263             .diagnostics(&DiagnosticsConfig::default(), current_file_id)
264             .unwrap()
265             .pop()
266             .unwrap();
267         let mut fix = diagnostic.fix.unwrap();
268         let edit = fix.source_change.source_file_edits.pop().unwrap();
269         let changed_file_id = edit.file_id;
270         let before = analysis.file_text(changed_file_id).unwrap();
271         let actual = {
272             let mut actual = before.to_string();
273             edit.edit.apply(&mut actual);
274             actual
275         };
276         assert_eq_text!(ra_fixture_after, &actual);
277     }
278
279     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
280     /// apply to the file containing the cursor.
281     fn check_no_diagnostics(ra_fixture: &str) {
282         let (analysis, files) = fixture::files(ra_fixture);
283         let diagnostics = files
284             .into_iter()
285             .flat_map(|file_id| {
286                 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
287             })
288             .collect::<Vec<_>>();
289         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
290     }
291
292     fn check_expect(ra_fixture: &str, expect: Expect) {
293         let (analysis, file_id) = fixture::file(ra_fixture);
294         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
295         expect.assert_debug_eq(&diagnostics)
296     }
297
298     #[test]
299     fn test_wrap_return_type() {
300         check_fix(
301             r#"
302 //- /main.rs crate:main deps:core
303 use core::result::Result::{self, Ok, Err};
304
305 fn div(x: i32, y: i32) -> Result<i32, ()> {
306     if y == 0 {
307         return Err(());
308     }
309     x / y<|>
310 }
311 //- /core/lib.rs crate:core
312 pub mod result {
313     pub enum Result<T, E> { Ok(T), Err(E) }
314 }
315 "#,
316             r#"
317 use core::result::Result::{self, Ok, Err};
318
319 fn div(x: i32, y: i32) -> Result<i32, ()> {
320     if y == 0 {
321         return Err(());
322     }
323     Ok(x / y)
324 }
325 "#,
326         );
327     }
328
329     #[test]
330     fn test_wrap_return_type_handles_generic_functions() {
331         check_fix(
332             r#"
333 //- /main.rs crate:main deps:core
334 use core::result::Result::{self, Ok, Err};
335
336 fn div<T>(x: T) -> Result<T, i32> {
337     if x == 0 {
338         return Err(7);
339     }
340     <|>x
341 }
342 //- /core/lib.rs crate:core
343 pub mod result {
344     pub enum Result<T, E> { Ok(T), Err(E) }
345 }
346 "#,
347             r#"
348 use core::result::Result::{self, Ok, Err};
349
350 fn div<T>(x: T) -> Result<T, i32> {
351     if x == 0 {
352         return Err(7);
353     }
354     Ok(x)
355 }
356 "#,
357         );
358     }
359
360     #[test]
361     fn test_wrap_return_type_handles_type_aliases() {
362         check_fix(
363             r#"
364 //- /main.rs crate:main deps:core
365 use core::result::Result::{self, Ok, Err};
366
367 type MyResult<T> = Result<T, ()>;
368
369 fn div(x: i32, y: i32) -> MyResult<i32> {
370     if y == 0 {
371         return Err(());
372     }
373     x <|>/ y
374 }
375 //- /core/lib.rs crate:core
376 pub mod result {
377     pub enum Result<T, E> { Ok(T), Err(E) }
378 }
379 "#,
380             r#"
381 use core::result::Result::{self, Ok, Err};
382
383 type MyResult<T> = Result<T, ()>;
384
385 fn div(x: i32, y: i32) -> MyResult<i32> {
386     if y == 0 {
387         return Err(());
388     }
389     Ok(x / y)
390 }
391 "#,
392         );
393     }
394
395     #[test]
396     fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
397         check_no_diagnostics(
398             r#"
399 //- /main.rs crate:main deps:core
400 use core::result::Result::{self, Ok, Err};
401
402 fn foo() -> Result<(), i32> { 0 }
403
404 //- /core/lib.rs crate:core
405 pub mod result {
406     pub enum Result<T, E> { Ok(T), Err(E) }
407 }
408 "#,
409         );
410     }
411
412     #[test]
413     fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
414         check_no_diagnostics(
415             r#"
416 //- /main.rs crate:main deps:core
417 use core::result::Result::{self, Ok, Err};
418
419 enum SomeOtherEnum { Ok(i32), Err(String) }
420
421 fn foo() -> SomeOtherEnum { 0 }
422
423 //- /core/lib.rs crate:core
424 pub mod result {
425     pub enum Result<T, E> { Ok(T), Err(E) }
426 }
427 "#,
428         );
429     }
430
431     #[test]
432     fn test_fill_struct_fields_empty() {
433         check_fix(
434             r#"
435 struct TestStruct { one: i32, two: i64 }
436
437 fn test_fn() {
438     let s = TestStruct {<|>};
439 }
440 "#,
441             r#"
442 struct TestStruct { one: i32, two: i64 }
443
444 fn test_fn() {
445     let s = TestStruct { one: (), two: ()};
446 }
447 "#,
448         );
449     }
450
451     #[test]
452     fn test_fill_struct_fields_self() {
453         check_fix(
454             r#"
455 struct TestStruct { one: i32 }
456
457 impl TestStruct {
458     fn test_fn() { let s = Self {<|>}; }
459 }
460 "#,
461             r#"
462 struct TestStruct { one: i32 }
463
464 impl TestStruct {
465     fn test_fn() { let s = Self { one: ()}; }
466 }
467 "#,
468         );
469     }
470
471     #[test]
472     fn test_fill_struct_fields_enum() {
473         check_fix(
474             r#"
475 enum Expr {
476     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
477 }
478
479 impl Expr {
480     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
481         Expr::Bin {<|> }
482     }
483 }
484 "#,
485             r#"
486 enum Expr {
487     Bin { lhs: Box<Expr>, rhs: Box<Expr> }
488 }
489
490 impl Expr {
491     fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
492         Expr::Bin { lhs: (), rhs: () }
493     }
494 }
495 "#,
496         );
497     }
498
499     #[test]
500     fn test_fill_struct_fields_partial() {
501         check_fix(
502             r#"
503 struct TestStruct { one: i32, two: i64 }
504
505 fn test_fn() {
506     let s = TestStruct{ two: 2<|> };
507 }
508 "#,
509             r"
510 struct TestStruct { one: i32, two: i64 }
511
512 fn test_fn() {
513     let s = TestStruct{ two: 2, one: () };
514 }
515 ",
516         );
517     }
518
519     #[test]
520     fn test_fill_struct_fields_no_diagnostic() {
521         check_no_diagnostics(
522             r"
523             struct TestStruct { one: i32, two: i64 }
524
525             fn test_fn() {
526                 let one = 1;
527                 let s = TestStruct{ one, two: 2 };
528             }
529         ",
530         );
531     }
532
533     #[test]
534     fn test_fill_struct_fields_no_diagnostic_on_spread() {
535         check_no_diagnostics(
536             r"
537             struct TestStruct { one: i32, two: i64 }
538
539             fn test_fn() {
540                 let one = 1;
541                 let s = TestStruct{ ..a };
542             }
543         ",
544         );
545     }
546
547     #[test]
548     fn test_unresolved_module_diagnostic() {
549         check_expect(
550             r#"mod foo;"#,
551             expect![[r#"
552                 [
553                     Diagnostic {
554                         message: "unresolved module",
555                         range: 0..8,
556                         severity: Error,
557                         fix: Some(
558                             Fix {
559                                 label: "Create module",
560                                 source_change: SourceChange {
561                                     source_file_edits: [],
562                                     file_system_edits: [
563                                         CreateFile {
564                                             anchor: FileId(
565                                                 0,
566                                             ),
567                                             dst: "foo.rs",
568                                         },
569                                     ],
570                                     is_snippet: false,
571                                 },
572                                 fix_trigger_range: 0..8,
573                             },
574                         ),
575                     },
576                 ]
577             "#]],
578         );
579     }
580
581     #[test]
582     fn range_mapping_out_of_macros() {
583         // FIXME: this is very wrong, but somewhat tricky to fix.
584         check_fix(
585             r#"
586 fn some() {}
587 fn items() {}
588 fn here() {}
589
590 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
591
592 fn main() {
593     let _x = id![Foo { a: <|>42 }];
594 }
595
596 pub struct Foo { pub a: i32, pub b: i32 }
597 "#,
598             r#"
599 fn {a:42, b: ()} {}
600 fn items() {}
601 fn here() {}
602
603 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
604
605 fn main() {
606     let _x = id![Foo { a: 42 }];
607 }
608
609 pub struct Foo { pub a: i32, pub b: i32 }
610 "#,
611         );
612     }
613
614     #[test]
615     fn test_check_unnecessary_braces_in_use_statement() {
616         check_no_diagnostics(
617             r#"
618 use a;
619 use a::{c, d::e};
620
621 mod a {
622     mod c {}
623     mod d {
624         mod e {}
625     }
626 }
627 "#,
628         );
629         check_fix(
630             r"
631             mod b {}
632             use {<|>b};
633             ",
634             r"
635             mod b {}
636             use b;
637             ",
638         );
639         check_fix(
640             r"
641             mod b {}
642             use {b<|>};
643             ",
644             r"
645             mod b {}
646             use b;
647             ",
648         );
649         check_fix(
650             r"
651             mod a { mod c {} }
652             use a::{c<|>};
653             ",
654             r"
655             mod a { mod c {} }
656             use a::c;
657             ",
658         );
659         check_fix(
660             r"
661             mod a {}
662             use a::{self<|>};
663             ",
664             r"
665             mod a {}
666             use a;
667             ",
668         );
669         check_fix(
670             r"
671             mod a { mod c {} mod d { mod e {} } }
672             use a::{c, d::{e<|>}};
673             ",
674             r"
675             mod a { mod c {} mod d { mod e {} } }
676             use a::{c, d::e};
677             ",
678         );
679     }
680
681     #[test]
682     fn test_check_struct_shorthand_initialization() {
683         check_no_diagnostics(
684             r#"
685 struct A { a: &'static str }
686 fn main() { A { a: "hello" } }
687 "#,
688         );
689         check_no_diagnostics(
690             r#"
691 struct A(usize);
692 fn main() { A { 0: 0 } }
693 "#,
694         );
695
696         check_fix(
697             r#"
698 struct A { a: &'static str }
699 fn main() {
700     let a = "haha";
701     A { a<|>: a }
702 }
703 "#,
704             r#"
705 struct A { a: &'static str }
706 fn main() {
707     let a = "haha";
708     A { a }
709 }
710 "#,
711         );
712
713         check_fix(
714             r#"
715 struct A { a: &'static str, b: &'static str }
716 fn main() {
717     let a = "haha";
718     let b = "bb";
719     A { a<|>: a, b }
720 }
721 "#,
722             r#"
723 struct A { a: &'static str, b: &'static str }
724 fn main() {
725     let a = "haha";
726     let b = "bb";
727     A { a, b }
728 }
729 "#,
730         );
731     }
732
733     #[test]
734     fn test_add_field_from_usage() {
735         check_fix(
736             r"
737 fn main() {
738     Foo { bar: 3, baz<|>: false};
739 }
740 struct Foo {
741     bar: i32
742 }
743 ",
744             r"
745 fn main() {
746     Foo { bar: 3, baz: false};
747 }
748 struct Foo {
749     bar: i32,
750     baz: bool
751 }
752 ",
753         )
754     }
755
756     #[test]
757     fn test_add_field_in_other_file_from_usage() {
758         check_apply_diagnostic_fix_in_other_file(
759             r"
760             //- /main.rs
761             mod foo;
762
763             fn main() {
764                 <|>foo::Foo { bar: 3, baz: false};
765             }
766             //- /foo.rs
767             struct Foo {
768                 bar: i32
769             }
770             ",
771             r"
772             struct Foo {
773                 bar: i32,
774                 pub(crate) baz: bool
775             }
776             ",
777         )
778     }
779
780     #[test]
781     fn test_disabled_diagnostics() {
782         let mut config = DiagnosticsConfig::default();
783         config.disabled.insert("unresolved-module".into());
784
785         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
786
787         let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
788         assert!(diagnostics.is_empty());
789
790         let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
791         assert!(!diagnostics.is_empty());
792     }
793 }