ide_diagnostics/handlers/
unresolved_import.rs

1use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
2
3// Diagnostic: unresolved-import
4//
5// This diagnostic is triggered if rust-analyzer is unable to resolve a path in
6// a `use` declaration.
7pub(crate) fn unresolved_import(
8    ctx: &DiagnosticsContext<'_>,
9    d: &hir::UnresolvedImport,
10) -> Diagnostic {
11    Diagnostic::new_with_syntax_node_ptr(
12        ctx,
13        DiagnosticCode::RustcHardError("E0432"),
14        "unresolved import",
15        d.decl.map(|it| it.into()),
16    )
17    // This currently results in false positives in the following cases:
18    // - `cfg_if!`-generated code in libstd (we don't load the sysroot correctly)
19    // - `core::arch` (we don't handle `#[path = "../<path>"]` correctly)
20    // - proc macros and/or proc macro generated code
21}
22
23#[cfg(test)]
24mod tests {
25    use crate::tests::check_diagnostics;
26
27    #[test]
28    fn unresolved_import() {
29        check_diagnostics(
30            r#"
31use does_exist;
32use does_not_exist;
33  //^^^^^^^^^^^^^^ error: unresolved import
34
35mod does_exist {}
36"#,
37        );
38    }
39
40    #[test]
41    fn unresolved_import_in_use_tree() {
42        // Only the relevant part of a nested `use` item should be highlighted.
43        check_diagnostics(
44            r#"
45use does_exist::{Exists, DoesntExist};
46                       //^^^^^^^^^^^ error: unresolved import
47
48use {does_not_exist::*, does_exist};
49   //^^^^^^^^^^^^^^^^^ error: unresolved import
50
51use does_not_exist::{
52    a,
53  //^ error: unresolved import
54    b,
55  //^ error: unresolved import
56    c,
57  //^ error: unresolved import
58};
59
60mod does_exist {
61    pub struct Exists;
62}
63"#,
64        );
65    }
66
67    #[test]
68    fn dedup_unresolved_import_from_unresolved_crate() {
69        check_diagnostics(
70            r#"
71//- /main.rs crate:main
72mod a {
73    extern crate doesnotexist;
74  //^^^^^^^^^^^^^^^^^^^^^^^^^^ error: unresolved extern crate
75
76    // Should not error, since we already errored for the missing crate.
77    use doesnotexist::{self, bla, *};
78
79    use crate::doesnotexist;
80      //^^^^^^^^^^^^^^^^^^^ error: unresolved import
81}
82
83mod m {
84    use super::doesnotexist;
85      //^^^^^^^^^^^^^^^^^^^ error: unresolved import
86}
87"#,
88        );
89    }
90}