complete imports

This commit is contained in:
Aleksey Kladov 2018-08-30 20:37:33 +03:00
parent 49e14a99ed
commit 80ab3433d3
3 changed files with 181 additions and 20 deletions

View file

@ -6,21 +6,38 @@ pub struct ModuleScope {
entries: Vec<Entry>, entries: Vec<Entry>,
} }
pub struct Entry {
node: SyntaxNode,
kind: EntryKind,
}
enum EntryKind {
Item, Import,
}
impl ModuleScope { impl ModuleScope {
pub fn new(m: ast::Root) -> ModuleScope { pub fn new(m: ast::Root) -> ModuleScope {
let entries = m.items().filter_map(|item| { let mut entries = Vec::new();
match item { for item in m.items() {
let entry = match item {
ast::ModuleItem::StructDef(item) => Entry::new(item), ast::ModuleItem::StructDef(item) => Entry::new(item),
ast::ModuleItem::EnumDef(item) => Entry::new(item), ast::ModuleItem::EnumDef(item) => Entry::new(item),
ast::ModuleItem::FnDef(item) => Entry::new(item), ast::ModuleItem::FnDef(item) => Entry::new(item),
ast::ModuleItem::ConstDef(item) => Entry::new(item), ast::ModuleItem::ConstDef(item) => Entry::new(item),
ast::ModuleItem::StaticDef(item) => Entry::new(item), ast::ModuleItem::StaticDef(item) => Entry::new(item),
ast::ModuleItem::TraitDef(item) => Entry::new(item), ast::ModuleItem::TraitDef(item) => Entry::new(item),
ast::ModuleItem::Module(item) => Entry::new(item),
ast::ModuleItem::UseItem(item) => {
if let Some(tree) = item.use_tree() {
collect_imports(tree, &mut entries);
}
continue;
},
ast::ModuleItem::ExternCrateItem(_) | ast::ModuleItem::ExternCrateItem(_) |
ast::ModuleItem::ImplItem(_) | ast::ModuleItem::ImplItem(_) => continue,
ast::ModuleItem::UseItem(_) => None };
} entries.extend(entry)
}).collect(); }
ModuleScope { entries } ModuleScope { entries }
} }
@ -30,20 +47,63 @@ impl ModuleScope {
} }
} }
pub struct Entry {
name: SyntaxNode,
}
impl Entry { impl Entry {
fn new<'a>(item: impl ast::NameOwner<'a>) -> Option<Entry> { fn new<'a>(item: impl ast::NameOwner<'a>) -> Option<Entry> {
let name = item.name()?; let name = item.name()?;
Some(Entry { name: name.syntax().owned() }) Some(Entry { node: name.syntax().owned(), kind: EntryKind::Item })
}
fn new_import(path: ast::Path) -> Option<Entry> {
let name_ref = path.segment()?.name_ref()?;
Some(Entry { node: name_ref.syntax().owned(), kind: EntryKind::Import })
} }
pub fn name(&self) -> SmolStr { pub fn name(&self) -> SmolStr {
self.ast().text() match self.kind {
} EntryKind::Item =>
fn ast(&self) -> ast::Name { ast::Name::cast(self.node.borrowed()).unwrap()
ast::Name::cast(self.name.borrowed()).unwrap() .text(),
EntryKind::Import =>
ast::NameRef::cast(self.node.borrowed()).unwrap()
.text(),
}
} }
} }
fn collect_imports(tree: ast::UseTree, acc: &mut Vec<Entry>) {
if let Some(use_tree_list) = tree.use_tree_list() {
return use_tree_list.use_trees().for_each(|it| collect_imports(it, acc));
}
if let Some(path) = tree.path() {
acc.extend(Entry::new_import(path));
}
}
#[cfg(test)]
mod tests {
use super::*;
use libsyntax2::File;
fn do_check(code: &str, expected: &[&str]) {
let file = File::parse(&code);
let scope = ModuleScope::new(file.ast());
let actual = scope.entries
.iter()
.map(|it| it.name())
.collect::<Vec<_>>();
assert_eq!(expected, actual.as_slice());
}
#[test]
fn test_module_scope() {
do_check("
struct Foo;
enum Bar {}
mod baz {}
fn quux() {}
use x::{
y::z,
t,
};
", &["Foo", "Bar", "baz", "quux", "z", "t"])
}
}

View file

@ -977,6 +977,7 @@ pub enum ModuleItem<'a> {
ExternCrateItem(ExternCrateItem<'a>), ExternCrateItem(ExternCrateItem<'a>),
ConstDef(ConstDef<'a>), ConstDef(ConstDef<'a>),
StaticDef(StaticDef<'a>), StaticDef(StaticDef<'a>),
Module(Module<'a>),
} }
impl<'a> AstNode<'a> for ModuleItem<'a> { impl<'a> AstNode<'a> for ModuleItem<'a> {
@ -991,6 +992,7 @@ impl<'a> AstNode<'a> for ModuleItem<'a> {
EXTERN_CRATE_ITEM => Some(ModuleItem::ExternCrateItem(ExternCrateItem { syntax })), EXTERN_CRATE_ITEM => Some(ModuleItem::ExternCrateItem(ExternCrateItem { syntax })),
CONST_DEF => Some(ModuleItem::ConstDef(ConstDef { syntax })), CONST_DEF => Some(ModuleItem::ConstDef(ConstDef { syntax })),
STATIC_DEF => Some(ModuleItem::StaticDef(StaticDef { syntax })), STATIC_DEF => Some(ModuleItem::StaticDef(StaticDef { syntax })),
MODULE => Some(ModuleItem::Module(Module { syntax })),
_ => None, _ => None,
} }
} }
@ -1005,6 +1007,7 @@ impl<'a> AstNode<'a> for ModuleItem<'a> {
ModuleItem::ExternCrateItem(inner) => inner.syntax(), ModuleItem::ExternCrateItem(inner) => inner.syntax(),
ModuleItem::ConstDef(inner) => inner.syntax(), ModuleItem::ConstDef(inner) => inner.syntax(),
ModuleItem::StaticDef(inner) => inner.syntax(), ModuleItem::StaticDef(inner) => inner.syntax(),
ModuleItem::Module(inner) => inner.syntax(),
} }
} }
} }
@ -1294,7 +1297,11 @@ impl<'a> AstNode<'a> for Path<'a> {
fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax } fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax }
} }
impl<'a> Path<'a> {} impl<'a> Path<'a> {
pub fn segment(self) -> Option<PathSegment<'a>> {
super::child_opt(self)
}
}
// PathExpr // PathExpr
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@ -1332,6 +1339,28 @@ impl<'a> AstNode<'a> for PathPat<'a> {
impl<'a> PathPat<'a> {} impl<'a> PathPat<'a> {}
// PathSegment
#[derive(Debug, Clone, Copy)]
pub struct PathSegment<'a> {
syntax: SyntaxNodeRef<'a>,
}
impl<'a> AstNode<'a> for PathSegment<'a> {
fn cast(syntax: SyntaxNodeRef<'a>) -> Option<Self> {
match syntax.kind() {
PATH_SEGMENT => Some(PathSegment { syntax }),
_ => None,
}
}
fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax }
}
impl<'a> PathSegment<'a> {
pub fn name_ref(self) -> Option<NameRef<'a>> {
super::child_opt(self)
}
}
// PathType // PathType
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct PathType<'a> { pub struct PathType<'a> {
@ -1989,7 +2018,59 @@ impl<'a> AstNode<'a> for UseItem<'a> {
fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax } fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax }
} }
impl<'a> UseItem<'a> {} impl<'a> UseItem<'a> {
pub fn use_tree(self) -> Option<UseTree<'a>> {
super::child_opt(self)
}
}
// UseTree
#[derive(Debug, Clone, Copy)]
pub struct UseTree<'a> {
syntax: SyntaxNodeRef<'a>,
}
impl<'a> AstNode<'a> for UseTree<'a> {
fn cast(syntax: SyntaxNodeRef<'a>) -> Option<Self> {
match syntax.kind() {
USE_TREE => Some(UseTree { syntax }),
_ => None,
}
}
fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax }
}
impl<'a> UseTree<'a> {
pub fn path(self) -> Option<Path<'a>> {
super::child_opt(self)
}
pub fn use_tree_list(self) -> Option<UseTreeList<'a>> {
super::child_opt(self)
}
}
// UseTreeList
#[derive(Debug, Clone, Copy)]
pub struct UseTreeList<'a> {
syntax: SyntaxNodeRef<'a>,
}
impl<'a> AstNode<'a> for UseTreeList<'a> {
fn cast(syntax: SyntaxNodeRef<'a>) -> Option<Self> {
match syntax.kind() {
USE_TREE_LIST => Some(UseTreeList { syntax }),
_ => None,
}
}
fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax }
}
impl<'a> UseTreeList<'a> {
pub fn use_trees(self) -> impl Iterator<Item = UseTree<'a>> + 'a {
super::children(self)
}
}
// WhereClause // WhereClause
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]

