rust/crates/ra_hir/src/module_tree.rs

335 lines
11 KiB
Rust
Raw Normal View History

2019-01-06 15:33:27 +01:00
use std::sync::Arc;
2018-11-28 01:42:26 +01:00
2019-01-06 15:33:27 +01:00
use arrayvec::ArrayVec;
use relative_path::RelativePathBuf;
use ra_db::{FileId, SourceRoot, CrateId};
2018-11-28 01:42:26 +01:00
use ra_syntax::{
SyntaxNode, TreeArc,
2018-11-28 01:42:26 +01:00
algo::generate,
ast::{self, AstNode, NameOwner},
};
2019-01-04 14:15:50 +01:00
use ra_arena::{Arena, RawId, impl_arena_id};
2019-01-23 13:36:29 +01:00
use test_utils::tested_by;
2018-11-28 01:42:26 +01:00
2019-01-26 21:25:18 +01:00
use crate::{
Name, AsName, HirDatabase, SourceItemId, HirFileId, Problem, SourceFileItems, ModuleSource,
ids::SourceFileItemId,
};
2019-01-06 17:58:10 +01:00
impl ModuleSource {
2019-01-26 21:25:18 +01:00
pub(crate) fn new(
2019-01-06 17:58:10 +01:00
db: &impl HirDatabase,
2019-01-26 21:25:18 +01:00
file_id: HirFileId,
decl_id: Option<SourceFileItemId>,
2019-01-06 17:58:10 +01:00
) -> ModuleSource {
2019-01-26 21:25:18 +01:00
match decl_id {
Some(item_id) => {
let module = db.file_item(SourceItemId { file_id, item_id });
let module = ast::Module::cast(&*module).unwrap();
assert!(module.item_list().is_some(), "expected inline module");
ModuleSource::Module(module.to_owned())
}
None => {
let source_file = db.hir_parse(file_id);
ModuleSource::SourceFile(source_file)
}
2019-01-06 17:58:10 +01:00
}
}
}
2018-11-28 01:42:26 +01:00
2019-01-06 15:33:27 +01:00
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
2019-01-06 17:58:10 +01:00
pub struct Submodule {
name: Name,
is_declaration: bool,
2019-01-26 21:25:18 +01:00
decl_id: SourceFileItemId,
2019-01-06 15:33:27 +01:00
}
impl Submodule {
pub(crate) fn submodules_query(
db: &impl HirDatabase,
2019-01-26 21:25:18 +01:00
file_id: HirFileId,
decl_id: Option<SourceFileItemId>,
) -> Arc<Vec<Submodule>> {
2019-01-15 13:45:48 +01:00
db.check_canceled();
2019-01-06 17:58:10 +01:00
let file_items = db.file_items(file_id);
2019-01-26 21:25:18 +01:00
let module_source = ModuleSource::new(db, file_id, decl_id);
2019-01-06 17:58:10 +01:00
let submodules = match module_source {
ModuleSource::SourceFile(source_file) => {
2019-01-08 09:28:42 +01:00
collect_submodules(file_id, &file_items, &*source_file)
2019-01-06 17:58:10 +01:00
}
ModuleSource::Module(module) => {
collect_submodules(file_id, &file_items, module.item_list().unwrap())
}
};
2019-01-26 21:25:18 +01:00
return Arc::new(submodules);
2019-01-08 09:28:42 +01:00
fn collect_submodules(
file_id: HirFileId,
2019-01-06 17:58:10 +01:00
file_items: &SourceFileItems,
2019-01-08 09:28:42 +01:00
root: &impl ast::ModuleItemOwner,
) -> Vec<Submodule> {
2019-01-23 15:57:41 +01:00
root.items()
.filter_map(|item| match item.kind() {
ast::ModuleItemKind::Module(m) => Some(m),
_ => None,
})
.filter_map(|module| {
let name = module.name()?.as_name();
if !module.has_semi() && module.item_list().is_none() {
tested_by!(name_res_works_for_broken_modules);
return None;
}
let sub = Submodule {
name,
is_declaration: module.has_semi(),
2019-01-26 21:25:18 +01:00
decl_id: file_items.id_of(file_id, module.syntax()),
2019-01-23 15:57:41 +01:00
};
Some(sub)
})
.collect()
}
}
2019-01-06 15:33:27 +01:00
}
2018-11-28 01:42:26 +01:00
2019-01-04 14:15:50 +01:00
#[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
2018-11-28 01:42:26 +01:00
/// organized as a tree of modules. Usually, a single file corresponds to a
/// single module, but it is not neccessarily always the case.
2018-11-28 01:42:26 +01:00
///
/// `ModuleTree` encapsulates the logic of transitioning from the fuzzy world of files
2018-11-28 01:42:26 +01:00
/// (which can have multiple parents) to the precise world of modules (which
/// always have one parent).
#[derive(Default, Debug, PartialEq, Eq)]
2018-11-28 02:09:44 +01:00
pub struct ModuleTree {
2019-01-04 14:15:50 +01:00
mods: Arena<ModuleId, ModuleData>,
links: Arena<LinkId, LinkData>,
2018-11-28 01:42:26 +01:00
}
2019-01-06 15:33:27 +01:00
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ModuleData {
2019-01-26 21:25:18 +01:00
file_id: HirFileId,
/// Points to `ast::Module`, `None` for the whole file.
decl_id: Option<SourceFileItemId>,
2019-01-06 15:33:27 +01:00
parent: Option<LinkId>,
children: Vec<LinkId>,
}
#[derive(Hash, Debug, PartialEq, Eq)]
struct LinkData {
2019-01-06 17:58:10 +01:00
source: SourceItemId,
2019-01-06 15:33:27 +01:00
owner: ModuleId,
name: Name,
points_to: Vec<ModuleId>,
problem: Option<Problem>,
}
2018-11-28 01:42:26 +01:00
impl ModuleTree {
pub(crate) fn module_tree_query(db: &impl HirDatabase, crate_id: CrateId) -> Arc<ModuleTree> {
2019-01-15 13:45:48 +01:00
db.check_canceled();
2019-01-23 16:09:45 +01:00
let mut res = ModuleTree::default();
res.init_crate(db, crate_id);
Arc::new(res)
2019-01-06 15:33:27 +01:00
}
2018-11-28 01:42:26 +01:00
pub(crate) fn modules<'a>(&'a self) -> impl Iterator<Item = ModuleId> + 'a {
self.mods.iter().map(|(id, _)| id)
}
2019-01-26 21:25:18 +01:00
pub(crate) fn find_module_by_source(
&self,
file_id: HirFileId,
decl_id: Option<SourceFileItemId>,
) -> Option<ModuleId> {
let (res, _) = self
.mods
.iter()
.find(|(_, m)| (m.file_id, m.decl_id) == (file_id, decl_id))?;
2019-01-06 17:58:10 +01:00
Some(res)
2018-11-28 01:42:26 +01:00
}
2019-01-23 15:52:26 +01:00
fn init_crate(&mut self, db: &impl HirDatabase, crate_id: CrateId) {
let crate_graph = db.crate_graph();
let file_id = crate_graph.crate_root(crate_id);
let source_root_id = db.file_source_root(file_id);
let source_root = db.source_root(source_root_id);
2019-01-26 21:25:18 +01:00
self.init_subtree(db, &source_root, None, file_id.into(), None);
2019-01-23 16:09:45 +01:00
}
fn init_subtree(
&mut self,
db: &impl HirDatabase,
source_root: &SourceRoot,
parent: Option<LinkId>,
2019-01-26 21:25:18 +01:00
file_id: HirFileId,
decl_id: Option<SourceFileItemId>,
2019-01-23 16:09:45 +01:00
) -> ModuleId {
2019-01-26 13:12:55 +01:00
let is_root = parent.is_none();
2019-01-23 16:09:45 +01:00
let id = self.alloc_mod(ModuleData {
2019-01-26 21:25:18 +01:00
file_id,
decl_id,
2019-01-23 16:09:45 +01:00
parent,
children: Vec::new(),
});
2019-01-26 21:25:18 +01:00
for sub in db.submodules(file_id, decl_id).iter() {
2019-01-23 16:09:45 +01:00
let link = self.alloc_link(LinkData {
2019-01-26 21:25:18 +01:00
source: SourceItemId {
file_id,
item_id: sub.decl_id,
},
2019-01-23 16:09:45 +01:00
name: sub.name.clone(),
owner: id,
points_to: Vec::new(),
problem: None,
});
let (points_to, problem) = if sub.is_declaration {
2019-01-26 21:25:18 +01:00
let (points_to, problem) = resolve_submodule(db, file_id, &sub.name);
2019-01-23 16:09:45 +01:00
let points_to = points_to
.into_iter()
2019-01-25 19:14:41 +01:00
.map(|file_id| {
2019-01-26 21:25:18 +01:00
self.init_subtree(db, source_root, Some(link), file_id.into(), None)
2019-01-23 16:09:45 +01:00
})
.collect::<Vec<_>>();
(points_to, problem)
} else {
2019-01-26 21:25:18 +01:00
let points_to =
self.init_subtree(db, source_root, Some(link), file_id, Some(sub.decl_id));
2019-01-23 16:09:45 +01:00
(vec![points_to], None)
};
self.links[link].points_to = points_to;
self.links[link].problem = problem;
}
id
}
2019-01-23 15:52:26 +01:00
fn alloc_mod(&mut self, data: ModuleData) -> ModuleId {
self.mods.alloc(data)
}
fn alloc_link(&mut self, data: LinkData) -> LinkId {
let owner = data.owner;
let id = self.links.alloc(data);
self.mods[owner].children.push(id);
id
}
2018-11-28 01:42:26 +01:00
}
impl ModuleId {
2019-01-26 21:25:18 +01:00
pub(crate) fn file_id(self, tree: &ModuleTree) -> HirFileId {
tree.mods[self].file_id
}
pub(crate) fn decl_id(self, tree: &ModuleTree) -> Option<SourceFileItemId> {
tree.mods[self].decl_id
2018-11-28 01:42:26 +01:00
}
2019-01-06 13:58:45 +01:00
pub(crate) fn parent_link(self, tree: &ModuleTree) -> Option<LinkId> {
2018-11-28 01:42:26 +01:00
tree.mods[self].parent
}
2019-01-06 12:05:03 +01:00
pub(crate) fn parent(self, tree: &ModuleTree) -> Option<ModuleId> {
2018-11-28 01:42:26 +01:00
let link = self.parent_link(tree)?;
Some(tree.links[link].owner)
}
2019-01-04 23:37:40 +01:00
pub(crate) fn crate_root(self, tree: &ModuleTree) -> ModuleId {
2018-11-28 01:42:26 +01:00
generate(Some(self), move |it| it.parent(tree))
.last()
.unwrap()
}
2019-01-04 23:37:40 +01:00
pub(crate) fn child(self, tree: &ModuleTree, name: &Name) -> Option<ModuleId> {
2018-11-28 01:42:26 +01:00
let link = tree.mods[self]
.children
.iter()
.map(|&it| &tree.links[it])
2018-12-27 18:07:21 +01:00
.find(|it| it.name == *name)?;
2018-11-28 01:42:26 +01:00
Some(*link.points_to.first()?)
}
2019-01-06 15:33:27 +01:00
pub(crate) fn children<'a>(
self,
tree: &'a ModuleTree,
) -> impl Iterator<Item = (Name, ModuleId)> + 'a {
2018-11-28 01:42:26 +01:00
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))
})
}
2019-01-06 13:58:45 +01:00
pub(crate) fn problems(
self,
tree: &ModuleTree,
db: &impl HirDatabase,
) -> Vec<(TreeArc<SyntaxNode>, Problem)> {
2018-11-28 01:42:26 +01:00
tree.mods[self]
.children
.iter()
2019-01-06 17:58:10 +01:00
.filter_map(|&link| {
let p = tree.links[link].problem.clone()?;
let s = link.source(tree, db);
2019-01-08 09:28:42 +01:00
let s = s.name().unwrap().syntax().to_owned();
2018-11-28 01:42:26 +01:00
Some((s, p))
})
.collect()
}
}
impl LinkId {
2019-01-06 13:58:45 +01:00
pub(crate) fn owner(self, tree: &ModuleTree) -> ModuleId {
2018-11-28 01:42:26 +01:00
tree.links[self].owner
}
2019-01-06 13:58:45 +01:00
pub(crate) fn name(self, tree: &ModuleTree) -> &Name {
2018-12-27 18:07:21 +01:00
&tree.links[self].name
2018-11-28 01:42:26 +01:00
}
pub(crate) fn source(self, tree: &ModuleTree, db: &impl HirDatabase) -> TreeArc<ast::Module> {
2019-01-06 17:58:10 +01:00
let syntax_node = db.file_item(tree.links[self].source);
2019-01-08 09:28:42 +01:00
ast::Module::cast(&syntax_node).unwrap().to_owned()
2018-11-28 01:42:26 +01:00
}
}
2019-01-06 15:33:27 +01:00
fn resolve_submodule(
db: &impl HirDatabase,
2019-01-06 17:58:10 +01:00
file_id: HirFileId,
2019-01-06 15:33:27 +01:00
name: &Name,
2019-01-26 13:12:55 +01:00
is_root: bool,
2019-01-06 15:33:27 +01:00
) -> (Vec<FileId>, Option<Problem>) {
// FIXME: handle submodules of inline modules properly
2019-01-06 17:58:10 +01:00
let file_id = file_id.original_file(db);
2019-01-06 15:33:27 +01:00
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");
2019-01-26 13:12:55 +01:00
let is_dir_owner = is_root || mod_name == "mod";
2019-01-06 15:33:27 +01:00
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::<Vec<_>>();
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)
}