From 0e4b710af83844f4a7c471c5335c99aaaa25a90c Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 28 Nov 2018 03:42:26 +0300 Subject: introduce hir crate --- crates/ra_hir/src/module/imp.rs | 194 ++++++++++++++++ crates/ra_hir/src/module/mod.rs | 378 ++++++++++++++++++++++++++++++ crates/ra_hir/src/module/nameres.rs | 444 ++++++++++++++++++++++++++++++++++++ 3 files changed, 1016 insertions(+) create mode 100644 crates/ra_hir/src/module/imp.rs create mode 100644 crates/ra_hir/src/module/mod.rs create mode 100644 crates/ra_hir/src/module/nameres.rs (limited to 'crates/ra_hir/src/module') diff --git a/crates/ra_hir/src/module/imp.rs b/crates/ra_hir/src/module/imp.rs new file mode 100644 index 000000000..d55fa3e6b --- /dev/null +++ b/crates/ra_hir/src/module/imp.rs @@ -0,0 +1,194 @@ +use std::sync::Arc; + +use ra_syntax::{ + ast::{self, NameOwner}, + SmolStr, +}; +use relative_path::RelativePathBuf; +use rustc_hash::{FxHashMap, FxHashSet}; +use ra_db::{SourceRoot, SourceRootId, FileResolverImp, Cancelable, FileId,}; + +use crate::{ + HirDatabase, +}; + +use super::{ + LinkData, LinkId, ModuleData, ModuleId, ModuleSource, + ModuleTree, Problem, +}; + +#[derive(Clone, Hash, PartialEq, Eq, Debug)] +pub(crate) enum Submodule { + Declaration(SmolStr), + Definition(SmolStr, ModuleSource), +} + +impl Submodule { + fn name(&self) -> &SmolStr { + 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()?.text(); + 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.iter() { + let source = ModuleSource::SourceFile(file_id); + 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(source, &name, &source_root.file_resolver); + 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::SourceFile(file_id), + ), + }) + .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( + source: ModuleSource, + name: &SmolStr, + file_resolver: &FileResolverImp, +) -> (Vec, Option) { + let file_id = match source { + ModuleSource::SourceFile(it) => it, + ModuleSource::Module(..) => { + // TODO + return (Vec::new(), None); + } + }; + let mod_name = file_resolver.file_stem(file_id); + let is_dir_owner = mod_name == "mod" || mod_name == "lib" || mod_name == "main"; + + let file_mod = RelativePathBuf::from(format!("../{}.rs", name)); + let dir_mod = RelativePathBuf::from(format!("../{}/mod.rs", name)); + let points_to: Vec; + let problem: Option; + if is_dir_owner { + points_to = [&file_mod, &dir_mod] + .iter() + .filter_map(|path| file_resolver.resolve(file_id, path)) + .collect(); + problem = if points_to.is_empty() { + Some(Problem::UnresolvedModule { + candidate: file_mod, + }) + } else { + None + } + } else { + points_to = Vec::new(); + problem = Some(Problem::NotDirOwner { + move_to: RelativePathBuf::from(format!("../{}/mod.rs", mod_name)), + candidate: file_mod, + }); + } + (points_to, problem) +} diff --git a/crates/ra_hir/src/module/mod.rs b/crates/ra_hir/src/module/mod.rs new file mode 100644 index 000000000..81b9f948d --- /dev/null +++ b/crates/ra_hir/src/module/mod.rs @@ -0,0 +1,378 @@ +pub(super) mod imp; +pub(super) mod nameres; + +use std::sync::Arc; + +use ra_editor::find_node_at_offset; + +use ra_syntax::{ + algo::generate, + ast::{self, AstNode, NameOwner}, + SmolStr, SyntaxNode, +}; +use ra_db::{SourceRootId, FileId, FilePosition, Cancelable}; +use relative_path::RelativePathBuf; + +use crate::{ + DefLoc, DefId, Path, PathKind, HirDatabase, SourceItemId, + arena::{Arena, Id}, +}; + +pub(crate) use self::nameres::ModuleScope; + +/// `Module` is API entry point to get all the information +/// about a particular module. +#[derive(Debug, Clone)] +pub(crate) struct Module { + tree: Arc, + source_root_id: SourceRootId, + module_id: ModuleId, +} + +impl Module { + /// Lookup `Module` by `FileId`. Note that this is inherently + /// lossy transformation: in general, a single source might correspond to + /// several modules. + pub fn guess_from_file_id( + db: &impl HirDatabase, + file_id: FileId, + ) -> Cancelable> { + Module::guess_from_source(db, file_id, ModuleSource::SourceFile(file_id)) + } + + /// Lookup `Module` by position in the source code. Note that this + /// is inherently lossy transformation: in general, a single source might + /// correspond to several modules. + pub fn guess_from_position( + db: &impl HirDatabase, + position: FilePosition, + ) -> Cancelable> { + let file = db.source_file(position.file_id); + let module_source = match find_node_at_offset::(file.syntax(), position.offset) + { + Some(m) if !m.has_semi() => ModuleSource::new_inline(db, position.file_id, m), + _ => ModuleSource::SourceFile(position.file_id), + }; + Module::guess_from_source(db, position.file_id, module_source) + } + + fn guess_from_source( + db: &impl HirDatabase, + file_id: FileId, + module_source: ModuleSource, + ) -> Cancelable> { + let source_root_id = db.file_source_root(file_id); + let module_tree = db.module_tree(source_root_id)?; + + let res = match module_tree.any_module_for_source(module_source) { + None => None, + Some(module_id) => Some(Module { + tree: module_tree, + source_root_id, + module_id, + }), + }; + Ok(res) + } + + 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(); + let src = link.bind_source(&self.tree, db); + Some((file_id, src)) + } + + pub fn source(&self) -> ModuleSource { + self.module_id.source(&self.tree) + } + + /// 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() + }) + } + + /// 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 + #[allow(unused)] + pub fn name(&self) -> Option { + 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::Module { + id: self.module_id, + source_root: self.source_root_id, + }; + def_loc.id(db) + } + + /// Finds a child module with the specified name. + pub fn child(&self, name: &str) -> 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(crate) 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(crate) fn resolve_path( + &self, + db: &impl HirDatabase, + path: Path, + ) -> Cancelable> { + let mut curr = match path.kind { + PathKind::Crate => self.crate_root(), + PathKind::Self_ | PathKind::Plain => self.clone(), + PathKind::Super => ctry!(self.parent()), + } + .def_id(db); + + let segments = path.segments; + for name in segments.iter() { + let module = match curr.loc(db) { + DefLoc::Module { id, source_root } => Module::new(db, source_root, id)?, + _ => return Ok(None), + }; + let scope = module.scope(db)?; + curr = ctry!(ctry!(scope.get(&name)).def_id); + } + Ok(Some(curr)) + } + + pub fn problems(&self, db: &impl HirDatabase) -> Vec<(SyntaxNode, Problem)> { + self.module_id.problems(&self.tree, db) + } +} + +/// Phisically, 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(crate) struct ModuleTree { + mods: Arena, + links: Arena, +} + +impl ModuleTree { + pub(crate) fn modules<'a>(&'a self) -> impl Iterator + 'a { + self.mods.iter().map(|(id, _)| id) + } + + fn modules_for_source(&self, source: ModuleSource) -> Vec { + self.mods + .iter() + .filter(|(_idx, it)| it.source == source) + .map(|(idx, _)| idx) + .collect() + } + + fn any_module_for_source(&self, source: ModuleSource) -> Option { + self.modules_for_source(source).pop() + } +} + +/// `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(crate) enum ModuleSource { + SourceFile(FileId), + Module(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), +} + +pub(crate) type ModuleId = Id; +type LinkId = Id; + +#[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: &str) -> 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) -> SmolStr { + tree.links[self].name.clone() + } + 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(crate) struct ModuleData { + source: ModuleSource, + parent: Option, + children: Vec, +} + +impl ModuleSource { + pub(crate) fn new_inline( + db: &impl HirDatabase, + file_id: FileId, + module: ast::Module, + ) -> ModuleSource { + assert!(!module.has_semi()); + let items = db.file_items(file_id); + let item_id = items.id_of(module.syntax()); + let id = SourceItemId { file_id, item_id }; + ModuleSource::Module(id) + } + + pub(crate) fn as_file(self) -> Option { + match self { + ModuleSource::SourceFile(f) => Some(f), + ModuleSource::Module(..) => None, + } + } + + pub(crate) fn file_id(self) -> FileId { + match self { + ModuleSource::SourceFile(f) => f, + ModuleSource::Module(source_item_id) => source_item_id.file_id, + } + } + + pub(crate) fn resolve(self, db: &impl HirDatabase) -> ModuleSourceNode { + match self { + ModuleSource::SourceFile(file_id) => { + let syntax = db.source_file(file_id); + ModuleSourceNode::SourceFile(syntax.ast().owned()) + } + ModuleSource::Module(item_id) => { + let syntax = db.file_item(item_id); + let syntax = syntax.borrowed(); + let module = ast::Module::cast(syntax).unwrap(); + ModuleSourceNode::Module(module.owned()) + } + } + } +} + +#[derive(Hash, Debug, PartialEq, Eq)] +struct LinkData { + owner: ModuleId, + name: SmolStr, + 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/nameres.rs b/crates/ra_hir/src/module/nameres.rs new file mode 100644 index 000000000..513a37646 --- /dev/null +++ b/crates/ra_hir/src/module/nameres.rs @@ -0,0 +1,444 @@ +//! Name resolution algorithm. The end result of the algorithm is `ItemMap`: a +//! map with maps each module to it's scope: the set of items, visible in the +//! module. That is, we only resolve imports here, name resolution of item +//! bodies will be done in a separate step. +//! +//! Like Rustc, we use an interative per-crate algorithm: we start with scopes +//! containing only directly defined items, and then iteratively resolve +//! imports. +//! +//! To make this work nicely in the IDE scenarios, we place `InputModuleItems` +//! in between raw syntax and name resolution. `InputModuleItems` are computed +//! using only the module's syntax, and it is all directly defined items plus +//! imports. The plain is to make `InputModuleItems` independent of local +//! modifications (that is, typing inside a function shold not change IMIs), +//! such that the results of name resolution can be preserved unless the module +//! structure itself is modified. +use std::{ + sync::Arc, +}; + +use rustc_hash::FxHashMap; +use ra_syntax::{ + TextRange, + SmolStr, SyntaxKind::{self, *}, + ast::{self, AstNode} +}; +use ra_db::SourceRootId; + +use crate::{ + Cancelable, FileId, + DefId, DefLoc, + SourceItemId, SourceFileItemId, SourceFileItems, + Path, PathKind, + HirDatabase, + module::{ModuleId, ModuleTree}, +}; + +/// Item map is the result of the name resolution. Item map contains, for each +/// module, the set of visible items. +#[derive(Default, Debug, PartialEq, Eq)] +pub(crate) struct ItemMap { + pub(crate) per_module: FxHashMap, +} + +#[derive(Debug, Default, PartialEq, Eq, Clone)] +pub(crate) struct ModuleScope { + items: FxHashMap, +} + +impl ModuleScope { + pub(crate) fn entries<'a>(&'a self) -> impl Iterator + 'a { + self.items.iter() + } + pub(crate) fn get(&self, name: &SmolStr) -> Option<&Resolution> { + self.items.get(name) + } +} + +/// A set of items and imports declared inside a module, without relation to +/// other modules. +/// +/// This stands in-between raw syntax and name resolution and alow us to avoid +/// recomputing name res: if `InputModuleItems` are the same, we can avoid +/// running name resolution. +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct InputModuleItems { + items: Vec, + imports: Vec, +} + +#[derive(Debug, PartialEq, Eq)] +struct ModuleItem { + id: SourceFileItemId, + name: SmolStr, + kind: SyntaxKind, + vis: Vis, +} + +#[derive(Debug, PartialEq, Eq)] +enum Vis { + // Priv, + Other, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Import { + path: Path, + kind: ImportKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct NamedImport { + file_item_id: SourceFileItemId, + relative_range: TextRange, +} + +impl NamedImport { + pub(crate) fn range(&self, db: &impl HirDatabase, file_id: FileId) -> TextRange { + let source_item_id = SourceItemId { + file_id, + item_id: self.file_item_id, + }; + let syntax = db.file_item(source_item_id); + let offset = syntax.borrowed().range().start(); + self.relative_range + offset + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum ImportKind { + Glob, + Named(NamedImport), +} + +/// Resolution is basically `DefId` atm, but it should account for stuff like +/// multiple namespaces, ambiguity and errors. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Resolution { + /// None for unresolved + pub(crate) def_id: Option, + /// ident by whitch this is imported into local scope. + pub(crate) import: Option, +} + +// #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +// enum Namespace { +// Types, +// Values, +// } + +// #[derive(Debug)] +// struct PerNs { +// types: Option, +// values: Option, +// } + +impl InputModuleItems { + pub(crate) fn new<'a>( + file_items: &SourceFileItems, + items: impl Iterator>, + ) -> InputModuleItems { + let mut res = InputModuleItems::default(); + for item in items { + res.add_item(file_items, item); + } + res + } + + fn add_item(&mut self, file_items: &SourceFileItems, item: ast::ModuleItem) -> Option<()> { + match item { + ast::ModuleItem::StructDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::EnumDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::FnDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::TraitDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::TypeDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::ImplItem(_) => { + // impls don't define items + } + ast::ModuleItem::UseItem(it) => self.add_use_item(file_items, it), + ast::ModuleItem::ExternCrateItem(_) => { + // TODO + } + ast::ModuleItem::ConstDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::StaticDef(it) => self.items.push(ModuleItem::new(file_items, it)?), + ast::ModuleItem::Module(it) => self.items.push(ModuleItem::new(file_items, it)?), + } + Some(()) + } + + fn add_use_item(&mut self, file_items: &SourceFileItems, item: ast::UseItem) { + let file_item_id = file_items.id_of(item.syntax()); + let start_offset = item.syntax().range().start(); + Path::expand_use_item(item, |path, range| { + let kind = match range { + None => ImportKind::Glob, + Some(range) => ImportKind::Named(NamedImport { + file_item_id, + relative_range: range - start_offset, + }), + }; + self.imports.push(Import { kind, path }) + }) + } +} + +impl ModuleItem { + fn new<'a>(file_items: &SourceFileItems, item: impl ast::NameOwner<'a>) -> Option { + let name = item.name()?.text(); + let kind = item.syntax().kind(); + let vis = Vis::Other; + let id = file_items.id_of(item.syntax()); + let res = ModuleItem { + id, + name, + kind, + vis, + }; + Some(res) + } +} + +pub(crate) struct Resolver<'a, DB> { + pub db: &'a DB, + pub input: &'a FxHashMap>, + pub source_root: SourceRootId, + pub module_tree: Arc, + pub result: ItemMap, +} + +impl<'a, DB> Resolver<'a, DB> +where + DB: HirDatabase, +{ + pub(crate) fn resolve(mut self) -> Cancelable { + for (&module_id, items) in self.input.iter() { + self.populate_module(module_id, items) + } + + for &module_id in self.input.keys() { + self.db.check_canceled()?; + self.resolve_imports(module_id); + } + Ok(self.result) + } + + fn populate_module(&mut self, module_id: ModuleId, input: &InputModuleItems) { + let file_id = module_id.source(&self.module_tree).file_id(); + + let mut module_items = ModuleScope::default(); + + for import in input.imports.iter() { + if let Some(name) = import.path.segments.iter().last() { + if let ImportKind::Named(import) = import.kind { + module_items.items.insert( + name.clone(), + Resolution { + def_id: None, + import: Some(import), + }, + ); + } + } + } + + for item in input.items.iter() { + if item.kind == MODULE { + // handle submodules separatelly + continue; + } + let def_loc = DefLoc::Item { + source_item_id: SourceItemId { + file_id, + item_id: item.id, + }, + }; + let def_id = def_loc.id(self.db); + let resolution = Resolution { + def_id: Some(def_id), + import: None, + }; + module_items.items.insert(item.name.clone(), resolution); + } + + for (name, mod_id) in module_id.children(&self.module_tree) { + let def_loc = DefLoc::Module { + id: mod_id, + source_root: self.source_root, + }; + let def_id = def_loc.id(self.db); + let resolution = Resolution { + def_id: Some(def_id), + import: None, + }; + module_items.items.insert(name, resolution); + } + + self.result.per_module.insert(module_id, module_items); + } + + fn resolve_imports(&mut self, module_id: ModuleId) { + for import in self.input[&module_id].imports.iter() { + self.resolve_import(module_id, import); + } + } + + fn resolve_import(&mut self, module_id: ModuleId, import: &Import) { + let ptr = match import.kind { + ImportKind::Glob => return, + ImportKind::Named(ptr) => ptr, + }; + + let mut curr = match import.path.kind { + // TODO: handle extern crates + PathKind::Plain => return, + PathKind::Self_ => module_id, + PathKind::Super => { + match module_id.parent(&self.module_tree) { + Some(it) => it, + // TODO: error + None => return, + } + } + PathKind::Crate => module_id.crate_root(&self.module_tree), + }; + + for (i, name) in import.path.segments.iter().enumerate() { + let is_last = i == import.path.segments.len() - 1; + + let def_id = match self.result.per_module[&curr].items.get(name) { + None => return, + Some(res) => match res.def_id { + Some(it) => it, + None => return, + }, + }; + + if !is_last { + curr = match def_id.loc(self.db) { + DefLoc::Module { id, .. } => id, + _ => return, + } + } else { + self.update(module_id, |items| { + let res = Resolution { + def_id: Some(def_id), + import: Some(ptr), + }; + items.items.insert(name.clone(), res); + }) + } + } + } + + fn update(&mut self, module_id: ModuleId, f: impl FnOnce(&mut ModuleScope)) { + let module_items = self.result.per_module.get_mut(&module_id).unwrap(); + f(module_items) + } +} + +#[cfg(test)] +mod tests { + use ra_db::FilesDatabase; + use crate::{ + AnalysisChange, + mock_analysis::{MockAnalysis, analysis_and_position}, + hir::{self, HirDatabase}, +}; + use super::*; + + fn item_map(fixture: &str) -> (Arc, ModuleId) { + let (analysis, pos) = analysis_and_position(fixture); + let db = analysis.imp.db; + let source_root = db.file_source_root(pos.file_id); + let descr = hir::Module::guess_from_position(&*db, pos) + .unwrap() + .unwrap(); + let module_id = descr.module_id; + (db.item_map(source_root).unwrap(), module_id) + } + + #[test] + fn test_item_map() { + let (item_map, module_id) = item_map( + " + //- /lib.rs + mod foo; + + use crate::foo::bar::Baz; + <|> + + //- /foo/mod.rs + pub mod bar; + + //- /foo/bar.rs + pub struct Baz; + ", + ); + let name = SmolStr::from("Baz"); + let resolution = &item_map.per_module[&module_id].items[&name]; + assert!(resolution.def_id.is_some()); + } + + #[test] + fn typing_inside_a_function_should_not_invalidate_item_map() { + let mock_analysis = MockAnalysis::with_files( + " + //- /lib.rs + mod foo; + + use crate::foo::bar::Baz; + + fn foo() -> i32 { + 1 + 1 + } + //- /foo/mod.rs + pub mod bar; + + //- /foo/bar.rs + pub struct Baz; + ", + ); + + let file_id = mock_analysis.id_of("/lib.rs"); + let mut host = mock_analysis.analysis_host(); + + let source_root = host.analysis().imp.db.file_source_root(file_id); + + { + let db = host.analysis().imp.db; + let events = db.log_executed(|| { + db.item_map(source_root).unwrap(); + }); + assert!(format!("{:?}", events).contains("item_map")) + } + + let mut change = AnalysisChange::new(); + + change.change_file( + file_id, + " + mod foo; + + use crate::foo::bar::Baz; + + fn foo() -> i32 { 92 } + " + .to_string(), + ); + + host.apply_change(change); + + { + let db = host.analysis().imp.db; + let events = db.log_executed(|| { + db.item_map(source_root).unwrap(); + }); + assert!( + !format!("{:?}", events).contains("_item_map"), + "{:#?}", + events + ) + } + } +} -- cgit v1.2.3 From 59e29aef633e906837f8fed604435976a46be691 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 28 Nov 2018 04:09:44 +0300 Subject: Move hir to a separate crate --- crates/ra_hir/src/module/imp.rs | 2 +- crates/ra_hir/src/module/mod.rs | 31 ++++----- crates/ra_hir/src/module/nameres.rs | 134 ++++-------------------------------- 3 files changed, 29 insertions(+), 138 deletions(-) (limited to 'crates/ra_hir/src/module') diff --git a/crates/ra_hir/src/module/imp.rs b/crates/ra_hir/src/module/imp.rs index d55fa3e6b..76ea129a7 100644 --- a/crates/ra_hir/src/module/imp.rs +++ b/crates/ra_hir/src/module/imp.rs @@ -18,7 +18,7 @@ use super::{ }; #[derive(Clone, Hash, PartialEq, Eq, Debug)] -pub(crate) enum Submodule { +pub enum Submodule { Declaration(SmolStr), Definition(SmolStr, ModuleSource), } diff --git a/crates/ra_hir/src/module/mod.rs b/crates/ra_hir/src/module/mod.rs index 81b9f948d..a011fd53e 100644 --- a/crates/ra_hir/src/module/mod.rs +++ b/crates/ra_hir/src/module/mod.rs @@ -18,15 +18,16 @@ use crate::{ arena::{Arena, Id}, }; -pub(crate) use self::nameres::ModuleScope; +pub use self::nameres::ModuleScope; /// `Module` is API entry point to get all the information /// about a particular module. #[derive(Debug, Clone)] -pub(crate) struct Module { +pub struct Module { tree: Arc, source_root_id: SourceRootId, - module_id: ModuleId, + //TODO: make private + pub module_id: ModuleId, } impl Module { @@ -145,17 +146,13 @@ impl Module { } /// Returns a `ModuleScope`: a set of items, visible in this module. - pub(crate) fn scope(&self, db: &impl HirDatabase) -> Cancelable { + 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(crate) fn resolve_path( - &self, - db: &impl HirDatabase, - path: Path, - ) -> Cancelable> { + pub fn resolve_path(&self, db: &impl HirDatabase, path: Path) -> Cancelable> { let mut curr = match path.kind { PathKind::Crate => self.crate_root(), PathKind::Self_ | PathKind::Plain => self.clone(), @@ -188,7 +185,7 @@ impl Module { /// (which can have multiple parents) to the precise world of modules (which /// always have one parent). #[derive(Default, Debug, PartialEq, Eq)] -pub(crate) struct ModuleTree { +pub struct ModuleTree { mods: Arena, links: Arena, } @@ -214,19 +211,19 @@ impl ModuleTree { /// `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(crate) enum ModuleSource { +pub enum ModuleSource { SourceFile(FileId), Module(SourceItemId), } /// An owned syntax node for a module. Unlike `ModuleSource`, /// this holds onto the AST for the whole file. -pub(crate) enum ModuleSourceNode { +pub enum ModuleSourceNode { SourceFile(ast::SourceFileNode), Module(ast::ModuleNode), } -pub(crate) type ModuleId = Id; +pub type ModuleId = Id; type LinkId = Id; #[derive(Clone, Debug, Hash, PartialEq, Eq)] @@ -308,7 +305,7 @@ impl LinkId { } #[derive(Debug, PartialEq, Eq, Hash)] -pub(crate) struct ModuleData { +pub struct ModuleData { source: ModuleSource, parent: Option, children: Vec, @@ -327,21 +324,21 @@ impl ModuleSource { ModuleSource::Module(id) } - pub(crate) fn as_file(self) -> Option { + pub fn as_file(self) -> Option { match self { ModuleSource::SourceFile(f) => Some(f), ModuleSource::Module(..) => None, } } - pub(crate) fn file_id(self) -> FileId { + pub fn file_id(self) -> FileId { match self { ModuleSource::SourceFile(f) => f, ModuleSource::Module(source_item_id) => source_item_id.file_id, } } - pub(crate) fn resolve(self, db: &impl HirDatabase) -> ModuleSourceNode { + pub fn resolve(self, db: &impl HirDatabase) -> ModuleSourceNode { match self { ModuleSource::SourceFile(file_id) => { let syntax = db.source_file(file_id); diff --git a/crates/ra_hir/src/module/nameres.rs b/crates/ra_hir/src/module/nameres.rs index 513a37646..837a8d5ae 100644 --- a/crates/ra_hir/src/module/nameres.rs +++ b/crates/ra_hir/src/module/nameres.rs @@ -38,20 +38,20 @@ use crate::{ /// Item map is the result of the name resolution. Item map contains, for each /// module, the set of visible items. #[derive(Default, Debug, PartialEq, Eq)] -pub(crate) struct ItemMap { - pub(crate) per_module: FxHashMap, +pub struct ItemMap { + pub per_module: FxHashMap, } #[derive(Debug, Default, PartialEq, Eq, Clone)] -pub(crate) struct ModuleScope { - items: FxHashMap, +pub struct ModuleScope { + pub items: FxHashMap, } impl ModuleScope { - pub(crate) fn entries<'a>(&'a self) -> impl Iterator + 'a { + pub fn entries<'a>(&'a self) -> impl Iterator + 'a { self.items.iter() } - pub(crate) fn get(&self, name: &SmolStr) -> Option<&Resolution> { + pub fn get(&self, name: &SmolStr) -> Option<&Resolution> { self.items.get(name) } } @@ -63,7 +63,7 @@ impl ModuleScope { /// recomputing name res: if `InputModuleItems` are the same, we can avoid /// running name resolution. #[derive(Debug, Default, PartialEq, Eq)] -pub(crate) struct InputModuleItems { +pub struct InputModuleItems { items: Vec, imports: Vec, } @@ -89,13 +89,13 @@ struct Import { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct NamedImport { - file_item_id: SourceFileItemId, - relative_range: TextRange, +pub struct NamedImport { + pub file_item_id: SourceFileItemId, + pub relative_range: TextRange, } impl NamedImport { - pub(crate) fn range(&self, db: &impl HirDatabase, file_id: FileId) -> TextRange { + pub fn range(&self, db: &impl HirDatabase, file_id: FileId) -> TextRange { let source_item_id = SourceItemId { file_id, item_id: self.file_item_id, @@ -115,11 +115,11 @@ enum ImportKind { /// Resolution is basically `DefId` atm, but it should account for stuff like /// multiple namespaces, ambiguity and errors. #[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct Resolution { +pub struct Resolution { /// None for unresolved - pub(crate) def_id: Option, + pub def_id: Option, /// ident by whitch this is imported into local scope. - pub(crate) import: Option, + pub import: Option, } // #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -336,109 +336,3 @@ where f(module_items) } } - -#[cfg(test)] -mod tests { - use ra_db::FilesDatabase; - use crate::{ - AnalysisChange, - mock_analysis::{MockAnalysis, analysis_and_position}, - hir::{self, HirDatabase}, -}; - use super::*; - - fn item_map(fixture: &str) -> (Arc, ModuleId) { - let (analysis, pos) = analysis_and_position(fixture); - let db = analysis.imp.db; - let source_root = db.file_source_root(pos.file_id); - let descr = hir::Module::guess_from_position(&*db, pos) - .unwrap() - .unwrap(); - let module_id = descr.module_id; - (db.item_map(source_root).unwrap(), module_id) - } - - #[test] - fn test_item_map() { - let (item_map, module_id) = item_map( - " - //- /lib.rs - mod foo; - - use crate::foo::bar::Baz; - <|> - - //- /foo/mod.rs - pub mod bar; - - //- /foo/bar.rs - pub struct Baz; - ", - ); - let name = SmolStr::from("Baz"); - let resolution = &item_map.per_module[&module_id].items[&name]; - assert!(resolution.def_id.is_some()); - } - - #[test] - fn typing_inside_a_function_should_not_invalidate_item_map() { - let mock_analysis = MockAnalysis::with_files( - " - //- /lib.rs - mod foo; - - use crate::foo::bar::Baz; - - fn foo() -> i32 { - 1 + 1 - } - //- /foo/mod.rs - pub mod bar; - - //- /foo/bar.rs - pub struct Baz; - ", - ); - - let file_id = mock_analysis.id_of("/lib.rs"); - let mut host = mock_analysis.analysis_host(); - - let source_root = host.analysis().imp.db.file_source_root(file_id); - - { - let db = host.analysis().imp.db; - let events = db.log_executed(|| { - db.item_map(source_root).unwrap(); - }); - assert!(format!("{:?}", events).contains("item_map")) - } - - let mut change = AnalysisChange::new(); - - change.change_file( - file_id, - " - mod foo; - - use crate::foo::bar::Baz; - - fn foo() -> i32 { 92 } - " - .to_string(), - ); - - host.apply_change(change); - - { - let db = host.analysis().imp.db; - let events = db.log_executed(|| { - db.item_map(source_root).unwrap(); - }); - assert!( - !format!("{:?}", events).contains("_item_map"), - "{:#?}", - events - ) - } - } -} -- cgit v1.2.3