View file

@ -337,7 +337,7 @@ Grammar(
), ),
"ModuleItem": ( "ModuleItem": (
enum: ["StructDef", "EnumDef", "FnDef", "TraitDef", "ImplItem", enum: ["StructDef", "EnumDef", "FnDef", "TraitDef", "ImplItem",
"UseItem", "ExternCrateItem", "ConstDef", "StaticDef" ] "UseItem", "ExternCrateItem", "ConstDef", "StaticDef", "Module" ]
), ),
"TupleExpr": (), "TupleExpr": (),
@ -507,13 +507,33 @@ Grammar(
"Param": ( "Param": (
options: [["pat", "Pat"]], options: [["pat", "Pat"]],
), ),
"UseItem": (), "UseItem": (
options: [["use_tree", "UseTree"]]
),
"UseTree": (
options: [
["path", "Path"],
["use_tree_list", "UseTreeList"],
]
),
"UseTreeList": (
collections: [["use_trees", "UseTree"]]
),
"ExternCrateItem": (), "ExternCrateItem": (),
"ArgList": ( "ArgList": (
collections: [ collections: [
["args", "Expr"] ["args", "Expr"]
] ]
), ),
"Path": (), "Path": (
options: [
["segment", "PathSegment"]
]
),
"PathSegment": (
options: [
["name_ref", "NameRef"]
]
),
}, },
) )