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.
10 use std::cell::RefCell;
13 diagnostics::{Diagnostic as _, DiagnosticCode, DiagnosticSinkBuilder},
16 use ide_db::base_db::SourceDatabase;
17 use ide_db::RootDatabase;
18 use itertools::Itertools;
19 use rustc_hash::FxHashSet;
22 SyntaxNode, TextRange, T,
24 use text_edit::TextEdit;
26 use crate::{FileId, Label, SourceChange, SourceFileEdit};
28 use self::fixes::DiagnosticWithFix;
31 pub struct Diagnostic {
32 // pub name: Option<String>,
35 pub severity: Severity,
38 pub code: Option<DiagnosticCode>,
42 fn error(range: TextRange, message: String) -> Self {
43 Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
46 fn hint(range: TextRange, message: String) -> Self {
50 severity: Severity::WeakWarning,
57 fn with_fix(self, fix: Option<Fix>) -> Self {
61 fn with_unused(self, unused: bool) -> Self {
62 Self { unused, ..self }
65 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
73 pub source_change: SourceChange,
74 /// Allows to trigger the fix only when the caret is in the range given
75 pub fix_trigger_range: TextRange,
79 fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
80 let label = Label::new(label);
81 Self { label, source_change, fix_trigger_range }
85 #[derive(Debug, Copy, Clone)]
91 #[derive(Default, Debug, Clone)]
92 pub struct DiagnosticsConfig {
93 pub disable_experimental: bool,
94 pub disabled: FxHashSet<String>,
97 pub(crate) fn diagnostics(
99 config: &DiagnosticsConfig,
101 ) -> Vec<Diagnostic> {
102 let _p = profile::span("diagnostics");
103 let sema = Semantics::new(db);
104 let parse = db.parse(file_id);
105 let mut res = Vec::new();
107 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
113 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
116 for node in parse.tree().syntax().descendants() {
117 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
118 field_shorthand::check(&mut res, file_id, &node);
120 let res = RefCell::new(res);
121 let sink_builder = DiagnosticSinkBuilder::new()
122 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
123 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
125 .on::<hir::diagnostics::MissingFields, _>(|d| {
126 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
128 .on::<hir::diagnostics::MissingOkInTailExpr, _>(|d| {
129 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
131 .on::<hir::diagnostics::NoSuchField, _>(|d| {
132 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
134 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
135 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
137 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
138 res.borrow_mut().push(warning_with_fix(d, &sema));
140 .on::<hir::diagnostics::InactiveCode, _>(|d| {
141 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
142 if d.display_source().file_id.expansion_info(db).is_some() {
146 // Override severity and mark as unused.
147 res.borrow_mut().push(
148 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
150 .with_code(Some(d.code())),
153 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
154 // Use more accurate position if available.
156 d.precise_location.unwrap_or_else(|| sema.diagnostics_display_range(d).range);
158 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
160 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
162 // Only collect experimental diagnostics when they're enabled.
163 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
164 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
166 // Finalize the `DiagnosticSink` building process.
167 let mut sink = sink_builder
168 // Diagnostics not handled above get no fix and default treatment.
170 res.borrow_mut().push(
171 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
172 .with_code(Some(d.code())),
176 if let Some(m) = sema.to_module_def(file_id) {
177 m.diagnostics(db, &mut sink);
183 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
184 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
185 .with_fix(d.fix(&sema))
186 .with_code(Some(d.code()))
189 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
190 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
191 .with_fix(d.fix(&sema))
192 .with_code(Some(d.code()))
195 fn check_unnecessary_braces_in_use_statement(
196 acc: &mut Vec<Diagnostic>,
200 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
201 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
202 let use_range = use_tree_list.syntax().text_range();
204 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
206 let to_replace = single_use_tree.syntax().text().to_string();
207 let mut edit_builder = TextEdit::builder();
208 edit_builder.delete(use_range);
209 edit_builder.insert(use_range.start(), to_replace);
210 edit_builder.finish()
214 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
215 .with_fix(Some(Fix::new(
216 "Remove unnecessary braces",
217 SourceFileEdit { file_id, edit }.into(),
226 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
227 single_use_tree: &ast::UseTree,
228 ) -> Option<TextEdit> {
229 let use_tree_list_node = single_use_tree.syntax().parent()?;
230 if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
231 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
232 let end = use_tree_list_node.text_range().end();
233 return Some(TextEdit::delete(TextRange::new(start, end)));
240 use expect_test::{expect, Expect};
241 use stdx::trim_indent;
242 use test_utils::assert_eq_text;
244 use crate::{fixture, DiagnosticsConfig};
246 /// Takes a multi-file input fixture with annotated cursor positions,
248 /// * a diagnostic is produced
249 /// * this diagnostic fix trigger range touches the input cursor position
250 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
251 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
252 let after = trim_indent(ra_fixture_after);
254 let (analysis, file_position) = fixture::position(ra_fixture_before);
255 let diagnostic = analysis
256 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
260 let fix = diagnostic.fix.unwrap();
262 let file_id = fix.source_change.source_file_edits.first().unwrap().file_id;
263 let mut actual = analysis.file_text(file_id).unwrap().to_string();
265 // Go from the last one to the first one, so that ranges won't be affected by previous edits.
266 // FIXME: https://github.com/rust-analyzer/rust-analyzer/issues/4901#issuecomment-644675309
267 for edit in fix.source_change.source_file_edits.iter().rev() {
268 edit.edit.apply(&mut actual);
273 assert_eq_text!(&after, &actual);
275 fix.fix_trigger_range.contains_inclusive(file_position.offset),
276 "diagnostic fix range {:?} does not touch cursor position {:?}",
277 fix.fix_trigger_range,
282 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
283 /// apply to the file containing the cursor.
284 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
285 let (analysis, files) = fixture::files(ra_fixture);
286 let diagnostics = files
288 .flat_map(|file_id| {
289 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
291 .collect::<Vec<_>>();
292 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
295 fn check_expect(ra_fixture: &str, expect: Expect) {
296 let (analysis, file_id) = fixture::file(ra_fixture);
297 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
298 expect.assert_debug_eq(&diagnostics)
302 fn test_wrap_return_type() {
305 //- /main.rs crate:main deps:core
306 use core::result::Result::{self, Ok, Err};
308 fn div(x: i32, y: i32) -> Result<i32, ()> {
314 //- /core/lib.rs crate:core
316 pub enum Result<T, E> { Ok(T), Err(E) }
320 use core::result::Result::{self, Ok, Err};
322 fn div(x: i32, y: i32) -> Result<i32, ()> {
333 fn test_wrap_return_type_handles_generic_functions() {
336 //- /main.rs crate:main deps:core
337 use core::result::Result::{self, Ok, Err};
339 fn div<T>(x: T) -> Result<T, i32> {
345 //- /core/lib.rs crate:core
347 pub enum Result<T, E> { Ok(T), Err(E) }
351 use core::result::Result::{self, Ok, Err};
353 fn div<T>(x: T) -> Result<T, i32> {
364 fn test_wrap_return_type_handles_type_aliases() {
367 //- /main.rs crate:main deps:core
368 use core::result::Result::{self, Ok, Err};
370 type MyResult<T> = Result<T, ()>;
372 fn div(x: i32, y: i32) -> MyResult<i32> {
378 //- /core/lib.rs crate:core
380 pub enum Result<T, E> { Ok(T), Err(E) }
384 use core::result::Result::{self, Ok, Err};
386 type MyResult<T> = Result<T, ()>;
388 fn div(x: i32, y: i32) -> MyResult<i32> {
399 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
400 check_no_diagnostics(
402 //- /main.rs crate:main deps:core
403 use core::result::Result::{self, Ok, Err};
405 fn foo() -> Result<(), i32> { 0 }
407 //- /core/lib.rs crate:core
409 pub enum Result<T, E> { Ok(T), Err(E) }
416 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
417 check_no_diagnostics(
419 //- /main.rs crate:main deps:core
420 use core::result::Result::{self, Ok, Err};
422 enum SomeOtherEnum { Ok(i32), Err(String) }
424 fn foo() -> SomeOtherEnum { 0 }
426 //- /core/lib.rs crate:core
428 pub enum Result<T, E> { Ok(T), Err(E) }
435 fn test_fill_struct_fields_empty() {
438 struct TestStruct { one: i32, two: i64 }
441 let s = TestStruct {<|>};
445 struct TestStruct { one: i32, two: i64 }
448 let s = TestStruct { one: (), two: ()};
455 fn test_fill_struct_fields_self() {
458 struct TestStruct { one: i32 }
461 fn test_fn() { let s = Self {<|>}; }
465 struct TestStruct { one: i32 }
468 fn test_fn() { let s = Self { one: ()}; }
475 fn test_fill_struct_fields_enum() {
479 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
483 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
490 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
494 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
495 Expr::Bin { lhs: (), rhs: () }
503 fn test_fill_struct_fields_partial() {
506 struct TestStruct { one: i32, two: i64 }
509 let s = TestStruct{ two: 2<|> };
513 struct TestStruct { one: i32, two: i64 }
516 let s = TestStruct{ two: 2, one: () };
523 fn test_fill_struct_fields_no_diagnostic() {
524 check_no_diagnostics(
526 struct TestStruct { one: i32, two: i64 }
530 let s = TestStruct{ one, two: 2 };
537 fn test_fill_struct_fields_no_diagnostic_on_spread() {
538 check_no_diagnostics(
540 struct TestStruct { one: i32, two: i64 }
544 let s = TestStruct{ ..a };
551 fn test_unresolved_module_diagnostic() {
557 message: "unresolved module",
562 label: "Create module",
563 source_change: SourceChange {
564 source_file_edits: [],
567 dst: AnchoredPathBuf {
573 initial_contents: "",
578 fix_trigger_range: 0..8,
594 fn range_mapping_out_of_macros() {
595 // FIXME: this is very wrong, but somewhat tricky to fix.
602 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
605 let _x = id![Foo { a: <|>42 }];
608 pub struct Foo { pub a: i32, pub b: i32 }
615 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
618 let _x = id![Foo { a: 42 }];
621 pub struct Foo { pub a: i32, pub b: i32 }
627 fn test_check_unnecessary_braces_in_use_statement() {
628 check_no_diagnostics(
683 mod a { mod c {} mod d { mod e {} } }
684 use a::{c, d::{e<|>}};
687 mod a { mod c {} mod d { mod e {} } }
694 fn test_add_field_from_usage() {
698 Foo { bar: 3, baz<|>: false};
706 Foo { bar: 3, baz: false};
717 fn test_add_field_in_other_file_from_usage() {
724 foo::Foo { bar: 3, <|>baz: false};
741 fn test_disabled_diagnostics() {
742 let mut config = DiagnosticsConfig::default();
743 config.disabled.insert("unresolved-module".into());
745 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
747 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
748 assert!(diagnostics.is_empty());
750 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
751 assert!(!diagnostics.is_empty());
755 fn test_rename_incorrect_case() {
758 pub struct test_struct<|> { one: i32 }
760 pub fn some_fn(val: test_struct) -> test_struct {
761 test_struct { one: val.one + 1 }
765 pub struct TestStruct { one: i32 }
767 pub fn some_fn(val: TestStruct) -> TestStruct {
768 TestStruct { one: val.one + 1 }
775 pub fn some_fn(NonSnakeCase<|>: u8) -> u8 {
780 pub fn some_fn(non_snake_case: u8) -> u8 {
788 pub fn SomeFn<|>(val: u8) -> u8 {
789 if val != 0 { SomeFn(val - 1) } else { val }
793 pub fn some_fn(val: u8) -> u8 {
794 if val != 0 { some_fn(val - 1) } else { val }
802 let whatAWeird_Formatting<|> = 10;
803 another_func(whatAWeird_Formatting);
808 let what_a_weird_formatting = 10;
809 another_func(what_a_weird_formatting);
816 fn test_uppercase_const_no_diagnostics() {
817 check_no_diagnostics(
820 const ANOTHER_ITEM<|>: &str = "some_item";
827 fn test_rename_incorrect_case_struct_method() {
830 pub struct TestStruct;
833 pub fn SomeFn<|>() -> TestStruct {
839 pub struct TestStruct;
842 pub fn some_fn() -> TestStruct {
851 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
852 let input = r#"fn FOO<|>() {}"#;
853 let expected = r#"fn foo() {}"#;
855 let (analysis, file_position) = fixture::position(input);
857 analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
858 assert_eq!(diagnostics.len(), 1);
860 check_fix(input, expected);