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