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::DiagnosticWithFix;
34 pub struct Diagnostic {
35 // pub name: Option<String>,
38 pub severity: Severity,
39 pub fix: Option<Assist>,
41 pub code: Option<DiagnosticCode>,
45 fn error(range: TextRange, message: String) -> Self {
46 Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
49 fn hint(range: TextRange, message: String) -> Self {
53 severity: Severity::WeakWarning,
60 fn with_fix(self, fix: Option<Assist>) -> 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_fix(d.fix(&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 // Only collect experimental diagnostics when they're enabled.
186 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
187 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
189 // Finalize the `DiagnosticSink` building process.
190 let mut sink = sink_builder
191 // Diagnostics not handled above get no fix and default treatment.
193 res.borrow_mut().push(
195 sema.diagnostics_display_range(d.display_source()).range,
198 .with_code(Some(d.code())),
202 match sema.to_module_def(file_id) {
203 Some(m) => m.diagnostics(db, &mut sink),
205 sink.push(UnlinkedFile { file_id, node: SyntaxNodePtr::new(&parse.tree().syntax()) });
213 fn diagnostic_with_fix<D: DiagnosticWithFix>(
215 sema: &Semantics<RootDatabase>,
216 resolve: &AssistResolveStrategy,
218 Diagnostic::error(sema.diagnostics_display_range(d.display_source()).range, d.message())
219 .with_fix(d.fix(&sema, resolve))
220 .with_code(Some(d.code()))
223 fn warning_with_fix<D: DiagnosticWithFix>(
225 sema: &Semantics<RootDatabase>,
226 resolve: &AssistResolveStrategy,
228 Diagnostic::hint(sema.diagnostics_display_range(d.display_source()).range, d.message())
229 .with_fix(d.fix(&sema, resolve))
230 .with_code(Some(d.code()))
233 fn check_unnecessary_braces_in_use_statement(
234 acc: &mut Vec<Diagnostic>,
238 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
239 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
240 // If there is a comment inside the bracketed `use`,
241 // assume it is a commented out module path and don't show diagnostic.
242 if use_tree_list.has_inner_comment() {
246 let use_range = use_tree_list.syntax().text_range();
248 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
250 let to_replace = single_use_tree.syntax().text().to_string();
251 let mut edit_builder = TextEdit::builder();
252 edit_builder.delete(use_range);
253 edit_builder.insert(use_range.start(), to_replace);
254 edit_builder.finish()
258 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
261 "Remove unnecessary braces",
262 SourceChange::from_text_edit(file_id, edit),
271 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
272 single_use_tree: &ast::UseTree,
273 ) -> Option<TextEdit> {
274 let use_tree_list_node = single_use_tree.syntax().parent()?;
275 if single_use_tree.path()?.segment()?.self_token().is_some() {
276 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
277 let end = use_tree_list_node.text_range().end();
278 return Some(TextEdit::delete(TextRange::new(start, end)));
283 fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
284 let mut res = unresolved_fix(id, label, target);
285 res.source_change = Some(source_change);
289 fn unresolved_fix(id: &'static str, label: &str, target: TextRange) -> Assist {
290 assert!(!id.contains(' '));
292 id: AssistId(id, AssistKind::QuickFix),
293 label: Label::new(label),
302 use expect_test::{expect, Expect};
303 use ide_assists::AssistResolveStrategy;
304 use stdx::trim_indent;
305 use test_utils::assert_eq_text;
307 use crate::{fixture, DiagnosticsConfig};
309 /// Takes a multi-file input fixture with annotated cursor positions,
311 /// * a diagnostic is produced
312 /// * this diagnostic fix trigger range touches the input cursor position
313 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
314 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
315 let after = trim_indent(ra_fixture_after);
317 let (analysis, file_position) = fixture::position(ra_fixture_before);
318 let diagnostic = analysis
320 &DiagnosticsConfig::default(),
321 AssistResolveStrategy::All,
322 file_position.file_id,
327 let fix = diagnostic.fix.unwrap();
329 let source_change = fix.source_change.unwrap();
330 let file_id = *source_change.source_file_edits.keys().next().unwrap();
331 let mut actual = analysis.file_text(file_id).unwrap().to_string();
333 for edit in source_change.source_file_edits.values() {
334 edit.apply(&mut actual);
339 assert_eq_text!(&after, &actual);
341 fix.target.contains_inclusive(file_position.offset),
342 "diagnostic fix range {:?} does not touch cursor position {:?}",
348 /// Checks that there's a diagnostic *without* fix at `$0`.
349 fn check_no_fix(ra_fixture: &str) {
350 let (analysis, file_position) = fixture::position(ra_fixture);
351 let diagnostic = analysis
353 &DiagnosticsConfig::default(),
354 AssistResolveStrategy::All,
355 file_position.file_id,
360 assert!(diagnostic.fix.is_none(), "got a fix when none was expected: {:?}", diagnostic);
363 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
364 /// apply to the file containing the cursor.
365 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
366 let (analysis, files) = fixture::files(ra_fixture);
367 let diagnostics = files
369 .flat_map(|file_id| {
371 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
374 .collect::<Vec<_>>();
375 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
378 fn check_expect(ra_fixture: &str, expect: Expect) {
379 let (analysis, file_id) = fixture::file(ra_fixture);
380 let diagnostics = analysis
381 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
383 expect.assert_debug_eq(&diagnostics)
387 fn test_wrap_return_type_option() {
390 //- /main.rs crate:main deps:core
391 use core::option::Option::{self, Some, None};
393 fn div(x: i32, y: i32) -> Option<i32> {
399 //- /core/lib.rs crate:core
401 pub enum Result<T, E> { Ok(T), Err(E) }
404 pub enum Option<T> { Some(T), None }
408 use core::option::Option::{self, Some, None};
410 fn div(x: i32, y: i32) -> Option<i32> {
421 fn test_wrap_return_type() {
424 //- /main.rs crate:main deps:core
425 use core::result::Result::{self, Ok, Err};
427 fn div(x: i32, y: i32) -> Result<i32, ()> {
433 //- /core/lib.rs crate:core
435 pub enum Result<T, E> { Ok(T), Err(E) }
438 pub enum Option<T> { Some(T), None }
442 use core::result::Result::{self, Ok, Err};
444 fn div(x: i32, y: i32) -> Result<i32, ()> {
455 fn test_wrap_return_type_handles_generic_functions() {
458 //- /main.rs crate:main deps:core
459 use core::result::Result::{self, Ok, Err};
461 fn div<T>(x: T) -> Result<T, i32> {
467 //- /core/lib.rs crate:core
469 pub enum Result<T, E> { Ok(T), Err(E) }
472 pub enum Option<T> { Some(T), None }
476 use core::result::Result::{self, Ok, Err};
478 fn div<T>(x: T) -> Result<T, i32> {
489 fn test_wrap_return_type_handles_type_aliases() {
492 //- /main.rs crate:main deps:core
493 use core::result::Result::{self, Ok, Err};
495 type MyResult<T> = Result<T, ()>;
497 fn div(x: i32, y: i32) -> MyResult<i32> {
503 //- /core/lib.rs crate:core
505 pub enum Result<T, E> { Ok(T), Err(E) }
508 pub enum Option<T> { Some(T), None }
512 use core::result::Result::{self, Ok, Err};
514 type MyResult<T> = Result<T, ()>;
516 fn div(x: i32, y: i32) -> MyResult<i32> {
527 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
528 check_no_diagnostics(
530 //- /main.rs crate:main deps:core
531 use core::result::Result::{self, Ok, Err};
533 fn foo() -> Result<(), i32> { 0 }
535 //- /core/lib.rs crate:core
537 pub enum Result<T, E> { Ok(T), Err(E) }
540 pub enum Option<T> { Some(T), None }
547 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
548 check_no_diagnostics(
550 //- /main.rs crate:main deps:core
551 use core::result::Result::{self, Ok, Err};
553 enum SomeOtherEnum { Ok(i32), Err(String) }
555 fn foo() -> SomeOtherEnum { 0 }
557 //- /core/lib.rs crate:core
559 pub enum Result<T, E> { Ok(T), Err(E) }
562 pub enum Option<T> { Some(T), None }
569 fn test_fill_struct_fields_empty() {
572 struct TestStruct { one: i32, two: i64 }
575 let s = TestStruct {$0};
579 struct TestStruct { one: i32, two: i64 }
582 let s = TestStruct { one: (), two: ()};
589 fn test_fill_struct_fields_self() {
592 struct TestStruct { one: i32 }
595 fn test_fn() { let s = Self {$0}; }
599 struct TestStruct { one: i32 }
602 fn test_fn() { let s = Self { one: ()}; }
609 fn test_fill_struct_fields_enum() {
613 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
617 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
624 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
628 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
629 Expr::Bin { lhs: (), rhs: () }
637 fn test_fill_struct_fields_partial() {
640 struct TestStruct { one: i32, two: i64 }
643 let s = TestStruct{ two: 2$0 };
647 struct TestStruct { one: i32, two: i64 }
650 let s = TestStruct{ two: 2, one: () };
657 fn test_fill_struct_fields_no_diagnostic() {
658 check_no_diagnostics(
660 struct TestStruct { one: i32, two: i64 }
664 let s = TestStruct{ one, two: 2 };
671 fn test_fill_struct_fields_no_diagnostic_on_spread() {
672 check_no_diagnostics(
674 struct TestStruct { one: i32, two: i64 }
678 let s = TestStruct{ ..a };
685 fn test_unresolved_module_diagnostic() {
691 message: "unresolved module",
700 label: "Create module",
705 source_file_edits: {},
708 dst: AnchoredPathBuf {
714 initial_contents: "",
735 fn test_unresolved_macro_range() {
741 message: "unresolved macro `foo::bar!`",
748 "unresolved-macro-call",
758 fn range_mapping_out_of_macros() {
759 // FIXME: this is very wrong, but somewhat tricky to fix.
766 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
769 let _x = id![Foo { a: $042 }];
772 pub struct Foo { pub a: i32, pub b: i32 }
779 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
782 let _x = id![Foo { a: 42 }];
785 pub struct Foo { pub a: i32, pub b: i32 }
791 fn test_check_unnecessary_braces_in_use_statement() {
792 check_no_diagnostics(
805 check_no_diagnostics(
863 mod a { mod c {} mod d { mod e {} } }
864 use a::{c, d::{e$0}};
867 mod a { mod c {} mod d { mod e {} } }
874 fn test_add_field_from_usage() {
878 Foo { bar: 3, baz$0: false};
886 Foo { bar: 3, baz: false};
897 fn test_add_field_in_other_file_from_usage() {
904 foo::Foo { bar: 3, $0baz: false};
921 fn test_disabled_diagnostics() {
922 let mut config = DiagnosticsConfig::default();
923 config.disabled.insert("unresolved-module".into());
925 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
928 analysis.diagnostics(&config, AssistResolveStrategy::All, file_id).unwrap();
929 assert!(diagnostics.is_empty());
931 let diagnostics = analysis
932 .diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::All, file_id)
934 assert!(!diagnostics.is_empty());
938 fn test_rename_incorrect_case() {
941 pub struct test_struct$0 { one: i32 }
943 pub fn some_fn(val: test_struct) -> test_struct {
944 test_struct { one: val.one + 1 }
948 pub struct TestStruct { one: i32 }
950 pub fn some_fn(val: TestStruct) -> TestStruct {
951 TestStruct { one: val.one + 1 }
958 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
963 pub fn some_fn(non_snake_case: u8) -> u8 {
971 pub fn SomeFn$0(val: u8) -> u8 {
972 if val != 0 { SomeFn(val - 1) } else { val }
976 pub fn some_fn(val: u8) -> u8 {
977 if val != 0 { some_fn(val - 1) } else { val }
985 let whatAWeird_Formatting$0 = 10;
986 another_func(whatAWeird_Formatting);
991 let what_a_weird_formatting = 10;
992 another_func(what_a_weird_formatting);
999 fn test_uppercase_const_no_diagnostics() {
1000 check_no_diagnostics(
1003 const ANOTHER_ITEM$0: &str = "some_item";
1010 fn test_rename_incorrect_case_struct_method() {
1013 pub struct TestStruct;
1016 pub fn SomeFn$0() -> TestStruct {
1022 pub struct TestStruct;
1025 pub fn some_fn() -> TestStruct {
1034 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
1035 let input = r#"fn FOO$0() {}"#;
1036 let expected = r#"fn foo() {}"#;
1038 let (analysis, file_position) = fixture::position(input);
1039 let diagnostics = analysis
1041 &DiagnosticsConfig::default(),
1042 AssistResolveStrategy::All,
1043 file_position.file_id,
1046 assert_eq!(diagnostics.len(), 1);
1048 check_fix(input, expected);
1052 fn unlinked_file_prepend_first_item() {
1053 cov_mark::check!(unlinked_file_prepend_before_first_item);
1070 fn unlinked_file_append_mod() {
1071 cov_mark::check!(unlinked_file_append_to_existing_mods);
1083 mod preexisting_bottom;)
1097 mod preexisting_bottom;)
1103 fn unlinked_file_insert_in_empty_file() {
1104 cov_mark::check!(unlinked_file_empty_file);
1118 fn unlinked_file_old_style_modrs() {
1136 fn unlinked_file_new_style_mod() {
1152 fn unlinked_file_with_cfg_off() {
1153 cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists);
1167 fn unlinked_file_with_cfg_on() {
1168 check_no_diagnostics(