Skip to content

Commit fbbee53

Browse files
committed
Add ModuleScope as a query
This is a first step towards queryifing completion and resolve. Some code currently duplicates ra_editor: the plan is to move all completion from ra_editor, but it'll take more than one commit.
1 parent d102145 commit fbbee53

File tree

8 files changed

+223
-22
lines changed

8 files changed

+223
-22
lines changed

crates/ra_analysis/src/completion.rs

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,51 @@
1-
use ra_editor::{CompletionItem, find_node_at_offset, complete_module_items};
1+
use ra_editor::{CompletionItem, find_node_at_offset};
22
use ra_syntax::{
33
AtomEdit, File, TextUnit, AstNode,
4-
ast::{self, ModuleItemOwner},
4+
ast::{self, ModuleItemOwner, AstChildren},
55
};
66

77
use crate::{
88
FileId, Cancelable,
99
input::FilesDatabase,
1010
db::{self, SyntaxDatabase},
11-
descriptors::module::{ModulesDatabase, ModuleTree, ModuleId},
11+
descriptors::module::{ModulesDatabase, ModuleTree, ModuleId, scope::ModuleScope},
1212
};
1313

1414
pub(crate) fn resolve_based_completion(db: &db::RootDatabase, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> {
1515
let source_root_id = db.file_source_root(file_id);
1616
let file = db.file_syntax(file_id);
1717
let module_tree = db.module_tree(source_root_id)?;
18+
let module_id = match module_tree.any_module_for_file(file_id) {
19+
None => return Ok(None),
20+
Some(it) => it,
21+
};
1822
let file = {
1923
let edit = AtomEdit::insert(offset, "intellijRulezz".to_string());
2024
file.reparse(&edit)
2125
};
22-
let target_file = match find_target_module(&module_tree, file_id, &file, offset) {
26+
let target_module_id = match find_target_module(&module_tree, module_id, &file, offset) {
2327
None => return Ok(None),
24-
Some(target_module) => {
25-
let file_id = target_module.file_id(&module_tree);
26-
db.file_syntax(file_id)
27-
}
28+
Some(it) => it,
2829
};
29-
let mut res = Vec::new();
30-
complete_module_items(target_file.ast().items(), None, &mut res);
30+
let module_scope = db.module_scope(source_root_id, target_module_id)?;
31+
let res: Vec<_> = module_scope
32+
.entries()
33+
.iter()
34+
.map(|entry| CompletionItem {
35+
label: entry.name().to_string(),
36+
lookup: None,
37+
snippet: None,
38+
})
39+
.collect();
3140
Ok(Some(res))
3241
}
3342

34-
pub(crate) fn find_target_module(module_tree: &ModuleTree, file_id: FileId, file: &File, offset: TextUnit) -> Option<ModuleId> {
43+
44+
45+
pub(crate) fn find_target_module(module_tree: &ModuleTree, module_id: ModuleId, file: &File, offset: TextUnit) -> Option<ModuleId> {
3546
let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), offset)?;
3647
let mut crate_path = crate_path(name_ref)?;
37-
let module_id = module_tree.any_module_for_file(file_id)?;
48+
3849
crate_path.pop();
3950
let mut target_module = module_id.root(&module_tree);
4051
for name in crate_path {

crates/ra_analysis/src/db.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ use salsa;
99
use crate::{
1010
db,
1111
Cancelable, Canceled,
12-
descriptors::module::{SubmodulesQuery, ModuleTreeQuery, ModulesDatabase},
12+
descriptors::module::{SubmodulesQuery, ModuleTreeQuery, ModulesDatabase, ModuleScopeQuery},
1313
symbol_index::SymbolIndex,
14+
syntax_ptr::{SyntaxPtrDatabase, ResolveSyntaxPtrQuery},
1415
FileId,
1516
};
1617

@@ -65,6 +66,10 @@ salsa::database_storage! {
6566
impl ModulesDatabase {
6667
fn module_tree() for ModuleTreeQuery;
6768
fn module_descriptor() for SubmodulesQuery;
69+
fn module_scope() for ModuleScopeQuery;
70+
}
71+
impl SyntaxPtrDatabase {
72+
fn resolve_syntax_ptr() for ResolveSyntaxPtrQuery;
6873
}
6974
}
7075
}

crates/ra_analysis/src/descriptors/module/imp.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::{
1313
};
1414

1515
use super::{
16-
ModuleData, ModuleTree, ModuleId, LinkId, LinkData, Problem, ModulesDatabase
16+
ModuleData, ModuleTree, ModuleId, LinkId, LinkData, Problem, ModulesDatabase, ModuleScope
1717
};
1818

1919

@@ -35,6 +35,18 @@ pub(super) fn modules(root: ast::Root<'_>) -> impl Iterator<Item = (SmolStr, ast
3535
})
3636
}
3737

