1 //! Collects diagnostics & fixits for a single file.
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.
11 use std::cell::RefCell;
15 diagnostics::{Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
18 use ide_assists::AssistResolveStrategy;
19 use ide_db::{base_db::SourceDatabase, RootDatabase};
20 use itertools::Itertools;
21 use rustc_hash::FxHashSet;
24 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
26 use text_edit::TextEdit;
27 use unlinked_file::UnlinkedFile;
29 use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
31 use self::fixes::DiagnosticWithFixes;
34 pub struct Diagnostic {
35 // pub name: Option<String>,
38 pub severity: Severity,
39 pub fixes: Option<Vec<Assist>>,
41 pub code: Option<DiagnosticCode>,
45 fn error(range: TextRange, message: String) -> Self {
46 Self { message, range, severity: Severity::Error, fixes: None, unused: false, code: None }
49 fn hint(range: TextRange, message: String) -> Self {
53 severity: Severity::WeakWarning,
60 fn with_fixes(self, fixes: Option<Vec<Assist>>) -> Self {
61 Self { fixes, ..self }
64 fn with_unused(self, unused: bool) -> Self {
65 Self { unused, ..self }
68 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
73 #[derive(Debug, Copy, Clone)]
79 #[derive(Default, Debug, Clone)]
80 pub struct DiagnosticsConfig {
81 pub disable_experimental: bool,
82 pub disabled: FxHashSet<String>,
85 pub(crate) fn diagnostics(
87 config: &DiagnosticsConfig,
88 resolve: &AssistResolveStrategy,
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();
96 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
102 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
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);
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));
114 .on::<hir::diagnostics::MissingFields, _>(|d| {
115 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
117 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
118 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
120 .on::<hir::diagnostics::NoSuchField, _>(|d| {
121 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
123 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
124 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
126 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
127 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
129 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
130 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
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() {
138 // Override severity and mark as unused.
139 res.borrow_mut().push(
141 sema.diagnostics_display_range(d.display_source()).range,
145 .with_code(Some(d.code())),
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);
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())),
161 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
162 // Use more accurate position if available.
163 let display_range = d
165 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
167 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
169 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
171 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
172 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
176 .and_then(|it| it.segment())
177 .and_then(|it| it.name_ref())
178 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
180 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
181 let display_range = sema.diagnostics_display_range(diagnostics).range;
183 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
185 .on::<hir::diagnostics::UnimplementedBuiltinMacro, _>(|d| {
186 let display_range = sema.diagnostics_display_range(d.display_source()).range;
188 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
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()));
194 // Finalize the `DiagnosticSink` building process.
195 let mut sink = sink_builder
196 // Diagnostics not handled above get no fix and default treatment.
198 res.borrow_mut().push(
200 sema.diagnostics_display_range(d.display_source()).range,
203 .with_code(Some(d.code())),
207 match sema.to_module_def(file_id) {
208 Some(m) => m.diagnostics(db, &mut sink),
210 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
218 fn diagnostic_with_fix<D: DiagnosticWithFixes>(
220 sema: &Semantics<RootDatabase>,
221 resolve: &AssistResolveStrategy,
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()))
228 fn warning_with_fix<D: DiagnosticWithFixes>(
230 sema: &Semantics<RootDatabase>,
231 resolve: &AssistResolveStrategy,
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()))
238 fn check_unnecessary_braces_in_use_statement(
239 acc: &mut Vec<Diagnostic>,
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() {
251 let use_range = use_tree_list.syntax().text_range();
253 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
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()
263 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
264 .with_fixes(Some(vec![fix(
266 "Remove unnecessary braces",
267 SourceChange::from_text_edit(file_id, edit),
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)));
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);
294 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
295 assert!(!id.contains(' '));
297 id: AssistId(id, AssistKind::QuickFix),
298 label: Label::new(label),
307 use expect_test::Expect;
308 use ide_assists::AssistResolveStrategy;
309 use stdx::trim_indent;
310 use test_utils::{assert_eq_text, extract_annotations};
312 use crate::{fixture, DiagnosticsConfig};
314 /// Takes a multi-file input fixture with annotated cursor positions,
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
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);
323 /// Takes a multi-file input fixture with annotated cursor positions,
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)
335 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
336 let after = trim_indent(ra_fixture_after);
338 let (analysis, file_position) = fixture::position(ra_fixture_before);
339 let diagnostic = analysis
341 &DiagnosticsConfig::default(),
342 AssistResolveStrategy::All,
343 file_position.file_id,
348 let fix = &diagnostic.fixes.unwrap()[nth];
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();
354 for edit in source_change.source_file_edits.values() {
355 edit.apply(&mut actual);
360 assert_eq_text!(&after, &actual);
362 fix.target.contains_inclusive(file_position.offset),
363 "diagnostic fix range {:?} does not touch cursor position {:?}",
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
373 &DiagnosticsConfig::default(),
374 AssistResolveStrategy::All,
375 file_position.file_id,
380 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
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
389 .flat_map(|file_id| {
391 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
394 .collect::<Vec<_>>();
395 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
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)
403 expect.assert_debug_eq(&diagnostics)
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)
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);
418 fn test_unresolved_macro_range() {
422 //^^^ unresolved macro `foo::bar!`
428 fn unresolved_import_in_use_tree() {
429 // Only the relevant part of a nested `use` item should be highlighted.
432 use does_exist::{Exists, DoesntExist};
433 //^^^^^^^^^^^ unresolved import
435 use {does_not_exist::*, does_exist};
436 //^^^^^^^^^^^^^^^^^ unresolved import
438 use does_not_exist::{
440 //^ unresolved import
442 //^ unresolved import
444 //^ unresolved import
455 fn range_mapping_out_of_macros() {
456 // FIXME: this is very wrong, but somewhat tricky to fix.
463 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
466 let _x = id![Foo { a: $042 }];
469 pub struct Foo { pub a: i32, pub b: i32 }
476 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
479 let _x = id![Foo { a: 42 }];
482 pub struct Foo { pub a: i32, pub b: i32 }
488 fn test_check_unnecessary_braces_in_use_statement() {
489 check_no_diagnostics(
502 check_no_diagnostics(
560 mod a { mod c {} mod d { mod e {} } }
561 use a::{c, d::{e$0}};
564 mod a { mod c {} mod d { mod e {} } }
571 fn test_disabled_diagnostics() {
572 let mut config = DiagnosticsConfig::default();
573 config.disabled.insert("unresolved-module".into());
575 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
578 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
579 assert!(diagnostics.is_empty());
581 let diagnostics = analysis
582 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
584 assert!(!diagnostics.is_empty());
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
614 fn unlinked_file_append_mod() {
615 cov_mark::check!(unlinked_file_append_to_existing_mods);
627 mod preexisting_bottom;)
641 mod preexisting_bottom;)
647 fn unlinked_file_insert_in_empty_file() {
648 cov_mark::check!(unlinked_file_empty_file);
662 fn unlinked_file_old_style_modrs() {
680 fn unlinked_file_new_style_mod() {
696 fn unlinked_file_with_cfg_off() {
697 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
711 fn unlinked_file_with_cfg_on() {
712 check_no_diagnostics(