rust/crates/hir_def/src/import_map.rs

1097 lines
32 KiB
Rust
Raw Normal View History

2020-05-20 16:51:20 -05:00
//! A map of all publicly exported items in a crate.
use std::{cmp::Ordering, fmt, hash::BuildHasherDefault, sync::Arc};
2020-06-05 06:15:16 -05:00
2020-08-13 09:25:38 -05:00
use base_db::CrateId;
2020-06-09 10:32:42 -05:00
use fst::{self, Streamer};
use hir_expand::name::Name;
use indexmap::{map::Entry, IndexMap};
use itertools::Itertools;
2021-01-01 18:05:09 -06:00
use rustc_hash::{FxHashSet, FxHasher};
2021-01-04 14:01:35 -06:00
use test_utils::mark;
2020-06-05 06:15:16 -05:00
2020-05-20 16:51:20 -05:00
use crate::{
db::DefDatabase, item_scope::ItemInNs, visibility::Visibility, AssocItemId, ModuleDefId,
ModuleId, TraitId,
2020-05-20 16:51:20 -05:00
};
type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
/// Item import details stored in the `ImportMap`.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ImportInfo {
/// A path that can be used to import the item, relative to the crate's root.
pub path: ImportPath,
/// The module containing this item.
pub container: ModuleId,
2021-01-01 18:05:09 -06:00
/// Whether the import is a trait associated item or not.
2021-01-03 04:24:50 -06:00
pub is_trait_assoc_item: bool,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ImportPath {
pub segments: Vec<Name>,
}
impl fmt::Display for ImportPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.segments.iter().format("::"), f)
}
}
impl ImportPath {
fn len(&self) -> usize {
self.segments.len()
}
}
2020-05-20 16:51:20 -05:00
/// A map from publicly exported items to the path needed to import/name them from a downstream
/// crate.
///
/// Reexports of items are taken into account, ie. if something is exported under multiple
/// names, the one with the shortest import path will be used.
///
/// Note that all paths are relative to the containing crate's root, so the crate name still needs
/// to be prepended to the `ModPath` before the path is valid.
#[derive(Default)]
2020-05-20 16:51:20 -05:00
pub struct ImportMap {
map: FxIndexMap<ItemInNs, ImportInfo>,
2020-06-09 10:32:42 -05:00
/// List of keys stored in `map`, sorted lexicographically by their `ModPath`. Indexed by the
/// values returned by running `fst`.
///
/// Since a path can refer to multiple items due to namespacing, we store all items with the
/// same path right after each other. This allows us to find all items after the FST gives us
/// the index of the first one.
importables: Vec<ItemInNs>,
fst: fst::Map<Vec<u8>>,
2020-05-20 16:51:20 -05:00
}
impl ImportMap {
pub fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> {
2020-08-12 09:32:36 -05:00
let _p = profile::span("import_map_query");
2020-05-20 16:51:20 -05:00
let def_map = db.crate_def_map(krate);
let mut import_map = Self::default();
2020-05-20 16:51:20 -05:00
// We look only into modules that are public(ly reexported), starting with the crate root.
let empty = ImportPath { segments: vec![] };
2021-01-20 08:41:18 -06:00
let root = ModuleId { krate, local_id: def_map.root() };
2020-05-20 16:51:20 -05:00
let mut worklist = vec![(root, empty)];
while let Some((module, mod_path)) = worklist.pop() {
let ext_def_map;
let mod_data = if module.krate == krate {
&def_map[module.local_id]
} else {
// The crate might reexport a module defined in another crate.
ext_def_map = module.def_map(db);
2020-05-20 16:51:20 -05:00
&ext_def_map[module.local_id]
};
let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public);
if per_ns.is_none() {
None
} else {
Some((name, per_ns))
}
});
for (name, per_ns) in visible_items {
let mk_path = || {
let mut path = mod_path.clone();
path.segments.push(name.clone());
path
};
for item in per_ns.iter_items() {
let path = mk_path();
2021-01-01 18:05:09 -06:00
let path_len = path.len();
2021-01-03 04:24:50 -06:00
let import_info =
ImportInfo { path, container: module, is_trait_assoc_item: false };
2021-01-01 18:05:09 -06:00
if let Some(ModuleDefId::TraitId(tr)) = item.as_module_def_id() {
2021-01-03 04:24:50 -06:00
import_map.collect_trait_assoc_items(
db,
tr,
matches!(item, ItemInNs::Types(_)),
&import_info,
);
2021-01-01 18:05:09 -06:00
}
match import_map.map.entry(item) {
2020-05-20 16:51:20 -05:00
Entry::Vacant(entry) => {
2021-01-01 18:05:09 -06:00
entry.insert(import_info);
2020-05-20 16:51:20 -05:00
}
Entry::Occupied(mut entry) => {
// If the new path is shorter, prefer that one.
2021-01-01 18:05:09 -06:00
if path_len < entry.get().path.len() {
*entry.get_mut() = import_info;
2020-05-20 16:51:20 -05:00
} else {
continue;
}
}
}
// If we've just added a path to a module, descend into it. We might traverse
// modules multiple times, but only if the new path to it is shorter than the
// first (else we `continue` above).
2020-05-20 16:51:20 -05:00
if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() {
worklist.push((mod_id, mk_path()));
}
}
}
}
let mut importables = import_map.map.iter().collect::<Vec<_>>();
2020-06-09 10:32:42 -05:00
importables.sort_by(cmp);
// Build the FST, taking care not to insert duplicate values.
let mut builder = fst::MapBuilder::memory();
let mut last_batch_start = 0;
for idx in 0..importables.len() {
if let Some(next_item) = importables.get(idx + 1) {
if cmp(&importables[last_batch_start], next_item) == Ordering::Equal {
continue;
}
}
2021-01-01 18:05:09 -06:00
let key = fst_path(&importables[last_batch_start].1.path);
builder.insert(key, last_batch_start as u64).unwrap();
2020-06-09 10:32:42 -05:00
2021-01-01 18:05:09 -06:00
last_batch_start = idx + 1;
2020-06-09 10:32:42 -05:00
}
import_map.fst = fst::Map::new(builder.into_inner().unwrap()).unwrap();
import_map.importables = importables.iter().map(|(item, _)| **item).collect();
2020-06-09 10:32:42 -05:00
Arc::new(import_map)
2020-05-20 16:51:20 -05:00
}
/// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root.
pub fn path_of(&self, item: ItemInNs) -> Option<&ImportPath> {
self.import_info_for(item).map(|it| &it.path)
}
pub fn import_info_for(&self, item: ItemInNs) -> Option<&ImportInfo> {
2020-05-20 16:51:20 -05:00
self.map.get(&item)
}
2021-01-01 18:05:09 -06:00
fn collect_trait_assoc_items(
&mut self,
db: &dyn DefDatabase,
tr: TraitId,
2021-01-03 04:24:50 -06:00
is_type_in_ns: bool,
original_import_info: &ImportInfo,
2021-01-01 18:05:09 -06:00
) {
2021-01-03 04:24:50 -06:00
for (assoc_item_name, item) in &db.trait_data(tr).items {
2021-01-03 08:16:09 -06:00
let module_def_id = match item {
AssocItemId::FunctionId(f) => ModuleDefId::from(*f),
AssocItemId::ConstId(c) => ModuleDefId::from(*c),
// cannot use associated type aliases directly: need a `<Struct as Trait>::TypeAlias`
// qualifier, ergo no need to store it for imports in import_map
2021-01-05 06:03:58 -06:00
AssocItemId::TypeAliasId(_) => {
mark::hit!(type_aliases_ignored);
continue;
}
2021-01-03 04:24:50 -06:00
};
let assoc_item = if is_type_in_ns {
ItemInNs::Types(module_def_id)
} else {
ItemInNs::Values(module_def_id)
};
2021-01-04 10:33:05 -06:00
let mut assoc_item_info = original_import_info.clone();
2021-01-01 18:05:09 -06:00
assoc_item_info.path.segments.push(assoc_item_name.to_owned());
2021-01-03 04:24:50 -06:00
assoc_item_info.is_trait_assoc_item = true;
2021-01-01 18:05:09 -06:00
self.map.insert(assoc_item, assoc_item_info);
}
}
2020-05-20 16:51:20 -05:00
}
2020-06-09 10:32:42 -05:00
impl PartialEq for ImportMap {
fn eq(&self, other: &Self) -> bool {
2020-06-10 04:52:00 -05:00
// `fst` and `importables` are built from `map`, so we don't need to compare them.
self.map == other.map
2020-06-09 10:32:42 -05:00
}
}
impl Eq for ImportMap {}
2020-06-05 06:36:19 -05:00
impl fmt::Debug for ImportMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut importable_paths: Vec<_> = self
.map
.iter()
.map(|(item, info)| {
2020-06-05 06:36:19 -05:00
let ns = match item {
ItemInNs::Types(_) => "t",
ItemInNs::Values(_) => "v",
ItemInNs::Macros(_) => "m",
};
format!("- {} ({})", info.path, ns)
2020-06-05 06:36:19 -05:00
})
.collect();
importable_paths.sort();
f.write_str(&importable_paths.join("\n"))
}
}
2020-12-28 06:24:13 -06:00
fn fst_path(path: &ImportPath) -> String {
let mut s = path.to_string();
2020-06-10 04:52:00 -05:00
s.make_ascii_lowercase();
s
2020-06-09 10:32:42 -05:00
}
fn cmp((_, lhs): &(&ItemInNs, &ImportInfo), (_, rhs): &(&ItemInNs, &ImportInfo)) -> Ordering {
2020-12-28 06:24:13 -06:00
let lhs_str = fst_path(&lhs.path);
let rhs_str = fst_path(&rhs.path);
2020-06-10 04:52:00 -05:00
lhs_str.cmp(&rhs_str)
2020-06-09 10:32:42 -05:00
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum ImportKind {
Module,
Function,
Adt,
EnumVariant,
Const,
Static,
Trait,
TypeAlias,
BuiltinType,
AssociatedItem,
}
2020-12-28 06:54:31 -06:00
/// A way to match import map contents against the search query.
2020-12-28 06:24:13 -06:00
#[derive(Debug)]
pub enum SearchMode {
2020-12-28 06:54:31 -06:00
/// Import map entry should strictly match the query string.
2020-12-28 06:24:13 -06:00
Equals,
2020-12-28 06:54:31 -06:00
/// Import map entry should contain the query string.
2020-12-28 06:24:13 -06:00
Contains,
2020-12-28 06:54:31 -06:00
/// Import map entry should contain all letters from the query string,
/// in the same order, but not necessary adjacent.
2020-12-28 06:24:13 -06:00
Fuzzy,
}
2020-06-09 10:32:42 -05:00
#[derive(Debug)]
pub struct Query {
query: String,
lowercased: String,
2020-12-28 03:41:08 -06:00
name_only: bool,
assoc_items_only: bool,
2020-12-28 06:24:13 -06:00
search_mode: SearchMode,
case_sensitive: bool,
2020-06-10 05:30:33 -05:00
limit: usize,
exclude_import_kinds: FxHashSet<ImportKind>,
2020-06-09 10:32:42 -05:00
}
impl Query {
2020-12-29 06:35:49 -06:00
pub fn new(query: String) -> Self {
let lowercased = query.to_lowercase();
Self {
2020-12-29 06:35:49 -06:00
query,
lowercased,
2020-12-28 03:41:08 -06:00
name_only: false,
assoc_items_only: false,
2020-12-28 06:24:13 -06:00
search_mode: SearchMode::Contains,
case_sensitive: false,
limit: usize::max_value(),
exclude_import_kinds: FxHashSet::default(),
}
2020-06-09 10:32:42 -05:00
}
2020-12-28 06:54:31 -06:00
/// Matches entries' names only, ignoring the rest of
/// the qualifier.
/// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
2020-12-28 03:41:08 -06:00
pub fn name_only(self) -> Self {
Self { name_only: true, ..self }
}
/// Matches only the entries that are associated items, ignoring the rest.
pub fn assoc_items_only(self) -> Self {
Self { assoc_items_only: true, ..self }
}
2020-12-28 06:54:31 -06:00
/// Specifies the way to search for the entries using the query.
2020-12-28 06:24:13 -06:00
pub fn search_mode(self, search_mode: SearchMode) -> Self {
Self { search_mode, ..self }
2020-06-09 10:32:42 -05:00
}
2020-06-10 05:30:33 -05:00
/// Limits the returned number of items to `limit`.
pub fn limit(self, limit: usize) -> Self {
Self { limit, ..self }
}
/// Respect casing of the query string when matching.
pub fn case_sensitive(self) -> Self {
Self { case_sensitive: true, ..self }
}
/// Do not include imports of the specified kind in the search results.
pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
self.exclude_import_kinds.insert(import_kind);
self
}
2020-06-09 10:32:42 -05:00
2021-01-04 10:33:05 -06:00
fn import_matches(&self, import: &ImportInfo, enforce_lowercase: bool) -> bool {
if import.is_trait_assoc_item {
if self.exclude_import_kinds.contains(&ImportKind::AssociatedItem) {
return false;
}
} else if self.assoc_items_only {
return false;
}
2021-01-04 10:33:05 -06:00
let mut input = if import.is_trait_assoc_item || self.name_only {
import.path.segments.last().unwrap().to_string()
} else {
import.path.to_string()
};
if enforce_lowercase || !self.case_sensitive {
input.make_ascii_lowercase();
}
2020-12-28 03:41:08 -06:00
2021-01-04 10:33:05 -06:00
let query_string =
if !enforce_lowercase && self.case_sensitive { &self.query } else { &self.lowercased };
match self.search_mode {
SearchMode::Equals => &input == query_string,
SearchMode::Contains => input.contains(query_string),
SearchMode::Fuzzy => {
let mut unchecked_query_chars = query_string.chars();
let mut mismatching_query_char = unchecked_query_chars.next();
for input_char in input.chars() {
match mismatching_query_char {
None => return true,
Some(matching_query_char) if matching_query_char == input_char => {
mismatching_query_char = unchecked_query_chars.next();
}
_ => (),
2020-12-28 06:24:13 -06:00
}
}
2021-01-04 10:33:05 -06:00
mismatching_query_char.is_none()
2020-12-28 06:24:13 -06:00
}
2020-12-28 03:41:08 -06:00
}
}
}
2020-06-09 10:32:42 -05:00
/// Searches dependencies of `krate` for an importable path matching `query`.
///
2020-06-10 04:52:00 -05:00
/// This returns a list of items that could be imported from dependencies of `krate`.
2020-06-09 10:32:42 -05:00
pub fn search_dependencies<'a>(
db: &'a dyn DefDatabase,
krate: CrateId,
query: Query,
) -> Vec<ItemInNs> {
2020-08-12 09:32:36 -05:00
let _p = profile::span("search_dependencies").detail(|| format!("{:?}", query));
2020-06-09 10:32:42 -05:00
let graph = db.crate_graph();
let import_maps: Vec<_> =
graph[krate].dependencies.iter().map(|dep| db.import_map(dep.crate_id)).collect();
let automaton = fst::automaton::Subsequence::new(&query.lowercased);
2020-06-09 10:32:42 -05:00
let mut op = fst::map::OpBuilder::new();
for map in &import_maps {
op = op.add(map.fst.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 import_map = &import_maps[indexed_value.index];
let importables = &import_map.importables[indexed_value.value as usize..];
2021-01-01 18:05:09 -06:00
let common_importable_data = &import_map.map[&importables[0]];
2021-01-04 10:33:05 -06:00
if !query.import_matches(common_importable_data, true) {
2020-12-28 03:41:08 -06:00
continue;
2020-06-09 10:32:42 -05:00
}
2021-01-01 18:05:09 -06:00
// Path shared by the importable items in this group.
let common_importables_path_fst = fst_path(&common_importable_data.path);
2020-06-09 10:32:42 -05:00
// Add the items from this `ModPath` group. Those are all subsequent items in
// `importables` whose paths match `path`.
let iter = importables
.iter()
.copied()
.take_while(|item| {
2020-12-28 06:24:13 -06:00
common_importables_path_fst == fst_path(&import_map.map[item].path)
})
.filter(|&item| match item_import_kind(item) {
Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
None => true,
2020-12-28 03:41:08 -06:00
})
2020-12-28 06:54:31 -06:00
.filter(|item| {
!query.case_sensitive // we've already checked the common importables path case-insensitively
2021-01-04 10:33:05 -06:00
|| query.import_matches(&import_map.map[item], false)
2020-12-28 06:54:31 -06:00
});
2020-12-28 03:41:08 -06:00
res.extend(iter);
2020-06-10 05:30:33 -05:00
if res.len() >= query.limit {
res.truncate(query.limit);
return res;
}
2020-06-09 10:32:42 -05:00
}
}
res
}
fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
Some(match item.as_module_def_id()? {
ModuleDefId::ModuleId(_) => ImportKind::Module,
ModuleDefId::FunctionId(_) => ImportKind::Function,
ModuleDefId::AdtId(_) => ImportKind::Adt,
ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
ModuleDefId::ConstId(_) => ImportKind::Const,
ModuleDefId::StaticId(_) => ImportKind::Static,
ModuleDefId::TraitId(_) => ImportKind::Trait,
ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
})
}
2020-05-20 16:51:20 -05:00
#[cfg(test)]
mod tests {
2020-08-13 09:25:38 -05:00
use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
2020-08-21 06:19:31 -05:00
use expect_test::{expect, Expect};
2021-01-04 14:01:35 -06:00
use test_utils::mark;
2020-05-20 16:51:20 -05:00
2021-01-03 04:08:08 -06:00
use crate::{test_db::TestDB, AssocContainerId, Lookup};
2020-05-20 16:51:20 -05:00
2020-07-17 08:54:40 -05:00
use super::*;
2020-05-20 16:51:20 -05:00
2020-10-02 13:38:22 -05:00
fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
2020-06-09 10:32:42 -05:00
let db = TestDB::with_files(ra_fixture);
let crate_graph = db.crate_graph();
let krate = crate_graph
.iter()
.find(|krate| {
crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
2020-10-02 13:38:22 -05:00
== Some(crate_name.to_string())
2020-06-09 10:32:42 -05:00
})
.unwrap();
2020-07-17 08:54:40 -05:00
let actual = search_dependencies(db.upcast(), krate, query)
2020-06-09 10:32:42 -05:00
.into_iter()
2021-01-03 04:08:08 -06:00
.filter_map(|dependency| {
let dependency_krate = dependency.krate(db.upcast())?;
let dependency_imports = db.import_map(dependency_krate);
let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
Some(assoc_item_path) => (assoc_item_path, "a"),
None => (
dependency_imports.path_of(dependency)?.to_string(),
match dependency {
2021-01-03 04:24:50 -06:00
ItemInNs::Types(ModuleDefId::FunctionId(_))
| ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
2021-01-03 04:08:08 -06:00
ItemInNs::Types(_) => "t",
ItemInNs::Values(_) => "v",
ItemInNs::Macros(_) => "m",
},
),
2020-06-09 10:32:42 -05:00
};
2021-01-03 04:08:08 -06:00
Some(format!(
"{}::{} ({})\n",
crate_graph[dependency_krate].display_name.as_ref()?,
path,
mark
))
2020-06-09 10:32:42 -05:00
})
2020-07-17 08:54:40 -05:00
.collect::<String>();
expect.assert_eq(&actual)
2020-06-09 10:32:42 -05:00
}
2021-01-03 04:08:08 -06:00
fn assoc_item_path(
db: &dyn DefDatabase,
dependency_imports: &ImportMap,
dependency: ItemInNs,
) -> Option<String> {
2021-01-03 04:24:50 -06:00
let dependency_assoc_item_id = match dependency {
ItemInNs::Types(ModuleDefId::FunctionId(id))
| ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
ItemInNs::Types(ModuleDefId::ConstId(id))
| ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
ItemInNs::Types(ModuleDefId::TypeAliasId(id))
| ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
_ => return None,
};
2021-01-03 04:08:08 -06:00
let trait_ = assoc_to_trait(db, dependency)?;
if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
let trait_data = db.trait_data(tr);
let assoc_item_name =
trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
if &dependency_assoc_item_id == assoc_item_id {
Some(assoc_item_name)
} else {
None
}
})?;
return Some(format!("{}::{}", dependency_imports.path_of(trait_)?, assoc_item_name));
}
None
}
2020-12-28 08:13:37 -06:00
fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
2020-07-02 06:34:08 -05:00
let assoc: AssocItemId = match item {
ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
ModuleDefId::TypeAliasId(it) => it.into(),
ModuleDefId::FunctionId(it) => it.into(),
ModuleDefId::ConstId(it) => it.into(),
2020-12-28 08:13:37 -06:00
_ => return None,
2020-07-02 06:34:08 -05:00
},
2020-12-28 08:13:37 -06:00
_ => return None,
2020-07-02 06:34:08 -05:00
};
let container = match assoc {
AssocItemId::FunctionId(it) => it.lookup(db).container,
AssocItemId::ConstId(it) => it.lookup(db).container,
AssocItemId::TypeAliasId(it) => it.lookup(db).container,
};
match container {
2020-12-28 08:13:37 -06:00
AssocContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
_ => None,
2020-07-02 06:34:08 -05:00
}
}
2020-07-17 08:54:40 -05:00
fn check(ra_fixture: &str, expect: Expect) {
let db = TestDB::with_files(ra_fixture);
let crate_graph = db.crate_graph();
let actual = crate_graph
.iter()
.filter_map(|krate| {
let cdata = &crate_graph[krate];
let name = cdata.display_name.as_ref()?;
2020-07-17 08:54:40 -05:00
let map = db.import_map(krate);
Some(format!("{}:\n{:?}\n", name, map))
})
.collect::<String>();
expect.assert_eq(&actual)
}
2020-05-20 16:51:20 -05:00
#[test]
fn smoke() {
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /main.rs crate:main deps:lib
mod private {
pub use lib::Pub;
pub struct InPrivateModule;
}
pub mod publ1 {
use lib::Pub;
}
pub mod real_pub {
pub use lib::Pub;
}
pub mod real_pu2 { // same path length as above
pub use lib::Pub;
}
//- /lib.rs crate:lib
pub struct Pub {}
pub struct Pub2; // t + v
struct Priv;
",
2020-07-17 08:54:40 -05:00
expect![[r#"
main:
- publ1 (t)
- real_pu2 (t)
- real_pub (t)
- real_pub::Pub (t)
lib:
- Pub (t)
- Pub2 (t)
- Pub2 (v)
"#]],
2020-05-20 16:51:20 -05:00
);
}
#[test]
fn prefers_shortest_path() {
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /main.rs crate:main
pub mod sub {
pub mod subsub {
pub struct Def {}
}
pub use super::sub::subsub::Def;
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
main:
- sub (t)
- sub::Def (t)
- sub::subsub (t)
"#]],
2020-05-20 16:51:20 -05:00
);
}
#[test]
fn type_reexport_cross_crate() {
// Reexports need to be visible from a crate, even if the original crate exports the item
// at a shorter path.
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /main.rs crate:main deps:lib
pub mod m {
pub use lib::S;
}
//- /lib.rs crate:lib
pub struct S;
",
2020-07-17 08:54:40 -05:00
expect![[r#"
main:
- m (t)
- m::S (t)
- m::S (v)
lib:
- S (t)
- S (v)
"#]],
2020-05-20 16:51:20 -05:00
);
}
#[test]
fn macro_reexport() {
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /main.rs crate:main deps:lib
pub mod m {
pub use lib::pub_macro;
}
//- /lib.rs crate:lib
#[macro_export]
macro_rules! pub_macro {
() => {};
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
main:
- m (t)
- m::pub_macro (m)
lib:
- pub_macro (m)
"#]],
2020-05-20 16:51:20 -05:00
);
}
#[test]
fn module_reexport() {
// Reexporting modules from a dependency adds all contents to the import map.
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /main.rs crate:main deps:lib
pub use lib::module as reexported_module;
//- /lib.rs crate:lib
pub mod module {
pub struct S;
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
main:
- reexported_module (t)
- reexported_module::S (t)
- reexported_module::S (v)
lib:
- module (t)
- module::S (t)
- module::S (v)
"#]],
2020-05-20 16:51:20 -05:00
);
}
#[test]
fn cyclic_module_reexport() {
2020-06-05 06:04:35 -05:00
// A cyclic reexport does not hang.
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /lib.rs crate:lib
pub mod module {
pub struct S;
pub use super::sub::*;
}
pub mod sub {
pub use super::module;
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
lib:
- module (t)
- module::S (t)
- module::S (v)
- sub (t)
"#]],
2020-05-20 16:51:20 -05:00
);
}
#[test]
fn private_macro() {
2020-07-17 08:54:40 -05:00
check(
2020-05-20 16:51:20 -05:00
r"
//- /lib.rs crate:lib
macro_rules! private_macro {
() => {};
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
lib:
2020-05-20 16:51:20 -05:00
2020-07-17 08:54:40 -05:00
"#]],
);
2020-05-20 16:51:20 -05:00
}
2020-06-09 10:32:42 -05:00
#[test]
fn namespacing() {
2020-07-17 08:54:40 -05:00
check(
2020-06-09 10:32:42 -05:00
r"
//- /lib.rs crate:lib
pub struct Thing; // t + v
#[macro_export]
macro_rules! Thing { // m
() => {};
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
lib:
- Thing (m)
- Thing (t)
- Thing (v)
"#]],
2020-06-09 10:32:42 -05:00
);
2020-07-17 08:54:40 -05:00
check(
2020-06-09 10:32:42 -05:00
r"
//- /lib.rs crate:lib
pub mod Thing {} // t
#[macro_export]
macro_rules! Thing { // m
() => {};
}
",
2020-07-17 08:54:40 -05:00
expect![[r#"
lib:
- Thing (m)
- Thing (t)
"#]],
2020-06-09 10:32:42 -05:00
);
}
#[test]
2021-01-03 04:08:08 -06:00
fn fuzzy_import_trait_and_assoc_items() {
2021-01-04 14:01:35 -06:00
mark::check!(type_aliases_ignored);
let ra_fixture = r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep
pub mod fmt {
pub trait Display {
2021-01-03 04:08:08 -06:00
type FmtTypeAlias;
const FMT_CONST: bool;
fn format_function();
fn format_method(&self);
}
}
"#;
check_search(
ra_fixture,
"main",
Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
expect![[r#"
dep::fmt (t)
dep::fmt::Display (t)
2021-01-03 04:08:08 -06:00
dep::fmt::Display::FMT_CONST (a)
dep::fmt::Display::format_function (a)
dep::fmt::Display::format_method (a)
"#]],
);
}
#[test]
fn assoc_items_filtering() {
let ra_fixture = r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep
pub mod fmt {
pub trait Display {
type FmtTypeAlias;
const FMT_CONST: bool;
fn format_function();
fn format_method(&self);
}
}
"#;
check_search(
ra_fixture,
"main",
Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(),
expect![[r#"
dep::fmt::Display::FMT_CONST (a)
dep::fmt::Display::format_function (a)
dep::fmt::Display::format_method (a)
"#]],
);
check_search(
ra_fixture,
"main",
Query::new("fmt".to_string())
.search_mode(SearchMode::Fuzzy)
.exclude_import_kind(ImportKind::AssociatedItem),
expect![[r#"
dep::fmt (t)
dep::fmt::Display (t)
"#]],
);
check_search(
ra_fixture,
"main",
Query::new("fmt".to_string())
.search_mode(SearchMode::Fuzzy)
.assoc_items_only()
.exclude_import_kind(ImportKind::AssociatedItem),
expect![[r#""#]],
);
}
2020-06-09 10:32:42 -05:00
#[test]
2020-12-28 07:22:03 -06:00
fn search_mode() {
2020-06-09 10:32:42 -05:00
let ra_fixture = r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep deps:tdep
use tdep::fmt as fmt_dep;
pub mod fmt {
pub trait Display {
fn fmt();
}
}
#[macro_export]
macro_rules! Fmt {
() => {};
}
pub struct Fmt;
pub fn format() {}
pub fn no() {}
//- /tdep.rs crate:tdep
pub mod fmt {
pub struct NotImportableFromMain;
}
"#;
2020-07-17 08:54:40 -05:00
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
2020-07-17 08:54:40 -05:00
expect![[r#"
dep::fmt (t)
dep::Fmt (t)
dep::Fmt (v)
dep::Fmt (m)
dep::fmt::Display (t)
2021-01-03 04:08:08 -06:00
dep::fmt::Display::fmt (a)
2021-01-03 04:24:50 -06:00
dep::format (f)
2020-07-17 08:54:40 -05:00
"#]],
);
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
2020-12-28 07:22:03 -06:00
expect![[r#"
dep::fmt (t)
dep::Fmt (t)
dep::Fmt (v)
dep::Fmt (m)
2021-01-03 04:08:08 -06:00
dep::fmt::Display::fmt (a)
2020-12-28 07:22:03 -06:00
"#]],
);
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
2020-12-28 07:22:03 -06:00
expect![[r#"
dep::fmt (t)
dep::Fmt (t)
dep::Fmt (v)
dep::Fmt (m)
dep::fmt::Display (t)
2021-01-03 04:08:08 -06:00
dep::fmt::Display::fmt (a)
2020-12-28 07:22:03 -06:00
"#]],
);
}
#[test]
fn name_only() {
let ra_fixture = r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep deps:tdep
use tdep::fmt as fmt_dep;
pub mod fmt {
pub trait Display {
fn fmt();
}
}
#[macro_export]
macro_rules! Fmt {
() => {};
}
pub struct Fmt;
pub fn format() {}
pub fn no() {}
//- /tdep.rs crate:tdep
pub mod fmt {
pub struct NotImportableFromMain;
}
"#;
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("fmt".to_string()),
2020-12-28 07:22:03 -06:00
expect![[r#"
dep::fmt (t)
dep::Fmt (t)
dep::Fmt (v)
dep::Fmt (m)
dep::fmt::Display (t)
2021-01-03 04:08:08 -06:00
dep::fmt::Display::fmt (a)
2020-12-28 07:22:03 -06:00
"#]],
);
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("fmt".to_string()).name_only(),
2020-07-17 08:54:40 -05:00
expect![[r#"
dep::fmt (t)
dep::Fmt (t)
dep::Fmt (v)
dep::Fmt (m)
2021-01-03 04:08:08 -06:00
dep::fmt::Display::fmt (a)
2020-07-17 08:54:40 -05:00
"#]],
);
2020-06-09 10:32:42 -05:00
}
2020-06-10 05:30:33 -05:00
#[test]
fn search_casing() {
let ra_fixture = r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep
pub struct fmt;
pub struct FMT;
"#;
2020-07-17 08:54:40 -05:00
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("FMT".to_string()),
2020-07-17 08:54:40 -05:00
expect![[r#"
dep::fmt (t)
dep::fmt (v)
dep::FMT (t)
dep::FMT (v)
"#]],
);
2020-07-17 08:54:40 -05:00
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("FMT".to_string()).case_sensitive(),
2020-07-17 08:54:40 -05:00
expect![[r#"
dep::FMT (t)
dep::FMT (v)
"#]],
);
}
2020-06-10 05:30:33 -05:00
#[test]
fn search_limit() {
2020-07-17 08:54:40 -05:00
check_search(
2020-06-10 05:30:33 -05:00
r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep
pub mod fmt {
pub trait Display {
fn fmt();
}
}
#[macro_export]
macro_rules! Fmt {
() => {};
}
pub struct Fmt;
pub fn format() {}
pub fn no() {}
"#,
"main",
2020-12-29 06:35:49 -06:00
Query::new("".to_string()).limit(2),
2020-07-17 08:54:40 -05:00
expect![[r#"
dep::fmt (t)
dep::Fmt (t)
"#]],
2020-06-10 05:30:33 -05:00
);
}
#[test]
fn search_exclusions() {
let ra_fixture = r#"
//- /main.rs crate:main deps:dep
//- /dep.rs crate:dep
pub struct fmt;
pub struct FMT;
"#;
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("FMT".to_string()),
expect![[r#"
dep::fmt (t)
dep::fmt (v)
dep::FMT (t)
dep::FMT (v)
"#]],
);
check_search(
ra_fixture,
"main",
2020-12-29 06:35:49 -06:00
Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),
expect![[r#""#]],
);
}
2020-05-20 16:51:20 -05:00
}