Skip to content

Commit ad810a5

Browse files
committed
Auto merge of #17277 - Veykril:find-path-fixes, r=Veykril
fix: Various find path fixes Fixes rust-lang/rust-analyzer#17271
2 parents d9dda8f + b1830a5 commit ad810a5

33 files changed

+647
-346
lines changed

src/tools/rust-analyzer/crates/hir-def/src/find_path.rs

+565-269
Large diffs are not rendered by default.

src/tools/rust-analyzer/crates/hir-def/src/import_map.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
//! A map of all publicly exported items in a crate.
22
3-
use std::{fmt, hash::BuildHasherDefault};
3+
use std::fmt;
44

55
use base_db::CrateId;
66
use fst::{raw::IndexedValue, Automaton, Streamer};
77
use hir_expand::name::Name;
8-
use indexmap::IndexMap;
98
use itertools::Itertools;
10-
use rustc_hash::{FxHashSet, FxHasher};
9+
use rustc_hash::FxHashSet;
1110
use smallvec::SmallVec;
1211
use stdx::{format_to, TupleExt};
1312
use triomphe::Arc;
@@ -17,7 +16,7 @@ use crate::{
1716
item_scope::{ImportOrExternCrate, ItemInNs},
1817
nameres::DefMap,
1918
visibility::Visibility,
20-
AssocItemId, ModuleDefId, ModuleId, TraitId,
19+
AssocItemId, FxIndexMap, ModuleDefId, ModuleId, TraitId,
2120
};
2221

2322
/// Item import details stored in the `ImportMap`.
@@ -58,7 +57,6 @@ enum IsTraitAssocItem {
5857
No,
5958
}
6059

61-
type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
6260
type ImportMapIndex = FxIndexMap<ItemInNs, (SmallVec<[ImportInfo; 1]>, IsTraitAssocItem)>;
6361

