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;
221 use crate::{fixture, DiagnosticsConfig};
223 /// Takes a multi-file input fixture with annotated cursor positions,
225 /// * a diagnostic is produced
226 /// * this diagnostic fix trigger range touches the input cursor position
227 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
228 fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
229 let after = trim_indent(ra_fixture_after);
231 let (analysis, file_position) = fixture::position(ra_fixture_before);
232 let diagnostic = analysis
233 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
237 let mut fix = diagnostic.fix.unwrap();
238 let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
239 let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
241 let mut actual = target_file_contents.to_string();
242 edit.apply(&mut actual);
246 assert_eq_text!(&after, &actual);
248 fix.fix_trigger_range.start() <= file_position.offset
249 && fix.fix_trigger_range.end() >= file_position.offset,
250 "diagnostic fix range {:?} does not touch cursor position {:?}",
251 fix.fix_trigger_range,
256 /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
257 /// which has a fix that can apply to other files.
258 fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
259 let ra_fixture_after = &trim_indent(ra_fixture_after);
260 let (analysis, file_pos) = fixture::position(ra_fixture_before);
261 let current_file_id = file_pos.file_id;
262 let diagnostic = analysis
263 .diagnostics(&DiagnosticsConfig::default(), current_file_id)
267 let mut fix = diagnostic.fix.unwrap();
268 let edit = fix.source_change.source_file_edits.pop().unwrap();
269 let changed_file_id = edit.file_id;
270 let before = analysis.file_text(changed_file_id).unwrap();
272 let mut actual = before.to_string();
273 edit.edit.apply(&mut actual);
276 assert_eq_text!(ra_fixture_after, &actual);
279 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
280 /// apply to the file containing the cursor.
281 fn check_no_diagnostics(ra_fixture: &str) {
282 let (analysis, files) = fixture::files(ra_fixture);
283 let diagnostics = files
285 .flat_map(|file_id| {
286 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
288 .collect::<Vec<_>>();
289 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
292 fn check_expect(ra_fixture: &str, expect: Expect) {
293 let (analysis, file_id) = fixture::file(ra_fixture);
294 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
295 expect.assert_debug_eq(&diagnostics)
299 fn test_wrap_return_type() {
302 //- /main.rs crate:main deps:core
303 use core::result::Result::{self, Ok, Err};
305 fn div(x: i32, y: i32) -> Result<i32, ()> {
311 //- /core/lib.rs crate:core
313 pub enum Result<T, E> { Ok(T), Err(E) }
317 use core::result::Result::{self, Ok, Err};
319 fn div(x: i32, y: i32) -> Result<i32, ()> {
330 fn test_wrap_return_type_handles_generic_functions() {
333 //- /main.rs crate:main deps:core
334 use core::result::Result::{self, Ok, Err};
336 fn div<T>(x: T) -> Result<T, i32> {
342 //- /core/lib.rs crate:core
344 pub enum Result<T, E> { Ok(T), Err(E) }
348 use core::result::Result::{self, Ok, Err};
350 fn div<T>(x: T) -> Result<T, i32> {
361 fn test_wrap_return_type_handles_type_aliases() {
364 //- /main.rs crate:main deps:core
365 use core::result::Result::{self, Ok, Err};
367 type MyResult<T> = Result<T, ()>;
369 fn div(x: i32, y: i32) -> MyResult<i32> {
375 //- /core/lib.rs crate:core
377 pub enum Result<T, E> { Ok(T), Err(E) }
381 use core::result::Result::{self, Ok, Err};
383 type MyResult<T> = Result<T, ()>;
385 fn div(x: i32, y: i32) -> MyResult<i32> {
396 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
397 check_no_diagnostics(
399 //- /main.rs crate:main deps:core
400 use core::result::Result::{self, Ok, Err};
402 fn foo() -> Result<(), i32> { 0 }
404 //- /core/lib.rs crate:core
406 pub enum Result<T, E> { Ok(T), Err(E) }
413 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
414 check_no_diagnostics(
416 //- /main.rs crate:main deps:core
417 use core::result::Result::{self, Ok, Err};
419 enum SomeOtherEnum { Ok(i32), Err(String) }
421 fn foo() -> SomeOtherEnum { 0 }
423 //- /core/lib.rs crate:core
425 pub enum Result<T, E> { Ok(T), Err(E) }
432 fn test_fill_struct_fields_empty() {
435 struct TestStruct { one: i32, two: i64 }
438 let s = TestStruct {<|>};
442 struct TestStruct { one: i32, two: i64 }
445 let s = TestStruct { one: (), two: ()};
452 fn test_fill_struct_fields_self() {
455 struct TestStruct { one: i32 }
458 fn test_fn() { let s = Self {<|>}; }
462 struct TestStruct { one: i32 }
465 fn test_fn() { let s = Self { one: ()}; }
472 fn test_fill_struct_fields_enum() {
476 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
480 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
487 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
491 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
492 Expr::Bin { lhs: (), rhs: () }
500 fn test_fill_struct_fields_partial() {
503 struct TestStruct { one: i32, two: i64 }
506 let s = TestStruct{ two: 2<|> };
510 struct TestStruct { one: i32, two: i64 }
513 let s = TestStruct{ two: 2, one: () };
520 fn test_fill_struct_fields_no_diagnostic() {
521 check_no_diagnostics(
523 struct TestStruct { one: i32, two: i64 }
527 let s = TestStruct{ one, two: 2 };
534 fn test_fill_struct_fields_no_diagnostic_on_spread() {
535 check_no_diagnostics(
537 struct TestStruct { one: i32, two: i64 }
541 let s = TestStruct{ ..a };
548 fn test_unresolved_module_diagnostic() {
554 message: "unresolved module",
559 label: "Create module",
560 source_change: SourceChange {
561 source_file_edits: [],
572 fix_trigger_range: 0..8,
582 fn range_mapping_out_of_macros() {
583 // FIXME: this is very wrong, but somewhat tricky to fix.
590 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
593 let _x = id![Foo { a: <|>42 }];
596 pub struct Foo { pub a: i32, pub b: i32 }
603 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
606 let _x = id![Foo { a: 42 }];
609 pub struct Foo { pub a: i32, pub b: i32 }
615 fn test_check_unnecessary_braces_in_use_statement() {
616 check_no_diagnostics(
671 mod a { mod c {} mod d { mod e {} } }
672 use a::{c, d::{e<|>}};
675 mod a { mod c {} mod d { mod e {} } }
682 fn test_check_struct_shorthand_initialization() {
683 check_no_diagnostics(
685 struct A { a: &'static str }
686 fn main() { A { a: "hello" } }
689 check_no_diagnostics(
692 fn main() { A { 0: 0 } }
698 struct A { a: &'static str }
705 struct A { a: &'static str }
715 struct A { a: &'static str, b: &'static str }
723 struct A { a: &'static str, b: &'static str }
734 fn test_add_field_from_usage() {
738 Foo { bar: 3, baz<|>: false};
746 Foo { bar: 3, baz: false};
757 fn test_add_field_in_other_file_from_usage() {
758 check_apply_diagnostic_fix_in_other_file(
764 <|>foo::Foo { bar: 3, baz: false};
781 fn test_disabled_diagnostics() {
782 let mut config = DiagnosticsConfig::default();
783 config.disabled.insert("unresolved-module".into());
785 let (analysis, file_id) = fixture::file(r#"mod foo;"#);
787 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
788 assert!(diagnostics.is_empty());
790 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
791 assert!(!diagnostics.is_empty());