1 //! This module resolves `mod foo;` declaration to file.
2 use hir_expand::name::Name;
4 use ra_syntax::SmolStr;
5 use relative_path::RelativePathBuf;
7 use crate::{db::DefDatabase2, HirFileId};
9 #[derive(Clone, Debug)]
11 /// `.` for `mod.rs`, `lib.rs`
12 /// `./foo` for `foo.rs`
13 /// `./foo/bar` for `mod bar { mod x; }` nested in `foo.rs`
14 path: RelativePathBuf,
15 /// inside `./foo.rs`, mods with `#[path]` should *not* be relative to `./foo/`
16 root_non_dir_owner: bool,
20 pub fn root() -> ModDir {
21 ModDir { path: RelativePathBuf::default(), root_non_dir_owner: false }
24 pub fn descend_into_definition(&self, name: &Name, attr_path: Option<&SmolStr>) -> ModDir {
25 let mut path = self.path.clone();
26 match attr_to_path(attr_path) {
27 None => path.push(&name.to_string()),
29 if self.root_non_dir_owner {
35 ModDir { path, root_non_dir_owner: false }
38 pub fn resolve_declaration(
40 db: &impl DefDatabase2,
43 attr_path: Option<&SmolStr>,
44 ) -> Result<(FileId, ModDir), RelativePathBuf> {
45 let file_id = file_id.original_file(db);
47 let mut candidate_files = Vec::new();
48 match attr_to_path(attr_path) {
51 if self.root_non_dir_owner { self.path.parent().unwrap() } else { &self.path };
52 candidate_files.push(base.join(attr_path))
55 candidate_files.push(self.path.join(&format!("{}.rs", name)));
56 candidate_files.push(self.path.join(&format!("{}/mod.rs", name)));
60 for candidate in candidate_files.iter() {
61 if let Some(file_id) = db.resolve_relative_path(file_id, candidate) {
62 let mut root_non_dir_owner = false;
63 let mut mod_path = RelativePathBuf::new();
64 if !(candidate.ends_with("mod.rs") || attr_path.is_some()) {
65 root_non_dir_owner = true;
66 mod_path.push(&name.to_string());
68 return Ok((file_id, ModDir { path: mod_path, root_non_dir_owner }));
71 Err(candidate_files.remove(0))
75 fn attr_to_path(attr: Option<&SmolStr>) -> Option<RelativePathBuf> {
76 attr.and_then(|it| RelativePathBuf::from_path(&it.replace("\\", "/")).ok())