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, source_change::SourceFileEdits, RootDatabase};
17 use itertools::Itertools;
18 use rustc_hash::FxHashSet;
21 SyntaxNode, TextRange, T,
23 use text_edit::TextEdit;
25 use crate::{FileId, Label, SourceChange};
27 use self::fixes::DiagnosticWithFix;
30 pub struct Diagnostic {
31 // pub name: Option<String>,
34 pub severity: Severity,
37 pub code: Option<DiagnosticCode>,
41 fn error(range: TextRange, message: String) -> Self {
42 Self { message, range, severity: Severity::Error, fix: None, unused: false, code: None }
45 fn hint(range: TextRange, message: String) -> Self {
49 severity: Severity::WeakWarning,
56 fn with_fix(self, fix: Option<Fix>) -> Self {
60 fn with_unused(self, unused: bool) -> Self {
61 Self { unused, ..self }
64 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
72 pub source_change: SourceChange,
73 /// Allows to trigger the fix only when the caret is in the range given
74 pub fix_trigger_range: TextRange,
78 fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
79 let label = Label::new(label);
80 Self { label, source_change, fix_trigger_range }
84 #[derive(Debug, Copy, Clone)]
90 #[derive(Default, Debug, Clone)]
91 pub struct DiagnosticsConfig {
92 pub disable_experimental: bool,
93 pub disabled: FxHashSet<String>,
96 pub(crate) fn diagnostics(
98 config: &DiagnosticsConfig,
100 ) -> Vec<Diagnostic> {
101 let _p = profile::span("diagnostics");
102 let sema = Semantics::new(db);
103 let parse = db.parse(file_id);
104 let mut res = Vec::new();
106 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
112 .map(|err| Diagnostic::error(err.range(), format!("Syntax Error: {}", err))),
115 for node in parse.tree().syntax().descendants() {
116 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
117 field_shorthand::check(&mut res, file_id, &node);
119 let res = RefCell::new(res);
120 let sink_builder = DiagnosticSinkBuilder::new()
121 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
122 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
124 .on::<hir::diagnostics::MissingFields, _>(|d| {
125 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
127 .on::<hir::diagnostics::MissingOkOrSomeInTailExpr, _>(|d| {
128 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
130 .on::<hir::diagnostics::NoSuchField, _>(|d| {
131 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
133 .on::<hir::diagnostics::RemoveThisSemicolon, _>(|d| {
134 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
136 .on::<hir::diagnostics::IncorrectCase, _>(|d| {
137 res.borrow_mut().push(warning_with_fix(d, &sema));
139 .on::<hir::diagnostics::InactiveCode, _>(|d| {
140 // If there's inactive code somewhere in a macro, don't propagate to the call-site.
141 if d.display_source().file_id.expansion_info(db).is_some() {
145 // Override severity and mark as unused.
146 res.borrow_mut().push(
147 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
149 .with_code(Some(d.code())),
152 .on::<hir::diagnostics::UnresolvedProcMacro, _>(|d| {
153 // Use more accurate position if available.
155 d.precise_location.unwrap_or_else(|| sema.diagnostics_display_range(d).range);
157 // FIXME: it would be nice to tell the user whether proc macros are currently disabled
159 .push(Diagnostic::hint(display_range, d.message()).with_code(Some(d.code())));
161 // Only collect experimental diagnostics when they're enabled.
162 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
163 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
165 // Finalize the `DiagnosticSink` building process.
166 let mut sink = sink_builder
167 // Diagnostics not handled above get no fix and default treatment.
169 res.borrow_mut().push(
170 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
171 .with_code(Some(d.code())),
175 if let Some(m) = sema.to_module_def(file_id) {
176 m.diagnostics(db, &mut sink);
182 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
183 Diagnostic::error(sema.diagnostics_display_range(d).range, d.message())
184 .with_fix(d.fix(&sema))
185 .with_code(Some(d.code()))
188 fn warning_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
189 Diagnostic::hint(sema.diagnostics_display_range(d).range, d.message())
190 .with_fix(d.fix(&sema))
191 .with_code(Some(d.code()))
194 fn check_unnecessary_braces_in_use_statement(
195 acc: &mut Vec<Diagnostic>,
199 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
200 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
201 // If there is a comment inside the bracketed `use`,
202 // assume it is a commented out module path and don't show diagnostic.
203 if use_tree_list.has_inner_comment() {
207 let use_range = use_tree_list.syntax().text_range();
209 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
211 let to_replace = single_use_tree.syntax().text().to_string();
212 let mut edit_builder = TextEdit::builder();
213 edit_builder.delete(use_range);
214 edit_builder.insert(use_range.start(), to_replace);
215 edit_builder.finish()
219 Diagnostic::hint(use_range, "Unnecessary braces in use statement".to_string())
220 .with_fix(Some(Fix::new(
221 "Remove unnecessary braces",
222 SourceFileEdits::from_text_edit(file_id, edit).into(),
231 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
232 single_use_tree: &ast::UseTree,
233 ) -> Option<TextEdit> {
234 let use_tree_list_node = single_use_tree.syntax().parent()?;
235 if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
236 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
237 let end = use_tree_list_node.text_range().end();
238 return Some(TextEdit::delete(TextRange::new(start, end)));
245 use expect_test::{expect, Expect};
246 use stdx::trim_indent;
247 use test_utils::assert_eq_text;
249 use crate::{fixture, DiagnosticsConfig};
251 /// Takes a multi-file input fixture with annotated cursor positions,
253 /// * a diagnostic is produced
254 /// * this diagnostic fix trigger range touches the input cursor position
255 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
256 pub(crate) fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
257 let after = trim_indent(ra_fixture_after);
259 let (analysis, file_position) = fixture::position(ra_fixture_before);
260 let diagnostic = analysis
261 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
265 let fix = diagnostic.fix.unwrap();
267 let file_id = *fix.source_change.source_file_edits.edits.keys().next().unwrap();
268 let mut actual = analysis.file_text(file_id).unwrap().to_string();
270 for edit in fix.source_change.source_file_edits.edits.values() {
271 edit.apply(&mut actual);
276 assert_eq_text!(&after, &actual);
278 fix.fix_trigger_range.contains_inclusive(file_position.offset),
279 "diagnostic fix range {:?} does not touch cursor position {:?}",
280 fix.fix_trigger_range,
285 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
286 /// apply to the file containing the cursor.
287 pub(crate) fn check_no_diagnostics(ra_fixture: &str) {
288 let (analysis, files) = fixture::files(ra_fixture);
289 let diagnostics = files
291 .flat_map(|file_id| {
292 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
294 .collect::<Vec<_>>();
295 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
298 fn check_expect(ra_fixture: &str, expect: Expect) {
299 let (analysis, file_id) = fixture::file(ra_fixture);
300 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
301 expect.assert_debug_eq(&diagnostics)
305 fn test_wrap_return_type_option() {
308 //- /main.rs crate:main deps:core
309 use core::option::Option::{self, Some, None};
311 fn div(x: i32, y: i32) -> Option<i32> {
317 //- /core/lib.rs crate:core
319 pub enum Result<T, E> { Ok(T), Err(E) }
322 pub enum Option<T> { Some(T), None }
326 use core::option::Option::{self, Some, None};
328 fn div(x: i32, y: i32) -> Option<i32> {
339 fn test_wrap_return_type() {
342 //- /main.rs crate:main deps:core
343 use core::result::Result::{self, Ok, Err};
345 fn div(x: i32, y: i32) -> Result<i32, ()> {
351 //- /core/lib.rs crate:core
353 pub enum Result<T, E> { Ok(T), Err(E) }
356 pub enum Option<T> { Some(T), None }
360 use core::result::Result::{self, Ok, Err};
362 fn div(x: i32, y: i32) -> Result<i32, ()> {
373 fn test_wrap_return_type_handles_generic_functions() {
376 //- /main.rs crate:main deps:core
377 use core::result::Result::{self, Ok, Err};
379 fn div<T>(x: T) -> Result<T, i32> {
385 //- /core/lib.rs crate:core
387 pub enum Result<T, E> { Ok(T), Err(E) }
390 pub enum Option<T> { Some(T), None }
394 use core::result::Result::{self, Ok, Err};
396 fn div<T>(x: T) -> Result<T, i32> {
407 fn test_wrap_return_type_handles_type_aliases() {
410 //- /main.rs crate:main deps:core
411 use core::result::Result::{self, Ok, Err};
413 type MyResult<T> = Result<T, ()>;
415 fn div(x: i32, y: i32) -> MyResult<i32> {
421 //- /core/lib.rs crate:core
423 pub enum Result<T, E> { Ok(T), Err(E) }
426 pub enum Option<T> { Some(T), None }
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) }
458 pub enum Option<T> { Some(T), None }
465 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() {
466 check_no_diagnostics(
468 //- /main.rs crate:main deps:core
469 use core::result::Result::{self, Ok, Err};
471 enum SomeOtherEnum { Ok(i32), Err(String) }
473 fn foo() -> SomeOtherEnum { 0 }
475 //- /core/lib.rs crate:core
477 pub enum Result<T, E> { Ok(T), Err(E) }
480 pub enum Option<T> { Some(T), None }
487 fn test_fill_struct_fields_empty() {
490 struct TestStruct { one: i32, two: i64 }
493 let s = TestStruct {$0};
497 struct TestStruct { one: i32, two: i64 }
500 let s = TestStruct { one: (), two: ()};
507 fn test_fill_struct_fields_self() {
510 struct TestStruct { one: i32 }
513 fn test_fn() { let s = Self {$0}; }
517 struct TestStruct { one: i32 }
520 fn test_fn() { let s = Self { one: ()}; }
527 fn test_fill_struct_fields_enum() {
531 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
535 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
542 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
546 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
547 Expr::Bin { lhs: (), rhs: () }
555 fn test_fill_struct_fields_partial() {
558 struct TestStruct { one: i32, two: i64 }
561 let s = TestStruct{ two: 2$0 };
565 struct TestStruct { one: i32, two: i64 }
568 let s = TestStruct{ two: 2, one: () };
575 fn test_fill_struct_fields_no_diagnostic() {
576 check_no_diagnostics(
578 struct TestStruct { one: i32, two: i64 }
582 let s = TestStruct{ one, two: 2 };
589 fn test_fill_struct_fields_no_diagnostic_on_spread() {
590 check_no_diagnostics(
592 struct TestStruct { one: i32, two: i64 }
596 let s = TestStruct{ ..a };
603 fn test_unresolved_module_diagnostic() {
609 message: "unresolved module",
614 label: "Create module",
615 source_change: SourceChange {
616 source_file_edits: SourceFileEdits {
621 dst: AnchoredPathBuf {
627 initial_contents: "",
632 fix_trigger_range: 0..8,
648 fn range_mapping_out_of_macros() {
649 // FIXME: this is very wrong, but somewhat tricky to fix.
656 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
659 let _x = id![Foo { a: $042 }];
662 pub struct Foo { pub a: i32, pub b: i32 }
669 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
672 let _x = id![Foo { a: 42 }];
675 pub struct Foo { pub a: i32, pub b: i32 }
681 fn test_check_unnecessary_braces_in_use_statement() {
682 check_no_diagnostics(
695 check_no_diagnostics(
753 mod a { mod c {} mod d { mod e {} } }
754 use a::{c, d::{e$0}};
757 mod a { mod c {} mod d { mod e {} } }
764 fn test_add_field_from_usage() {
768 Foo { bar: 3, baz$0: false};
776 Foo { bar: 3, baz: false};
787 fn test_add_field_in_other_file_from_usage() {
794 foo::Foo { bar: 3, $0baz: false};
811 fn test_disabled_diagnostics() {
812 let mut config = DiagnosticsConfig::default();
813 config.disabled.insert("unresolved-module".into());
815 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
817 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
818 assert!(diagnostics.is_empty());
820 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
821 assert!(!diagnostics.is_empty());
825 fn test_rename_incorrect_case() {
828 pub struct test_struct$0 { one: i32 }
830 pub fn some_fn(val: test_struct) -> test_struct {
831 test_struct { one: val.one + 1 }
835 pub struct TestStruct { one: i32 }
837 pub fn some_fn(val: TestStruct) -> TestStruct {
838 TestStruct { one: val.one + 1 }
845 pub fn some_fn(NonSnakeCase$0: u8) -> u8 {
850 pub fn some_fn(non_snake_case: u8) -> u8 {
858 pub fn SomeFn$0(val: u8) -> u8 {
859 if val != 0 { SomeFn(val - 1) } else { val }
863 pub fn some_fn(val: u8) -> u8 {
864 if val != 0 { some_fn(val - 1) } else { val }
872 let whatAWeird_Formatting$0 = 10;
873 another_func(whatAWeird_Formatting);
878 let what_a_weird_formatting = 10;
879 another_func(what_a_weird_formatting);
886 fn test_uppercase_const_no_diagnostics() {
887 check_no_diagnostics(
890 const ANOTHER_ITEM$0: &str = "some_item";
897 fn test_rename_incorrect_case_struct_method() {
900 pub struct TestStruct;
903 pub fn SomeFn$0() -> TestStruct {
909 pub struct TestStruct;
912 pub fn some_fn() -> TestStruct {
921 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
922 let input = r#"fn FOO$0() {}"#;
923 let expected = r#"fn foo() {}"#;
925 let (analysis, file_position) = fixture::position(input);
927 analysis.diagnostics(&DiagnosticsConfig::default(), file_position.file_id).unwrap();
928 assert_eq!(diagnostics.len(), 1);
930 check_fix(input, expected);