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::DefDatabase2, HirFileId};
8 #[derive(Clone, Debug)]
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 fn root() -> ModDir {
20 ModDir { path: RelativePathBuf::default(), root_non_dir_owner: false }
23 pub fn descend_into_definition(&self, name: &Name, attr_path: Option<&SmolStr>) -> ModDir {
24 let mut path = self.path.clone();
25 match attr_to_path(attr_path) {
26 None => path.push(&name.to_string()),
28 if self.root_non_dir_owner {
34 ModDir { path, root_non_dir_owner: false }
37 pub fn resolve_declaration(
39 db: &impl DefDatabase2,
42 attr_path: Option<&SmolStr>,
43 ) -> Result<(FileId, ModDir), RelativePathBuf> {
44 let file_id = file_id.original_file(db);
46 let mut candidate_files = Vec::new();
47 match attr_to_path(attr_path) {
50 if self.root_non_dir_owner { self.path.parent().unwrap() } else { &self.path };
51 candidate_files.push(base.join(attr_path))
54 candidate_files.push(self.path.join(&format!("{}.rs", name)));
55 candidate_files.push(self.path.join(&format!("{}/mod.rs", name)));
59 for candidate in candidate_files.iter() {
60 if let Some(file_id) = db.resolve_relative_path(file_id, candidate) {
61 let mut root_non_dir_owner = false;
62 let mut mod_path = RelativePathBuf::new();
63 if !(candidate.ends_with("mod.rs") || attr_path.is_some()) {
64 root_non_dir_owner = true;
65 mod_path.push(&name.to_string());
67 return Ok((file_id, ModDir { path: mod_path, root_non_dir_owner }));
70 Err(candidate_files.remove(0))
74 fn attr_to_path(attr: Option<&SmolStr>) -> Option<RelativePathBuf> {
75 attr.and_then(|it| RelativePathBuf::from_path(&it.replace("\\", "/")).ok())