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