38+
pub(super) fn module_scope(
39+
db: &impl ModulesDatabase,
40+
source_root_id: SourceRootId,
41+
module_id: ModuleId,
42+
) -> Cancelable<Arc<ModuleScope>> {
43+
let tree = db.module_tree(source_root_id)?;
44+
let file_id = module_id.file_id(&tree);
45+
let syntax = db.file_syntax(file_id);
46+
let res = ModuleScope::new(&syntax);
47+
Ok(Arc::new(res))
48+
}
49+
3850
pub(super) fn module_tree(
3951
db: &impl ModulesDatabase,
4052
source_root: SourceRootId,

crates/ra_analysis/src/descriptors/module/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod imp;
2+
pub(crate) mod scope;
23

34
use std::sync::Arc;
45

@@ -11,6 +12,8 @@ use crate::{
1112
input::SourceRootId,
1213
};
1314

15+
pub(crate) use self::scope::ModuleScope;
16+
1417
salsa::query_group! {
1518
pub(crate) trait ModulesDatabase: SyntaxDatabase {
1619
fn module_tree(source_root_id: SourceRootId) -> Cancelable<Arc<ModuleTree>> {
@@ -21,6 +24,10 @@ salsa::query_group! {
2124
type SubmodulesQuery;
2225
use fn imp::submodules;
2326
}
27+
fn module_scope(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable<Arc<ModuleScope>> {
28+
type ModuleScopeQuery;
29+
use fn imp::module_scope;
30+
}
2431
}
2532
}
2633

@@ -78,6 +85,7 @@ impl ModuleId {
7885
while let Some(next) = curr.parent(tree) {
7986
curr = next;
8087
i += 1;
88+
// simplistic cycle detection
8189
if i > 100 {
8290
return self;
8391
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
//! Backend for module-level scope resolution & completion
2+
3+
4+
use ra_syntax::{
5+
ast::{self, AstChildren, ModuleItemOwner},
6+
File, AstNode, SmolStr, SyntaxNode, SyntaxNodeRef,
7+
};
8+
9+
use crate::syntax_ptr::LocalSyntaxPtr;
10+
11+
/// `ModuleScope` contains all named items declared in the scope.
12+
#[derive(Debug, PartialEq, Eq)]
13+
pub(crate) struct ModuleScope {
14+
entries: Vec<Entry>,
15+
}
16+
17+
/// `Entry` is a single named declaration iside a module.
18+
#[derive(Debug, PartialEq, Eq)]
19+
pub(crate) struct Entry {
20+
ptr: LocalSyntaxPtr,
21+
kind: EntryKind,
22+
name: SmolStr,
23+
}
24+
25+
#[derive(Debug, PartialEq, Eq)]
26+
enum EntryKind {
27+
Item,
28+
Import,
29+
}
30+
31+
impl ModuleScope {
32+
pub fn new(file: &File) -> ModuleScope {
33+
let mut entries = Vec::new();
34+
for item in file.ast().items() {
35+
let entry = match item {
36+
ast::ModuleItem::StructDef(item) => Entry::new(item),
37+
ast::ModuleItem::EnumDef(item) => Entry::new(item),
38+
ast::ModuleItem::FnDef(item) => Entry::new(item),
39+
ast::ModuleItem::ConstDef(item) => Entry::new(item),
40+
ast::ModuleItem::StaticDef(item) => Entry::new(item),
41+
ast::ModuleItem::TraitDef(item) => Entry::new(item),
42+
ast::ModuleItem::TypeDef(item) => Entry::new(item),
43+
ast::ModuleItem::Module(item) => Entry::new(item),
44+
ast::ModuleItem::UseItem(item) => {
45+
if let Some(tree) = item.use_tree() {
46+
collect_imports(tree, &mut entries);
47+
}
48+
continue;
49+
}
50+
ast::ModuleItem::ExternCrateItem(_) | ast::ModuleItem::ImplItem(_) => continue,
51+
};
52+
entries.extend(entry)
53+
}
54+
55+
ModuleScope { entries }
56+
}
57+
58+
pub fn entries(&self) -> &[Entry] {
59+
self.entries.as_slice()
60+
}
61+
}
62+
63+
impl Entry {
64+
fn new<'a>(item: impl ast::NameOwner<'a>) -> Option<Entry> {
65+
let name = item.name()?;
66+
Some(Entry {
67+
name: name.text(),
68+
ptr: LocalSyntaxPtr::new(name.syntax()),
69+
kind: EntryKind::Item,
70+
})
71+
}
72+
fn new_import(path: ast::Path) -> Option<Entry> {
73+
let name_ref = path.segment()?.name_ref()?;
74+
Some(Entry {
75+
name: name_ref.text(),
76+
ptr: LocalSyntaxPtr::new(name_ref.syntax()),
77+
kind: EntryKind::Import,
78+
})
79+
}
80+
pub fn name(&self) -> &SmolStr {
81+
&self.name
82+
}
83+
pub fn ptr(&self) -> LocalSyntaxPtr {
84+
self.ptr
85+
}
86+
}
87+
88+
fn collect_imports(tree: ast::UseTree, acc: &mut Vec<Entry>) {
89+
if let Some(use_tree_list) = tree.use_tree_list() {
90+
return use_tree_list
91+
.use_trees()
92+
.for_each(|it| collect_imports(it, acc));
93+
}
94+
if let Some(path) = tree.path() {
95+
acc.extend(Entry::new_import(path));
96+
}
97+
}
98+
99+
#[cfg(test)]
100+
mod tests {
101+
use super::*;
102+
use ra_syntax::{ast::ModuleItemOwner, File};
103+
104+
fn do_check(code: &str, expected: &[&str]) {
105+
let file = File::parse(&code);
106+
let scope = ModuleScope::new(&file);
107+
let actual = scope.entries.iter().map(|it| it.name()).collect::<Vec<_>>();
108+
assert_eq!(expected, actual.as_slice());
109+
}
110+
111+
#[test]
112+
fn test_module_scope() {
113+
do_check(
114+
"
115+
struct Foo;
116+
enum Bar {}
117+
mod baz {}
118+
fn quux() {}
119+
use x::{
120+
y::z,
121+
t,
122+
};
123+
type T = ();
124+
",
125+
&["Foo", "Bar", "baz", "quux", "z", "t", "T"],
126+
)
127+
}
128+
}

crates/ra_analysis/src/syntax_ptr.rs

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::marker::PhantomData;
2+
13
use ra_syntax::{
24
File, TextRange, SyntaxKind, SyntaxNode, SyntaxNodeRef,
35
ast::{self, AstNode},
@@ -6,10 +8,24 @@ use ra_syntax::{
68
use crate::FileId;
79
use crate::db::SyntaxDatabase;
810

11+
salsa::query_group! {
12+
pub(crate) trait SyntaxPtrDatabase: SyntaxDatabase {
13+
fn resolve_syntax_ptr(ptr: SyntaxPtr) -> SyntaxNode {
14+
type ResolveSyntaxPtrQuery;
15+
storage volatile;
16+
}
17+
}
18+
}
19+
20+
fn resolve_syntax_ptr(db: &impl SyntaxDatabase, ptr: SyntaxPtr) -> SyntaxNode {
21+
let syntax = db.file_syntax(ptr.file_id);
22+
ptr.local.resolve(&syntax)
23+
}
24+
925
/// SyntaxPtr is a cheap `Copy` id which identifies a particular syntax node,
1026
/// without retainig syntax tree in memory. You need to explicitelly `resovle`
1127
/// `SyntaxPtr` to get a `SyntaxNode`
12-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1329
pub(crate) struct SyntaxPtr {
1430
file_id: FileId,
1531
local: LocalSyntaxPtr,
@@ -20,30 +36,43 @@ impl SyntaxPtr {
2036
let local = LocalSyntaxPtr::new(node);
2137
SyntaxPtr { file_id, local }
2238
}
39+
}
40+
41+
struct OwnedAst<T> {
42+
syntax: SyntaxNode,
43+
phantom: PhantomData<T>,
44+
}
45+
46+
trait ToAst {
47+
type Ast;
48+
fn to_ast(self) -> Self::Ast;
49+
}
2350

24-
pub(crate) fn resolve(self, db: &impl SyntaxDatabase) -> SyntaxNode {
25-
let syntax = db.file_syntax(self.file_id);
26-
self.local.resolve(&syntax)
51+
impl<'a> ToAst for &'a OwnedAst<ast::FnDef<'static>> {
52+
type Ast = ast::FnDef<'a>;
53+
fn to_ast(self) -> ast::FnDef<'a> {
54+
ast::FnDef::cast(self.syntax.borrowed())
55+
.unwrap()
2756
}
2857
}
2958

3059

3160
/// A pionter to a syntax node inside a file.
32-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33-
struct LocalSyntaxPtr {
61+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62+
pub(crate) struct LocalSyntaxPtr {
3463
range: TextRange,
3564
kind: SyntaxKind,
3665
}
3766

3867
impl LocalSyntaxPtr {
39-
fn new(node: SyntaxNodeRef) -> LocalSyntaxPtr {
68+
pub(crate) fn new(node: SyntaxNodeRef) -> LocalSyntaxPtr {
4069
LocalSyntaxPtr {
4170
range: node.range(),
4271
kind: node.kind(),
4372
}
4473
}
4574

46-
fn resolve(self, file: &File) -> SyntaxNode {
75+
pub(crate) fn resolve(self, file: &File) -> SyntaxNode {
4776
let mut curr = file.syntax();
4877
loop {
4978
if curr.range() == self.range && curr.kind() == self.kind {

crates/ra_editor/src/completion.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/// FIXME: move completion from ra_editor to ra_analysis
2+
13
use rustc_hash::{FxHashMap, FxHashSet};
24

35
use ra_syntax::{

crates/ra_editor/src/scope/mod_scope.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
/// FIXME: this is now moved to ra_analysis::descriptors::module::scope.
2+
///
3+
/// Current copy will be deleted as soon as we move the rest of the completion
4+
/// to the analyezer.
5+
6+
17
use ra_syntax::{
28
ast::{self, AstChildren},
39
AstNode, SmolStr, SyntaxNode, SyntaxNodeRef,

0 commit comments

Comments
 (0)