fix: Show what file paths were expected for unresolved modules

This commit is contained in:
Lukas Wirth 2022-03-11 16:49:41 +01:00
parent 6c8c02f625
commit a9dd606387
12 changed files with 133 additions and 59 deletions

View file

@ -1,5 +1,6 @@
use hir::db::AstDatabase;
use ide_db::{assists::Assist, base_db::AnchoredPathBuf, source_change::FileSystemEdit};
use itertools::Itertools;
use syntax::AstNode;
use crate::{fix, Diagnostic, DiagnosticsContext};
@ -13,7 +14,17 @@ pub(crate) fn unresolved_module(
) -> Diagnostic {
Diagnostic::new(
"unresolved-module",
"unresolved module",
match &*d.candidates {
[] => "unresolved module".to_string(),
[candidate] => format!("unresolved module, can't find module file: {}", candidate),
[candidates @ .., last] => {
format!(
"unresolved module, can't find module file: {}, or {}",
candidates.iter().format(", "),
last
)
}
},
ctx.sema.diagnostics_display_range(d.decl.clone().map(|it| it.into())).range,
)
.with_fixes(fixes(ctx, d))
@ -22,19 +33,26 @@ pub(crate) fn unresolved_module(
fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedModule) -> Option<Vec<Assist>> {
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(),
)])
Some(
d.candidates
.iter()
.map(|candidate| {
fix(
"create_module",
"Create module",
FileSystemEdit::CreateFile {
dst: AnchoredPathBuf {
anchor: d.decl.file_id.original_file(ctx.sema.db),
path: candidate.clone(),
},
initial_contents: "".to_string(),
}
.into(),
unresolved_module.syntax().text_range(),
)
})
.collect(),
)
}
#[cfg(test)]
@ -50,7 +68,7 @@ mod tests {
//- /lib.rs
mod foo;
mod bar;
//^^^^^^^^ 💡 error: unresolved module
//^^^^^^^^ 💡 error: unresolved module, can't find module file: bar.rs, or bar/mod.rs
mod baz {}
//- /foo.rs
"#,
@ -67,7 +85,7 @@ mod baz {}
code: DiagnosticCode(
"unresolved-module",
),
message: "unresolved module",
message: "unresolved module, can't find module file: foo.rs, or foo/mod.rs",
range: 0..8,
severity: Error,
unused: false,
@ -100,6 +118,32 @@ mod baz {}
},
),
},
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/mod.rs",
},
initial_contents: "",
},
],
is_snippet: false,
},
),
},
],
),
},