Repository: rust-analyzer/rust-analyzer
Pull request #2375 (2019-11-23 13:56:51)

Privatise nameres


Patch:
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index 50c9a79fc0..fd7776fb79 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -9,18 +9,19 @@ use hir_def::{
     body::scope::ExprScopes,
     builtin_type::BuiltinType,
     docs::Documentation,
-    nameres::{per_ns::PerNs, raw::ImportId},
+    per_ns::PerNs,
     resolver::{HasResolver, TypeNs},
     type_ref::TypeRef,
-    ContainerId, CrateModuleId, HasModule, ImplId, LocalEnumVariantId, LocalStructFieldId, Lookup,
-    ModuleId, UnionId,
+    ContainerId, HasModule, ImplId, LocalEnumVariantId, LocalImportId, LocalModuleId,
+    LocalStructFieldId, Lookup, ModuleId, UnionId,
 };
 use hir_expand::{
     diagnostics::DiagnosticSink,
     name::{self, AsName},
+    AstId,
 };
-use ra_db::{CrateId, Edition};
-use ra_syntax::ast;
+use ra_db::{CrateId, Edition, FileId, FilePosition};
+use ra_syntax::{ast, AstNode, SyntaxNode};
 
 use crate::{
     db::{DefDatabase, HirDatabase},
@@ -78,6 +79,64 @@ impl Crate {
     }
 }
 
