1 //! Type inference-based diagnostics.
7 use std::{any::Any, fmt};
10 use hir_def::{DefWithBodyId, ModuleDefId};
11 use hir_expand::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticSink};
12 use hir_expand::{name::Name, HirFileId, InFile};
14 use syntax::{ast, AstPtr, SyntaxNodePtr};
16 use crate::db::HirDatabase;
18 pub use crate::diagnostics::expr::{record_literal_missing_fields, record_pattern_missing_fields};
20 pub fn validate_module_item(
24 sink: &mut DiagnosticSink<'_>,
26 let _p = profile::span("validate_module_item");
27 let mut validator = decl_check::DeclValidator::new(db, krate, sink);
28 validator.validate_item(owner);
31 pub fn validate_body(db: &dyn HirDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) {
32 let _p = profile::span("validate_body");
33 let infer = db.infer(owner);
34 infer.add_diagnostics(db, owner, sink);
35 let mut validator = expr::ExprValidator::new(owner, infer.clone(), sink);
36 validator.validate_body(db);
37 let mut validator = unsafe_check::UnsafeValidator::new(owner, infer, sink);
38 validator.validate_body(db);
41 // Diagnostic: no-such-field
43 // This diagnostic is triggered if created structure does not have field provided in record.
45 pub struct NoSuchField {
47 pub field: AstPtr<ast::RecordExprField>,
50 impl Diagnostic for NoSuchField {
51 fn code(&self) -> DiagnosticCode {
52 DiagnosticCode("no-such-field")
55 fn message(&self) -> String {
56 "no such field".to_string()
59 fn display_source(&self) -> InFile<SyntaxNodePtr> {
60 InFile::new(self.file, self.field.clone().into())
63 fn as_any(&self) -> &(dyn Any + Send + 'static) {
68 // Diagnostic: missing-structure-fields
70 // This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
75 // struct A { a: u8, b: u8 }
77 // let a = A { a: 10 };
80 pub struct MissingFields {
82 pub field_list_parent: AstPtr<ast::RecordExpr>,
83 pub field_list_parent_path: Option<AstPtr<ast::Path>>,
84 pub missed_fields: Vec<Name>,
87 impl Diagnostic for MissingFields {
88 fn code(&self) -> DiagnosticCode {
89 DiagnosticCode("missing-structure-fields")
91 fn message(&self) -> String {
92 let mut buf = String::from("Missing structure fields:\n");
93 for field in &self.missed_fields {
94 format_to!(buf, "- {}\n", field);
99 fn display_source(&self) -> InFile<SyntaxNodePtr> {
103 .field_list_parent_path
105 .map(SyntaxNodePtr::from)
106 .unwrap_or_else(|| self.field_list_parent.clone().into()),
110 fn as_any(&self) -> &(dyn Any + Send + 'static) {
115 // Diagnostic: missing-pat-fields
117 // This diagnostic is triggered if pattern lacks some fields that exist in the corresponding structure.
122 // struct A { a: u8, b: u8 }
124 // let a = A { a: 10, b: 20 };
126 // if let A { a } = a {
131 pub struct MissingPatFields {
133 pub field_list_parent: AstPtr<ast::RecordPat>,
134 pub field_list_parent_path: Option<AstPtr<ast::Path>>,
135 pub missed_fields: Vec<Name>,
138 impl Diagnostic for MissingPatFields {
139 fn code(&self) -> DiagnosticCode {
140 DiagnosticCode("missing-pat-fields")
142 fn message(&self) -> String {
143 let mut buf = String::from("Missing structure fields:\n");
144 for field in &self.missed_fields {
145 format_to!(buf, "- {}\n", field);
149 fn display_source(&self) -> InFile<SyntaxNodePtr> {
153 .field_list_parent_path
155 .map(SyntaxNodePtr::from)
156 .unwrap_or_else(|| self.field_list_parent.clone().into()),
159 fn as_any(&self) -> &(dyn Any + Send + 'static) {
164 // Diagnostic: missing-match-arm
166 // This diagnostic is triggered if `match` block is missing one or more match arms.
168 pub struct MissingMatchArms {
170 pub match_expr: AstPtr<ast::Expr>,
171 pub arms: AstPtr<ast::MatchArmList>,
174 impl Diagnostic for MissingMatchArms {
175 fn code(&self) -> DiagnosticCode {
176 DiagnosticCode("missing-match-arm")
178 fn message(&self) -> String {
179 String::from("Missing match arm")
181 fn display_source(&self) -> InFile<SyntaxNodePtr> {
182 InFile { file_id: self.file, value: self.match_expr.clone().into() }
184 fn as_any(&self) -> &(dyn Any + Send + 'static) {
189 // Diagnostic: missing-ok-or-some-in-tail-expr
191 // This diagnostic is triggered if a block that should return `Result` returns a value not wrapped in `Ok`,
192 // or if a block that should return `Option` returns a value not wrapped in `Some`.
197 // fn foo() -> Result<u8, ()> {
202 pub struct MissingOkOrSomeInTailExpr {
204 pub expr: AstPtr<ast::Expr>,
205 // `Some` or `Ok` depending on whether the return type is Result or Option
206 pub required: String,
209 impl Diagnostic for MissingOkOrSomeInTailExpr {
210 fn code(&self) -> DiagnosticCode {
211 DiagnosticCode("missing-ok-or-some-in-tail-expr")
213 fn message(&self) -> String {
214 format!("wrap return expression in {}", self.required)
216 fn display_source(&self) -> InFile<SyntaxNodePtr> {
217 InFile { file_id: self.file, value: self.expr.clone().into() }
219 fn as_any(&self) -> &(dyn Any + Send + 'static) {
225 pub struct RemoveThisSemicolon {
227 pub expr: AstPtr<ast::Expr>,
230 impl Diagnostic for RemoveThisSemicolon {
231 fn code(&self) -> DiagnosticCode {
232 DiagnosticCode("remove-this-semicolon")
235 fn message(&self) -> String {
236 "Remove this semicolon".to_string()
239 fn display_source(&self) -> InFile<SyntaxNodePtr> {
240 InFile { file_id: self.file, value: self.expr.clone().into() }
243 fn as_any(&self) -> &(dyn Any + Send + 'static) {
248 // Diagnostic: break-outside-of-loop
250 // This diagnostic is triggered if the `break` keyword is used outside of a loop.
252 pub struct BreakOutsideOfLoop {
254 pub expr: AstPtr<ast::Expr>,
257 impl Diagnostic for BreakOutsideOfLoop {
258 fn code(&self) -> DiagnosticCode {
259 DiagnosticCode("break-outside-of-loop")
261 fn message(&self) -> String {
262 "break outside of loop".to_string()
264 fn display_source(&self) -> InFile<SyntaxNodePtr> {
265 InFile { file_id: self.file, value: self.expr.clone().into() }
267 fn as_any(&self) -> &(dyn Any + Send + 'static) {
272 // Diagnostic: missing-unsafe
274 // This diagnostic is triggered if an operation marked as `unsafe` is used outside of an `unsafe` function or block.
276 pub struct MissingUnsafe {
278 pub expr: AstPtr<ast::Expr>,
281 impl Diagnostic for MissingUnsafe {
282 fn code(&self) -> DiagnosticCode {
283 DiagnosticCode("missing-unsafe")
285 fn message(&self) -> String {
286 format!("This operation is unsafe and requires an unsafe function or block")
288 fn display_source(&self) -> InFile<SyntaxNodePtr> {
289 InFile { file_id: self.file, value: self.expr.clone().into() }
291 fn as_any(&self) -> &(dyn Any + Send + 'static) {
296 // Diagnostic: mismatched-arg-count
298 // This diagnostic is triggered if a function is invoked with an incorrect amount of arguments.
300 pub struct MismatchedArgCount {
302 pub call_expr: AstPtr<ast::Expr>,
307 impl Diagnostic for MismatchedArgCount {
308 fn code(&self) -> DiagnosticCode {
309 DiagnosticCode("mismatched-arg-count")
311 fn message(&self) -> String {
312 let s = if self.expected == 1 { "" } else { "s" };
313 format!("Expected {} argument{}, found {}", self.expected, s, self.found)
315 fn display_source(&self) -> InFile<SyntaxNodePtr> {
316 InFile { file_id: self.file, value: self.call_expr.clone().into() }
318 fn as_any(&self) -> &(dyn Any + Send + 'static) {
321 fn is_experimental(&self) -> bool {
336 impl fmt::Display for CaseType {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 let repr = match self {
339 CaseType::LowerSnakeCase => "snake_case",
340 CaseType::UpperSnakeCase => "UPPER_SNAKE_CASE",
341 CaseType::UpperCamelCase => "CamelCase",
344 write!(f, "{}", repr)
361 impl fmt::Display for IdentType {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 let repr = match self {
364 IdentType::Argument => "Argument",
365 IdentType::Constant => "Constant",
366 IdentType::Enum => "Enum",
367 IdentType::Field => "Field",
368 IdentType::Function => "Function",
369 IdentType::StaticVariable => "Static variable",
370 IdentType::Structure => "Structure",
371 IdentType::Variable => "Variable",
372 IdentType::Variant => "Variant",
375 write!(f, "{}", repr)
379 // Diagnostic: incorrect-ident-case
381 // This diagnostic is triggered if an item name doesn't follow https://doc.rust-lang.org/1.0.0/style/style/naming/README.html[Rust naming convention].
383 pub struct IncorrectCase {
385 pub ident: AstPtr<ast::Name>,
386 pub expected_case: CaseType,
387 pub ident_type: IdentType,
388 pub ident_text: String,
389 pub suggested_text: String,
392 impl Diagnostic for IncorrectCase {
393 fn code(&self) -> DiagnosticCode {
394 DiagnosticCode("incorrect-ident-case")
397 fn message(&self) -> String {
399 "{} `{}` should have {} name, e.g. `{}`",
402 self.expected_case.to_string(),
407 fn display_source(&self) -> InFile<SyntaxNodePtr> {
408 InFile::new(self.file, self.ident.clone().into())
411 fn as_any(&self) -> &(dyn Any + Send + 'static) {
415 fn is_experimental(&self) -> bool {
420 // Diagnostic: replace-filter-map-next-with-find-map
422 // This diagnostic is triggered when `.filter_map(..).next()` is used, rather than the more concise `.find_map(..)`.
424 pub struct ReplaceFilterMapNextWithFindMap {
426 /// This expression is the whole method chain up to and including `.filter_map(..).next()`.
427 pub next_expr: AstPtr<ast::Expr>,
430 impl Diagnostic for ReplaceFilterMapNextWithFindMap {
431 fn code(&self) -> DiagnosticCode {
432 DiagnosticCode("replace-filter-map-next-with-find-map")
434 fn message(&self) -> String {
435 "replace filter_map(..).next() with find_map(..)".to_string()
437 fn display_source(&self) -> InFile<SyntaxNodePtr> {
438 InFile { file_id: self.file, value: self.next_expr.clone().into() }
440 fn as_any(&self) -> &(dyn Any + Send + 'static) {
447 use base_db::{fixture::WithFixture, FileId, SourceDatabase, SourceDatabaseExt};
448 use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId};
451 diagnostics::{Diagnostic, DiagnosticSinkBuilder},
453 use rustc_hash::FxHashMap;
454 use syntax::{TextRange, TextSize};
457 diagnostics::{validate_body, validate_module_item},
462 fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) {
463 let crate_graph = self.crate_graph();
464 for krate in crate_graph.iter() {
465 let crate_def_map = self.crate_def_map(krate);
467 let mut fns = Vec::new();
468 for (module_id, _) in crate_def_map.modules() {
469 for decl in crate_def_map[module_id].scope.declarations() {
470 let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
471 validate_module_item(self, krate, decl, &mut sink);
473 if let ModuleDefId::FunctionId(f) = decl {
478 for impl_id in crate_def_map[module_id].scope.impls() {
479 let impl_data = self.impl_data(impl_id);
480 for item in impl_data.items.iter() {
481 if let AssocItemId::FunctionId(f) = item {
482 let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
483 validate_module_item(
486 ModuleDefId::FunctionId(*f),
496 let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
497 validate_body(self, f.into(), &mut sink);
503 pub(crate) fn check_diagnostics(ra_fixture: &str) {
504 let db = TestDB::with_files(ra_fixture);
505 let annotations = db.extract_annotations();
507 let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
509 let src = d.display_source();
510 let root = db.parse_or_expand(src.file_id).unwrap();
512 let file_id = src.file_id.original_file(&db);
513 let range = src.value.to_node(&root).text_range();
514 let message = d.message();
515 actual.entry(file_id).or_default().push((range, message));
518 for (file_id, diags) in actual.iter_mut() {
519 diags.sort_by_key(|it| it.0.start());
520 let text = db.file_text(*file_id);
521 // For multiline spans, place them on line start
522 for (range, content) in diags {
523 if text[*range].contains('\n') {
524 *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
525 *content = format!("... {}", content);
530 assert_eq!(annotations, actual);
534 fn no_such_field_diagnostics() {
537 struct S { foo: i32, bar: () }
541 //^ Missing structure fields:
545 //^^^^^^^ no such field
553 fn no_such_field_with_feature_flag_diagnostics() {
556 //- /lib.rs crate:foo cfg:feature=foo
559 #[cfg(feature = "foo")]
564 #[cfg(feature = "foo")]
565 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
568 #[cfg(not(feature = "foo"))]
569 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
578 fn no_such_field_enum_with_feature_flag_diagnostics() {
581 //- /lib.rs crate:foo cfg:feature=foo
583 #[cfg(not(feature = "foo"))]
585 #[cfg(feature = "foo")]
601 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
604 //- /lib.rs crate:foo cfg:feature=foo
606 #[cfg(feature = "foo")]
608 #[cfg(not(feature = "foo"))]
613 #[cfg(feature = "foo")]
614 fn new(foo: u32) -> Self {
617 #[cfg(not(feature = "foo"))]
618 fn new(bar: u32) -> Self {
621 fn new2(bar: u32) -> Self {
622 #[cfg(feature = "foo")]
623 { Self { foo: bar } }
624 #[cfg(not(feature = "foo"))]
627 fn new2(val: u32) -> Self {
629 #[cfg(feature = "foo")]
631 #[cfg(not(feature = "foo"))]
641 fn no_such_field_with_type_macro() {
644 macro_rules! Type { () => { u32 }; }
645 struct Foo { bar: Type![] }
657 fn missing_record_pat_field_diagnostic() {
660 struct S { foo: i32, bar: () }
662 let S { foo: _ } = s;
663 //^ Missing structure fields:
671 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
674 struct S { foo: i32, bar: () }
675 fn baz(s: S) -> i32 {
677 S { foo, .. } => foo,
685 fn missing_record_pat_field_box() {
688 struct S { s: Box<u32> }
697 fn missing_record_pat_field_ref() {
709 fn import_extern_crate_clash_with_inner_item() {
710 // This is more of a resolver test, but doesn't really work with the hir_def testsuite.
714 //- /lib.rs crate:lib deps:jwt
717 use permissions::jwt;
721 jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
729 //- /jwt/lib.rs crate:jwt
738 fn break_outside_of_loop() {
742 //^^^^^ break outside of loop
748 fn missing_semicolon() {
751 fn test() -> i32 { 123; }
752 //^^^ Remove this semicolon
757 // Register the required standard library types to make the tests work
758 fn add_filter_map_with_find_next_boilerplate(body: &str) -> String {
760 //- /main.rs crate:main deps:core
761 use core::iter::Iterator;
762 use core::option::Option::{self, Some, None};
765 //- /core/lib.rs crate:core
767 pub enum Option<T> { Some(T), None }
772 fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
773 fn next(&mut self) -> Option<Self::Item>;
775 pub struct FilterMap {}
776 impl Iterator for FilterMap {
778 fn next(&mut self) -> i32 { 7 }
782 format!("{}{}{}", prefix, body, suffix)
786 fn replace_filter_map_next_with_find_map2() {
787 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
790 let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next();
791 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..)
798 fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
799 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
804 .filter_map(|x| if *x == 2 { Some (4) } else { None })
812 fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
813 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
818 .filter_map(|x| if *x == 2 { Some (4) } else { None })
827 fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
828 check_diagnostics(&add_filter_map_with_find_next_boilerplate(
833 .filter_map(|x| if *x == 2 { Some (4) } else { None });