]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Merge #9003
[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;
303     use ide_assists::AssistResolveStrategy;
304     use stdx::trim_indent;
305     use test_utils::{assert_eq_text, extract_annotations};
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     pub(crate) fn check_diagnostics(ra_fixture: &str) {
400         let (analysis, file_id) = fixture::file(ra_fixture);
401         let diagnostics = analysis
402             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
403             .unwrap();
404
405         let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
406         let actual = diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
407         assert_eq!(expected, actual);
408     }
409
410     #[test]
411     fn test_unresolved_macro_range() {
412         check_diagnostics(
413             r#"
414 foo::bar!(92);
415    //^^^ unresolved macro `foo::bar!`
416 "#,
417         );
418     }
419
420     #[test]
421     fn unresolved_import_in_use_tree() {
422         // Only the relevant part of a nested `use` item should be highlighted.
423         check_diagnostics(
424             r#"
425 use does_exist::{Exists, DoesntExist};
426                        //^^^^^^^^^^^ unresolved import
427
428 use {does_not_exist::*, does_exist};
429    //^^^^^^^^^^^^^^^^^ unresolved import
430
431 use does_not_exist::{
432     a,
433   //^ unresolved import
434     b,
435   //^ unresolved import
436     c,
437   //^ unresolved import
438 };
439
440 mod does_exist {
441     pub struct Exists;
442 }
443 "#,
444         );
445     }
446
447     #[test]
448     fn range_mapping_out_of_macros() {
449         // FIXME: this is very wrong, but somewhat tricky to fix.
450         check_fix(
451             r#"
452 fn some() {}
453 fn items() {}
454 fn here() {}
455
456 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
457
458 fn main() {
459     let _x = id![Foo { a: $042 }];
460 }
461
462 pub struct Foo { pub a: i32, pub b: i32 }
463 "#,
464             r#"
465 fn some(, b: () ) {}
466 fn items() {}
467 fn here() {}
468
469 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
470
471 fn main() {
472     let _x = id![Foo { a: 42 }];
473 }
474
475 pub struct Foo { pub a: i32, pub b: i32 }
476 "#,
477         );
478     }
479
480     #[test]
481     fn test_check_unnecessary_braces_in_use_statement() {
482         check_no_diagnostics(
483             r#"
484 use a;
485 use a::{c, d::e};
486
487 mod a {
488     mod c {}
489     mod d {
490         mod e {}
491     }
492 }
493 "#,
494         );
495         check_no_diagnostics(
496             r#"
497 use a;
498 use a::{
499     c,
500     // d::e
501 };
502
503 mod a {
504     mod c {}
505     mod d {
506         mod e {}
507     }
508 }
509 "#,
510         );
511         check_fix(
512             r"
513             mod b {}
514             use {$0b};
515             ",
516             r"
517             mod b {}
518             use b;
519             ",
520         );
521         check_fix(
522             r"
523             mod b {}
524             use {b$0};
525             ",
526             r"
527             mod b {}
528             use b;
529             ",
530         );
531         check_fix(
532             r"
533             mod a { mod c {} }
534             use a::{c$0};
535             ",
536             r"
537             mod a { mod c {} }
538             use a::c;
539             ",
540         );
541         check_fix(
542             r"
543             mod a {}
544             use a::{self$0};
545             ",
546             r"
547             mod a {}
548             use a;
549             ",
550         );
551         check_fix(
552             r"
553             mod a { mod c {} mod d { mod e {} } }
554             use a::{c, d::{e$0}};
555             ",
556             r"
557             mod a { mod c {} mod d { mod e {} } }
558             use a::{c, d::e};
559             ",
560         );
561     }
562
563     #[test]
564     fn test_disabled_diagnostics() {
565         let mut config = DiagnosticsConfig::default();
566         config.disabled.insert("unresolved-module".into());
567
568         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
569
570         let diagnostics =
571             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
572         assert!(diagnostics.is_empty());
573
574         let diagnostics = analysis
575             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
576             .unwrap();
577         assert!(!diagnostics.is_empty());
578     }
579
580     #[test]
581     fn unlinked_file_prepend_first_item() {
582         cov_mark::check!(unlinked_file_prepend_before_first_item);
583         // Only tests the first one for `pub mod` since the rest are the same
584         check_fixes(
585             r#"
586 //- /main.rs
587 fn f() {}
588 //- /foo.rs
589 $0
590 "#,
591             vec![
592                 r#"
593 mod foo;
594
595 fn f() {}
596 "#,
597                 r#"
598 pub mod foo;
599
600 fn f() {}
601 "#,
602             ],
603         );
604     }
605
606     #[test]
607     fn unlinked_file_append_mod() {
608         cov_mark::check!(unlinked_file_append_to_existing_mods);
609         check_fix(
610             r#"
611 //- /main.rs
612 //! Comment on top
613
614 mod preexisting;
615
616 mod preexisting2;
617
618 struct S;
619
620 mod preexisting_bottom;)
621 //- /foo.rs
622 $0
623 "#,
624             r#"
625 //! Comment on top
626
627 mod preexisting;
628
629 mod preexisting2;
630 mod foo;
631
632 struct S;
633
634 mod preexisting_bottom;)
635 "#,
636         );
637     }
638
639     #[test]
640     fn unlinked_file_insert_in_empty_file() {
641         cov_mark::check!(unlinked_file_empty_file);
642         check_fix(
643             r#"
644 //- /main.rs
645 //- /foo.rs
646 $0
647 "#,
648             r#"
649 mod foo;
650 "#,
651         );
652     }
653
654     #[test]
655     fn unlinked_file_old_style_modrs() {
656         check_fix(
657             r#"
658 //- /main.rs
659 mod submod;
660 //- /submod/mod.rs
661 // in mod.rs
662 //- /submod/foo.rs
663 $0
664 "#,
665             r#"
666 // in mod.rs
667 mod foo;
668 "#,
669         );
670     }
671
672     #[test]
673     fn unlinked_file_new_style_mod() {
674         check_fix(
675             r#"
676 //- /main.rs
677 mod submod;
678 //- /submod.rs
679 //- /submod/foo.rs
680 $0
681 "#,
682             r#"
683 mod foo;
684 "#,
685         );
686     }
687
688     #[test]
689     fn unlinked_file_with_cfg_off() {
690         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
691         check_no_fix(
692             r#"
693 //- /main.rs
694 #[cfg(never)]
695 mod foo;
696
697 //- /foo.rs
698 $0
699 "#,
700         );
701     }
702
703     #[test]
704     fn unlinked_file_with_cfg_on() {
705         check_no_diagnostics(
706             r#"
707 //- /main.rs
708 #[cfg(not(never))]
709 mod foo;
710
711 //- /foo.rs
712 "#,
713         );
714     }
715 }