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,
88 ) -> Vec<Diagnostic> {
89 let _p = profile::span("diagnostics");
90 let sema = Semantics::new(db);
91 let parse = db.parse(file_id);
92 let mut res = Vec::new();
94 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
100 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
103 for node in parse.tree().syntax().descendants() {
104 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
105 field_shorthand::check(&mut res, file_id, &node);
107 let res = RefCell::new(res);
108 let sink_builder = DiagnosticSinkBuilder::new()
109 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
110 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
112 .on::<hir::diagnostics::MissingFields, _>(|d| {
113 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
115 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
116 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
118 .on::<hir::diagnostics::NoSuchField, _>(|d| {
119 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
121 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
122 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
124 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
125 res.borrow_mut().push(warning_with_fix(d, &sema));
127 .on::<hir::diagnostics::ReplaceFilterMapNextWithFindMap, _>(|d| {
128 res.borrow_mut().push(warning_with_fix(d, &sema));
130 .on::<hir::diagnostics::InactiveCode, _>(|d| {
131 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
132 if d.display_source().file_id.expansion_info(db).is_some() {
136 // Override severity and mark as unused.
137 res.borrow_mut().push(
139 sema.diagnostics_display_range(d.display_source()).range,
143 .with_code(Some(d.code())),
146 .on::<UnlinkedFile, _>(|d| {
147 // Limit diagnostic to the first few characters in the file. This matches how VS Code
148 // renders it with the full span, but on other editors, and is less invasive.
149 let range = sema.diagnostics_display_range(d.display_source()).range;
150 let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range);
152 // Override severity and mark as unused.
153 res.borrow_mut().push(
154 Diagnostic::hint(range, d.message())
155 .with_fix(d.fix(&sema))
156 .with_code(Some(d.code())),
159 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
160 // Use more accurate position if available.
161 let display_range = d
163 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
165 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
167 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
169 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
170 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
174 .and_then(|it| it.segment())
175 .and_then(|it| it.name_ref())
176 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
178 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
179 let display_range = sema.diagnostics_display_range(diagnostics).range;
181 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
183 // Only collect experimental diagnostics when they're enabled.
184 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
185 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
187 // Finalize the `DiagnosticSink` building process.
188 let mut sink = sink_builder
189 // Diagnostics not handled above get no fix and default treatment.
191 res.borrow_mut().push(
193 sema.diagnostics_display_range(d.display_source()).range,
196 .with_code(Some(d.code())),
200 match sema.to_module_def(file_id) {
201 Some(m) => m.diagnostics(db, &mut sink),
203 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
211 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
212 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
213 .with_fix(d.fix(&sema))
214 .with_code(Some(d.code()))
217 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
218 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
219 .with_fix(d.fix(&sema))
220 .with_code(Some(d.code()))
223 fn check_unnecessary_braces_in_use_statement(
224 acc: &mut Vec<Diagnostic>,
228 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
229 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
230 // If there is a comment inside the bracketed `use`,
231 // assume it is a commented out module path and don't show diagnostic.
232 if use_tree_list.has_inner_comment() {
236 let use_range = use_tree_list.syntax().text_range();
238 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
240 let to_replace = single_use_tree.syntax().text().to_string();
241 let mut edit_builder = TextEdit::builder();
242 edit_builder.delete(use_range);
243 edit_builder.insert(use_range.start(), to_replace);
244 edit_builder.finish()
248 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
251 "Remove unnecessary braces",
252 SourceChange::from_text_edit(file_id, edit),
261 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
262 single_use_tree: &ast::UseTree,
263 ) -> Option<TextEdit> {
264 let use_tree_list_node = single_use_tree.syntax().parent()?;
265 if single_use_tree.path()?.segment()?.self_token().is_some() {
266 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
267 let end = use_tree_list_node.text_range().end();
268 return Some(TextEdit::delete(TextRange::new(start, end)));
273 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
274 assert!(!id.contains(' '));
276 id: AssistId(id, AssistKind::QuickFix),
277 label: Label::new(label),
280 source_change: Some(source_change),
286 use expect_test::{expect, Expect};
287 use stdx::trim_indent;
288 use test_utils::assert_eq_text;
290 use crate::{fixture, DiagnosticsConfig};
292 /// Takes a multi-file input fixture with annotated cursor positions,
294 /// * a diagnostic is produced
295 /// * this diagnostic fix trigger range touches the input cursor position
296 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
297 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
298 let after = trim_indent(ra_fixture_after);
300 let (analysis, file_position) = fixture::position(ra_fixture_before);
301 let diagnostic = analysis
302 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
306 let fix = diagnostic.fix.unwrap();
308 let source_change = fix.source_change.unwrap();
309 let file_id = *source_change.source_file_edits.keys().next().unwrap();
310 let mut actual = analysis.file_text(file_id).unwrap().to_string();
312 for edit in source_change.source_file_edits.values() {
313 edit.apply(&mut actual);
318 assert_eq_text!(&after, &actual);
320 fix.target.contains_inclusive(file_position.offset),
321 "diagnostic fix range {:?} does not touch cursor position {:?}",
327 /// Checks that there's a diagnostic *without* fix at `$0`.
328 fn check_no_fix(ra_fixture: &str) {
329 let (analysis, file_position) = fixture::position(ra_fixture);
330 let diagnostic = analysis
331 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
335 assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
338 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
339 /// apply to the file containing the cursor.
340 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
341 let (analysis, files) = fixture::files(ra_fixture);
342 let diagnostics = files
344 .flat_map(|file_id| {
345 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
347 .collect::<Vec<_>>();
348 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
351 fn check_expect(ra_fixture: &str, expect: Expect) {
352 let (analysis, file_id) = fixture::file(ra_fixture);
353 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
354 expect.assert_debug_eq(&diagnostics)
358 fn test_wrap_return_type_option() {
361 //- /main.rs crate:main deps:core
362 use core::option::Option::{self, Some, None};
364 fn div(x: i32, y: i32) -> Option<i32> {
370 //- /core/lib.rs crate:core
372 pub enum Result<T, E> { Ok(T), Err(E) }
375 pub enum Option<T> { Some(T), None }
379 use core::option::Option::{self, Some, None};
381 fn div(x: i32, y: i32) -> Option<i32> {
392 fn test_wrap_return_type() {
395 //- /main.rs crate:main deps:core
396 use core::result::Result::{self, Ok, Err};
398 fn div(x: i32, y: i32) -> Result<i32, ()> {
404 //- /core/lib.rs crate:core
406 pub enum Result<T, E> { Ok(T), Err(E) }
409 pub enum Option<T> { Some(T), None }
413 use core::result::Result::{self, Ok, Err};
415 fn div(x: i32, y: i32) -> Result<i32, ()> {
426 fn test_wrap_return_type_handles_generic_functions() {
429 //- /main.rs crate:main deps:core
430 use core::result::Result::{self, Ok, Err};
432 fn div<T>(x: T) -> Result<T, i32> {
438 //- /core/lib.rs crate:core
440 pub enum Result<T, E> { Ok(T), Err(E) }
443 pub enum Option<T> { Some(T), None }
447 use core::result::Result::{self, Ok, Err};
449 fn div<T>(x: T) -> Result<T, i32> {
460 fn test_wrap_return_type_handles_type_aliases() {
463 //- /main.rs crate:main deps:core
464 use core::result::Result::{self, Ok, Err};
466 type MyResult<T> = Result<T, ()>;
468 fn div(x: i32, y: i32) -> MyResult<i32> {
474 //- /core/lib.rs crate:core
476 pub enum Result<T, E> { Ok(T), Err(E) }
479 pub enum Option<T> { Some(T), None }
483 use core::result::Result::{self, Ok, Err};
485 type MyResult<T> = Result<T, ()>;
487 fn div(x: i32, y: i32) -> MyResult<i32> {
498 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
499 check_no_diagnostics(
501 //- /main.rs crate:main deps:core
502 use core::result::Result::{self, Ok, Err};
504 fn foo() -> Result<(), i32> { 0 }
506 //- /core/lib.rs crate:core
508 pub enum Result<T, E> { Ok(T), Err(E) }
511 pub enum Option<T> { Some(T), None }
518 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
519 check_no_diagnostics(
521 //- /main.rs crate:main deps:core
522 use core::result::Result::{self, Ok, Err};
524 enum SomeOtherEnum { Ok(i32), Err(String) }
526 fn foo() -> SomeOtherEnum { 0 }
528 //- /core/lib.rs crate:core
530 pub enum Result<T, E> { Ok(T), Err(E) }
533 pub enum Option<T> { Some(T), None }
540 fn test_fill_struct_fields_empty() {
543 struct TestStruct { one: i32, two: i64 }
546 let s = TestStruct {$0};
550 struct TestStruct { one: i32, two: i64 }
553 let s = TestStruct { one: (), two: ()};
560 fn test_fill_struct_fields_self() {
563 struct TestStruct { one: i32 }
566 fn test_fn() { let s = Self {$0}; }
570 struct TestStruct { one: i32 }
573 fn test_fn() { let s = Self { one: ()}; }
580 fn test_fill_struct_fields_enum() {
584 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
588 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
595 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
599 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
600 Expr::Bin { lhs: (), rhs: () }
608 fn test_fill_struct_fields_partial() {
611 struct TestStruct { one: i32, two: i64 }
614 let s = TestStruct{ two: 2$0 };
618 struct TestStruct { one: i32, two: i64 }
621 let s = TestStruct{ two: 2, one: () };
628 fn test_fill_struct_fields_no_diagnostic() {
629 check_no_diagnostics(
631 struct TestStruct { one: i32, two: i64 }
635 let s = TestStruct{ one, two: 2 };
642 fn test_fill_struct_fields_no_diagnostic_on_spread() {
643 check_no_diagnostics(
645 struct TestStruct { one: i32, two: i64 }
649 let s = TestStruct{ ..a };
656 fn test_unresolved_module_diagnostic() {
662 message: "unresolved module",
671 label: "Create module",
676 source_file_edits: {},
679 dst: AnchoredPathBuf {
685 initial_contents: "",
706 fn test_unresolved_macro_range() {
712 message: "unresolved macro call",
719 "unresolved-macro-call",
729 fn range_mapping_out_of_macros() {
730 // FIXME: this is very wrong, but somewhat tricky to fix.
737 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
740 let _x = id![Foo { a: $042 }];
743 pub struct Foo { pub a: i32, pub b: i32 }
750 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
753 let _x = id![Foo { a: 42 }];
756 pub struct Foo { pub a: i32, pub b: i32 }
762 fn test_check_unnecessary_braces_in_use_statement() {
763 check_no_diagnostics(
776 check_no_diagnostics(
834 mod a { mod c {} mod d { mod e {} } }
835 use a::{c, d::{e$0}};
838 mod a { mod c {} mod d { mod e {} } }
845 fn test_add_field_from_usage() {
849 Foo { bar: 3, baz$0: false};
857 Foo { bar: 3, baz: false};
868 fn test_add_field_in_other_file_from_usage() {
875 foo::Foo { bar: 3, $0baz: false};
892 fn test_disabled_diagnostics() {
893 let mut config = DiagnosticsConfig::default();
894 config.disabled.insert("unresolved-module".into());
896 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
898 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
899 assert!(diagnostics.is_empty());
901 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
902 assert!(!diagnostics.is_empty());
906 fn test_rename_incorrect_case() {
909 pub struct test_struct$0 { one: i32 }
911 pub fn some_fn(val: test_struct) -> test_struct {
912 test_struct { one: val.one + 1 }
916 pub struct TestStruct { one: i32 }
918 pub fn some_fn(val: TestStruct) -> TestStruct {
919 TestStruct { one: val.one + 1 }
926 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
931 pub fn some_fn(non_snake_case: u8) -> u8 {
939 pub fn SomeFn$0(val: u8) -> u8 {
940 if val != 0 { SomeFn(val - 1) } else { val }
944 pub fn some_fn(val: u8) -> u8 {
945 if val != 0 { some_fn(val - 1) } else { val }
953 let whatAWeird_Formatting$0 = 10;
954 another_func(whatAWeird_Formatting);
959 let what_a_weird_formatting = 10;
960 another_func(what_a_weird_formatting);
967 fn test_uppercase_const_no_diagnostics() {
968 check_no_diagnostics(
971 const ANOTHER_ITEM$0: &str = "some_item";
978 fn test_rename_incorrect_case_struct_method() {
981 pub struct TestStruct;
984 pub fn SomeFn$0() -> TestStruct {
990 pub struct TestStruct;
993 pub fn some_fn() -> TestStruct {
1002 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
1003 let input = r#"fn FOO$0() {}"#;
1004 let expected = r#"fn foo() {}"#;
1006 let (analysis, file_position) = fixture::position(input);
1008 analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
1009 assert_eq!(diagnostics.len(), 1);
1011 check_fix(input, expected);
1015 fn unlinked_file_prepend_first_item() {
1016 cov_mark::check!(unlinked_file_prepend_before_first_item);
1033 fn unlinked_file_append_mod() {
1034 cov_mark::check!(unlinked_file_append_to_existing_mods);
1046 mod preexisting_bottom;)
1060 mod preexisting_bottom;)
1066 fn unlinked_file_insert_in_empty_file() {
1067 cov_mark::check!(unlinked_file_empty_file);
1081 fn unlinked_file_old_style_modrs() {
1099 fn unlinked_file_new_style_mod() {
1115 fn unlinked_file_with_cfg_off() {
1116 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1130 fn unlinked_file_with_cfg_on() {
1131 check_no_diagnostics(