1 //! Diagnostic emitted for files that aren't part of any crate.
5 diagnostics::{Diagnostic, DiagnosticCode},
9 base_db::{FileId, FileLoader, SourceDatabase, SourceDatabaseExt},
10 source_change::SourceChange,
14 ast::{self, ModuleItemOwner, NameOwner},
15 AstNode, SyntaxNodePtr,
17 use text_edit::TextEdit;
21 use super::fixes::DiagnosticWithFix;
23 // Diagnostic: unlinked-file
25 // This diagnostic is shown for files that are not included in any crate, or files that are part of
26 // crates rust-analyzer failed to discover. The file will not have IDE features available.
28 pub(crate) struct UnlinkedFile {
29 pub(crate) file_id: FileId,
30 pub(crate) node: SyntaxNodePtr,
33 impl Diagnostic for UnlinkedFile {
34 fn code(&self) -> DiagnosticCode {
35 DiagnosticCode("unlinked-file")
38 fn message(&self) -> String {
39 "file not included in module tree".to_string()
42 fn display_source(&self) -> InFile<SyntaxNodePtr> {
43 InFile::new(self.file_id.into(), self.node.clone())
46 fn as_any(&self) -> &(dyn std::any::Any + Send + 'static) {
51 impl DiagnosticWithFix for UnlinkedFile {
52 fn fix(&self, sema: &hir::Semantics<RootDatabase>) -> Option<Fix> {
53 // If there's an existing module that could add a `mod` item to include the unlinked file,
54 // suggest that as a fix.
56 let source_root = sema.db.source_root(sema.db.file_source_root(self.file_id));
57 let our_path = source_root.path_for_file(&self.file_id)?;
58 let module_name = our_path.name_and_extension()?.0;
60 // Candidates to look for:
61 // - `mod.rs` in the same folder
62 // - we also check `main.rs` and `lib.rs`
63 // - `$dir.rs` in the parent folder, where `$dir` is the directory containing `self.file_id`
64 let parent = our_path.parent()?;
66 vec![parent.join("mod.rs")?, parent.join("main.rs")?, parent.join("lib.rs")?];
68 // `submod/bla.rs` -> `submod.rs`
69 if let Some(newmod) = (|| {
70 let name = parent.name_and_extension()?.0;
71 parent.parent()?.join(&format!("{}.rs", name))
77 if let Some(parent_id) = source_root.file_for_path(path) {
78 for krate in sema.db.relevant_crates(*parent_id).iter() {
79 let crate_def_map = sema.db.crate_def_map(*krate);
80 for (_, module) in crate_def_map.modules() {
81 if module.origin.is_inline() {
82 // We don't handle inline `mod parent {}`s, they use different paths.
86 if module.origin.file_id() == Some(*parent_id) {
87 return make_fix(sema.db, *parent_id, module_name, self.file_id);
100 parent_file_id: FileId,
102 added_file_id: FileId,
104 fn is_outline_mod(item: &ast::Item) -> bool {
105 matches!(item, ast::Item::Module(m) if m.item_list().is_none())
108 let mod_decl = format!("mod {};", new_mod_name);
109 let ast: ast::SourceFile = db.parse(parent_file_id).tree();
111 let mut builder = TextEdit::builder();
113 // If there's an existing `mod m;` statement matching the new one, don't emit a fix (it's
114 // probably `#[cfg]`d out).
115 for item in ast.items() {
116 if let ast::Item::Module(m) = item {
117 if let Some(name) = m.name() {
118 if m.item_list().is_none() && name.to_string() == new_mod_name {
119 cov_mark::hit!(unlinked_file_skip_fix_when_mod_already_exists);
126 // If there are existing `mod m;` items, append after them (after the first group of them, rather).
129 .skip_while(|item| !is_outline_mod(item))
130 .take_while(|item| is_outline_mod(item))
134 cov_mark::hit!(unlinked_file_append_to_existing_mods);
135 builder.insert(last.syntax().text_range().end(), format!("\n{}", mod_decl));
138 // Prepend before the first item in the file.
139 match ast.items().next() {
141 cov_mark::hit!(unlinked_file_prepend_before_first_item);
142 builder.insert(item.syntax().text_range().start(), format!("{}\n\n", mod_decl));
145 // No items in the file, so just append at the end.
146 cov_mark::hit!(unlinked_file_empty_file);
147 builder.insert(ast.syntax().text_range().end(), format!("{}\n", mod_decl));
153 let edit = builder.finish();
154 let trigger_range = db.parse(added_file_id).tree().syntax().text_range();
156 &format!("Insert `{}`", mod_decl),
157 SourceChange::from_text_edit(parent_file_id, edit),