]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/diagnostics.rs
Merge #8866
[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         .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
186             let display_range = sema.diagnostics_display_range(d.display_source()).range;
187             res.borrow_mut()
188                 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
189         })
190         // Only collect experimental diagnostics when they're enabled.
191         .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
192         .filter(|diag| !config.disabled.contains(diag.code().as_str()));
193
194     // Finalize the `DiagnosticSink` building process.
195     let mut sink = sink_builder
196         // Diagnostics not handled above get no fix and default treatment.
197         .build(|d| {
198             res.borrow_mut().push(
199                 Diagnostic::error(
200                     sema.diagnostics_display_range(d.display_source()).range,
201                     d.message(),
202                 )
203                 .with_code(Some(d.code())),
204             );
205         });
206
207     match sema.to_module_def(file_id) {
208         Some(m) => m.diagnostics(db, &mut sink),
209         None => {
210             sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
211         }
212     }
213
214     drop(sink);
215     res.into_inner()
216 }
217
218 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
219     d: &D,
220     sema: &Semantics<RootDatabase>,
221     resolve: &AssistResolveStrategy,
222 ) -> Diagnostic {
223     Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
224         .with_fixes(d.fixes(&sema, resolve))
225         .with_code(Some(d.code()))
226 }
227
228 fn warning_with_fix<D: DiagnosticWithFixes>(
229     d: &D,
230     sema: &Semantics<RootDatabase>,
231     resolve: &AssistResolveStrategy,
232 ) -> Diagnostic {
233     Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
234         .with_fixes(d.fixes(&sema, resolve))
235         .with_code(Some(d.code()))
236 }
237
238 fn check_unnecessary_braces_in_use_statement(
239     acc: &mut Vec<Diagnostic>,
240     file_id: FileId,
241     node: &SyntaxNode,
242 ) -> Option<()> {
243     let use_tree_list = ast::UseTreeList::cast(node.clone())?;
244     if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
245         // If there is a comment inside the bracketed `use`,
246         // assume it is a commented out module path and don't show diagnostic.
247         if use_tree_list.has_inner_comment() {
248             return Some(());
249         }
250
251         let use_range = use_tree_list.syntax().text_range();
252         let edit =
253             text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
254                 .unwrap_or_else(|| {
255                     let to_replace = single_use_tree.syntax().text().to_string();
256                     let mut edit_builder = TextEdit::builder();
257                     edit_builder.delete(use_range);
258                     edit_builder.insert(use_range.start(), to_replace);
259                     edit_builder.finish()
260                 });
261
262         acc.push(
263             Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
264                 .with_fixes(Some(vec![fix(
265                     "remove_braces",
266                     "Remove unnecessary braces",
267                     SourceChange::from_text_edit(file_id, edit),
268                     use_range,
269                 )])),
270         );
271     }
272
273     Some(())
274 }
275
276 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
277     single_use_tree: &ast::UseTree,
278 ) -> Option<TextEdit> {
279     let use_tree_list_node = single_use_tree.syntax().parent()?;
280     if single_use_tree.path()?.segment()?.self_token().is_some() {
281         let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
282         let end = use_tree_list_node.text_range().end();
283         return Some(TextEdit::delete(TextRange::new(start, end)));
284     }
285     None
286 }
287
288 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
289     let mut res = unresolved_fix(id, label, target);
290     res.source_change = Some(source_change);
291     res
292 }
293
294 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
295     assert!(!id.contains(' '));
296     Assist {
297         id: AssistId(id, AssistKind::QuickFix),
298         label: Label::new(label),
299         group: None,
300         target,
301         source_change: None,
302     }
303 }
304
305 #[cfg(test)]
306 mod tests {
307     use expect_test::Expect;
308     use ide_assists::AssistResolveStrategy;
309     use stdx::trim_indent;
310     use test_utils::{assert_eq_text, extract_annotations};
311
312     use crate::{fixture, DiagnosticsConfig};
313
314     /// Takes a multi-file input fixture with annotated cursor positions,
315     /// and checks that:
316     ///  * a diagnostic is produced
317     ///  * the first diagnostic fix trigger range touches the input cursor position
318     ///  * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
319     #[track_caller]
320     pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
321         check_nth_fix(0, ra_fixture_before, ra_fixture_after);
322     }
323     /// Takes a multi-file input fixture with annotated cursor positions,
324     /// and checks that:
325     ///  * a diagnostic is produced
326     ///  * every diagnostic fixes trigger range touches the input cursor position
327     ///  * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
328     pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
329         for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
330             check_nth_fix(i, ra_fixture_before, ra_fixture_after)
331         }
332     }
333
334     #[track_caller]
335     fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
336         let after = trim_indent(ra_fixture_after);
337
338         let (analysis, file_position) = fixture::position(ra_fixture_before);
339         let diagnostic = analysis
340             .diagnostics(
341                 &DiagnosticsConfig::default(),
342                 AssistResolveStrategy::All,
343                 file_position.file_id,
344             )
345             .unwrap()
346             .pop()
347             .unwrap();
348         let fix = &diagnostic.fixes.unwrap()[nth];
349         let actual = {
350             let source_change = fix.source_change.as_ref().unwrap();
351             let file_id = *source_change.source_file_edits.keys().next().unwrap();
352             let mut actual = analysis.file_text(file_id).unwrap().to_string();
353
354             for edit in source_change.source_file_edits.values() {
355                 edit.apply(&mut actual);
356             }
357             actual
358         };
359
360         assert_eq_text!(&after, &actual);
361         assert!(
362             fix.target.contains_inclusive(file_position.offset),
363             "diagnostic fix range {:?} does not touch cursor position {:?}",
364             fix.target,
365             file_position.offset
366         );
367     }
368     /// Checks that there's a diagnostic *without* fix at `$0`.
369     fn check_no_fix(ra_fixture: &str) {
370         let (analysis, file_position) = fixture::position(ra_fixture);
371         let diagnostic = analysis
372             .diagnostics(
373                 &DiagnosticsConfig::default(),
374                 AssistResolveStrategy::All,
375                 file_position.file_id,
376             )
377             .unwrap()
378             .pop()
379             .unwrap();
380         assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
381     }
382
383     /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
384     /// apply to the file containing the cursor.
385     pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
386         let (analysis, files) = fixture::files(ra_fixture);
387         let diagnostics = files
388             .into_iter()
389             .flat_map(|file_id| {
390                 analysis
391                     .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
392                     .unwrap()
393             })
394             .collect::<Vec<_>>();
395         assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
396     }
397
398     pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
399         let (analysis, file_id) = fixture::file(ra_fixture);
400         let diagnostics = analysis
401             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
402             .unwrap();
403         expect.assert_debug_eq(&diagnostics)
404     }
405
406     pub(crate) fn check_diagnostics(ra_fixture: &str) {
407         let (analysis, file_id) = fixture::file(ra_fixture);
408         let diagnostics = analysis
409             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
410             .unwrap();
411
412         let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
413         let actual = diagnostics.into_iter().map(|d| (d.range, d.message)).collect::<Vec<_>>();
414         assert_eq!(expected, actual);
415     }
416
417     #[test]
418     fn test_unresolved_macro_range() {
419         check_diagnostics(
420             r#"
421 foo::bar!(92);
422    //^^^ unresolved macro `foo::bar!`
423 "#,
424         );
425     }
426
427     #[test]
428     fn unresolved_import_in_use_tree() {
429         // Only the relevant part of a nested `use` item should be highlighted.
430         check_diagnostics(
431             r#"
432 use does_exist::{Exists, DoesntExist};
433                        //^^^^^^^^^^^ unresolved import
434
435 use {does_not_exist::*, does_exist};
436    //^^^^^^^^^^^^^^^^^ unresolved import
437
438 use does_not_exist::{
439     a,
440   //^ unresolved import
441     b,
442   //^ unresolved import
443     c,
444   //^ unresolved import
445 };
446
447 mod does_exist {
448     pub struct Exists;
449 }
450 "#,
451         );
452     }
453
454     #[test]
455     fn range_mapping_out_of_macros() {
456         // FIXME: this is very wrong, but somewhat tricky to fix.
457         check_fix(
458             r#"
459 fn some() {}
460 fn items() {}
461 fn here() {}
462
463 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
464
465 fn main() {
466     let _x = id![Foo { a: $042 }];
467 }
468
469 pub struct Foo { pub a: i32, pub b: i32 }
470 "#,
471             r#"
472 fn some(, b: () ) {}
473 fn items() {}
474 fn here() {}
475
476 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
477
478 fn main() {
479     let _x = id![Foo { a: 42 }];
480 }
481
482 pub struct Foo { pub a: i32, pub b: i32 }
483 "#,
484         );
485     }
486
487     #[test]
488     fn test_check_unnecessary_braces_in_use_statement() {
489         check_no_diagnostics(
490             r#"
491 use a;
492 use a::{c, d::e};
493
494 mod a {
495     mod c {}
496     mod d {
497         mod e {}
498     }
499 }
500 "#,
501         );
502         check_no_diagnostics(
503             r#"
504 use a;
505 use a::{
506     c,
507     // d::e
508 };
509
510 mod a {
511     mod c {}
512     mod d {
513         mod e {}
514     }
515 }
516 "#,
517         );
518         check_fix(
519             r"
520             mod b {}
521             use {$0b};
522             ",
523             r"
524             mod b {}
525             use b;
526             ",
527         );
528         check_fix(
529             r"
530             mod b {}
531             use {b$0};
532             ",
533             r"
534             mod b {}
535             use b;
536             ",
537         );
538         check_fix(
539             r"
540             mod a { mod c {} }
541             use a::{c$0};
542             ",
543             r"
544             mod a { mod c {} }
545             use a::c;
546             ",
547         );
548         check_fix(
549             r"
550             mod a {}
551             use a::{self$0};
552             ",
553             r"
554             mod a {}
555             use a;
556             ",
557         );
558         check_fix(
559             r"
560             mod a { mod c {} mod d { mod e {} } }
561             use a::{c, d::{e$0}};
562             ",
563             r"
564             mod a { mod c {} mod d { mod e {} } }
565             use a::{c, d::e};
566             ",
567         );
568     }
569
570     #[test]
571     fn test_disabled_diagnostics() {
572         let mut config = DiagnosticsConfig::default();
573         config.disabled.insert("unresolved-module".into());
574
575         let (analysis, file_id) = fixture::file(r#"mod foo;"#);
576
577         let diagnostics =
578             analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
579         assert!(diagnostics.is_empty());
580
581         let diagnostics = analysis
582             .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
583             .unwrap();
584         assert!(!diagnostics.is_empty());
585     }
586
587     #[test]
588     fn unlinked_file_prepend_first_item() {
589         cov_mark::check!(unlinked_file_prepend_before_first_item);
590         // Only tests the first one for `pub mod` since the rest are the same
591         check_fixes(
592             r#"
593 //- /main.rs
594 fn f() {}
595 //- /foo.rs
596 $0
597 "#,
598             vec![
599                 r#"
600 mod foo;
601
602 fn f() {}
603 "#,
604                 r#"
605 pub mod foo;
606
607 fn f() {}
608 "#,
609             ],
610         );
611     }
612
613     #[test]
614     fn unlinked_file_append_mod() {
615         cov_mark::check!(unlinked_file_append_to_existing_mods);
616         check_fix(
617             r#"
618 //- /main.rs
619 //! Comment on top
620
621 mod preexisting;
622
623 mod preexisting2;
624
625 struct S;
626
627 mod preexisting_bottom;)
628 //- /foo.rs
629 $0
630 "#,
631             r#"
632 //! Comment on top
633
634 mod preexisting;
635
636 mod preexisting2;
637 mod foo;
638
639 struct S;
640
641 mod preexisting_bottom;)
642 "#,
643         );
644     }
645
646     #[test]
647     fn unlinked_file_insert_in_empty_file() {
648         cov_mark::check!(unlinked_file_empty_file);
649         check_fix(
650             r#"
651 //- /main.rs
652 //- /foo.rs
653 $0
654 "#,
655             r#"
656 mod foo;
657 "#,
658         );
659     }
660
661     #[test]
662     fn unlinked_file_old_style_modrs() {
663         check_fix(
664             r#"
665 //- /main.rs
666 mod submod;
667 //- /submod/mod.rs
668 // in mod.rs
669 //- /submod/foo.rs
670 $0
671 "#,
672             r#"
673 // in mod.rs
674 mod foo;
675 "#,
676         );
677     }
678
679     #[test]
680     fn unlinked_file_new_style_mod() {
681         check_fix(
682             r#"
683 //- /main.rs
684 mod submod;
685 //- /submod.rs
686 //- /submod/foo.rs
687 $0
688 "#,
689             r#"
690 mod foo;
691 "#,
692         );
693     }
694
695     #[test]
696     fn unlinked_file_with_cfg_off() {
697         cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
698         check_no_fix(
699             r#"
700 //- /main.rs
701 #[cfg(never)]
702 mod foo;
703
704 //- /foo.rs
705 $0
706 "#,
707         );
708     }
709
710     #[test]
711     fn unlinked_file_with_cfg_on() {
712         check_no_diagnostics(
713             r#"
714 //- /main.rs
715 #[cfg(not(never))]
716 mod foo;
717
718 //- /foo.rs
719 "#,
720         );
721     }
722 }