+pub enum ModuleSource {
+    SourceFile(ast::SourceFile),
+    Module(ast::Module),
+}
+
+impl ModuleSource {
+    pub fn new(
+        db: &impl DefDatabase,
+        file_id: Option<FileId>,
+        decl_id: Option<AstId<ast::Module>>,
+    ) -> ModuleSource {
+        match (file_id, decl_id) {
+            (Some(file_id), _) => {
+                let source_file = db.parse(file_id).tree();
+                ModuleSource::SourceFile(source_file)
+            }
+            (None, Some(item_id)) => {
+                let module = item_id.to_node(db);
+                assert!(module.item_list().is_some(), "expected inline module");
+                ModuleSource::Module(module)
+            }
+            (None, None) => panic!(),
+        }
+    }
+
+    // FIXME: this methods do not belong here
+    pub fn from_position(db: &impl DefDatabase, position: FilePosition) -> ModuleSource {
+        let parse = db.parse(position.file_id);
+        match &ra_syntax::algo::find_node_at_offset::<ast::Module>(
+            parse.tree().syntax(),
+            position.offset,
+        ) {
+            Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()),
+            _ => {
+                let source_file = parse.tree();
+                ModuleSource::SourceFile(source_file)
+            }
+        }
+    }
+
+    pub fn from_child_node(db: &impl DefDatabase, child: Source<&SyntaxNode>) -> ModuleSource {
+        if let Some(m) =
+            child.value.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi())
+        {
+            ModuleSource::Module(m)
+        } else {
+            let file_id = child.file_id.original_file(db);
+            let source_file = db.parse(file_id).tree();
+            ModuleSource::SourceFile(source_file)
+        }
+    }
+
+    pub fn from_file_id(db: &impl DefDatabase, file_id: FileId) -> ModuleSource {
+        let source_file = db.parse(file_id).tree();
+        ModuleSource::SourceFile(source_file)
+    }
+}
+
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 pub struct Module {
     pub(crate) id: ModuleId,
@@ -109,10 +168,10 @@ impl_froms!(
     BuiltinType
 );
 
-pub use hir_def::{attr::Attrs, ModuleSource};
+pub use hir_def::attr::Attrs;
 
 impl Module {
-    pub(crate) fn new(krate: Crate, crate_module_id: CrateModuleId) -> Module {
+    pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module {
         Module { id: ModuleId { krate: krate.crate_id, module_id: crate_module_id } }
     }
 
@@ -222,14 +281,14 @@ impl Module {
         def_map[self.id.module_id].impls.iter().copied().map(ImplBlock::from).collect()
     }
 
-    fn with_module_id(self, module_id: CrateModuleId) -> Module {
+    fn with_module_id(self, module_id: LocalModuleId) -> Module {
         Module::new(self.krate(), module_id)
     }
 }
 
 pub struct Import {
     pub(crate) parent: Module,
-    pub(crate) id: ImportId,
+    pub(crate) id: LocalImportId,
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
diff --git a/crates/ra_hir/src/code_model/src.rs b/crates/ra_hir/src/code_model/src.rs
index 402f821bf9..b7bafe23df 100644
--- a/crates/ra_hir/src/code_model/src.rs
+++ b/crates/ra_hir/src/code_model/src.rs
@@ -117,7 +117,9 @@ impl HasSource for Import {
     fn source(self, db: &impl DefDatabase) -> Source<Self::Ast> {
         let src = self.parent.definition_source(db);
         let (_, source_map) = db.raw_items_with_source_map(src.file_id);
-        src.with_value(source_map.get(&src.value, self.id))
+        let root = db.parse_or_expand(src.file_id).unwrap();
+        let ptr = source_map.get(self.id);
+        src.with_value(ptr.map(|it| it.to_node(&root), |it| it.to_node(&root)))
     }
 }
 
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs
index 1b2bc6f45e..1d195d65d0 100644
--- a/crates/ra_hir_def/src/lib.rs
+++ b/crates/ra_hir_def/src/lib.rs
@@ -21,95 +21,40 @@ pub mod resolver;
 pub mod data;
 pub mod lang_item;
 pub mod docs;
+pub mod per_ns;
 
 mod trace;
+mod nameres;
 
 #[cfg(test)]
 mod test_db;
 #[cfg(test)]
 mod marks;
 
-// FIXME: this should be private
-pub mod nameres;
-
 use std::hash::{Hash, Hasher};
 
 use hir_expand::{ast_id_map::FileAstId, db::AstDatabase, AstId, HirFileId, MacroDefId, Source};
 use ra_arena::{impl_arena_id, map::ArenaMap, RawId};
-use ra_db::{salsa, CrateId, FileId};
-use ra_syntax::{ast, AstNode, SyntaxNode};
+use ra_db::{salsa, CrateId};
+use ra_syntax::{ast, AstNode};
 
 use crate::{builtin_type::BuiltinType, db::InternDatabase};
 
-pub enum ModuleSource {
-    SourceFile(ast::SourceFile),
-    Module(ast::Module),
-}
-
-impl ModuleSource {
-    pub fn new(
-        db: &impl db::DefDatabase,
-        file_id: Option<FileId>,
-        decl_id: Option<AstId<ast::Module>>,
-    ) -> ModuleSource {
-        match (file_id, decl_id) {
-            (Some(file_id), _) => {
-                let source_file = db.parse(file_id).tree();
-                ModuleSource::SourceFile(source_file)
-            }
-            (None, Some(item_id)) => {
-                let module = item_id.to_node(db);
-                assert!(module.item_list().is_some(), "expected inline module");
-                ModuleSource::Module(module)
-            }
-            (None, None) => panic!(),
-        }
-    }
-
-    // FIXME: this methods do not belong here
-    pub fn from_position(db: &impl db::DefDatabase, position: ra_db::FilePosition) -> ModuleSource {
-        let parse = db.parse(position.file_id);
-        match &ra_syntax::algo::find_node_at_offset::<ast::Module>(
-            parse.tree().syntax(),
-            position.offset,
-        ) {
-            Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()),
-            _ => {
-                let source_file = parse.tree();
-                ModuleSource::SourceFile(source_file)
-            }
-        }
-    }
-
-    pub fn from_child_node(db: &impl db::DefDatabase, child: Source<&SyntaxNode>) -> ModuleSource {
-        if let Some(m) =
-            child.value.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi())
-        {
-            ModuleSource::Module(m)
-        } else {
-            let file_id = child.file_id.original_file(db);
-            let source_file = db.parse(file_id).tree();
-            ModuleSource::SourceFile(source_file)
-        }
-    }
-
-    pub fn from_file_id(db: &impl db::DefDatabase, file_id: FileId) -> ModuleSource {
-        let source_file = db.parse(file_id).tree();
-        ModuleSource::SourceFile(source_file)
-    }
-}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct LocalImportId(RawId);
+impl_arena_id!(LocalImportId);
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 pub struct ModuleId {
     pub krate: CrateId,
-    pub module_id: CrateModuleId,
+    pub module_id: LocalModuleId,
 }
 
 /// An ID of a module, **local** to a specific crate
 // FIXME: rename to `LocalModuleId`.
 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct CrateModuleId(RawId);
-impl_arena_id!(CrateModuleId);
+pub struct LocalModuleId(RawId);
+impl_arena_id!(LocalModuleId);
 
 macro_rules! impl_intern_key {
     ($name:ident) => {
diff --git a/crates/ra_hir_def/src/nameres.rs b/crates/ra_hir_def/src/nameres.rs
index 101203b7b5..3b2e996470 100644
--- a/crates/ra_hir_def/src/nameres.rs
+++ b/crates/ra_hir_def/src/nameres.rs
@@ -47,8 +47,7 @@
 //! path and, upon success, we run macro expansion and "collect module" phase on
 //! the result
 
-pub mod raw;
-pub mod per_ns;
+pub(crate) mod raw;
 mod collector;
 mod mod_resolution;
 mod path_resolution;
@@ -72,11 +71,10 @@ use rustc_hash::{FxHashMap, FxHashSet};
 use crate::{
     builtin_type::BuiltinType,
     db::DefDatabase,
-    nameres::{
-        diagnostics::DefDiagnostic, path_resolution::ResolveMode, per_ns::PerNs, raw::ImportId,
-    },
+    nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
     path::Path,
-    AstId, CrateModuleId, FunctionId, ImplId, ModuleDefId, ModuleId, TraitId,
+    per_ns::PerNs,
+    AstId, FunctionId, ImplId, LocalImportId, LocalModuleId, ModuleDefId, ModuleId, TraitId,
 };
 
 /// Contains all top-level defs from a macro-expanded crate
@@ -89,8 +87,8 @@ pub struct CrateDefMap {
     /// a dependency (`std` or `core`).
     prelude: Option<ModuleId>,
     extern_prelude: FxHashMap<Name, ModuleDefId>,
-    root: CrateModuleId,
-    modules: Arena<CrateModuleId, ModuleData>,
+    root: LocalModuleId,
+    modules: Arena<LocalModuleId, ModuleData>,
 
     /// Some macros are not well-behavior, which leads to infinite loop
     /// e.g. macro_rules! foo { ($ty:ty) => { foo!($ty); } }
@@ -107,17 +105,17 @@ pub struct CrateDefMap {
     diagnostics: Vec<DefDiagnostic>,
 }
 
-impl std::ops::Index<CrateModuleId> for CrateDefMap {
+impl std::ops::Index<LocalModuleId> for CrateDefMap {
     type Output = ModuleData;
-    fn index(&self, id: CrateModuleId) -> &ModuleData {
+    fn index(&self, id: LocalModuleId) -> &ModuleData {
         &self.modules[id]
     }
 }
 
 #[derive(Default, Debug, PartialEq, Eq)]
 pub struct ModuleData {
-    pub parent: Option<CrateModuleId>,
-    pub children: FxHashMap<Name, CrateModuleId>,
+    pub parent: Option<LocalModuleId>,
+    pub children: FxHashMap<Name, LocalModuleId>,
     pub scope: ModuleScope,
 
     //  FIXME: these can't be both null, we need a three-state enum here.
@@ -213,7 +211,7 @@ pub struct Resolution {
     /// None for unresolved
     pub def: PerNs,
     /// ident by which this is imported into local scope.
-    pub import: Option<ImportId>,
+    pub import: Option<LocalImportId>,
 }
 
 impl CrateDefMap {
@@ -227,7 +225,7 @@ impl CrateDefMap {
         let def_map = {
             let crate_graph = db.crate_graph();
             let edition = crate_graph.edition(krate);
-            let mut modules: Arena<CrateModuleId, ModuleData> = Arena::default();
+            let mut modules: Arena<LocalModuleId, ModuleData> = Arena::default();
             let root = modules.alloc(ModuleData::default());
             CrateDefMap {
                 krate,
@@ -248,7 +246,7 @@ impl CrateDefMap {
         self.krate
     }
 
-    pub fn root(&self) -> CrateModuleId {
+    pub fn root(&self) -> LocalModuleId {
         self.root
     }
 
@@ -263,7 +261,7 @@ impl CrateDefMap {
     pub fn add_diagnostics(
         &self,
         db: &impl DefDatabase,
-        module: CrateModuleId,
+        module: LocalModuleId,
         sink: &mut DiagnosticSink,
     ) {
         self.diagnostics.iter().for_each(|it| it.add_to(db, module, sink))
@@ -272,18 +270,18 @@ impl CrateDefMap {
     pub fn resolve_path(
         &self,
         db: &impl DefDatabase,
-        original_module: CrateModuleId,
+        original_module: LocalModuleId,
         path: &Path,
     ) -> (PerNs, Option<usize>) {
         let res = self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path);
         (res.resolved_def, res.segment_index)
     }
 
-    pub fn modules(&self) -> impl Iterator<Item = CrateModuleId> + '_ {
+    pub fn modules(&self) -> impl Iterator<Item = LocalModuleId> + '_ {
         self.modules.iter().map(|(id, _data)| id)
     }
 
-    pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = CrateModuleId> + '_ {
+    pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
         self.modules
             .iter()
             .filter(move |(_id, data)| data.definition == Some(file_id))
@@ -319,12 +317,12 @@ mod diagnostics {
     use ra_db::RelativePathBuf;
     use ra_syntax::{ast, AstPtr};
 
-    use crate::{db::DefDatabase, diagnostics::UnresolvedModule, nameres::CrateModuleId, AstId};
+    use crate::{db::DefDatabase, diagnostics::UnresolvedModule, nameres::LocalModuleId, AstId};
 
     #[derive(Debug, PartialEq, Eq)]
     pub(super) enum DefDiagnostic {
         UnresolvedModule {
-            module: CrateModuleId,
+            module: LocalModuleId,
             declaration: AstId<ast::Module>,
             candidate: RelativePathBuf,
         },
@@ -334,7 +332,7 @@ mod diagnostics {
         pub(super) fn add_to(
             &self,
             db: &impl DefDatabase,
-            target_module: CrateModuleId,
+            target_module: LocalModuleId,
             sink: &mut DiagnosticSink,
         ) {
             match self {
diff --git a/crates/ra_hir_def/src/nameres/collector.rs b/crates/ra_hir_def/src/nameres/collector.rs
index 1894b072a9..b02364e86f 100644
--- a/crates/ra_hir_def/src/nameres/collector.rs
+++ b/crates/ra_hir_def/src/nameres/collector.rs
@@ -16,11 +16,12 @@ use crate::{
     db::DefDatabase,
     nameres::{
         diagnostics::DefDiagnostic, mod_resolution::ModDir, path_resolution::ReachedFixedPoint,
-        per_ns::PerNs, raw, CrateDefMap, ModuleData, Resolution, ResolveMode,
+        raw, CrateDefMap, ModuleData, Resolution, ResolveMode,
     },
     path::{Path, PathKind},
-    AdtId, AstId, AstItemDef, ConstLoc, ContainerId, CrateModuleId, EnumId, EnumVariantId,
-    FunctionLoc, ImplId, Intern, LocationCtx, ModuleDefId, ModuleId, StaticId, StructId,
+    per_ns::PerNs,
+    AdtId, AstId, AstItemDef, ConstLoc, ContainerId, EnumId, EnumVariantId, FunctionLoc, ImplId,
+    Intern, LocalImportId, LocalModuleId, LocationCtx, ModuleDefId, ModuleId, StaticId, StructId,
     StructOrUnionId, TraitId, TypeAliasLoc, UnionId,
 };
 
@@ -94,10 +95,10 @@ impl MacroStackMonitor {
 struct DefCollector<'a, DB> {
     db: &'a DB,
     def_map: CrateDefMap,
-    glob_imports: FxHashMap<CrateModuleId, Vec<(CrateModuleId, raw::ImportId)>>,
-    unresolved_imports: Vec<(CrateModuleId, raw::ImportId, raw::ImportData)>,
-    unexpanded_macros: Vec<(CrateModuleId, AstId<ast::MacroCall>, Path)>,
-    mod_dirs: FxHashMap<CrateModuleId, ModDir>,
+    glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, LocalImportId)>>,
+    unresolved_imports: Vec<(LocalModuleId, LocalImportId, raw::ImportData)>,
+    unexpanded_macros: Vec<(LocalModuleId, AstId<ast::MacroCall>, Path)>,
+    mod_dirs: FxHashMap<LocalModuleId, ModDir>,
 
     /// Some macro use `$tt:tt which mean we have to handle the macro perfectly
     /// To prevent stack overflow, we add a deep counter here for prevent that.
@@ -173,7 +174,7 @@ where
     /// ```
     fn define_macro(
         &mut self,
-        module_id: CrateModuleId,
+        module_id: LocalModuleId,
         name: Name,
         macro_: MacroDefId,
         export: bool,
@@ -200,7 +201,7 @@ where
     /// the definition of current module.
     /// And also, `macro_use` on a module will import all legacy macros visable inside to
     /// current legacy scope, with possible shadowing.
-    fn define_legacy_macro(&mut self, module_id: CrateModuleId, name: Name, macro_: MacroDefId) {
+    fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, macro_: MacroDefId) {
         // Always shadowing
         self.def_map.modules[module_id].scope.legacy_macros.insert(name, macro_);
     }
@@ -208,7 +209,7 @@ where
     /// Import macros from `#[macro_use] extern crate`.
     fn import_macros_from_extern_crate(
         &mut self,
-        current_module_id: CrateModuleId,
+        current_module_id: LocalModuleId,
         import: &raw::ImportData,
     ) {
         log::debug!(
@@ -235,7 +236,7 @@ where
     /// Exported macros are just all macros in the root module scope.
     /// Note that it contains not only all `#[macro_export]` macros, but also all aliases
     /// created by `use` in the root module, ignoring the visibility of `use`.
-    fn import_all_macros_exported(&mut self, current_module_id: CrateModuleId, krate: CrateId) {
+    fn import_all_macros_exported(&mut self, current_module_id: LocalModuleId, krate: CrateId) {
         let def_map = self.db.crate_def_map(krate);
         for (name, def) in def_map[def_map.root].scope.macros() {
             // `macro_use` only bring things into legacy scope.
@@ -265,7 +266,7 @@ where
 
     fn resolve_import(
         &self,
-        module_id: CrateModuleId,
+        module_id: LocalModuleId,
         import: &raw::ImportData,
     ) -> (PerNs, ReachedFixedPoint) {
         log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
@@ -291,9 +292,9 @@ where
 
     fn record_resolved_import(
         &mut self,
-        module_id: CrateModuleId,
+        module_id: LocalModuleId,
         def: PerNs,
-        import_id: raw::ImportId,
+        import_id: LocalImportId,
         import: &raw::ImportData,
     ) {
         if import.is_glob {
@@ -387,8 +388,8 @@ where
 
     fn update(
         &mut self,
-        module_id: CrateModuleId,
-        import: Option<raw::ImportId>,
+        module_id: LocalModuleId,
+        import: Option<LocalImportId>,
         resolutions: &[(Name, Resolution)],
     ) {
         self.update_recursive(module_id, import, resolutions, 0)
@@ -396,8 +397,8 @@ where
 
     fn update_recursive(
         &mut self,
-        module_id: CrateModuleId,
-        import: Option<raw::ImportId>,
+        module_id: LocalModuleId,
+        import: Option<LocalImportId>,
         resolutions: &[(Name, Resolution)],
         depth: usize,
     ) {
@@ -484,7 +485,7 @@ where
 
     fn collect_macro_expansion(
         &mut self,
-        module_id: CrateModuleId,
+        module_id: LocalModuleId,
         macro_call_id: MacroCallId,
         macro_def_id: MacroDefId,
     ) {
@@ -522,7 +523,7 @@ where
 /// Walks a single module, populating defs, imports and macros
 struct ModCollector<'a, D> {
     def_collector: D,
-    module_id: CrateModuleId,
+    module_id: LocalModuleId,
     file_id: HirFileId,
     raw_items: &'a raw::RawItems,
     mod_dir: ModDir,
@@ -647,7 +648,7 @@ where
         name: Name,
         declaration: AstId<ast::Module>,
         definition: Option<FileId>,
-    ) -> CrateModuleId {
+    ) -> LocalModuleId {
         let modules = &mut self.def_collector.def_map.modules;
         let res = modules.alloc(ModuleData::default());
         modules[res].parent = Some(self.module_id);
@@ -772,7 +773,7 @@ where
         self.def_collector.unexpanded_macros.push((self.module_id, ast_id, path));
     }
 
-    fn import_all_legacy_macros(&mut self, module_id: CrateModuleId) {
+    fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
         let macros = self.def_collector.def_map[module_id].scope.legacy_macros.clone();
         for (name, macro_) in macros {
             self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_);
@@ -827,7 +828,7 @@ mod tests {
 
         let def_map = {
             let edition = db.crate_graph().edition(krate);
-            let mut modules: Arena<CrateModuleId, ModuleData> = Arena::default();
+            let mut modules: Arena<LocalModuleId, ModuleData> = Arena::default();
             let root = modules.alloc(ModuleData::default());
             CrateDefMap {
                 krate,
diff --git a/crates/ra_hir_def/src/nameres/path_resolution.rs b/crates/ra_hir_def/src/nameres/path_resolution.rs
index 102009ac70..9455f22bbd 100644
--- a/crates/ra_hir_def/src/nameres/path_resolution.rs
+++ b/crates/ra_hir_def/src/nameres/path_resolution.rs
@@ -16,9 +16,10 @@ use test_utils::tested_by;
 
 use crate::{
     db::DefDatabase,
-    nameres::{per_ns::PerNs, CrateDefMap},
+    nameres::CrateDefMap,
     path::{Path, PathKind},
-    AdtId, CrateModuleId, EnumVariantId, ModuleDefId, ModuleId,
+    per_ns::PerNs,
+    AdtId, EnumVariantId, LocalModuleId, ModuleDefId, ModuleId,
 };
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -65,7 +66,7 @@ impl CrateDefMap {
         &self,
         db: &impl DefDatabase,
         mode: ResolveMode,
-        original_module: CrateModuleId,
+        original_module: LocalModuleId,
         path: &Path,
     ) -> ResolvePathResult {
         let mut segments = path.segments.iter().enumerate();
@@ -217,7 +218,7 @@ impl CrateDefMap {
     fn resolve_name_in_module(
         &self,
         db: &impl DefDatabase,
-        module: CrateModuleId,
+        module: LocalModuleId,
         name: &Name,
     ) -> PerNs {
         // Resolve in:
diff --git a/crates/ra_hir_def/src/nameres/raw.rs b/crates/ra_hir_def/src/nameres/raw.rs
index 7618cb0596..552cbe5448 100644
--- a/crates/ra_hir_def/src/nameres/raw.rs
+++ b/crates/ra_hir_def/src/nameres/raw.rs
@@ -12,7 +12,7 @@ use hir_expand::{
 use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
 use ra_syntax::{
     ast::{self, AttrsOwner, NameOwner},
-    AstNode, AstPtr, SourceFile,
+    AstNode, AstPtr,
 };
 use test_utils::tested_by;
 
@@ -20,7 +20,7 @@ use crate::{
     attr::{Attr, Attrs},
     db::DefDatabase,
     path::Path,
-    FileAstId, HirFileId, ModuleSource, Source,
+    FileAstId, HirFileId, LocalImportId, Source,
 };
 
 /// `RawItems` is a set of top-level items in a file (except for impls).
@@ -30,7 +30,7 @@ use crate::{
 #[derive(Debug, Default, PartialEq, Eq)]
 pub struct RawItems {
     modules: Arena<Module, ModuleData>,
-    imports: Arena<ImportId, ImportData>,
+    imports: Arena<LocalImportId, ImportData>,
     defs: Arena<Def, DefData>,
     macros: Arena<Macro, MacroData>,
     impls: Arena<Impl, ImplData>,
@@ -40,28 +40,18 @@ pub struct RawItems {
 
 #[derive(Debug, Default, PartialEq, Eq)]
 pub struct ImportSourceMap {
-    map: ArenaMap<ImportId, ImportSourcePtr>,
+    map: ArenaMap<LocalImportId, ImportSourcePtr>,
 }
 
 type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>;
-type ImportSource = Either<ast::UseTree, ast::ExternCrateItem>;
-
-fn to_node(ptr: ImportSourcePtr, file: &SourceFile) -> ImportSource {
-    ptr.map(|ptr| ptr.to_node(file.syntax()), |ptr| ptr.to_node(file.syntax()))
-}
 
 impl ImportSourceMap {
-    fn insert(&mut self, import: ImportId, ptr: ImportSourcePtr) {
+    fn insert(&mut self, import: LocalImportId, ptr: ImportSourcePtr) {
         self.map.insert(import, ptr)
     }
 
-    pub fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource {
-        let file = match source {
-            ModuleSource::SourceFile(file) => file.clone(),
-            ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(),
-        };
-
-        to_node(self.map[import], &file)
+    pub fn get(&self, import: LocalImportId) -> ImportSourcePtr {
+        self.map[import].clone()
     }
 }
 
@@ -106,9 +96,9 @@ impl Index<Module> for RawItems {
     }
 }
 
-impl Index<ImportId> for RawItems {
+impl Index<LocalImportId> for RawItems {
     type Output = ImportData;
-    fn index(&self, idx: ImportId) -> &ImportData {
+    fn index(&self, idx: LocalImportId) -> &ImportData {
         &self.imports[idx]
     }
 }
@@ -143,7 +133,7 @@ pub(super) struct RawItem {
 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
 pub(super) enum RawItemKind {
     Module(Module),
-    Import(ImportId),
+    Import(LocalImportId),
     Def(Def),
     Macro(Macro),
     Impl(Impl),
@@ -159,10 +149,6 @@ pub(super) enum ModuleData {
     Definition { name: Name, ast_id: FileAstId<ast::Module>, items: Vec<RawItem> },
 }
 
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub struct ImportId(RawId);
-impl_arena_id!(ImportId);
-
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct ImportData {
     pub(super) path: Path,
diff --git a/crates/ra_hir_def/src/nameres/per_ns.rs b/crates/ra_hir_def/src/per_ns.rs
similarity index 100%
rename from crates/ra_hir_def/src/nameres/per_ns.rs
rename to crates/ra_hir_def/src/per_ns.rs
diff --git a/crates/ra_hir_def/src/resolver.rs b/crates/ra_hir_def/src/resolver.rs
index 48a836a20e..b56de44dd7 100644
--- a/crates/ra_hir_def/src/resolver.rs
+++ b/crates/ra_hir_def/src/resolver.rs
@@ -14,11 +14,12 @@ use crate::{
     db::DefDatabase,
     expr::{ExprId, PatId},
     generics::GenericParams,
-    nameres::{per_ns::PerNs, CrateDefMap},
+    nameres::CrateDefMap,
     path::{Path, PathKind},
-    AdtId, AstItemDef, ConstId, ContainerId, CrateModuleId, DefWithBodyId, EnumId, EnumVariantId,
-    FunctionId, GenericDefId, ImplId, Lookup, ModuleDefId, ModuleId, StaticId, StructId, TraitId,
-    TypeAliasId,
+    per_ns::PerNs,
+    AdtId, AstItemDef, ConstId, ContainerId, DefWithBodyId, EnumId, EnumVariantId, FunctionId,
+    GenericDefId, ImplId, LocalModuleId, Lookup, ModuleDefId, ModuleId, StaticId, StructId,
+    TraitId, TypeAliasId,
 };
 
 #[derive(Debug, Clone, Default)]
@@ -30,7 +31,7 @@ pub struct Resolver {
 #[derive(Debug, Clone)]
 pub(crate) struct ModuleItemMap {
     crate_def_map: Arc<CrateDefMap>,
-    module_id: CrateModuleId,
+    module_id: LocalModuleId,
 }
 
 #[derive(Debug, Clone)]
@@ -330,7 +331,7 @@ impl Resolver {
         traits
     }
 
-    fn module(&self) -> Option<(&CrateDefMap, CrateModuleId)> {
+    fn module(&self) -> Option<(&CrateDefMap, LocalModuleId)> {
         self.scopes.iter().rev().find_map(|scope| match scope {
             Scope::ModuleScope(m) => Some((&*m.crate_def_map, m.module_id)),
 
@@ -466,7 +467,7 @@ impl Resolver {
     fn push_module_scope(
         self,
         crate_def_map: Arc<CrateDefMap>,
-        module_id: CrateModuleId,
+        module_id: LocalModuleId,
     ) -> Resolver {
         self.push_scope(Scope::ModuleScope(ModuleItemMap { crate_def_map, module_id }))
     }


Test patch:
diff --git a/crates/ra_hir_def/src/nameres/tests.rs b/crates/ra_hir_def/src/nameres/tests.rs
index b5053ba20e..f0b86af7c1 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;
 use ra_db::{fixture::WithFixture, SourceDatabase};
 use test_utils::covers;
 
-use crate::{db::DefDatabase, nameres::*, test_db::TestDB, CrateModuleId};
+use crate::{db::DefDatabase, nameres::*, test_db::TestDB, LocalModuleId};
 
 fn def_map(fixtute: &str) -> String {
     let dm = compute_crate_def_map(fixtute);
@@ -28,7 +28,7 @@ fn render_crate_def_map(map: &CrateDefMap) -> String {
     go(&mut buf, map, "\ncrate", map.root());
     return buf.trim().to_string();
 
-    fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: CrateModuleId) {
+    fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: LocalModuleId) {
         *buf += path;
         *buf += "\n";
 
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 eb7b85c07c..e11530062d 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() {
         @r###"
     [
         UnresolvedModule {
-            module: CrateModuleId(
+            module: LocalModuleId(
                 0,
             ),
             declaration: AstId {