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::DiagnosticWithFix;
34 pub struct Diagnostic {
35 // pub name: Option<String>,
38 pub severity: Severity,
39 pub fix: Option<Assist>,
41 pub code: Option<DiagnosticCode>,
45 fn error(range: TextRange, message: String) -> Self {
46 Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
49 fn hint(range: TextRange, message: String) -> Self {
53 severity: Severity::WeakWarning,
60 fn with_fix(self, fix: Option<Assist>) -> 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_fix(d.fix(&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 // 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()));
189 // Finalize the `DiagnosticSink` building process.
190 let mut sink = sink_builder
191 // Diagnostics not handled above get no fix and default treatment.
193 res.borrow_mut().push(
195 sema.diagnostics_display_range(d.display_source()).range,
198 .with_code(Some(d.code())),
202 match sema.to_module_def(file_id) {
203 Some(m) => m.diagnostics(db, &mut sink),
205 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
213 fn diagnostic_with_fix<D: DiagnosticWithFix>(
215 sema: &Semantics<RootDatabase>,
216 resolve: &AssistResolveStrategy,
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()))
223 fn warning_with_fix<D: DiagnosticWithFix>(
225 sema: &Semantics<RootDatabase>,
226 resolve: &AssistResolveStrategy,
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()))
233 fn check_unnecessary_braces_in_use_statement(
234 acc: &mut Vec<Diagnostic>,
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() {
246 let use_range = use_tree_list.syntax().text_range();
248 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
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()
258 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
261 "Remove unnecessary braces",
262 SourceChange::from_text_edit(file_id, edit),
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)));
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);
289 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
290 assert!(!id.contains(' '));
292 id: AssistId(id, AssistKind::QuickFix),
293 label: Label::new(label),
302 use expect_test::{expect, Expect};
303 use ide_assists::AssistResolveStrategy;
304 use stdx::trim_indent;
305 use test_utils::assert_eq_text;
307 use crate::{fixture, DiagnosticsConfig};
309 /// Takes a multi-file input fixture with annotated cursor positions,
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);
317 let (analysis, file_position) = fixture::position(ra_fixture_before);
318 let diagnostic = analysis
320 &DiagnosticsConfig::default(),
321 AssistResolveStrategy::All,
322 file_position.file_id,
327 let fix = diagnostic.fix.unwrap();
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();
333 for edit in source_change.source_file_edits.values() {
334 edit.apply(&mut actual);
339 assert_eq_text!(&after, &actual);
341 fix.target.contains_inclusive(file_position.offset),
342 "diagnostic fix range {:?} does not touch cursor position {:?}",
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
353 &DiagnosticsConfig::default(),
354 AssistResolveStrategy::All,
355 file_position.file_id,
360 assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
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
369 .flat_map(|file_id| {
371 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
374 .collect::<Vec<_>>();
375 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
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)
383 expect.assert_debug_eq(&diagnostics)
387 fn test_unresolved_macro_range() {
393 message: "unresolved macro `foo::bar!`",
400 "unresolved-macro-call",
410 fn range_mapping_out_of_macros() {
411 // FIXME: this is very wrong, but somewhat tricky to fix.
418 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
421 let _x = id![Foo { a: $042 }];
424 pub struct Foo { pub a: i32, pub b: i32 }
431 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
434 let _x = id![Foo { a: 42 }];
437 pub struct Foo { pub a: i32, pub b: i32 }
443 fn test_check_unnecessary_braces_in_use_statement() {
444 check_no_diagnostics(
457 check_no_diagnostics(
515 mod a { mod c {} mod d { mod e {} } }
516 use a::{c, d::{e$0}};
519 mod a { mod c {} mod d { mod e {} } }
526 fn test_disabled_diagnostics() {
527 let mut config = DiagnosticsConfig::default();
528 config.disabled.insert("unresolved-module".into());
530 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
533 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
534 assert!(diagnostics.is_empty());
536 let diagnostics = analysis
537 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
539 assert!(!diagnostics.is_empty());
543 fn unlinked_file_prepend_first_item() {
544 cov_mark::check!(unlinked_file_prepend_before_first_item);
561 fn unlinked_file_append_mod() {
562 cov_mark::check!(unlinked_file_append_to_existing_mods);
574 mod preexisting_bottom;)
588 mod preexisting_bottom;)
594 fn unlinked_file_insert_in_empty_file() {
595 cov_mark::check!(unlinked_file_empty_file);
609 fn unlinked_file_old_style_modrs() {
627 fn unlinked_file_new_style_mod() {
643 fn unlinked_file_with_cfg_off() {
644 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
658 fn unlinked_file_with_cfg_on() {
659 check_no_diagnostics(