182: Module source r=matklad a=matklad



Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2018-11-01 10:53:17 +00:00
commit f6f9a0bf35
5 changed files with 114 additions and 38 deletions

View File

@ -148,7 +148,7 @@ fn complete_module_items(
this_item: Option<ast::NameRef>,
acc: &mut Vec<CompletionItem>,
) {
let scope = ModuleScope::from_items(items);
let scope = ModuleScope::new(items); // FIXME
acc.extend(
scope
.entries()

View File

@ -1,7 +1,7 @@
use std::sync::Arc;
use ra_syntax::{
ast::{self, NameOwner},
ast::{self, ModuleItemOwner, NameOwner},
SmolStr,
};
use relative_path::RelativePathBuf;
@ -14,7 +14,10 @@
Cancelable, FileId, FileResolverImp,
};
use super::{LinkData, LinkId, ModuleData, ModuleId, ModuleScope, ModuleTree, Problem};
use super::{
LinkData, LinkId, ModuleData, ModuleId, ModuleScope, ModuleSource, ModuleSourceNode,
ModuleTree, Problem,
};
pub(crate) fn submodules(
db: &impl DescriptorDatabase,
@ -43,9 +46,14 @@ pub(crate) fn module_scope(
module_id: ModuleId,
) -> Cancelable<Arc<ModuleScope>> {
let tree = db.module_tree(source_root_id)?;
let file_id = module_id.file_id(&tree);
let syntax = db.file_syntax(file_id);
let res = ModuleScope::new(&syntax);
let source = module_id.source(&tree).resolve(db);
let res = match source {
ModuleSourceNode::Root(root) => ModuleScope::new(root.ast().items()),
ModuleSourceNode::Inline(inline) => match inline.ast().item_list() {
Some(items) => ModuleScope::new(items.items()),
None => ModuleScope::new(std::iter::empty()),
},
};
Ok(Arc::new(res))
}
@ -106,7 +114,7 @@ fn build_subtree(
) -> Cancelable<ModuleId> {
visited.insert(file_id);
let id = tree.push_mod(ModuleData {
file_id,
source: ModuleSource::File(file_id),
parent,
children: Vec::new(),
});

View File

@ -7,10 +7,17 @@
};
use relative_path::RelativePathBuf;
use crate::FileId;
use crate::{db::SyntaxDatabase, syntax_ptr::SyntaxPtr, FileId};
pub(crate) use self::scope::ModuleScope;
/// 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(Debug, PartialEq, Eq, Hash)]
pub(crate) struct ModuleTree {
mods: Vec<ModuleData>,
@ -22,7 +29,7 @@ pub(crate) fn modules_for_file(&self, file_id: FileId) -> Vec<ModuleId> {
self.mods
.iter()
.enumerate()
.filter(|(_idx, it)| it.file_id == file_id)
.filter(|(_idx, it)| it.source.is_file(file_id))
.map(|(idx, _)| ModuleId(idx as u32))
.collect()
}
@ -32,6 +39,23 @@ pub(crate) fn any_module_for_file(&self, file_id: FileId) -> Option<ModuleId> {
}
}
/// `ModuleSource` is the syntax tree element that produced this module:
/// either a file, or an inlinde module.
/// TODO: we don't produce Inline modules yet
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum ModuleSource {
File(FileId),
#[allow(dead_code)]
Inline(SyntaxPtr),
}
/// An owned syntax node for a module. Unlike `ModuleSource`,
/// this holds onto the AST for the whole file.
enum ModuleSourceNode {
Root(ast::RootNode),
Inline(ast::ModuleNode),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub(crate) struct ModuleId(u32);
@ -50,8 +74,8 @@ pub enum Problem {
}
impl ModuleId {
pub(crate) fn file_id(self, tree: &ModuleTree) -> FileId {
tree.module(self).file_id
pub(crate) fn source(self, tree: &ModuleTree) -> ModuleSource {
tree.module(self).source
}
pub(crate) fn parent_link(self, tree: &ModuleTree) -> Option<LinkId> {
tree.module(self).parent
@ -82,14 +106,18 @@ pub(crate) fn child(self, tree: &ModuleTree, name: &str) -> Option<ModuleId> {
.find(|it| it.name == name)?;
Some(*link.points_to.first()?)
}
pub(crate) fn problems(self, tree: &ModuleTree, root: ast::Root) -> Vec<(SyntaxNode, Problem)> {
pub(crate) fn problems(
self,
tree: &ModuleTree,
db: &impl SyntaxDatabase,
) -> Vec<(SyntaxNode, Problem)> {
tree.module(self)
.children
.iter()
.filter_map(|&it| {
let p = tree.link(it).problem.clone()?;
let s = it.bind_source(tree, root);
let s = s.name().unwrap().syntax().owned();
let s = it.bind_source(tree, db);
let s = s.ast().name().unwrap().syntax().owned();
Some((s, p))
})
.collect()
@ -100,21 +128,62 @@ impl LinkId {
pub(crate) fn owner(self, tree: &ModuleTree) -> ModuleId {
tree.link(self).owner
}
pub(crate) fn bind_source<'a>(self, tree: &ModuleTree, root: ast::Root<'a>) -> ast::Module<'a> {
imp::modules(root)
.find(|(name, _)| name == &tree.link(self).name)
.unwrap()
.1
pub(crate) fn bind_source<'a>(
self,
tree: &ModuleTree,
db: &impl SyntaxDatabase,
) -> ast::ModuleNode {
let owner = self.owner(tree);
match owner.source(tree).resolve(db) {
ModuleSourceNode::Root(root) => {
let ast = imp::modules(root.ast())
.find(|(name, _)| name == &tree.link(self).name)
.unwrap()
.1;
ast.into()
}
ModuleSourceNode::Inline(..) => {
unimplemented!("https://github.com/rust-analyzer/rust-analyzer/issues/181")
}
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ModuleData {
file_id: FileId,
source: ModuleSource,
parent: Option<LinkId>,
children: Vec<LinkId>,
}
impl ModuleSource {
pub(crate) fn as_file(self) -> Option<FileId> {
match self {
ModuleSource::File(f) => Some(f),
ModuleSource::Inline(..) => None,
}
}
fn resolve(self, db: &impl SyntaxDatabase) -> ModuleSourceNode {
match self {
ModuleSource::File(file_id) => {
let syntax = db.file_syntax(file_id);
ModuleSourceNode::Root(syntax.ast().into())
}
ModuleSource::Inline(ptr) => {
let syntax = db.resolve_syntax_ptr(ptr);
let syntax = syntax.borrowed();
let module = ast::Module::cast(syntax).unwrap();
ModuleSourceNode::Inline(module.into())
}
}
}
fn is_file(self, file_id: FileId) -> bool {
self.as_file() == Some(file_id)
}
}
#[derive(Hash, Debug, PartialEq, Eq)]
struct LinkData {
owner: ModuleId,

View File

@ -1,9 +1,6 @@
//! Backend for module-level scope resolution & completion
use ra_syntax::{
ast::{self, ModuleItemOwner},
AstNode, File, SmolStr,
};
use ra_syntax::{ast, AstNode, SmolStr};
use crate::syntax_ptr::LocalSyntaxPtr;
@ -28,11 +25,7 @@ enum EntryKind {
}
impl ModuleScope {
pub fn new(file: &File) -> ModuleScope {
ModuleScope::from_items(file.ast().items())
}
pub fn from_items<'a>(items: impl Iterator<Item = ast::ModuleItem<'a>>) -> ModuleScope {
pub(crate) fn new<'a>(items: impl Iterator<Item = ast::ModuleItem<'a>>) -> ModuleScope {
let mut entries = Vec::new();
for item in items {
let entry = match item {
@ -102,11 +95,11 @@ fn collect_imports(tree: ast::UseTree, acc: &mut Vec<Entry>) {
#[cfg(test)]
mod tests {
use super::*;
use ra_syntax::File;
use ra_syntax::{ast::ModuleItemOwner, File};
fn do_check(code: &str, expected: &[&str]) {
let file = File::parse(&code);
let scope = ModuleScope::new(&file);
let scope = ModuleScope::new(file.ast().items());
let actual = scope.entries.iter().map(|it| it.name()).collect::<Vec<_>>();
assert_eq!(expected, actual.as_slice());
}

View File

@ -20,7 +20,7 @@
db::{self, FileSyntaxQuery, SyntaxDatabase},
descriptors::{
function::{FnDescriptor, FnId},
module::{ModuleTree, Problem},
module::{ModuleSource, ModuleTree, Problem},
DeclarationDescriptor, DescriptorDatabase,
},
input::{FilesDatabase, SourceRoot, SourceRootId, WORKSPACE},
@ -222,9 +222,15 @@ pub fn parent_module(&self, file_id: FileId) -> Cancelable<Vec<(FileId, FileSymb
.into_iter()
.filter_map(|module_id| {
let link = module_id.parent_link(&module_tree)?;
let file_id = link.owner(&module_tree).file_id(&module_tree);
let syntax = self.db.file_syntax(file_id);
let decl = link.bind_source(&module_tree, syntax.ast());
let file_id = match link.owner(&module_tree).source(&module_tree) {
ModuleSource::File(file_id) => file_id,
ModuleSource::Inline(..) => {
//TODO: https://github.com/rust-analyzer/rust-analyzer/issues/181
return None;
}
};
let decl = link.bind_source(&module_tree, &self.db);
let decl = decl.ast();
let sym = FileSymbol {
name: decl.name().unwrap().text(),
@ -243,7 +249,7 @@ pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
.modules_for_file(file_id)
.into_iter()
.map(|it| it.root(&module_tree))
.map(|it| it.file_id(&module_tree))
.filter_map(|it| it.source(&module_tree).as_file())
.filter_map(|it| crate_graph.crate_id_for_crate_root(it))
.collect();
@ -365,7 +371,7 @@ pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
})
.collect::<Vec<_>>();
if let Some(m) = module_tree.any_module_for_file(file_id) {
for (name_node, problem) in m.problems(&module_tree, syntax.ast()) {
for (name_node, problem) in m.problems(&module_tree, &self.db) {
let diag = match problem {
Problem::UnresolvedModule { candidate } => {
let create_file = FileSystemEdit::CreateFile {
@ -533,7 +539,7 @@ fn resolve_module(
};
module_id
.child(module_tree, name.as_str())
.map(|it| it.file_id(module_tree))
.and_then(|it| it.source(&module_tree).as_file())
.into_iter()
.collect()
}