introduce ra_hir_def

This commit is contained in:
Aleksey Kladov 2019-10-30 12:27:54 +03:00
parent 56bc874f1d
commit a136cc0653
14 changed files with 139 additions and 100 deletions

12
Cargo.lock generated
View file

@ -1003,6 +1003,7 @@ dependencies = [
"ra_arena 0.1.0", "ra_arena 0.1.0",
"ra_cfg 0.1.0", "ra_cfg 0.1.0",
"ra_db 0.1.0", "ra_db 0.1.0",
"ra_hir_def 0.1.0",
"ra_hir_expand 0.1.0", "ra_hir_expand 0.1.0",
"ra_mbe 0.1.0", "ra_mbe 0.1.0",
"ra_prof 0.1.0", "ra_prof 0.1.0",
@ -1013,6 +1014,17 @@ dependencies = [
"test_utils 0.1.0", "test_utils 0.1.0",
] ]
[[package]]
name = "ra_hir_def"
version = "0.1.0"
dependencies = [
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"ra_arena 0.1.0",
"ra_db 0.1.0",
"ra_prof 0.1.0",
"ra_syntax 0.1.0",
]
[[package]] [[package]]
name = "ra_hir_expand" name = "ra_hir_expand"
version = "0.1.0" version = "0.1.0"

View file

@ -20,6 +20,7 @@ ra_db = { path = "../ra_db" }
mbe = { path = "../ra_mbe", package = "ra_mbe" } mbe = { path = "../ra_mbe", package = "ra_mbe" }
tt = { path = "../ra_tt", package = "ra_tt" } tt = { path = "../ra_tt", package = "ra_tt" }
hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
hir_def = { path = "../ra_hir_def", package = "ra_hir_def" }
test_utils = { path = "../test_utils" } test_utils = { path = "../test_utils" }
ra_prof = { path = "../ra_prof" } ra_prof = { path = "../ra_prof" }

View file

