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::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
30 use self::fixes::DiagnosticWithFix;
33 pub struct Diagnostic {
34 // pub name: Option<String>,
37 pub severity: Severity,
38 pub fix: Option<Assist>,
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<Assist>) -> Self {
63 fn with_unused(self, unused: bool) -> Self {
64 Self { unused, ..self }
67 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
72 #[derive(Debug, Copy, Clone)]
78 #[derive(Default, Debug, Clone)]
79 pub struct DiagnosticsConfig {
80 pub disable_experimental: bool,
81 pub disabled: FxHashSet<String>,
84 pub(crate) fn diagnostics(
86 config: &DiagnosticsConfig,
89 ) -> Vec<Diagnostic> {
90 let _p = profile::span("diagnostics");
91 let sema = Semantics::new(db);
92 let parse = db.parse(file_id);
93 let mut res = Vec::new();
95 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
101 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
104 for node in parse.tree().syntax().descendants() {
105 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
106 field_shorthand::check(&mut res, file_id, &node);
108 let res = RefCell::new(res);
109 let sink_builder = DiagnosticSinkBuilder::new()
110 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
111 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
113 .on::<hir::diagnostics::MissingFields, _>(|d| {
114 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
116 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
117 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
119 .on::<hir::diagnostics::NoSuchField, _>(|d| {
120 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
122 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
123 res.borrow_mut().push(diagnostic_with_fix(d, &sema, resolve));
125 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
126 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
128 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
129 res.borrow_mut().push(warning_with_fix(d, &sema, resolve));
131 .on::<hir::diagnostics::InactiveCode, _>(|d| {
132 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
133 if d.display_source().file_id.expansion_info(db).is_some() {
137 // Override severity and mark as unused.
138 res.borrow_mut().push(
140 sema.diagnostics_display_range(d.display_source()).range,
144 .with_code(Some(d.code())),
147 .on::<UnlinkedFile, _>(|d| {
148 // Limit diagnostic to the first few characters in the file. This matches how VS Code
149 // renders it with the full span, but on other editors, and is less invasive.
150 let range = sema.diagnostics_display_range(d.display_source()).range;
151 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
153 // Override severity and mark as unused.
154 res.borrow_mut().push(
155 Diagnostic::hint(range, d.message())
156 .with_fix(d.fix(&sema, resolve))
157 .with_code(Some(d.code())),
160 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
161 // Use more accurate position if available.
162 let display_range = d
164 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
166 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
168 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
170 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
171 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
175 .and_then(|it| it.segment())
176 .and_then(|it| it.name_ref())
177 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
179 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
180 let display_range = sema.diagnostics_display_range(diagnostics).range;
182 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
184 // Only collect experimental diagnostics when they're enabled.
185 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
186 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
188 // Finalize the `DiagnosticSink` building process.
189 let mut sink = sink_builder
190 // Diagnostics not handled above get no fix and default treatment.
192 res.borrow_mut().push(
194 sema.diagnostics_display_range(d.display_source()).range,
197 .with_code(Some(d.code())),
201 match sema.to_module_def(file_id) {
202 Some(m) => m.diagnostics(db, &mut sink),
204 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
212 fn diagnostic_with_fix<D: DiagnosticWithFix>(
214 sema: &Semantics<RootDatabase>,
217 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
218 .with_fix(d.fix(&sema, resolve))
219 .with_code(Some(d.code()))
222 fn warning_with_fix<D: DiagnosticWithFix>(
224 sema: &Semantics<RootDatabase>,
227 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
228 .with_fix(d.fix(&sema, resolve))
229 .with_code(Some(d.code()))
232 fn check_unnecessary_braces_in_use_statement(
233 acc: &mut Vec<Diagnostic>,
237 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
238 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
239 // If there is a comment inside the bracketed `use`,
240 // assume it is a commented out module path and don't show diagnostic.
241 if use_tree_list.has_inner_comment() {
245 let use_range = use_tree_list.syntax().text_range();
247 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
249 let to_replace = single_use_tree.syntax().text().to_string();
250 let mut edit_builder = TextEdit::builder();
251 edit_builder.delete(use_range);
252 edit_builder.insert(use_range.start(), to_replace);
253 edit_builder.finish()
257 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
260 "Remove unnecessary braces",
261 SourceChange::from_text_edit(file_id, edit),
270 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
271 single_use_tree: &ast::UseTree,
272 ) -> Option<TextEdit> {
273 let use_tree_list_node = single_use_tree.syntax().parent()?;
274 if single_use_tree.path()?.segment()?.self_token().is_some() {
275 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
276 let end = use_tree_list_node.text_range().end();
277 return Some(TextEdit::delete(TextRange::new(start, end)));
282 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
283 let mut res = unresolved_fix(id, label, target);
284 res.source_change = Some(source_change);
288 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
289 assert!(!id.contains(' '));
291 id: AssistId(id, AssistKind::QuickFix),
292 label: Label::new(label),
301 use expect_test::{expect, Expect};
302 use stdx::trim_indent;
303 use test_utils::assert_eq_text;
305 use crate::{fixture, DiagnosticsConfig};
307 /// Takes a multi-file input fixture with annotated cursor positions,
309 /// * a diagnostic is produced
310 /// * this diagnostic fix trigger range touches the input cursor position
311 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
312 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
313 let after = trim_indent(ra_fixture_after);
315 let (analysis, file_position) = fixture::position(ra_fixture_before);
316 let diagnostic = analysis
317 .diagnostics(&DiagnosticsConfig::default(), true, file_position.file_id)
321 let fix = diagnostic.fix.unwrap();
323 let source_change = fix.source_change.unwrap();
324 let file_id = *source_change.source_file_edits.keys().next().unwrap();
325 let mut actual = analysis.file_text(file_id).unwrap().to_string();
327 for edit in source_change.source_file_edits.values() {
328 edit.apply(&mut actual);
333 assert_eq_text!(&after, &actual);
335 fix.target.contains_inclusive(file_position.offset),
336 "diagnostic fix range {:?} does not touch cursor position {:?}",
342 /// Checks that there's a diagnostic *without* fix at `$0`.
343 fn check_no_fix(ra_fixture: &str) {
344 let (analysis, file_position) = fixture::position(ra_fixture);
345 let diagnostic = analysis
346 .diagnostics(&DiagnosticsConfig::default(), true, file_position.file_id)
350 assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
353 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
354 /// apply to the file containing the cursor.
355 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
356 let (analysis, files) = fixture::files(ra_fixture);
357 let diagnostics = files
359 .flat_map(|file_id| {
360 analysis.diagnostics(&DiagnosticsConfig::default(), true, file_id).unwrap()
362 .collect::<Vec<_>>();
363 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
366 fn check_expect(ra_fixture: &str, expect: Expect) {
367 let (analysis, file_id) = fixture::file(ra_fixture);
369 analysis.diagnostics(&DiagnosticsConfig::default(), true, file_id).unwrap();
370 expect.assert_debug_eq(&diagnostics)
374 fn test_wrap_return_type_option() {
377 //- /main.rs crate:main deps:core
378 use core::option::Option::{self, Some, None};
380 fn div(x: i32, y: i32) -> Option<i32> {
386 //- /core/lib.rs crate:core
388 pub enum Result<T, E> { Ok(T), Err(E) }
391 pub enum Option<T> { Some(T), None }
395 use core::option::Option::{self, Some, None};
397 fn div(x: i32, y: i32) -> Option<i32> {
408 fn test_wrap_return_type() {
411 //- /main.rs crate:main deps:core
412 use core::result::Result::{self, Ok, Err};
414 fn div(x: i32, y: i32) -> Result<i32, ()> {
420 //- /core/lib.rs crate:core
422 pub enum Result<T, E> { Ok(T), Err(E) }
425 pub enum Option<T> { Some(T), None }
429 use core::result::Result::{self, Ok, Err};
431 fn div(x: i32, y: i32) -> Result<i32, ()> {
442 fn test_wrap_return_type_handles_generic_functions() {
445 //- /main.rs crate:main deps:core
446 use core::result::Result::{self, Ok, Err};
448 fn div<T>(x: T) -> Result<T, i32> {
454 //- /core/lib.rs crate:core
456 pub enum Result<T, E> { Ok(T), Err(E) }
459 pub enum Option<T> { Some(T), None }
463 use core::result::Result::{self, Ok, Err};
465 fn div<T>(x: T) -> Result<T, i32> {
476 fn test_wrap_return_type_handles_type_aliases() {
479 //- /main.rs crate:main deps:core
480 use core::result::Result::{self, Ok, Err};
482 type MyResult<T> = Result<T, ()>;
484 fn div(x: i32, y: i32) -> MyResult<i32> {
490 //- /core/lib.rs crate:core
492 pub enum Result<T, E> { Ok(T), Err(E) }
495 pub enum Option<T> { Some(T), None }
499 use core::result::Result::{self, Ok, Err};
501 type MyResult<T> = Result<T, ()>;
503 fn div(x: i32, y: i32) -> MyResult<i32> {
514 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
515 check_no_diagnostics(
517 //- /main.rs crate:main deps:core
518 use core::result::Result::{self, Ok, Err};
520 fn foo() -> Result<(), i32> { 0 }
522 //- /core/lib.rs crate:core
524 pub enum Result<T, E> { Ok(T), Err(E) }
527 pub enum Option<T> { Some(T), None }
534 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
535 check_no_diagnostics(
537 //- /main.rs crate:main deps:core
538 use core::result::Result::{self, Ok, Err};
540 enum SomeOtherEnum { Ok(i32), Err(String) }
542 fn foo() -> SomeOtherEnum { 0 }
544 //- /core/lib.rs crate:core
546 pub enum Result<T, E> { Ok(T), Err(E) }
549 pub enum Option<T> { Some(T), None }
556 fn test_fill_struct_fields_empty() {
559 struct TestStruct { one: i32, two: i64 }
562 let s = TestStruct {$0};
566 struct TestStruct { one: i32, two: i64 }
569 let s = TestStruct { one: (), two: ()};
576 fn test_fill_struct_fields_self() {
579 struct TestStruct { one: i32 }
582 fn test_fn() { let s = Self {$0}; }
586 struct TestStruct { one: i32 }
589 fn test_fn() { let s = Self { one: ()}; }
596 fn test_fill_struct_fields_enum() {
600 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
604 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
611 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
615 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
616 Expr::Bin { lhs: (), rhs: () }
624 fn test_fill_struct_fields_partial() {
627 struct TestStruct { one: i32, two: i64 }
630 let s = TestStruct{ two: 2$0 };
634 struct TestStruct { one: i32, two: i64 }
637 let s = TestStruct{ two: 2, one: () };
644 fn test_fill_struct_fields_no_diagnostic() {
645 check_no_diagnostics(
647 struct TestStruct { one: i32, two: i64 }
651 let s = TestStruct{ one, two: 2 };
658 fn test_fill_struct_fields_no_diagnostic_on_spread() {
659 check_no_diagnostics(
661 struct TestStruct { one: i32, two: i64 }
665 let s = TestStruct{ ..a };
672 fn test_unresolved_module_diagnostic() {
678 message: "unresolved module",
687 label: "Create module",
692 source_file_edits: {},
695 dst: AnchoredPathBuf {
701 initial_contents: "",
722 fn test_unresolved_macro_range() {
728 message: "unresolved macro call",
735 "unresolved-macro-call",
745 fn range_mapping_out_of_macros() {
746 // FIXME: this is very wrong, but somewhat tricky to fix.
753 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
756 let _x = id![Foo { a: $042 }];
759 pub struct Foo { pub a: i32, pub b: i32 }
766 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
769 let _x = id![Foo { a: 42 }];
772 pub struct Foo { pub a: i32, pub b: i32 }
778 fn test_check_unnecessary_braces_in_use_statement() {
779 check_no_diagnostics(
792 check_no_diagnostics(
850 mod a { mod c {} mod d { mod e {} } }
851 use a::{c, d::{e$0}};
854 mod a { mod c {} mod d { mod e {} } }
861 fn test_add_field_from_usage() {
865 Foo { bar: 3, baz$0: false};
873 Foo { bar: 3, baz: false};
884 fn test_add_field_in_other_file_from_usage() {
891 foo::Foo { bar: 3, $0baz: false};
908 fn test_disabled_diagnostics() {
909 let mut config = DiagnosticsConfig::default();
910 config.disabled.insert("unresolved-module".into());
912 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
914 let diagnostics = analysis.diagnostics(&config, true, file_id).unwrap();
915 assert!(diagnostics.is_empty());
918 analysis.diagnostics(&DiagnosticsConfig::default(), true, file_id).unwrap();
919 assert!(!diagnostics.is_empty());
923 fn test_rename_incorrect_case() {
926 pub struct test_struct$0 { one: i32 }
928 pub fn some_fn(val: test_struct) -> test_struct {
929 test_struct { one: val.one + 1 }
933 pub struct TestStruct { one: i32 }
935 pub fn some_fn(val: TestStruct) -> TestStruct {
936 TestStruct { one: val.one + 1 }
943 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
948 pub fn some_fn(non_snake_case: u8) -> u8 {
956 pub fn SomeFn$0(val: u8) -> u8 {
957 if val != 0 { SomeFn(val - 1) } else { val }
961 pub fn some_fn(val: u8) -> u8 {
962 if val != 0 { some_fn(val - 1) } else { val }
970 let whatAWeird_Formatting$0 = 10;
971 another_func(whatAWeird_Formatting);
976 let what_a_weird_formatting = 10;
977 another_func(what_a_weird_formatting);
984 fn test_uppercase_const_no_diagnostics() {
985 check_no_diagnostics(
988 const ANOTHER_ITEM$0: &str = "some_item";
995 fn test_rename_incorrect_case_struct_method() {
998 pub struct TestStruct;
1001 pub fn SomeFn$0() -> TestStruct {
1007 pub struct TestStruct;
1010 pub fn some_fn() -> TestStruct {
1019 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
1020 let input = r#"fn FOO$0() {}"#;
1021 let expected = r#"fn foo() {}"#;
1023 let (analysis, file_position) = fixture::position(input);
1024 let diagnostics = analysis
1025 .diagnostics(&DiagnosticsConfig::default(), true, file_position.file_id)
1027 assert_eq!(diagnostics.len(), 1);
1029 check_fix(input, expected);
1033 fn unlinked_file_prepend_first_item() {
1034 cov_mark::check!(unlinked_file_prepend_before_first_item);
1051 fn unlinked_file_append_mod() {
1052 cov_mark::check!(unlinked_file_append_to_existing_mods);
1064 mod preexisting_bottom;)
1078 mod preexisting_bottom;)
1084 fn unlinked_file_insert_in_empty_file() {
1085 cov_mark::check!(unlinked_file_empty_file);
1099 fn unlinked_file_old_style_modrs() {
1117 fn unlinked_file_new_style_mod() {
1133 fn unlinked_file_with_cfg_off() {
1134 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1148 fn unlinked_file_with_cfg_on() {
1149 check_no_diagnostics(