]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/nameres/mod_resolution.rs
:arrow_up: rust-analyzer
[rust.git] / src / tools / rust-analyzer / crates / hir-def / src / nameres / mod_resolution.rs
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;
5 use limit::Limit;
6 use syntax::SmolStr;
7
8 use crate::{db::DefDatabase, HirFileId};
9
10 const MOD_DEPTH_LIMIT: Limit = Limit::new(32);
11
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('/')
18     dir_path: DirPath,
19     /// inside `./foo.rs`, mods with `#[path]` should *not* be relative to `./foo/`
20     root_non_dir_owner: bool,
21     depth: u32,
22 }
23
24 impl ModDir {
25     pub(super) fn root() -> ModDir {
26         ModDir { dir_path: DirPath::empty(), root_non_dir_owner: false, depth: 0 }
27     }
28
29     pub(super) fn descend_into_definition(
30         &self,
31         name: &Name,
32         attr_path: Option<&SmolStr>,
33     ) -> Option<ModDir> {
34         let path = match attr_path.map(SmolStr::as_str) {
35             None => {
36                 let mut path = self.dir_path.clone();
37                 path.push(&name.to_smol_str());
38                 path
39             }
40             Some(attr_path) => {
41                 let mut path = self.dir_path.join_attr(attr_path, self.root_non_dir_owner);
42                 if !(path.is_empty() || path.ends_with('/')) {
43                     path.push('/')
44                 }
45                 DirPath::new(path)
46             }
47         };
48         self.child(path, false)
49     }
50
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);
56             return None;
57         }
58         Some(ModDir { dir_path, root_non_dir_owner, depth })
59     }
60
61     pub(super) fn resolve_declaration(
62         &self,
63         db: &dyn DefDatabase,
64         file_id: HirFileId,
65         name: &Name,
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());
70
71         let mut candidate_files = ArrayVec::<_, 2>::new();
72         match attr_path {
73             Some(attr_path) => {
74                 candidate_files.push(self.dir_path.join_attr(attr_path, self.root_non_dir_owner))
75             }
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));
79             }
80             None => {
81                 candidate_files.push(format!("{}{}.rs", self.dir_path.0, name));
82                 candidate_files.push(format!("{}{}/mod.rs", self.dir_path.0, name));
83             }
84         };
85
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");
90
91                 let (dir_path, root_non_dir_owner) = if is_mod_rs || attr_path.is_some() {
92                     (DirPath::empty(), false)
93                 } else {
94                     (DirPath::new(format!("{}/", name)), true)
95                 };
96                 if let Some(mod_dir) = self.child(dir_path, root_non_dir_owner) {
97                     return Ok((file_id, is_mod_rs, mod_dir));
98                 }
99             }
100         }
101         Err(candidate_files.into_iter().collect())
102     }
103 }
104
105 #[derive(Clone, Debug)]
106 struct DirPath(String);
107
108 impl DirPath {
109     fn assert_invariant(&self) {
110         assert!(self.0.is_empty() || self.0.ends_with('/'));
111     }
112     fn new(repr: String) -> DirPath {
113         let res = DirPath(repr);
114         res.assert_invariant();
115         res
116     }
117     fn empty() -> DirPath {
118         DirPath::new(String::new())
119     }
120     fn push(&mut self, name: &str) {
121         self.0.push_str(name);
122         self.0.push('/');
123         self.assert_invariant();
124     }
125     fn parent(&self) -> Option<&str> {
126         if self.0.is_empty() {
127             return None;
128         };
129         let idx =
130             self.0[..self.0.len() - '/'.len_utf8()].rfind('/').map_or(0, |it| it + '/'.len_utf8());
131         Some(&self.0[..idx])
132     }
133     /// So this is the case which doesn't really work I think if we try to be
134     /// 100% platform agnostic:
135     ///
136     /// ```
137     /// mod a {
138     ///     #[path="C://sad/face"]
139     ///     mod b { mod c; }
140     /// }
141     /// ```
142     ///
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 };
148
149         if attr.starts_with("./") {
150             attr = &attr["./".len()..];
151         }
152         let tmp;
153         let attr = if attr.contains('\\') {
154             tmp = attr.replace('\\', "/");
155             &tmp
156         } else {
157             attr
158         };
159         let res = format!("{}{}", base, attr);
160         res
161     }
162 }