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.
9 use std::cell::RefCell;
11 use base_db::SourceDatabase;
12 use hir::{diagnostics::DiagnosticSinkBuilder, Semantics};
13 use ide_db::RootDatabase;
14 use itertools::Itertools;
15 use rustc_hash::FxHashSet;
18 SyntaxNode, TextRange, T,
20 use text_edit::TextEdit;
22 use crate::{FileId, Label, SourceChange, SourceFileEdit};
24 use self::fixes::DiagnosticWithFix;
27 pub struct Diagnostic {
28 // pub name: Option<String>,
31 pub severity: Severity,
38 pub source_change: SourceChange,
39 /// Allows to trigger the fix only when the caret is in the range given
40 pub fix_trigger_range: TextRange,
44 fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
45 let label = Label::new(label);
46 Self { label, source_change, fix_trigger_range }
50 #[derive(Debug, Copy, Clone)]
56 #[derive(Default, Debug, Clone)]
57 pub struct DiagnosticsConfig {
58 pub disable_experimental: bool,
59 pub disabled: FxHashSet<String>,
62 pub(crate) fn diagnostics(
64 config: &DiagnosticsConfig,
66 ) -> Vec<Diagnostic> {
67 let _p = profile::span("diagnostics");
68 let sema = Semantics::new(db);
69 let parse = db.parse(file_id);
70 let mut res = Vec::new();
72 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
73 res.extend(parse.errors().iter().take(128).map(|err| Diagnostic {
76 message: format!("Syntax Error: {}", err),
77 severity: Severity::Error,
81 for node in parse.tree().syntax().descendants() {
82 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
83 check_struct_shorthand_initialization(&mut res, file_id, &node);
85 let res = RefCell::new(res);
86 let sink_builder = DiagnosticSinkBuilder::new()
87 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
88 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
90 .on::<hir::diagnostics::MissingFields, _>(|d| {
91 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
93 .on::<hir::diagnostics::MissingOkInTailExpr, _>(|d| {
94 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
96 .on::<hir::diagnostics::NoSuchField, _>(|d| {
97 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
99 // Only collect experimental diagnostics when they're enabled.
100 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
101 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
103 // Finalize the `DiagnosticSink` building process.
104 let mut sink = sink_builder
105 // Diagnostics not handled above get no fix and default treatment.
107 res.borrow_mut().push(Diagnostic {
108 // name: Some(d.name().into()),
109 message: d.message(),
110 range: sema.diagnostics_display_range(d).range,
111 severity: Severity::Error,
116 if let Some(m) = sema.to_module_def(file_id) {
117 m.diagnostics(db, &mut sink);
123 fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
125 // name: Some(d.name().into()),
126 range: sema.diagnostics_display_range(d).range,
127 message: d.message(),
128 severity: Severity::Error,
133 fn check_unnecessary_braces_in_use_statement(
134 acc: &mut Vec<Diagnostic>,
138 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
139 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
140 let use_range = use_tree_list.syntax().text_range();
142 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
144 let to_replace = single_use_tree.syntax().text().to_string();
145 let mut edit_builder = TextEdit::builder();
146 edit_builder.delete(use_range);
147 edit_builder.insert(use_range.start(), to_replace);
148 edit_builder.finish()
151 acc.push(Diagnostic {
154 message: "Unnecessary braces in use statement".to_string(),
155 severity: Severity::WeakWarning,
157 "Remove unnecessary braces",
158 SourceFileEdit { file_id, edit }.into(),
167 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
168 single_use_tree: &ast::UseTree,
169 ) -> Option<TextEdit> {
170 let use_tree_list_node = single_use_tree.syntax().parent()?;
171 if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
172 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
173 let end = use_tree_list_node.text_range().end();
174 return Some(TextEdit::delete(TextRange::new(start, end)));
179 fn check_struct_shorthand_initialization(
180 acc: &mut Vec<Diagnostic>,
184 let record_lit = ast::RecordExpr::cast(node.clone())?;
185 let record_field_list = record_lit.record_expr_field_list()?;
186 for record_field in record_field_list.fields() {
187 if let (Some(name_ref), Some(expr)) = (record_field.name_ref(), record_field.expr()) {
188 let field_name = name_ref.syntax().text().to_string();
189 let field_expr = expr.syntax().text().to_string();
190 let field_name_is_tup_index = name_ref.as_tuple_field().is_some();
191 if field_name == field_expr && !field_name_is_tup_index {
192 let mut edit_builder = TextEdit::builder();
193 edit_builder.delete(record_field.syntax().text_range());
194 edit_builder.insert(record_field.syntax().text_range().start(), field_name);
195 let edit = edit_builder.finish();
197 let field_range = record_field.syntax().text_range();
198 acc.push(Diagnostic {
201 message: "Shorthand struct initialization".to_string(),
202 severity: Severity::WeakWarning,
204 "Use struct shorthand initialization",
205 SourceFileEdit { file_id, edit }.into(),
217 use expect_test::{expect, Expect};
218 use stdx::trim_indent;
219 use test_utils::assert_eq_text;
222 mock_analysis::{analysis_and_position, many_files, single_file},
226 /// Takes a multi-file input fixture with annotated cursor positions,
228 /// * a diagnostic is produced
229 /// * this diagnostic fix trigger range touches the input cursor position
230 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
231 fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
232 let after = trim_indent(ra_fixture_after);
234 let (analysis, file_position) = analysis_and_position(ra_fixture_before);
235 let diagnostic = analysis
236 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
240 let mut fix = diagnostic.fix.unwrap();
241 let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
242 let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
244 let mut actual = target_file_contents.to_string();
245 edit.apply(&mut actual);
249 assert_eq_text!(&after, &actual);
251 fix.fix_trigger_range.start() <= file_position.offset
252 && fix.fix_trigger_range.end() >= file_position.offset,
253 "diagnostic fix range {:?} does not touch cursor position {:?}",
254 fix.fix_trigger_range,
259 /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
260 /// which has a fix that can apply to other files.
261 fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
262 let ra_fixture_after = &trim_indent(ra_fixture_after);
263 let (analysis, file_pos) = analysis_and_position(ra_fixture_before);
264 let current_file_id = file_pos.file_id;
265 let diagnostic = analysis
266 .diagnostics(&DiagnosticsConfig::default(), current_file_id)
270 let mut fix = diagnostic.fix.unwrap();
271 let edit = fix.source_change.source_file_edits.pop().unwrap();
272 let changed_file_id = edit.file_id;
273 let before = analysis.file_text(changed_file_id).unwrap();
275 let mut actual = before.to_string();
276 edit.edit.apply(&mut actual);
279 assert_eq_text!(ra_fixture_after, &actual);
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 fn check_no_diagnostics(ra_fixture: &str) {
285 let (analysis, files) = many_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) = single_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: [],
575 fix_trigger_range: 0..8,
585 fn range_mapping_out_of_macros() {
586 // FIXME: this is very wrong, but somewhat tricky to fix.
593 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
596 let _x = id![Foo { a: <|>42 }];
599 pub struct Foo { pub a: i32, pub b: i32 }
606 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
609 let _x = id![Foo { a: 42 }];
612 pub struct Foo { pub a: i32, pub b: i32 }
618 fn test_check_unnecessary_braces_in_use_statement() {
619 check_no_diagnostics(
674 mod a { mod c {} mod d { mod e {} } }
675 use a::{c, d::{e<|>}};
678 mod a { mod c {} mod d { mod e {} } }
685 fn test_check_struct_shorthand_initialization() {
686 check_no_diagnostics(
688 struct A { a: &'static str }
689 fn main() { A { a: "hello" } }
692 check_no_diagnostics(
695 fn main() { A { 0: 0 } }
701 struct A { a: &'static str }
708 struct A { a: &'static str }
718 struct A { a: &'static str, b: &'static str }
726 struct A { a: &'static str, b: &'static str }
737 fn test_add_field_from_usage() {
741 Foo { bar: 3, baz<|>: false};
749 Foo { bar: 3, baz: false};
760 fn test_add_field_in_other_file_from_usage() {
761 check_apply_diagnostic_fix_in_other_file(
767 <|>foo::Foo { bar: 3, baz: false};
784 fn test_disabled_diagnostics() {
785 let mut config = DiagnosticsConfig::default();
786 config.disabled.insert("unresolved-module".into());
788 let (analysis, file_id) = single_file(r#"mod foo;"#);
790 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
791 assert!(diagnostics.is_empty());
793 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
794 assert!(!diagnostics.is_empty());