8015:  Introduce Semantics::visit_file_defs r=matklad a=Veykril

See https://github.com/rust-analyzer/rust-analyzer/issues/3538#issuecomment-798920601

Co-authored-by: Lukas Wirth <lukastw97@gmail.com>
This commit is contained in:
bors[bot] 2021-03-15 13:18:26 +00:00 committed by GitHub
commit b245e8d115
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 113 additions and 72 deletions

View File

@ -1,17 +1,18 @@
use hir::Semantics;
use either::Either;
use hir::{HasSource, Semantics};
use ide_db::{
base_db::{FileId, FilePosition, FileRange, SourceDatabase},
RootDatabase, SymbolKind,
base_db::{FileId, FilePosition, FileRange},
helpers::visit_file_defs,
RootDatabase,
};
use syntax::TextRange;
use syntax::{ast::NameOwner, AstNode, TextRange, TextSize};
use crate::{
file_structure::file_structure,
fn_references::find_all_methods,
goto_implementation::goto_implementation,
references::find_all_refs,
runnables::{runnables, Runnable},
NavigationTarget, RunnableKind, StructureNodeKind,
NavigationTarget, RunnableKind,
};
// Feature: Annotations
@ -75,41 +76,56 @@ pub(crate) fn annotations(
}
}
file_structure(&db.parse(file_id).tree())
.into_iter()
.filter(|node| {
matches!(
node.kind,
StructureNodeKind::SymbolKind(SymbolKind::Trait)
| StructureNodeKind::SymbolKind(SymbolKind::Struct)
| StructureNodeKind::SymbolKind(SymbolKind::Enum)
| StructureNodeKind::SymbolKind(SymbolKind::Union)
| StructureNodeKind::SymbolKind(SymbolKind::Const)
)
})
.for_each(|node| {
if config.annotate_impls
&& node.kind != StructureNodeKind::SymbolKind(SymbolKind::Const)
{
visit_file_defs(&Semantics::new(db), file_id, &mut |def| match def {
Either::Left(def) => {
let node = match def {
hir::ModuleDef::Const(konst) => {
konst.source(db).and_then(|node| range_and_position_of(&node.value))
}
hir::ModuleDef::Trait(trait_) => {
trait_.source(db).and_then(|node| range_and_position_of(&node.value))
}
hir::ModuleDef::Adt(hir::Adt::Struct(strukt)) => {
strukt.source(db).and_then(|node| range_and_position_of(&node.value))
}
hir::ModuleDef::Adt(hir::Adt::Enum(enum_)) => {
enum_.source(db).and_then(|node| range_and_position_of(&node.value))
}
hir::ModuleDef::Adt(hir::Adt::Union(union)) => {
union.source(db).and_then(|node| range_and_position_of(&node.value))
}
_ => None,
};
let (offset, range) = match node {
Some(node) => node,
None => return,
};
if config.annotate_impls && !matches!(def, hir::ModuleDef::Const(_)) {
annotations.push(Annotation {
range: node.node_range,
range,
kind: AnnotationKind::HasImpls {
position: FilePosition { file_id, offset: node.navigation_range.start() },
position: FilePosition { file_id, offset },
data: None,
},
});
}
if config.annotate_references {
annotations.push(Annotation {
range,
kind: AnnotationKind::HasReferences {
position: FilePosition { file_id, offset },
data: None,
},
});
}
if config.annotate_references {
annotations.push(Annotation {
range: node.node_range,
kind: AnnotationKind::HasReferences {
position: FilePosition { file_id, offset: node.navigation_range.start() },
data: None,
},
});
fn range_and_position_of(node: &dyn NameOwner) -> Option<(TextSize, TextRange)> {
Some((node.name()?.syntax().text_range().start(), node.syntax().text_range()))
}
});
}
Either::Right(_) => (),
});
if config.annotate_method_references {
annotations.extend(find_all_methods(db, file_id).into_iter().map(|method| Annotation {
@ -936,4 +952,19 @@ fn my_cool_test() {}
"#]],
);
}
#[test]
fn test_no_annotations_outside_module_tree() {
check(
r#"
//- /foo.rs
struct Foo;
//- /lib.rs
// this file comes last since `check` checks the first file only
"#,
expect![[r#"
[]
"#]],
);
}
}

View File

@ -2,11 +2,13 @@
use ast::NameOwner;
use cfg::CfgExpr;
use either::Either;
use hir::{AsAssocItem, HasAttrs, HasSource, HirDisplay, Semantics};
use ide_assists::utils::test_related_attribute;
use ide_db::{
base_db::{FilePosition, FileRange},
defs::Definition,
helpers::visit_file_defs,
search::SearchScope,
RootDatabase, SymbolKind,
};
@ -102,13 +104,27 @@ pub fn action(&self) -> &'static RunnableAction {
// |===
pub(crate) fn runnables(db: &RootDatabase, file_id: FileId) -> Vec<Runnable> {
let sema = Semantics::new(db);
let module = match sema.to_module_def(file_id) {
None => return Vec::new(),
Some(it) => it,
};
let mut res = Vec::new();
runnables_mod(&sema, &mut res, module);
visit_file_defs(&sema, file_id, &mut |def| match def {
Either::Left(def) => {
let runnable = match def {
hir::ModuleDef::Module(it) => runnable_mod(&sema, it),
hir::ModuleDef::Function(it) => runnable_fn(&sema, it),
_ => None,
};
res.extend(runnable.or_else(|| module_def_doctest(&sema, def)))
}
Either::Right(impl_) => {
res.extend(impl_.items(db).into_iter().filter_map(|assoc| match assoc {
hir::AssocItem::Function(it) => {
runnable_fn(&sema, it).or_else(|| module_def_doctest(&sema, it.into()))
}
hir::AssocItem::Const(it) => module_def_doctest(&sema, it.into()),
hir::AssocItem::TypeAlias(it) => module_def_doctest(&sema, it.into()),
}))
}
});
res
}
@ -211,39 +227,6 @@ fn parent_test_module(sema: &Semantics<RootDatabase>, fn_def: &ast::Fn) -> Optio
})
}
fn runnables_mod(sema: &Semantics<RootDatabase>, acc: &mut Vec<Runnable>, module: hir::Module) {
acc.extend(module.declarations(sema.db).into_iter().filter_map(|def| {
let runnable = match def {
hir::ModuleDef::Module(it) => runnable_mod(&sema, it),
hir::ModuleDef::Function(it) => runnable_fn(&sema, it),
_ => None,
};
runnable.or_else(|| module_def_doctest(&sema, def))
}));
acc.extend(module.impl_defs(sema.db).into_iter().flat_map(|it| it.items(sema.db)).filter_map(
|def| match def {
hir::AssocItem::Function(it) => {
runnable_fn(&sema, it).or_else(|| module_def_doctest(&sema, it.into()))
}
hir::AssocItem::Const(it) => module_def_doctest(&sema, it.into()),
hir::AssocItem::TypeAlias(it) => module_def_doctest(&sema, it.into()),
},
));
for def in module.declarations(sema.db) {
if let hir::ModuleDef::Module(submodule) = def {
match submodule.definition_source(sema.db).value {
hir::ModuleSource::Module(_) => runnables_mod(sema, acc, submodule),
hir::ModuleSource::SourceFile(_) => {
cov_mark::hit!(dont_recurse_in_outline_submodules)
}
hir::ModuleSource::BlockExpr(_) => {} // inner items aren't runnable
}
}
}
}
pub(crate) fn runnable_fn(sema: &Semantics<RootDatabase>, def: hir::Function) -> Option<Runnable> {
let func = def.source(sema.db)?;
let name_string = def.name(sema.db).to_string();
@ -1178,7 +1161,6 @@ mod tests {
#[test]
fn dont_recurse_in_outline_submodules() {
cov_mark::check!(dont_recurse_in_outline_submodules);
check(
r#"
//- /lib.rs

View File

@ -2,6 +2,10 @@
pub mod insert_use;
pub mod import_assets;
use std::collections::VecDeque;
use base_db::FileId;
use either::Either;
use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef, Semantics, Trait};
use syntax::ast::{self, make};
@ -39,6 +43,30 @@ pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
make::path_from_segments(segments, is_abs)
}
/// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
pub fn visit_file_defs(
sema: &Semantics<RootDatabase>,
file_id: FileId,
cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
) {
let db = sema.db;
let module = match sema.to_module_def(file_id) {
Some(it) => it,
None => return,
};
let mut defs: VecDeque<_> = module.declarations(db).into();
while let Some(def) = defs.pop_front() {
if let ModuleDef::Module(submodule) = def {
if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
defs.extend(submodule.declarations(db));
submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
}
}
cb(Either::Left(def));
}
module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
}
/// Helps with finding well-know things inside the standard library. This is
/// somewhat similar to the known paths infra inside hir, but it different; We
/// want to make sure that IDE specific paths don't become interesting inside