@ -5,6 +5,7 @@ pub(crate) mod docs;
use std::sync::Arc; use std::sync::Arc;
use hir_def::{CrateModuleId, ModuleId};
use ra_db::{CrateId, Edition, FileId}; use ra_db::{CrateId, Edition, FileId};
use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner}; use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner};
@ -23,7 +24,7 @@ use crate::{
BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, U16, U32, U64, BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, U16, U32, U64,
U8, USIZE, U8, USIZE,
}, },
nameres::{CrateModuleId, ImportId, ModuleScope, Namespace}, nameres::{ImportId, ModuleScope, Namespace},
resolve::{Resolver, Scope, TypeNs}, resolve::{Resolver, Scope, TypeNs},
traits::TraitData, traits::TraitData,
ty::{ ty::{
@ -67,8 +68,7 @@ impl Crate {
pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> { pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> {
let module_id = db.crate_def_map(self).root(); let module_id = db.crate_def_map(self).root();
let module = Module { krate: self, module_id }; Some(Module::new(self, module_id))
Some(module)
} }
pub fn edition(self, db: &impl DefDatabase) -> Edition { pub fn edition(self, db: &impl DefDatabase) -> Edition {
@ -83,8 +83,7 @@ impl Crate {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Module { pub struct Module {
pub(crate) krate: Crate, pub(crate) id: ModuleId,
pub(crate) module_id: CrateModuleId,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@ -175,12 +174,16 @@ impl ModuleSource {
} }
impl Module { impl Module {
pub(crate) fn new(krate: Crate, crate_module_id: CrateModuleId) -> Module {
Module { id: ModuleId { krate: krate.crate_id, module_id: crate_module_id } }
}
/// Name of this module. /// Name of this module.
pub fn name(self, db: &impl DefDatabase) -> Option<Name> { pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
let parent = def_map[self.module_id].parent?; let parent = def_map[self.id.module_id].parent?;
def_map[parent].children.iter().find_map(|(name, module_id)| { def_map[parent].children.iter().find_map(|(name, module_id)| {
if *module_id == self.module_id { if *module_id == self.id.module_id {
Some(name.clone()) Some(name.clone())
} else { } else {
None None
@ -200,29 +203,29 @@ impl Module {
} }
/// Returns the crate this module is part of. /// Returns the crate this module is part of.
pub fn krate(self, _db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self) -> Crate {
Some(self.krate) Crate { crate_id: self.id.krate }
} }
/// Topmost parent of this module. Every module has a `crate_root`, but some /// Topmost parent of this module. Every module has a `crate_root`, but some
/// might be missing `krate`. This can happen if a module's file is not included /// might be missing `krate`. This can happen if a module's file is not included
/// in the module tree of any target in `Cargo.toml`. /// in the module tree of any target in `Cargo.toml`.
pub fn crate_root(self, db: &impl DefDatabase) -> Module { pub fn crate_root(self, db: &impl DefDatabase) -> Module {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
self.with_module_id(def_map.root()) self.with_module_id(def_map.root())
} }
/// Finds a child module with the specified name. /// Finds a child module with the specified name.
pub fn child(self, db: &impl HirDatabase, name: &Name) -> Option<Module> { pub fn child(self, db: &impl HirDatabase, name: &Name) -> Option<Module> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
let child_id = def_map[self.module_id].children.get(name)?; let child_id = def_map[self.id.module_id].children.get(name)?;
Some(self.with_module_id(*child_id)) Some(self.with_module_id(*child_id))
} }
/// Iterates over all child modules. /// Iterates over all child modules.
pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
let children = def_map[self.module_id] let children = def_map[self.id.module_id]
.children .children
.iter() .iter()
.map(|(_, module_id)| self.with_module_id(*module_id)) .map(|(_, module_id)| self.with_module_id(*module_id))
@ -232,8 +235,8 @@ impl Module {
/// Finds a parent module. /// Finds a parent module.
pub fn parent(self, db: &impl DefDatabase) -> Option<Module> { pub fn parent(self, db: &impl DefDatabase) -> Option<Module> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
let parent_id = def_map[self.module_id].parent?; let parent_id = def_map[self.id.module_id].parent?;
Some(self.with_module_id(parent_id)) Some(self.with_module_id(parent_id))
} }
@ -249,11 +252,11 @@ impl Module {
/// Returns a `ModuleScope`: a set of items, visible in this module. /// Returns a `ModuleScope`: a set of items, visible in this module.
pub fn scope(self, db: &impl HirDatabase) -> ModuleScope { pub fn scope(self, db: &impl HirDatabase) -> ModuleScope {
db.crate_def_map(self.krate)[self.module_id].scope.clone() db.crate_def_map(self.krate())[self.id.module_id].scope.clone()
} }
pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
db.crate_def_map(self.krate).add_diagnostics(db, self.module_id, sink); db.crate_def_map(self.krate()).add_diagnostics(db, self.id.module_id, sink);
for decl in self.declarations(db) { for decl in self.declarations(db) {
match decl { match decl {
crate::ModuleDef::Function(f) => f.diagnostics(db, sink), crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
@ -277,13 +280,13 @@ impl Module {
} }
pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver { pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
Resolver::default().push_module_scope(def_map, self.module_id) Resolver::default().push_module_scope(def_map, self.id.module_id)
} }
pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> { pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
def_map[self.module_id] def_map[self.id.module_id]
.scope .scope
.entries() .entries()
.filter_map(|(_name, res)| if res.import.is_none() { Some(res.def) } else { None }) .filter_map(|(_name, res)| if res.import.is_none() { Some(res.def) } else { None })
@ -303,7 +306,7 @@ impl Module {
} }
fn with_module_id(self, module_id: CrateModuleId) -> Module { fn with_module_id(self, module_id: CrateModuleId) -> Module {
Module { module_id, krate: self.krate } Module::new(self.krate(), module_id)
} }
} }
@ -344,7 +347,7 @@ impl Struct {
} }
pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
self.module(db).krate(db) Some(self.module(db).krate())
} }
pub fn name(self, db: &impl DefDatabase) -> Option<Name> { pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
@ -432,7 +435,7 @@ impl Enum {
} }
pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
self.module(db).krate(db) Some(self.module(db).krate())
} }
pub fn name(self, db: &impl DefDatabase) -> Option<Name> { pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
@ -523,12 +526,14 @@ impl Adt {
} }
pub fn krate(self, db: &impl HirDatabase) -> Option<Crate> { pub fn krate(self, db: &impl HirDatabase) -> Option<Crate> {
Some(
match self { match self {
Adt::Struct(s) => s.module(db), Adt::Struct(s) => s.module(db),
Adt::Union(s) => s.module(db), Adt::Union(s) => s.module(db),
Adt::Enum(e) => e.module(db), Adt::Enum(e) => e.module(db),
} }
.krate(db) .krate(),
)
} }
pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver { pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
@ -696,7 +701,7 @@ impl Function {
} }
pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
self.module(db).krate(db) Some(self.module(db).krate())
} }
pub fn name(self, db: &impl HirDatabase) -> Name { pub fn name(self, db: &impl HirDatabase) -> Name {
@ -774,7 +779,7 @@ impl Const {
} }
pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
self.module(db).krate(db) Some(self.module(db).krate())
} }
pub fn data(self, db: &impl HirDatabase) -> Arc<ConstData> { pub fn data(self, db: &impl HirDatabase) -> Arc<ConstData> {
@ -871,7 +876,7 @@ impl Static {
} }
pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
self.module(db).krate(db) Some(self.module(db).krate())
} }
pub fn data(self, db: &impl HirDatabase) -> Arc<ConstData> { pub fn data(self, db: &impl HirDatabase) -> Arc<ConstData> {
@ -1002,7 +1007,7 @@ impl TypeAlias {
} }
pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
self.module(db).krate(db) Some(self.module(db).krate())
} }
/// The containing impl block, if this is a method. /// The containing impl block, if this is a method.

View file

@ -37,9 +37,9 @@ impl<T> Source<T> {
impl Module { impl Module {
/// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
pub fn definition_source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ModuleSource> { pub fn definition_source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ModuleSource> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
let decl_id = def_map[self.module_id].declaration; let decl_id = def_map[self.id.module_id].declaration;
let file_id = def_map[self.module_id].definition; let file_id = def_map[self.id.module_id].definition;
let ast = ModuleSource::new(db, file_id, decl_id); let ast = ModuleSource::new(db, file_id, decl_id);
let file_id = file_id.map(HirFileId::from).unwrap_or_else(|| decl_id.unwrap().file_id()); let file_id = file_id.map(HirFileId::from).unwrap_or_else(|| decl_id.unwrap().file_id());
Source { file_id, ast } Source { file_id, ast }
@ -51,8 +51,8 @@ impl Module {
self, self,
db: &(impl DefDatabase + AstDatabase), db: &(impl DefDatabase + AstDatabase),
) -> Option<Source<ast::Module>> { ) -> Option<Source<ast::Module>> {
let def_map = db.crate_def_map(self.krate); let def_map = db.crate_def_map(self.krate());
let decl = def_map[self.module_id].declaration?; let decl = def_map[self.id.module_id].declaration?;
let ast = decl.to_node(db); let ast = decl.to_node(db);
Some(Source { file_id: decl.file_id(), ast }) Some(Source { file_id: decl.file_id(), ast })
} }

View file

@ -195,7 +195,7 @@ impl Module {
.find_map(|krate| { .find_map(|krate| {
let def_map = db.crate_def_map(krate); let def_map = db.crate_def_map(krate);
let module_id = def_map.find_module_by_source(src.file_id, decl_id)?; let module_id = def_map.find_module_by_source(src.file_id, decl_id)?;
Some(Module { krate, module_id }) Some(Module::new(krate, module_id))
}) })
} }
} }

View file

@ -182,7 +182,7 @@ impl ModuleImplBlocks {
) -> (Arc<ModuleImplBlocks>, Arc<ImplSourceMap>) { ) -> (Arc<ModuleImplBlocks>, Arc<ImplSourceMap>) {
let mut source_map = ImplSourceMap::default(); let mut source_map = ImplSourceMap::default();
let crate_graph = db.crate_graph(); let crate_graph = db.crate_graph();
let cfg_options = crate_graph.cfg_options(module.krate.crate_id()); let cfg_options = crate_graph.cfg_options(module.id.krate);
let result = ModuleImplBlocks::collect(db, cfg_options, module, &mut source_map); let result = ModuleImplBlocks::collect(db, cfg_options, module, &mut source_map);
(Arc::new(result), Arc::new(source_map)) (Arc::new(result), Arc::new(source_map))

View file

@ -22,14 +22,14 @@ pub enum LangItemTarget {
impl LangItemTarget { impl LangItemTarget {
pub(crate) fn krate(&self, db: &impl HirDatabase) -> Option<Crate> { pub(crate) fn krate(&self, db: &impl HirDatabase) -> Option<Crate> {
match self { Some(match self {
LangItemTarget::Enum(e) => e.module(db).krate(db), LangItemTarget::Enum(e) => e.module(db).krate(),
LangItemTarget::Function(f) => f.module(db).krate(db), LangItemTarget::Function(f) => f.module(db).krate(),
LangItemTarget::ImplBlock(i) => i.module().krate(db), LangItemTarget::ImplBlock(i) => i.module().krate(),
LangItemTarget::Static(s) => s.module(db).krate(db), LangItemTarget::Static(s) => s.module(db).krate(),
LangItemTarget::Struct(s) => s.module(db).krate(db), LangItemTarget::Struct(s) => s.module(db).krate(),
LangItemTarget::Trait(t) => t.module(db).krate(db), LangItemTarget::Trait(t) => t.module(db).krate(),
} })
} }
} }

View file

@ -56,8 +56,9 @@ mod tests;
use std::sync::Arc; use std::sync::Arc;
use hir_def::CrateModuleId;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use ra_arena::{impl_arena_id, Arena, RawId}; use ra_arena::Arena;
use ra_db::{Edition, FileId}; use ra_db::{Edition, FileId};
use ra_prof::profile; use ra_prof::profile;
use ra_syntax::ast; use ra_syntax::ast;
@ -115,13 +116,8 @@ impl std::ops::Index<CrateModuleId> for CrateDefMap {
} }
} }
/// An ID of a module, **local** to a specific crate
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct CrateModuleId(RawId);
impl_arena_id!(CrateModuleId);
#[derive(Default, Debug, PartialEq, Eq)] #[derive(Default, Debug, PartialEq, Eq)]
pub(crate) struct ModuleData { pub struct ModuleData {
pub(crate) parent: Option<CrateModuleId>, pub(crate) parent: Option<CrateModuleId>,
pub(crate) children: FxHashMap<Name, CrateModuleId>, pub(crate) children: FxHashMap<Name, CrateModuleId>,
pub(crate) scope: ModuleScope, pub(crate) scope: ModuleScope,
@ -335,7 +331,7 @@ impl CrateDefMap {
PathKind::DollarCrate(krate) => { PathKind::DollarCrate(krate) => {
if krate == self.krate { if krate == self.krate {
tested_by!(macro_dollar_crate_self); tested_by!(macro_dollar_crate_self);
PerNs::types(Module { krate: self.krate, module_id: self.root }.into()) PerNs::types(Module::new(self.krate, self.root).into())
} else { } else {
match krate.root_module(db) { match krate.root_module(db) {
Some(module) => { Some(module) => {
@ -346,12 +342,8 @@ impl CrateDefMap {
} }
} }
} }
PathKind::Crate => { PathKind::Crate => PerNs::types(Module::new(self.krate, self.root).into()),
PerNs::types(Module { krate: self.krate, module_id: self.root }.into()) PathKind::Self_ => PerNs::types(Module::new(self.krate, original_module).into()),
}
PathKind::Self_ => {
PerNs::types(Module { krate: self.krate, module_id: original_module }.into())
}
// plain import or absolute path in 2015: crate-relative with // plain import or absolute path in 2015: crate-relative with
// fallback to extern prelude (with the simplification in // fallback to extern prelude (with the simplification in
// rust-lang/rust#57745) // rust-lang/rust#57745)
@ -377,7 +369,7 @@ impl CrateDefMap {
} }
PathKind::Super => { PathKind::Super => {
if let Some(p) = self.modules[original_module].parent { if let Some(p) = self.modules[original_module].parent {
PerNs::types(Module { krate: self.krate, module_id: p }.into()) PerNs::types(Module::new(self.krate, p).into())
} else { } else {
log::debug!("super path in root module"); log::debug!("super path in root module");
return ResolvePathResult::empty(ReachedFixedPoint::Yes); return ResolvePathResult::empty(ReachedFixedPoint::Yes);
@ -419,12 +411,12 @@ impl CrateDefMap {
curr_per_ns = match curr { curr_per_ns = match curr {
ModuleDef::Module(module) => { ModuleDef::Module(module) => {
if module.krate != self.krate { if module.krate() != self.krate {
let path = let path =
Path { segments: path.segments[i..].to_vec(), kind: PathKind::Self_ }; Path { segments: path.segments[i..].to_vec(), kind: PathKind::Self_ };
log::debug!("resolving {:?} in other crate", path); log::debug!("resolving {:?} in other crate", path);
let defp_map = db.crate_def_map(module.krate); let defp_map = db.crate_def_map(module.krate());
let (def, s) = defp_map.resolve_path(db, module.module_id, &path); let (def, s) = defp_map.resolve_path(db, module.id.module_id, &path);
return ResolvePathResult::with( return ResolvePathResult::with(
def, def,
ReachedFixedPoint::Yes, ReachedFixedPoint::Yes,
@ -433,7 +425,7 @@ impl CrateDefMap {
} }
// Since it is a qualified path here, it should not contains legacy macros // Since it is a qualified path here, it should not contains legacy macros
match self[module.module_id].scope.get(&segment.name) { match self[module.id.module_id].scope.get(&segment.name) {
Some(res) => res.def, Some(res) => res.def,
_ => { _ => {
log::debug!("path segment {:?} not found", segment.name); log::debug!("path segment {:?} not found", segment.name);
@ -511,14 +503,14 @@ impl CrateDefMap {
fn resolve_in_prelude(&self, db: &impl DefDatabase, name: &Name) -> PerNs { fn resolve_in_prelude(&self, db: &impl DefDatabase, name: &Name) -> PerNs {
if let Some(prelude) = self.prelude { if let Some(prelude) = self.prelude {
let keep; let keep;
let def_map = if prelude.krate == self.krate { let def_map = if prelude.krate() == self.krate {
self self
} else { } else {
// Extend lifetime // Extend lifetime
keep = db.crate_def_map(prelude.krate); keep = db.crate_def_map(prelude.krate());
&keep &keep
}; };
def_map[prelude.module_id].scope.get(name).map_or_else(PerNs::none, |res| res.def) def_map[prelude.id.module_id].scope.get(name).map_or_else(PerNs::none, |res| res.def)
} else { } else {
PerNs::none() PerNs::none()
} }

View file

@ -212,7 +212,7 @@ where
if let Some(ModuleDef::Module(m)) = res.take_types() { if let Some(ModuleDef::Module(m)) = res.take_types() {
tested_by!(macro_rules_from_other_crates_are_visible_with_macro_use); tested_by!(macro_rules_from_other_crates_are_visible_with_macro_use);
self.import_all_macros_exported(current_module_id, m.krate); self.import_all_macros_exported(current_module_id, m.krate());
} }
} }
@ -289,11 +289,11 @@ where
if import.is_prelude { if import.is_prelude {
tested_by!(std_prelude); tested_by!(std_prelude);
self.def_map.prelude = Some(m); self.def_map.prelude = Some(m);
} else if m.krate != self.def_map.krate { } else if m.krate() != self.def_map.krate {
tested_by!(glob_across_crates); tested_by!(glob_across_crates);
// glob import from other crate => we can just import everything once // glob import from other crate => we can just import everything once
let item_map = self.db.crate_def_map(m.krate); let item_map = self.db.crate_def_map(m.krate());
let scope = &item_map[m.module_id].scope; let scope = &item_map[m.id.module_id].scope;
// Module scoped macros is included // Module scoped macros is included
let items = scope let items = scope
@ -307,7 +307,7 @@ where
// glob import from same crate => we do an initial // glob import from same crate => we do an initial
// import, and then need to propagate any further // import, and then need to propagate any further
// additions // additions
let scope = &self.def_map[m.module_id].scope; let scope = &self.def_map[m.id.module_id].scope;
// Module scoped macros is included // Module scoped macros is included
let items = scope let items = scope
@ -319,7 +319,7 @@ where
self.update(module_id, Some(import_id), &items); self.update(module_id, Some(import_id), &items);
// record the glob import in case we add further items // record the glob import in case we add further items
self.glob_imports self.glob_imports
.entry(m.module_id) .entry(m.id.module_id)
.or_default() .or_default()
.push((module_id, import_id)); .push((module_id, import_id));
} }
@ -523,9 +523,10 @@ where
// Prelude module is always considered to be `#[macro_use]`. // Prelude module is always considered to be `#[macro_use]`.
if let Some(prelude_module) = self.def_collector.def_map.prelude { if let Some(prelude_module) = self.def_collector.def_map.prelude {
if prelude_module.krate != self.def_collector.def_map.krate { if prelude_module.krate() != self.def_collector.def_map.krate {
tested_by!(prelude_is_macro_use); tested_by!(prelude_is_macro_use);
self.def_collector.import_all_macros_exported(self.module_id, prelude_module.krate); self.def_collector
.import_all_macros_exported(self.module_id, prelude_module.krate());
} }
} }
@ -631,9 +632,7 @@ where
modules[res].scope.legacy_macros = modules[self.module_id].scope.legacy_macros.clone(); modules[res].scope.legacy_macros = modules[self.module_id].scope.legacy_macros.clone();
modules[self.module_id].children.insert(name.clone(), res); modules[self.module_id].children.insert(name.clone(), res);
let resolution = Resolution { let resolution = Resolution {
def: PerNs::types( def: PerNs::types(Module::new(self.def_collector.def_map.krate, res).into()),
Module { krate: self.def_collector.def_map.krate, module_id: res }.into(),
),
import: None, import: None,
}; };
self.def_collector.update(self.module_id, None, &[(name, resolution)]); self.def_collector.update(self.module_id, None, &[(name, resolution)]);
@ -641,7 +640,7 @@ where
} }
fn define_def(&mut self, def: &raw::DefData) { fn define_def(&mut self, def: &raw::DefData) {
let module = Module { krate: self.def_collector.def_map.krate, module_id: self.module_id }; let module = Module::new(self.def_collector.def_map.krate, self.module_id);
let ctx = LocationCtx::new(self.def_collector.db, module, self.file_id); let ctx = LocationCtx::new(self.def_collector.db, module, self.file_id);
macro_rules! def { macro_rules! def {

View file

@ -1,6 +1,7 @@
//! Name resolution. //! Name resolution.
use std::sync::Arc; use std::sync::Arc;
use hir_def::CrateModuleId;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use crate::{ use crate::{
@ -13,7 +14,7 @@ use crate::{
generics::GenericParams, generics::GenericParams,
impl_block::ImplBlock, impl_block::ImplBlock,
name::{Name, SELF_PARAM, SELF_TYPE}, name::{Name, SELF_PARAM, SELF_TYPE},
nameres::{CrateDefMap, CrateModuleId, PerNs}, nameres::{CrateDefMap, PerNs},
path::{Path, PathKind}, path::{Path, PathKind},
Adt, BuiltinType, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct, Adt, BuiltinType, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct,
Trait, TypeAlias, Trait, TypeAlias,
@ -330,8 +331,8 @@ impl Resolver {
for scope in &self.scopes { for scope in &self.scopes {
if let Scope::ModuleScope(m) = scope { if let Scope::ModuleScope(m) = scope {
if let Some(prelude) = m.crate_def_map.prelude() { if let Some(prelude) = m.crate_def_map.prelude() {
let prelude_def_map = db.crate_def_map(prelude.krate); let prelude_def_map = db.crate_def_map(prelude.krate());
traits.extend(prelude_def_map[prelude.module_id].scope.traits()); traits.extend(prelude_def_map[prelude.id.module_id].scope.traits());
} }
traits.extend(m.crate_def_map[m.module_id].scope.traits()); traits.extend(m.crate_def_map[m.module_id].scope.traits());
} }
@ -444,10 +445,12 @@ impl Scope {
f(name.clone(), ScopeDef::ModuleDef(*def)); f(name.clone(), ScopeDef::ModuleDef(*def));
}); });
if let Some(prelude) = m.crate_def_map.prelude() { if let Some(prelude) = m.crate_def_map.prelude() {
let prelude_def_map = db.crate_def_map(prelude.krate); let prelude_def_map = db.crate_def_map(prelude.krate());
prelude_def_map[prelude.module_id].scope.entries().for_each(|(name, res)| { prelude_def_map[prelude.id.module_id].scope.entries().for_each(
|(name, res)| {
f(name.clone(), res.def.into()); f(name.clone(), res.def.into());
}); },
);
} }
} }
Scope::GenericParams(gp) => { Scope::GenericParams(gp) => {

View file

@ -5,13 +5,13 @@
use std::sync::Arc; use std::sync::Arc;
use arrayvec::ArrayVec; use arrayvec::ArrayVec;
use hir_def::CrateModuleId;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use super::{autoderef, lower, Canonical, InEnvironment, TraitEnvironment, TraitRef}; use super::{autoderef, lower, Canonical, InEnvironment, TraitEnvironment, TraitRef};
use crate::{ use crate::{
db::HirDatabase, db::HirDatabase,
impl_block::{ImplBlock, ImplId}, impl_block::{ImplBlock, ImplId},
nameres::CrateModuleId,
resolve::Resolver, resolve::Resolver,
ty::primitive::{FloatBitness, UncertainFloatTy, UncertainIntTy}, ty::primitive::{FloatBitness, UncertainFloatTy, UncertainIntTy},
ty::{Ty, TypeCtor}, ty::{Ty, TypeCtor},
@ -50,7 +50,7 @@ impl CrateImplBlocks {
let fingerprint = TyFingerprint::for_impl(ty); let fingerprint = TyFingerprint::for_impl(ty);
fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flat_map(|i| i.iter()).map( fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flat_map(|i| i.iter()).map(
move |(module_id, impl_id)| { move |(module_id, impl_id)| {
let module = Module { krate: self.krate, module_id: *module_id }; let module = Module::new(self.krate, *module_id);
ImplBlock::from_id(module, *impl_id) ImplBlock::from_id(module, *impl_id)
}, },
) )
@ -62,7 +62,7 @@ impl CrateImplBlocks {
) -> impl Iterator<Item = ImplBlock> + 'a { ) -> impl Iterator<Item = ImplBlock> + 'a {
self.impls_by_trait.get(&tr).into_iter().flat_map(|i| i.iter()).map( self.impls_by_trait.get(&tr).into_iter().flat_map(|i| i.iter()).map(
move |(module_id, impl_id)| { move |(module_id, impl_id)| {
let module = Module { krate: self.krate, module_id: *module_id }; let module = Module::new(self.krate, *module_id);
ImplBlock::from_id(module, *impl_id) ImplBlock::from_id(module, *impl_id)
}, },
) )
@ -71,7 +71,7 @@ impl CrateImplBlocks {
pub fn all_impls<'a>(&'a self) -> impl Iterator<Item = ImplBlock> + 'a { pub fn all_impls<'a>(&'a self) -> impl Iterator<Item = ImplBlock> + 'a {
self.impls.values().chain(self.impls_by_trait.values()).flat_map(|i| i.iter()).map( self.impls.values().chain(self.impls_by_trait.values()).flat_map(|i| i.iter()).map(
move |(module_id, impl_id)| { move |(module_id, impl_id)| {
let module = Module { krate: self.krate, module_id: *module_id }; let module = Module::new(self.krate, *module_id);
ImplBlock::from_id(module, *impl_id) ImplBlock::from_id(module, *impl_id)
}, },
) )
@ -90,14 +90,14 @@ impl CrateImplBlocks {
self.impls_by_trait self.impls_by_trait
.entry(tr.trait_) .entry(tr.trait_)
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
.push((module.module_id, impl_id)); .push((module.id.module_id, impl_id));
} }
} else { } else {
if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) {
self.impls self.impls
.entry(target_ty_fp) .entry(target_ty_fp)
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
.push((module.module_id, impl_id)); .push((module.id.module_id, impl_id));
} }
} }
} }

View file

@ -537,7 +537,7 @@ pub(crate) fn trait_datum_query(
let trait_ref = trait_.trait_ref(db).subst(&bound_vars).to_chalk(db); let trait_ref = trait_.trait_ref(db).subst(&bound_vars).to_chalk(db);
let flags = chalk_rust_ir::TraitFlags { let flags = chalk_rust_ir::TraitFlags {
auto: trait_.is_auto(db), auto: trait_.is_auto(db),
upstream: trait_.module(db).krate(db) != Some(krate), upstream: trait_.module(db).krate() != krate,
non_enumerable: true, non_enumerable: true,
// FIXME set these flags correctly // FIXME set these flags correctly
marker: false, marker: false,
@ -625,7 +625,7 @@ fn impl_block_datum(
.target_trait_ref(db) .target_trait_ref(db)
.expect("FIXME handle unresolved impl block trait ref") .expect("FIXME handle unresolved impl block trait ref")
.subst(&bound_vars); .subst(&bound_vars);
let impl_type = if impl_block.module().krate(db) == Some(krate) { let impl_type = if impl_block.module().krate() == krate {
chalk_rust_ir::ImplType::Local chalk_rust_ir::ImplType::Local
} else { } else {
chalk_rust_ir::ImplType::External chalk_rust_ir::ImplType::External

View file

@ -0,0 +1,13 @@
[package]
edition = "2018"
name = "ra_hir_def"
version = "0.1.0"
authors = ["rust-analyzer developers"]
[dependencies]
log = "0.4.5"
ra_arena = { path = "../ra_arena" }
ra_db = { path = "../ra_db" }
ra_syntax = { path = "../ra_syntax" }
ra_prof = { path = "../ra_prof" }

View file

@ -0,0 +1,14 @@
use ra_arena::{impl_arena_id, RawId};
use ra_db::CrateId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ModuleId {
pub krate: CrateId,
pub module_id: CrateModuleId,
}
/// 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);