1 //! This module resolves `mod foo;` declaration to file.
2 use hir_expand::name::Name;
3 use ra_db::{FileId, RelativePathBuf};
4 use ra_syntax::SmolStr;
6 use crate::{db::DefDatabase, HirFileId};
8 #[derive(Clone, Debug)]
9 pub(super) struct ModDir {
10 /// `.` for `mod.rs`, `lib.rs`
11 /// `./foo` for `foo.rs`
12 /// `./foo/bar` for `mod bar { mod x; }` nested in `foo.rs`
13 path: RelativePathBuf,
14 /// inside `./foo.rs`, mods with `#[path]` should *not* be relative to `./foo/`
15 root_non_dir_owner: bool,
19 pub(super) fn root() -> ModDir {
20 ModDir { path: RelativePathBuf::default(), root_non_dir_owner: false }
23 pub(super) fn descend_into_definition(
26 attr_path: Option<&SmolStr>,
28 let mut path = self.path.clone();
29 match attr_to_path(attr_path) {
30 None => path.push(&name.to_string()),
32 if self.root_non_dir_owner {
38 ModDir { path, root_non_dir_owner: false }
41 pub(super) fn resolve_declaration(
46 attr_path: Option<&SmolStr>,
47 ) -> Result<(FileId, bool, ModDir), String> {
48 let file_id = file_id.original_file(db.upcast());
50 let mut candidate_files = Vec::new();
51 match attr_to_path(attr_path) {
54 if self.root_non_dir_owner { self.path.parent().unwrap() } else { &self.path };
55 candidate_files.push(base.join(attr_path).to_string())
58 candidate_files.push(self.path.join(&format!("{}.rs", name)).to_string());
59 candidate_files.push(self.path.join(&format!("{}/mod.rs", name)).to_string());
63 for candidate in candidate_files.iter() {
64 if let Some(file_id) = db.resolve_path(file_id, candidate.as_str()) {
65 let mut root_non_dir_owner = false;
66 let mut mod_path = RelativePathBuf::new();
67 let is_mod_rs = candidate.ends_with("mod.rs");
68 if !(is_mod_rs || attr_path.is_some()) {
69 root_non_dir_owner = true;
70 mod_path.push(&name.to_string());
72 return Ok((file_id, is_mod_rs, ModDir { path: mod_path, root_non_dir_owner }));
75 Err(candidate_files.remove(0))
79 fn attr_to_path(attr: Option<&SmolStr>) -> Option<RelativePathBuf> {
80 attr.and_then(|it| RelativePathBuf::from_path(&it.replace("\\", "/")).ok())