Skip to content

Move completio to ra_analysis #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
623 changes: 619 additions & 4 deletions crates/ra_analysis/src/completion.rs

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions crates/ra_analysis/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ use salsa;
use crate::{
db,
Cancelable, Canceled,
descriptors::module::{SubmodulesQuery, ModuleTreeQuery, ModulesDatabase, ModuleScopeQuery},
descriptors::{
DescriptorDatabase, SubmodulesQuery, ModuleTreeQuery, ModuleScopeQuery,
FnSyntaxQuery, FnScopesQuery
},
symbol_index::SymbolIndex,
syntax_ptr::{SyntaxPtrDatabase, ResolveSyntaxPtrQuery},
FileId,
Expand Down Expand Up @@ -63,10 +66,12 @@ salsa::database_storage! {
fn file_lines() for FileLinesQuery;
fn file_symbols() for FileSymbolsQuery;
}
impl ModulesDatabase {
impl DescriptorDatabase {
fn module_tree() for ModuleTreeQuery;
fn module_descriptor() for SubmodulesQuery;
fn module_scope() for ModuleScopeQuery;
fn fn_syntax() for FnSyntaxQuery;
fn fn_scopes() for FnScopesQuery;
}
impl SyntaxPtrDatabase {
fn resolve_syntax_ptr() for ResolveSyntaxPtrQuery;
Expand Down
26 changes: 26 additions & 0 deletions crates/ra_analysis/src/descriptors/function/imp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use std::sync::Arc;

use ra_syntax::{
ast::{AstNode, FnDef, FnDefNode},
};

use crate::{
descriptors::{
DescriptorDatabase,
function::{FnId, FnScopes},
},
};

/// Resolve `FnId` to the corresponding `SyntaxNode`
/// TODO: this should return something more type-safe then `SyntaxNode`
pub(crate) fn fn_syntax(db: &impl DescriptorDatabase, fn_id: FnId) -> FnDefNode {
let syntax = db.resolve_syntax_ptr(fn_id.0);
let fn_def = FnDef::cast(syntax.borrowed()).unwrap();
FnDefNode::new(fn_def)
}

pub(crate) fn fn_scopes(db: &impl DescriptorDatabase, fn_id: FnId) -> Arc<FnScopes> {
let syntax = db.fn_syntax(fn_id);
let res = FnScopes::new(syntax.ast());
Arc::new(res)
}
83 changes: 83 additions & 0 deletions crates/ra_analysis/src/descriptors/function/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
pub(super) mod imp;
mod scope;

use ra_syntax::{
ast::{self, AstNode, NameOwner}
};

use crate::{
FileId,
syntax_ptr::SyntaxPtr
};

pub(crate) use self::scope::{FnScopes, resolve_local_name};


#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct FnId(SyntaxPtr);

impl FnId {
pub(crate) fn new(file_id: FileId, fn_def: ast::FnDef) -> FnId {
let ptr = SyntaxPtr::new(file_id, fn_def.syntax());
FnId(ptr)
}
}


#[derive(Debug, Clone)]
pub struct FnDescriptor {
pub name: String,
pub label: String,
pub ret_type: Option<String>,
pub params: Vec<String>,
}

impl FnDescriptor {
pub fn new(node: ast::FnDef) -> Option<Self> {
let name = node.name()?.text().to_string();

// Strip the body out for the label.
let label: String = if let Some(body) = node.body() {
let body_range = body.syntax().range();
let label: String = node
.syntax()
.children()
.filter(|child| !child.range().is_subrange(&body_range))
.map(|node| node.text().to_string())
.collect();
label
} else {
node.syntax().text().to_string()
};

let params = FnDescriptor::param_list(node);
let ret_type = node.ret_type().map(|r| r.syntax().text().to_string());

Some(FnDescriptor {
name,
ret_type,
params,
label,
})
}

fn param_list(node: ast::FnDef) -> Vec<String> {
let mut res = vec![];
if let Some(param_list) = node.param_list() {
if let Some(self_param) = param_list.self_param() {
res.push(self_param.syntax().text().to_string())
}

// Maybe use param.pat here? See if we can just extract the name?
//res.extend(param_list.params().map(|p| p.syntax().text().to_string()));
res.extend(
param_list
.params()
.filter_map(|p| p.pat())
.map(|pat| pat.syntax().text().to_string()),
);
}
res
}
}

Original file line number Diff line number Diff line change
@@ -1,29 +1,42 @@
use std::fmt;

use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};

use ra_syntax::{
algo::generate,
ast::{self, ArgListOwner, LoopBodyOwner, NameOwner},
AstNode, SmolStr, SyntaxNode, SyntaxNodeRef,
AstNode, SmolStr, SyntaxNodeRef,
};

type ScopeId = usize;
use crate::syntax_ptr::LocalSyntaxPtr;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct ScopeId(u32);

#[derive(Debug)]
#[derive(Debug, PartialEq, Eq)]
pub struct FnScopes {
pub self_param: Option<SyntaxNode>,
pub(crate) self_param: Option<LocalSyntaxPtr>,
scopes: Vec<ScopeData>,
scope_for: FxHashMap<SyntaxNode, ScopeId>,
scope_for: FxHashMap<LocalSyntaxPtr, ScopeId>,
}

#[derive(Debug, PartialEq, Eq)]
pub struct ScopeEntry {
name: SmolStr,
ptr: LocalSyntaxPtr,
}

#[derive(Debug, PartialEq, Eq)]
struct ScopeData {
parent: Option<ScopeId>,
entries: Vec<ScopeEntry>,
}

impl FnScopes {
pub fn new(fn_def: ast::FnDef) -> FnScopes {
pub(crate) fn new(fn_def: ast::FnDef) -> FnScopes {
let mut scopes = FnScopes {
self_param: fn_def
.param_list()
.and_then(|it| it.self_param())
.map(|it| it.syntax().owned()),
.map(|it| LocalSyntaxPtr::new(it.syntax())),
scopes: Vec::new(),
scope_for: FxHashMap::default(),
};
Expand All @@ -34,24 +47,24 @@ impl FnScopes {
}
scopes
}
pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
&self.scopes[scope].entries
pub(crate) fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
&self.get(scope).entries
}
pub fn scope_chain<'a>(&'a self, node: SyntaxNodeRef) -> impl Iterator<Item = ScopeId> + 'a {
generate(self.scope_for(node), move |&scope| {
self.scopes[scope].parent
self.get(scope).parent
})
}
fn root_scope(&mut self) -> ScopeId {
let res = self.scopes.len();
let res = ScopeId(self.scopes.len() as u32);
self.scopes.push(ScopeData {
parent: None,
entries: vec![],
});
res
}
fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
let res = self.scopes.len();
let res = ScopeId(self.scopes.len() as u32);
self.scopes.push(ScopeData {
parent: Some(parent),
entries: vec![],
Expand All @@ -64,7 +77,7 @@ impl FnScopes {
.descendants()
.filter_map(ast::BindPat::cast)
.filter_map(ScopeEntry::new);
self.scopes[scope].entries.extend(entries);
self.get_mut(scope).entries.extend(entries);
}
fn add_params_bindings(&mut self, scope: ScopeId, params: Option<ast::ParamList>) {
params
Expand All @@ -74,43 +87,36 @@ impl FnScopes {
.for_each(|it| self.add_bindings(scope, it));
}
fn set_scope(&mut self, node: SyntaxNodeRef, scope: ScopeId) {
self.scope_for.insert(node.owned(), scope);
self.scope_for.insert(LocalSyntaxPtr::new(node), scope);
}
fn scope_for(&self, node: SyntaxNodeRef) -> Option<ScopeId> {
node.ancestors()
.filter_map(|it| self.scope_for.get(&it.owned()).map(|&scope| scope))
.map(LocalSyntaxPtr::new)
.filter_map(|it| self.scope_for.get(&it).map(|&scope| scope))
.next()
}
}

pub struct ScopeEntry {
syntax: SyntaxNode,
fn get(&self, scope: ScopeId) -> &ScopeData {
&self.scopes[scope.0 as usize]
}
fn get_mut(&mut self, scope: ScopeId) -> &mut ScopeData {
&mut self.scopes[scope.0 as usize]
}
}

impl ScopeEntry {
fn new(pat: ast::BindPat) -> Option<ScopeEntry> {
if pat.name().is_some() {
Some(ScopeEntry {
syntax: pat.syntax().owned(),
})
} else {
None
}
}
pub fn name(&self) -> SmolStr {
self.ast().name().unwrap().text()
let name = pat.name()?;
let res = ScopeEntry {
name: name.text(),
ptr: LocalSyntaxPtr::new(pat.syntax()),
};
Some(res)
}
pub fn ast(&self) -> ast::BindPat {
ast::BindPat::cast(self.syntax.borrowed()).unwrap()
pub(crate) fn name(&self) -> &SmolStr {
&self.name
}
}

impl fmt::Debug for ScopeEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ScopeEntry")
.field("name", &self.name())
.field("syntax", &self.syntax)
.finish()
pub(crate) fn ptr(&self) -> LocalSyntaxPtr {
self.ptr
}
}

Expand Down Expand Up @@ -251,33 +257,28 @@ fn compute_expr_scopes(expr: ast::Expr, scopes: &mut FnScopes, scope: ScopeId) {
}
}

#[derive(Debug)]
struct ScopeData {
parent: Option<ScopeId>,
entries: Vec<ScopeEntry>,
}

pub fn resolve_local_name<'a>(
name_ref: ast::NameRef,
scopes: &'a FnScopes,
) -> Option<&'a ScopeEntry> {
use rustc_hash::FxHashSet;

let mut shadowed = FxHashSet::default();
let ret = scopes
.scope_chain(name_ref.syntax())
.flat_map(|scope| scopes.entries(scope).iter())
.filter(|entry| shadowed.insert(entry.name()))
.filter(|entry| entry.name() == name_ref.text())
.filter(|entry| entry.name() == &name_ref.text())
.nth(0);
ret
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{find_node_at_offset, test_utils::extract_offset};
use ra_syntax::File;
use test_utils::extract_offset;
use ra_editor::{find_node_at_offset};

use super::*;


fn do_check(code: &str, expected: &[&str]) {
let (off, code) = extract_offset(code);
Expand Down Expand Up @@ -384,14 +385,11 @@ mod tests {

let scopes = FnScopes::new(fn_def);

let local_name = resolve_local_name(name_ref, &scopes)
.unwrap()
.ast()
.name()
.unwrap();
let local_name_entry = resolve_local_name(name_ref, &scopes).unwrap();
let local_name = local_name_entry.ptr().resolve(&file);
let expected_name =
find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into()).unwrap();
assert_eq!(local_name.syntax().range(), expected_name.syntax().range());
assert_eq!(local_name.range(), expected_name.syntax().range());
}

#[test]
Expand Down
Loading