]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Merge #8871
[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::DiagnosticWithFixes;
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 fixes: Option<Vec<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, fixes: 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             fixes: None,
55             unused: false,
56             code: None,
57         }
58     }
59
60     fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
61         Self { fixes, ..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_fixes(d.fixes(&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: DiagnosticWithFixes>(
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_fixes(d.fixes(&sema, resolve))
220         .with_code(Some(d.code()))
221 }
222
223 fn warning_with_fix<D: DiagnosticWithFixes>(
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_fixes(d.fixes(&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_fixes(Some(vec![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     ///  * the first 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         check_nth_fix(0, ra_fixture_before, ra_fixture_after);
316     }
317     /// Takes a multi-file input fixture with annotated cursor positions,
318     /// and checks that:
319     ///  * a diagnostic is produced
320     ///  * every diagnostic fixes trigger range touches the input cursor position
321     ///  * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
322     pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
323         for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
324             check_nth_fix(i, ra_fixture_before, ra_fixture_after)
325         }
326     }
327
328     fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
329         let after = trim_indent(ra_fixture_after);
330
331         let (analysis, file_position) = fixture::position(ra_fixture_before);
332         let diagnostic = analysis
333             .diagnostics(
334                 &DiagnosticsConfig::default(),
335                 AssistResolveStrategy::All,
336                 file_position.file_id,
337             )
338             .unwrap()
339             .pop()
340             .unwrap();
341         let fix = &diagnostic.fixes.unwrap()[nth];
342         let actual = {
343             let source_change = fix.source_change.as_ref().unwrap();
344             let file_id = *source_change.source_file_edits.keys().next().unwrap();
345             let mut actual = analysis.file_text(file_id).unwrap().to_string();
346
347             for edit in source_change.source_file_edits.values() {
348                 edit.apply(&mut actual);
349             }
350             actual
351         };
352
353         assert_eq_text!(&after, &actual);
354         assert!(
355             fix.target.contains_inclusive(file_position.offset),
356             "diagnostic fix range {:?} does not touch cursor position {:?}",
357             fix.target,
358             file_position.offset
359         );
360     }
361     /// Checks that there's a diagnostic *without* fix at `$0`.
362     fn check_no_fix(ra_fixture: &str) {
363         let (analysis, file_position) = fixture::position(ra_fixture);
364         let diagnostic = analysis
365             .diagnostics(
366                 &DiagnosticsConfig::default(),
367                 AssistResolveStrategy::All,
368                 file_position.file_id,
369             )
370             .unwrap()
371             .pop()
372             .unwrap();
373         assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
374     }
375
376     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
377     /// apply to the file containing the cursor.
378     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
379         let (analysis, files) = fixture::files(ra_fixture);
380         let diagnostics = files
381             .into_iter()
382             .flat_map(|file_id| {
383                 analysis
384                     .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
385                     .unwrap()
386             })
387             .collect::<Vec<_>>();
388         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
389     }
390
391     pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
392         let (analysis, file_id) = fixture::file(ra_fixture);
393         let diagnostics = analysis
394             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
395             .unwrap();
396         expect.assert_debug_eq(&diagnostics)
397     }
398
399     #[test]
400     fn test_unresolved_macro_range() {
401         check_expect(
402             r#"foo::bar!(92);"#,
403             expect![[r#"
404                 [
405                     Diagnostic {
406                         message: "unresolved macro `foo::bar!`",
407                         range: 5..8,
408                         severity: Error,
409                         fixes: None,
410                         unused: false,
411                         code: Some(
412                             DiagnosticCode(
413                                 "unresolved-macro-call",
414                             ),
415                         ),
416                     },
417                 ]
418             "#]],
419         );
420     }
421
422     #[test]
423     fn range_mapping_out_of_macros() {
424         // FIXME: this is very wrong, but somewhat tricky to fix.
425         check_fix(
426             r#"
427 fn some() {}
428 fn items() {}
429 fn here() {}
430
431 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
432
433 fn main() {
434     let _x = id![Foo { a: $042 }];
435 }
436
437 pub struct Foo { pub a: i32, pub b: i32 }
438 "#,
439             r#"
440 fn some(, b: () ) {}
441 fn items() {}
442 fn here() {}
443
444 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
445
446 fn main() {
447     let _x = id![Foo { a: 42 }];
448 }
449
450 pub struct Foo { pub a: i32, pub b: i32 }
451 "#,
452         );
453     }
454
455     #[test]
456     fn test_check_unnecessary_braces_in_use_statement() {
457         check_no_diagnostics(
458             r#"
459 use a;
460 use a::{c, d::e};
461
462 mod a {
463     mod c {}
464     mod d {
465         mod e {}
466     }
467 }
468 "#,
469         );
470         check_no_diagnostics(
471             r#"
472 use a;
473 use a::{
474     c,
475     // d::e
476 };
477
478 mod a {
479     mod c {}
480     mod d {
481         mod e {}
482     }
483 }
484 "#,
485         );
486         check_fix(
487             r"
488             mod b {}
489             use {$0b};
490             ",
491             r"
492             mod b {}
493             use b;
494             ",
495         );
496         check_fix(
497             r"
498             mod b {}
499             use {b$0};
500             ",
501             r"
502             mod b {}
503             use b;
504             ",
505         );
506         check_fix(
507             r"
508             mod a { mod c {} }
509             use a::{c$0};
510             ",
511             r"
512             mod a { mod c {} }
513             use a::c;
514             ",
515         );
516         check_fix(
517             r"
518             mod a {}
519             use a::{self$0};
520             ",
521             r"
522             mod a {}
523             use a;
524             ",
525         );
526         check_fix(
527             r"
528             mod a { mod c {} mod d { mod e {} } }
529             use a::{c, d::{e$0}};
530             ",
531             r"
532             mod a { mod c {} mod d { mod e {} } }
533             use a::{c, d::e};
534             ",
535         );
536     }
537
538     #[test]
539     fn test_disabled_diagnostics() {
540         let mut config = DiagnosticsConfig::default();
541         config.disabled.insert("unresolved-module".into());
542
543         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
544
545         let diagnostics =
546             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
547         assert!(diagnostics.is_empty());
548
549         let diagnostics = analysis
550             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
551             .unwrap();
552         assert!(!diagnostics.is_empty());
553     }
554
555     #[test]
556     fn unlinked_file_prepend_first_item() {
557         cov_mark::check!(unlinked_file_prepend_before_first_item);
558         // Only tests the first one for `pub mod` since the rest are the same
559         check_fixes(
560             r#"
561 //- /main.rs
562 fn f() {}
563 //- /foo.rs
564 $0
565 "#,
566             vec![
567                 r#"
568 mod foo;
569
570 fn f() {}
571 "#,
572                 r#"
573 pub mod foo;
574
575 fn f() {}
576 "#,
577             ],
578         );
579     }
580
581     #[test]
582     fn unlinked_file_append_mod() {
583         cov_mark::check!(unlinked_file_append_to_existing_mods);
584         check_fix(
585             r#"
586 //- /main.rs
587 //! Comment on top
588
589 mod preexisting;
590
591 mod preexisting2;
592
593 struct S;
594
595 mod preexisting_bottom;)
596 //- /foo.rs
597 $0
598 "#,
599             r#"
600 //! Comment on top
601
602 mod preexisting;
603
604 mod preexisting2;
605 mod foo;
606
607 struct S;
608
609 mod preexisting_bottom;)
610 "#,
611         );
612     }
613
614     #[test]
615     fn unlinked_file_insert_in_empty_file() {
616         cov_mark::check!(unlinked_file_empty_file);
617         check_fix(
618             r#"
619 //- /main.rs
620 //- /foo.rs
621 $0
622 "#,
623             r#"
624 mod foo;
625 "#,
626         );
627     }
628
629     #[test]
630     fn unlinked_file_old_style_modrs() {
631         check_fix(
632             r#"
633 //- /main.rs
634 mod submod;
635 //- /submod/mod.rs
636 // in mod.rs
637 //- /submod/foo.rs
638 $0
639 "#,
640             r#"
641 // in mod.rs
642 mod foo;
643 "#,
644         );
645     }
646
647     #[test]
648     fn unlinked_file_new_style_mod() {
649         check_fix(
650             r#"
651 //- /main.rs
652 mod submod;
653 //- /submod.rs
654 //- /submod/foo.rs
655 $0
656 "#,
657             r#"
658 mod foo;
659 "#,
660         );
661     }
662
663     #[test]
664     fn unlinked_file_with_cfg_off() {
665         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
666         check_no_fix(
667             r#"
668 //- /main.rs
669 #[cfg(never)]
670 mod foo;
671
672 //- /foo.rs
673 $0
674 "#,
675         );
676     }
677
678     #[test]
679     fn unlinked_file_with_cfg_on() {
680         check_no_diagnostics(
681             r#"
682 //- /main.rs
683 #[cfg(not(never))]
684 mod foo;
685
686 //- /foo.rs
687 "#,
688         );
689     }
690 }