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,
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 // Override severity and mark as unused.
163 res.borrow_mut().push(
165 sema.diagnostics_display_range(d.display_source()).range,
169 .with_fix(d.fix(&sema))
170 .with_code(Some(d.code())),
173 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
174 // Use more accurate position if available.
175 let display_range = d
177 .unwrap_or_else(|| sema.diagnostics_display_range(d.display_source()).range);
179 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
181 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
183 .on::<hir::diagnostics::UnresolvedMacroCall, _>(|d| {
184 let last_path_segment = sema.db.parse_or_expand(d.file).and_then(|root| {
188 .and_then(|it| it.segment())
189 .and_then(|it| it.name_ref())
190 .map(|it| InFile::new(d.file, SyntaxNodePtr::new(it.syntax())))
192 let diagnostics = last_path_segment.unwrap_or_else(|| d.display_source());
193 let display_range = sema.diagnostics_display_range(diagnostics).range;
195 .push(Diagnostic::error(display_range, d.message()).with_code(Some(d.code())));
197 // Only collect experimental diagnostics when they're enabled.
198 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
199 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
201 // Finalize the `DiagnosticSink` building process.
202 let mut sink = sink_builder
203 // Diagnostics not handled above get no fix and default treatment.
205 res.borrow_mut().push(
207 sema.diagnostics_display_range(d.display_source()).range,
210 .with_code(Some(d.code())),
214 match sema.to_module_def(file_id) {
215 Some(m) => m.diagnostics(db, &mut sink),
217 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
225 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
226 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
227 .with_fix(d.fix(&sema))
228 .with_code(Some(d.code()))
231 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
232 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
233 .with_fix(d.fix(&sema))
234 .with_code(Some(d.code()))
237 fn check_unnecessary_braces_in_use_statement(
238 acc: &mut Vec<Diagnostic>,
242 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
243 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
244 // If there is a comment inside the bracketed `use`,
245 // assume it is a commented out module path and don't show diagnostic.
246 if use_tree_list.has_inner_comment() {
250 let use_range = use_tree_list.syntax().text_range();
252 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
254 let to_replace = single_use_tree.syntax().text().to_string();
255 let mut edit_builder = TextEdit::builder();
256 edit_builder.delete(use_range);
257 edit_builder.insert(use_range.start(), to_replace);
258 edit_builder.finish()
262 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
263 .with_fix(Some(Fix::new(
264 "Remove unnecessary braces",
265 SourceChange::from_text_edit(file_id, edit),
274 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
275 single_use_tree: &ast::UseTree,
276 ) -> Option<TextEdit> {
277 let use_tree_list_node = single_use_tree.syntax().parent()?;
278 if single_use_tree.path()?.segment()?.self_token().is_some() {
279 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
280 let end = use_tree_list_node.text_range().end();
281 return Some(TextEdit::delete(TextRange::new(start, end)));
288 use expect_test::{expect, Expect};
289 use stdx::trim_indent;
290 use test_utils::assert_eq_text;
292 use crate::{fixture, DiagnosticsConfig};
294 /// Takes a multi-file input fixture with annotated cursor positions,
296 /// * a diagnostic is produced
297 /// * this diagnostic fix trigger range touches the input cursor position
298 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
299 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
300 let after = trim_indent(ra_fixture_after);
302 let (analysis, file_position) = fixture::position(ra_fixture_before);
303 let diagnostic = analysis
304 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
308 let fix = diagnostic.fix.unwrap();
310 let file_id = *fix.source_change.source_file_edits.keys().next().unwrap();
311 let mut actual = analysis.file_text(file_id).unwrap().to_string();
313 for edit in fix.source_change.source_file_edits.values() {
314 edit.apply(&mut actual);
319 assert_eq_text!(&after, &actual);
321 fix.fix_trigger_range.contains_inclusive(file_position.offset),
322 "diagnostic fix range {:?} does not touch cursor position {:?}",
323 fix.fix_trigger_range,
328 /// Checks that there's a diagnostic *without* fix at `$0`.
329 fn check_no_fix(ra_fixture: &str) {
330 let (analysis, file_position) = fixture::position(ra_fixture);
331 let diagnostic = analysis
332 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
336 assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
339 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
340 /// apply to the file containing the cursor.
341 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
342 let (analysis, files) = fixture::files(ra_fixture);
343 let diagnostics = files
345 .flat_map(|file_id| {
346 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
348 .collect::<Vec<_>>();
349 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
352 fn check_expect(ra_fixture: &str, expect: Expect) {
353 let (analysis, file_id) = fixture::file(ra_fixture);
354 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
355 expect.assert_debug_eq(&diagnostics)
359 fn test_wrap_return_type_option() {
362 //- /main.rs crate:main deps:core
363 use core::option::Option::{self, Some, None};
365 fn div(x: i32, y: i32) -> Option<i32> {
371 //- /core/lib.rs crate:core
373 pub enum Result<T, E> { Ok(T), Err(E) }
376 pub enum Option<T> { Some(T), None }
380 use core::option::Option::{self, Some, None};
382 fn div(x: i32, y: i32) -> Option<i32> {
393 fn test_wrap_return_type() {
396 //- /main.rs crate:main deps:core
397 use core::result::Result::{self, Ok, Err};
399 fn div(x: i32, y: i32) -> Result<i32, ()> {
405 //- /core/lib.rs crate:core
407 pub enum Result<T, E> { Ok(T), Err(E) }
410 pub enum Option<T> { Some(T), None }
414 use core::result::Result::{self, Ok, Err};
416 fn div(x: i32, y: i32) -> Result<i32, ()> {
427 fn test_wrap_return_type_handles_generic_functions() {
430 //- /main.rs crate:main deps:core
431 use core::result::Result::{self, Ok, Err};
433 fn div<T>(x: T) -> Result<T, i32> {
439 //- /core/lib.rs crate:core
441 pub enum Result<T, E> { Ok(T), Err(E) }
444 pub enum Option<T> { Some(T), None }
448 use core::result::Result::{self, Ok, Err};
450 fn div<T>(x: T) -> Result<T, i32> {
461 fn test_wrap_return_type_handles_type_aliases() {
464 //- /main.rs crate:main deps:core
465 use core::result::Result::{self, Ok, Err};
467 type MyResult<T> = Result<T, ()>;
469 fn div(x: i32, y: i32) -> MyResult<i32> {
475 //- /core/lib.rs crate:core
477 pub enum Result<T, E> { Ok(T), Err(E) }
480 pub enum Option<T> { Some(T), None }
484 use core::result::Result::{self, Ok, Err};
486 type MyResult<T> = Result<T, ()>;
488 fn div(x: i32, y: i32) -> MyResult<i32> {
499 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
500 check_no_diagnostics(
502 //- /main.rs crate:main deps:core
503 use core::result::Result::{self, Ok, Err};
505 fn foo() -> Result<(), i32> { 0 }
507 //- /core/lib.rs crate:core
509 pub enum Result<T, E> { Ok(T), Err(E) }
512 pub enum Option<T> { Some(T), None }
519 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
520 check_no_diagnostics(
522 //- /main.rs crate:main deps:core
523 use core::result::Result::{self, Ok, Err};
525 enum SomeOtherEnum { Ok(i32), Err(String) }
527 fn foo() -> SomeOtherEnum { 0 }
529 //- /core/lib.rs crate:core
531 pub enum Result<T, E> { Ok(T), Err(E) }
534 pub enum Option<T> { Some(T), None }
541 fn test_fill_struct_fields_empty() {
544 struct TestStruct { one: i32, two: i64 }
547 let s = TestStruct {$0};
551 struct TestStruct { one: i32, two: i64 }
554 let s = TestStruct { one: (), two: ()};
561 fn test_fill_struct_fields_self() {
564 struct TestStruct { one: i32 }
567 fn test_fn() { let s = Self {$0}; }
571 struct TestStruct { one: i32 }
574 fn test_fn() { let s = Self { one: ()}; }
581 fn test_fill_struct_fields_enum() {
585 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
589 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
596 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
600 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
601 Expr::Bin { lhs: (), rhs: () }
609 fn test_fill_struct_fields_partial() {
612 struct TestStruct { one: i32, two: i64 }
615 let s = TestStruct{ two: 2$0 };
619 struct TestStruct { one: i32, two: i64 }
622 let s = TestStruct{ two: 2, one: () };
629 fn test_fill_struct_fields_no_diagnostic() {
630 check_no_diagnostics(
632 struct TestStruct { one: i32, two: i64 }
636 let s = TestStruct{ one, two: 2 };
643 fn test_fill_struct_fields_no_diagnostic_on_spread() {
644 check_no_diagnostics(
646 struct TestStruct { one: i32, two: i64 }
650 let s = TestStruct{ ..a };
657 fn test_unresolved_module_diagnostic() {
663 message: "unresolved module",
668 label: "Create module",
669 source_change: SourceChange {
670 source_file_edits: {},
673 dst: AnchoredPathBuf {
679 initial_contents: "",
684 fix_trigger_range: 0..8,
700 fn test_unresolved_macro_range() {
706 message: "unresolved macro call",
713 "unresolved-macro-call",
723 fn range_mapping_out_of_macros() {
724 // FIXME: this is very wrong, but somewhat tricky to fix.
731 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
734 let _x = id![Foo { a: $042 }];
737 pub struct Foo { pub a: i32, pub b: i32 }
744 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
747 let _x = id![Foo { a: 42 }];
750 pub struct Foo { pub a: i32, pub b: i32 }
756 fn test_check_unnecessary_braces_in_use_statement() {
757 check_no_diagnostics(
770 check_no_diagnostics(
828 mod a { mod c {} mod d { mod e {} } }
829 use a::{c, d::{e$0}};
832 mod a { mod c {} mod d { mod e {} } }
839 fn test_add_field_from_usage() {
843 Foo { bar: 3, baz$0: false};
851 Foo { bar: 3, baz: false};
862 fn test_add_field_in_other_file_from_usage() {
869 foo::Foo { bar: 3, $0baz: false};
886 fn test_disabled_diagnostics() {
887 let mut config = DiagnosticsConfig::default();
888 config.disabled.insert("unresolved-module".into());
890 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
892 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
893 assert!(diagnostics.is_empty());
895 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
896 assert!(!diagnostics.is_empty());
900 fn test_rename_incorrect_case() {
903 pub struct test_struct$0 { one: i32 }
905 pub fn some_fn(val: test_struct) -> test_struct {
906 test_struct { one: val.one + 1 }
910 pub struct TestStruct { one: i32 }
912 pub fn some_fn(val: TestStruct) -> TestStruct {
913 TestStruct { one: val.one + 1 }
920 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
925 pub fn some_fn(non_snake_case: u8) -> u8 {
933 pub fn SomeFn$0(val: u8) -> u8 {
934 if val != 0 { SomeFn(val - 1) } else { val }
938 pub fn some_fn(val: u8) -> u8 {
939 if val != 0 { some_fn(val - 1) } else { val }
947 let whatAWeird_Formatting$0 = 10;
948 another_func(whatAWeird_Formatting);
953 let what_a_weird_formatting = 10;
954 another_func(what_a_weird_formatting);
961 fn test_uppercase_const_no_diagnostics() {
962 check_no_diagnostics(
965 const ANOTHER_ITEM$0: &str = "some_item";
972 fn test_rename_incorrect_case_struct_method() {
975 pub struct TestStruct;
978 pub fn SomeFn$0() -> TestStruct {
984 pub struct TestStruct;
987 pub fn some_fn() -> TestStruct {
996 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
997 let input = r#"fn FOO$0() {}"#;
998 let expected = r#"fn foo() {}"#;
1000 let (analysis, file_position) = fixture::position(input);
1002 analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
1003 assert_eq!(diagnostics.len(), 1);
1005 check_fix(input, expected);
1009 fn unlinked_file_prepend_first_item() {
1010 cov_mark::check!(unlinked_file_prepend_before_first_item);
1027 fn unlinked_file_append_mod() {
1028 cov_mark::check!(unlinked_file_append_to_existing_mods);
1040 mod preexisting_bottom;)
1054 mod preexisting_bottom;)
1060 fn unlinked_file_insert_in_empty_file() {
1061 cov_mark::check!(unlinked_file_empty_file);
1075 fn unlinked_file_old_style_modrs() {
1093 fn unlinked_file_new_style_mod() {
1109 fn unlinked_file_with_cfg_off() {
1110 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1124 fn unlinked_file_with_cfg_on() {
1125 check_no_diagnostics(