6462
impl ImportMap {

src/tools/rust-analyzer/crates/hir-def/src/item_scope.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ impl ItemScope {
295295
pub(crate) fn names_of<T>(
296296
&self,
297297
item: ItemInNs,
298-
mut cb: impl FnMut(&Name, Visibility, bool) -> Option<T>,
298+
mut cb: impl FnMut(&Name, Visibility, /*declared*/ bool) -> Option<T>,
299299
) -> Option<T> {
300300
match item {
301301
ItemInNs::Macros(def) => self

src/tools/rust-analyzer/crates/hir-def/src/lib.rs

+23
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,9 @@ use crate::{
106106
},
107107
};
108108

109+
type FxIndexMap<K, V> =
110+
indexmap::IndexMap<K, V, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
111+
109112
#[derive(Debug)]
110113
pub struct ItemLoc<N: ItemTreeNode> {
111114
pub container: ModuleId,
@@ -455,6 +458,26 @@ impl ModuleId {
455458
pub fn is_block_module(self) -> bool {
456459
self.block.is_some() && self.local_id == DefMap::ROOT
457460
}
461+
462+
pub fn is_within_block(self) -> bool {
463+
self.block.is_some()
464+
}
465+
466+
pub fn as_crate_root(&self) -> Option<CrateRootModuleId> {
467+
if self.local_id == DefMap::ROOT && self.block.is_none() {
468+
Some(CrateRootModuleId { krate: self.krate })
469+
} else {
470+
None
471+
}
472+
}
473+
474+
pub fn derive_crate_root(&self) -> CrateRootModuleId {
475+
CrateRootModuleId { krate: self.krate }
476+
}
477+
478+
fn is_crate_root(&self) -> bool {
479+
self.local_id == DefMap::ROOT && self.block.is_none()
480+
}
458481
}
459482

460483
impl PartialEq<CrateRootModuleId> for ModuleId {

src/tools/rust-analyzer/crates/hir-def/src/nameres.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ use crate::{
8181
per_ns::PerNs,
8282
visibility::{Visibility, VisibilityExplicitness},
8383
AstId, BlockId, BlockLoc, CrateRootModuleId, EnumId, EnumVariantId, ExternCrateId, FunctionId,
84-
LocalModuleId, Lookup, MacroExpander, MacroId, ModuleId, ProcMacroId, UseId,
84+
FxIndexMap, LocalModuleId, Lookup, MacroExpander, MacroId, ModuleId, ProcMacroId, UseId,
8585
};
8686

8787
const PREDEFINED_TOOLS: &[SmolStr] = &[
@@ -137,7 +137,7 @@ pub struct DefMap {
137137
#[derive(Clone, Debug, PartialEq, Eq)]
138138
struct DefMapCrateData {
139139
/// The extern prelude which contains all root modules of external crates that are in scope.
140-
extern_prelude: FxHashMap<Name, (CrateRootModuleId, Option<ExternCrateId>)>,
140+
extern_prelude: FxIndexMap<Name, (CrateRootModuleId, Option<ExternCrateId>)>,
141141

142142
/// Side table for resolving derive helpers.
143143
exported_derives: FxHashMap<MacroDefId, Box<[Name]>>,
@@ -163,7 +163,7 @@ struct DefMapCrateData {
163163
impl DefMapCrateData {
164164
fn new(edition: Edition) -> Self {
165165
Self {
166-
extern_prelude: FxHashMap::default(),
166+
extern_prelude: FxIndexMap::default(),
167167
exported_derives: FxHashMap::default(),
168168
fn_proc_macro_mapping: FxHashMap::default(),
169169
proc_macro_loading_error: None,
@@ -586,7 +586,8 @@ impl DefMap {
586586

587587
pub(crate) fn extern_prelude(
588588
&self,
589-
) -> impl Iterator<Item = (&Name, (CrateRootModuleId, Option<ExternCrateId>))> + '_ {
589+
) -> impl DoubleEndedIterator<Item = (&Name, (CrateRootModuleId, Option<ExternCrateId>))> + '_
590+
{
590591
self.data.extern_prelude.iter().map(|(name, &def)| (name, def))
591592
}
592593

src/tools/rust-analyzer/crates/hir-def/src/resolver.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
//! Name resolution façade.
2-
use std::{fmt, hash::BuildHasherDefault, iter, mem};
2+
use std::{fmt, iter, mem};
33

44
use base_db::CrateId;
55
use hir_expand::{
66
name::{name, Name},
77
MacroDefId,
88
};
9-
use indexmap::IndexMap;
109
use intern::Interned;
1110
use rustc_hash::FxHashSet;
1211
use smallvec::{smallvec, SmallVec};
@@ -27,10 +26,10 @@ use crate::{
2726
type_ref::LifetimeRef,
2827
visibility::{RawVisibility, Visibility},
2928
AdtId, ConstId, ConstParamId, CrateRootModuleId, DefWithBodyId, EnumId, EnumVariantId,
30-
ExternBlockId, ExternCrateId, FunctionId, GenericDefId, GenericParamId, HasModule, ImplId,
31-
ItemContainerId, ItemTreeLoc, LifetimeParamId, LocalModuleId, Lookup, Macro2Id, MacroId,
32-
MacroRulesId, ModuleDefId, ModuleId, ProcMacroId, StaticId, StructId, TraitAliasId, TraitId,
33-
TypeAliasId, TypeOrConstParamId, TypeOwnerId, TypeParamId, UseId, VariantId,
29+
ExternBlockId, ExternCrateId, FunctionId, FxIndexMap, GenericDefId, GenericParamId, HasModule,
30+
ImplId, ItemContainerId, ItemTreeLoc, LifetimeParamId, LocalModuleId, Lookup, Macro2Id,
31+
MacroId, MacroRulesId, ModuleDefId, ModuleId, ProcMacroId, StaticId, StructId, TraitAliasId,
32+
TraitId, TypeAliasId, TypeOrConstParamId, TypeOwnerId, TypeParamId, UseId, VariantId,
3433
};
3534

3635
#[derive(Debug, Clone)]
@@ -957,7 +956,6 @@ fn to_type_ns(per_ns: PerNs) -> Option<(TypeNs, Option<ImportOrExternCrate>)> {
957956
Some((res, import))
958957
}
959958

960-
type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<rustc_hash::FxHasher>>;
961959
#[derive(Default)]
962960
struct ScopeNames {
963961
map: FxIndexMap<Name, SmallVec<[ScopeDef; 1]>>,

src/tools/rust-analyzer/crates/hir-ty/src/display.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use either::Either;
1313
use hir_def::{
1414
data::adt::VariantData,
1515
db::DefDatabase,
16-
find_path,
16+
find_path::{self, PrefixKind},
1717
generics::{TypeOrConstParamData, TypeParamProvenance},
1818
item_scope::ItemInNs,
1919
lang_item::{LangItem, LangItemTarget},
@@ -999,6 +999,8 @@ impl HirDisplay for Ty {
999999
db.upcast(),
10001000
ItemInNs::Types((*def_id).into()),
10011001
module_id,
1002+
PrefixKind::Plain,
1003+
false,
10021004
false,
10031005
true,
10041006
) {

src/tools/rust-analyzer/crates/hir/src/lib.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ impl Module {
788788

789789
/// Finds a path that can be used to refer to the given item from within
790790
/// this module, if possible.
791-
pub fn find_use_path(
791+
pub fn find_path(
792792
self,
793793
db: &dyn DefDatabase,
794794
item: impl Into<ItemInNs>,
@@ -799,26 +799,29 @@ impl Module {
799799
db,
800800
item.into().into(),
801801
self.into(),
802+
PrefixKind::Plain,
803+
false,
802804
prefer_no_std,
803805
prefer_prelude,
804806
)
805807
}
806808

807809
/// Finds a path that can be used to refer to the given item from within
808810
/// this module, if possible. This is used for returning import paths for use-statements.
809-
pub fn find_use_path_prefixed(
811+
pub fn find_use_path(
810812
self,
811813
db: &dyn DefDatabase,
812814
item: impl Into<ItemInNs>,
813815
prefix_kind: PrefixKind,
814816
prefer_no_std: bool,
815817
prefer_prelude: bool,
816818
) -> Option<ModPath> {
817-
hir_def::find_path::find_path_prefixed(
819+
hir_def::find_path::find_path(
818820
db,
819821
item.into().into(),
820822
self.into(),
821823
prefix_kind,
824+
true,
822825
prefer_no_std,
823826
prefer_prelude,
824827
)

src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs

+1-22
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
//! Type tree for term search
22
3-
use hir_def::find_path::PrefixKind;
43
use hir_expand::mod_path::ModPath;
54
use hir_ty::{
65
db::HirDatabase,
@@ -21,28 +20,8 @@ fn mod_item_path(
2120
prefer_prelude: bool,
2221
) -> Option<ModPath> {
2322
let db = sema_scope.db;
24-
// Account for locals shadowing items from module
25-
let name_hit_count = def.name(db).map(|def_name| {
26-
let mut name_hit_count = 0;
27-
sema_scope.process_all_names(&mut |name, _| {
28-
if name == def_name {
29-
name_hit_count += 1;
30-
}
31-
});
32-
name_hit_count
33-
});
34-
3523
let m = sema_scope.module();
36-
match name_hit_count {
37-
Some(0..=1) | None => m.find_use_path(db.upcast(), *def, prefer_no_std, prefer_prelude),
38-
Some(_) => m.find_use_path_prefixed(
39-
db.upcast(),
40-
*def,
41-
PrefixKind::ByCrate,
42-
prefer_no_std,
43-
prefer_prelude,
44-
),
45-
}
24+
m.find_path(db.upcast(), *def, prefer_no_std, prefer_prelude)
4625
}
4726

4827
/// Helper function to get path to `ModuleDef` as string

src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_match_arms.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,7 @@ fn build_pat(
462462
) -> Option<ast::Pat> {
463463
match var {
464464
ExtendedVariant::Variant(var) => {
465-
let path = mod_path_to_ast(&module.find_use_path(
465+
let path = mod_path_to_ast(&module.find_path(
466466
db,
467467
ModuleDef::from(var),
468468
prefer_no_std,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/bool_to_enum.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ fn augment_references_with_imports(
341341

342342
let import_scope = ImportScope::find_insert_use_container(name.syntax(), &ctx.sema);
343343
let path = ref_module
344-
.find_use_path_prefixed(
344+
.find_use_path(
345345
ctx.sema.db,
346346
ModuleDef::Module(*target_module),
347347
ctx.config.insert_use.prefix_kind,
@@ -1521,7 +1521,7 @@ mod foo {
15211521
}
15221522
"#,
15231523
r#"
1524-
use crate::foo::Bool;
1524+
use foo::Bool;
15251525
15261526
fn main() {
15271527
use foo::FOO;
@@ -1602,7 +1602,7 @@ pub mod bar {
16021602
"#,
16031603
r#"
16041604
//- /main.rs
1605-
use crate::foo::bar::Bool;
1605+
use foo::bar::Bool;
16061606
16071607
mod foo;
16081608

src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_into_to_from.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) -
5050
_ => return None,
5151
};
5252

53-
mod_path_to_ast(&module.find_use_path(
53+
mod_path_to_ast(&module.find_path(
5454
ctx.db(),
5555
src_type_def,
5656
ctx.config.prefer_no_std,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ fn augment_references_with_imports(
201201
let import_scope =
202202
ImportScope::find_insert_use_container(new_name.syntax(), &ctx.sema);
203203
let path = ref_module
204-
.find_use_path_prefixed(
204+
.find_use_path(
205205
ctx.sema.db,
206206
ModuleDef::Module(*target_module),
207207
ctx.config.insert_use.prefix_kind,
@@ -811,7 +811,7 @@ pub mod bar {
811811
"#,
812812
r#"
813813
//- /main.rs
814-
use crate::foo::bar::BarResult;
814+
use foo::bar::BarResult;
815815
816816
mod foo;
817817

src/tools/rust-analyzer/crates/ide-assists/src/handlers/destructure_struct_binding.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ fn collect_data(ident_pat: ast::IdentPat, ctx: &AssistContext<'_>) -> Option<Str
9090
let module = ctx.sema.scope(ident_pat.syntax())?.module();
9191
let struct_def = hir::ModuleDef::from(struct_type);
9292
let kind = struct_type.kind(ctx.db());
93-
let struct_def_path = module.find_use_path(
93+
let struct_def_path = module.find_path(
9494
ctx.db(),
9595
struct_def,
9696
ctx.config.prefer_no_std,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_function.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
209209
FamousDefs(&ctx.sema, module.krate()).core_ops_ControlFlow();
210210

211211
if let Some(control_flow_enum) = control_flow_enum {
212-
let mod_path = module.find_use_path_prefixed(
212+
let mod_path = module.find_use_path(
213213
ctx.sema.db,
214214
ModuleDef::from(control_flow_enum),
215215
ctx.config.insert_use.prefix_kind,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ fn process_references(
386386
let segment = builder.make_mut(segment);
387387
let scope_node = builder.make_syntax_mut(scope_node);
388388
if !visited_modules.contains(&module) {
389-
let mod_path = module.find_use_path_prefixed(
389+
let mod_path = module.find_use_path(
390390
ctx.sema.db,
391391
*enum_module_def,
392392
ctx.config.insert_use.prefix_kind,
@@ -881,7 +881,7 @@ fn another_fn() {
881881
r#"use my_mod::my_other_mod::MyField;
882882
883883
mod my_mod {
884-
use self::my_other_mod::MyField;
884+
use my_other_mod::MyField;
885885
886886
fn another_fn() {
887887
let m = my_other_mod::MyEnum::MyField(MyField(1, 1));

src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_deref.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
5858

5959
let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
6060
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
61-
let trait_path = module.find_use_path(
61+
let trait_path = module.find_path(
6262
ctx.db(),
6363
ModuleDef::Trait(trait_),
6464
ctx.config.prefer_no_std,
@@ -103,7 +103,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
103103

104104
let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
105105
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
106-
let trait_path = module.find_use_path(
106+
let trait_path = module.find_path(
107107
ctx.db(),
108108
ModuleDef::Trait(trait_),
109109
ctx.config.prefer_no_std,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/generate_new.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
5858

5959
let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
6060

61-
let type_path = current_module.find_use_path(
61+
let type_path = current_module.find_path(
6262
ctx.sema.db,
6363
item_for_path_search(ctx.sema.db, item_in_ns)?,
6464
ctx.config.prefer_no_std,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/qualify_method_call.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) ->
4444
let current_module = ctx.sema.scope(call.syntax())?.module();
4545
let target_module_def = ModuleDef::from(resolved_call);
4646
let item_in_ns = ItemInNs::from(target_module_def);
47-
let receiver_path = current_module.find_use_path(
47+
let receiver_path = current_module.find_path(
4848
ctx.sema.db,
4949
item_for_path_search(ctx.sema.db, item_in_ns)?,
5050
ctx.config.prefer_no_std,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ pub(crate) fn replace_derive_with_manual_impl(
8383
})
8484
.flat_map(|trait_| {
8585
current_module
86-
.find_use_path(
86+
.find_path(
8787
ctx.sema.db,
8888
hir::ModuleDef::Trait(trait_),
8989
ctx.config.prefer_no_std,

0 commit comments

Comments
 (0)