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 hir::diagnostics::DiagnosticCode;
309 use ide_assists::AssistResolveStrategy;
310 use stdx::trim_indent;
311 use test_utils::{assert_eq_text, extract_annotations};
313 use crate::{fixture, DiagnosticsConfig};
315 /// Takes a multi-file input fixture with annotated cursor positions,
317 /// * a diagnostic is produced
318 /// * the first diagnostic fix trigger range touches the input cursor position
319 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
321 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
322 check_nth_fix(0, ra_fixture_before, ra_fixture_after);
324 /// Takes a multi-file input fixture with annotated cursor positions,
326 /// * a diagnostic is produced
327 /// * every diagnostic fixes trigger range touches the input cursor position
328 /// * that the contents of the file containing the cursor match `after` after each diagnostic fix is applied
329 pub(crate) fn check_fixes(ra_fixture_before: &str, ra_fixtures_after: Vec<&str>) {
330 for (i, ra_fixture_after) in ra_fixtures_after.iter().enumerate() {
331 check_nth_fix(i, ra_fixture_before, ra_fixture_after)
336 fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
337 let after = trim_indent(ra_fixture_after);
339 let (analysis, file_position) = fixture::position(ra_fixture_before);
340 let diagnostic = analysis
342 &DiagnosticsConfig::default(),
343 AssistResolveStrategy::All,
344 file_position.file_id,
349 let fix = &diagnostic.fixes.unwrap()[nth];
351 let source_change = fix.source_change.as_ref().unwrap();
352 let file_id = *source_change.source_file_edits.keys().next().unwrap();
353 let mut actual = analysis.file_text(file_id).unwrap().to_string();
355 for edit in source_change.source_file_edits.values() {
356 edit.apply(&mut actual);
361 assert_eq_text!(&after, &actual);
363 fix.target.contains_inclusive(file_position.offset),
364 "diagnostic fix range {:?} does not touch cursor position {:?}",
369 /// Checks that there's a diagnostic *without* fix at `$0`.
370 fn check_no_fix(ra_fixture: &str) {
371 let (analysis, file_position) = fixture::position(ra_fixture);
372 let diagnostic = analysis
374 &DiagnosticsConfig::default(),
375 AssistResolveStrategy::All,
376 file_position.file_id,
381 assert!(diagnostic.fixes.is_none(), "got a fix when none was expected: {:?}", diagnostic);
384 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
385 /// apply to the file containing the cursor.
386 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
387 let (analysis, files) = fixture::files(ra_fixture);
388 let diagnostics = files
390 .flat_map(|file_id| {
392 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
395 .collect::<Vec<_>>();
396 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
399 pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
400 let (analysis, file_id) = fixture::file(ra_fixture);
401 let diagnostics = analysis
402 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
404 expect.assert_debug_eq(&diagnostics)
407 pub(crate) fn check_diagnostics(ra_fixture: &str) {
408 let (analysis, file_id) = fixture::file(ra_fixture);
409 let diagnostics = analysis
410 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
413 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
414 let mut actual = diagnostics
416 .filter(|d| d.code != Some(DiagnosticCode("inactive-code")))
417 .map(|d| (d.range, d.message))
418 .collect::<Vec<_>>();
419 actual.sort_by_key(|(range, _)| range.start());
420 assert_eq!(expected, actual);
424 fn test_unresolved_macro_range() {
428 //^^^ unresolved macro `foo::bar!`
434 fn unresolved_import_in_use_tree() {
435 // Only the relevant part of a nested `use` item should be highlighted.
438 use does_exist::{Exists, DoesntExist};
439 //^^^^^^^^^^^ unresolved import
441 use {does_not_exist::*, does_exist};
442 //^^^^^^^^^^^^^^^^^ unresolved import
444 use does_not_exist::{
446 //^ unresolved import
448 //^ unresolved import
450 //^ unresolved import
461 fn range_mapping_out_of_macros() {
462 // FIXME: this is very wrong, but somewhat tricky to fix.
469 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
472 let _x = id![Foo { a: $042 }];
475 pub struct Foo { pub a: i32, pub b: i32 }
482 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
485 let _x = id![Foo { a: 42 }];
488 pub struct Foo { pub a: i32, pub b: i32 }
494 fn test_check_unnecessary_braces_in_use_statement() {
495 check_no_diagnostics(
508 check_no_diagnostics(
566 mod a { mod c {} mod d { mod e {} } }
567 use a::{c, d::{e$0}};
570 mod a { mod c {} mod d { mod e {} } }
577 fn test_disabled_diagnostics() {
578 let mut config = DiagnosticsConfig::default();
579 config.disabled.insert("unresolved-module".into());
581 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
584 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
585 assert!(diagnostics.is_empty());
587 let diagnostics = analysis
588 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
590 assert!(!diagnostics.is_empty());
594 fn unlinked_file_prepend_first_item() {
595 cov_mark::check!(unlinked_file_prepend_before_first_item);
596 // Only tests the first one for `pub mod` since the rest are the same
620 fn unlinked_file_append_mod() {
621 cov_mark::check!(unlinked_file_append_to_existing_mods);
633 mod preexisting_bottom;)
647 mod preexisting_bottom;)
653 fn unlinked_file_insert_in_empty_file() {
654 cov_mark::check!(unlinked_file_empty_file);
668 fn unlinked_file_old_style_modrs() {
686 fn unlinked_file_new_style_mod() {
702 fn unlinked_file_with_cfg_off() {
703 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
717 fn unlinked_file_with_cfg_on() {
718 check_no_diagnostics(
730 fn break_outside_of_loop() {
734 //^^^^^ break outside of loop
740 fn no_such_field_diagnostics() {
743 struct S { foo: i32, bar: () }
747 //^ Missing structure fields:
751 //^^^^^^^ no such field
759 fn no_such_field_with_feature_flag_diagnostics() {
762 //- /lib.rs crate:foo cfg:feature=foo
765 #[cfg(feature = "foo")]
770 #[cfg(feature = "foo")]
771 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
774 #[cfg(not(feature = "foo"))]
775 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
784 fn no_such_field_enum_with_feature_flag_diagnostics() {
787 //- /lib.rs crate:foo cfg:feature=foo
789 #[cfg(not(feature = "foo"))]
791 #[cfg(feature = "foo")]
807 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
810 //- /lib.rs crate:foo cfg:feature=foo
812 #[cfg(feature = "foo")]
814 #[cfg(not(feature = "foo"))]
819 #[cfg(feature = "foo")]
820 fn new(foo: u32) -> Self {
823 #[cfg(not(feature = "foo"))]
824 fn new(bar: u32) -> Self {
827 fn new2(bar: u32) -> Self {
828 #[cfg(feature = "foo")]
829 { Self { foo: bar } }
830 #[cfg(not(feature = "foo"))]
833 fn new2(val: u32) -> Self {
835 #[cfg(feature = "foo")]
837 #[cfg(not(feature = "foo"))]
847 fn no_such_field_with_type_macro() {
850 macro_rules! Type { () => { u32 }; }
851 struct Foo { bar: Type![] }
863 fn missing_unsafe_diagnostic_with_raw_ptr() {
867 let x = &5 as *const usize;
868 unsafe { let y = *x; }
870 } //^^ This operation is unsafe and requires an unsafe function or block
876 fn missing_unsafe_diagnostic_with_unsafe_call() {
882 unsafe fn unsafe_fn(&self) {
883 let x = &5 as *const usize;
888 unsafe fn unsafe_fn() {
889 let x = &5 as *const usize;
895 //^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
896 HasUnsafe.unsafe_fn();
897 //^^^^^^^^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
900 HasUnsafe.unsafe_fn();
908 fn missing_unsafe_diagnostic_with_static_mut() {
915 static mut STATIC_MUT: Ty = Ty { a: 0 };
918 let x = STATIC_MUT.a;
919 //^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block
921 let x = STATIC_MUT.a;
929 fn no_missing_unsafe_diagnostic_with_safe_intrinsic() {
932 extern "rust-intrinsic" {
933 pub fn bitreverse(x: u32) -> u32; // Safe intrinsic
934 pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic
938 let _ = bitreverse(12);
939 let _ = floorf32(12.0);
940 //^^^^^^^^^^^^^^ This operation is unsafe and requires an unsafe function or block