1 //! This module resolves `mod foo;` declaration to file.
2 use arrayvec::ArrayVec;
3 use base_db::{AnchoredPath, FileId};
4 use hir_expand::name::Name;
8 use crate::{db::DefDatabase, HirFileId};
10 const MOD_DEPTH_LIMIT: Limit = Limit::new(32);
12 #[derive(Clone, Debug)]
13 pub(super) struct ModDir {
14 /// `` for `mod.rs`, `lib.rs`
15 /// `foo/` for `foo.rs`
16 /// `foo/bar/` for `mod bar { mod x; }` nested in `foo.rs`
17 /// Invariant: path.is_empty() || path.ends_with('/')
19 /// inside `./foo.rs`, mods with `#[path]` should *not* be relative to `./foo/`
20 root_non_dir_owner: bool,
25 pub(super) fn root() -> ModDir {
26 ModDir { dir_path: DirPath::empty(), root_non_dir_owner: false, depth: 0 }
29 pub(super) fn descend_into_definition(
32 attr_path: Option<&SmolStr>,
34 let path = match attr_path.map(SmolStr::as_str) {
36 let mut path = self.dir_path.clone();
37 path.push(&name.to_smol_str());
41 let mut path = self.dir_path.join_attr(attr_path, self.root_non_dir_owner);
42 if !(path.is_empty() || path.ends_with('/')) {
48 self.child(path, false)
51 fn child(&self, dir_path: DirPath, root_non_dir_owner: bool) -> Option<ModDir> {
52 let depth = self.depth + 1;
53 if MOD_DEPTH_LIMIT.check(depth as usize).is_err() {
54 tracing::error!("MOD_DEPTH_LIMIT exceeded");
55 cov_mark::hit!(circular_mods);
58 Some(ModDir { dir_path, root_non_dir_owner, depth })
61 pub(super) fn resolve_declaration(
66 attr_path: Option<&SmolStr>,
67 ) -> Result<(FileId, bool, ModDir), Box<[String]>> {
68 let name = name.unescaped();
69 let orig_file_id = file_id.original_file(db.upcast());
71 let mut candidate_files = ArrayVec::<_, 2>::new();
74 candidate_files.push(self.dir_path.join_attr(attr_path, self.root_non_dir_owner))
76 None if file_id.is_include_macro(db.upcast()) => {
77 candidate_files.push(format!("{}.rs", name));
78 candidate_files.push(format!("{}/mod.rs", name));
81 candidate_files.push(format!("{}{}.rs", self.dir_path.0, name));
82 candidate_files.push(format!("{}{}/mod.rs", self.dir_path.0, name));
86 for candidate in candidate_files.iter() {
87 let path = AnchoredPath { anchor: orig_file_id, path: candidate.as_str() };
88 if let Some(file_id) = db.resolve_path(path) {
89 let is_mod_rs = candidate.ends_with("/mod.rs");
91 let (dir_path, root_non_dir_owner) = if is_mod_rs || attr_path.is_some() {
92 (DirPath::empty(), false)
94 (DirPath::new(format!("{}/", name)), true)
96 if let Some(mod_dir) = self.child(dir_path, root_non_dir_owner) {
97 return Ok((file_id, is_mod_rs, mod_dir));
101 Err(candidate_files.into_iter().collect())
105 #[derive(Clone, Debug)]
106 struct DirPath(String);
109 fn assert_invariant(&self) {
110 assert!(self.0.is_empty() || self.0.ends_with('/'));
112 fn new(repr: String) -> DirPath {
113 let res = DirPath(repr);
114 res.assert_invariant();
117 fn empty() -> DirPath {
118 DirPath::new(String::new())
120 fn push(&mut self, name: &str) {
121 self.0.push_str(name);
123 self.assert_invariant();
125 fn parent(&self) -> Option<&str> {
126 if self.0.is_empty() {
130 self.0[..self.0.len() - '/'.len_utf8()].rfind('/').map_or(0, |it| it + '/'.len_utf8());
133 /// So this is the case which doesn't really work I think if we try to be
134 /// 100% platform agnostic:
138 /// #[path="C://sad/face"]
143 /// Here, we need to join logical dir path to a string path from an
144 /// attribute. Ideally, we should somehow losslessly communicate the whole
145 /// construction to `FileLoader`.
146 fn join_attr(&self, mut attr: &str, relative_to_parent: bool) -> String {
147 let base = if relative_to_parent { self.parent().unwrap() } else { &self.0 };
149 if attr.starts_with("./") {
150 attr = &attr["./".len()..];
153 let attr = if attr.contains('\\') {
154 tmp = attr.replace('\\', "/");
159 let res = format!("{}{}", base, attr);