aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_def/src/nameres
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_def/src/nameres')
-rw-r--r--crates/ra_hir_def/src/nameres/collector.rs79
-rw-r--r--crates/ra_hir_def/src/nameres/mod_resolution.rs4
-rw-r--r--crates/ra_hir_def/src/nameres/path_resolution.rs17
-rw-r--r--crates/ra_hir_def/src/nameres/per_ns.rs74
-rw-r--r--crates/ra_hir_def/src/nameres/raw.rs54
-rw-r--r--crates/ra_hir_def/src/nameres/tests.rs4
-rw-r--r--crates/ra_hir_def/src/nameres/tests/mod_resolution.rs2
7 files changed, 70 insertions, 164 deletions
diff --git a/crates/ra_hir_def/src/nameres/collector.rs b/crates/ra_hir_def/src/nameres/collector.rs
index aae3dcadf..b02364e86 100644
--- a/crates/ra_hir_def/src/nameres/collector.rs
+++ b/crates/ra_hir_def/src/nameres/collector.rs
@@ -12,19 +12,20 @@ use rustc_hash::FxHashMap;
12use test_utils::tested_by; 12use test_utils::tested_by;
13 13
14use crate::{ 14use crate::{
15 attr::Attr, 15 attr::Attrs,
16 db::DefDatabase2, 16 db::DefDatabase,
17 nameres::{ 17 nameres::{
18 diagnostics::DefDiagnostic, mod_resolution::ModDir, path_resolution::ReachedFixedPoint, 18 diagnostics::DefDiagnostic, mod_resolution::ModDir, path_resolution::ReachedFixedPoint,
19 per_ns::PerNs, raw, CrateDefMap, ModuleData, Resolution, ResolveMode, 19 raw, CrateDefMap, ModuleData, Resolution, ResolveMode,
20 }, 20 },
21 path::{Path, PathKind}, 21 path::{Path, PathKind},
22 AdtId, AstId, AstItemDef, ConstLoc, ContainerId, CrateModuleId, EnumId, EnumVariantId, 22 per_ns::PerNs,
23 FunctionLoc, ImplId, Intern, LocationCtx, ModuleDefId, ModuleId, StaticId, StructId, 23 AdtId, AstId, AstItemDef, ConstLoc, ContainerId, EnumId, EnumVariantId, FunctionLoc, ImplId,
24 Intern, LocalImportId, LocalModuleId, LocationCtx, ModuleDefId, ModuleId, StaticId, StructId,
24 StructOrUnionId, TraitId, TypeAliasLoc, UnionId, 25 StructOrUnionId, TraitId, TypeAliasLoc, UnionId,
25}; 26};
26 27
27pub(super) fn collect_defs(db: &impl DefDatabase2, mut def_map: CrateDefMap) -> CrateDefMap { 28pub(super) fn collect_defs(db: &impl DefDatabase, mut def_map: CrateDefMap) -> CrateDefMap {
28 let crate_graph = db.crate_graph(); 29 let crate_graph = db.crate_graph();
29 30
30 // populate external prelude 31 // populate external prelude
@@ -94,10 +95,10 @@ impl MacroStackMonitor {
94struct DefCollector<'a, DB> { 95struct DefCollector<'a, DB> {
95 db: &'a DB, 96 db: &'a DB,
96 def_map: CrateDefMap, 97 def_map: CrateDefMap,
97 glob_imports: FxHashMap<CrateModuleId, Vec<(CrateModuleId, raw::ImportId)>>, 98 glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, LocalImportId)>>,
98 unresolved_imports: Vec<(CrateModuleId, raw::ImportId, raw::ImportData)>, 99 unresolved_imports: Vec<(LocalModuleId, LocalImportId, raw::ImportData)>,
99 unexpanded_macros: Vec<(CrateModuleId, AstId<ast::MacroCall>, Path)>, 100 unexpanded_macros: Vec<(LocalModuleId, AstId<ast::MacroCall>, Path)>,
100 mod_dirs: FxHashMap<CrateModuleId, ModDir>, 101 mod_dirs: FxHashMap<LocalModuleId, ModDir>,
101 102
102 /// Some macro use `$tt:tt which mean we have to handle the macro perfectly 103 /// Some macro use `$tt:tt which mean we have to handle the macro perfectly
103 /// To prevent stack overflow, we add a deep counter here for prevent that. 104 /// To prevent stack overflow, we add a deep counter here for prevent that.
@@ -108,7 +109,7 @@ struct DefCollector<'a, DB> {
108 109
109impl<DB> DefCollector<'_, DB> 110impl<DB> DefCollector<'_, DB>
110where 111where
111 DB: DefDatabase2, 112 DB: DefDatabase,
112{ 113{
113 fn collect(&mut self) { 114 fn collect(&mut self) {
114 let crate_graph = self.db.crate_graph(); 115 let crate_graph = self.db.crate_graph();
@@ -173,7 +174,7 @@ where
173 /// ``` 174 /// ```
174 fn define_macro( 175 fn define_macro(
175 &mut self, 176 &mut self,
176 module_id: CrateModuleId, 177 module_id: LocalModuleId,
177 name: Name, 178 name: Name,
178 macro_: MacroDefId, 179 macro_: MacroDefId,
179 export: bool, 180 export: bool,
@@ -200,7 +201,7 @@ where
200 /// the definition of current module. 201 /// the definition of current module.
201 /// And also, `macro_use` on a module will import all legacy macros visable inside to 202 /// And also, `macro_use` on a module will import all legacy macros visable inside to
202 /// current legacy scope, with possible shadowing. 203 /// current legacy scope, with possible shadowing.
203 fn define_legacy_macro(&mut self, module_id: CrateModuleId, name: Name, macro_: MacroDefId) { 204 fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, macro_: MacroDefId) {
204 // Always shadowing 205 // Always shadowing
205 self.def_map.modules[module_id].scope.legacy_macros.insert(name, macro_); 206 self.def_map.modules[module_id].scope.legacy_macros.insert(name, macro_);
206 } 207 }
@@ -208,7 +209,7 @@ where
208 /// Import macros from `#[macro_use] extern crate`. 209 /// Import macros from `#[macro_use] extern crate`.
209 fn import_macros_from_extern_crate( 210 fn import_macros_from_extern_crate(
210 &mut self, 211 &mut self,
211 current_module_id: CrateModuleId, 212 current_module_id: LocalModuleId,
212 import: &raw::ImportData, 213 import: &raw::ImportData,
213 ) { 214 ) {
214 log::debug!( 215 log::debug!(
@@ -235,7 +236,7 @@ where
235 /// Exported macros are just all macros in the root module scope. 236 /// Exported macros are just all macros in the root module scope.
236 /// Note that it contains not only all `#[macro_export]` macros, but also all aliases 237 /// Note that it contains not only all `#[macro_export]` macros, but also all aliases
237 /// created by `use` in the root module, ignoring the visibility of `use`. 238 /// created by `use` in the root module, ignoring the visibility of `use`.
238 fn import_all_macros_exported(&mut self, current_module_id: CrateModuleId, krate: CrateId) { 239 fn import_all_macros_exported(&mut self, current_module_id: LocalModuleId, krate: CrateId) {
239 let def_map = self.db.crate_def_map(krate); 240 let def_map = self.db.crate_def_map(krate);
240 for (name, def) in def_map[def_map.root].scope.macros() { 241 for (name, def) in def_map[def_map.root].scope.macros() {
241 // `macro_use` only bring things into legacy scope. 242 // `macro_use` only bring things into legacy scope.
@@ -265,7 +266,7 @@ where
265 266
266 fn resolve_import( 267 fn resolve_import(
267 &self, 268 &self,
268 module_id: CrateModuleId, 269 module_id: LocalModuleId,
269 import: &raw::ImportData, 270 import: &raw::ImportData,
270 ) -> (PerNs, ReachedFixedPoint) { 271 ) -> (PerNs, ReachedFixedPoint) {
271 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition); 272 log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
@@ -291,9 +292,9 @@ where
291 292
292 fn record_resolved_import( 293 fn record_resolved_import(
293 &mut self, 294 &mut self,
294 module_id: CrateModuleId, 295 module_id: LocalModuleId,
295 def: PerNs, 296 def: PerNs,
296 import_id: raw::ImportId, 297 import_id: LocalImportId,
297 import: &raw::ImportData, 298 import: &raw::ImportData,
298 ) { 299 ) {
299 if import.is_glob { 300 if import.is_glob {
@@ -387,8 +388,8 @@ where
387 388
388 fn update( 389 fn update(
389 &mut self, 390 &mut self,
390 module_id: CrateModuleId, 391 module_id: LocalModuleId,
391 import: Option<raw::ImportId>, 392 import: Option<LocalImportId>,
392 resolutions: &[(Name, Resolution)], 393 resolutions: &[(Name, Resolution)],
393 ) { 394 ) {
394 self.update_recursive(module_id, import, resolutions, 0) 395 self.update_recursive(module_id, import, resolutions, 0)
@@ -396,8 +397,8 @@ where
396 397
397 fn update_recursive( 398 fn update_recursive(
398 &mut self, 399 &mut self,
399 module_id: CrateModuleId, 400 module_id: LocalModuleId,
400 import: Option<raw::ImportId>, 401 import: Option<LocalImportId>,
401 resolutions: &[(Name, Resolution)], 402 resolutions: &[(Name, Resolution)],
402 depth: usize, 403 depth: usize,
403 ) { 404 ) {
@@ -484,7 +485,7 @@ where
484 485
485 fn collect_macro_expansion( 486 fn collect_macro_expansion(
486 &mut self, 487 &mut self,
487 module_id: CrateModuleId, 488 module_id: LocalModuleId,
488 macro_call_id: MacroCallId, 489 macro_call_id: MacroCallId,
489 macro_def_id: MacroDefId, 490 macro_def_id: MacroDefId,
490 ) { 491 ) {
@@ -522,7 +523,7 @@ where
522/// Walks a single module, populating defs, imports and macros 523/// Walks a single module, populating defs, imports and macros
523struct ModCollector<'a, D> { 524struct ModCollector<'a, D> {
524 def_collector: D, 525 def_collector: D,
525 module_id: CrateModuleId, 526 module_id: LocalModuleId,
526 file_id: HirFileId, 527 file_id: HirFileId,
527 raw_items: &'a raw::RawItems, 528 raw_items: &'a raw::RawItems,
528 mod_dir: ModDir, 529 mod_dir: ModDir,
@@ -530,7 +531,7 @@ struct ModCollector<'a, D> {
530 531
531impl<DB> ModCollector<'_, &'_ mut DefCollector<'_, DB>> 532impl<DB> ModCollector<'_, &'_ mut DefCollector<'_, DB>>
532where 533where
533 DB: DefDatabase2, 534 DB: DefDatabase,
534{ 535{
535 fn collect(&mut self, items: &[raw::RawItem]) { 536 fn collect(&mut self, items: &[raw::RawItem]) {
536 // Note: don't assert that inserted value is fresh: it's simply not true 537 // Note: don't assert that inserted value is fresh: it's simply not true
@@ -549,7 +550,7 @@ where
549 // `#[macro_use] extern crate` is hoisted to imports macros before collecting 550 // `#[macro_use] extern crate` is hoisted to imports macros before collecting
550 // any other items. 551 // any other items.
551 for item in items { 552 for item in items {
552 if self.is_cfg_enabled(item.attrs()) { 553 if self.is_cfg_enabled(&item.attrs) {
553 if let raw::RawItemKind::Import(import_id) = item.kind { 554 if let raw::RawItemKind::Import(import_id) = item.kind {
554 let import = self.raw_items[import_id].clone(); 555 let import = self.raw_items[import_id].clone();
555 if import.is_extern_crate && import.is_macro_use { 556 if import.is_extern_crate && import.is_macro_use {
@@ -560,10 +561,10 @@ where
560 } 561 }
561 562
562 for item in items { 563 for item in items {
563 if self.is_cfg_enabled(item.attrs()) { 564 if self.is_cfg_enabled(&item.attrs) {
564 match item.kind { 565 match item.kind {
565 raw::RawItemKind::Module(m) => { 566 raw::RawItemKind::Module(m) => {
566 self.collect_module(&self.raw_items[m], item.attrs()) 567 self.collect_module(&self.raw_items[m], &item.attrs)
567 } 568 }
568 raw::RawItemKind::Import(import_id) => self 569 raw::RawItemKind::Import(import_id) => self
569 .def_collector 570 .def_collector
@@ -585,9 +586,9 @@ where
585 } 586 }
586 } 587 }
587 588
588 fn collect_module(&mut self, module: &raw::ModuleData, attrs: &[Attr]) { 589 fn collect_module(&mut self, module: &raw::ModuleData, attrs: &Attrs) {
589 let path_attr = self.path_attr(attrs); 590 let path_attr = self.path_attr(attrs);
590 let is_macro_use = self.is_macro_use(attrs); 591 let is_macro_use = attrs.has_atom("macro_use");
591 match module { 592 match module {
592 // inline module, just recurse 593 // inline module, just recurse
593 raw::ModuleData::Definition { name, items, ast_id } => { 594 raw::ModuleData::Definition { name, items, ast_id } => {
@@ -647,7 +648,7 @@ where
647 name: Name, 648 name: Name,
648 declaration: AstId<ast::Module>, 649 declaration: AstId<ast::Module>,
649 definition: Option<FileId>, 650 definition: Option<FileId>,
650 ) -> CrateModuleId { 651 ) -> LocalModuleId {
651 let modules = &mut self.def_collector.def_map.modules; 652 let modules = &mut self.def_collector.def_map.modules;
652 let res = modules.alloc(ModuleData::default()); 653 let res = modules.alloc(ModuleData::default());
653 modules[res].parent = Some(self.module_id); 654 modules[res].parent = Some(self.module_id);
@@ -772,24 +773,20 @@ where
772 self.def_collector.unexpanded_macros.push((self.module_id, ast_id, path)); 773 self.def_collector.unexpanded_macros.push((self.module_id, ast_id, path));
773 } 774 }
774 775
775 fn import_all_legacy_macros(&mut self, module_id: CrateModuleId) { 776 fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
776 let macros = self.def_collector.def_map[module_id].scope.legacy_macros.clone(); 777 let macros = self.def_collector.def_map[module_id].scope.legacy_macros.clone();
777 for (name, macro_) in macros { 778 for (name, macro_) in macros {
778 self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_); 779 self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_);
779 } 780 }
780 } 781 }
781 782
782 fn is_cfg_enabled(&self, attrs: &[Attr]) -> bool { 783 fn is_cfg_enabled(&self, attrs: &Attrs) -> bool {
783 attrs.iter().all(|attr| attr.is_cfg_enabled(&self.def_collector.cfg_options) != Some(false)) 784 attrs.iter().all(|attr| attr.is_cfg_enabled(&self.def_collector.cfg_options) != Some(false))
784 } 785 }
785 786
786 fn path_attr<'a>(&self, attrs: &'a [Attr]) -> Option<&'a SmolStr> { 787 fn path_attr<'a>(&self, attrs: &'a Attrs) -> Option<&'a SmolStr> {
787 attrs.iter().find_map(|attr| attr.as_path()) 788 attrs.iter().find_map(|attr| attr.as_path())
788 } 789 }
789
790 fn is_macro_use<'a>(&self, attrs: &'a [Attr]) -> bool {
791 attrs.iter().any(|attr| attr.is_simple_atom("macro_use"))
792 }
793} 790}
794 791
795fn is_macro_rules(path: &Path) -> bool { 792fn is_macro_rules(path: &Path) -> bool {
@@ -802,12 +799,12 @@ mod tests {
802 use ra_db::{fixture::WithFixture, SourceDatabase}; 799 use ra_db::{fixture::WithFixture, SourceDatabase};
803 use rustc_hash::FxHashSet; 800 use rustc_hash::FxHashSet;
804 801
805 use crate::{db::DefDatabase2, test_db::TestDB}; 802 use crate::{db::DefDatabase, test_db::TestDB};
806 803
807 use super::*; 804 use super::*;
808 805
809 fn do_collect_defs( 806 fn do_collect_defs(
810 db: &impl DefDatabase2, 807 db: &impl DefDatabase,
811 def_map: CrateDefMap, 808 def_map: CrateDefMap,
812 monitor: MacroStackMonitor, 809 monitor: MacroStackMonitor,
813 ) -> CrateDefMap { 810 ) -> CrateDefMap {
@@ -831,7 +828,7 @@ mod tests {
831 828
832 let def_map = { 829 let def_map = {
833 let edition = db.crate_graph().edition(krate); 830 let edition = db.crate_graph().edition(krate);
834 let mut modules: Arena<CrateModuleId, ModuleData> = Arena::default(); 831 let mut modules: Arena<LocalModuleId, ModuleData> = Arena::default();
835 let root = modules.alloc(ModuleData::default()); 832 let root = modules.alloc(ModuleData::default());
836 CrateDefMap { 833 CrateDefMap {
837 krate, 834 krate,
diff --git a/crates/ra_hir_def/src/nameres/mod_resolution.rs b/crates/ra_hir_def/src/nameres/mod_resolution.rs
index b3b1379d0..14fb8ba3a 100644
--- a/crates/ra_hir_def/src/nameres/mod_resolution.rs
+++ b/crates/ra_hir_def/src/nameres/mod_resolution.rs
@@ -3,7 +3,7 @@ use hir_expand::name::Name;
3use ra_db::{FileId, RelativePathBuf}; 3use ra_db::{FileId, RelativePathBuf};
4use ra_syntax::SmolStr; 4use ra_syntax::SmolStr;
5 5
6use crate::{db::DefDatabase2, HirFileId}; 6use crate::{db::DefDatabase, HirFileId};
7 7
8#[derive(Clone, Debug)] 8#[derive(Clone, Debug)]
9pub(super) struct ModDir { 9pub(super) struct ModDir {
@@ -40,7 +40,7 @@ impl ModDir {
40 40
41 pub(super) fn resolve_declaration( 41 pub(super) fn resolve_declaration(
42 &self, 42 &self,
43 db: &impl DefDatabase2, 43 db: &impl DefDatabase,
44 file_id: HirFileId, 44 file_id: HirFileId,
45 name: &Name, 45 name: &Name,
46 attr_path: Option<&SmolStr>, 46 attr_path: Option<&SmolStr>,
diff --git a/crates/ra_hir_def/src/nameres/path_resolution.rs b/crates/ra_hir_def/src/nameres/path_resolution.rs
index 95692f826..9455f22bb 100644
--- a/crates/ra_hir_def/src/nameres/path_resolution.rs
+++ b/crates/ra_hir_def/src/nameres/path_resolution.rs
@@ -15,10 +15,11 @@ use ra_db::Edition;
15use test_utils::tested_by; 15use test_utils::tested_by;
16 16
17use crate::{ 17use crate::{
18 db::DefDatabase2, 18 db::DefDatabase,
19 nameres::{per_ns::PerNs, CrateDefMap}, 19 nameres::CrateDefMap,
20 path::{Path, PathKind}, 20 path::{Path, PathKind},
21 AdtId, CrateModuleId, EnumVariantId, ModuleDefId, ModuleId, 21 per_ns::PerNs,
22 AdtId, EnumVariantId, LocalModuleId, ModuleDefId, ModuleId,
22}; 23};
23 24
24#[derive(Debug, Clone, Copy, PartialEq, Eq)] 25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -63,9 +64,9 @@ impl CrateDefMap {
63 // the result. 64 // the result.
64 pub(super) fn resolve_path_fp_with_macro( 65 pub(super) fn resolve_path_fp_with_macro(
65 &self, 66 &self,
66 db: &impl DefDatabase2, 67 db: &impl DefDatabase,
67 mode: ResolveMode, 68 mode: ResolveMode,
68 original_module: CrateModuleId, 69 original_module: LocalModuleId,
69 path: &Path, 70 path: &Path,
70 ) -> ResolvePathResult { 71 ) -> ResolvePathResult {
71 let mut segments = path.segments.iter().enumerate(); 72 let mut segments = path.segments.iter().enumerate();
@@ -216,8 +217,8 @@ impl CrateDefMap {
216 217
217 fn resolve_name_in_module( 218 fn resolve_name_in_module(
218 &self, 219 &self,
219 db: &impl DefDatabase2, 220 db: &impl DefDatabase,
220 module: CrateModuleId, 221 module: LocalModuleId,
221 name: &Name, 222 name: &Name,
222 ) -> PerNs { 223 ) -> PerNs {
223 // Resolve in: 224 // Resolve in:
@@ -243,7 +244,7 @@ impl CrateDefMap {
243 from_crate_root.or(from_extern_prelude) 244 from_crate_root.or(from_extern_prelude)
244 } 245 }
245 246
246 fn resolve_in_prelude(&self, db: &impl DefDatabase2, name: &Name) -> PerNs { 247 fn resolve_in_prelude(&self, db: &impl DefDatabase, name: &Name) -> PerNs {
247 if let Some(prelude) = self.prelude { 248 if let Some(prelude) = self.prelude {
248 let keep; 249 let keep;
249 let def_map = if prelude.krate == self.krate { 250 let def_map = if prelude.krate == self.krate {
diff --git a/crates/ra_hir_def/src/nameres/per_ns.rs b/crates/ra_hir_def/src/nameres/per_ns.rs
deleted file mode 100644
index 717ed1ef9..000000000
--- a/crates/ra_hir_def/src/nameres/per_ns.rs
+++ /dev/null
@@ -1,74 +0,0 @@
1//! FIXME: write short doc here
2
3use hir_expand::MacroDefId;
4
5use crate::ModuleDefId;
6
7#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
8pub struct PerNs {
9 pub types: Option<ModuleDefId>,
10 pub values: Option<ModuleDefId>,
11 /// Since macros has different type, many methods simply ignore it.
12 /// We can only use special method like `get_macros` to access it.
13 pub macros: Option<MacroDefId>,
14}
15
16impl Default for PerNs {
17 fn default() -> Self {
18 PerNs { types: None, values: None, macros: None }
19 }
20}
21
22impl PerNs {
23 pub fn none() -> PerNs {
24 PerNs { types: None, values: None, macros: None }
25 }
26
27 pub fn values(t: ModuleDefId) -> PerNs {
28 PerNs { types: None, values: Some(t), macros: None }
29 }
30
31 pub fn types(t: ModuleDefId) -> PerNs {
32 PerNs { types: Some(t), values: None, macros: None }
33 }
34
35 pub fn both(types: ModuleDefId, values: ModuleDefId) -> PerNs {
36 PerNs { types: Some(types), values: Some(values), macros: None }
37 }
38
39 pub fn macros(macro_: MacroDefId) -> PerNs {
40 PerNs { types: None, values: None, macros: Some(macro_) }
41 }
42
43 pub fn is_none(&self) -> bool {
44 self.types.is_none() && self.values.is_none() && self.macros.is_none()
45 }
46
47 pub fn is_all(&self) -> bool {
48 self.types.is_some() && self.values.is_some() && self.macros.is_some()
49 }
50
51 pub fn take_types(self) -> Option<ModuleDefId> {
52 self.types
53 }
54
55 pub fn take_values(self) -> Option<ModuleDefId> {
56 self.values
57 }
58
59 pub fn get_macros(&self) -> Option<MacroDefId> {
60 self.macros
61 }
62
63 pub fn only_macros(&self) -> PerNs {
64 PerNs { types: None, values: None, macros: self.macros }
65 }
66
67 pub fn or(self, other: PerNs) -> PerNs {
68 PerNs {
69 types: self.types.or(other.types),
70 values: self.values.or(other.values),
71 macros: self.macros.or(other.macros),
72 }
73 }
74}
diff --git a/crates/ra_hir_def/src/nameres/raw.rs b/crates/ra_hir_def/src/nameres/raw.rs
index 7c68fd638..552cbe544 100644
--- a/crates/ra_hir_def/src/nameres/raw.rs
+++ b/crates/ra_hir_def/src/nameres/raw.rs
@@ -12,11 +12,16 @@ use hir_expand::{
12use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; 12use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
13use ra_syntax::{ 13use ra_syntax::{
14 ast::{self, AttrsOwner, NameOwner}, 14 ast::{self, AttrsOwner, NameOwner},
15 AstNode, AstPtr, SourceFile, 15 AstNode, AstPtr,
16}; 16};
17use test_utils::tested_by; 17use test_utils::tested_by;
18 18
19use crate::{attr::Attr, db::DefDatabase2, path::Path, FileAstId, HirFileId, ModuleSource, Source}; 19use crate::{
20 attr::{Attr, Attrs},
21 db::DefDatabase,
22 path::Path,
23 FileAstId, HirFileId, LocalImportId, Source,
24};
20 25
21/// `RawItems` is a set of top-level items in a file (except for impls). 26/// `RawItems` is a set of top-level items in a file (except for impls).
22/// 27///
@@ -25,7 +30,7 @@ use crate::{attr::Attr, db::DefDatabase2, path::Path, FileAstId, HirFileId, Modu
25#[derive(Debug, Default, PartialEq, Eq)] 30#[derive(Debug, Default, PartialEq, Eq)]
26pub struct RawItems { 31pub struct RawItems {
27 modules: Arena<Module, ModuleData>, 32 modules: Arena<Module, ModuleData>,
28 imports: Arena<ImportId, ImportData>, 33 imports: Arena<LocalImportId, ImportData>,
29 defs: Arena<Def, DefData>, 34 defs: Arena<Def, DefData>,
30 macros: Arena<Macro, MacroData>, 35 macros: Arena<Macro, MacroData>,
31 impls: Arena<Impl, ImplData>, 36 impls: Arena<Impl, ImplData>,
@@ -35,41 +40,31 @@ pub struct RawItems {
35 40
36#[derive(Debug, Default, PartialEq, Eq)] 41#[derive(Debug, Default, PartialEq, Eq)]
37pub struct ImportSourceMap { 42pub struct ImportSourceMap {
38 map: ArenaMap<ImportId, ImportSourcePtr>, 43 map: ArenaMap<LocalImportId, ImportSourcePtr>,
39} 44}
40 45
41type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>; 46type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>;
42type ImportSource = Either<ast::UseTree, ast::ExternCrateItem>;
43
44fn to_node(ptr: ImportSourcePtr, file: &SourceFile) -> ImportSource {
45 ptr.map(|ptr| ptr.to_node(file.syntax()), |ptr| ptr.to_node(file.syntax()))
46}
47 47
48impl ImportSourceMap { 48impl ImportSourceMap {
49 fn insert(&mut self, import: ImportId, ptr: ImportSourcePtr) { 49 fn insert(&mut self, import: LocalImportId, ptr: ImportSourcePtr) {
50 self.map.insert(import, ptr) 50 self.map.insert(import, ptr)
51 } 51 }
52 52
53 pub fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource { 53 pub fn get(&self, import: LocalImportId) -> ImportSourcePtr {
54 let file = match source { 54 self.map[import].clone()
55 ModuleSource::SourceFile(file) => file.clone(),
56 ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(),
57 };
58
59 to_node(self.map[import], &file)
60 } 55 }
61} 56}
62 57
63impl RawItems { 58impl RawItems {
64 pub(crate) fn raw_items_query( 59 pub(crate) fn raw_items_query(
65 db: &(impl DefDatabase2 + AstDatabase), 60 db: &(impl DefDatabase + AstDatabase),
66 file_id: HirFileId, 61 file_id: HirFileId,
67 ) -> Arc<RawItems> { 62 ) -> Arc<RawItems> {
68 db.raw_items_with_source_map(file_id).0 63 db.raw_items_with_source_map(file_id).0
69 } 64 }
70 65
71 pub(crate) fn raw_items_with_source_map_query( 66 pub(crate) fn raw_items_with_source_map_query(
72 db: &(impl DefDatabase2 + AstDatabase), 67 db: &(impl DefDatabase + AstDatabase),
73 file_id: HirFileId, 68 file_id: HirFileId,
74 ) -> (Arc<RawItems>, Arc<ImportSourceMap>) { 69 ) -> (Arc<RawItems>, Arc<ImportSourceMap>) {
75 let mut collector = RawItemsCollector { 70 let mut collector = RawItemsCollector {
@@ -101,9 +96,9 @@ impl Index<Module> for RawItems {
101 } 96 }
102} 97}
103 98
104impl Index<ImportId> for RawItems { 99impl Index<LocalImportId> for RawItems {
105 type Output = ImportData; 100 type Output = ImportData;
106 fn index(&self, idx: ImportId) -> &ImportData { 101 fn index(&self, idx: LocalImportId) -> &ImportData {
107 &self.imports[idx] 102 &self.imports[idx]
108 } 103 }
109} 104}
@@ -129,25 +124,16 @@ impl Index<Impl> for RawItems {
129 } 124 }
130} 125}
131 126
132// Avoid heap allocation on items without attributes.
133type Attrs = Option<Arc<[Attr]>>;
134
135#[derive(Debug, PartialEq, Eq, Clone)] 127#[derive(Debug, PartialEq, Eq, Clone)]
136pub(super) struct RawItem { 128pub(super) struct RawItem {
137 attrs: Attrs, 129 pub(super) attrs: Attrs,
138 pub(super) kind: RawItemKind, 130 pub(super) kind: RawItemKind,
139} 131}
140 132
141impl RawItem {
142 pub(super) fn attrs(&self) -> &[Attr] {
143 self.attrs.as_ref().map_or(&[], |it| &*it)
144 }
145}
146
147#[derive(Debug, PartialEq, Eq, Clone, Copy)] 133#[derive(Debug, PartialEq, Eq, Clone, Copy)]
148pub(super) enum RawItemKind { 134pub(super) enum RawItemKind {
149 Module(Module), 135 Module(Module),
150 Import(ImportId), 136 Import(LocalImportId),
151 Def(Def), 137 Def(Def),
152 Macro(Macro), 138 Macro(Macro),
153 Impl(Impl), 139 Impl(Impl),
@@ -163,10 +149,6 @@ pub(super) enum ModuleData {
163 Definition { name: Name, ast_id: FileAstId<ast::Module>, items: Vec<RawItem> }, 149 Definition { name: Name, ast_id: FileAstId<ast::Module>, items: Vec<RawItem> },
164} 150}
165 151
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
167pub struct ImportId(RawId);
168impl_arena_id!(ImportId);
169
170#[derive(Debug, Clone, PartialEq, Eq)] 152#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct ImportData { 153pub struct ImportData {
172 pub(super) path: Path, 154 pub(super) path: Path,
diff --git a/crates/ra_hir_def/src/nameres/tests.rs b/crates/ra_hir_def/src/nameres/tests.rs
index 256f7d4be..f0b86af7c 100644
--- a/crates/ra_hir_def/src/nameres/tests.rs
+++ b/crates/ra_hir_def/src/nameres/tests.rs
@@ -10,7 +10,7 @@ use insta::assert_snapshot;
10use ra_db::{fixture::WithFixture, SourceDatabase}; 10use ra_db::{fixture::WithFixture, SourceDatabase};
11use test_utils::covers; 11use test_utils::covers;
12 12
13use crate::{db::DefDatabase2, nameres::*, test_db::TestDB, CrateModuleId}; 13use crate::{db::DefDatabase, nameres::*, test_db::TestDB, LocalModuleId};
14 14
15fn def_map(fixtute: &str) -> String { 15fn def_map(fixtute: &str) -> String {
16 let dm = compute_crate_def_map(fixtute); 16 let dm = compute_crate_def_map(fixtute);
@@ -28,7 +28,7 @@ fn render_crate_def_map(map: &CrateDefMap) -> String {
28 go(&mut buf, map, "\ncrate", map.root()); 28 go(&mut buf, map, "\ncrate", map.root());
29 return buf.trim().to_string(); 29 return buf.trim().to_string();
30 30
31 fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: CrateModuleId) { 31 fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: LocalModuleId) {
32 *buf += path; 32 *buf += path;
33 *buf += "\n"; 33 *buf += "\n";
34 34
diff --git a/crates/ra_hir_def/src/nameres/tests/mod_resolution.rs b/crates/ra_hir_def/src/nameres/tests/mod_resolution.rs
index eb7b85c07..e11530062 100644
--- a/crates/ra_hir_def/src/nameres/tests/mod_resolution.rs
+++ b/crates/ra_hir_def/src/nameres/tests/mod_resolution.rs
@@ -665,7 +665,7 @@ fn unresolved_module_diagnostics() {
665 @r###" 665 @r###"
666 [ 666 [
667 UnresolvedModule { 667 UnresolvedModule {
668 module: CrateModuleId( 668 module: LocalModuleId(
669 0, 669 0,
670 ), 670 ),
671 declaration: AstId { 671 declaration: AstId {