From 4768e5fb23c058eba90f0a1dcd6e9d5c0ecdee1b Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Mon, 14 Jun 2021 19:32:39 +0300 Subject: internal: document diagnostics crate --- .../src/handlers/break_outside_of_loop.rs | 30 + .../ide_diagnostics/src/handlers/inactive_code.rs | 116 +++ .../ide_diagnostics/src/handlers/incorrect_case.rs | 479 +++++++++++ crates/ide_diagnostics/src/handlers/macro_error.rs | 173 ++++ .../src/handlers/mismatched_arg_count.rs | 272 ++++++ .../ide_diagnostics/src/handlers/missing_fields.rs | 326 ++++++++ .../src/handlers/missing_match_arms.rs | 929 +++++++++++++++++++++ .../handlers/missing_ok_or_some_in_tail_expr.rs | 229 +++++ .../ide_diagnostics/src/handlers/missing_unsafe.rs | 101 +++ .../ide_diagnostics/src/handlers/no_such_field.rs | 283 +++++++ .../src/handlers/remove_this_semicolon.rs | 61 ++ .../replace_filter_map_next_with_find_map.rs | 179 ++++ .../src/handlers/unimplemented_builtin_macro.rs | 16 + .../ide_diagnostics/src/handlers/unlinked_file.rs | 301 +++++++ .../src/handlers/unresolved_extern_crate.rs | 49 ++ .../src/handlers/unresolved_import.rs | 90 ++ .../src/handlers/unresolved_macro_call.rs | 84 ++ .../src/handlers/unresolved_module.rs | 110 +++ .../src/handlers/unresolved_proc_macro.rs | 27 + 19 files changed, 3855 insertions(+) create mode 100644 crates/ide_diagnostics/src/handlers/break_outside_of_loop.rs create mode 100644 crates/ide_diagnostics/src/handlers/inactive_code.rs create mode 100644 crates/ide_diagnostics/src/handlers/incorrect_case.rs create mode 100644 crates/ide_diagnostics/src/handlers/macro_error.rs create mode 100644 crates/ide_diagnostics/src/handlers/mismatched_arg_count.rs create mode 100644 crates/ide_diagnostics/src/handlers/missing_fields.rs create mode 100644 crates/ide_diagnostics/src/handlers/missing_match_arms.rs create mode 100644 crates/ide_diagnostics/src/handlers/missing_ok_or_some_in_tail_expr.rs create mode 100644 crates/ide_diagnostics/src/handlers/missing_unsafe.rs create mode 100644 crates/ide_diagnostics/src/handlers/no_such_field.rs create mode 100644 crates/ide_diagnostics/src/handlers/remove_this_semicolon.rs create mode 100644 crates/ide_diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs create mode 100644 crates/ide_diagnostics/src/handlers/unimplemented_builtin_macro.rs create mode 100644 crates/ide_diagnostics/src/handlers/unlinked_file.rs create mode 100644 crates/ide_diagnostics/src/handlers/unresolved_extern_crate.rs create mode 100644 crates/ide_diagnostics/src/handlers/unresolved_import.rs create mode 100644 crates/ide_diagnostics/src/handlers/unresolved_macro_call.rs create mode 100644 crates/ide_diagnostics/src/handlers/unresolved_module.rs create mode 100644 crates/ide_diagnostics/src/handlers/unresolved_proc_macro.rs (limited to 'crates/ide_diagnostics/src/handlers') diff --git a/crates/ide_diagnostics/src/handlers/break_outside_of_loop.rs b/crates/ide_diagnostics/src/handlers/break_outside_of_loop.rs new file mode 100644 index 000000000..5ad0fbd1b --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/break_outside_of_loop.rs @@ -0,0 +1,30 @@ +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: break-outside-of-loop +// +// This diagnostic is triggered if the `break` keyword is used outside of a loop. +pub(crate) fn break_outside_of_loop( + ctx: &DiagnosticsContext<'_>, + d: &hir::BreakOutsideOfLoop, +) -> Diagnostic { + Diagnostic::new( + "break-outside-of-loop", + "break outside of loop", + ctx.sema.diagnostics_display_range(d.expr.clone().map(|it| it.into())).range, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + #[test] + fn break_outside_of_loop() { + check_diagnostics( + r#" +fn foo() { break; } + //^^^^^ break outside of loop +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/inactive_code.rs b/crates/ide_diagnostics/src/handlers/inactive_code.rs new file mode 100644 index 000000000..4b722fd64 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/inactive_code.rs @@ -0,0 +1,116 @@ +use cfg::DnfExpr; +use stdx::format_to; + +use crate::{Diagnostic, DiagnosticsContext, Severity}; + +// Diagnostic: inactive-code +// +// This diagnostic is shown for code with inactive `#[cfg]` attributes. +pub(crate) fn inactive_code( + ctx: &DiagnosticsContext<'_>, + d: &hir::InactiveCode, +) -> Option { + // If there's inactive code somewhere in a macro, don't propagate to the call-site. + if d.node.file_id.expansion_info(ctx.sema.db).is_some() { + return None; + } + + let inactive = DnfExpr::new(d.cfg.clone()).why_inactive(&d.opts); + let mut message = "code is inactive due to #[cfg] directives".to_string(); + + if let Some(inactive) = inactive { + format_to!(message, ": {}", inactive); + } + + let res = Diagnostic::new( + "inactive-code", + message, + ctx.sema.diagnostics_display_range(d.node.clone()).range, + ) + .severity(Severity::WeakWarning) + .with_unused(true); + Some(res) +} + +#[cfg(test)] +mod tests { + use crate::{tests::check_diagnostics_with_config, DiagnosticsConfig}; + + pub(crate) fn check(ra_fixture: &str) { + let config = DiagnosticsConfig::default(); + check_diagnostics_with_config(config, ra_fixture) + } + + #[test] + fn cfg_diagnostics() { + check( + r#" +fn f() { + // The three g̶e̶n̶d̶e̶r̶s̶ statements: + + #[cfg(a)] fn f() {} // Item statement + //^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled + #[cfg(a)] {} // Expression statement + //^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled + #[cfg(a)] let x = 0; // let statement + //^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled + + abc(#[cfg(a)] 0); + //^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled + let x = Struct { + #[cfg(a)] f: 0, + //^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled + }; + match () { + () => (), + #[cfg(a)] () => (), + //^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled + } + + #[cfg(a)] 0 // Trailing expression of block + //^^^^^^^^^^^ code is inactive due to #[cfg] directives: a is disabled +} + "#, + ); + } + + #[test] + fn inactive_item() { + // Additional tests in `cfg` crate. This only tests disabled cfgs. + + check( + r#" + #[cfg(no)] pub fn f() {} + //^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no is disabled + + #[cfg(no)] #[cfg(no2)] mod m; + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no and no2 are disabled + + #[cfg(all(not(a), b))] enum E {} + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: b is disabled + + #[cfg(feature = "std")] use std; + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: feature = "std" is disabled +"#, + ); + } + + /// Tests that `cfg` attributes behind `cfg_attr` is handled properly. + #[test] + fn inactive_via_cfg_attr() { + cov_mark::check!(cfg_attr_active); + check( + r#" + #[cfg_attr(not(never), cfg(no))] fn f() {} + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no is disabled + + #[cfg_attr(not(never), cfg(not(no)))] fn f() {} + + #[cfg_attr(never, cfg(no))] fn g() {} + + #[cfg_attr(not(never), inline, cfg(no))] fn h() {} + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ code is inactive due to #[cfg] directives: no is disabled +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/incorrect_case.rs b/crates/ide_diagnostics/src/handlers/incorrect_case.rs new file mode 100644 index 000000000..3a33029cf --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/incorrect_case.rs @@ -0,0 +1,479 @@ +use hir::{db::AstDatabase, InFile}; +use ide_db::{assists::Assist, defs::NameClass}; +use syntax::AstNode; + +use crate::{ + // references::rename::rename_with_semantics, + unresolved_fix, + Diagnostic, + DiagnosticsContext, + Severity, +}; + +// Diagnostic: incorrect-ident-case +// +// 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]. +pub(crate) fn incorrect_case(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCase) -> Diagnostic { + Diagnostic::new( + "incorrect-ident-case", + format!( + "{} `{}` should have {} name, e.g. `{}`", + d.ident_type, d.ident_text, d.expected_case, d.suggested_text + ), + ctx.sema.diagnostics_display_range(InFile::new(d.file, d.ident.clone().into())).range, + ) + .severity(Severity::WeakWarning) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCase) -> Option> { + let root = ctx.sema.db.parse_or_expand(d.file)?; + let name_node = d.ident.to_node(&root); + let def = NameClass::classify(&ctx.sema, &name_node)?.defined(ctx.sema.db)?; + + let name_node = InFile::new(d.file, name_node.syntax()); + let frange = name_node.original_file_range(ctx.sema.db); + + let label = format!("Rename to {}", d.suggested_text); + let mut res = unresolved_fix("change_case", &label, frange.range); + if ctx.resolve.should_resolve(&res.id) { + let source_change = def.rename(&ctx.sema, &d.suggested_text); + res.source_change = Some(source_change.ok().unwrap_or_default()); + } + + Some(vec![res]) +} + +#[cfg(test)] +mod change_case { + use crate::tests::{check_diagnostics, check_fix}; + + #[test] + fn test_rename_incorrect_case() { + check_fix( + r#" +pub struct test_struct$0 { one: i32 } + +pub fn some_fn(val: test_struct) -> test_struct { + test_struct { one: val.one + 1 } +} +"#, + r#" +pub struct TestStruct { one: i32 } + +pub fn some_fn(val: TestStruct) -> TestStruct { + TestStruct { one: val.one + 1 } +} +"#, + ); + + check_fix( + r#" +pub fn some_fn(NonSnakeCase$0: u8) -> u8 { + NonSnakeCase +} +"#, + r#" +pub fn some_fn(non_snake_case: u8) -> u8 { + non_snake_case +} +"#, + ); + + check_fix( + r#" +pub fn SomeFn$0(val: u8) -> u8 { + if val != 0 { SomeFn(val - 1) } else { val } +} +"#, + r#" +pub fn some_fn(val: u8) -> u8 { + if val != 0 { some_fn(val - 1) } else { val } +} +"#, + ); + + check_fix( + r#" +fn some_fn() { + let whatAWeird_Formatting$0 = 10; + another_func(whatAWeird_Formatting); +} +"#, + r#" +fn some_fn() { + let what_a_weird_formatting = 10; + another_func(what_a_weird_formatting); +} +"#, + ); + } + + #[test] + fn test_uppercase_const_no_diagnostics() { + check_diagnostics( + r#" +fn foo() { + const ANOTHER_ITEM: &str = "some_item"; +} +"#, + ); + } + + #[test] + fn test_rename_incorrect_case_struct_method() { + check_fix( + r#" +pub struct TestStruct; + +impl TestStruct { + pub fn SomeFn$0() -> TestStruct { + TestStruct + } +} +"#, + r#" +pub struct TestStruct; + +impl TestStruct { + pub fn some_fn() -> TestStruct { + TestStruct + } +} +"#, + ); + } + + #[test] + fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() { + check_diagnostics( + r#" +fn FOO() {} +// ^^^ Function `FOO` should have snake_case name, e.g. `foo` +"#, + ); + check_fix(r#"fn FOO$0() {}"#, r#"fn foo() {}"#); + } + + #[test] + fn incorrect_function_name() { + check_diagnostics( + r#" +fn NonSnakeCaseName() {} +// ^^^^^^^^^^^^^^^^ Function `NonSnakeCaseName` should have snake_case name, e.g. `non_snake_case_name` +"#, + ); + } + + #[test] + fn incorrect_function_params() { + check_diagnostics( + r#" +fn foo(SomeParam: u8) {} + // ^^^^^^^^^ Parameter `SomeParam` should have snake_case name, e.g. `some_param` + +fn foo2(ok_param: &str, CAPS_PARAM: u8) {} + // ^^^^^^^^^^ Parameter `CAPS_PARAM` should have snake_case name, e.g. `caps_param` +"#, + ); + } + + #[test] + fn incorrect_variable_names() { + check_diagnostics( + r#" +fn foo() { + let SOME_VALUE = 10; + // ^^^^^^^^^^ Variable `SOME_VALUE` should have snake_case name, e.g. `some_value` + let AnotherValue = 20; + // ^^^^^^^^^^^^ Variable `AnotherValue` should have snake_case name, e.g. `another_value` +} +"#, + ); + } + + #[test] + fn incorrect_struct_names() { + check_diagnostics( + r#" +struct non_camel_case_name {} + // ^^^^^^^^^^^^^^^^^^^ Structure `non_camel_case_name` should have CamelCase name, e.g. `NonCamelCaseName` + +struct SCREAMING_CASE {} + // ^^^^^^^^^^^^^^ Structure `SCREAMING_CASE` should have CamelCase name, e.g. `ScreamingCase` +"#, + ); + } + + #[test] + fn no_diagnostic_for_camel_cased_acronyms_in_struct_name() { + check_diagnostics( + r#" +struct AABB {} +"#, + ); + } + + #[test] + fn incorrect_struct_field() { + check_diagnostics( + r#" +struct SomeStruct { SomeField: u8 } + // ^^^^^^^^^ Field `SomeField` should have snake_case name, e.g. `some_field` +"#, + ); + } + + #[test] + fn incorrect_enum_names() { + check_diagnostics( + r#" +enum some_enum { Val(u8) } + // ^^^^^^^^^ Enum `some_enum` should have CamelCase name, e.g. `SomeEnum` + +enum SOME_ENUM {} + // ^^^^^^^^^ Enum `SOME_ENUM` should have CamelCase name, e.g. `SomeEnum` +"#, + ); + } + + #[test] + fn no_diagnostic_for_camel_cased_acronyms_in_enum_name() { + check_diagnostics( + r#" +enum AABB {} +"#, + ); + } + + #[test] + fn incorrect_enum_variant_name() { + check_diagnostics( + r#" +enum SomeEnum { SOME_VARIANT(u8) } + // ^^^^^^^^^^^^ Variant `SOME_VARIANT` should have CamelCase name, e.g. `SomeVariant` +"#, + ); + } + + #[test] + fn incorrect_const_name() { + check_diagnostics( + r#" +const some_weird_const: u8 = 10; + // ^^^^^^^^^^^^^^^^ Constant `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST` +"#, + ); + } + + #[test] + fn incorrect_static_name() { + check_diagnostics( + r#" +static some_weird_const: u8 = 10; + // ^^^^^^^^^^^^^^^^ Static variable `some_weird_const` should have UPPER_SNAKE_CASE name, e.g. `SOME_WEIRD_CONST` +"#, + ); + } + + #[test] + fn fn_inside_impl_struct() { + check_diagnostics( + r#" +struct someStruct; + // ^^^^^^^^^^ Structure `someStruct` should have CamelCase name, e.g. `SomeStruct` + +impl someStruct { + fn SomeFunc(&self) { + // ^^^^^^^^ Function `SomeFunc` should have snake_case name, e.g. `some_func` + let WHY_VAR_IS_CAPS = 10; + // ^^^^^^^^^^^^^^^ Variable `WHY_VAR_IS_CAPS` should have snake_case name, e.g. `why_var_is_caps` + } +} +"#, + ); + } + + #[test] + fn no_diagnostic_for_enum_varinats() { + check_diagnostics( + r#" +enum Option { Some, None } + +fn main() { + match Option::None { + None => (), + Some => (), + } +} +"#, + ); + } + + #[test] + fn non_let_bind() { + check_diagnostics( + r#" +enum Option { Some, None } + +fn main() { + match Option::None { + SOME_VAR @ None => (), + // ^^^^^^^^ Variable `SOME_VAR` should have snake_case name, e.g. `some_var` + Some => (), + } +} +"#, + ); + } + + #[test] + fn allow_attributes_crate_attr() { + check_diagnostics( + r#" +#![allow(non_snake_case)] + +mod F { + fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {} +} + "#, + ); + } + + #[test] + #[ignore] + fn bug_trait_inside_fn() { + // FIXME: + // This is broken, and in fact, should not even be looked at by this + // lint in the first place. There's weird stuff going on in the + // collection phase. + // It's currently being brought in by: + // * validate_func on `a` recursing into modules + // * then it finds the trait and then the function while iterating + // through modules + // * then validate_func is called on Dirty + // * ... which then proceeds to look at some unknown module taking no + // attrs from either the impl or the fn a, and then finally to the root + // module + // + // It should find the attribute on the trait, but it *doesn't even see + // the trait* as far as I can tell. + + check_diagnostics( + r#" +trait T { fn a(); } +struct U {} +impl T for U { + fn a() { + // this comes out of bitflags, mostly + #[allow(non_snake_case)] + trait __BitFlags { + const HiImAlsoBad: u8 = 2; + #[inline] + fn Dirty(&self) -> bool { + false + } + } + + } +} + "#, + ); + } + + #[test] + fn infinite_loop_inner_items() { + check_diagnostics( + r#" +fn qualify() { + mod foo { + use super::*; + } +} + "#, + ) + } + + #[test] // Issue #8809. + fn parenthesized_parameter() { + check_diagnostics(r#"fn f((O): _) {}"#) + } + + #[test] + fn ignores_extern_items() { + cov_mark::check!(extern_func_incorrect_case_ignored); + cov_mark::check!(extern_static_incorrect_case_ignored); + check_diagnostics( + r#" +extern { + fn NonSnakeCaseName(SOME_VAR: u8) -> u8; + pub static SomeStatic: u8 = 10; +} + "#, + ); + } + + #[test] + #[ignore] + fn bug_traits_arent_checked() { + // FIXME: Traits and functions in traits aren't currently checked by + // r-a, even though rustc will complain about them. + check_diagnostics( + r#" +trait BAD_TRAIT { + // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait` + fn BAD_FUNCTION(); + // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function` + fn BadFunction(); + // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function` +} + "#, + ); + } + + #[test] + fn allow_attributes() { + check_diagnostics( + r#" +#[allow(non_snake_case)] +fn NonSnakeCaseName(SOME_VAR: u8) -> u8{ + // cov_flags generated output from elsewhere in this file + extern "C" { + #[no_mangle] + static lower_case: u8; + } + + let OtherVar = SOME_VAR + 1; + OtherVar +} + +#[allow(nonstandard_style)] +mod CheckNonstandardStyle { + fn HiImABadFnName() {} +} + +#[allow(bad_style)] +mod CheckBadStyle { + fn HiImABadFnName() {} +} + +mod F { + #![allow(non_snake_case)] + fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {} +} + +#[allow(non_snake_case, non_camel_case_types)] +pub struct some_type { + SOME_FIELD: u8, + SomeField: u16, +} + +#[allow(non_upper_case_globals)] +pub const some_const: u8 = 10; + +#[allow(non_upper_case_globals)] +pub static SomeStatic: u8 = 10; + "#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/macro_error.rs b/crates/ide_diagnostics/src/handlers/macro_error.rs new file mode 100644 index 000000000..d4d928ad1 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/macro_error.rs @@ -0,0 +1,173 @@ +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: macro-error +// +// This diagnostic is shown for macro expansion errors. +pub(crate) fn macro_error(ctx: &DiagnosticsContext<'_>, d: &hir::MacroError) -> Diagnostic { + Diagnostic::new( + "macro-error", + d.message.clone(), + ctx.sema.diagnostics_display_range(d.node.clone()).range, + ) + .experimental() +} + +#[cfg(test)] +mod tests { + use crate::{ + tests::{check_diagnostics, check_diagnostics_with_config}, + DiagnosticsConfig, + }; + + #[test] + fn builtin_macro_fails_expansion() { + check_diagnostics( + r#" +#[rustc_builtin_macro] +macro_rules! include { () => {} } + + include!("doesntexist"); +//^^^^^^^^^^^^^^^^^^^^^^^^ failed to load file `doesntexist` + "#, + ); + } + + #[test] + fn include_macro_should_allow_empty_content() { + let mut config = DiagnosticsConfig::default(); + + // FIXME: This is a false-positive, the file is actually linked in via + // `include!` macro + config.disabled.insert("unlinked-file".to_string()); + + check_diagnostics_with_config( + config, + r#" +//- /lib.rs +#[rustc_builtin_macro] +macro_rules! include { () => {} } + +include!("foo/bar.rs"); +//- /foo/bar.rs +// empty +"#, + ); + } + + #[test] + fn good_out_dir_diagnostic() { + check_diagnostics( + r#" +#[rustc_builtin_macro] +macro_rules! include { () => {} } +#[rustc_builtin_macro] +macro_rules! env { () => {} } +#[rustc_builtin_macro] +macro_rules! concat { () => {} } + + include!(concat!(env!("OUT_DIR"), "/out.rs")); +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `OUT_DIR` not set, enable "run build scripts" to fix +"#, + ); + } + + #[test] + fn register_attr_and_tool() { + cov_mark::check!(register_attr); + cov_mark::check!(register_tool); + check_diagnostics( + r#" +#![register_tool(tool)] +#![register_attr(attr)] + +#[tool::path] +#[attr] +struct S; +"#, + ); + // NB: we don't currently emit diagnostics here + } + + #[test] + fn macro_diag_builtin() { + check_diagnostics( + r#" +#[rustc_builtin_macro] +macro_rules! env {} + +#[rustc_builtin_macro] +macro_rules! include {} + +#[rustc_builtin_macro] +macro_rules! compile_error {} + +#[rustc_builtin_macro] +macro_rules! format_args { () => {} } + +fn main() { + // Test a handful of built-in (eager) macros: + + include!(invalid); + //^^^^^^^^^^^^^^^^^ could not convert tokens + include!("does not exist"); + //^^^^^^^^^^^^^^^^^^^^^^^^^^ failed to load file `does not exist` + + env!(invalid); + //^^^^^^^^^^^^^ could not convert tokens + + env!("OUT_DIR"); + //^^^^^^^^^^^^^^^ `OUT_DIR` not set, enable "run build scripts" to fix + + compile_error!("compile_error works"); + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ compile_error works + + // Lazy: + + format_args!(); + //^^^^^^^^^^^^^^ no rule matches input tokens +} +"#, + ); + } + + #[test] + fn macro_rules_diag() { + check_diagnostics( + r#" +macro_rules! m { + () => {}; +} +fn f() { + m!(); + + m!(hi); + //^^^^^^ leftover tokens +} + "#, + ); + } + #[test] + fn dollar_crate_in_builtin_macro() { + check_diagnostics( + r#" +#[macro_export] +#[rustc_builtin_macro] +macro_rules! format_args {} + +#[macro_export] +macro_rules! arg { () => {} } + +#[macro_export] +macro_rules! outer { + () => { + $crate::format_args!( "", $crate::arg!(1) ) + }; +} + +fn f() { + outer!(); +} //^^^^^^^^ leftover tokens +"#, + ) + } +} diff --git a/crates/ide_diagnostics/src/handlers/mismatched_arg_count.rs b/crates/ide_diagnostics/src/handlers/mismatched_arg_count.rs new file mode 100644 index 000000000..ce313b2cc --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/mismatched_arg_count.rs @@ -0,0 +1,272 @@ +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: mismatched-arg-count +// +// This diagnostic is triggered if a function is invoked with an incorrect amount of arguments. +pub(crate) fn mismatched_arg_count( + ctx: &DiagnosticsContext<'_>, + d: &hir::MismatchedArgCount, +) -> Diagnostic { + let s = if d.expected == 1 { "" } else { "s" }; + let message = format!("expected {} argument{}, found {}", d.expected, s, d.found); + Diagnostic::new( + "mismatched-arg-count", + message, + ctx.sema.diagnostics_display_range(d.call_expr.clone().map(|it| it.into())).range, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + #[test] + fn simple_free_fn_zero() { + check_diagnostics( + r#" +fn zero() {} +fn f() { zero(1); } + //^^^^^^^ expected 0 arguments, found 1 +"#, + ); + + check_diagnostics( + r#" +fn zero() {} +fn f() { zero(); } +"#, + ); + } + + #[test] + fn simple_free_fn_one() { + check_diagnostics( + r#" +fn one(arg: u8) {} +fn f() { one(); } + //^^^^^ expected 1 argument, found 0 +"#, + ); + + check_diagnostics( + r#" +fn one(arg: u8) {} +fn f() { one(1); } +"#, + ); + } + + #[test] + fn method_as_fn() { + check_diagnostics( + r#" +struct S; +impl S { fn method(&self) {} } + +fn f() { + S::method(); +} //^^^^^^^^^^^ expected 1 argument, found 0 +"#, + ); + + check_diagnostics( + r#" +struct S; +impl S { fn method(&self) {} } + +fn f() { + S::method(&S); + S.method(); +} +"#, + ); + } + + #[test] + fn method_with_arg() { + check_diagnostics( + r#" +struct S; +impl S { fn method(&self, arg: u8) {} } + + fn f() { + S.method(); + } //^^^^^^^^^^ expected 1 argument, found 0 + "#, + ); + + check_diagnostics( + r#" +struct S; +impl S { fn method(&self, arg: u8) {} } + +fn f() { + S::method(&S, 0); + S.method(1); +} +"#, + ); + } + + #[test] + fn method_unknown_receiver() { + // note: this is incorrect code, so there might be errors on this in the + // future, but we shouldn't emit an argument count diagnostic here + check_diagnostics( + r#" +trait Foo { fn method(&self, arg: usize) {} } + +fn f() { + let x; + x.method(); +} +"#, + ); + } + + #[test] + fn tuple_struct() { + check_diagnostics( + r#" +struct Tup(u8, u16); +fn f() { + Tup(0); +} //^^^^^^ expected 2 arguments, found 1 +"#, + ) + } + + #[test] + fn enum_variant() { + check_diagnostics( + r#" +enum En { Variant(u8, u16), } +fn f() { + En::Variant(0); +} //^^^^^^^^^^^^^^ expected 2 arguments, found 1 +"#, + ) + } + + #[test] + fn enum_variant_type_macro() { + check_diagnostics( + r#" +macro_rules! Type { + () => { u32 }; +} +enum Foo { + Bar(Type![]) +} +impl Foo { + fn new() { + Foo::Bar(0); + Foo::Bar(0, 1); + //^^^^^^^^^^^^^^ expected 1 argument, found 2 + Foo::Bar(); + //^^^^^^^^^^ expected 1 argument, found 0 + } +} + "#, + ); + } + + #[test] + fn varargs() { + check_diagnostics( + r#" +extern "C" { + fn fixed(fixed: u8); + fn varargs(fixed: u8, ...); + fn varargs2(...); +} + +fn f() { + unsafe { + fixed(0); + fixed(0, 1); + //^^^^^^^^^^^ expected 1 argument, found 2 + varargs(0); + varargs(0, 1); + varargs2(); + varargs2(0); + varargs2(0, 1); + } +} + "#, + ) + } + + #[test] + fn arg_count_lambda() { + check_diagnostics( + r#" +fn main() { + let f = |()| (); + f(); + //^^^ expected 1 argument, found 0 + f(()); + f((), ()); + //^^^^^^^^^ expected 1 argument, found 2 +} +"#, + ) + } + + #[test] + fn cfgd_out_call_arguments() { + check_diagnostics( + r#" +struct C(#[cfg(FALSE)] ()); +impl C { + fn new() -> Self { + Self( + #[cfg(FALSE)] + (), + ) + } + + fn method(&self) {} +} + +fn main() { + C::new().method(#[cfg(FALSE)] 0); +} + "#, + ); + } + + #[test] + fn cfgd_out_fn_params() { + check_diagnostics( + r#" +fn foo(#[cfg(NEVER)] x: ()) {} + +struct S; + +impl S { + fn method(#[cfg(NEVER)] self) {} + fn method2(#[cfg(NEVER)] self, arg: u8) {} + fn method3(self, #[cfg(NEVER)] arg: u8) {} +} + +extern "C" { + fn fixed(fixed: u8, #[cfg(NEVER)] ...); + fn varargs(#[cfg(not(NEVER))] ...); +} + +fn main() { + foo(); + S::method(); + S::method2(0); + S::method3(S); + S.method3(); + unsafe { + fixed(0); + varargs(1, 2, 3); + } +} + "#, + ) + } +} diff --git a/crates/ide_diagnostics/src/handlers/missing_fields.rs b/crates/ide_diagnostics/src/handlers/missing_fields.rs new file mode 100644 index 000000000..bc82c0e4a --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/missing_fields.rs @@ -0,0 +1,326 @@ +use either::Either; +use hir::{db::AstDatabase, InFile}; +use ide_db::{assists::Assist, source_change::SourceChange}; +use stdx::format_to; +use syntax::{algo, ast::make, AstNode, SyntaxNodePtr}; +use text_edit::TextEdit; + +use crate::{fix, Diagnostic, DiagnosticsContext}; + +// Diagnostic: missing-fields +// +// This diagnostic is triggered if record lacks some fields that exist in the corresponding structure. +// +// Example: +// +// ```rust +// struct A { a: u8, b: u8 } +// +// let a = A { a: 10 }; +// ``` +pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic { + let mut message = String::from("Missing structure fields:\n"); + for field in &d.missed_fields { + format_to!(message, "- {}\n", field); + } + + let ptr = InFile::new( + d.file, + d.field_list_parent_path + .clone() + .map(SyntaxNodePtr::from) + .unwrap_or_else(|| d.field_list_parent.clone().either(|it| it.into(), |it| it.into())), + ); + + Diagnostic::new("missing-fields", message, ctx.sema.diagnostics_display_range(ptr).range) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option> { + // Note that although we could add a diagnostics to + // fill the missing tuple field, e.g : + // `struct A(usize);` + // `let a = A { 0: () }` + // but it is uncommon usage and it should not be encouraged. + if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) { + return None; + } + + let root = ctx.sema.db.parse_or_expand(d.file)?; + let field_list_parent = match &d.field_list_parent { + Either::Left(record_expr) => record_expr.to_node(&root), + // FIXE: patterns should be fixable as well. + Either::Right(_) => return None, + }; + let old_field_list = field_list_parent.record_expr_field_list()?; + let new_field_list = old_field_list.clone_for_update(); + for f in d.missed_fields.iter() { + let field = + make::record_expr_field(make::name_ref(&f.to_string()), Some(make::expr_unit())) + .clone_for_update(); + new_field_list.add_field(field); + } + + let edit = { + let mut builder = TextEdit::builder(); + algo::diff(old_field_list.syntax(), new_field_list.syntax()).into_text_edit(&mut builder); + builder.finish() + }; + Some(vec![fix( + "fill_missing_fields", + "Fill struct fields", + SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit), + ctx.sema.original_range(field_list_parent.syntax()).range, + )]) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_diagnostics, check_fix}; + + #[test] + fn missing_record_pat_field_diagnostic() { + check_diagnostics( + r#" +struct S { foo: i32, bar: () } +fn baz(s: S) { + let S { foo: _ } = s; + //^ Missing structure fields: + //| - bar +} +"#, + ); + } + + #[test] + fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() { + check_diagnostics( + r" +struct S { foo: i32, bar: () } +fn baz(s: S) -> i32 { + match s { + S { foo, .. } => foo, + } +} +", + ) + } + + #[test] + fn missing_record_pat_field_box() { + check_diagnostics( + r" +struct S { s: Box } +fn x(a: S) { + let S { box s } = a; +} +", + ) + } + + #[test] + fn missing_record_pat_field_ref() { + check_diagnostics( + r" +struct S { s: u32 } +fn x(a: S) { + let S { ref s } = a; +} +", + ) + } + + #[test] + fn range_mapping_out_of_macros() { + // FIXME: this is very wrong, but somewhat tricky to fix. + check_fix( + r#" +fn some() {} +fn items() {} +fn here() {} + +macro_rules! id { ($($tt:tt)*) => { $($tt)*}; } + +fn main() { + let _x = id![Foo { a: $042 }]; +} + +pub struct Foo { pub a: i32, pub b: i32 } +"#, + r#" +fn some(, b: () ) {} +fn items() {} +fn here() {} + +macro_rules! id { ($($tt:tt)*) => { $($tt)*}; } + +fn main() { + let _x = id![Foo { a: 42 }]; +} + +pub struct Foo { pub a: i32, pub b: i32 } +"#, + ); + } + + #[test] + fn test_fill_struct_fields_empty() { + check_fix( + r#" +struct TestStruct { one: i32, two: i64 } + +fn test_fn() { + let s = TestStruct {$0}; +} +"#, + r#" +struct TestStruct { one: i32, two: i64 } + +fn test_fn() { + let s = TestStruct { one: (), two: () }; +} +"#, + ); + } + + #[test] + fn test_fill_struct_fields_self() { + check_fix( + r#" +struct TestStruct { one: i32 } + +impl TestStruct { + fn test_fn() { let s = Self {$0}; } +} +"#, + r#" +struct TestStruct { one: i32 } + +impl TestStruct { + fn test_fn() { let s = Self { one: () }; } +} +"#, + ); + } + + #[test] + fn test_fill_struct_fields_enum() { + check_fix( + r#" +enum Expr { + Bin { lhs: Box, rhs: Box } +} + +impl Expr { + fn new_bin(lhs: Box, rhs: Box) -> Expr { + Expr::Bin {$0 } + } +} +"#, + r#" +enum Expr { + Bin { lhs: Box, rhs: Box } +} + +impl Expr { + fn new_bin(lhs: Box, rhs: Box) -> Expr { + Expr::Bin { lhs: (), rhs: () } + } +} +"#, + ); + } + + #[test] + fn test_fill_struct_fields_partial() { + check_fix( + r#" +struct TestStruct { one: i32, two: i64 } + +fn test_fn() { + let s = TestStruct{ two: 2$0 }; +} +"#, + r" +struct TestStruct { one: i32, two: i64 } + +fn test_fn() { + let s = TestStruct{ two: 2, one: () }; +} +", + ); + } + + #[test] + fn test_fill_struct_fields_raw_ident() { + check_fix( + r#" +struct TestStruct { r#type: u8 } + +fn test_fn() { + TestStruct { $0 }; +} +"#, + r" +struct TestStruct { r#type: u8 } + +fn test_fn() { + TestStruct { r#type: () }; +} +", + ); + } + + #[test] + fn test_fill_struct_fields_no_diagnostic() { + check_diagnostics( + r#" +struct TestStruct { one: i32, two: i64 } + +fn test_fn() { + let one = 1; + let s = TestStruct{ one, two: 2 }; +} + "#, + ); + } + + #[test] + fn test_fill_struct_fields_no_diagnostic_on_spread() { + check_diagnostics( + r#" +struct TestStruct { one: i32, two: i64 } + +fn test_fn() { + let one = 1; + let s = TestStruct{ ..a }; +} +"#, + ); + } + + #[test] + fn test_fill_struct_fields_blank_line() { + check_fix( + r#" +struct S { a: (), b: () } + +fn f() { + S { + $0 + }; +} +"#, + r#" +struct S { a: (), b: () } + +fn f() { + S { + a: (), + b: (), + }; +} +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/missing_match_arms.rs b/crates/ide_diagnostics/src/handlers/missing_match_arms.rs new file mode 100644 index 000000000..9ea533d74 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/missing_match_arms.rs @@ -0,0 +1,929 @@ +use hir::InFile; + +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: missing-match-arm +// +// This diagnostic is triggered if `match` block is missing one or more match arms. +pub(crate) fn missing_match_arms( + ctx: &DiagnosticsContext<'_>, + d: &hir::MissingMatchArms, +) -> Diagnostic { + Diagnostic::new( + "missing-match-arm", + "missing match arm", + ctx.sema.diagnostics_display_range(InFile::new(d.file, d.match_expr.clone().into())).range, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + fn check_diagnostics_no_bails(ra_fixture: &str) { + cov_mark::check_count!(validate_match_bailed_out, 0); + crate::tests::check_diagnostics(ra_fixture) + } + + #[test] + fn empty_tuple() { + check_diagnostics_no_bails( + r#" +fn main() { + match () { } + //^^ missing match arm + match (()) { } + //^^^^ missing match arm + + match () { _ => (), } + match () { () => (), } + match (()) { (()) => (), } +} +"#, + ); + } + + #[test] + fn tuple_of_two_empty_tuple() { + check_diagnostics_no_bails( + r#" +fn main() { + match ((), ()) { } + //^^^^^^^^ missing match arm + + match ((), ()) { ((), ()) => (), } +} +"#, + ); + } + + #[test] + fn boolean() { + check_diagnostics_no_bails( + r#" +fn test_main() { + match false { } + //^^^^^ missing match arm + match false { true => (), } + //^^^^^ missing match arm + match (false, true) {} + //^^^^^^^^^^^^^ missing match arm + match (false, true) { (true, true) => (), } + //^^^^^^^^^^^^^ missing match arm + match (false, true) { + //^^^^^^^^^^^^^ missing match arm + (false, true) => (), + (false, false) => (), + (true, false) => (), + } + match (false, true) { (true, _x) => (), } + //^^^^^^^^^^^^^ missing match arm + + match false { true => (), false => (), } + match (false, true) { + (false, _) => (), + (true, false) => (), + (_, true) => (), + } + match (false, true) { + (true, true) => (), + (true, false) => (), + (false, true) => (), + (false, false) => (), + } + match (false, true) { + (true, _x) => (), + (false, true) => (), + (false, false) => (), + } + match (false, true, false) { + (false, ..) => (), + (true, ..) => (), + } + match (false, true, false) { + (.., false) => (), + (.., true) => (), + } + match (false, true, false) { (..) => (), } +} +"#, + ); + } + + #[test] + fn tuple_of_tuple_and_bools() { + check_diagnostics_no_bails( + r#" +fn main() { + match (false, ((), false)) {} + //^^^^^^^^^^^^^^^^^^^^ missing match arm + match (false, ((), false)) { (true, ((), true)) => (), } + //^^^^^^^^^^^^^^^^^^^^ missing match arm + match (false, ((), false)) { (true, _) => (), } + //^^^^^^^^^^^^^^^^^^^^ missing match arm + + match (false, ((), false)) { + (true, ((), true)) => (), + (true, ((), false)) => (), + (false, ((), true)) => (), + (false, ((), false)) => (), + } + match (false, ((), false)) { + (true, ((), true)) => (), + (true, ((), false)) => (), + (false, _) => (), + } +} +"#, + ); + } + + #[test] + fn enums() { + check_diagnostics_no_bails( + r#" +enum Either { A, B, } + +fn main() { + match Either::A { } + //^^^^^^^^^ missing match arm + match Either::B { Either::A => (), } + //^^^^^^^^^ missing match arm + + match &Either::B { + //^^^^^^^^^^ missing match arm + Either::A => (), + } + + match Either::B { + Either::A => (), Either::B => (), + } + match &Either::B { + Either::A => (), Either::B => (), + } +} +"#, + ); + } + + #[test] + fn enum_containing_bool() { + check_diagnostics_no_bails( + r#" +enum Either { A(bool), B } + +fn main() { + match Either::B { } + //^^^^^^^^^ missing match arm + match Either::B { + //^^^^^^^^^ missing match arm + Either::A(true) => (), Either::B => () + } + + match Either::B { + Either::A(true) => (), + Either::A(false) => (), + Either::B => (), + } + match Either::B { + Either::B => (), + _ => (), + } + match Either::B { + Either::A(_) => (), + Either::B => (), + } + +} + "#, + ); + } + + #[test] + fn enum_different_sizes() { + check_diagnostics_no_bails( + r#" +enum Either { A(bool), B(bool, bool) } + +fn main() { + match Either::A(false) { + //^^^^^^^^^^^^^^^^ missing match arm + Either::A(_) => (), + Either::B(false, _) => (), + } + + match Either::A(false) { + Either::A(_) => (), + Either::B(true, _) => (), + Either::B(false, _) => (), + } + match Either::A(false) { + Either::A(true) | Either::A(false) => (), + Either::B(true, _) => (), + Either::B(false, _) => (), + } +} +"#, + ); + } + + #[test] + fn tuple_of_enum_no_diagnostic() { + check_diagnostics_no_bails( + r#" +enum Either { A(bool), B(bool, bool) } +enum Either2 { C, D } + +fn main() { + match (Either::A(false), Either2::C) { + (Either::A(true), _) | (Either::A(false), _) => (), + (Either::B(true, _), Either2::C) => (), + (Either::B(false, _), Either2::C) => (), + (Either::B(_, _), Either2::D) => (), + } +} +"#, + ); + } + + #[test] + fn or_pattern_no_diagnostic() { + check_diagnostics_no_bails( + r#" +enum Either {A, B} + +fn main() { + match (Either::A, Either::B) { + (Either::A | Either::B, _) => (), + } +}"#, + ) + } + + #[test] + fn mismatched_types() { + cov_mark::check_count!(validate_match_bailed_out, 4); + // Match statements with arms that don't match the + // expression pattern do not fire this diagnostic. + check_diagnostics( + r#" +enum Either { A, B } +enum Either2 { C, D } + +fn main() { + match Either::A { + Either2::C => (), + Either2::D => (), + } + match (true, false) { + (true, false, true) => (), + (true) => (), + } + match (true, false) { (true,) => {} } + match (0) { () => () } + match Unresolved::Bar { Unresolved::Baz => () } +} + "#, + ); + } + + #[test] + fn mismatched_types_in_or_patterns() { + cov_mark::check_count!(validate_match_bailed_out, 2); + check_diagnostics( + r#" +fn main() { + match false { true | () => {} } + match (false,) { (true | (),) => {} } +} +"#, + ); + } + + #[test] + fn malformed_match_arm_tuple_enum_missing_pattern() { + // We are testing to be sure we don't panic here when the match + // arm `Either::B` is missing its pattern. + check_diagnostics_no_bails( + r#" +enum Either { A, B(u32) } + +fn main() { + match Either::A { + Either::A => (), + Either::B() => (), + } +} +"#, + ); + } + + #[test] + fn malformed_match_arm_extra_fields() { + cov_mark::check_count!(validate_match_bailed_out, 2); + check_diagnostics( + r#" +enum A { B(isize, isize), C } +fn main() { + match A::B(1, 2) { + A::B(_, _, _) => (), + } + match A::B(1, 2) { + A::C(_) => (), + } +} +"#, + ); + } + + #[test] + fn expr_diverges() { + cov_mark::check_count!(validate_match_bailed_out, 2); + check_diagnostics( + r#" +enum Either { A, B } + +fn main() { + match loop {} { + Either::A => (), + Either::B => (), + } + match loop {} { + Either::A => (), + } + match loop { break Foo::A } { + //^^^^^^^^^^^^^^^^^^^^^ missing match arm + Either::A => (), + } + match loop { break Foo::A } { + Either::A => (), + Either::B => (), + } +} +"#, + ); + } + + #[test] + fn expr_partially_diverges() { + check_diagnostics_no_bails( + r#" +enum Either { A(T), B } + +fn foo() -> Either { Either::B } +fn main() -> u32 { + match foo() { + Either::A(val) => val, + Either::B => 0, + } +} +"#, + ); + } + + #[test] + fn enum_record() { + check_diagnostics_no_bails( + r#" +enum Either { A { foo: bool }, B } + +fn main() { + let a = Either::A { foo: true }; + match a { } + //^ missing match arm + match a { Either::A { foo: true } => () } + //^ missing match arm + match a { + Either::A { } => (), + //^^^^^^^^^ Missing structure fields: + // | - foo + Either::B => (), + } + match a { + //^ missing match arm + Either::A { } => (), + } //^^^^^^^^^ Missing structure fields: + // | - foo + + match a { + Either::A { foo: true } => (), + Either::A { foo: false } => (), + Either::B => (), + } + match a { + Either::A { foo: _ } => (), + Either::B => (), + } +} +"#, + ); + } + + #[test] + fn enum_record_fields_out_of_order() { + check_diagnostics_no_bails( + r#" +enum Either { + A { foo: bool, bar: () }, + B, +} + +fn main() { + let a = Either::A { foo: true, bar: () }; + match a { + //^ missing match arm + Either::A { bar: (), foo: false } => (), + Either::A { foo: true, bar: () } => (), + } + + match a { + Either::A { bar: (), foo: false } => (), + Either::A { foo: true, bar: () } => (), + Either::B => (), + } +} +"#, + ); + } + + #[test] + fn enum_record_ellipsis() { + check_diagnostics_no_bails( + r#" +enum Either { + A { foo: bool, bar: bool }, + B, +} + +fn main() { + let a = Either::B; + match a { + //^ missing match arm + Either::A { foo: true, .. } => (), + Either::B => (), + } + match a { + //^ missing match arm + Either::A { .. } => (), + } + + match a { + Either::A { foo: true, .. } => (), + Either::A { foo: false, .. } => (), + Either::B => (), + } + + match a { + Either::A { .. } => (), + Either::B => (), + } +} +"#, + ); + } + + #[test] + fn enum_tuple_partial_ellipsis() { + check_diagnostics_no_bails( + r#" +enum Either { + A(bool, bool, bool, bool), + B, +} + +fn main() { + match Either::B { + //^^^^^^^^^ missing match arm + Either::A(true, .., true) => (), + Either::A(true, .., false) => (), + Either::A(false, .., false) => (), + Either::B => (), + } + match Either::B { + //^^^^^^^^^ missing match arm + Either::A(true, .., true) => (), + Either::A(true, .., false) => (), + Either::A(.., true) => (), + Either::B => (), + } + + match Either::B { + Either::A(true, .., true) => (), + Either::A(true, .., false) => (), + Either::A(false, .., true) => (), + Either::A(false, .., false) => (), + Either::B => (), + } + match Either::B { + Either::A(true, .., true) => (), + Either::A(true, .., false) => (), + Either::A(.., true) => (), + Either::A(.., false) => (), + Either::B => (), + } +} +"#, + ); + } + + #[test] + fn never() { + check_diagnostics_no_bails( + r#" +enum Never {} + +fn enum_(never: Never) { + match never {} +} +fn enum_ref(never: &Never) { + match never {} + //^^^^^ missing match arm +} +fn bang(never: !) { + match never {} +} +"#, + ); + } + + #[test] + fn unknown_type() { + cov_mark::check_count!(validate_match_bailed_out, 1); + + check_diagnostics( + r#" +enum Option { Some(T), None } + +fn main() { + // `Never` is deliberately not defined so that it's an uninferred type. + match Option::::None { + None => (), + Some(never) => match never {}, + } + match Option::::None { + //^^^^^^^^^^^^^^^^^^^^^ missing match arm + Option::Some(_never) => {}, + } +} +"#, + ); + } + + #[test] + fn tuple_of_bools_with_ellipsis_at_end_missing_arm() { + check_diagnostics_no_bails( + r#" +fn main() { + match (false, true, false) { + //^^^^^^^^^^^^^^^^^^^^ missing match arm + (false, ..) => (), + } +}"#, + ); + } + + #[test] + fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() { + check_diagnostics_no_bails( + r#" +fn main() { + match (false, true, false) { + //^^^^^^^^^^^^^^^^^^^^ missing match arm + (.., false) => (), + } +}"#, + ); + } + + #[test] + fn tuple_of_bools_with_ellipsis_in_middle_missing_arm() { + check_diagnostics_no_bails( + r#" +fn main() { + match (false, true, false) { + //^^^^^^^^^^^^^^^^^^^^ missing match arm + (true, .., false) => (), + } +}"#, + ); + } + + #[test] + fn record_struct() { + check_diagnostics_no_bails( + r#"struct Foo { a: bool } +fn main(f: Foo) { + match f {} + //^ missing match arm + match f { Foo { a: true } => () } + //^ missing match arm + match &f { Foo { a: true } => () } + //^^ missing match arm + match f { Foo { a: _ } => () } + match f { + Foo { a: true } => (), + Foo { a: false } => (), + } + match &f { + Foo { a: true } => (), + Foo { a: false } => (), + } +} +"#, + ); + } + + #[test] + fn tuple_struct() { + check_diagnostics_no_bails( + r#"struct Foo(bool); +fn main(f: Foo) { + match f {} + //^ missing match arm + match f { Foo(true) => () } + //^ missing match arm + match f { + Foo(true) => (), + Foo(false) => (), + } +} +"#, + ); + } + + #[test] + fn unit_struct() { + check_diagnostics_no_bails( + r#"struct Foo; +fn main(f: Foo) { + match f {} + //^ missing match arm + match f { Foo => () } +} +"#, + ); + } + + #[test] + fn record_struct_ellipsis() { + check_diagnostics_no_bails( + r#"struct Foo { foo: bool, bar: bool } +fn main(f: Foo) { + match f { Foo { foo: true, .. } => () } + //^ missing match arm + match f { + //^ missing match arm + Foo { foo: true, .. } => (), + Foo { bar: false, .. } => () + } + match f { Foo { .. } => () } + match f { + Foo { foo: true, .. } => (), + Foo { foo: false, .. } => () + } +} +"#, + ); + } + + #[test] + fn internal_or() { + check_diagnostics_no_bails( + r#" +fn main() { + enum Either { A(bool), B } + match Either::B { + //^^^^^^^^^ missing match arm + Either::A(true | false) => (), + } +} +"#, + ); + } + + #[test] + fn no_panic_at_unimplemented_subpattern_type() { + cov_mark::check_count!(validate_match_bailed_out, 1); + + check_diagnostics( + r#" +struct S { a: char} +fn main(v: S) { + match v { S{ a } => {} } + match v { S{ a: _x } => {} } + match v { S{ a: 'a' } => {} } + match v { S{..} => {} } + match v { _ => {} } + match v { } + //^ missing match arm +} +"#, + ); + } + + #[test] + fn binding() { + check_diagnostics_no_bails( + r#" +fn main() { + match true { + _x @ true => {} + false => {} + } + match true { _x @ true => {} } + //^^^^ missing match arm +} +"#, + ); + } + + #[test] + fn binding_ref_has_correct_type() { + cov_mark::check_count!(validate_match_bailed_out, 1); + + // Asserts `PatKind::Binding(ref _x): bool`, not &bool. + // If that's not true match checking will panic with "incompatible constructors" + // FIXME: make facilities to test this directly like `tests::check_infer(..)` + check_diagnostics( + r#" +enum Foo { A } +fn main() { + // FIXME: this should not bail out but current behavior is such as the old algorithm. + // ExprValidator::validate_match(..) checks types of top level patterns incorrecly. + match Foo::A { + ref _x => {} + Foo::A => {} + } + match (true,) { + (ref _x,) => {} + (true,) => {} + } +} +"#, + ); + } + + #[test] + fn enum_non_exhaustive() { + check_diagnostics_no_bails( + r#" +//- /lib.rs crate:lib +#[non_exhaustive] +pub enum E { A, B } +fn _local() { + match E::A { _ => {} } + match E::A { + E::A => {} + E::B => {} + } + match E::A { + E::A | E::B => {} + } +} + +//- /main.rs crate:main deps:lib +use lib::E; +fn main() { + match E::A { _ => {} } + match E::A { + //^^^^ missing match arm + E::A => {} + E::B => {} + } + match E::A { + //^^^^ missing match arm + E::A | E::B => {} + } +} +"#, + ); + } + + #[test] + fn match_guard() { + check_diagnostics_no_bails( + r#" +fn main() { + match true { + true if false => {} + true => {} + false => {} + } + match true { + //^^^^ missing match arm + true if false => {} + false => {} + } +} +"#, + ); + } + + #[test] + fn pattern_type_is_of_substitution() { + cov_mark::check!(match_check_wildcard_expanded_to_substitutions); + check_diagnostics_no_bails( + r#" +struct Foo(T); +struct Bar; +fn main() { + match Foo(Bar) { + _ | Foo(Bar) => {} + } +} +"#, + ); + } + + #[test] + fn record_struct_no_such_field() { + cov_mark::check_count!(validate_match_bailed_out, 1); + + check_diagnostics( + r#" +struct Foo { } +fn main(f: Foo) { + match f { Foo { bar } => () } +} +"#, + ); + } + + #[test] + fn match_ergonomics_issue_9095() { + check_diagnostics_no_bails( + r#" +enum Foo { A(T) } +fn main() { + match &Foo::A(true) { + _ => {} + Foo::A(_) => {} + } +} +"#, + ); + } + + mod false_negatives { + //! The implementation of match checking here is a work in progress. As we roll this out, we + //! prefer false negatives to false positives (ideally there would be no false positives). This + //! test module should document known false negatives. Eventually we will have a complete + //! implementation of match checking and this module will be empty. + //! + //! The reasons for documenting known false negatives: + //! + //! 1. It acts as a backlog of work that can be done to improve the behavior of the system. + //! 2. It ensures the code doesn't panic when handling these cases. + use super::*; + + #[test] + fn integers() { + cov_mark::check_count!(validate_match_bailed_out, 1); + + // We don't currently check integer exhaustiveness. + check_diagnostics( + r#" +fn main() { + match 5 { + 10 => (), + 11..20 => (), + } +} +"#, + ); + } + + #[test] + fn reference_patterns_at_top_level() { + cov_mark::check_count!(validate_match_bailed_out, 1); + + check_diagnostics( + r#" +fn main() { + match &false { + &true => {} + } +} + "#, + ); + } + + #[test] + fn reference_patterns_in_fields() { + cov_mark::check_count!(validate_match_bailed_out, 2); + + check_diagnostics( + r#" +fn main() { + match (&false,) { + (true,) => {} + } + match (&false,) { + (&true,) => {} + } +} + "#, + ); + } + } +} diff --git a/crates/ide_diagnostics/src/handlers/missing_ok_or_some_in_tail_expr.rs b/crates/ide_diagnostics/src/handlers/missing_ok_or_some_in_tail_expr.rs new file mode 100644 index 000000000..63de54570 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/missing_ok_or_some_in_tail_expr.rs @@ -0,0 +1,229 @@ +use hir::db::AstDatabase; +use ide_db::{assists::Assist, source_change::SourceChange}; +use syntax::AstNode; +use text_edit::TextEdit; + +use crate::{fix, Diagnostic, DiagnosticsContext}; + +// Diagnostic: missing-ok-or-some-in-tail-expr +// +// This diagnostic is triggered if a block that should return `Result` returns a value not wrapped in `Ok`, +// or if a block that should return `Option` returns a value not wrapped in `Some`. +// +// Example: +// +// ```rust +// fn foo() -> Result { +// 10 +// } +// ``` +pub(crate) fn missing_ok_or_some_in_tail_expr( + ctx: &DiagnosticsContext<'_>, + d: &hir::MissingOkOrSomeInTailExpr, +) -> Diagnostic { + Diagnostic::new( + "missing-ok-or-some-in-tail-expr", + format!("wrap return expression in {}", d.required), + ctx.sema.diagnostics_display_range(d.expr.clone().map(|it| it.into())).range, + ) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingOkOrSomeInTailExpr) -> Option> { + let root = ctx.sema.db.parse_or_expand(d.expr.file_id)?; + let tail_expr = d.expr.value.to_node(&root); + let tail_expr_range = tail_expr.syntax().text_range(); + let replacement = format!("{}({})", d.required, tail_expr.syntax()); + let edit = TextEdit::replace(tail_expr_range, replacement); + let source_change = + SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), edit); + let name = if d.required == "Ok" { "Wrap with Ok" } else { "Wrap with Some" }; + Some(vec![fix("wrap_tail_expr", name, source_change, tail_expr_range)]) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_diagnostics, check_fix}; + + #[test] + fn test_wrap_return_type_option() { + check_fix( + r#" +//- /main.rs crate:main deps:core +use core::option::Option::{self, Some, None}; + +fn div(x: i32, y: i32) -> Option { + if y == 0 { + return None; + } + x / y$0 +} +//- /core/lib.rs crate:core +pub mod result { + pub enum Result { Ok(T), Err(E) } +} +pub mod option { + pub enum Option { Some(T), None } +} +"#, + r#" +use core::option::Option::{self, Some, None}; + +fn div(x: i32, y: i32) -> Option { + if y == 0 { + return None; + } + Some(x / y) +} +"#, + ); + } + + #[test] + fn test_wrap_return_type() { + check_fix( + r#" +//- /main.rs crate:main deps:core +use core::result::Result::{self, Ok, Err}; + +fn div(x: i32, y: i32) -> Result { + if y == 0 { + return Err(()); + } + x / y$0 +} +//- /core/lib.rs crate:core +pub mod result { + pub enum Result { Ok(T), Err(E) } +} +pub mod option { + pub enum Option { Some(T), None } +} +"#, + r#" +use core::result::Result::{self, Ok, Err}; + +fn div(x: i32, y: i32) -> Result { + if y == 0 { + return Err(()); + } + Ok(x / y) +} +"#, + ); + } + + #[test] + fn test_wrap_return_type_handles_generic_functions() { + check_fix( + r#" +//- /main.rs crate:main deps:core +use core::result::Result::{self, Ok, Err}; + +fn div(x: T) -> Result { + if x == 0 { + return Err(7); + } + $0x +} +//- /core/lib.rs crate:core +pub mod result { + pub enum Result { Ok(T), Err(E) } +} +pub mod option { + pub enum Option { Some(T), None } +} +"#, + r#" +use core::result::Result::{self, Ok, Err}; + +fn div(x: T) -> Result { + if x == 0 { + return Err(7); + } + Ok(x) +} +"#, + ); + } + + #[test] + fn test_wrap_return_type_handles_type_aliases() { + check_fix( + r#" +//- /main.rs crate:main deps:core +use core::result::Result::{self, Ok, Err}; + +type MyResult = Result; + +fn div(x: i32, y: i32) -> MyResult { + if y == 0 { + return Err(()); + } + x $0/ y +} +//- /core/lib.rs crate:core +pub mod result { + pub enum Result { Ok(T), Err(E) } +} +pub mod option { + pub enum Option { Some(T), None } +} +"#, + r#" +use core::result::Result::{self, Ok, Err}; + +type MyResult = Result; + +fn div(x: i32, y: i32) -> MyResult { + if y == 0 { + return Err(()); + } + Ok(x / y) +} +"#, + ); + } + + #[test] + fn test_wrap_return_type_not_applicable_when_expr_type_does_not_match_ok_type() { + check_diagnostics( + r#" +//- /main.rs crate:main deps:core +use core::result::Result::{self, Ok, Err}; + +fn foo() -> Result<(), i32> { 0 } + +//- /core/lib.rs crate:core +pub mod result { + pub enum Result { Ok(T), Err(E) } +} +pub mod option { + pub enum Option { Some(T), None } +} +"#, + ); + } + + #[test] + fn test_wrap_return_type_not_applicable_when_return_type_is_not_result_or_option() { + check_diagnostics( + r#" +//- /main.rs crate:main deps:core +use core::result::Result::{self, Ok, Err}; + +enum SomeOtherEnum { Ok(i32), Err(String) } + +fn foo() -> SomeOtherEnum { 0 } + +//- /core/lib.rs crate:core +pub mod result { + pub enum Result { Ok(T), Err(E) } +} +pub mod option { + pub enum Option { Some(T), None } +} +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/missing_unsafe.rs b/crates/ide_diagnostics/src/handlers/missing_unsafe.rs new file mode 100644 index 000000000..62d8687ba --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/missing_unsafe.rs @@ -0,0 +1,101 @@ +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: missing-unsafe +// +// This diagnostic is triggered if an operation marked as `unsafe` is used outside of an `unsafe` function or block. +pub(crate) fn missing_unsafe(ctx: &DiagnosticsContext<'_>, d: &hir::MissingUnsafe) -> Diagnostic { + Diagnostic::new( + "missing-unsafe", + "this operation is unsafe and requires an unsafe function or block", + ctx.sema.diagnostics_display_range(d.expr.clone().map(|it| it.into())).range, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + #[test] + fn missing_unsafe_diagnostic_with_raw_ptr() { + check_diagnostics( + r#" +fn main() { + let x = &5 as *const usize; + unsafe { let y = *x; } + let z = *x; +} //^^ this operation is unsafe and requires an unsafe function or block +"#, + ) + } + + #[test] + fn missing_unsafe_diagnostic_with_unsafe_call() { + check_diagnostics( + r#" +struct HasUnsafe; + +impl HasUnsafe { + unsafe fn unsafe_fn(&self) { + let x = &5 as *const usize; + let y = *x; + } +} + +unsafe fn unsafe_fn() { + let x = &5 as *const usize; + let y = *x; +} + +fn main() { + unsafe_fn(); + //^^^^^^^^^^^ this operation is unsafe and requires an unsafe function or block + HasUnsafe.unsafe_fn(); + //^^^^^^^^^^^^^^^^^^^^^ this operation is unsafe and requires an unsafe function or block + unsafe { + unsafe_fn(); + HasUnsafe.unsafe_fn(); + } +} +"#, + ); + } + + #[test] + fn missing_unsafe_diagnostic_with_static_mut() { + check_diagnostics( + r#" +struct Ty { + a: u8, +} + +static mut STATIC_MUT: Ty = Ty { a: 0 }; + +fn main() { + let x = STATIC_MUT.a; + //^^^^^^^^^^ this operation is unsafe and requires an unsafe function or block + unsafe { + let x = STATIC_MUT.a; + } +} +"#, + ); + } + + #[test] + fn no_missing_unsafe_diagnostic_with_safe_intrinsic() { + check_diagnostics( + r#" +extern "rust-intrinsic" { + pub fn bitreverse(x: u32) -> u32; // Safe intrinsic + pub fn floorf32(x: f32) -> f32; // Unsafe intrinsic +} + +fn main() { + let _ = bitreverse(12); + let _ = floorf32(12.0); + //^^^^^^^^^^^^^^ this operation is unsafe and requires an unsafe function or block +} +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/no_such_field.rs b/crates/ide_diagnostics/src/handlers/no_such_field.rs new file mode 100644 index 000000000..e4cc8a840 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/no_such_field.rs @@ -0,0 +1,283 @@ +use hir::{db::AstDatabase, HasSource, HirDisplay, Semantics}; +use ide_db::{base_db::FileId, source_change::SourceChange, RootDatabase}; +use syntax::{ + ast::{self, edit::IndentLevel, make}, + AstNode, +}; +use text_edit::TextEdit; + +use crate::{fix, Assist, Diagnostic, DiagnosticsContext}; + +// Diagnostic: no-such-field +// +// This diagnostic is triggered if created structure does not have field provided in record. +pub(crate) fn no_such_field(ctx: &DiagnosticsContext<'_>, d: &hir::NoSuchField) -> Diagnostic { + Diagnostic::new( + "no-such-field", + "no such field", + ctx.sema.diagnostics_display_range(d.field.clone().map(|it| it.into())).range, + ) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::NoSuchField) -> Option> { + let root = ctx.sema.db.parse_or_expand(d.field.file_id)?; + missing_record_expr_field_fixes( + &ctx.sema, + d.field.file_id.original_file(ctx.sema.db), + &d.field.value.to_node(&root), + ) +} + +fn missing_record_expr_field_fixes( + sema: &Semantics, + usage_file_id: FileId, + record_expr_field: &ast::RecordExprField, +) -> Option> { + let record_lit = ast::RecordExpr::cast(record_expr_field.syntax().parent()?.parent()?)?; + let def_id = sema.resolve_variant(record_lit)?; + let module; + let def_file_id; + let record_fields = match def_id { + hir::VariantDef::Struct(s) => { + module = s.module(sema.db); + let source = s.source(sema.db)?; + def_file_id = source.file_id; + let fields = source.value.field_list()?; + record_field_list(fields)? + } + hir::VariantDef::Union(u) => { + module = u.module(sema.db); + let source = u.source(sema.db)?; + def_file_id = source.file_id; + source.value.record_field_list()? + } + hir::VariantDef::Variant(e) => { + module = e.module(sema.db); + let source = e.source(sema.db)?; + def_file_id = source.file_id; + let fields = source.value.field_list()?; + record_field_list(fields)? + } + }; + let def_file_id = def_file_id.original_file(sema.db); + + let new_field_type = sema.type_of_expr(&record_expr_field.expr()?)?; + if new_field_type.is_unknown() { + return None; + } + let new_field = make::record_field( + None, + make::name(&record_expr_field.field_name()?.text()), + make::ty(&new_field_type.display_source_code(sema.db, module.into()).ok()?), + ); + + let last_field = record_fields.fields().last()?; + let last_field_syntax = last_field.syntax(); + let indent = IndentLevel::from_node(last_field_syntax); + + let mut new_field = new_field.to_string(); + if usage_file_id != def_file_id { + new_field = format!("pub(crate) {}", new_field); + } + new_field = format!("\n{}{}", indent, new_field); + + let needs_comma = !last_field_syntax.to_string().ends_with(','); + if needs_comma { + new_field = format!(",{}", new_field); + } + + let source_change = SourceChange::from_text_edit( + def_file_id, + TextEdit::insert(last_field_syntax.text_range().end(), new_field), + ); + + return Some(vec![fix( + "create_field", + "Create field", + source_change, + record_expr_field.syntax().text_range(), + )]); + + fn record_field_list(field_def_list: ast::FieldList) -> Option { + match field_def_list { + ast::FieldList::RecordFieldList(it) => Some(it), + ast::FieldList::TupleFieldList(_) => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_diagnostics, check_fix}; + + #[test] + fn no_such_field_diagnostics() { + check_diagnostics( + r#" +struct S { foo: i32, bar: () } +impl S { + fn new() -> S { + S { + //^ Missing structure fields: + //| - bar + foo: 92, + baz: 62, + //^^^^^^^ no such field + } + } +} +"#, + ); + } + #[test] + fn no_such_field_with_feature_flag_diagnostics() { + check_diagnostics( + r#" +//- /lib.rs crate:foo cfg:feature=foo +struct MyStruct { + my_val: usize, + #[cfg(feature = "foo")] + bar: bool, +} + +impl MyStruct { + #[cfg(feature = "foo")] + pub(crate) fn new(my_val: usize, bar: bool) -> Self { + Self { my_val, bar } + } + #[cfg(not(feature = "foo"))] + pub(crate) fn new(my_val: usize, _bar: bool) -> Self { + Self { my_val } + } +} +"#, + ); + } + + #[test] + fn no_such_field_enum_with_feature_flag_diagnostics() { + check_diagnostics( + r#" +//- /lib.rs crate:foo cfg:feature=foo +enum Foo { + #[cfg(not(feature = "foo"))] + Buz, + #[cfg(feature = "foo")] + Bar, + Baz +} + +fn test_fn(f: Foo) { + match f { + Foo::Bar => {}, + Foo::Baz => {}, + } +} +"#, + ); + } + + #[test] + fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() { + check_diagnostics( + r#" +//- /lib.rs crate:foo cfg:feature=foo +struct S { + #[cfg(feature = "foo")] + foo: u32, + #[cfg(not(feature = "foo"))] + bar: u32, +} + +impl S { + #[cfg(feature = "foo")] + fn new(foo: u32) -> Self { + Self { foo } + } + #[cfg(not(feature = "foo"))] + fn new(bar: u32) -> Self { + Self { bar } + } + fn new2(bar: u32) -> Self { + #[cfg(feature = "foo")] + { Self { foo: bar } } + #[cfg(not(feature = "foo"))] + { Self { bar } } + } + fn new2(val: u32) -> Self { + Self { + #[cfg(feature = "foo")] + foo: val, + #[cfg(not(feature = "foo"))] + bar: val, + } + } +} +"#, + ); + } + + #[test] + fn no_such_field_with_type_macro() { + check_diagnostics( + r#" +macro_rules! Type { () => { u32 }; } +struct Foo { bar: Type![] } + +impl Foo { + fn new() -> Self { + Foo { bar: 0 } + } +} +"#, + ); + } + + #[test] + fn test_add_field_from_usage() { + check_fix( + r" +fn main() { + Foo { bar: 3, baz$0: false}; +} +struct Foo { + bar: i32 +} +", + r" +fn main() { + Foo { bar: 3, baz: false}; +} +struct Foo { + bar: i32, + baz: bool +} +", + ) + } + + #[test] + fn test_add_field_in_other_file_from_usage() { + check_fix( + r#" +//- /main.rs +mod foo; + +fn main() { + foo::Foo { bar: 3, $0baz: false}; +} +//- /foo.rs +struct Foo { + bar: i32 +} +"#, + r#" +struct Foo { + bar: i32, + pub(crate) baz: bool +} +"#, + ) + } +} diff --git a/crates/ide_diagnostics/src/handlers/remove_this_semicolon.rs b/crates/ide_diagnostics/src/handlers/remove_this_semicolon.rs new file mode 100644 index 000000000..b52e4dc84 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/remove_this_semicolon.rs @@ -0,0 +1,61 @@ +use hir::db::AstDatabase; +use ide_db::source_change::SourceChange; +use syntax::{ast, AstNode}; +use text_edit::TextEdit; + +use crate::{fix, Assist, Diagnostic, DiagnosticsContext}; + +// Diagnostic: remove-this-semicolon +// +// This diagnostic is triggered when there's an erroneous `;` at the end of the block. +pub(crate) fn remove_this_semicolon( + ctx: &DiagnosticsContext<'_>, + d: &hir::RemoveThisSemicolon, +) -> Diagnostic { + Diagnostic::new( + "remove-this-semicolon", + "remove this semicolon", + ctx.sema.diagnostics_display_range(d.expr.clone().map(|it| it.into())).range, + ) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::RemoveThisSemicolon) -> Option> { + let root = ctx.sema.db.parse_or_expand(d.expr.file_id)?; + + let semicolon = d + .expr + .value + .to_node(&root) + .syntax() + .parent() + .and_then(ast::ExprStmt::cast) + .and_then(|expr| expr.semicolon_token())? + .text_range(); + + let edit = TextEdit::delete(semicolon); + let source_change = + SourceChange::from_text_edit(d.expr.file_id.original_file(ctx.sema.db), edit); + + Some(vec![fix("remove_semicolon", "Remove this semicolon", source_change, semicolon)]) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_diagnostics, check_fix}; + + #[test] + fn missing_semicolon() { + check_diagnostics( + r#" +fn test() -> i32 { 123; } + //^^^ remove this semicolon +"#, + ); + } + + #[test] + fn remove_semicolon() { + check_fix(r#"fn f() -> i32 { 92$0; }"#, r#"fn f() -> i32 { 92 }"#); + } +} diff --git a/crates/ide_diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs b/crates/ide_diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs new file mode 100644 index 000000000..10d5da15d --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs @@ -0,0 +1,179 @@ +use hir::{db::AstDatabase, InFile}; +use ide_db::source_change::SourceChange; +use syntax::{ + ast::{self, ArgListOwner}, + AstNode, TextRange, +}; +use text_edit::TextEdit; + +use crate::{fix, Assist, Diagnostic, DiagnosticsContext, Severity}; + +// Diagnostic: replace-filter-map-next-with-find-map +// +// This diagnostic is triggered when `.filter_map(..).next()` is used, rather than the more concise `.find_map(..)`. +pub(crate) fn replace_filter_map_next_with_find_map( + ctx: &DiagnosticsContext<'_>, + d: &hir::ReplaceFilterMapNextWithFindMap, +) -> Diagnostic { + Diagnostic::new( + "replace-filter-map-next-with-find-map", + "replace filter_map(..).next() with find_map(..)", + ctx.sema.diagnostics_display_range(InFile::new(d.file, d.next_expr.clone().into())).range, + ) + .severity(Severity::WeakWarning) + .with_fixes(fixes(ctx, d)) +} + +fn fixes( + ctx: &DiagnosticsContext<'_>, + d: &hir::ReplaceFilterMapNextWithFindMap, +) -> Option> { + let root = ctx.sema.db.parse_or_expand(d.file)?; + let next_expr = d.next_expr.to_node(&root); + let next_call = ast::MethodCallExpr::cast(next_expr.syntax().clone())?; + + let filter_map_call = ast::MethodCallExpr::cast(next_call.receiver()?.syntax().clone())?; + let filter_map_name_range = filter_map_call.name_ref()?.ident_token()?.text_range(); + let filter_map_args = filter_map_call.arg_list()?; + + let range_to_replace = + TextRange::new(filter_map_name_range.start(), next_expr.syntax().text_range().end()); + let replacement = format!("find_map{}", filter_map_args.syntax().text()); + let trigger_range = next_expr.syntax().text_range(); + + let edit = TextEdit::replace(range_to_replace, replacement); + + let source_change = SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit); + + Some(vec![fix( + "replace_with_find_map", + "Replace filter_map(..).next() with find_map()", + source_change, + trigger_range, + )]) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_fix; + + // Register the required standard library types to make the tests work + #[track_caller] + fn check_diagnostics(ra_fixture: &str) { + let prefix = r#" +//- /main.rs crate:main deps:core +use core::iter::Iterator; +use core::option::Option::{self, Some, None}; +"#; + let suffix = r#" +//- /core/lib.rs crate:core +pub mod option { + pub enum Option { Some(T), None } +} +pub mod iter { + pub trait Iterator { + type Item; + fn filter_map(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option { FilterMap } + fn next(&mut self) -> Option; + } + pub struct FilterMap {} + impl Iterator for FilterMap { + type Item = i32; + fn next(&mut self) -> i32 { 7 } + } +} +"#; + crate::tests::check_diagnostics(&format!("{}{}{}", prefix, ra_fixture, suffix)) + } + + #[test] + fn replace_filter_map_next_with_find_map2() { + check_diagnostics( + r#" + fn foo() { + let m = [1, 2, 3].iter().filter_map(|x| if *x == 2 { Some (4) } else { None }).next(); + } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ replace filter_map(..).next() with find_map(..) +"#, + ); + } + + #[test] + fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() { + check_diagnostics( + r#" +fn foo() { + let m = [1, 2, 3] + .iter() + .filter_map(|x| if *x == 2 { Some (4) } else { None }) + .len(); +} +"#, + ); + } + + #[test] + fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() { + check_diagnostics( + r#" +fn foo() { + let m = [1, 2, 3] + .iter() + .filter_map(|x| if *x == 2 { Some (4) } else { None }) + .map(|x| x + 2) + .len(); +} +"#, + ); + } + + #[test] + fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() { + check_diagnostics( + r#" +fn foo() { + let m = [1, 2, 3] + .iter() + .filter_map(|x| if *x == 2 { Some (4) } else { None }); + let n = m.next(); +} +"#, + ); + } + + #[test] + fn replace_with_wind_map() { + check_fix( + r#" +//- /main.rs crate:main deps:core +use core::iter::Iterator; +use core::option::Option::{self, Some, None}; +fn foo() { + let m = [1, 2, 3].iter().$0filter_map(|x| if *x == 2 { Some (4) } else { None }).next(); +} +//- /core/lib.rs crate:core +pub mod option { + pub enum Option { Some(T), None } +} +pub mod iter { + pub trait Iterator { + type Item; + fn filter_map(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option { FilterMap } + fn next(&mut self) -> Option; + } + pub struct FilterMap {} + impl Iterator for FilterMap { + type Item = i32; + fn next(&mut self) -> i32 { 7 } + } +} +"#, + r#" +use core::iter::Iterator; +use core::option::Option::{self, Some, None}; +fn foo() { + let m = [1, 2, 3].iter().find_map(|x| if *x == 2 { Some (4) } else { None }); +} +"#, + ) + } +} diff --git a/crates/ide_diagnostics/src/handlers/unimplemented_builtin_macro.rs b/crates/ide_diagnostics/src/handlers/unimplemented_builtin_macro.rs new file mode 100644 index 000000000..e879de75c --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unimplemented_builtin_macro.rs @@ -0,0 +1,16 @@ +use crate::{Diagnostic, DiagnosticsContext, Severity}; + +// Diagnostic: unimplemented-builtin-macro +// +// This diagnostic is shown for builtin macros which are not yet implemented by rust-analyzer +pub(crate) fn unimplemented_builtin_macro( + ctx: &DiagnosticsContext<'_>, + d: &hir::UnimplementedBuiltinMacro, +) -> Diagnostic { + Diagnostic::new( + "unimplemented-builtin-macro", + "unimplemented built-in macro".to_string(), + ctx.sema.diagnostics_display_range(d.node.clone()).range, + ) + .severity(Severity::WeakWarning) +} diff --git a/crates/ide_diagnostics/src/handlers/unlinked_file.rs b/crates/ide_diagnostics/src/handlers/unlinked_file.rs new file mode 100644 index 000000000..8921ddde2 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unlinked_file.rs @@ -0,0 +1,301 @@ +//! Diagnostic emitted for files that aren't part of any crate. + +use hir::db::DefDatabase; +use ide_db::{ + base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt}, + source_change::SourceChange, + RootDatabase, +}; +use syntax::{ + ast::{self, ModuleItemOwner, NameOwner}, + AstNode, TextRange, TextSize, +}; +use text_edit::TextEdit; + +use crate::{fix, Assist, Diagnostic, DiagnosticsContext}; + +#[derive(Debug)] +pub(crate) struct UnlinkedFile { + pub(crate) file: FileId, +} + +// Diagnostic: unlinked-file +// +// This diagnostic is shown for files that are not included in any crate, or files that are part of +// crates rust-analyzer failed to discover. The file will not have IDE features available. +pub(crate) fn unlinked_file(ctx: &DiagnosticsContext, d: &UnlinkedFile) -> Diagnostic { + // Limit diagnostic to the first few characters in the file. This matches how VS Code + // renders it with the full span, but on other editors, and is less invasive. + let range = ctx.sema.db.parse(d.file).syntax_node().text_range(); + // FIXME: This is wrong if one of the first three characters is not ascii: `//Ы`. + let range = range.intersect(TextRange::up_to(TextSize::of("..."))).unwrap_or(range); + + Diagnostic::new("unlinked-file", "file not included in module tree", range) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext, d: &UnlinkedFile) -> Option> { + // If there's an existing module that could add `mod` or `pub mod` items to include the unlinked file, + // suggest that as a fix. + + let source_root = ctx.sema.db.source_root(ctx.sema.db.file_source_root(d.file)); + let our_path = source_root.path_for_file(&d.file)?; + let module_name = our_path.name_and_extension()?.0; + + // Candidates to look for: + // - `mod.rs` in the same folder + // - we also check `main.rs` and `lib.rs` + // - `$dir.rs` in the parent folder, where `$dir` is the directory containing `self.file_id` + let parent = our_path.parent()?; + let mut paths = vec![parent.join("mod.rs")?, parent.join("lib.rs")?, parent.join("main.rs")?]; + + // `submod/bla.rs` -> `submod.rs` + if let Some(newmod) = (|| { + let name = parent.name_and_extension()?.0; + parent.parent()?.join(&format!("{}.rs", name)) + })() { + paths.push(newmod); + } + + for path in &paths { + if let Some(parent_id) = source_root.file_for_path(path) { + for krate in ctx.sema.db.relevant_crates(*parent_id).iter() { + let crate_def_map = ctx.sema.db.crate_def_map(*krate); + for (_, module) in crate_def_map.modules() { + if module.origin.is_inline() { + // We don't handle inline `mod parent {}`s, they use different paths. + continue; + } + + if module.origin.file_id() == Some(*parent_id) { + return make_fixes(ctx.sema.db, *parent_id, module_name, d.file); + } + } + } + } + } + + None +} + +fn make_fixes( + db: &RootDatabase, + parent_file_id: FileId, + new_mod_name: &str, + added_file_id: FileId, +) -> Option> { + fn is_outline_mod(item: &ast::Item) -> bool { + matches!(item, ast::Item::Module(m) if m.item_list().is_none()) + } + + let mod_decl = format!("mod {};", new_mod_name); + let pub_mod_decl = format!("pub mod {};", new_mod_name); + + let ast: ast::SourceFile = db.parse(parent_file_id).tree(); + + let mut mod_decl_builder = TextEdit::builder(); + let mut pub_mod_decl_builder = TextEdit::builder(); + + // If there's an existing `mod m;` statement matching the new one, don't emit a fix (it's + // probably `#[cfg]`d out). + for item in ast.items() { + if let ast::Item::Module(m) = item { + if let Some(name) = m.name() { + if m.item_list().is_none() && name.to_string() == new_mod_name { + cov_mark::hit!(unlinked_file_skip_fix_when_mod_already_exists); + return None; + } + } + } + } + + // If there are existing `mod m;` items, append after them (after the first group of them, rather). + match ast + .items() + .skip_while(|item| !is_outline_mod(item)) + .take_while(|item| is_outline_mod(item)) + .last() + { + Some(last) => { + cov_mark::hit!(unlinked_file_append_to_existing_mods); + let offset = last.syntax().text_range().end(); + mod_decl_builder.insert(offset, format!("\n{}", mod_decl)); + pub_mod_decl_builder.insert(offset, format!("\n{}", pub_mod_decl)); + } + None => { + // Prepend before the first item in the file. + match ast.items().next() { + Some(item) => { + cov_mark::hit!(unlinked_file_prepend_before_first_item); + let offset = item.syntax().text_range().start(); + mod_decl_builder.insert(offset, format!("{}\n\n", mod_decl)); + pub_mod_decl_builder.insert(offset, format!("{}\n\n", pub_mod_decl)); + } + None => { + // No items in the file, so just append at the end. + cov_mark::hit!(unlinked_file_empty_file); + let offset = ast.syntax().text_range().end(); + mod_decl_builder.insert(offset, format!("{}\n", mod_decl)); + pub_mod_decl_builder.insert(offset, format!("{}\n", pub_mod_decl)); + } + } + } + } + + let trigger_range = db.parse(added_file_id).tree().syntax().text_range(); + Some(vec![ + fix( + "add_mod_declaration", + &format!("Insert `{}`", mod_decl), + SourceChange::from_text_edit(parent_file_id, mod_decl_builder.finish()), + trigger_range, + ), + fix( + "add_pub_mod_declaration", + &format!("Insert `{}`", pub_mod_decl), + SourceChange::from_text_edit(parent_file_id, pub_mod_decl_builder.finish()), + trigger_range, + ), + ]) +} + +#[cfg(test)] +mod tests { + use crate::tests::{check_diagnostics, check_fix, check_fixes, check_no_fix}; + + #[test] + fn unlinked_file_prepend_first_item() { + cov_mark::check!(unlinked_file_prepend_before_first_item); + // Only tests the first one for `pub mod` since the rest are the same + check_fixes( + r#" +//- /main.rs +fn f() {} +//- /foo.rs +$0 +"#, + vec![ + r#" +mod foo; + +fn f() {} +"#, + r#" +pub mod foo; + +fn f() {} +"#, + ], + ); + } + + #[test] + fn unlinked_file_append_mod() { + cov_mark::check!(unlinked_file_append_to_existing_mods); + check_fix( + r#" +//- /main.rs +//! Comment on top + +mod preexisting; + +mod preexisting2; + +struct S; + +mod preexisting_bottom;) +//- /foo.rs +$0 +"#, + r#" +//! Comment on top + +mod preexisting; + +mod preexisting2; +mod foo; + +struct S; + +mod preexisting_bottom;) +"#, + ); + } + + #[test] + fn unlinked_file_insert_in_empty_file() { + cov_mark::check!(unlinked_file_empty_file); + check_fix( + r#" +//- /main.rs +//- /foo.rs +$0 +"#, + r#" +mod foo; +"#, + ); + } + + #[test] + fn unlinked_file_old_style_modrs() { + check_fix( + r#" +//- /main.rs +mod submod; +//- /submod/mod.rs +// in mod.rs +//- /submod/foo.rs +$0 +"#, + r#" +// in mod.rs +mod foo; +"#, + ); + } + + #[test] + fn unlinked_file_new_style_mod() { + check_fix( + r#" +//- /main.rs +mod submod; +//- /submod.rs +//- /submod/foo.rs +$0 +"#, + r#" +mod foo; +"#, + ); + } + + #[test] + fn unlinked_file_with_cfg_off() { + cov_mark::check!(unlinked_file_skip_fix_when_mod_already_exists); + check_no_fix( + r#" +//- /main.rs +#[cfg(never)] +mod foo; + +//- /foo.rs +$0 +"#, + ); + } + + #[test] + fn unlinked_file_with_cfg_on() { + check_diagnostics( + r#" +//- /main.rs +#[cfg(not(never))] +mod foo; + +//- /foo.rs +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/unresolved_extern_crate.rs b/crates/ide_diagnostics/src/handlers/unresolved_extern_crate.rs new file mode 100644 index 000000000..f5313cc0c --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unresolved_extern_crate.rs @@ -0,0 +1,49 @@ +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: unresolved-extern-crate +// +// This diagnostic is triggered if rust-analyzer is unable to discover referred extern crate. +pub(crate) fn unresolved_extern_crate( + ctx: &DiagnosticsContext<'_>, + d: &hir::UnresolvedExternCrate, +) -> Diagnostic { + Diagnostic::new( + "unresolved-extern-crate", + "unresolved extern crate", + ctx.sema.diagnostics_display_range(d.decl.clone().map(|it| it.into())).range, + ) +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + #[test] + fn unresolved_extern_crate() { + check_diagnostics( + r#" +//- /main.rs crate:main deps:core +extern crate core; + extern crate doesnotexist; +//^^^^^^^^^^^^^^^^^^^^^^^^^^ unresolved extern crate +//- /lib.rs crate:core +"#, + ); + } + + #[test] + fn extern_crate_self_as() { + cov_mark::check!(extern_crate_self_as); + check_diagnostics( + r#" +//- /lib.rs + extern crate doesnotexist; +//^^^^^^^^^^^^^^^^^^^^^^^^^^ unresolved extern crate +// Should not error. +extern crate self as foo; +struct Foo; +use foo::Foo as Bar; +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/unresolved_import.rs b/crates/ide_diagnostics/src/handlers/unresolved_import.rs new file mode 100644 index 000000000..f30051c12 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unresolved_import.rs @@ -0,0 +1,90 @@ +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: unresolved-import +// +// This diagnostic is triggered if rust-analyzer is unable to resolve a path in +// a `use` declaration. +pub(crate) fn unresolved_import( + ctx: &DiagnosticsContext<'_>, + d: &hir::UnresolvedImport, +) -> Diagnostic { + Diagnostic::new( + "unresolved-import", + "unresolved import", + ctx.sema.diagnostics_display_range(d.decl.clone().map(|it| it.into())).range, + ) + // This currently results in false positives in the following cases: + // - `cfg_if!`-generated code in libstd (we don't load the sysroot correctly) + // - `core::arch` (we don't handle `#[path = "../"]` correctly) + // - proc macros and/or proc macro generated code + .experimental() +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + #[test] + fn unresolved_import() { + check_diagnostics( + r#" +use does_exist; +use does_not_exist; + //^^^^^^^^^^^^^^ unresolved import + +mod does_exist {} +"#, + ); + } + + #[test] + fn unresolved_import_in_use_tree() { + // Only the relevant part of a nested `use` item should be highlighted. + check_diagnostics( + r#" +use does_exist::{Exists, DoesntExist}; + //^^^^^^^^^^^ unresolved import + +use {does_not_exist::*, does_exist}; + //^^^^^^^^^^^^^^^^^ unresolved import + +use does_not_exist::{ + a, + //^ unresolved import + b, + //^ unresolved import + c, + //^ unresolved import +}; + +mod does_exist { + pub struct Exists; +} +"#, + ); + } + + #[test] + fn dedup_unresolved_import_from_unresolved_crate() { + check_diagnostics( + r#" +//- /main.rs crate:main +mod a { + extern crate doesnotexist; + //^^^^^^^^^^^^^^^^^^^^^^^^^^ unresolved extern crate + + // Should not error, since we already errored for the missing crate. + use doesnotexist::{self, bla, *}; + + use crate::doesnotexist; + //^^^^^^^^^^^^^^^^^^^ unresolved import +} + +mod m { + use super::doesnotexist; + //^^^^^^^^^^^^^^^^^^^ unresolved import +} +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/unresolved_macro_call.rs b/crates/ide_diagnostics/src/handlers/unresolved_macro_call.rs new file mode 100644 index 000000000..4c3c1c19a --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unresolved_macro_call.rs @@ -0,0 +1,84 @@ +use hir::{db::AstDatabase, InFile}; +use syntax::{AstNode, SyntaxNodePtr}; + +use crate::{Diagnostic, DiagnosticsContext}; + +// Diagnostic: unresolved-macro-call +// +// This diagnostic is triggered if rust-analyzer is unable to resolve the path +// to a macro in a macro invocation. +pub(crate) fn unresolved_macro_call( + ctx: &DiagnosticsContext<'_>, + d: &hir::UnresolvedMacroCall, +) -> Diagnostic { + let last_path_segment = ctx.sema.db.parse_or_expand(d.macro_call.file_id).and_then(|root| { + d.macro_call + .value + .to_node(&root) + .path() + .and_then(|it| it.segment()) + .and_then(|it| it.name_ref()) + .map(|it| InFile::new(d.macro_call.file_id, SyntaxNodePtr::new(it.syntax()))) + }); + let diagnostics = last_path_segment.unwrap_or_else(|| d.macro_call.clone().map(|it| it.into())); + + Diagnostic::new( + "unresolved-macro-call", + format!("unresolved macro `{}!`", d.path), + ctx.sema.diagnostics_display_range(diagnostics).range, + ) + .experimental() +} + +#[cfg(test)] +mod tests { + use crate::tests::check_diagnostics; + + #[test] + fn unresolved_macro_diag() { + check_diagnostics( + r#" +fn f() { + m!(); +} //^ unresolved macro `m!` + +"#, + ); + } + + #[test] + fn test_unresolved_macro_range() { + check_diagnostics( + r#" +foo::bar!(92); + //^^^ unresolved macro `foo::bar!` +"#, + ); + } + + #[test] + fn unresolved_legacy_scope_macro() { + check_diagnostics( + r#" +macro_rules! m { () => {} } + +m!(); m2!(); + //^^ unresolved macro `self::m2!` +"#, + ); + } + + #[test] + fn unresolved_module_scope_macro() { + check_diagnostics( + r#" +mod mac { +#[macro_export] +macro_rules! m { () => {} } } + +self::m!(); self::m2!(); + //^^ unresolved macro `self::m2!` +"#, + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/unresolved_module.rs b/crates/ide_diagnostics/src/handlers/unresolved_module.rs new file mode 100644 index 000000000..17166a0c6 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unresolved_module.rs @@ -0,0 +1,110 @@ +use hir::db::AstDatabase; +use ide_db::{assists::Assist, base_db::AnchoredPathBuf, source_change::FileSystemEdit}; +use syntax::AstNode; + +use crate::{fix, Diagnostic, DiagnosticsContext}; + +// Diagnostic: unresolved-module +// +// This diagnostic is triggered if rust-analyzer is unable to discover referred module. +pub(crate) fn unresolved_module( + ctx: &DiagnosticsContext<'_>, + d: &hir::UnresolvedModule, +) -> Diagnostic { + Diagnostic::new( + "unresolved-module", + "unresolved module", + ctx.sema.diagnostics_display_range(d.decl.clone().map(|it| it.into())).range, + ) + .with_fixes(fixes(ctx, d)) +} + +fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedModule) -> Option> { + let root = ctx.sema.db.parse_or_expand(d.decl.file_id)?; + let unresolved_module = d.decl.value.to_node(&root); + Some(vec![fix( + "create_module", + "Create module", + FileSystemEdit::CreateFile { + dst: AnchoredPathBuf { + anchor: d.decl.file_id.original_file(ctx.sema.db), + path: d.candidate.clone(), + }, + initial_contents: "".to_string(), + } + .into(), + unresolved_module.syntax().text_range(), + )]) +} + +#[cfg(test)] +mod tests { + use expect_test::expect; + + use crate::tests::{check_diagnostics, check_expect}; + + #[test] + fn unresolved_module() { + check_diagnostics( + r#" +//- /lib.rs +mod foo; + mod bar; +//^^^^^^^^ unresolved module +mod baz {} +//- /foo.rs +"#, + ); + } + + #[test] + fn test_unresolved_module_diagnostic() { + check_expect( + r#"mod foo;"#, + expect![[r#" + [ + Diagnostic { + code: DiagnosticCode( + "unresolved-module", + ), + message: "unresolved module", + range: 0..8, + severity: Error, + unused: false, + experimental: false, + fixes: Some( + [ + Assist { + id: AssistId( + "create_module", + QuickFix, + ), + label: "Create module", + group: None, + target: 0..8, + source_change: Some( + SourceChange { + source_file_edits: {}, + file_system_edits: [ + CreateFile { + dst: AnchoredPathBuf { + anchor: FileId( + 0, + ), + path: "foo.rs", + }, + initial_contents: "", + }, + ], + is_snippet: false, + }, + ), + }, + ], + ), + }, + ] + "#]], + ); + } +} diff --git a/crates/ide_diagnostics/src/handlers/unresolved_proc_macro.rs b/crates/ide_diagnostics/src/handlers/unresolved_proc_macro.rs new file mode 100644 index 000000000..fde1d1323 --- /dev/null +++ b/crates/ide_diagnostics/src/handlers/unresolved_proc_macro.rs @@ -0,0 +1,27 @@ +use crate::{Diagnostic, DiagnosticsContext, Severity}; + +// Diagnostic: unresolved-proc-macro +// +// This diagnostic is shown when a procedural macro can not be found. This usually means that +// procedural macro support is simply disabled (and hence is only a weak hint instead of an error), +// but can also indicate project setup problems. +// +// If you are seeing a lot of "proc macro not expanded" warnings, you can add this option to the +// `rust-analyzer.diagnostics.disabled` list to prevent them from showing. Alternatively you can +// enable support for procedural macros (see `rust-analyzer.procMacro.enable`). +pub(crate) fn unresolved_proc_macro( + ctx: &DiagnosticsContext<'_>, + d: &hir::UnresolvedProcMacro, +) -> Diagnostic { + // Use more accurate position if available. + let display_range = d + .precise_location + .unwrap_or_else(|| ctx.sema.diagnostics_display_range(d.node.clone()).range); + // FIXME: it would be nice to tell the user whether proc macros are currently disabled + let message = match &d.macro_name { + Some(name) => format!("proc macro `{}` not expanded", name), + None => "proc macro not expanded".to_string(), + }; + + Diagnostic::new("unresolved-proc-macro", message, display_range).severity(Severity::WeakWarning) +} -- cgit v1.2.3