2862: Move from `from_source` to `SourceBinder` r=matklad a=matklad

bors r+

Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2020-01-16 16:58:13 +00:00 committed by GitHub
commit d3c4fbbbc4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 306 additions and 430 deletions

View file

@ -1,6 +1,6 @@
//! This module defines `AssistCtx` -- the API surface that is exposed to assists.
use either::Either;
use hir::{db::HirDatabase, InFile, SourceAnalyzer};
use hir::{db::HirDatabase, InFile, SourceAnalyzer, SourceBinder};
use ra_db::FileRange;
use ra_fmt::{leading_indent, reindent};
use ra_syntax::{
@ -142,12 +142,16 @@ impl<'a, DB: HirDatabase> AssistCtx<'a, DB> {
pub(crate) fn covering_element(&self) -> SyntaxElement {
find_covering_element(self.source_file.syntax(), self.frange.range)
}
pub(crate) fn source_binder(&self) -> SourceBinder<'a, DB> {
SourceBinder::new(self.db)
}
pub(crate) fn source_analyzer(
&self,
node: &SyntaxNode,
offset: Option<TextUnit>,
) -> SourceAnalyzer {
SourceAnalyzer::new(self.db, InFile::new(self.frange.file_id.into(), node), offset)
let src = InFile::new(self.frange.file_id.into(), node);
self.source_binder().analyze(src, offset)
}
pub(crate) fn covering_node_for_range(&self, range: TextRange) -> SyntaxElement {

View file

@ -1,5 +1,5 @@
use format_buf::format;
use hir::{db::HirDatabase, FromSource, InFile};
use hir::{db::HirDatabase, InFile};
use join_to_string::join;
use ra_syntax::{
ast::{
@ -136,15 +136,16 @@ fn find_struct_impl(
let module = strukt.syntax().ancestors().find(|node| {
ast::Module::can_cast(node.kind()) || ast::SourceFile::can_cast(node.kind())
})?;
let mut sb = ctx.source_binder();
let struct_ty = {
let src = InFile { file_id: ctx.frange.file_id.into(), value: strukt.clone() };
hir::Struct::from_source(db, src)?.ty(db)
sb.to_def(src)?.ty(db)
};
let block = module.descendants().filter_map(ast::ImplBlock::cast).find_map(|impl_blk| {
let src = InFile { file_id: ctx.frange.file_id.into(), value: impl_blk.clone() };
let blk = hir::ImplBlock::from_source(db, src)?;
let blk = sb.to_def(src)?;
let same_ty = blk.target_ty(db) == struct_ty;
let not_trait_impl = blk.target_trait(db).is_none();

View file

@ -1,265 +0,0 @@
//! Finds a corresponding hir data structure for a syntax node in a specific
//! file.
use hir_def::{
child_by_source::ChildBySource, dyn_map::DynMap, keys, keys::Key, nameres::ModuleSource,
ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, ImplId, ModuleId,
StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId,
};
use hir_expand::{name::AsName, AstId, MacroDefId, MacroDefKind};
use ra_db::FileId;
use ra_prof::profile;
use ra_syntax::{
ast::{self, AstNode, NameOwner},
match_ast, SyntaxNode,
};
use crate::{
db::{DefDatabase, HirDatabase},
Const, DefWithBody, Enum, EnumVariant, FieldSource, Function, ImplBlock, InFile, Local,
MacroDef, Module, Static, Struct, StructField, Trait, TypeAlias, TypeParam, Union,
};
pub trait FromSource: Sized {
type Ast;
fn from_source(db: &impl DefDatabase, src: InFile<Self::Ast>) -> Option<Self>;
}
pub trait FromSourceByContainer: Sized {
type Ast: AstNode + 'static;
type Id: Copy + 'static;
const KEY: Key<Self::Ast, Self::Id>;
}
impl<T: FromSourceByContainer> FromSource for T
where
T: From<<T as FromSourceByContainer>::Id>,
{
type Ast = <T as FromSourceByContainer>::Ast;
fn from_source(db: &impl DefDatabase, src: InFile<Self::Ast>) -> Option<Self> {
analyze_container(db, src.as_ref().map(|it| it.syntax()))[T::KEY]
.get(&src)
.copied()
.map(Self::from)
}
}
macro_rules! from_source_by_container_impls {
($(($hir:ident, $id:ident, $ast:path, $key:path)),* ,) => {$(
impl FromSourceByContainer for $hir {
type Ast = $ast;
type Id = $id;
const KEY: Key<Self::Ast, Self::Id> = $key;
}
)*}
}
from_source_by_container_impls![
(Struct, StructId, ast::StructDef, keys::STRUCT),
(Union, UnionId, ast::UnionDef, keys::UNION),
(Enum, EnumId, ast::EnumDef, keys::ENUM),
(Trait, TraitId, ast::TraitDef, keys::TRAIT),
(Function, FunctionId, ast::FnDef, keys::FUNCTION),
(Static, StaticId, ast::StaticDef, keys::STATIC),
(Const, ConstId, ast::ConstDef, keys::CONST),
(TypeAlias, TypeAliasId, ast::TypeAliasDef, keys::TYPE_ALIAS),
(ImplBlock, ImplId, ast::ImplBlock, keys::IMPL),
];
impl FromSource for MacroDef {
type Ast = ast::MacroCall;
fn from_source(db: &impl DefDatabase, src: InFile<Self::Ast>) -> Option<Self> {
let kind = MacroDefKind::Declarative;
let module_src = ModuleSource::from_child_node(db, src.as_ref().map(|it| it.syntax()));
let module = Module::from_definition(db, InFile::new(src.file_id, module_src))?;
let krate = Some(module.krate().id);
let ast_id = Some(AstId::new(src.file_id, db.ast_id_map(src.file_id).ast_id(&src.value)));
let id: MacroDefId = MacroDefId { krate, ast_id, kind };
Some(MacroDef { id })
}
}
impl FromSource for EnumVariant {
type Ast = ast::EnumVariant;
fn from_source(db: &impl DefDatabase, src: InFile<Self::Ast>) -> Option<Self> {
let parent_enum = src.value.parent_enum();
let src_enum = InFile { file_id: src.file_id, value: parent_enum };
let parent_enum = Enum::from_source(db, src_enum)?;
parent_enum.id.child_by_source(db)[keys::ENUM_VARIANT]
.get(&src)
.copied()
.map(EnumVariant::from)
}
}
impl FromSource for StructField {
type Ast = FieldSource;
fn from_source(db: &impl DefDatabase, src: InFile<Self::Ast>) -> Option<Self> {
let src = src.as_ref();
// FIXME this is buggy
let variant_id: VariantId = match src.value {
FieldSource::Named(field) => {
let value = field.syntax().ancestors().find_map(ast::StructDef::cast)?;
let src = InFile { file_id: src.file_id, value };
let def = Struct::from_source(db, src)?;
def.id.into()
}
FieldSource::Pos(field) => {
let value = field.syntax().ancestors().find_map(ast::EnumVariant::cast)?;
let src = InFile { file_id: src.file_id, value };
let def = EnumVariant::from_source(db, src)?;
EnumVariantId::from(def).into()
}
};
let dyn_map = variant_id.child_by_source(db);
match src.value {
FieldSource::Pos(it) => dyn_map[keys::TUPLE_FIELD].get(&src.with_value(it.clone())),
FieldSource::Named(it) => dyn_map[keys::RECORD_FIELD].get(&src.with_value(it.clone())),
}
.copied()
.map(StructField::from)
}
}
impl Local {
pub fn from_source(db: &impl HirDatabase, src: InFile<ast::BindPat>) -> Option<Self> {
let file_id = src.file_id;
let parent: DefWithBody = src.value.syntax().ancestors().find_map(|it| {
let res = match_ast! {
match it {
ast::ConstDef(value) => { Const::from_source(db, InFile { value, file_id})?.into() },
ast::StaticDef(value) => { Static::from_source(db, InFile { value, file_id})?.into() },
ast::FnDef(value) => { Function::from_source(db, InFile { value, file_id})?.into() },
_ => return None,
}
};
Some(res)
})?;
let (_body, source_map) = db.body_with_source_map(parent.into());
let src = src.map(ast::Pat::from);
let pat_id = source_map.node_pat(src.as_ref())?;
Some(Local { parent, pat_id })
}
}
impl TypeParam {
pub fn from_source(db: &impl HirDatabase, src: InFile<ast::TypeParam>) -> Option<Self> {
let file_id = src.file_id;
let parent: GenericDefId = src.value.syntax().ancestors().find_map(|it| {
let res = match_ast! {
match it {
ast::FnDef(value) => { Function::from_source(db, InFile { value, file_id})?.id.into() },
ast::StructDef(value) => { Struct::from_source(db, InFile { value, file_id})?.id.into() },
ast::EnumDef(value) => { Enum::from_source(db, InFile { value, file_id})?.id.into() },
ast::TraitDef(value) => { Trait::from_source(db, InFile { value, file_id})?.id.into() },
ast::TypeAliasDef(value) => { TypeAlias::from_source(db, InFile { value, file_id})?.id.into() },
ast::ImplBlock(value) => { ImplBlock::from_source(db, InFile { value, file_id})?.id.into() },
_ => return None,
}
};
Some(res)
})?;
let &id = parent.child_by_source(db)[keys::TYPE_PARAM].get(&src)?;
Some(TypeParam { id })
}
}
impl Module {
pub fn from_declaration(db: &impl DefDatabase, src: InFile<ast::Module>) -> Option<Self> {
let _p = profile("Module::from_declaration");
let parent_declaration = src.value.syntax().ancestors().skip(1).find_map(ast::Module::cast);
let parent_module = match parent_declaration {
Some(parent_declaration) => {
let src_parent = InFile { file_id: src.file_id, value: parent_declaration };
Module::from_declaration(db, src_parent)
}
None => {
let source_file = db.parse(src.file_id.original_file(db)).tree();
let src_parent =
InFile { file_id: src.file_id, value: ModuleSource::SourceFile(source_file) };
Module::from_definition(db, src_parent)
}
}?;
let child_name = src.value.name()?.as_name();
let def_map = db.crate_def_map(parent_module.id.krate);
let child_id = def_map[parent_module.id.local_id].children.get(&child_name)?;
Some(parent_module.with_module_id(*child_id))
}
pub fn from_definition(db: &impl DefDatabase, src: InFile<ModuleSource>) -> Option<Self> {
let _p = profile("Module::from_definition");
match src.value {
ModuleSource::Module(ref module) => {
assert!(!module.has_semi());
return Module::from_declaration(
db,
InFile { file_id: src.file_id, value: module.clone() },
);
}
ModuleSource::SourceFile(_) => (),
};
let original_file = src.file_id.original_file(db);
Module::from_file(db, original_file)
}
fn from_file(db: &impl DefDatabase, file: FileId) -> Option<Self> {
let _p = profile("Module::from_file");
let (krate, local_id) = db.relevant_crates(file).iter().find_map(|&crate_id| {
let crate_def_map = db.crate_def_map(crate_id);
let local_id = crate_def_map.modules_for_file(file).next()?;
Some((crate_id, local_id))
})?;
Some(Module { id: ModuleId { krate, local_id } })
}
}
fn analyze_container(db: &impl DefDatabase, src: InFile<&SyntaxNode>) -> DynMap {
let _p = profile("analyze_container");
return child_by_source(db, src).unwrap_or_default();
fn child_by_source(db: &impl DefDatabase, src: InFile<&SyntaxNode>) -> Option<DynMap> {
for container in src.value.ancestors().skip(1) {
let res = match_ast! {
match container {
ast::TraitDef(it) => {
let def = Trait::from_source(db, src.with_value(it))?;
def.id.child_by_source(db)
},
ast::ImplBlock(it) => {
let def = ImplBlock::from_source(db, src.with_value(it))?;
def.id.child_by_source(db)
},
ast::FnDef(it) => {
let def = Function::from_source(db, src.with_value(it))?;
DefWithBodyId::from(def.id)
.child_by_source(db)
},
ast::StaticDef(it) => {
let def = Static::from_source(db, src.with_value(it))?;
DefWithBodyId::from(def.id)
.child_by_source(db)
},
ast::ConstDef(it) => {
let def = Const::from_source(db, src.with_value(it))?;
DefWithBodyId::from(def.id)
.child_by_source(db)
},
_ => { continue },
}
};
return Some(res);
}
let module_source = ModuleSource::from_child_node(db, src);
let c = Module::from_definition(db, src.with_value(module_source))?;
Some(c.id.child_by_source(db))
}
}

View file

@ -36,7 +36,6 @@ mod from_id;
mod code_model;
mod has_source;
mod from_source;
pub use crate::{
code_model::{
@ -45,7 +44,6 @@ pub use crate::{
MacroDef, Module, ModuleDef, ScopeDef, Static, Struct, StructField, Trait, Type, TypeAlias,
TypeParam, Union, VariantDef,
},
from_source::FromSource,
has_source::HasSource,
source_analyzer::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer},
source_binder::SourceBinder,

View file

@ -1,22 +1,24 @@
//! `SourceBinder` should be the main entry point for getting info about source code.
//! `SourceBinder` is the main entry point for getting info about source code.
//! It's main task is to map source syntax trees to hir-level IDs.
//!
//! It is intended to subsume `FromSource` and `SourceAnalyzer`.
use hir_def::{
child_by_source::ChildBySource,
dyn_map::DynMap,
keys::{self, Key},
resolver::{HasResolver, Resolver},
ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, ImplId, ModuleId, StaticId,
StructFieldId, StructId, TraitId, TypeAliasId, UnionId, VariantId,
ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, ImplId, ModuleId,
StaticId, StructFieldId, StructId, TraitId, TypeAliasId, UnionId, VariantId,
};
use hir_expand::InFile;
use hir_expand::{name::AsName, AstId, InFile, MacroDefId, MacroDefKind};
use ra_prof::profile;
use ra_syntax::{ast, match_ast, AstNode, SyntaxNode, TextUnit};
use ra_syntax::{
ast::{self, NameOwner},
match_ast, AstNode, SyntaxNode, TextUnit,
};
use rustc_hash::FxHashMap;
use crate::{db::HirDatabase, ModuleSource, SourceAnalyzer};
use crate::{db::HirDatabase, Local, Module, SourceAnalyzer, TypeParam};
use ra_db::FileId;
pub struct SourceBinder<'a, DB> {
pub db: &'a DB,
@ -48,32 +50,27 @@ impl<DB: HirDatabase> SourceBinder<'_, DB> {
ChildContainer::ModuleId(it) => it.resolver(self.db),
ChildContainer::EnumId(it) => it.resolver(self.db),
ChildContainer::VariantId(it) => it.resolver(self.db),
ChildContainer::GenericDefId(it) => it.resolver(self.db),
};
SourceAnalyzer::new_for_resolver(resolver, src)
}
pub fn to_def<D, T>(&mut self, src: InFile<T>) -> Option<D>
where
D: From<T::ID>,
T: ToId,
{
let id: T::ID = self.to_id(src)?;
Some(id.into())
pub fn to_def<T: ToDef>(&mut self, src: InFile<T>) -> Option<T::Def> {
T::to_def(self, src)
}
pub fn to_module_def(&mut self, file: FileId) -> Option<Module> {
let _p = profile("SourceBinder::to_module_def");
let (krate, local_id) = self.db.relevant_crates(file).iter().find_map(|&crate_id| {
let crate_def_map = self.db.crate_def_map(crate_id);
let local_id = crate_def_map.modules_for_file(file).next()?;
Some((crate_id, local_id))
})?;
Some(Module { id: ModuleId { krate, local_id } })
}
fn to_id<T: ToId>(&mut self, src: InFile<T>) -> Option<T::ID> {
let container = self.find_container(src.as_ref().map(|it| it.syntax()))?;
let db = self.db;
let dyn_map =
&*self.child_by_source_cache.entry(container).or_insert_with(|| match container {
ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
ChildContainer::ModuleId(it) => it.child_by_source(db),
ChildContainer::TraitId(it) => it.child_by_source(db),
ChildContainer::ImplId(it) => it.child_by_source(db),
ChildContainer::EnumId(it) => it.child_by_source(db),
ChildContainer::VariantId(it) => it.child_by_source(db),
});
dyn_map[T::KEY].get(&src).copied()
T::to_id(self, src)
}
fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
@ -112,19 +109,75 @@ impl<DB: HirDatabase> SourceBinder<'_, DB> {
let def: UnionId = self.to_id(container.with_value(it))?;
VariantId::from(def).into()
},
// FIXME: handle out-of-line modules here
ast::Module(it) => {
let def: ModuleId = self.to_id(container.with_value(it))?;
def.into()
},
_ => { continue },
}
};
return Some(res);
}
let module_source = ModuleSource::from_child_node(self.db, src);
let c = crate::Module::from_definition(self.db, src.with_value(module_source))?;
let c = self.to_module_def(src.file_id.original_file(self.db))?;
Some(c.id.into())
}
fn child_by_source(&mut self, container: ChildContainer) -> &DynMap {
let db = self.db;
self.child_by_source_cache.entry(container).or_insert_with(|| match container {
ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
ChildContainer::ModuleId(it) => it.child_by_source(db),
ChildContainer::TraitId(it) => it.child_by_source(db),
ChildContainer::ImplId(it) => it.child_by_source(db),
ChildContainer::EnumId(it) => it.child_by_source(db),
ChildContainer::VariantId(it) => it.child_by_source(db),
ChildContainer::GenericDefId(it) => it.child_by_source(db),
})
}
}
pub trait ToId: Sized {
type ID: Sized + Copy + 'static;
fn to_id<DB: HirDatabase>(sb: &mut SourceBinder<'_, DB>, src: InFile<Self>)
-> Option<Self::ID>;
}
pub trait ToDef: Sized + AstNode + 'static {
type Def;
fn to_def<DB: HirDatabase>(
sb: &mut SourceBinder<'_, DB>,
src: InFile<Self>,
) -> Option<Self::Def>;
}
macro_rules! to_def_impls {
($(($def:path, $ast:path)),* ,) => {$(
impl ToDef for $ast {
type Def = $def;
fn to_def<DB: HirDatabase>(sb: &mut SourceBinder<'_, DB>, src: InFile<Self>)
-> Option<Self::Def>
{ sb.to_id(src).map(Into::into) }
}
)*}
}
to_def_impls![
(crate::Module, ast::Module),
(crate::Struct, ast::StructDef),
(crate::Enum, ast::EnumDef),
(crate::Union, ast::UnionDef),
(crate::Trait, ast::TraitDef),
(crate::ImplBlock, ast::ImplBlock),
(crate::TypeAlias, ast::TypeAliasDef),
(crate::Const, ast::ConstDef),
(crate::Static, ast::StaticDef),
(crate::Function, ast::FnDef),
(crate::StructField, ast::RecordFieldDef),
(crate::EnumVariant, ast::EnumVariant),
(crate::MacroDef, ast::MacroCall), // this one is dubious, not all calls are macros
];
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum ChildContainer {
DefWithBodyId(DefWithBodyId),
@ -133,6 +186,9 @@ enum ChildContainer {
ImplId(ImplId),
EnumId(EnumId),
VariantId(VariantId),
/// XXX: this might be the same def as, for example an `EnumId`. However,
/// here the children generic parameters, and not, eg enum variants.
GenericDefId(GenericDefId),
}
impl_froms! {
ChildContainer:
@ -142,23 +198,46 @@ impl_froms! {
ImplId,
EnumId,
VariantId,
GenericDefId
}
pub trait ToId: Sized + AstNode + 'static {
pub trait ToIdByKey: Sized + AstNode + 'static {
type ID: Sized + Copy + 'static;
const KEY: Key<Self, Self::ID>;
}
macro_rules! to_id_impls {
impl<T: ToIdByKey> ToId for T {
type ID = <T as ToIdByKey>::ID;
fn to_id<DB: HirDatabase>(
sb: &mut SourceBinder<'_, DB>,
src: InFile<Self>,
) -> Option<Self::ID> {
let container = sb.find_container(src.as_ref().map(|it| it.syntax()))?;
let db = sb.db;
let dyn_map =
&*sb.child_by_source_cache.entry(container).or_insert_with(|| match container {
ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
ChildContainer::ModuleId(it) => it.child_by_source(db),
ChildContainer::TraitId(it) => it.child_by_source(db),
ChildContainer::ImplId(it) => it.child_by_source(db),
ChildContainer::EnumId(it) => it.child_by_source(db),
ChildContainer::VariantId(it) => it.child_by_source(db),
ChildContainer::GenericDefId(it) => it.child_by_source(db),
});
dyn_map[T::KEY].get(&src).copied()
}
}
macro_rules! to_id_key_impls {
($(($id:ident, $ast:path, $key:path)),* ,) => {$(
impl ToId for $ast {
impl ToIdByKey for $ast {
type ID = $id;
const KEY: Key<Self, Self::ID> = $key;
}
)*}
}
to_id_impls![
to_id_key_impls![
(StructId, ast::StructDef, keys::STRUCT),
(UnionId, ast::UnionDef, keys::UNION),
(EnumId, ast::EnumDef, keys::ENUM),
@ -171,3 +250,108 @@ to_id_impls![
(StructFieldId, ast::RecordFieldDef, keys::RECORD_FIELD),
(EnumVariantId, ast::EnumVariant, keys::ENUM_VARIANT),
];
// FIXME: use DynMap as well?
impl ToId for ast::MacroCall {
type ID = MacroDefId;
fn to_id<DB: HirDatabase>(
sb: &mut SourceBinder<'_, DB>,
src: InFile<Self>,
) -> Option<Self::ID> {
let kind = MacroDefKind::Declarative;
let krate = sb.to_module_def(src.file_id.original_file(sb.db))?.id.krate;
let ast_id =
Some(AstId::new(src.file_id, sb.db.ast_id_map(src.file_id).ast_id(&src.value)));
Some(MacroDefId { krate: Some(krate), ast_id, kind })
}
}
impl ToDef for ast::BindPat {
type Def = Local;
fn to_def<DB: HirDatabase>(sb: &mut SourceBinder<'_, DB>, src: InFile<Self>) -> Option<Local> {
let file_id = src.file_id;
let parent: DefWithBodyId = src.value.syntax().ancestors().find_map(|it| {
let res = match_ast! {
match it {
ast::ConstDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::StaticDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::FnDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
_ => return None,
}
};
Some(res)
})?;
let (_body, source_map) = sb.db.body_with_source_map(parent);
let src = src.map(ast::Pat::from);
let pat_id = source_map.node_pat(src.as_ref())?;
Some(Local { parent: parent.into(), pat_id })
}
}
impl ToDef for ast::TypeParam {
type Def = TypeParam;
fn to_def<DB: HirDatabase>(
sb: &mut SourceBinder<'_, DB>,
src: InFile<ast::TypeParam>,
) -> Option<TypeParam> {
let mut sb = SourceBinder::new(sb.db);
let file_id = src.file_id;
let parent: GenericDefId = src.value.syntax().ancestors().find_map(|it| {
let res = match_ast! {
match it {
ast::FnDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::StructDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::EnumDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::TraitDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::TypeAliasDef(value) => { sb.to_id(InFile { value, file_id})?.into() },
ast::ImplBlock(value) => { sb.to_id(InFile { value, file_id})?.into() },
_ => return None,
}
};
Some(res)
})?;
let &id = sb.child_by_source(parent.into())[keys::TYPE_PARAM].get(&src)?;
Some(TypeParam { id })
}
}
impl ToId for ast::Module {
type ID = ModuleId;
fn to_id<DB: HirDatabase>(
sb: &mut SourceBinder<'_, DB>,
src: InFile<ast::Module>,
) -> Option<ModuleId> {
{
let _p = profile("ast::Module::to_def");
let parent_declaration = src
.as_ref()
.map(|it| it.syntax())
.cloned()
.ancestors_with_macros(sb.db)
.skip(1)
.find_map(|it| {
let m = ast::Module::cast(it.value.clone())?;
Some(it.with_value(m))
});
let parent_module = match parent_declaration {
Some(parent_declaration) => sb.to_id(parent_declaration)?,
None => {
let file_id = src.file_id.original_file(sb.db);
sb.to_module_def(file_id)?.id
}
};
let child_name = src.value.name()?.as_name();
let def_map = sb.db.crate_def_map(parent_module.krate);
let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
Some(ModuleId { krate: parent_module.krate, local_id: child_id })
}
}
}

View file

@ -2,7 +2,7 @@
use std::marker::PhantomData;
use hir_expand::InFile;
use hir_expand::{InFile, MacroDefId};
use ra_syntax::{ast, AstNode, AstPtr};
use rustc_hash::FxHashMap;
@ -29,6 +29,8 @@ pub const TUPLE_FIELD: Key<ast::TupleFieldDef, StructFieldId> = Key::new();
pub const RECORD_FIELD: Key<ast::RecordFieldDef, StructFieldId> = Key::new();
pub const TYPE_PARAM: Key<ast::TypeParam, TypeParamId> = Key::new();
pub const MACRO: Key<ast::MacroCall, MacroDefId> = Key::new();
/// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are
/// equal if they point to exactly the same object.
///

View file

@ -59,12 +59,9 @@ use std::sync::Arc;
use hir_expand::{diagnostics::DiagnosticSink, name::Name, InFile};
use ra_arena::Arena;
use ra_db::{CrateId, Edition, FileId, FilePosition};
use ra_db::{CrateId, Edition, FileId};
use ra_prof::profile;
use ra_syntax::{
ast::{self, AstNode},
SyntaxNode,
};
use ra_syntax::ast;
use rustc_hash::FxHashMap;
use crate::{
@ -255,35 +252,6 @@ pub enum ModuleSource {
Module(ast::Module),
}
impl ModuleSource {
// FIXME: this methods do not belong here
pub fn from_position(db: &impl DefDatabase, position: FilePosition) -> ModuleSource {
let parse = db.parse(position.file_id);
match &ra_syntax::algo::find_node_at_offset::<ast::Module>(
parse.tree().syntax(),
position.offset,
) {
Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()),
_ => {
let source_file = parse.tree();
ModuleSource::SourceFile(source_file)
}
}
}
pub fn from_child_node(db: &impl DefDatabase, child: InFile<&SyntaxNode>) -> ModuleSource {
if let Some(m) =
child.value.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi())
{
ModuleSource::Module(m)
} else {
let file_id = child.file_id.original_file(db);
let source_file = db.parse(file_id).tree();
ModuleSource::SourceFile(source_file)
}
}
}
mod diagnostics {
use hir_expand::diagnostics::DiagnosticSink;
use ra_db::RelativePathBuf;

View file

@ -52,15 +52,11 @@ impl<'a> CompletionContext<'a> {
original_parse: &'a Parse<ast::SourceFile>,
position: FilePosition,
) -> Option<CompletionContext<'a>> {
let src = hir::ModuleSource::from_position(db, position);
let module = hir::Module::from_definition(
db,
hir::InFile { file_id: position.file_id.into(), value: src },
);
let mut sb = hir::SourceBinder::new(db);
let module = sb.to_module_def(position.file_id);
let token =
original_parse.tree().syntax().token_at_offset(position.offset).left_biased()?;
let analyzer = hir::SourceAnalyzer::new(
db,
let analyzer = sb.analyze(
hir::InFile::new(position.file_id.into(), &token.parent()),
Some(position.offset),
);

View file

@ -23,6 +23,7 @@ pub enum Severity {
pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> {
let _p = profile("diagnostics");
let mut sb = hir::SourceBinder::new(db);
let parse = db.parse(file_id);
let mut res = Vec::new();
@ -108,10 +109,7 @@ pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic>
fix: Some(fix),
})
});
let source_file = db.parse(file_id).tree();
let src =
hir::InFile { file_id: file_id.into(), value: hir::ModuleSource::SourceFile(source_file) };
if let Some(m) = hir::Module::from_definition(db, src) {
if let Some(m) = sb.to_module_def(file_id) {
m.diagnostics(db, &mut sink);
};
drop(sink);

View file

@ -24,13 +24,14 @@ pub(crate) fn goto_definition(
let original_token = pick_best(file.token_at_offset(position.offset))?;
let token = descend_into_macros(db, position.file_id, original_token.clone());
let mut sb = SourceBinder::new(db);
let nav_targets = match_ast! {
match (token.value.parent()) {
ast::NameRef(name_ref) => {
reference_definition(db, token.with_value(&name_ref)).to_vec()
reference_definition(&mut sb, token.with_value(&name_ref)).to_vec()
},
ast::Name(name) => {
name_definition(db, token.with_value(&name))?
name_definition(&mut sb, token.with_value(&name))?
},
_ => return None,
}
@ -67,20 +68,19 @@ impl ReferenceResult {
}
pub(crate) fn reference_definition(
db: &RootDatabase,
sb: &mut SourceBinder<RootDatabase>,
name_ref: InFile<&ast::NameRef>,
) -> ReferenceResult {
use self::ReferenceResult::*;
let mut sb = SourceBinder::new(db);
let name_kind = classify_name_ref(&mut sb, name_ref).map(|d| d.kind);
let name_kind = classify_name_ref(sb, name_ref).map(|d| d.kind);
match name_kind {
Some(Macro(it)) => return Exact(it.to_nav(db)),
Some(Field(it)) => return Exact(it.to_nav(db)),
Some(TypeParam(it)) => return Exact(it.to_nav(db)),
Some(AssocItem(it)) => return Exact(it.to_nav(db)),
Some(Local(it)) => return Exact(it.to_nav(db)),
Some(Def(def)) => match NavigationTarget::from_def(db, def) {
Some(Macro(it)) => return Exact(it.to_nav(sb.db)),
Some(Field(it)) => return Exact(it.to_nav(sb.db)),
Some(TypeParam(it)) => return Exact(it.to_nav(sb.db)),
Some(AssocItem(it)) => return Exact(it.to_nav(sb.db)),
Some(Local(it)) => return Exact(it.to_nav(sb.db)),
Some(Def(def)) => match NavigationTarget::from_def(sb.db, def) {
Some(nav) => return Exact(nav),
None => return Approximate(vec![]),
},
@ -88,21 +88,21 @@ pub(crate) fn reference_definition(
// FIXME: ideally, this should point to the type in the impl, and
// not at the whole impl. And goto **type** definition should bring
// us to the actual type
return Exact(imp.to_nav(db));
return Exact(imp.to_nav(sb.db));
}
None => {}
};
// Fallback index based approach:
let navs = crate::symbol_index::index_resolve(db, name_ref.value)
let navs = crate::symbol_index::index_resolve(sb.db, name_ref.value)
.into_iter()
.map(|s| s.to_nav(db))
.map(|s| s.to_nav(sb.db))
.collect();
Approximate(navs)
}
pub(crate) fn name_definition(
db: &RootDatabase,
fn name_definition(
sb: &mut SourceBinder<RootDatabase>,
name: InFile<&ast::Name>,
) -> Option<Vec<NavigationTarget>> {
let parent = name.value.syntax().parent()?;
@ -110,14 +110,14 @@ pub(crate) fn name_definition(
if let Some(module) = ast::Module::cast(parent.clone()) {
if module.has_semi() {
let src = name.with_value(module);
if let Some(child_module) = hir::Module::from_declaration(db, src) {
let nav = child_module.to_nav(db);
if let Some(child_module) = sb.to_def(src) {
let nav = child_module.to_nav(sb.db);
return Some(vec![nav]);
}
}
}
if let Some(nav) = named_target(db, name.with_value(&parent)) {
if let Some(nav) = named_target(sb.db, name.with_value(&parent)) {
return Some(vec![nav]);
}

View file

@ -1,6 +1,6 @@
//! FIXME: write short doc here
use hir::{FromSource, ImplBlock};
use hir::{Crate, ImplBlock, SourceBinder};
use ra_db::SourceDatabase;
use ra_syntax::{algo::find_node_at_offset, ast, AstNode};
@ -12,22 +12,19 @@ pub(crate) fn goto_implementation(
) -> Option<RangeInfo<Vec<NavigationTarget>>> {
let parse = db.parse(position.file_id);
let syntax = parse.tree().syntax().clone();
let mut sb = SourceBinder::new(db);
let src = hir::ModuleSource::from_position(db, position);
let module = hir::Module::from_definition(
db,
hir::InFile { file_id: position.file_id.into(), value: src },
)?;
let krate = sb.to_module_def(position.file_id)?.krate();
if let Some(nominal_def) = find_node_at_offset::<ast::NominalDef>(&syntax, position.offset) {
return Some(RangeInfo::new(
nominal_def.syntax().text_range(),
impls_for_def(db, position, &nominal_def, module)?,
impls_for_def(&mut sb, position, &nominal_def, krate)?,
));
} else if let Some(trait_def) = find_node_at_offset::<ast::TraitDef>(&syntax, position.offset) {
return Some(RangeInfo::new(
trait_def.syntax().text_range(),
impls_for_trait(db, position, &trait_def, module)?,
impls_for_trait(&mut sb, position, &trait_def, krate)?,
));
}
@ -35,51 +32,49 @@ pub(crate) fn goto_implementation(
}
fn impls_for_def(
db: &RootDatabase,
sb: &mut SourceBinder<RootDatabase>,
position: FilePosition,
node: &ast::NominalDef,
module: hir::Module,
krate: Crate,
) -> Option<Vec<NavigationTarget>> {
let ty = match node {
ast::NominalDef::StructDef(def) => {
let src = hir::InFile { file_id: position.file_id.into(), value: def.clone() };
hir::Struct::from_source(db, src)?.ty(db)
sb.to_def(src)?.ty(sb.db)
}
ast::NominalDef::EnumDef(def) => {
let src = hir::InFile { file_id: position.file_id.into(), value: def.clone() };
hir::Enum::from_source(db, src)?.ty(db)
sb.to_def(src)?.ty(sb.db)
}
ast::NominalDef::UnionDef(def) => {
let src = hir::InFile { file_id: position.file_id.into(), value: def.clone() };
hir::Union::from_source(db, src)?.ty(db)
sb.to_def(src)?.ty(sb.db)
}
};
let krate = module.krate();
let impls = ImplBlock::all_in_crate(db, krate);
let impls = ImplBlock::all_in_crate(sb.db, krate);
Some(
impls
.into_iter()
.filter(|impl_block| ty.is_equal_for_find_impls(&impl_block.target_ty(db)))
.map(|imp| imp.to_nav(db))
.filter(|impl_block| ty.is_equal_for_find_impls(&impl_block.target_ty(sb.db)))
.map(|imp| imp.to_nav(sb.db))
.collect(),
)
}
fn impls_for_trait(
db: &RootDatabase,
sb: &mut SourceBinder<RootDatabase>,
position: FilePosition,
node: &ast::TraitDef,
module: hir::Module,
krate: Crate,
) -> Option<Vec<NavigationTarget>> {
let src = hir::InFile { file_id: position.file_id.into(), value: node.clone() };
let tr = hir::Trait::from_source(db, src)?;
let tr = sb.to_def(src)?;
let krate = module.krate();
let impls = ImplBlock::for_trait(db, krate, tr);
let impls = ImplBlock::for_trait(sb.db, krate, tr);
Some(impls.into_iter().map(|imp| imp.to_nav(db)).collect())
Some(impls.into_iter().map(|imp| imp.to_nav(sb.db)).collect())
}
#[cfg(test)]
@ -210,7 +205,7 @@ mod tests {
"
//- /lib.rs
#[derive(Copy)]
struct Foo<|>;
struct Foo<|>;
",
&["impl IMPL_BLOCK FileId(1) [0; 15)"],
);

View file

@ -1,17 +1,23 @@
//! FIXME: write short doc here
use ra_db::{CrateId, FileId, FilePosition, SourceDatabase};
use ra_syntax::{
algo::find_node_at_offset,
ast::{self, AstNode},
};
use crate::{db::RootDatabase, NavigationTarget};
/// This returns `Vec` because a module may be included from several places. We
/// don't handle this case yet though, so the Vec has length at most one.
pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<NavigationTarget> {
let src = hir::ModuleSource::from_position(db, position);
let module = match hir::Module::from_definition(
db,
hir::InFile { file_id: position.file_id.into(), value: src },
) {
let mut sb = hir::SourceBinder::new(db);
let parse = db.parse(position.file_id);
let module = match find_node_at_offset::<ast::Module>(parse.tree().syntax(), position.offset) {
Some(module) => sb.to_def(hir::InFile::new(position.file_id.into(), module)),
None => sb.to_module_def(position.file_id),
};
let module = match module {
None => return Vec::new(),
Some(it) => it,
};
@ -21,14 +27,11 @@ pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<Na
/// Returns `Vec` for the same reason as `parent_module`
pub(crate) fn crate_for(db: &RootDatabase, file_id: FileId) -> Vec<CrateId> {
let source_file = db.parse(file_id).tree();
let src = hir::ModuleSource::SourceFile(source_file);
let module =
match hir::Module::from_definition(db, hir::InFile { file_id: file_id.into(), value: src })
{
Some(it) => it,
None => return Vec::new(),
};
let mut sb = hir::SourceBinder::new(db);
let module = match sb.to_module_def(file_id) {
Some(it) => it,
None => return Vec::new(),
};
let krate = module.krate();
vec![krate.into()]
}

View file

@ -1,6 +1,6 @@
//! Functions that are used to classify an element from its definition or reference.
use hir::{FromSource, InFile, Module, ModuleSource, PathResolution, SourceBinder};
use hir::{InFile, PathResolution, SourceBinder};
use ra_prof::profile;
use ra_syntax::{ast, match_ast, AstNode};
use test_utils::tested_by;
@ -22,7 +22,7 @@ pub(crate) fn classify_name(
match parent {
ast::BindPat(it) => {
let src = name.with_value(it);
let local = hir::Local::from_source(sb.db, src)?;
let local = sb.to_def(src)?;
Some(NameDefinition {
visibility: None,
container: local.module(sb.db),
@ -35,16 +35,7 @@ pub(crate) fn classify_name(
Some(from_struct_field(sb.db, field))
},
ast::Module(it) => {
let def = {
if !it.has_semi() {
let ast = hir::ModuleSource::Module(it);
let src = name.with_value(ast);
hir::Module::from_definition(sb.db, src)
} else {
let src = name.with_value(it);
hir::Module::from_declaration(sb.db, src)
}
}?;
let def = sb.to_def(name.with_value(it))?;
Some(from_module_def(sb.db, def.into(), None))
},
ast::StructDef(it) => {
@ -101,10 +92,9 @@ pub(crate) fn classify_name(
},
ast::MacroCall(it) => {
let src = name.with_value(it);
let def = hir::MacroDef::from_source(sb.db, src.clone())?;
let def = sb.to_def(src.clone())?;
let module_src = ModuleSource::from_child_node(sb.db, src.as_ref().map(|it| it.syntax()));
let module = Module::from_definition(sb.db, src.with_value(module_src))?;
let module = sb.to_module_def(src.file_id.original_file(sb.db))?;
Some(NameDefinition {
visibility: None,
@ -114,7 +104,7 @@ pub(crate) fn classify_name(
},
ast::TypeParam(it) => {
let src = name.with_value(it);
let def = hir::TypeParam::from_source(sb.db, src)?;
let def = sb.to_def(src)?;
Some(NameDefinition {
visibility: None,
container: def.module(sb.db),
@ -157,10 +147,9 @@ pub(crate) fn classify_name_ref(
}
}
let ast = ModuleSource::from_child_node(sb.db, name_ref.with_value(&parent));
// FIXME: find correct container and visibility for each case
let container = Module::from_definition(sb.db, name_ref.with_value(ast))?;
let visibility = None;
let container = sb.to_module_def(name_ref.file_id.original_file(sb.db))?;
if let Some(macro_call) = parent.ancestors().find_map(ast::MacroCall::cast) {
tested_by!(goto_def_for_macros);
@ -178,12 +167,13 @@ pub(crate) fn classify_name_ref(
PathResolution::Def(def) => Some(from_module_def(sb.db, def, Some(container))),
PathResolution::AssocItem(item) => Some(from_assoc_item(sb.db, item)),
PathResolution::Local(local) => {
let container = local.module(sb.db);
let kind = NameKind::Local(local);
let container = local.module(sb.db);
Some(NameDefinition { kind, container, visibility: None })
}
PathResolution::TypeParam(par) => {
let kind = NameKind::TypeParam(par);
let container = par.module(sb.db);
Some(NameDefinition { kind, container, visibility })
}
PathResolution::Macro(def) => {

View file

@ -25,6 +25,8 @@ pub enum NameKind {
#[derive(PartialEq, Eq)]
pub(crate) struct NameDefinition {
pub visibility: Option<ast::Visibility>,
/// FIXME: this doesn't really make sense. For example, builtin types don't
/// really have a module.
pub container: Module,
pub kind: NameKind,
}

View file

@ -63,7 +63,7 @@ fn rename_mod(
let mut source_file_edits = Vec::new();
let mut file_system_edits = Vec::new();
let module_src = hir::InFile { file_id: position.file_id.into(), value: ast_module.clone() };
if let Some(module) = hir::Module::from_declaration(db, module_src) {
if let Some(module) = hir::SourceBinder::new(db).to_def(module_src) {
let src = module.definition_source(db);
let file_id = src.file_id.original_file(db);
match src.value {

View file

@ -66,8 +66,8 @@ fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Opti
return None;
}
let range = module.syntax().text_range();
let src = hir::ModuleSource::from_child_node(db, InFile::new(file_id.into(), &module.syntax()));
let module = hir::Module::from_definition(db, InFile::new(file_id.into(), src))?;
let mut sb = hir::SourceBinder::new(db);
let module = sb.to_def(InFile::new(file_id.into(), module))?;
let path = module.path_to_root(db).into_iter().rev().filter_map(|it| it.name(db)).join("::");
Some(Runnable { range, kind: RunnableKind::TestMod { path } })