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_db::{base_db::SourceDatabase, RootDatabase};
19 use itertools::Itertools;
20 use rustc_hash::FxHashSet;
23 SyntaxNode, SyntaxNodePtr, TextRange, TextSize,
25 use text_edit::TextEdit;
26 use unlinked_file::UnlinkedFile;
28 use crate::{FileId, Label, SourceChange};
30 use self::fixes::DiagnosticWithFix;
33 pub struct Diagnostic {
34 // pub name: Option<String>,
37 pub severity: Severity,
40 pub code: Option<DiagnosticCode>,
44 fn error(range: TextRange, message: String) -> Self {
45 Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
48 fn hint(range: TextRange, message: String) -> Self {
52 severity: Severity::WeakWarning,
59 fn with_fix(self, fix: Option<Fix>) -> Self {
63 fn with_unused(self, unused: bool) -> Self {
64 Self { unused, ..self }
67 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
75 pub source_change: SourceChange,
76 /// Allows to trigger the fix only when the caret is in the range given
77 pub fix_trigger_range: TextRange,
81 fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
82 let label = Label::new(label);
83 Self { label, source_change, fix_trigger_range }
87 #[derive(Debug, Copy, Clone)]
93 #[derive(Default, Debug, Clone)]
94 pub struct DiagnosticsConfig {
95 pub disable_experimental: bool,
96 pub disabled: FxHashSet<String>,
99 pub(crate) fn diagnostics(
101 config: &DiagnosticsConfig,
103 ) -> Vec<Diagnostic> {
104 let _p = profile::span("diagnostics");
105 let sema = Semantics::new(db);
106 let parse = db.parse(file_id);
107 let mut res = Vec::new();
109 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
115 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
118 for node in parse.tree().syntax().descendants() {
119 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
120 field_shorthand::check(&mut res, file_id, &node);
122 let res = RefCell::new(res);
123 let sink_builder = DiagnosticSinkBuilder::new()
124 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
125 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
127 .on::<hir::diagnostics::MissingFields, _>(|d| {
128 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
130 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
131 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
133 .on::<hir::diagnostics::NoSuchField, _>(|d| {
134 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
136 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
137 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
139 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
140 res.borrow_mut().push(warning_with_fix(d, &sema));
142 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
143 res.borrow_mut().push(warning_with_fix(d, &sema));
145 .on::<hir::diagnostics::InactiveCode, _>(|d| {
146 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
147 if d.display_source().file_id.expansion_info(db).is_some() {
151 // Override severity and mark as unused.
152 res.borrow_mut().push(
154 sema.diagnostics_display_range(d.display_source()).range,
158 .with_code(Some(d.code())),
161 .on::<UnlinkedFile, _>(|d| {
162 // Limit diagnostic to the first few characters in the file. This matches how VS Code
163 // renders it with the full span, but on other editors, and is less invasive.
164 let range = sema.diagnostics_display_range(d.display_source()).range;
165 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
167 // Override severity and mark as unused.
168 res.borrow_mut().push(
169 Diagnostic::hint(range, d.message())
170 .with_fix(d.fix(&sema))
171 .with_code(Some(d.code())),
174 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
175 // Use more accurate position if available.
176 let display_range = d
178 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
180 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
182 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
184 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
185 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
189 .and_then(|it| it.segment())
190 .and_then(|it| it.name_ref())
191 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
193 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
194 let display_range = sema.diagnostics_display_range(diagnostics).range;
196 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
198 // Only collect experimental diagnostics when they're enabled.
199 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
200 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
202 // Finalize the `DiagnosticSink` building process.
203 let mut sink = sink_builder
204 // Diagnostics not handled above get no fix and default treatment.
206 res.borrow_mut().push(
208 sema.diagnostics_display_range(d.display_source()).range,
211 .with_code(Some(d.code())),
215 match sema.to_module_def(file_id) {
216 Some(m) => m.diagnostics(db, &mut sink),
218 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
226 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
227 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
228 .with_fix(d.fix(&sema))
229 .with_code(Some(d.code()))
232 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
233 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
234 .with_fix(d.fix(&sema))
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_fix(Some(Fix::new(
265 "Remove unnecessary braces",
266 SourceChange::from_text_edit(file_id, edit),
275 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
276 single_use_tree: &ast::UseTree,
277 ) -> Option<TextEdit> {
278 let use_tree_list_node = single_use_tree.syntax().parent()?;
279 if single_use_tree.path()?.segment()?.self_token().is_some() {
280 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
281 let end = use_tree_list_node.text_range().end();
282 return Some(TextEdit::delete(TextRange::new(start, end)));
289 use expect_test::{expect, Expect};
290 use stdx::trim_indent;
291 use test_utils::assert_eq_text;
293 use crate::{fixture, DiagnosticsConfig};
295 /// Takes a multi-file input fixture with annotated cursor positions,
297 /// * a diagnostic is produced
298 /// * this diagnostic fix trigger range touches the input cursor position
299 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
300 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
301 let after = trim_indent(ra_fixture_after);
303 let (analysis, file_position) = fixture::position(ra_fixture_before);
304 let diagnostic = analysis
305 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
309 let fix = diagnostic.fix.unwrap();
311 let file_id = *fix.source_change.source_file_edits.keys().next().unwrap();
312 let mut actual = analysis.file_text(file_id).unwrap().to_string();
314 for edit in fix.source_change.source_file_edits.values() {
315 edit.apply(&mut actual);
320 assert_eq_text!(&after, &actual);
322 fix.fix_trigger_range.contains_inclusive(file_position.offset),
323 "diagnostic fix range {:?} does not touch cursor position {:?}",
324 fix.fix_trigger_range,
329 /// Checks that there's a diagnostic *without* fix at `$0`.
330 fn check_no_fix(ra_fixture: &str) {
331 let (analysis, file_position) = fixture::position(ra_fixture);
332 let diagnostic = analysis
333 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
337 assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
340 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
341 /// apply to the file containing the cursor.
342 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
343 let (analysis, files) = fixture::files(ra_fixture);
344 let diagnostics = files
346 .flat_map(|file_id| {
347 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
349 .collect::<Vec<_>>();
350 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
353 fn check_expect(ra_fixture: &str, expect: Expect) {
354 let (analysis, file_id) = fixture::file(ra_fixture);
355 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
356 expect.assert_debug_eq(&diagnostics)
360 fn test_wrap_return_type_option() {
363 //- /main.rs crate:main deps:core
364 use core::option::Option::{self, Some, None};
366 fn div(x: i32, y: i32) -> Option<i32> {
372 //- /core/lib.rs crate:core
374 pub enum Result<T, E> { Ok(T), Err(E) }
377 pub enum Option<T> { Some(T), None }
381 use core::option::Option::{self, Some, None};
383 fn div(x: i32, y: i32) -> Option<i32> {
394 fn test_wrap_return_type() {
397 //- /main.rs crate:main deps:core
398 use core::result::Result::{self, Ok, Err};
400 fn div(x: i32, y: i32) -> Result<i32, ()> {
406 //- /core/lib.rs crate:core
408 pub enum Result<T, E> { Ok(T), Err(E) }
411 pub enum Option<T> { Some(T), None }
415 use core::result::Result::{self, Ok, Err};
417 fn div(x: i32, y: i32) -> Result<i32, ()> {
428 fn test_wrap_return_type_handles_generic_functions() {
431 //- /main.rs crate:main deps:core
432 use core::result::Result::{self, Ok, Err};
434 fn div<T>(x: T) -> Result<T, i32> {
440 //- /core/lib.rs crate:core
442 pub enum Result<T, E> { Ok(T), Err(E) }
445 pub enum Option<T> { Some(T), None }
449 use core::result::Result::{self, Ok, Err};
451 fn div<T>(x: T) -> Result<T, i32> {
462 fn test_wrap_return_type_handles_type_aliases() {
465 //- /main.rs crate:main deps:core
466 use core::result::Result::{self, Ok, Err};
468 type MyResult<T> = Result<T, ()>;
470 fn div(x: i32, y: i32) -> MyResult<i32> {
476 //- /core/lib.rs crate:core
478 pub enum Result<T, E> { Ok(T), Err(E) }
481 pub enum Option<T> { Some(T), None }
485 use core::result::Result::{self, Ok, Err};
487 type MyResult<T> = Result<T, ()>;
489 fn div(x: i32, y: i32) -> MyResult<i32> {
500 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
501 check_no_diagnostics(
503 //- /main.rs crate:main deps:core
504 use core::result::Result::{self, Ok, Err};
506 fn foo() -> Result<(), i32> { 0 }
508 //- /core/lib.rs crate:core
510 pub enum Result<T, E> { Ok(T), Err(E) }
513 pub enum Option<T> { Some(T), None }
520 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
521 check_no_diagnostics(
523 //- /main.rs crate:main deps:core
524 use core::result::Result::{self, Ok, Err};
526 enum SomeOtherEnum { Ok(i32), Err(String) }
528 fn foo() -> SomeOtherEnum { 0 }
530 //- /core/lib.rs crate:core
532 pub enum Result<T, E> { Ok(T), Err(E) }
535 pub enum Option<T> { Some(T), None }
542 fn test_fill_struct_fields_empty() {
545 struct TestStruct { one: i32, two: i64 }
548 let s = TestStruct {$0};
552 struct TestStruct { one: i32, two: i64 }
555 let s = TestStruct { one: (), two: ()};
562 fn test_fill_struct_fields_self() {
565 struct TestStruct { one: i32 }
568 fn test_fn() { let s = Self {$0}; }
572 struct TestStruct { one: i32 }
575 fn test_fn() { let s = Self { one: ()}; }
582 fn test_fill_struct_fields_enum() {
586 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
590 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
597 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
601 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
602 Expr::Bin { lhs: (), rhs: () }
610 fn test_fill_struct_fields_partial() {
613 struct TestStruct { one: i32, two: i64 }
616 let s = TestStruct{ two: 2$0 };
620 struct TestStruct { one: i32, two: i64 }
623 let s = TestStruct{ two: 2, one: () };
630 fn test_fill_struct_fields_no_diagnostic() {
631 check_no_diagnostics(
633 struct TestStruct { one: i32, two: i64 }
637 let s = TestStruct{ one, two: 2 };
644 fn test_fill_struct_fields_no_diagnostic_on_spread() {
645 check_no_diagnostics(
647 struct TestStruct { one: i32, two: i64 }
651 let s = TestStruct{ ..a };
658 fn test_unresolved_module_diagnostic() {
664 message: "unresolved module",
669 label: "Create module",
670 source_change: SourceChange {
671 source_file_edits: {},
674 dst: AnchoredPathBuf {
680 initial_contents: "",
685 fix_trigger_range: 0..8,
701 fn test_unresolved_macro_range() {
707 message: "unresolved macro call",
714 "unresolved-macro-call",
724 fn range_mapping_out_of_macros() {
725 // FIXME: this is very wrong, but somewhat tricky to fix.
732 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
735 let _x = id![Foo { a: $042 }];
738 pub struct Foo { pub a: i32, pub b: i32 }
745 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
748 let _x = id![Foo { a: 42 }];
751 pub struct Foo { pub a: i32, pub b: i32 }
757 fn test_check_unnecessary_braces_in_use_statement() {
758 check_no_diagnostics(
771 check_no_diagnostics(
829 mod a { mod c {} mod d { mod e {} } }
830 use a::{c, d::{e$0}};
833 mod a { mod c {} mod d { mod e {} } }
840 fn test_add_field_from_usage() {
844 Foo { bar: 3, baz$0: false};
852 Foo { bar: 3, baz: false};
863 fn test_add_field_in_other_file_from_usage() {
870 foo::Foo { bar: 3, $0baz: false};
887 fn test_disabled_diagnostics() {
888 let mut config = DiagnosticsConfig::default();
889 config.disabled.insert("unresolved-module".into());
891 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
893 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
894 assert!(diagnostics.is_empty());
896 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
897 assert!(!diagnostics.is_empty());
901 fn test_rename_incorrect_case() {
904 pub struct test_struct$0 { one: i32 }
906 pub fn some_fn(val: test_struct) -> test_struct {
907 test_struct { one: val.one + 1 }
911 pub struct TestStruct { one: i32 }
913 pub fn some_fn(val: TestStruct) -> TestStruct {
914 TestStruct { one: val.one + 1 }
921 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
926 pub fn some_fn(non_snake_case: u8) -> u8 {
934 pub fn SomeFn$0(val: u8) -> u8 {
935 if val != 0 { SomeFn(val - 1) } else { val }
939 pub fn some_fn(val: u8) -> u8 {
940 if val != 0 { some_fn(val - 1) } else { val }
948 let whatAWeird_Formatting$0 = 10;
949 another_func(whatAWeird_Formatting);
954 let what_a_weird_formatting = 10;
955 another_func(what_a_weird_formatting);
962 fn test_uppercase_const_no_diagnostics() {
963 check_no_diagnostics(
966 const ANOTHER_ITEM$0: &str = "some_item";
973 fn test_rename_incorrect_case_struct_method() {
976 pub struct TestStruct;
979 pub fn SomeFn$0() -> TestStruct {
985 pub struct TestStruct;
988 pub fn some_fn() -> TestStruct {
997 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
998 let input = r#"fn FOO$0() {}"#;
999 let expected = r#"fn foo() {}"#;
1001 let (analysis, file_position) = fixture::position(input);
1003 analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
1004 assert_eq!(diagnostics.len(), 1);
1006 check_fix(input, expected);
1010 fn unlinked_file_prepend_first_item() {
1011 cov_mark::check!(unlinked_file_prepend_before_first_item);
1028 fn unlinked_file_append_mod() {
1029 cov_mark::check!(unlinked_file_append_to_existing_mods);
1041 mod preexisting_bottom;)
1055 mod preexisting_bottom;)
1061 fn unlinked_file_insert_in_empty_file() {
1062 cov_mark::check!(unlinked_file_empty_file);
1076 fn unlinked_file_old_style_modrs() {
1094 fn unlinked_file_new_style_mod() {
1110 fn unlinked_file_with_cfg_off() {
1111 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1125 fn unlinked_file_with_cfg_on() {
1126 check_no_diagnostics(