rust-analyzer/crates/ide_db/src/symbol_index.rs

777 lines
25 KiB
Rust
Raw Normal View History

2019-01-08 19:33:36 +00:00
//! This module handles fuzzy-searching of functions, structs and other symbols
//! by name across the whole workspace and dependencies.
//!
//! It works by building an incrementally-updated text-search index of all
//! symbols. The backbone of the index is the **awesome** `fst` crate by
//! @BurntSushi.
//!
2019-02-11 16:18:27 +00:00
//! In a nutshell, you give a set of strings to `fst`, and it builds a
2019-01-21 02:35:18 +00:00
//! finite state machine describing this set of strings. The strings which
2019-01-08 19:33:36 +00:00
//! could fuzzy-match a pattern can also be described by a finite state machine.
2019-02-11 16:18:27 +00:00
//! What is freaking cool is that you can now traverse both state machines in
2019-01-08 19:33:36 +00:00
//! lock-step to enumerate the strings which are both in the input set and
2019-01-21 02:35:18 +00:00
//! fuzz-match the query. Or, more formally, given two languages described by
2019-02-11 16:18:27 +00:00
//! FSTs, one can build a product FST which describes the intersection of the
2019-01-08 19:33:36 +00:00
//! languages.
//!
//! `fst` does not support cheap updating of the index, but it supports unioning
2019-02-11 16:18:27 +00:00
//! of state machines. So, to account for changing source code, we build an FST
//! for each library (which is assumed to never change) and an FST for each Rust
2019-01-21 02:35:18 +00:00
//! file in the current workspace, and run a query against the union of all
2019-02-11 16:18:27 +00:00
//! those FSTs.
2020-02-06 14:08:31 +00:00
2019-01-08 19:33:36 +00:00
use std::{
2020-02-18 13:39:24 +00:00
cmp::Ordering,
fmt,
2019-01-08 19:33:36 +00:00
hash::{Hash, Hasher},
2019-01-25 14:20:52 +00:00
mem,
sync::Arc,
2019-01-08 19:33:36 +00:00
};
2020-08-13 14:25:38 +00:00
use base_db::{
2019-01-17 11:11:00 +00:00
salsa::{self, ParallelDatabase},
2021-11-29 09:36:00 +00:00
CrateId, FileRange, SourceDatabaseExt, SourceRootId, Upcast,
};
2021-11-29 05:22:30 +00:00
use either::Either;
2020-08-13 14:25:38 +00:00
use fst::{self, Streamer};
2021-11-27 11:25:05 +00:00
use hir::{
2021-11-29 05:22:30 +00:00
db::{DefDatabase, HirDatabase},
AdtId, AssocContainerId, AssocItemId, AssocItemLoc, DefHasSource, DefWithBodyId, HasSource,
HirFileId, ImplId, InFile, ItemLoc, ItemTreeNode, Lookup, MacroDef, ModuleDefId, ModuleId,
2021-11-29 03:54:52 +00:00
Semantics, TraitId,
2021-11-27 11:25:05 +00:00
};
2020-08-12 16:26:51 +00:00
use rayon::prelude::*;
2021-11-29 09:36:00 +00:00
use rustc_hash::FxHashSet;
use syntax::{ast::HasName, AstNode, SmolStr, SyntaxNode, SyntaxNodePtr};
2019-01-08 19:33:36 +00:00
2020-02-06 11:43:56 +00:00
use crate::RootDatabase;
2020-02-06 11:24:13 +00:00
#[derive(Debug)]
pub struct Query {
query: String,
lowercased: String,
only_types: bool,
libs: bool,
exact: bool,
case_sensitive: bool,
2020-02-06 11:24:13 +00:00
limit: usize,
}
impl Query {
pub fn new(query: String) -> Query {
let lowercased = query.to_lowercase();
Query {
query,
lowercased,
only_types: false,
libs: false,
exact: false,
case_sensitive: false,
2020-02-06 11:24:13 +00:00
limit: usize::max_value(),
}
}
pub fn only_types(&mut self) {
self.only_types = true;
}
pub fn libs(&mut self) {
self.libs = true;
}
pub fn exact(&mut self) {
self.exact = true;
}
pub fn case_sensitive(&mut self) {
self.case_sensitive = true;
}
2020-02-06 11:24:13 +00:00
pub fn limit(&mut self, limit: usize) {
self.limit = limit
}
}
2019-01-08 19:33:36 +00:00
2019-01-25 20:27:16 +00:00
#[salsa::query_group(SymbolsDatabaseStorage)]
2021-11-29 05:22:30 +00:00
pub trait SymbolsDatabase: HirDatabase + SourceDatabaseExt + Upcast<dyn HirDatabase> {
2021-11-29 09:52:03 +00:00
/// The symbol index for a given module. These modules should only be in source roots that
/// are inside local_roots.
2021-11-27 13:00:02 +00:00
fn module_symbols(&self, module_id: ModuleId) -> Arc<SymbolIndex>;
2021-11-29 09:52:03 +00:00
/// The symbol index for a given source root within library_roots.
2021-11-29 09:36:00 +00:00
fn library_symbols(&self, source_root_id: SourceRootId) -> Arc<SymbolIndex>;
2021-11-29 09:52:03 +00:00
2019-01-26 08:17:05 +00:00
/// The set of "local" (that is, from the current workspace) roots.
/// Files in local roots are assumed to change frequently.
#[salsa::input]
2020-06-11 09:04:09 +00:00
fn local_roots(&self) -> Arc<FxHashSet<SourceRootId>>;
2021-11-29 09:52:03 +00:00
2019-01-26 08:17:05 +00:00
/// The set of roots for crates.io libraries.
/// Files in libraries are assumed to never change.
#[salsa::input]
2020-06-11 09:04:09 +00:00
fn library_roots(&self) -> Arc<FxHashSet<SourceRootId>>;
2019-01-08 19:33:36 +00:00
}
2021-11-29 09:36:00 +00:00
fn library_symbols(db: &dyn SymbolsDatabase, source_root_id: SourceRootId) -> Arc<SymbolIndex> {
2020-08-12 14:32:36 +00:00
let _p = profile::span("library_symbols");
2021-11-29 09:36:00 +00:00
// todo: this could be parallelized, once I figure out how to do that...
let symbols = db
.source_root_crates(source_root_id)
.iter()
2021-11-29 09:36:00 +00:00
.flat_map(|&krate| module_ids_for_crate(db.upcast(), krate))
2021-11-29 09:52:03 +00:00
// we specifically avoid calling SymbolsDatabase::module_symbols here, even they do the same thing,
// as the index for a library is not going to really ever change, and we do not want to store each
// module's index in salsa.
2021-11-29 09:36:00 +00:00
.map(|module_id| SymbolCollector::collect(db, module_id))
.flatten()
.collect();
2021-11-29 09:36:00 +00:00
Arc::new(SymbolIndex::new(symbols))
}
2021-11-27 13:00:02 +00:00
fn module_symbols(db: &dyn SymbolsDatabase, module_id: ModuleId) -> Arc<SymbolIndex> {
2021-11-29 09:36:00 +00:00
let _p = profile::span("module_symbols");
2021-11-29 05:22:30 +00:00
let symbols = SymbolCollector::collect(db, module_id);
2019-01-15 15:19:09 +00:00
Arc::new(SymbolIndex::new(symbols))
2019-01-08 19:33:36 +00:00
}
/// Need to wrap Snapshot to provide `Clone` impl for `map_with`
struct Snap<DB>(DB);
2021-11-29 09:52:03 +00:00
impl<DB: ParallelDatabase> Snap<salsa::Snapshot<DB>> {
fn new(db: &DB) -> Self {
Self(db.snapshot())
}
}
impl<DB: ParallelDatabase> Clone for Snap<salsa::Snapshot<DB>> {
fn clone(&self) -> Snap<salsa::Snapshot<DB>> {
Snap(self.0.snapshot())
}
}
2021-11-29 09:52:03 +00:00
impl<DB> std::ops::Deref for Snap<DB> {
type Target = DB;
fn deref(&self) -> &Self::Target {
&self.0
}
}
2020-05-30 23:54:54 +00:00
// Feature: Workspace Symbol
//
// Uses fuzzy-search to find types, modules and functions by name across your
// project and dependencies. This is **the** most useful feature, which improves code
// navigation tremendously. It mostly works on top of the built-in LSP
// functionality, however `#` and `*` symbols can be used to narrow down the
// search. Specifically,
//
// - `Foo` searches for `Foo` type in the current workspace
// - `foo#` searches for `foo` function in the current workspace
// - `Foo*` searches for `Foo` type among dependencies, including `stdlib`
// - `foo#*` searches for `foo` function among dependencies
//
// That is, `#` switches from "types" to all symbols, `*` switches from the current
// workspace to dependencies.
//
// Note that filtering does not currently work in VSCode due to the editor never
// sending the special symbols to the language server. Instead, you can configure
// the filtering via the `rust-analyzer.workspace.symbol.search.scope` and
// `rust-analyzer.workspace.symbol.search.kind` settings.
//
2020-05-30 23:54:54 +00:00
// |===
// | Editor | Shortcut
//
// | VS Code | kbd:[Ctrl+T]
// |===
2020-02-06 11:43:56 +00:00
pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec<FileSymbol> {
2020-08-12 14:32:36 +00:00
let _p = profile::span("world_symbols").detail(|| query.query.clone());
2020-06-08 11:00:31 +00:00
2021-11-29 09:36:00 +00:00
let indices = if query.libs {
db.library_roots()
.par_iter()
2021-11-29 09:52:03 +00:00
.map_with(Snap::new(db), |snap, &root| snap.library_symbols(root))
2021-11-29 09:36:00 +00:00
.collect()
2019-01-08 19:33:36 +00:00
} else {
2021-11-27 13:00:02 +00:00
let mut module_ids = Vec::new();
2019-01-08 19:33:36 +00:00
for &root in db.local_roots().iter() {
2021-11-27 13:00:02 +00:00
let crates = db.source_root_crates(root);
for &krate in crates.iter() {
module_ids.extend(module_ids_for_crate(db, krate));
}
2019-01-08 19:33:36 +00:00
}
2021-11-29 09:36:00 +00:00
module_ids
.par_iter()
2021-11-29 09:52:03 +00:00
.map_with(Snap::new(db), |snap, &module_id| snap.module_symbols(module_id))
2021-11-29 09:36:00 +00:00
.collect()
2019-01-08 19:33:36 +00:00
};
2021-11-29 09:36:00 +00:00
query.search(indices)
2019-01-08 19:33:36 +00:00
}
pub fn crate_symbols(db: &RootDatabase, krate: CrateId, query: Query) -> Vec<FileSymbol> {
2021-06-10 20:03:16 +00:00
let _p = profile::span("crate_symbols").detail(|| format!("{:?}", query));
2020-06-11 10:03:08 +00:00
2021-11-27 13:00:02 +00:00
let module_ids = module_ids_for_crate(db, krate);
2021-11-29 09:36:00 +00:00
let indices: Vec<_> = module_ids
2021-11-27 13:00:02 +00:00
.par_iter()
2021-11-29 09:52:03 +00:00
.map_with(Snap::new(db), |snap, &module_id| snap.module_symbols(module_id))
2021-11-27 11:25:05 +00:00
.collect();
2021-11-29 02:07:16 +00:00
2021-11-29 09:36:00 +00:00
query.search(indices)
}
2021-11-29 09:36:00 +00:00
fn module_ids_for_crate(db: &dyn DefDatabase, krate: CrateId) -> Vec<ModuleId> {
2021-11-27 13:00:02 +00:00
let def_map = db.crate_def_map(krate);
2021-11-29 02:07:16 +00:00
def_map.modules().map(|(id, _)| def_map.module_id(id)).collect()
2021-11-27 13:00:02 +00:00
}
2021-01-19 22:56:11 +00:00
pub fn index_resolve(db: &RootDatabase, name: &str) -> Vec<FileSymbol> {
2019-02-08 11:09:57 +00:00
let mut query = Query::new(name.to_string());
query.exact();
query.limit(4);
2020-02-06 11:22:35 +00:00
world_symbols(db, query)
2019-02-08 11:09:57 +00:00
}
2019-03-05 14:09:48 +00:00
#[derive(Default)]
2020-02-06 11:43:56 +00:00
pub struct SymbolIndex {
2019-01-08 19:33:36 +00:00
symbols: Vec<FileSymbol>,
2020-03-10 13:55:23 +00:00
map: fst::Map<Vec<u8>>,
2019-01-08 19:33:36 +00:00
}
2019-03-05 14:09:48 +00:00
impl fmt::Debug for SymbolIndex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("SymbolIndex").field("n_symbols", &self.symbols.len()).finish()
}
}
2019-01-08 19:33:36 +00:00
impl PartialEq for SymbolIndex {
fn eq(&self, other: &SymbolIndex) -> bool {
self.symbols == other.symbols
}
}
impl Eq for SymbolIndex {}
impl Hash for SymbolIndex {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.symbols.hash(hasher)
}
}
impl SymbolIndex {
fn new(mut symbols: Vec<FileSymbol>) -> SymbolIndex {
2020-02-18 13:39:24 +00:00
fn cmp(lhs: &FileSymbol, rhs: &FileSymbol) -> Ordering {
let lhs_chars = lhs.name.chars().map(|c| c.to_ascii_lowercase());
let rhs_chars = rhs.name.chars().map(|c| c.to_ascii_lowercase());
lhs_chars.cmp(rhs_chars)
2019-01-08 19:33:36 +00:00
}
2020-02-18 13:39:24 +00:00
symbols.par_sort_by(cmp);
let mut builder = fst::MapBuilder::memory();
let mut last_batch_start = 0;
for idx in 0..symbols.len() {
2020-02-18 13:39:24 +00:00
if let Some(next_symbol) = symbols.get(idx + 1) {
if cmp(&symbols[last_batch_start], next_symbol) == Ordering::Equal {
continue;
}
}
let start = last_batch_start;
let end = idx + 1;
last_batch_start = end;
2020-02-18 13:39:24 +00:00
let key = symbols[start].name.as_str().to_ascii_lowercase();
let value = SymbolIndex::range_to_map_value(start, end);
builder.insert(key, value).unwrap();
}
2020-03-10 13:55:23 +00:00
let map = fst::Map::new(builder.into_inner().unwrap()).unwrap();
2019-01-08 19:33:36 +00:00
SymbolIndex { symbols, map }
}
2020-02-06 11:43:56 +00:00
pub fn len(&self) -> usize {
2019-01-08 19:33:36 +00:00
self.symbols.len()
}
2020-02-06 11:43:56 +00:00
pub fn memory_size(&self) -> usize {
2019-01-25 18:10:28 +00:00
self.map.as_fst().size() + self.symbols.len() * mem::size_of::<FileSymbol>()
2019-01-25 14:20:52 +00:00
}
fn range_to_map_value(start: usize, end: usize) -> u64 {
debug_assert![start <= (std::u32::MAX as usize)];
debug_assert![end <= (std::u32::MAX as usize)];
2019-04-23 20:19:45 +00:00
((start as u64) << 32) | end as u64
}
fn map_value_to_range(value: u64) -> (usize, usize) {
let end = value as u32 as usize;
let start = (value >> 32) as usize;
(start, end)
}
2019-01-08 19:33:36 +00:00
}
impl Query {
2021-11-29 09:36:00 +00:00
pub(crate) fn search(self, indices: Vec<Arc<SymbolIndex>>) -> Vec<FileSymbol> {
2021-06-10 20:03:16 +00:00
let _p = profile::span("symbol_index::Query::search");
2019-01-08 19:33:36 +00:00
let mut op = fst::map::OpBuilder::new();
2021-11-29 09:36:00 +00:00
for file_symbols in &indices {
2019-01-08 19:33:36 +00:00
let automaton = fst::automaton::Subsequence::new(&self.lowercased);
op = op.add(file_symbols.map.search(automaton))
}
let mut stream = op.union();
let mut res = Vec::new();
while let Some((_, indexed_values)) = stream.next() {
for indexed_value in indexed_values {
let symbol_index = &indices[indexed_value.index];
let (start, end) = SymbolIndex::map_value_to_range(indexed_value.value);
for symbol in &symbol_index.symbols[start..end] {
if self.only_types && !symbol.kind.is_type() {
continue;
}
if self.exact {
if symbol.name != self.query {
continue;
}
} else if self.case_sensitive {
if self.query.chars().any(|c| !symbol.name.contains(c)) {
continue;
}
}
2020-06-08 11:00:53 +00:00
2020-06-10 10:37:00 +00:00
res.push(symbol.clone());
2020-06-08 11:00:53 +00:00
if res.len() >= self.limit {
return res;
}
2019-01-08 19:33:36 +00:00
}
}
}
res
}
}
/// The actual data that is stored in the index. It should be as compact as
/// possible.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2020-02-06 11:43:56 +00:00
pub struct FileSymbol {
pub name: SmolStr,
2021-11-28 00:42:42 +00:00
pub loc: DeclarationLocation,
pub kind: FileSymbolKind,
2020-02-06 11:43:56 +00:00
pub container_name: Option<SmolStr>,
}
2021-11-28 00:42:42 +00:00
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeclarationLocation {
/// The file id for both the `ptr` and `name_ptr`.
pub hir_file_id: HirFileId,
/// This points to the whole syntax node of the declaration.
pub ptr: SyntaxNodePtr,
/// This points to the [`syntax::ast::Name`] identifier of the declaration.
pub name_ptr: SyntaxNodePtr,
}
impl DeclarationLocation {
pub fn syntax(&self, semantics: &Semantics<'_, RootDatabase>) -> Option<SyntaxNode> {
let root = semantics.parse_or_expand(self.hir_file_id)?;
Some(self.ptr.to_node(&root))
}
pub fn original_range(&self, semantics: &Semantics<'_, RootDatabase>) -> Option<FileRange> {
find_original_file_range(semantics, self.hir_file_id, &self.ptr)
}
pub fn original_name_range(
&self,
semantics: &Semantics<'_, RootDatabase>,
) -> Option<FileRange> {
find_original_file_range(semantics, self.hir_file_id, &self.name_ptr)
}
}
fn find_original_file_range(
semantics: &Semantics<'_, RootDatabase>,
file_id: HirFileId,
ptr: &SyntaxNodePtr,
) -> Option<FileRange> {
let root = semantics.parse_or_expand(file_id)?;
let node = ptr.to_node(&root);
let node = InFile::new(file_id, &node);
Some(node.original_file_range(semantics.db.upcast()))
}
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum FileSymbolKind {
2021-01-24 00:32:52 +00:00
Const,
Enum,
Function,
2021-01-24 00:32:52 +00:00
Macro,
Module,
Static,
Struct,
Trait,
TypeAlias,
2021-01-24 00:32:52 +00:00
Union,
}
impl FileSymbolKind {
fn is_type(self: FileSymbolKind) -> bool {
matches!(
self,
FileSymbolKind::Struct
| FileSymbolKind::Enum
| FileSymbolKind::Trait
| FileSymbolKind::TypeAlias
2021-01-24 00:32:52 +00:00
| FileSymbolKind::Union
)
}
}
2021-11-29 07:17:18 +00:00
/// Represents an outstanding module that the symbol collector must collect symbols from.
struct SymbolCollectorWork {
module_id: ModuleId,
parent: Option<DefWithBodyId>,
2021-11-29 03:54:52 +00:00
}
2021-11-27 11:25:05 +00:00
2021-11-29 03:54:52 +00:00
struct SymbolCollector<'a> {
2021-11-29 05:22:30 +00:00
db: &'a dyn SymbolsDatabase,
2021-11-29 03:54:52 +00:00
symbols: Vec<FileSymbol>,
2021-11-29 05:42:46 +00:00
work: Vec<SymbolCollectorWork>,
2021-11-29 03:54:52 +00:00
container_name_stack: Vec<SmolStr>,
2021-11-27 11:25:05 +00:00
}
2021-11-29 05:22:30 +00:00
/// Given a [`ModuleId`] and a [`SymbolsDatabase`], use the DefMap for the module's crate to collect all symbols that should be
/// indexed for the given module.
2021-11-29 03:54:52 +00:00
impl<'a> SymbolCollector<'a> {
2021-11-29 05:22:30 +00:00
fn collect(db: &dyn SymbolsDatabase, module_id: ModuleId) -> Vec<FileSymbol> {
2021-11-29 03:54:52 +00:00
let mut symbol_collector = SymbolCollector {
db,
symbols: Default::default(),
container_name_stack: Default::default(),
2021-11-29 07:17:18 +00:00
// The initial work is the root module we're collecting, additional work will
// be populated as we traverse the module's definitions.
work: vec![SymbolCollectorWork { module_id, parent: None }],
2021-11-29 03:54:52 +00:00
};
2021-11-29 05:42:46 +00:00
while let Some(work) = symbol_collector.work.pop() {
symbol_collector.do_work(work);
2021-11-29 03:54:52 +00:00
}
symbol_collector.symbols
}
2021-11-29 05:42:46 +00:00
fn do_work(&mut self, work: SymbolCollectorWork) {
2021-11-29 03:54:52 +00:00
self.db.unwind_if_cancelled();
2021-11-29 07:17:18 +00:00
let parent_name = work.parent.and_then(|id| self.def_with_body_id_name(id));
self.with_container_name(parent_name, |s| s.collect_from_module(work.module_id));
2021-11-29 03:54:52 +00:00
}
fn collect_from_module(&mut self, module_id: ModuleId) {
2021-11-29 05:22:30 +00:00
let def_map = module_id.def_map(self.db.upcast());
2021-11-29 03:54:52 +00:00
let module_data = &def_map[module_id.local_id];
let scope = &module_data.scope;
for module_def_id in scope.declarations() {
match module_def_id {
ModuleDefId::ModuleId(id) => self.push_module(id),
ModuleDefId::FunctionId(id) => {
self.push_decl_assoc(id, FileSymbolKind::Function);
2021-11-29 07:17:18 +00:00
self.collect_from_body(id);
2021-11-29 03:54:52 +00:00
}
ModuleDefId::AdtId(AdtId::StructId(id)) => {
self.push_decl(id, FileSymbolKind::Struct)
}
ModuleDefId::AdtId(AdtId::EnumId(id)) => self.push_decl(id, FileSymbolKind::Enum),
ModuleDefId::AdtId(AdtId::UnionId(id)) => self.push_decl(id, FileSymbolKind::Union),
ModuleDefId::ConstId(id) => {
self.push_decl_assoc(id, FileSymbolKind::Const);
2021-11-29 07:17:18 +00:00
self.collect_from_body(id);
2021-11-29 03:54:52 +00:00
}
ModuleDefId::StaticId(id) => {
self.push_decl(id, FileSymbolKind::Static);
2021-11-29 07:17:18 +00:00
self.collect_from_body(id);
2021-11-29 03:54:52 +00:00
}
ModuleDefId::TraitId(id) => {
self.push_decl(id, FileSymbolKind::Trait);
2021-11-29 07:17:18 +00:00
self.collect_from_trait(id);
2021-11-29 03:54:52 +00:00
}
ModuleDefId::TypeAliasId(id) => {
self.push_decl_assoc(id, FileSymbolKind::TypeAlias);
}
// Don't index these.
ModuleDefId::BuiltinType(_) => {}
ModuleDefId::EnumVariantId(_) => {}
2021-11-27 12:26:03 +00:00
}
2021-11-28 00:42:42 +00:00
}
2021-11-29 03:54:52 +00:00
for impl_id in scope.impls() {
2021-11-29 07:17:18 +00:00
self.collect_from_impl(impl_id);
2021-11-29 03:54:52 +00:00
}
for const_id in scope.unnamed_consts() {
2021-11-29 07:17:18 +00:00
self.collect_from_body(const_id);
2021-11-29 03:54:52 +00:00
}
2021-11-29 05:22:30 +00:00
for macro_def_id in scope.macro_declarations() {
self.push_decl_macro(macro_def_id.into());
}
2021-11-29 03:54:52 +00:00
}
2021-11-29 07:17:18 +00:00
fn collect_from_body(&mut self, body_id: impl Into<DefWithBodyId>) {
let body_id = body_id.into();
2021-11-29 03:54:52 +00:00
let body = self.db.body(body_id);
// Descend into the blocks and enqueue collection of all modules within.
2021-11-29 05:22:30 +00:00
for (_, def_map) in body.blocks(self.db.upcast()) {
2021-11-29 03:54:52 +00:00
for (id, _) in def_map.modules() {
2021-11-29 07:17:18 +00:00
self.work.push(SymbolCollectorWork {
2021-11-29 03:54:52 +00:00
module_id: def_map.module_id(id),
parent: Some(body_id),
});
}
}
}
fn collect_from_impl(&mut self, impl_id: ImplId) {
let impl_data = self.db.impl_data(impl_id);
for &assoc_item_id in &impl_data.items {
self.push_assoc_item(assoc_item_id)
}
}
fn collect_from_trait(&mut self, trait_id: TraitId) {
let trait_data = self.db.trait_data(trait_id);
2021-11-29 07:17:18 +00:00
self.with_container_name(trait_data.name.as_text(), |s| {
for &(_, assoc_item_id) in &trait_data.items {
s.push_assoc_item(assoc_item_id);
}
});
2021-11-29 03:54:52 +00:00
}
fn with_container_name(&mut self, container_name: Option<SmolStr>, f: impl FnOnce(&mut Self)) {
if let Some(container_name) = container_name {
self.container_name_stack.push(container_name);
f(self);
self.container_name_stack.pop();
} else {
f(self);
}
}
fn current_container_name(&self) -> Option<SmolStr> {
self.container_name_stack.last().cloned()
2021-11-28 00:42:42 +00:00
}
2021-11-29 03:54:52 +00:00
fn def_with_body_id_name(&self, body_id: DefWithBodyId) -> Option<SmolStr> {
match body_id {
2021-11-29 05:22:30 +00:00
DefWithBodyId::FunctionId(id) => Some(
id.lookup(self.db.upcast()).source(self.db.upcast()).value.name()?.text().into(),
),
DefWithBodyId::StaticId(id) => Some(
id.lookup(self.db.upcast()).source(self.db.upcast()).value.name()?.text().into(),
),
DefWithBodyId::ConstId(id) => Some(
id.lookup(self.db.upcast()).source(self.db.upcast()).value.name()?.text().into(),
),
2021-11-29 03:54:52 +00:00
}
}
fn push_assoc_item(&mut self, assoc_item_id: AssocItemId) {
match assoc_item_id {
AssocItemId::FunctionId(id) => self.push_decl_assoc(id, FileSymbolKind::Function),
AssocItemId::ConstId(id) => self.push_decl_assoc(id, FileSymbolKind::Const),
AssocItemId::TypeAliasId(id) => self.push_decl_assoc(id, FileSymbolKind::TypeAlias),
}
}
fn push_decl_assoc<L, T>(&mut self, id: L, kind: FileSymbolKind)
2021-11-28 00:42:42 +00:00
where
L: Lookup<Data = AssocItemLoc<T>>,
T: ItemTreeNode,
<T as ItemTreeNode>::Source: HasName,
{
2021-11-29 03:54:52 +00:00
fn container_name(db: &dyn DefDatabase, container: AssocContainerId) -> Option<SmolStr> {
match container {
AssocContainerId::ModuleId(module_id) => {
let def_map = module_id.def_map(db);
let module_data = &def_map[module_id.local_id];
module_data
.origin
.declaration()
.and_then(|s| s.to_node(db.upcast()).name().map(|n| n.text().into()))
}
AssocContainerId::TraitId(trait_id) => {
let loc = trait_id.lookup(db);
let source = loc.source(db);
source.value.name().map(|n| n.text().into())
}
AssocContainerId::ImplId(_) => None,
}
}
self.push_file_symbol(|s| {
2021-11-29 05:22:30 +00:00
let loc = id.lookup(s.db.upcast());
let source = loc.source(s.db.upcast());
2021-11-29 03:54:52 +00:00
let name_node = source.value.name()?;
let container_name =
2021-11-29 05:22:30 +00:00
container_name(s.db.upcast(), loc.container).or_else(|| s.current_container_name());
2021-11-29 03:54:52 +00:00
Some(FileSymbol {
name: name_node.text().into(),
kind,
container_name,
loc: DeclarationLocation {
hir_file_id: source.file_id,
ptr: SyntaxNodePtr::new(source.value.syntax()),
name_ptr: SyntaxNodePtr::new(name_node.syntax()),
},
})
2021-11-27 11:25:05 +00:00
})
}
2021-11-28 00:42:42 +00:00
2021-11-29 03:54:52 +00:00
fn push_decl<L, T>(&mut self, id: L, kind: FileSymbolKind)
2021-11-27 11:25:05 +00:00
where
L: Lookup<Data = ItemLoc<T>>,
T: ItemTreeNode,
<T as ItemTreeNode>::Source: HasName,
{
2021-11-29 03:54:52 +00:00
self.push_file_symbol(|s| {
2021-11-29 05:22:30 +00:00
let loc = id.lookup(s.db.upcast());
let source = loc.source(s.db.upcast());
2021-11-29 03:54:52 +00:00
let name_node = source.value.name()?;
Some(FileSymbol {
name: name_node.text().into(),
kind,
container_name: s.current_container_name(),
loc: DeclarationLocation {
hir_file_id: source.file_id,
ptr: SyntaxNodePtr::new(source.value.syntax()),
name_ptr: SyntaxNodePtr::new(name_node.syntax()),
},
})
2021-11-27 11:25:05 +00:00
})
}
2021-11-29 03:54:52 +00:00
fn push_module(&mut self, module_id: ModuleId) {
self.push_file_symbol(|s| {
2021-11-29 05:22:30 +00:00
let def_map = module_id.def_map(s.db.upcast());
2021-11-29 03:54:52 +00:00
let module_data = &def_map[module_id.local_id];
let declaration = module_data.origin.declaration()?;
let module = declaration.to_node(s.db.upcast());
let name_node = module.name()?;
Some(FileSymbol {
name: name_node.text().into(),
kind: FileSymbolKind::Module,
container_name: s.current_container_name(),
loc: DeclarationLocation {
hir_file_id: declaration.file_id,
ptr: SyntaxNodePtr::new(module.syntax()),
name_ptr: SyntaxNodePtr::new(name_node.syntax()),
},
})
2021-11-27 11:25:05 +00:00
})
}
fn push_decl_macro(&mut self, macro_def: MacroDef) {
2021-11-29 05:22:30 +00:00
self.push_file_symbol(|s| {
let name = macro_def.name(s.db.upcast())?.as_text()?;
let source = macro_def.source(s.db.upcast())?;
let (ptr, name_ptr) = match source.value {
Either::Left(m) => {
(SyntaxNodePtr::new(m.syntax()), SyntaxNodePtr::new(m.name()?.syntax()))
}
Either::Right(f) => {
(SyntaxNodePtr::new(f.syntax()), SyntaxNodePtr::new(f.name()?.syntax()))
}
};
Some(FileSymbol {
name,
kind: FileSymbolKind::Macro,
container_name: s.current_container_name(),
loc: DeclarationLocation { hir_file_id: source.file_id, name_ptr, ptr },
})
})
}
2021-11-29 03:54:52 +00:00
fn push_file_symbol(&mut self, f: impl FnOnce(&Self) -> Option<FileSymbol>) {
if let Some(file_symbol) = f(self) {
self.symbols.push(file_symbol);
2021-11-27 11:25:05 +00:00
}
2021-11-29 01:09:39 +00:00
}
2021-11-27 11:25:05 +00:00
}
2021-11-29 10:36:22 +00:00
#[cfg(test)]
mod tests {
use base_db::fixture::WithFixture;
use expect_test::expect_file;
use super::*;
#[test]
fn test_symbol_index_collection() {
let (db, _) = RootDatabase::with_many_files(
r#"
//- /main.rs
macro_rules! macro_rules_macro {
() => {}
};
macro Macro { }
struct Struct;
enum Enum {
A, B
}
union Union {}
impl Struct {
fn impl_fn() {}
}
trait Trait {
fn trait_fn(&self);
}
fn main() {
struct StructInFn;
}
const CONST: u32 = 1;
static STATIC: &'static str = "2";
type Alias = Struct;
mod a_mod {
struct StructInModA;
}
mod b_mod;
//- /b_mod.rs
struct StructInModB;
"#,
);
let symbols: Vec<_> = module_ids_for_crate(db.upcast(), db.test_crate())
.into_iter()
.map(|module_id| {
(module_id, SymbolCollector::collect(&db as &dyn SymbolsDatabase, module_id))
})
.collect();
expect_file!["./test_data/test_symbol_index_collection.txt"].assert_debug_eq(&symbols);
}
}