diff --git a/crates/ra_analysis/src/completion/complete_scope.rs b/crates/ra_analysis/src/completion/complete_scope.rs index 21d77aa9780..ee9052d3d5d 100644 --- a/crates/ra_analysis/src/completion/complete_scope.rs +++ b/crates/ra_analysis/src/completion/complete_scope.rs @@ -20,14 +20,17 @@ pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) -> } let module_scope = module.scope(ctx.db)?; + let (file_id, _) = module.defenition_source(ctx.db)?; module_scope .entries() .filter(|(_name, res)| { // Don't expose this item + // FIXME: this penetrates through all kinds of abstractions, + // we need to figura out the way to do it less ugly. match res.import { None => true, Some(import) => { - let range = import.range(ctx.db, module.file_id()); + let range = import.range(ctx.db, file_id); !range.is_subrange(&ctx.leaf.range()) } } diff --git a/crates/ra_analysis/src/goto_defenition.rs b/crates/ra_analysis/src/goto_defenition.rs index 68b6ac3ba49..aa0616e3b3b 100644 --- a/crates/ra_analysis/src/goto_defenition.rs +++ b/crates/ra_analysis/src/goto_defenition.rs @@ -60,8 +60,8 @@ fn name_defenition( if let Some(child_module) = hir::source_binder::module_from_declaration(db, file_id, module)? { - let file_id = child_module.file_id(); - let name = match child_module.name() { + let (file_id, _) = child_module.defenition_source(db)?; + let name = match child_module.name(db)? { Some(name) => name.to_string().into(), None => "".into(), }; diff --git a/crates/ra_analysis/src/imp.rs b/crates/ra_analysis/src/imp.rs index 5988fb7794e..07a96629052 100644 --- a/crates/ra_analysis/src/imp.rs +++ b/crates/ra_analysis/src/imp.rs @@ -105,39 +105,35 @@ pub(crate) fn parent_module( &self, position: FilePosition, ) -> Cancelable> { - let descr = match source_binder::module_from_position(self, position)? { + let module = match source_binder::module_from_position(self, position)? { None => return Ok(Vec::new()), Some(it) => it, }; - let (file_id, decl) = match descr.parent_link_source(self) { + let (file_id, ast_module) = match module.declaration_source(self)? { None => return Ok(Vec::new()), Some(it) => it, }; - let decl = decl.borrowed(); - let decl_name = decl.name().unwrap(); + let ast_module = ast_module.borrowed(); + let name = ast_module.name().unwrap(); Ok(vec![NavigationTarget { file_id, - name: decl_name.text(), - range: decl_name.syntax().range(), + name: name.text(), + range: name.syntax().range(), kind: MODULE, ptr: None, }]) } /// Returns `Vec` for the same reason as `parent_module` pub(crate) fn crate_for(&self, file_id: FileId) -> Cancelable> { - let descr = match source_binder::module_from_file_id(self, file_id)? { - None => return Ok(Vec::new()), + let module = match source_binder::module_from_file_id(self, file_id)? { Some(it) => it, + None => return Ok(Vec::new()), }; - let root = descr.crate_root(); - let file_id = root.file_id(); - - let crate_graph = self.crate_graph(); - let crate_id = crate_graph.crate_id_for_crate_root(file_id); - Ok(crate_id.into_iter().collect()) - } - pub(crate) fn crate_root(&self, crate_id: CrateId) -> FileId { - self.crate_graph().crate_root(crate_id) + let krate = match module.krate(self)? { + Some(it) => it, + None => return Ok(Vec::new()), + }; + Ok(vec![krate.crate_id()]) } pub(crate) fn find_all_refs( &self, @@ -209,7 +205,7 @@ pub(crate) fn diagnostics(&self, file_id: FileId) -> Cancelable> }) .collect::>(); if let Some(m) = source_binder::module_from_file_id(self, file_id)? { - for (name_node, problem) in m.problems(self) { + for (name_node, problem) in m.problems(self)? { let source_root = self.file_source_root(file_id); let diag = match problem { Problem::UnresolvedModule { candidate } => { diff --git a/crates/ra_analysis/src/lib.rs b/crates/ra_analysis/src/lib.rs index 390c31c3fa0..77f77e9a8c9 100644 --- a/crates/ra_analysis/src/lib.rs +++ b/crates/ra_analysis/src/lib.rs @@ -397,7 +397,7 @@ pub fn crate_for(&self, file_id: FileId) -> Cancelable> { } /// Returns the root file of the given crate. pub fn crate_root(&self, crate_id: CrateId) -> Cancelable { - Ok(self.db.crate_root(crate_id)) + Ok(self.db.crate_graph().crate_root(crate_id)) } /// Returns the set of possible targets to run for the current file. pub fn runnables(&self, file_id: FileId) -> Cancelable> { diff --git a/crates/ra_analysis/src/runnables.rs b/crates/ra_analysis/src/runnables.rs index 4742676059c..216209098d3 100644 --- a/crates/ra_analysis/src/runnables.rs +++ b/crates/ra_analysis/src/runnables.rs @@ -72,12 +72,15 @@ fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Opti let range = module.syntax().range(); let module = hir::source_binder::module_from_child_node(db, file_id, module.syntax()).ok()??; + + // FIXME: thread cancellation instead of `.ok`ing let path = module - .path_to_root() + .path_to_root(db) + .ok()? .into_iter() .rev() - .into_iter() - .filter_map(|it| it.name().map(Clone::clone)) + .filter_map(|it| it.name(db).ok()) + .filter_map(|it| it) .join("::"); Some(Runnable { range, diff --git a/crates/ra_analysis/tests/test/main.rs b/crates/ra_analysis/tests/test/main.rs index 26da7c10c96..85911de921b 100644 --- a/crates/ra_analysis/tests/test/main.rs +++ b/crates/ra_analysis/tests/test/main.rs @@ -31,6 +31,7 @@ fn test_unresolved_module_diagnostic() { ); } +// FIXME: move this test to hir #[test] fn test_unresolved_module_diagnostic_no_diag_for_inline_mode() { let (analysis, file_id) = single_file("mod foo {}"); diff --git a/crates/ra_hir/src/code_model_api.rs b/crates/ra_hir/src/code_model_api.rs new file mode 100644 index 00000000000..09b532f7464 --- /dev/null +++ b/crates/ra_hir/src/code_model_api.rs @@ -0,0 +1,110 @@ +use relative_path::RelativePathBuf; +use ra_db::{CrateId, Cancelable, FileId}; +use ra_syntax::{ast, SyntaxNode}; + +use crate::{Name, db::HirDatabase, DefId, Path, PerNs, nameres::ModuleScope}; + +/// hir::Crate describes a single crate. It's the main inteface with which +/// crate's dependencies interact. Mostly, it should be just a proxy for the +/// root module. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Crate { + pub(crate) crate_id: CrateId, +} + +#[derive(Debug)] +pub struct CrateDependency { + pub krate: Crate, + pub name: Name, +} + +impl Crate { + pub fn crate_id(&self) -> CrateId { + self.crate_id + } + pub fn dependencies(&self, db: &impl HirDatabase) -> Cancelable> { + Ok(self.dependencies_impl(db)) + } + pub fn root_module(&self, db: &impl HirDatabase) -> Cancelable> { + self.root_module_impl(db) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Module { + pub(crate) def_id: DefId, +} + +pub enum ModuleSource { + SourceFile(ast::SourceFileNode), + Module(ast::ModuleNode), +} + +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +pub enum Problem { + UnresolvedModule { + candidate: RelativePathBuf, + }, + NotDirOwner { + move_to: RelativePathBuf, + candidate: RelativePathBuf, + }, +} + +impl Module { + /// Name of this module. + pub fn name(&self, db: &impl HirDatabase) -> Cancelable> { + self.name_impl(db) + } + + /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. + pub fn defenition_source(&self, db: &impl HirDatabase) -> Cancelable<(FileId, ModuleSource)> { + self.defenition_source_impl(db) + } + /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`. + /// `None` for the crate root. + pub fn declaration_source( + &self, + db: &impl HirDatabase, + ) -> Cancelable> { + self.declaration_source_impl(db) + } + + /// Returns the crate this module is part of. + pub fn krate(&self, db: &impl HirDatabase) -> Cancelable> { + self.krate_impl(db) + } + /// Topmost parent of this module. Every module has a `crate_root`, but some + /// might miss `krate`. This can happen if a module's file is not included + /// into any module tree of any target from Cargo.toml. + pub fn crate_root(&self, db: &impl HirDatabase) -> Cancelable { + self.crate_root_impl(db) + } + /// Finds a child module with the specified name. + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + } + /// Finds a parent module. + pub fn parent(&self, db: &impl HirDatabase) -> Cancelable> { + self.parent_impl(db) + } + pub fn path_to_root(&self, db: &impl HirDatabase) -> Cancelable> { + let mut res = vec![self.clone()]; + let mut curr = self.clone(); + while let Some(next) = curr.parent(db)? { + res.push(next.clone()); + curr = next + } + Ok(res) + } + /// Returns a `ModuleScope`: a set of items, visible in this module. + pub fn scope(&self, db: &impl HirDatabase) -> Cancelable { + self.scope_impl(db) + } + pub fn resolve_path(&self, db: &impl HirDatabase, path: &Path) -> Cancelable> { + self.resolve_path_impl(db, path) + } + pub fn problems(&self, db: &impl HirDatabase) -> Cancelable> { + self.problems_impl(db) + } +} diff --git a/crates/ra_hir/src/code_model_impl.rs b/crates/ra_hir/src/code_model_impl.rs new file mode 100644 index 00000000000..157b0c61688 --- /dev/null +++ b/crates/ra_hir/src/code_model_impl.rs @@ -0,0 +1,2 @@ +mod krate; // `crate` is invalid ident :( +mod module; diff --git a/crates/ra_hir/src/krate.rs b/crates/ra_hir/src/code_model_impl/krate.rs similarity index 58% rename from crates/ra_hir/src/krate.rs rename to crates/ra_hir/src/code_model_impl/krate.rs index 5194e280b75..591a81597da 100644 --- a/crates/ra_hir/src/krate.rs +++ b/crates/ra_hir/src/code_model_impl/krate.rs @@ -1,26 +1,15 @@ -pub use ra_db::{CrateId, Cancelable}; +use ra_db::{CrateId, Cancelable}; -use crate::{HirDatabase, Module, Name, AsName, HirFileId}; - -/// hir::Crate describes a single crate. It's the main inteface with which -/// crate's dependencies interact. Mostly, it should be just a proxy for the -/// root module. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct Crate { - crate_id: CrateId, -} - -#[derive(Debug)] -pub struct CrateDependency { - pub krate: Crate, - pub name: Name, -} +use crate::{ + HirFileId, Crate, CrateDependency, AsName, DefLoc, DefKind, Module, + db::HirDatabase, +}; impl Crate { pub(crate) fn new(crate_id: CrateId) -> Crate { Crate { crate_id } } - pub fn dependencies(&self, db: &impl HirDatabase) -> Vec { + pub(crate) fn dependencies_impl(&self, db: &impl HirDatabase) -> Vec { let crate_graph = db.crate_graph(); crate_graph .dependencies(self.crate_id) @@ -31,7 +20,7 @@ pub fn dependencies(&self, db: &impl HirDatabase) -> Vec { }) .collect() } - pub fn root_module(&self, db: &impl HirDatabase) -> Cancelable> { + pub(crate) fn root_module_impl(&self, db: &impl HirDatabase) -> Cancelable> { let crate_graph = db.crate_graph(); let file_id = crate_graph.crate_root(self.crate_id); let source_root_id = db.file_source_root(file_id); @@ -42,7 +31,15 @@ pub fn root_module(&self, db: &impl HirDatabase) -> Cancelable> { .modules_with_sources() .find(|(_, src)| src.file_id() == file_id)); - let module = Module::new(db, source_root_id, module_id)?; + let def_loc = DefLoc { + kind: DefKind::Module, + source_root_id, + module_id, + source_item_id: module_id.source(&module_tree).0, + }; + let def_id = def_loc.id(db); + + let module = Module::new(def_id); Ok(Some(module)) } } diff --git a/crates/ra_hir/src/code_model_impl/module.rs b/crates/ra_hir/src/code_model_impl/module.rs new file mode 100644 index 00000000000..02078f188dc --- /dev/null +++ b/crates/ra_hir/src/code_model_impl/module.rs @@ -0,0 +1,154 @@ +use ra_db::{Cancelable, SourceRootId, FileId}; +use ra_syntax::{ast, SyntaxNode, AstNode}; + +use crate::{ + Module, ModuleSource, Problem, + Crate, DefId, DefLoc, DefKind, Name, Path, PathKind, PerNs, Def, ModuleId, + nameres::ModuleScope, + db::HirDatabase, +}; + +impl Module { + pub(crate) fn new(def_id: DefId) -> Self { + crate::code_model_api::Module { def_id } + } + pub(crate) fn from_module_id( + db: &impl HirDatabase, + source_root_id: SourceRootId, + module_id: ModuleId, + ) -> Cancelable { + let module_tree = db.module_tree(source_root_id)?; + let def_loc = DefLoc { + kind: DefKind::Module, + source_root_id, + module_id, + source_item_id: module_id.source(&module_tree).0, + }; + let def_id = def_loc.id(db); + let module = Module::new(def_id); + Ok(module) + } + + pub(crate) fn name_impl(&self, db: &impl HirDatabase) -> Cancelable> { + let loc = self.def_id.loc(db); + let module_tree = db.module_tree(loc.source_root_id)?; + let link = ctry!(loc.module_id.parent_link(&module_tree)); + Ok(Some(link.name(&module_tree).clone())) + } + + pub fn defenition_source_impl( + &self, + db: &impl HirDatabase, + ) -> Cancelable<(FileId, ModuleSource)> { + let loc = self.def_id.loc(db); + let file_id = loc.source_item_id.file_id.as_original_file(); + let syntax_node = db.file_item(loc.source_item_id); + let syntax_node = syntax_node.borrowed(); + let module_source = if let Some(source_file) = ast::SourceFile::cast(syntax_node) { + ModuleSource::SourceFile(source_file.owned()) + } else { + let module = ast::Module::cast(syntax_node).unwrap(); + ModuleSource::Module(module.owned()) + }; + Ok((file_id, module_source)) + } + + pub fn declaration_source_impl( + &self, + db: &impl HirDatabase, + ) -> Cancelable> { + let loc = self.def_id.loc(db); + let module_tree = db.module_tree(loc.source_root_id)?; + let link = ctry!(loc.module_id.parent_link(&module_tree)); + let file_id = link + .owner(&module_tree) + .source(&module_tree) + .file_id() + .as_original_file(); + let src = link.bind_source(&module_tree, db); + Ok(Some((file_id, src))) + } + + pub(crate) fn krate_impl(&self, db: &impl HirDatabase) -> Cancelable> { + let root = self.crate_root(db)?; + let loc = root.def_id.loc(db); + let file_id = loc.source_item_id.file_id.as_original_file(); + + let crate_graph = db.crate_graph(); + let crate_id = ctry!(crate_graph.crate_id_for_crate_root(file_id)); + Ok(Some(Crate::new(crate_id))) + } + + pub(crate) fn crate_root_impl(&self, db: &impl HirDatabase) -> Cancelable { + let loc = self.def_id.loc(db); + let module_tree = db.module_tree(loc.source_root_id)?; + let module_id = loc.module_id.crate_root(&module_tree); + Module::from_module_id(db, loc.source_root_id, module_id) + } + /// Finds a child module with the specified name. + pub fn child_impl(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + let loc = self.def_id.loc(db); + let module_tree = db.module_tree(loc.source_root_id)?; + let child_id = ctry!(loc.module_id.child(&module_tree, name)); + Module::from_module_id(db, loc.source_root_id, child_id).map(Some) + } + pub fn parent_impl(&self, db: &impl HirDatabase) -> Cancelable> { + let loc = self.def_id.loc(db); + let module_tree = db.module_tree(loc.source_root_id)?; + let parent_id = ctry!(loc.module_id.parent(&module_tree)); + Module::from_module_id(db, loc.source_root_id, parent_id).map(Some) + } + /// Returns a `ModuleScope`: a set of items, visible in this module. + pub fn scope_impl(&self, db: &impl HirDatabase) -> Cancelable { + let loc = self.def_id.loc(db); + let item_map = db.item_map(loc.source_root_id)?; + let res = item_map.per_module[&loc.module_id].clone(); + Ok(res) + } + pub fn resolve_path_impl( + &self, + db: &impl HirDatabase, + path: &Path, + ) -> Cancelable> { + let mut curr_per_ns = PerNs::types( + match path.kind { + PathKind::Crate => self.crate_root(db)?, + PathKind::Self_ | PathKind::Plain => self.clone(), + PathKind::Super => { + if let Some(p) = self.parent(db)? { + p + } else { + return Ok(PerNs::none()); + } + } + } + .def_id, + ); + + let segments = &path.segments; + for name in segments.iter() { + let curr = if let Some(r) = curr_per_ns.as_ref().take_types() { + r + } else { + return Ok(PerNs::none()); + }; + let module = match curr.resolve(db)? { + Def::Module(it) => it, + // TODO here would be the place to handle enum variants... + _ => return Ok(PerNs::none()), + }; + let scope = module.scope(db)?; + curr_per_ns = if let Some(r) = scope.get(&name) { + r.def_id + } else { + return Ok(PerNs::none()); + }; + } + Ok(curr_per_ns) + } + pub fn problems_impl(&self, db: &impl HirDatabase) -> Cancelable> { + let loc = self.def_id.loc(db); + let module_tree = db.module_tree(loc.source_root_id)?; + Ok(loc.module_id.problems(&module_tree, db)) + } +} diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 96a3c60b9e8..e4249de141e 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs @@ -9,8 +9,8 @@ query_definitions, FnSignature, FnScopes, macros::MacroExpansion, - module::{ModuleId, ModuleTree, ModuleSource, - nameres::{ItemMap, InputModuleItems}}, + module_tree::{ModuleId, ModuleTree, ModuleSource}, + nameres::{ItemMap, InputModuleItems}, ty::{InferenceResult, Ty}, adt::{StructData, EnumData}, impl_block::ModuleImplBlocks, @@ -71,9 +71,9 @@ fn file_item(source_item_id: SourceItemId) -> SyntaxNode { use fn query_definitions::file_item; } - fn submodules(source: ModuleSource) -> Cancelable>> { + fn submodules(source: ModuleSource) -> Cancelable>> { type SubmodulesQuery; - use fn query_definitions::submodules; + use fn crate::module_tree::Submodule::submodules_query; } fn input_module_items(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable> { @@ -86,7 +86,7 @@ fn item_map(source_root_id: SourceRootId) -> Cancelable> { } fn module_tree(source_root_id: SourceRootId) -> Cancelable> { type ModuleTreeQuery; - use fn crate::module::imp::module_tree; + use fn crate::module_tree::ModuleTree::module_tree_query; } fn impls_in_module(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable> { diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs index 4d6378e0286..c7391ee0560 100644 --- a/crates/ra_hir/src/ids.rs +++ b/crates/ra_hir/src/ids.rs @@ -2,7 +2,9 @@ use ra_syntax::{SourceFileNode, SyntaxKind, SyntaxNode, SyntaxNodeRef, SourceFile, AstNode, ast}; use ra_arena::{Arena, RawId, impl_arena_id}; -use crate::{HirDatabase, PerNs, ModuleId, Module, Def, Function, Struct, Enum, ImplBlock, Crate}; +use crate::{HirDatabase, PerNs, ModuleId, Def, Function, Struct, Enum, ImplBlock, Crate}; + +use crate::code_model_api::Module; /// hir makes a heavy use of ids: integer (u32) handlers to various things. You /// can think of id as a pointer (but without a lifetime) or a file descriptor @@ -151,7 +153,7 @@ pub fn resolve(self, db: &impl HirDatabase) -> Cancelable { let loc = self.loc(db); let res = match loc.kind { DefKind::Module => { - let module = Module::new(db, loc.source_root_id, loc.module_id)?; + let module = Module::from_module_id(db, loc.source_root_id, loc.module_id)?; Def::Module(module) } DefKind::Function => { @@ -175,12 +177,12 @@ pub fn resolve(self, db: &impl HirDatabase) -> Cancelable { /// For a module, returns that module; for any other def, returns the containing module. pub fn module(self, db: &impl HirDatabase) -> Cancelable { let loc = self.loc(db); - Module::new(db, loc.source_root_id, loc.module_id) + Module::from_module_id(db, loc.source_root_id, loc.module_id) } /// Returns the containing crate. pub fn krate(&self, db: &impl HirDatabase) -> Cancelable> { - Ok(self.module(db)?.krate(db)) + Ok(self.module(db)?.krate(db)?) } /// Returns the containing impl block, if this is an impl item. diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs index 01afa84c496..7ce8d17e664 100644 --- a/crates/ra_hir/src/impl_block.rs +++ b/crates/ra_hir/src/impl_block.rs @@ -7,12 +7,14 @@ use crate::{ DefId, DefLoc, DefKind, SourceItemId, SourceFileItems, - Module, Function, + Function, db::HirDatabase, type_ref::TypeRef, - module::{ModuleSourceNode, ModuleId}, + module_tree::ModuleId, }; +use crate::code_model_api::{Module, ModuleSource}; + #[derive(Debug, Clone, PartialEq, Eq)] pub struct ImplBlock { module_impl_blocks: Arc, @@ -64,7 +66,7 @@ pub(crate) fn from_ast( ) -> Self { let target_trait = node.target_type().map(TypeRef::from_ast); let target_type = TypeRef::from_ast_opt(node.target_type()); - let file_id = module.source().file_id(); + let module_loc = module.def_id.loc(db); let items = if let Some(item_list) = node.item_list() { item_list .impl_items() @@ -75,14 +77,14 @@ pub(crate) fn from_ast( ast::ImplItem::TypeDef(..) => DefKind::Item, }; let item_id = file_items.id_of_unchecked(item_node.syntax()); + let source_item_id = SourceItemId { + file_id: module_loc.source_item_id.file_id, + item_id: Some(item_id), + }; let def_loc = DefLoc { kind, - source_root_id: module.source_root_id, - module_id: module.module_id, - source_item_id: SourceItemId { - file_id, - item_id: Some(item_id), - }, + source_item_id, + ..module_loc }; let def_id = def_loc.id(db); match item_node { @@ -148,13 +150,13 @@ fn new() -> Self { } fn collect(&mut self, db: &impl HirDatabase, module: Module) -> Cancelable<()> { - let module_source_node = module.source().resolve(db); - let node = match &module_source_node { - ModuleSourceNode::SourceFile(node) => node.borrowed().syntax(), - ModuleSourceNode::Module(node) => node.borrowed().syntax(), + let (file_id, module_source) = module.defenition_source(db)?; + let node = match &module_source { + ModuleSource::SourceFile(node) => node.borrowed().syntax(), + ModuleSource::Module(node) => node.borrowed().syntax(), }; - let source_file_items = db.file_items(module.source().file_id()); + let source_file_items = db.file_items(file_id.into()); for impl_block_ast in node.children().filter_map(ast::ImplBlock::cast) { let impl_block = ImplData::from_ast(db, &source_file_items, &module, impl_block_ast); @@ -174,7 +176,7 @@ pub(crate) fn impls_in_module( module_id: ModuleId, ) -> Cancelable> { let mut result = ModuleImplBlocks::new(); - let module = Module::new(db, source_root_id, module_id)?; + let module = Module::from_module_id(db, source_root_id, module_id)?; result.collect(db, module)?; Ok(Arc::new(result)) } diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index d600b91df31..9f133f17491 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs @@ -24,9 +24,8 @@ macro_rules! ctry { mod ids; mod macros; mod name; -// can't use `crate` or `r#crate` here :( -mod krate; -mod module; +mod module_tree; +mod nameres; mod function; mod adt; mod type_ref; @@ -34,6 +33,9 @@ macro_rules! ctry { mod impl_block; mod expr; +mod code_model_api; +mod code_model_impl; + use crate::{ db::HirDatabase, name::{AsName, KnownName}, @@ -43,10 +45,10 @@ macro_rules! ctry { pub use self::{ path::{Path, PathKind}, name::Name, - krate::Crate, ids::{HirFileId, DefId, DefLoc, MacroCallId, MacroCallLoc}, macros::{MacroDef, MacroInput, MacroExpansion}, - module::{Module, ModuleId, Problem, nameres::{ItemMap, PerNs, Namespace}, ModuleScope, Resolution}, + module_tree::ModuleId, + nameres::{ItemMap, PerNs, Namespace, Resolution}, function::{Function, FnSignature, FnScopes, ScopesWithSyntaxMapping}, adt::{Struct, Enum}, ty::Ty, @@ -55,6 +57,11 @@ macro_rules! ctry { pub use self::function::FnSignatureInfo; +pub use self::code_model_api::{ + Crate, CrateDependency, + Module, ModuleSource, Problem, +}; + pub enum Def { Module(Module), Function(Function), diff --git a/crates/ra_hir/src/module.rs b/crates/ra_hir/src/module.rs deleted file mode 100644 index b9821115ce8..00000000000 --- a/crates/ra_hir/src/module.rs +++ /dev/null @@ -1,376 +0,0 @@ -pub(super) mod imp; -pub(super) mod nameres; - -use std::sync::Arc; -use log; - -use ra_syntax::{ - algo::generate, - ast::{self, AstNode, NameOwner}, - SyntaxNode, -}; -use ra_arena::{Arena, RawId, impl_arena_id}; -use ra_db::{SourceRootId, FileId, Cancelable}; -use relative_path::RelativePathBuf; - -use crate::{ - Def, DefKind, DefLoc, DefId, - Name, Path, PathKind, HirDatabase, SourceItemId, SourceFileItemId, Crate, - HirFileId, -}; - -pub use self::nameres::{ModuleScope, Resolution, Namespace, PerNs}; - -/// `Module` is API entry point to get all the information -/// about a particular module. -#[derive(Debug, Clone)] -pub struct Module { - tree: Arc, - pub(crate) source_root_id: SourceRootId, - pub(crate) module_id: ModuleId, -} - -impl Module { - pub(super) fn new( - db: &impl HirDatabase, - source_root_id: SourceRootId, - module_id: ModuleId, - ) -> Cancelable { - let module_tree = db.module_tree(source_root_id)?; - let res = Module { - tree: module_tree, - source_root_id, - module_id, - }; - Ok(res) - } - - /// Returns `mod foo;` or `mod foo {}` node whihc declared this module. - /// Returns `None` for the root module - pub fn parent_link_source(&self, db: &impl HirDatabase) -> Option<(FileId, ast::ModuleNode)> { - let link = self.module_id.parent_link(&self.tree)?; - let file_id = link - .owner(&self.tree) - .source(&self.tree) - .file_id() - .as_original_file(); - let src = link.bind_source(&self.tree, db); - Some((file_id, src)) - } - - pub fn file_id(&self) -> FileId { - self.source().file_id().as_original_file() - } - - /// Parent module. Returns `None` if this is a root module. - pub fn parent(&self) -> Option { - let parent_id = self.module_id.parent(&self.tree)?; - Some(Module { - module_id: parent_id, - ..self.clone() - }) - } - - /// Returns an iterator of all children of this module. - pub fn children<'a>(&'a self) -> impl Iterator + 'a { - self.module_id - .children(&self.tree) - .map(move |(name, module_id)| { - ( - name, - Module { - module_id, - ..self.clone() - }, - ) - }) - } - - /// Returns the crate this module is part of. - pub fn krate(&self, db: &impl HirDatabase) -> Option { - let root_id = self.module_id.crate_root(&self.tree); - let file_id = root_id.source(&self.tree).file_id().as_original_file(); - let crate_graph = db.crate_graph(); - let crate_id = crate_graph.crate_id_for_crate_root(file_id)?; - Some(Crate::new(crate_id)) - } - - /// Returns the all modules on the way to the root. - pub fn path_to_root(&self) -> Vec { - generate(Some(self.clone()), move |it| it.parent()).collect::>() - } - - /// The root of the tree this module is part of - pub fn crate_root(&self) -> Module { - let root_id = self.module_id.crate_root(&self.tree); - Module { - module_id: root_id, - ..self.clone() - } - } - - /// `name` is `None` for the crate's root module - pub fn name(&self) -> Option<&Name> { - let link = self.module_id.parent_link(&self.tree)?; - Some(link.name(&self.tree)) - } - - pub fn def_id(&self, db: &impl HirDatabase) -> DefId { - let def_loc = DefLoc { - kind: DefKind::Module, - source_root_id: self.source_root_id, - module_id: self.module_id, - source_item_id: self.module_id.source(&self.tree).0, - }; - def_loc.id(db) - } - - /// Finds a child module with the specified name. - pub fn child(&self, name: &Name) -> Option { - let child_id = self.module_id.child(&self.tree, name)?; - Some(Module { - module_id: child_id, - ..self.clone() - }) - } - - /// Returns a `ModuleScope`: a set of items, visible in this module. - pub fn scope(&self, db: &impl HirDatabase) -> Cancelable { - let item_map = db.item_map(self.source_root_id)?; - let res = item_map.per_module[&self.module_id].clone(); - Ok(res) - } - - pub fn resolve_path(&self, db: &impl HirDatabase, path: &Path) -> Cancelable> { - let mut curr_per_ns = PerNs::types( - match path.kind { - PathKind::Crate => self.crate_root(), - PathKind::Self_ | PathKind::Plain => self.clone(), - PathKind::Super => { - if let Some(p) = self.parent() { - p - } else { - return Ok(PerNs::none()); - } - } - } - .def_id(db), - ); - - let segments = &path.segments; - for name in segments.iter() { - let curr = if let Some(r) = curr_per_ns.as_ref().take(Namespace::Types) { - r - } else { - return Ok(PerNs::none()); - }; - let module = match curr.resolve(db)? { - Def::Module(it) => it, - // TODO here would be the place to handle enum variants... - _ => return Ok(PerNs::none()), - }; - let scope = module.scope(db)?; - curr_per_ns = if let Some(r) = scope.get(&name) { - r.def_id - } else { - return Ok(PerNs::none()); - }; - } - Ok(curr_per_ns) - } - - pub fn problems(&self, db: &impl HirDatabase) -> Vec<(SyntaxNode, Problem)> { - self.module_id.problems(&self.tree, db) - } - - pub(crate) fn source(&self) -> ModuleSource { - self.module_id.source(&self.tree) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ModuleId(RawId); -impl_arena_id!(ModuleId); - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct LinkId(RawId); -impl_arena_id!(LinkId); - -/// Physically, rust source is organized as a set of files, but logically it is -/// organized as a tree of modules. Usually, a single file corresponds to a -/// single module, but it is not nessary the case. -/// -/// Module encapsulate the logic of transitioning from the fuzzy world of files -/// (which can have multiple parents) to the precise world of modules (which -/// always have one parent). -#[derive(Default, Debug, PartialEq, Eq)] -pub struct ModuleTree { - mods: Arena, - links: Arena, -} - -impl ModuleTree { - pub(crate) fn modules<'a>(&'a self) -> impl Iterator + 'a { - self.mods.iter().map(|(id, _)| id) - } - - pub(crate) fn modules_with_sources<'a>( - &'a self, - ) -> impl Iterator + 'a { - self.mods.iter().map(|(id, m)| (id, m.source)) - } -} - -/// `ModuleSource` is the syntax tree element that produced this module: -/// either a file, or an inlinde module. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct ModuleSource(SourceItemId); - -/// An owned syntax node for a module. Unlike `ModuleSource`, -/// this holds onto the AST for the whole file. -pub(crate) enum ModuleSourceNode { - SourceFile(ast::SourceFileNode), - Module(ast::ModuleNode), -} - -#[derive(Clone, Debug, Hash, PartialEq, Eq)] -pub enum Problem { - UnresolvedModule { - candidate: RelativePathBuf, - }, - NotDirOwner { - move_to: RelativePathBuf, - candidate: RelativePathBuf, - }, -} - -impl ModuleId { - pub(crate) fn source(self, tree: &ModuleTree) -> ModuleSource { - tree.mods[self].source - } - fn parent_link(self, tree: &ModuleTree) -> Option { - tree.mods[self].parent - } - fn parent(self, tree: &ModuleTree) -> Option { - let link = self.parent_link(tree)?; - Some(tree.links[link].owner) - } - fn crate_root(self, tree: &ModuleTree) -> ModuleId { - generate(Some(self), move |it| it.parent(tree)) - .last() - .unwrap() - } - fn child(self, tree: &ModuleTree, name: &Name) -> Option { - let link = tree.mods[self] - .children - .iter() - .map(|&it| &tree.links[it]) - .find(|it| it.name == *name)?; - Some(*link.points_to.first()?) - } - fn children<'a>(self, tree: &'a ModuleTree) -> impl Iterator + 'a { - tree.mods[self].children.iter().filter_map(move |&it| { - let link = &tree.links[it]; - let module = *link.points_to.first()?; - Some((link.name.clone(), module)) - }) - } - fn problems(self, tree: &ModuleTree, db: &impl HirDatabase) -> Vec<(SyntaxNode, Problem)> { - tree.mods[self] - .children - .iter() - .filter_map(|&it| { - let p = tree.links[it].problem.clone()?; - let s = it.bind_source(tree, db); - let s = s.borrowed().name().unwrap().syntax().owned(); - Some((s, p)) - }) - .collect() - } -} - -impl LinkId { - fn owner(self, tree: &ModuleTree) -> ModuleId { - tree.links[self].owner - } - fn name(self, tree: &ModuleTree) -> &Name { - &tree.links[self].name - } - fn bind_source<'a>(self, tree: &ModuleTree, db: &impl HirDatabase) -> ast::ModuleNode { - let owner = self.owner(tree); - match owner.source(tree).resolve(db) { - ModuleSourceNode::SourceFile(root) => { - let ast = imp::modules(root.borrowed()) - .find(|(name, _)| name == &tree.links[self].name) - .unwrap() - .1; - ast.owned() - } - ModuleSourceNode::Module(it) => it, - } - } -} - -#[derive(Debug, PartialEq, Eq, Hash)] -pub struct ModuleData { - source: ModuleSource, - parent: Option, - children: Vec, -} - -impl ModuleSource { - // precondition: item_id **must** point to module - fn new(file_id: HirFileId, item_id: Option) -> ModuleSource { - let source_item_id = SourceItemId { file_id, item_id }; - ModuleSource(source_item_id) - } - - pub(crate) fn new_file(file_id: HirFileId) -> ModuleSource { - ModuleSource::new(file_id, None) - } - - pub(crate) fn new_inline( - db: &impl HirDatabase, - file_id: HirFileId, - m: ast::Module, - ) -> ModuleSource { - assert!(!m.has_semi()); - let file_items = db.file_items(file_id); - let item_id = file_items.id_of(file_id, m.syntax()); - ModuleSource::new(file_id, Some(item_id)) - } - - pub(crate) fn file_id(self) -> HirFileId { - self.0.file_id - } - - pub(crate) fn resolve(self, db: &impl HirDatabase) -> ModuleSourceNode { - let syntax_node = db.file_item(self.0); - let syntax_node = syntax_node.borrowed(); - if let Some(file) = ast::SourceFile::cast(syntax_node) { - return ModuleSourceNode::SourceFile(file.owned()); - } - let module = ast::Module::cast(syntax_node).unwrap(); - ModuleSourceNode::Module(module.owned()) - } -} - -#[derive(Hash, Debug, PartialEq, Eq)] -struct LinkData { - owner: ModuleId, - name: Name, - points_to: Vec, - problem: Option, -} - -impl ModuleTree { - fn push_mod(&mut self, data: ModuleData) -> ModuleId { - self.mods.alloc(data) - } - fn push_link(&mut self, data: LinkData) -> LinkId { - let owner = data.owner; - let id = self.links.alloc(data); - self.mods[owner].children.push(id); - id - } -} diff --git a/crates/ra_hir/src/module/imp.rs b/crates/ra_hir/src/module/imp.rs deleted file mode 100644 index 3849026dbdd..00000000000 --- a/crates/ra_hir/src/module/imp.rs +++ /dev/null @@ -1,190 +0,0 @@ -use std::sync::Arc; - -use ra_syntax::ast::{self, NameOwner}; -use relative_path::RelativePathBuf; -use rustc_hash::{FxHashMap, FxHashSet}; -use arrayvec::ArrayVec; -use ra_db::{SourceRoot, SourceRootId, Cancelable, FileId}; - -use crate::{ - HirDatabase, Name, AsName, -}; - -use super::{ - LinkData, LinkId, ModuleData, ModuleId, ModuleSource, - ModuleTree, Problem, -}; - -#[derive(Clone, Hash, PartialEq, Eq, Debug)] -pub enum Submodule { - Declaration(Name), - Definition(Name, ModuleSource), -} - -impl Submodule { - fn name(&self) -> &Name { - match self { - Submodule::Declaration(name) => name, - Submodule::Definition(name, _) => name, - } - } -} - -pub(crate) fn modules<'a>( - root: impl ast::ModuleItemOwner<'a>, -) -> impl Iterator)> { - root.items() - .filter_map(|item| match item { - ast::ModuleItem::Module(m) => Some(m), - _ => None, - }) - .filter_map(|module| { - let name = module.name()?.as_name(); - Some((name, module)) - }) -} - -pub(crate) fn module_tree( - db: &impl HirDatabase, - source_root: SourceRootId, -) -> Cancelable> { - db.check_canceled()?; - let res = create_module_tree(db, source_root)?; - Ok(Arc::new(res)) -} - -fn create_module_tree<'a>( - db: &impl HirDatabase, - source_root: SourceRootId, -) -> Cancelable { - let mut tree = ModuleTree::default(); - - let mut roots = FxHashMap::default(); - let mut visited = FxHashSet::default(); - - let source_root = db.source_root(source_root); - for &file_id in source_root.files.values() { - let source = ModuleSource::new_file(file_id.into()); - if visited.contains(&source) { - continue; // TODO: use explicit crate_roots here - } - assert!(!roots.contains_key(&file_id)); - let module_id = build_subtree( - db, - &source_root, - &mut tree, - &mut visited, - &mut roots, - None, - source, - )?; - roots.insert(file_id, module_id); - } - Ok(tree) -} - -fn build_subtree( - db: &impl HirDatabase, - source_root: &SourceRoot, - tree: &mut ModuleTree, - visited: &mut FxHashSet, - roots: &mut FxHashMap, - parent: Option, - source: ModuleSource, -) -> Cancelable { - visited.insert(source); - let id = tree.push_mod(ModuleData { - source, - parent, - children: Vec::new(), - }); - for sub in db.submodules(source)?.iter() { - let link = tree.push_link(LinkData { - name: sub.name().clone(), - owner: id, - points_to: Vec::new(), - problem: None, - }); - - let (points_to, problem) = match sub { - Submodule::Declaration(name) => { - let (points_to, problem) = resolve_submodule(db, source, &name); - let points_to = points_to - .into_iter() - .map(|file_id| match roots.remove(&file_id) { - Some(module_id) => { - tree.mods[module_id].parent = Some(link); - Ok(module_id) - } - None => build_subtree( - db, - source_root, - tree, - visited, - roots, - Some(link), - ModuleSource::new_file(file_id.into()), - ), - }) - .collect::>>()?; - (points_to, problem) - } - Submodule::Definition(_name, submodule_source) => { - let points_to = build_subtree( - db, - source_root, - tree, - visited, - roots, - Some(link), - *submodule_source, - )?; - (vec![points_to], None) - } - }; - - tree.links[link].points_to = points_to; - tree.links[link].problem = problem; - } - Ok(id) -} - -fn resolve_submodule( - db: &impl HirDatabase, - source: ModuleSource, - name: &Name, -) -> (Vec, Option) { - // FIXME: handle submodules of inline modules properly - let file_id = source.file_id().original_file(db); - let source_root_id = db.file_source_root(file_id); - let path = db.file_relative_path(file_id); - let root = RelativePathBuf::default(); - let dir_path = path.parent().unwrap_or(&root); - let mod_name = path.file_stem().unwrap_or("unknown"); - let is_dir_owner = mod_name == "mod" || mod_name == "lib" || mod_name == "main"; - - let file_mod = dir_path.join(format!("{}.rs", name)); - let dir_mod = dir_path.join(format!("{}/mod.rs", name)); - let file_dir_mod = dir_path.join(format!("{}/{}.rs", mod_name, name)); - let mut candidates = ArrayVec::<[_; 2]>::new(); - if is_dir_owner { - candidates.push(file_mod.clone()); - candidates.push(dir_mod); - } else { - candidates.push(file_dir_mod.clone()); - }; - let sr = db.source_root(source_root_id); - let points_to = candidates - .into_iter() - .filter_map(|path| sr.files.get(&path)) - .map(|&it| it) - .collect::>(); - let problem = if points_to.is_empty() { - Some(Problem::UnresolvedModule { - candidate: if is_dir_owner { file_mod } else { file_dir_mod }, - }) - } else { - None - }; - (points_to, problem) -} diff --git a/crates/ra_hir/src/module_tree.rs b/crates/ra_hir/src/module_tree.rs new file mode 100644 index 00000000000..b7912ba5edb --- /dev/null +++ b/crates/ra_hir/src/module_tree.rs @@ -0,0 +1,409 @@ +use std::sync::Arc; + +use rustc_hash::{FxHashMap, FxHashSet}; +use arrayvec::ArrayVec; +use relative_path::RelativePathBuf; +use ra_db::{FileId, SourceRootId, Cancelable, SourceRoot}; +use ra_syntax::{ + algo::generate, + ast::{self, AstNode, NameOwner}, + SyntaxNode, +}; +use ra_arena::{Arena, RawId, impl_arena_id}; + +use crate::{Name, AsName, HirDatabase, SourceItemId, SourceFileItemId, HirFileId, Problem}; + +#[derive(Clone, Hash, PartialEq, Eq, Debug)] +pub enum Submodule { + Declaration(Name), + Definition(Name, ModuleSource), +} + +impl Submodule { + pub(crate) fn submodules_query( + db: &impl HirDatabase, + source: ModuleSource, + ) -> Cancelable>> { + db.check_canceled()?; + let file_id = source.file_id(); + let submodules = match source.resolve(db) { + ModuleSourceNode::SourceFile(it) => collect_submodules(db, file_id, it.borrowed()), + ModuleSourceNode::Module(it) => it + .borrowed() + .item_list() + .map(|it| collect_submodules(db, file_id, it)) + .unwrap_or_else(Vec::new), + }; + return Ok(Arc::new(submodules)); + + fn collect_submodules<'a>( + db: &impl HirDatabase, + file_id: HirFileId, + root: impl ast::ModuleItemOwner<'a>, + ) -> Vec { + modules(root) + .map(|(name, m)| { + if m.has_semi() { + Submodule::Declaration(name) + } else { + let src = ModuleSource::new_inline(db, file_id, m); + Submodule::Definition(name, src) + } + }) + .collect() + } + } + + fn name(&self) -> &Name { + match self { + Submodule::Declaration(name) => name, + Submodule::Definition(name, _) => name, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ModuleId(RawId); +impl_arena_id!(ModuleId); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct LinkId(RawId); +impl_arena_id!(LinkId); + +/// Physically, rust source is organized as a set of files, but logically it is +/// organized as a tree of modules. Usually, a single file corresponds to a +/// single module, but it is not nessary the case. +/// +/// Module encapsulate the logic of transitioning from the fuzzy world of files +/// (which can have multiple parents) to the precise world of modules (which +/// always have one parent). +#[derive(Default, Debug, PartialEq, Eq)] +pub struct ModuleTree { + mods: Arena, + links: Arena, +} + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct ModuleData { + source: ModuleSource, + parent: Option, + children: Vec, +} + +#[derive(Hash, Debug, PartialEq, Eq)] +struct LinkData { + owner: ModuleId, + name: Name, + points_to: Vec, + problem: Option, +} + +impl ModuleTree { + pub(crate) fn module_tree_query( + db: &impl HirDatabase, + source_root: SourceRootId, + ) -> Cancelable> { + db.check_canceled()?; + let res = create_module_tree(db, source_root)?; + Ok(Arc::new(res)) + } + + pub(crate) fn modules<'a>(&'a self) -> impl Iterator + 'a { + self.mods.iter().map(|(id, _)| id) + } + + pub(crate) fn modules_with_sources<'a>( + &'a self, + ) -> impl Iterator + 'a { + self.mods.iter().map(|(id, m)| (id, m.source)) + } +} + +/// `ModuleSource` is the syntax tree element that produced this module: +/// either a file, or an inlinde module. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ModuleSource(pub(crate) SourceItemId); + +/// An owned syntax node for a module. Unlike `ModuleSource`, +/// this holds onto the AST for the whole file. +pub(crate) enum ModuleSourceNode { + SourceFile(ast::SourceFileNode), + Module(ast::ModuleNode), +} + +impl ModuleId { + pub(crate) fn source(self, tree: &ModuleTree) -> ModuleSource { + tree.mods[self].source + } + pub(crate) fn parent_link(self, tree: &ModuleTree) -> Option { + tree.mods[self].parent + } + pub(crate) fn parent(self, tree: &ModuleTree) -> Option { + let link = self.parent_link(tree)?; + Some(tree.links[link].owner) + } + pub(crate) fn crate_root(self, tree: &ModuleTree) -> ModuleId { + generate(Some(self), move |it| it.parent(tree)) + .last() + .unwrap() + } + pub(crate) fn child(self, tree: &ModuleTree, name: &Name) -> Option { + let link = tree.mods[self] + .children + .iter() + .map(|&it| &tree.links[it]) + .find(|it| it.name == *name)?; + Some(*link.points_to.first()?) + } + pub(crate) fn children<'a>( + self, + tree: &'a ModuleTree, + ) -> impl Iterator + 'a { + tree.mods[self].children.iter().filter_map(move |&it| { + let link = &tree.links[it]; + let module = *link.points_to.first()?; + Some((link.name.clone(), module)) + }) + } + pub(crate) fn problems( + self, + tree: &ModuleTree, + db: &impl HirDatabase, + ) -> Vec<(SyntaxNode, Problem)> { + tree.mods[self] + .children + .iter() + .filter_map(|&it| { + let p = tree.links[it].problem.clone()?; + let s = it.bind_source(tree, db); + let s = s.borrowed().name().unwrap().syntax().owned(); + Some((s, p)) + }) + .collect() + } +} + +impl LinkId { + pub(crate) fn owner(self, tree: &ModuleTree) -> ModuleId { + tree.links[self].owner + } + pub(crate) fn name(self, tree: &ModuleTree) -> &Name { + &tree.links[self].name + } + pub(crate) fn bind_source<'a>( + self, + tree: &ModuleTree, + db: &impl HirDatabase, + ) -> ast::ModuleNode { + let owner = self.owner(tree); + match owner.source(tree).resolve(db) { + ModuleSourceNode::SourceFile(root) => { + let ast = modules(root.borrowed()) + .find(|(name, _)| name == &tree.links[self].name) + .unwrap() + .1; + ast.owned() + } + ModuleSourceNode::Module(it) => it, + } + } +} + +impl ModuleSource { + // precondition: item_id **must** point to module + fn new(file_id: HirFileId, item_id: Option) -> ModuleSource { + let source_item_id = SourceItemId { file_id, item_id }; + ModuleSource(source_item_id) + } + + pub(crate) fn new_file(file_id: HirFileId) -> ModuleSource { + ModuleSource::new(file_id, None) + } + + pub(crate) fn new_inline( + db: &impl HirDatabase, + file_id: HirFileId, + m: ast::Module, + ) -> ModuleSource { + assert!(!m.has_semi()); + let file_items = db.file_items(file_id); + let item_id = file_items.id_of(file_id, m.syntax()); + ModuleSource::new(file_id, Some(item_id)) + } + + pub(crate) fn file_id(self) -> HirFileId { + self.0.file_id + } + + pub(crate) fn resolve(self, db: &impl HirDatabase) -> ModuleSourceNode { + let syntax_node = db.file_item(self.0); + let syntax_node = syntax_node.borrowed(); + if let Some(file) = ast::SourceFile::cast(syntax_node) { + return ModuleSourceNode::SourceFile(file.owned()); + } + let module = ast::Module::cast(syntax_node).unwrap(); + ModuleSourceNode::Module(module.owned()) + } +} + +impl ModuleTree { + fn push_mod(&mut self, data: ModuleData) -> ModuleId { + self.mods.alloc(data) + } + fn push_link(&mut self, data: LinkData) -> LinkId { + let owner = data.owner; + let id = self.links.alloc(data); + self.mods[owner].children.push(id); + id + } +} + +fn modules<'a>( + root: impl ast::ModuleItemOwner<'a>, +) -> impl Iterator)> { + root.items() + .filter_map(|item| match item { + ast::ModuleItem::Module(m) => Some(m), + _ => None, + }) + .filter_map(|module| { + let name = module.name()?.as_name(); + Some((name, module)) + }) +} + +fn create_module_tree<'a>( + db: &impl HirDatabase, + source_root: SourceRootId, +) -> Cancelable { + let mut tree = ModuleTree::default(); + + let mut roots = FxHashMap::default(); + let mut visited = FxHashSet::default(); + + let source_root = db.source_root(source_root); + for &file_id in source_root.files.values() { + let source = ModuleSource::new_file(file_id.into()); + if visited.contains(&source) { + continue; // TODO: use explicit crate_roots here + } + assert!(!roots.contains_key(&file_id)); + let module_id = build_subtree( + db, + &source_root, + &mut tree, + &mut visited, + &mut roots, + None, + source, + )?; + roots.insert(file_id, module_id); + } + Ok(tree) +} + +fn build_subtree( + db: &impl HirDatabase, + source_root: &SourceRoot, + tree: &mut ModuleTree, + visited: &mut FxHashSet, + roots: &mut FxHashMap, + parent: Option, + source: ModuleSource, +) -> Cancelable { + visited.insert(source); + let id = tree.push_mod(ModuleData { + source, + parent, + children: Vec::new(), + }); + for sub in db.submodules(source)?.iter() { + let link = tree.push_link(LinkData { + name: sub.name().clone(), + owner: id, + points_to: Vec::new(), + problem: None, + }); + + let (points_to, problem) = match sub { + Submodule::Declaration(name) => { + let (points_to, problem) = resolve_submodule(db, source, &name); + let points_to = points_to + .into_iter() + .map(|file_id| match roots.remove(&file_id) { + Some(module_id) => { + tree.mods[module_id].parent = Some(link); + Ok(module_id) + } + None => build_subtree( + db, + source_root, + tree, + visited, + roots, + Some(link), + ModuleSource::new_file(file_id.into()), + ), + }) + .collect::>>()?; + (points_to, problem) + } + Submodule::Definition(_name, submodule_source) => { + let points_to = build_subtree( + db, + source_root, + tree, + visited, + roots, + Some(link), + *submodule_source, + )?; + (vec![points_to], None) + } + }; + + tree.links[link].points_to = points_to; + tree.links[link].problem = problem; + } + Ok(id) +} + +fn resolve_submodule( + db: &impl HirDatabase, + source: ModuleSource, + name: &Name, +) -> (Vec, Option) { + // FIXME: handle submodules of inline modules properly + let file_id = source.file_id().original_file(db); + let source_root_id = db.file_source_root(file_id); + let path = db.file_relative_path(file_id); + let root = RelativePathBuf::default(); + let dir_path = path.parent().unwrap_or(&root); + let mod_name = path.file_stem().unwrap_or("unknown"); + let is_dir_owner = mod_name == "mod" || mod_name == "lib" || mod_name == "main"; + + let file_mod = dir_path.join(format!("{}.rs", name)); + let dir_mod = dir_path.join(format!("{}/mod.rs", name)); + let file_dir_mod = dir_path.join(format!("{}/{}.rs", mod_name, name)); + let mut candidates = ArrayVec::<[_; 2]>::new(); + if is_dir_owner { + candidates.push(file_mod.clone()); + candidates.push(dir_mod); + } else { + candidates.push(file_dir_mod.clone()); + }; + let sr = db.source_root(source_root_id); + let points_to = candidates + .into_iter() + .filter_map(|path| sr.files.get(&path)) + .map(|&it| it) + .collect::>(); + let problem = if points_to.is_empty() { + Some(Problem::UnresolvedModule { + candidate: if is_dir_owner { file_mod } else { file_dir_mod }, + }) + } else { + None + }; + (points_to, problem) +} diff --git a/crates/ra_hir/src/module/nameres.rs b/crates/ra_hir/src/nameres.rs similarity index 98% rename from crates/ra_hir/src/module/nameres.rs rename to crates/ra_hir/src/nameres.rs index 3c6851a0a3d..e65cbcb2707 100644 --- a/crates/ra_hir/src/module/nameres.rs +++ b/crates/ra_hir/src/nameres.rs @@ -31,7 +31,7 @@ Path, PathKind, HirDatabase, Crate, Name, AsName, - module::{Module, ModuleId, ModuleTree}, + module_tree::{ModuleId, ModuleTree}, }; /// Item map is the result of the name resolution. Item map contains, for each @@ -177,11 +177,11 @@ pub fn take(self, namespace: Namespace) -> Option { } pub fn take_types(self) -> Option { - self.types + self.take(Namespace::Types) } pub fn take_values(self) -> Option { - self.values + self.take(Namespace::Values) } pub fn get(&self, namespace: Namespace) -> Option<&T> { @@ -344,9 +344,9 @@ fn populate_module( if let Some(crate_id) = crate_graph.crate_id_for_crate_root(file_id.as_original_file()) { let krate = Crate::new(crate_id); - for dep in krate.dependencies(self.db) { + for dep in krate.dependencies(self.db)? { if let Some(module) = dep.krate.root_module(self.db)? { - let def_id = module.def_id(self.db); + let def_id = module.def_id; self.add_module_item( &mut module_items, dep.name.clone(), @@ -466,7 +466,7 @@ fn resolve_import(&mut self, module_id: ModuleId, import: &Import) -> Cancelable if source_root_id == self.source_root { target_module_id } else { - let module = Module::new(self.db, source_root_id, target_module_id)?; + let module = crate::code_model_api::Module::new(type_def_id); let path = Path { segments: import.path.segments[i + 1..].iter().cloned().collect(), kind: PathKind::Crate, diff --git a/crates/ra_hir/src/module/nameres/tests.rs b/crates/ra_hir/src/nameres/tests.rs similarity index 98% rename from crates/ra_hir/src/module/nameres/tests.rs rename to crates/ra_hir/src/nameres/tests.rs index a6a0bea3160..dcbe65aec36 100644 --- a/crates/ra_hir/src/module/nameres/tests.rs +++ b/crates/ra_hir/src/nameres/tests.rs @@ -17,7 +17,7 @@ fn item_map(fixture: &str) -> (Arc, hir::ModuleId) { let module = hir::source_binder::module_from_position(&db, pos) .unwrap() .unwrap(); - let module_id = module.module_id; + let module_id = module.def_id.loc(&db).module_id; (db.item_map(source_root).unwrap(), module_id) } @@ -155,7 +155,7 @@ fn item_map_across_crates() { let module = hir::source_binder::module_from_file_id(&db, main_id) .unwrap() .unwrap(); - let module_id = module.module_id; + let module_id = module.def_id.loc(&db).module_id; let item_map = db.item_map(source_root).unwrap(); check_module_item_map( diff --git a/crates/ra_hir/src/query_definitions.rs b/crates/ra_hir/src/query_definitions.rs index d9ee9d37f09..f4b380022eb 100644 --- a/crates/ra_hir/src/query_definitions.rs +++ b/crates/ra_hir/src/query_definitions.rs @@ -6,20 +6,17 @@ use rustc_hash::FxHashMap; use ra_syntax::{ AstNode, SyntaxNode, - ast::{self, NameOwner, ModuleItemOwner} + ast::{self, ModuleItemOwner} }; use ra_db::{SourceRootId, Cancelable,}; use crate::{ - SourceFileItems, SourceItemId, DefKind, DefId, Name, AsName, HirFileId, + SourceFileItems, SourceItemId, DefKind, DefId, HirFileId, MacroCallLoc, db::HirDatabase, function::FnScopes, - module::{ - ModuleSource, ModuleSourceNode, ModuleId, - imp::Submodule, - nameres::{InputModuleItems, ItemMap, Resolver}, - }, + module_tree::{ModuleId, ModuleSourceNode}, + nameres::{InputModuleItems, ItemMap, Resolver}, adt::{StructData, EnumData}, }; @@ -61,54 +58,6 @@ pub(super) fn file_item(db: &impl HirDatabase, source_item_id: SourceItemId) -> } } -pub(crate) fn submodules( - db: &impl HirDatabase, - source: ModuleSource, -) -> Cancelable>> { - db.check_canceled()?; - let file_id = source.file_id(); - let submodules = match source.resolve(db) { - ModuleSourceNode::SourceFile(it) => collect_submodules(db, file_id, it.borrowed()), - ModuleSourceNode::Module(it) => it - .borrowed() - .item_list() - .map(|it| collect_submodules(db, file_id, it)) - .unwrap_or_else(Vec::new), - }; - return Ok(Arc::new(submodules)); - - fn collect_submodules<'a>( - db: &impl HirDatabase, - file_id: HirFileId, - root: impl ast::ModuleItemOwner<'a>, - ) -> Vec { - modules(root) - .map(|(name, m)| { - if m.has_semi() { - Submodule::Declaration(name) - } else { - let src = ModuleSource::new_inline(db, file_id, m); - Submodule::Definition(name, src) - } - }) - .collect() - } -} - -pub(crate) fn modules<'a>( - root: impl ast::ModuleItemOwner<'a>, -) -> impl Iterator)> { - root.items() - .filter_map(|item| match item { - ast::ModuleItem::Module(m) => Some(m), - _ => None, - }) - .filter_map(|module| { - let name = module.name()?.as_name(); - Some((name, module)) - }) -} - pub(super) fn input_module_items( db: &impl HirDatabase, source_root_id: SourceRootId, diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 29a3960e919..b7e3ff9b0c5 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -13,11 +13,13 @@ }; use crate::{ - HirDatabase, Module, Function, SourceItemId, - module::ModuleSource, + HirDatabase, Function, SourceItemId, + module_tree::ModuleSource, DefKind, DefLoc, AsName, }; +use crate::code_model_api::Module; + /// Locates the module by `FileId`. Picks topmost module in the file. pub fn module_from_file_id(db: &impl HirDatabase, file_id: FileId) -> Cancelable> { let module_source = ModuleSource::new_file(file_id.into()); @@ -34,7 +36,7 @@ pub fn module_from_declaration( let child_name = decl.name(); match (parent_module, child_name) { (Some(parent_module), Some(child_name)) => { - if let Some(child) = parent_module.child(&child_name.as_name()) { + if let Some(child) = parent_module.child(db, &child_name.as_name())? { return Ok(Some(child)); } } @@ -84,7 +86,15 @@ fn module_from_source( .modules_with_sources() .find(|(_id, src)| src == &module_source); let module_id = ctry!(m).0; - Ok(Some(Module::new(db, source_root_id, module_id)?)) + let def_loc = DefLoc { + kind: DefKind::Module, + source_root_id, + module_id, + source_item_id: module_source.0, + }; + let def_id = def_loc.id(db); + + Ok(Some(Module::new(def_id))) } pub fn function_from_position( @@ -114,7 +124,8 @@ pub fn function_from_module( module: &Module, fn_def: ast::FnDef, ) -> Function { - let file_id = module.source().file_id(); + let loc = module.def_id.loc(db); + let file_id = loc.source_item_id.file_id; let file_items = db.file_items(file_id); let item_id = file_items.id_of(file_id, fn_def.syntax()); let source_item_id = SourceItemId { @@ -123,8 +134,8 @@ pub fn function_from_module( }; let def_loc = DefLoc { kind: DefKind::Function, - source_root_id: module.source_root_id, - module_id: module.module_id, + source_root_id: loc.source_root_id, + module_id: loc.module_id, source_item_id, }; Function::new(def_loc.id(db)) @@ -147,7 +158,8 @@ pub fn macro_symbols( Some(it) => it, None => return Ok(Vec::new()), }; - let items = db.input_module_items(module.source_root_id, module.module_id)?; + let loc = module.def_id.loc(db); + let items = db.input_module_items(loc.source_root_id, loc.module_id)?; let mut res = Vec::new(); for macro_call_id in items