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::IncorrectCase, _>(|d| {
135 res.borrow_mut().push(warning_with_fix(d, &sema));
137 .on::<hir::diagnostics::InactiveCode, _>(|d| {
138 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
139 if d.display_source().file_id.expansion_info(db).is_some() {
143 // Override severity and mark as unused.
144 res.borrow_mut().push(
145 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
147 .with_code(Some(d.code())),
150 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
151 // Use more accurate position if available.
153 d.precise_location.unwrap_or_else(|| sema.diagnostics_display_range(d).range);
155 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
157 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
159 // Only collect experimental diagnostics when they're enabled.
160 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
161 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
163 // Finalize the `DiagnosticSink` building process.
164 let mut sink = sink_builder
165 // Diagnostics not handled above get no fix and default treatment.
167 res.borrow_mut().push(
168 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
169 .with_code(Some(d.code())),
173 if let Some(m) = sema.to_module_def(file_id) {
174 m.diagnostics(db, &mut sink);
180 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
181 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
182 .with_fix(d.fix(&sema))
183 .with_code(Some(d.code()))
186 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
187 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
188 .with_fix(d.fix(&sema))
189 .with_code(Some(d.code()))
192 fn check_unnecessary_braces_in_use_statement(
193 acc: &mut Vec<Diagnostic>,
197 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
198 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
199 let use_range = use_tree_list.syntax().text_range();
201 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
203 let to_replace = single_use_tree.syntax().text().to_string();
204 let mut edit_builder = TextEdit::builder();
205 edit_builder.delete(use_range);
206 edit_builder.insert(use_range.start(), to_replace);
207 edit_builder.finish()
211 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
212 .with_fix(Some(Fix::new(
213 "Remove unnecessary braces",
214 SourceFileEdit { file_id, edit }.into(),
223 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
224 single_use_tree: &ast::UseTree,
225 ) -> Option<TextEdit> {
226 let use_tree_list_node = single_use_tree.syntax().parent()?;
227 if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
228 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
229 let end = use_tree_list_node.text_range().end();
230 return Some(TextEdit::delete(TextRange::new(start, end)));
237 use expect_test::{expect, Expect};
238 use stdx::trim_indent;
239 use test_utils::assert_eq_text;
241 use crate::{fixture, DiagnosticsConfig};
243 /// Takes a multi-file input fixture with annotated cursor positions,
245 /// * a diagnostic is produced
246 /// * this diagnostic fix trigger range touches the input cursor position
247 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
248 pub(super) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
249 let after = trim_indent(ra_fixture_after);
251 let (analysis, file_position) = fixture::position(ra_fixture_before);
252 let diagnostic = analysis
253 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
257 let mut fix = diagnostic.fix.unwrap();
258 let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
259 let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
261 let mut actual = target_file_contents.to_string();
262 edit.apply(&mut actual);
266 assert_eq_text!(&after, &actual);
268 fix.fix_trigger_range.contains_inclusive(file_position.offset),
269 "diagnostic fix range {:?} does not touch cursor position {:?}",
270 fix.fix_trigger_range,
275 /// Similar to `check_fix`, but applies all the available fixes.
276 fn check_fixes(ra_fixture_before: &str, ra_fixture_after: &str) {
277 let after = trim_indent(ra_fixture_after);
279 let (analysis, file_position) = fixture::position(ra_fixture_before);
280 let diagnostic = analysis
281 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
285 let fix = diagnostic.fix.unwrap();
286 let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
288 let mut actual = target_file_contents.to_string();
289 // Go from the last one to the first one, so that ranges won't be affected by previous edits.
290 for edit in fix.source_change.source_file_edits.iter().rev() {
291 edit.edit.apply(&mut actual);
296 assert_eq_text!(&after, &actual);
298 fix.fix_trigger_range.contains_inclusive(file_position.offset),
299 "diagnostic fix range {:?} does not touch cursor position {:?}",
300 fix.fix_trigger_range,
305 /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
306 /// which has a fix that can apply to other files.
307 fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
308 let ra_fixture_after = &trim_indent(ra_fixture_after);
309 let (analysis, file_pos) = fixture::position(ra_fixture_before);
310 let current_file_id = file_pos.file_id;
311 let diagnostic = analysis
312 .diagnostics(&DiagnosticsConfig::default(), current_file_id)
316 let mut fix = diagnostic.fix.unwrap();
317 let edit = fix.source_change.source_file_edits.pop().unwrap();
318 let changed_file_id = edit.file_id;
319 let before = analysis.file_text(changed_file_id).unwrap();
321 let mut actual = before.to_string();
322 edit.edit.apply(&mut actual);
325 assert_eq_text!(ra_fixture_after, &actual);
328 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
329 /// apply to the file containing the cursor.
330 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
331 let (analysis, files) = fixture::files(ra_fixture);
332 let diagnostics = files
334 .flat_map(|file_id| {
335 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
337 .collect::<Vec<_>>();
338 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
341 fn check_expect(ra_fixture: &str, expect: Expect) {
342 let (analysis, file_id) = fixture::file(ra_fixture);
343 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
344 expect.assert_debug_eq(&diagnostics)
348 fn test_wrap_return_type() {
351 //- /main.rs crate:main deps:core
352 use core::result::Result::{self, Ok, Err};
354 fn div(x: i32, y: i32) -> Result<i32, ()> {
360 //- /core/lib.rs crate:core
362 pub enum Result<T, E> { Ok(T), Err(E) }
366 use core::result::Result::{self, Ok, Err};
368 fn div(x: i32, y: i32) -> Result<i32, ()> {
379 fn test_wrap_return_type_handles_generic_functions() {
382 //- /main.rs crate:main deps:core
383 use core::result::Result::{self, Ok, Err};
385 fn div<T>(x: T) -> Result<T, i32> {
391 //- /core/lib.rs crate:core
393 pub enum Result<T, E> { Ok(T), Err(E) }
397 use core::result::Result::{self, Ok, Err};
399 fn div<T>(x: T) -> Result<T, i32> {
410 fn test_wrap_return_type_handles_type_aliases() {
413 //- /main.rs crate:main deps:core
414 use core::result::Result::{self, Ok, Err};
416 type MyResult<T> = Result<T, ()>;
418 fn div(x: i32, y: i32) -> MyResult<i32> {
424 //- /core/lib.rs crate:core
426 pub enum Result<T, E> { Ok(T), Err(E) }
430 use core::result::Result::{self, Ok, Err};
432 type MyResult<T> = Result<T, ()>;
434 fn div(x: i32, y: i32) -> MyResult<i32> {
445 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
446 check_no_diagnostics(
448 //- /main.rs crate:main deps:core
449 use core::result::Result::{self, Ok, Err};
451 fn foo() -> Result<(), i32> { 0 }
453 //- /core/lib.rs crate:core
455 pub enum Result<T, E> { Ok(T), Err(E) }
462 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
463 check_no_diagnostics(
465 //- /main.rs crate:main deps:core
466 use core::result::Result::{self, Ok, Err};
468 enum SomeOtherEnum { Ok(i32), Err(String) }
470 fn foo() -> SomeOtherEnum { 0 }
472 //- /core/lib.rs crate:core
474 pub enum Result<T, E> { Ok(T), Err(E) }
481 fn test_fill_struct_fields_empty() {
484 struct TestStruct { one: i32, two: i64 }
487 let s = TestStruct {<|>};
491 struct TestStruct { one: i32, two: i64 }
494 let s = TestStruct { one: (), two: ()};
501 fn test_fill_struct_fields_self() {
504 struct TestStruct { one: i32 }
507 fn test_fn() { let s = Self {<|>}; }
511 struct TestStruct { one: i32 }
514 fn test_fn() { let s = Self { one: ()}; }
521 fn test_fill_struct_fields_enum() {
525 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
529 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
536 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
540 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
541 Expr::Bin { lhs: (), rhs: () }
549 fn test_fill_struct_fields_partial() {
552 struct TestStruct { one: i32, two: i64 }
555 let s = TestStruct{ two: 2<|> };
559 struct TestStruct { one: i32, two: i64 }
562 let s = TestStruct{ two: 2, one: () };
569 fn test_fill_struct_fields_no_diagnostic() {
570 check_no_diagnostics(
572 struct TestStruct { one: i32, two: i64 }
576 let s = TestStruct{ one, two: 2 };
583 fn test_fill_struct_fields_no_diagnostic_on_spread() {
584 check_no_diagnostics(
586 struct TestStruct { one: i32, two: i64 }
590 let s = TestStruct{ ..a };
597 fn test_unresolved_module_diagnostic() {
603 message: "unresolved module",
608 label: "Create module",
609 source_change: SourceChange {
610 source_file_edits: [],
613 dst: AnchoredPathBuf {
623 fix_trigger_range: 0..8,
639 fn range_mapping_out_of_macros() {
640 // FIXME: this is very wrong, but somewhat tricky to fix.
647 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
650 let _x = id![Foo { a: <|>42 }];
653 pub struct Foo { pub a: i32, pub b: i32 }
660 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
663 let _x = id![Foo { a: 42 }];
666 pub struct Foo { pub a: i32, pub b: i32 }
672 fn test_check_unnecessary_braces_in_use_statement() {
673 check_no_diagnostics(
728 mod a { mod c {} mod d { mod e {} } }
729 use a::{c, d::{e<|>}};
732 mod a { mod c {} mod d { mod e {} } }
739 fn test_add_field_from_usage() {
743 Foo { bar: 3, baz<|>: false};
751 Foo { bar: 3, baz: false};
762 fn test_add_field_in_other_file_from_usage() {
763 check_apply_diagnostic_fix_in_other_file(
769 <|>foo::Foo { bar: 3, baz: false};
786 fn test_disabled_diagnostics() {
787 let mut config = DiagnosticsConfig::default();
788 config.disabled.insert("unresolved-module".into());
790 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
792 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
793 assert!(diagnostics.is_empty());
795 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
796 assert!(!diagnostics.is_empty());
800 fn test_rename_incorrect_case() {
803 pub struct test_struct<|> { one: i32 }
805 pub fn some_fn(val: test_struct) -> test_struct {
806 test_struct { one: val.one + 1 }
810 pub struct TestStruct { one: i32 }
812 pub fn some_fn(val: TestStruct) -> TestStruct {
813 TestStruct { one: val.one + 1 }
820 pub fn some_fn(NonSnakeCase<|>: u8) -> u8 {
825 pub fn some_fn(non_snake_case: u8) -> u8 {
833 pub fn SomeFn<|>(val: u8) -> u8 {
834 if val != 0 { SomeFn(val - 1) } else { val }
838 pub fn some_fn(val: u8) -> u8 {
839 if val != 0 { some_fn(val - 1) } else { val }
847 let whatAWeird_Formatting<|> = 10;
848 another_func(whatAWeird_Formatting);
853 let what_a_weird_formatting = 10;
854 another_func(what_a_weird_formatting);
861 fn test_uppercase_const_no_diagnostics() {
862 check_no_diagnostics(
865 const ANOTHER_ITEM<|>: &str = "some_item";
872 fn test_rename_incorrect_case_struct_method() {
875 pub struct TestStruct;
878 pub fn SomeFn<|>() -> TestStruct {
884 pub struct TestStruct;
887 pub fn some_fn() -> TestStruct {