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.
7 use std::cell::RefCell;
10 diagnostics::{AstDiagnostic, Diagnostic as _, DiagnosticSinkBuilder},
11 HasSource, HirDisplay, Semantics, VariantDef,
13 use itertools::Itertools;
14 use ra_db::SourceDatabase;
15 use ra_ide_db::RootDatabase;
19 ast::{self, edit::IndentLevel, make, AstNode},
20 SyntaxNode, TextRange, T,
22 use ra_text_edit::{TextEdit, TextEditBuilder};
24 use crate::{Diagnostic, FileId, FileSystemEdit, Fix, SourceFileEdit};
26 #[derive(Debug, Copy, Clone)]
32 pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> {
33 let _p = profile("diagnostics");
34 let sema = Semantics::new(db);
35 let parse = db.parse(file_id);
36 let mut res = Vec::new();
38 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
39 res.extend(parse.errors().iter().take(128).map(|err| Diagnostic {
41 message: format!("Syntax Error: {}", err),
42 severity: Severity::Error,
46 for node in parse.tree().syntax().descendants() {
47 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
48 check_struct_shorthand_initialization(&mut res, file_id, &node);
50 let res = RefCell::new(res);
51 let mut sink = DiagnosticSinkBuilder::new()
52 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
53 let original_file = d.source().file_id.original_file(db);
56 FileSystemEdit::CreateFile { anchor: original_file, dst: d.candidate.clone() }
59 res.borrow_mut().push(Diagnostic {
60 range: sema.diagnostics_range(d).range,
62 severity: Severity::Error,
66 .on::<hir::diagnostics::MissingFields, _>(|d| {
67 // Note that although we could add a diagnostics to
68 // fill the missing tuple field, e.g :
70 // `let a = A { 0: () }`
71 // but it is uncommon usage and it should not be encouraged.
72 let fix = if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
75 let mut field_list = d.ast(db);
76 for f in d.missed_fields.iter() {
78 make::record_field(make::name_ref(&f.to_string()), Some(make::expr_unit()));
79 field_list = field_list.append_field(&field);
83 let mut builder = TextEditBuilder::default();
84 algo::diff(&d.ast(db).syntax(), &field_list.syntax())
85 .into_text_edit(&mut builder);
88 Some(Fix::new("Fill struct fields", SourceFileEdit { file_id, edit }.into()))
91 res.borrow_mut().push(Diagnostic {
92 range: sema.diagnostics_range(d).range,
94 severity: Severity::Error,
98 .on::<hir::diagnostics::MissingOkInTailExpr, _>(|d| {
100 let replacement = format!("Ok({})", node.syntax());
101 let edit = TextEdit::replace(node.syntax().text_range(), replacement);
102 let source_change = SourceFileEdit { file_id, edit }.into();
103 let fix = Fix::new("Wrap with ok", source_change);
104 res.borrow_mut().push(Diagnostic {
105 range: sema.diagnostics_range(d).range,
106 message: d.message(),
107 severity: Severity::Error,
111 .on::<hir::diagnostics::NoSuchField, _>(|d| {
112 res.borrow_mut().push(Diagnostic {
113 range: sema.diagnostics_range(d).range,
114 message: d.message(),
115 severity: Severity::Error,
116 fix: missing_struct_field_fix(&sema, file_id, d),
120 res.borrow_mut().push(Diagnostic {
121 message: d.message(),
122 range: sema.diagnostics_range(d).range,
123 severity: Severity::Error,
128 if let Some(m) = sema.to_module_def(file_id) {
129 m.diagnostics(db, &mut sink);
135 fn missing_struct_field_fix(
136 sema: &Semantics<RootDatabase>,
137 usage_file_id: FileId,
138 d: &hir::diagnostics::NoSuchField,
140 let record_expr = sema.ast(d);
142 let record_lit = ast::RecordLit::cast(record_expr.syntax().parent()?.parent()?)?;
143 let def_id = sema.resolve_variant(record_lit)?;
146 let record_fields = match VariantDef::from(def_id) {
147 VariantDef::Struct(s) => {
148 module = s.module(sema.db);
149 let source = s.source(sema.db);
150 def_file_id = source.file_id;
151 let fields = source.value.field_def_list()?;
152 record_field_def_list(fields)?
154 VariantDef::Union(u) => {
155 module = u.module(sema.db);
156 let source = u.source(sema.db);
157 def_file_id = source.file_id;
158 source.value.record_field_def_list()?
160 VariantDef::EnumVariant(e) => {
161 module = e.module(sema.db);
162 let source = e.source(sema.db);
163 def_file_id = source.file_id;
164 let fields = source.value.field_def_list()?;
165 record_field_def_list(fields)?
168 let def_file_id = def_file_id.original_file(sema.db);
170 let new_field_type = sema.type_of_expr(&record_expr.expr()?)?;
171 if new_field_type.is_unknown() {
174 let new_field = make::record_field_def(
175 record_expr.field_name()?,
176 make::type_ref(&new_field_type.display_source_code(sema.db, module.into()).ok()?),
179 let last_field = record_fields.fields().last()?;
180 let last_field_syntax = last_field.syntax();
181 let indent = IndentLevel::from_node(last_field_syntax);
183 let mut new_field = new_field.to_string();
184 if usage_file_id != def_file_id {
185 new_field = format!("pub(crate) {}", new_field);
187 new_field = format!("\n{}{}", indent, new_field);
189 let needs_comma = !last_field_syntax.to_string().ends_with(',');
191 new_field = format!(",{}", new_field);
194 let source_change = SourceFileEdit {
195 file_id: def_file_id,
196 edit: TextEdit::insert(last_field_syntax.text_range().end(), new_field),
198 let fix = Fix::new("Create field", source_change.into());
201 fn record_field_def_list(field_def_list: ast::FieldDefList) -> Option<ast::RecordFieldDefList> {
202 match field_def_list {
203 ast::FieldDefList::RecordFieldDefList(it) => Some(it),
204 ast::FieldDefList::TupleFieldDefList(_) => None,
209 fn check_unnecessary_braces_in_use_statement(
210 acc: &mut Vec<Diagnostic>,
214 let use_tree_list = ast::UseTreeList::cast(node.clone())?;
215 if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
216 let range = use_tree_list.syntax().text_range();
218 text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
220 let to_replace = single_use_tree.syntax().text().to_string();
221 let mut edit_builder = TextEditBuilder::default();
222 edit_builder.delete(range);
223 edit_builder.insert(range.start(), to_replace);
224 edit_builder.finish()
227 acc.push(Diagnostic {
229 message: "Unnecessary braces in use statement".to_string(),
230 severity: Severity::WeakWarning,
232 "Remove unnecessary braces",
233 SourceFileEdit { file_id, edit }.into(),
241 fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
242 single_use_tree: &ast::UseTree,
243 ) -> Option<TextEdit> {
244 let use_tree_list_node = single_use_tree.syntax().parent()?;
245 if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
246 let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
247 let end = use_tree_list_node.text_range().end();
248 let range = TextRange::new(start, end);
249 return Some(TextEdit::delete(range));
254 fn check_struct_shorthand_initialization(
255 acc: &mut Vec<Diagnostic>,
259 let record_lit = ast::RecordLit::cast(node.clone())?;
260 let record_field_list = record_lit.record_field_list()?;
261 for record_field in record_field_list.fields() {
262 if let (Some(name_ref), Some(expr)) = (record_field.name_ref(), record_field.expr()) {
263 let field_name = name_ref.syntax().text().to_string();
264 let field_expr = expr.syntax().text().to_string();
265 let field_name_is_tup_index = name_ref.as_tuple_field().is_some();
266 if field_name == field_expr && !field_name_is_tup_index {
267 let mut edit_builder = TextEditBuilder::default();
268 edit_builder.delete(record_field.syntax().text_range());
269 edit_builder.insert(record_field.syntax().text_range().start(), field_name);
270 let edit = edit_builder.finish();
272 acc.push(Diagnostic {
273 range: record_field.syntax().text_range(),
274 message: "Shorthand struct initialization".to_string(),
275 severity: Severity::WeakWarning,
277 "Use struct shorthand initialization",
278 SourceFileEdit { file_id, edit }.into(),
289 use stdx::trim_indent;
290 use test_utils::assert_eq_text;
292 use crate::mock_analysis::{analysis_and_position, single_file, MockAnalysis};
293 use expect::{expect, Expect};
295 /// Takes a multi-file input fixture with annotated cursor positions,
297 /// * a diagnostic is produced
298 /// * this diagnostic touches the input cursor position
299 /// * that the contents of the file containing the cursor match `after` after the diagnostic fix is applied
300 fn check_fix(ra_fixture_before: &str, ra_fixture_after: &str) {
301 let after = trim_indent(ra_fixture_after);
303 let (analysis, file_position) = analysis_and_position(ra_fixture_before);
304 let diagnostic = analysis.diagnostics(file_position.file_id).unwrap().pop().unwrap();
305 let mut fix = diagnostic.fix.unwrap();
306 let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
307 let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
309 let mut actual = target_file_contents.to_string();
310 edit.apply(&mut actual);
314 assert_eq_text!(&after, &actual);
316 diagnostic.range.start() <= file_position.offset
317 && diagnostic.range.end() >= file_position.offset,
318 "diagnostic range {:?} does not touch cursor position {:?}",
324 /// Checks that a diagnostic applies to the file containing the `<|>` cursor marker
325 /// which has a fix that can apply to other files.
326 fn check_apply_diagnostic_fix_in_other_file(ra_fixture_before: &str, ra_fixture_after: &str) {
327 let ra_fixture_after = &trim_indent(ra_fixture_after);
328 let (analysis, file_pos) = analysis_and_position(ra_fixture_before);
329 let current_file_id = file_pos.file_id;
330 let diagnostic = analysis.diagnostics(current_file_id).unwrap().pop().unwrap();
331 let mut fix = diagnostic.fix.unwrap();
332 let edit = fix.source_change.source_file_edits.pop().unwrap();
333 let changed_file_id = edit.file_id;
334 let before = analysis.file_text(changed_file_id).unwrap();
336 let mut actual = before.to_string();
337 edit.edit.apply(&mut actual);
340 assert_eq_text!(ra_fixture_after, &actual);
343 /// Takes a multi-file input fixture with annotated cursor position and checks that no diagnostics
344 /// apply to the file containing the cursor.
345 fn check_no_diagnostics(ra_fixture: &str) {
346 let mock = MockAnalysis::with_files(ra_fixture);
347 let files = mock.files().map(|(it, _)| it).collect::<Vec<_>>();
348 let analysis = mock.analysis();
349 let diagnostics = files
351 .flat_map(|file_id| analysis.diagnostics(file_id).unwrap())
352 .collect::<Vec<_>>();
353 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
356 fn check_expect(ra_fixture: &str, expect: Expect) {
357 let (analysis, file_id) = single_file(ra_fixture);
358 let diagnostics = analysis.diagnostics(file_id).unwrap();
359 expect.assert_debug_eq(&diagnostics)
363 fn test_wrap_return_type() {
367 use core::result::Result::{self, Ok, Err};
369 fn div(x: i32, y: i32) -> Result<i32, ()> {
377 pub enum Result<T, E> { Ok(T), Err(E) }
381 use core::result::Result::{self, Ok, Err};
383 fn div(x: i32, y: i32) -> Result<i32, ()> {
394 fn test_wrap_return_type_handles_generic_functions() {
398 use core::result::Result::{self, Ok, Err};
400 fn div<T>(x: T) -> Result<T, i32> {
408 pub enum Result<T, E> { Ok(T), Err(E) }
412 use core::result::Result::{self, Ok, Err};
414 fn div<T>(x: T) -> Result<T, i32> {
425 fn test_wrap_return_type_handles_type_aliases() {
429 use core::result::Result::{self, Ok, Err};
431 type MyResult<T> = Result<T, ()>;
433 fn div(x: i32, y: i32) -> MyResult<i32> {
441 pub enum Result<T, E> { Ok(T), Err(E) }
445 use core::result::Result::{self, Ok, Err};
447 type MyResult<T> = Result<T, ()>;
449 fn div(x: i32, y: i32) -> MyResult<i32> {
460 fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() {
461 check_no_diagnostics(
464 use core::result::Result::{self, Ok, Err};
466 fn foo() -> Result<(), i32> { 0 }
470 pub enum Result<T, E> { Ok(T), Err(E) }
477 fn test_wrap_return_type_not_applicable_when_return_type_is_not_result() {
478 check_no_diagnostics(
481 use core::result::Result::{self, Ok, Err};
483 enum SomeOtherEnum { Ok(i32), Err(String) }
485 fn foo() -> SomeOtherEnum { 0 }
489 pub enum Result<T, E> { Ok(T), Err(E) }
496 fn test_fill_struct_fields_empty() {
499 struct TestStruct { one: i32, two: i64 }
502 let s = TestStruct {<|>};
506 struct TestStruct { one: i32, two: i64 }
509 let s = TestStruct { one: (), two: ()};
516 fn test_fill_struct_fields_self() {
519 struct TestStruct { one: i32 }
522 fn test_fn() { let s = Self {<|>}; }
526 struct TestStruct { one: i32 }
529 fn test_fn() { let s = Self { one: ()}; }
536 fn test_fill_struct_fields_enum() {
540 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
544 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
551 Bin { lhs: Box<Expr>, rhs: Box<Expr> }
555 fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
556 Expr::Bin { lhs: (), rhs: () }
564 fn test_fill_struct_fields_partial() {
567 struct TestStruct { one: i32, two: i64 }
570 let s = TestStruct{ two: 2<|> };
574 struct TestStruct { one: i32, two: i64 }
577 let s = TestStruct{ two: 2, one: () };
584 fn test_fill_struct_fields_no_diagnostic() {
585 check_no_diagnostics(
587 struct TestStruct { one: i32, two: i64 }
591 let s = TestStruct{ one, two: 2 };
598 fn test_fill_struct_fields_no_diagnostic_on_spread() {
599 check_no_diagnostics(
601 struct TestStruct { one: i32, two: i64 }
605 let s = TestStruct{ ..a };
612 fn test_unresolved_module_diagnostic() {
618 message: "unresolved module",
623 label: "Create module",
624 source_change: SourceChange {
625 source_file_edits: [],
645 fn range_mapping_out_of_macros() {
646 // FIXME: this is very wrong, but somewhat tricky to fix.
653 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
656 let _x = id![Foo { a: <|>42 }];
659 pub struct Foo { pub a: i32, pub b: i32 }
666 macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }
669 let _x = id![Foo { a: 42 }];
672 pub struct Foo { pub a: i32, pub b: i32 }
678 fn test_check_unnecessary_braces_in_use_statement() {
679 check_no_diagnostics(
685 check_fix(r#"use {<|>b};"#, r#"use b;"#);
686 check_fix(r#"use {b<|>};"#, r#"use b;"#);
687 check_fix(r#"use a::{c<|>};"#, r#"use a::c;"#);
688 check_fix(r#"use a::{self<|>};"#, r#"use a;"#);
689 check_fix(r#"use a::{c, d::{e<|>}};"#, r#"use a::{c, d::e};"#);
693 fn test_check_struct_shorthand_initialization() {
694 check_no_diagnostics(
696 struct A { a: &'static str }
697 fn main() { A { a: "hello" } }
700 check_no_diagnostics(
703 fn main() { A { 0: 0 } }
709 struct A { a: &'static str }
716 struct A { a: &'static str }
726 struct A { a: &'static str, b: &'static str }
734 struct A { a: &'static str, b: &'static str }
745 fn test_add_field_from_usage() {
749 Foo { bar: 3, baz<|>: false};
757 Foo { bar: 3, baz: false};
768 fn test_add_field_in_other_file_from_usage() {
769 check_apply_diagnostic_fix_in_other_file(
775 <|>foo::Foo { bar: 3, baz: false};