Auto merge of #136117 - lnicola:sync-from-ra, r=lnicola

Subtree update of `rust-analyzer`

r? `@ghost`
This commit is contained in:
bors 2025-01-29 08:43:30 +00:00
commit 702da50daa
126 changed files with 2163 additions and 1325 deletions

View file

@ -1381,6 +1381,9 @@ impl ExprCollector<'_> {
}
}
ast::Stmt::Item(ast::Item::MacroDef(macro_)) => {
if self.check_cfg(&macro_).is_none() {
return;
}
let Some(name) = macro_.name() else {
statements.push(Statement::Item(Item::Other));
return;
@ -1390,6 +1393,9 @@ impl ExprCollector<'_> {
self.collect_macro_def(statements, macro_id);
}
ast::Stmt::Item(ast::Item::MacroRules(macro_)) => {
if self.check_cfg(&macro_).is_none() {
return;
}
let Some(name) = macro_.name() else {
statements.push(Statement::Item(Item::Other));
return;

View file

@ -475,7 +475,7 @@ fn outer() {
block scope::tests
name: _
outer: v
outer: vg
crate
outer: v

View file

@ -445,6 +445,10 @@ fn find_in_dep(
};
cov_mark::hit!(partially_imported);
if info.is_unstable {
if !ctx.cfg.allow_unstable {
// the item is unstable and we are not allowed to use unstable items
continue;
}
choice.stability = Unstable;
}
@ -670,6 +674,7 @@ mod tests {
prefer_prelude: bool,
prefer_absolute: bool,
prefer_no_std: bool,
allow_unstable: bool,
expect: Expect,
) {
let (db, pos) = TestDB::with_position(ra_fixture);
@ -711,7 +716,7 @@ mod tests {
module,
prefix,
ignore_local_imports,
ImportPathConfig { prefer_no_std, prefer_prelude, prefer_absolute },
ImportPathConfig { prefer_no_std, prefer_prelude, prefer_absolute, allow_unstable },
);
format_to!(
res,
@ -732,7 +737,7 @@ mod tests {
path: &str,
expect: Expect,
) {
check_found_path_(ra_fixture, path, false, false, false, expect);
check_found_path_(ra_fixture, path, false, false, false, false, expect);
}
fn check_found_path_prelude(
@ -740,7 +745,7 @@ mod tests {
path: &str,
expect: Expect,
) {
check_found_path_(ra_fixture, path, true, false, false, expect);
check_found_path_(ra_fixture, path, true, false, false, false, expect);
}
fn check_found_path_absolute(
@ -748,7 +753,7 @@ mod tests {
path: &str,
expect: Expect,
) {
check_found_path_(ra_fixture, path, false, true, false, expect);
check_found_path_(ra_fixture, path, false, true, false, false, expect);
}
fn check_found_path_prefer_no_std(
@ -756,7 +761,15 @@ mod tests {
path: &str,
expect: Expect,
) {
check_found_path_(ra_fixture, path, false, false, true, expect);
check_found_path_(ra_fixture, path, false, false, true, false, expect);
}
fn check_found_path_prefer_no_std_allow_unstable(
#[rust_analyzer::rust_fixture] ra_fixture: &str,
path: &str,
expect: Expect,
) {
check_found_path_(ra_fixture, path, false, false, true, true, expect);
}
#[test]
@ -1951,7 +1964,7 @@ pub mod ops {
#[test]
fn respect_unstable_modules() {
check_found_path_prefer_no_std(
check_found_path_prefer_no_std_allow_unstable(
r#"
//- /main.rs crate:main deps:std,core
extern crate std;

View file

@ -10,7 +10,6 @@ use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use span::Edition;
use stdx::{format_to, TupleExt};
use syntax::ToSmolStr;
use triomphe::Arc;
use crate::{
@ -88,9 +87,9 @@ impl ImportMap {
.iter()
// We've only collected items, whose name cannot be tuple field so unwrapping is fine.
.flat_map(|(&item, (info, _))| {
info.iter().enumerate().map(move |(idx, info)| {
(item, info.name.unescaped().display(db.upcast()).to_smolstr(), idx as u32)
})
info.iter()
.enumerate()
.map(move |(idx, info)| (item, info.name.as_str(), idx as u32))
})
.collect();
importables.sort_by(|(_, l_info, _), (_, r_info, _)| {
@ -168,7 +167,8 @@ impl ImportMap {
let attr_id = if let Some(import) = import {
match import {
ImportOrExternCrate::ExternCrate(id) => Some(id.into()),
ImportOrExternCrate::Import(id) => Some(id.import.into()),
ImportOrExternCrate::Import(id) => Some(id.use_.into()),
ImportOrExternCrate::Glob(id) => Some(id.use_.into()),
}
} else {
match item {
@ -441,7 +441,7 @@ pub fn search_dependencies(
}
fn search_maps(
db: &dyn DefDatabase,
_db: &dyn DefDatabase,
import_maps: &[Arc<ImportMap>],
mut stream: fst::map::Union<'_>,
query: &Query,
@ -464,11 +464,7 @@ fn search_maps(
.then(|| (item, &import_infos[info_idx as usize]))
})
.filter(|&(_, info)| {
query.search_mode.check(
&query.query,
query.case_sensitive,
&info.name.unescaped().display(db.upcast()).to_smolstr(),
)
query.search_mode.check(&query.query, query.case_sensitive, info.name.as_str())
});
res.extend(iter.map(TupleExt::head));
}

View file

@ -31,35 +31,103 @@ pub struct PerNsGlobImports {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ImportOrExternCrate {
Glob(GlobId),
Import(ImportId),
ExternCrate(ExternCrateId),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum ImportType {
Import(ImportId),
Glob(UseId),
ExternCrate(ExternCrateId),
impl From<ImportOrGlob> for ImportOrExternCrate {
fn from(value: ImportOrGlob) -> Self {
match value {
ImportOrGlob::Glob(it) => ImportOrExternCrate::Glob(it),
ImportOrGlob::Import(it) => ImportOrExternCrate::Import(it),
}
}
}
impl ImportOrExternCrate {
pub fn into_import(self) -> Option<ImportId> {
pub fn import_or_glob(self) -> Option<ImportOrGlob> {
match self {
ImportOrExternCrate::Import(it) => Some(ImportOrGlob::Import(it)),
ImportOrExternCrate::Glob(it) => Some(ImportOrGlob::Glob(it)),
_ => None,
}
}
pub fn import(self) -> Option<ImportId> {
match self {
ImportOrExternCrate::Import(it) => Some(it),
_ => None,
}
}
pub fn glob(self) -> Option<GlobId> {
match self {
ImportOrExternCrate::Glob(id) => Some(id),
_ => None,
}
}
pub fn use_(self) -> Option<UseId> {
match self {
ImportOrExternCrate::Glob(id) => Some(id.use_),
ImportOrExternCrate::Import(id) => Some(id.use_),
_ => None,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ImportOrGlob {
Glob(GlobId),
Import(ImportId),
}
impl ImportOrGlob {
pub fn into_import(self) -> Option<ImportId> {
match self {
ImportOrGlob::Import(it) => Some(it),
_ => None,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ImportOrDef {
Import(ImportId),
Glob(GlobId),
ExternCrate(ExternCrateId),
Def(ModuleDefId),
}
impl From<ImportOrExternCrate> for ImportOrDef {
fn from(value: ImportOrExternCrate) -> Self {
match value {
ImportOrExternCrate::Import(it) => ImportOrDef::Import(it),
ImportOrExternCrate::Glob(it) => ImportOrDef::Glob(it),
ImportOrExternCrate::ExternCrate(it) => ImportOrDef::ExternCrate(it),
}
}
}
impl From<ImportOrGlob> for ImportOrDef {
fn from(value: ImportOrGlob) -> Self {
match value {
ImportOrGlob::Import(it) => ImportOrDef::Import(it),
ImportOrGlob::Glob(it) => ImportOrDef::Glob(it),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct ImportId {
pub import: UseId,
pub use_: UseId,
pub idx: Idx<ast::UseTree>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct GlobId {
pub use_: UseId,
pub idx: Idx<ast::UseTree>,
}
@ -96,8 +164,8 @@ pub struct ItemScope {
// the resolutions of the imports of this scope
use_imports_types: FxHashMap<ImportOrExternCrate, ImportOrDef>,
use_imports_values: FxHashMap<ImportId, ImportOrDef>,
use_imports_macros: FxHashMap<ImportId, ImportOrDef>,
use_imports_values: FxHashMap<ImportOrGlob, ImportOrDef>,
use_imports_macros: FxHashMap<ImportOrGlob, ImportOrDef>,
use_decls: Vec<UseId>,
extern_crate_decls: Vec<ExternCrateId>,
@ -162,7 +230,7 @@ impl ItemScope {
.map(move |name| (name, self.get(name)))
}
pub fn values(&self) -> impl Iterator<Item = (&Name, Item<ModuleDefId, ImportId>)> + '_ {
pub fn values(&self) -> impl Iterator<Item = (&Name, Item<ModuleDefId, ImportOrGlob>)> + '_ {
self.values.iter().map(|(n, &i)| (n, i))
}
@ -172,7 +240,7 @@ impl ItemScope {
self.types.iter().map(|(n, &i)| (n, i))
}
pub fn macros(&self) -> impl Iterator<Item = (&Name, Item<MacroId, ImportId>)> + '_ {
pub fn macros(&self) -> impl Iterator<Item = (&Name, Item<MacroId, ImportOrGlob>)> + '_ {
self.macros.iter().map(|(n, &i)| (n, i))
}
@ -180,9 +248,10 @@ impl ItemScope {
self.use_imports_types
.keys()
.copied()
.filter_map(ImportOrExternCrate::into_import)
.filter_map(ImportOrExternCrate::import_or_glob)
.chain(self.use_imports_values.keys().copied())
.chain(self.use_imports_macros.keys().copied())
.filter_map(ImportOrGlob::into_import)
.sorted()
.dedup()
}
@ -192,10 +261,10 @@ impl ItemScope {
let mut def_map;
let mut scope = self;
while let Some(&m) = scope.use_imports_macros.get(&import) {
while let Some(&m) = scope.use_imports_macros.get(&ImportOrGlob::Import(import)) {
match m {
ImportOrDef::Import(i) => {
let module_id = i.import.lookup(db).container;
let module_id = i.use_.lookup(db).container;
def_map = module_id.def_map(db);
scope = &def_map[module_id.local_id].scope;
import = i;
@ -211,7 +280,7 @@ impl ItemScope {
while let Some(&m) = scope.use_imports_types.get(&ImportOrExternCrate::Import(import)) {
match m {
ImportOrDef::Import(i) => {
let module_id = i.import.lookup(db).container;
let module_id = i.use_.lookup(db).container;
def_map = module_id.def_map(db);
scope = &def_map[module_id.local_id].scope;
import = i;
@ -224,10 +293,10 @@ impl ItemScope {
}
}
let mut scope = self;
while let Some(&m) = scope.use_imports_values.get(&import) {
while let Some(&m) = scope.use_imports_values.get(&ImportOrGlob::Import(import)) {
match m {
ImportOrDef::Import(i) => {
let module_id = i.import.lookup(db).container;
let module_id = i.use_.lookup(db).container;
def_map = module_id.def_map(db);
scope = &def_map[module_id.local_id].scope;
import = i;
@ -488,9 +557,13 @@ impl ItemScope {
self.unnamed_trait_imports.get(&tr).map(|trait_| trait_.vis)
}
pub(crate) fn push_unnamed_trait(&mut self, tr: TraitId, vis: Visibility) {
// FIXME: import
self.unnamed_trait_imports.insert(tr, Item { def: (), vis, import: None });
pub(crate) fn push_unnamed_trait(
&mut self,
tr: TraitId,
vis: Visibility,
import: Option<ImportId>,
) {
self.unnamed_trait_imports.insert(tr, Item { def: (), vis, import });
}
pub(crate) fn push_res_with_import(
@ -498,7 +571,7 @@ impl ItemScope {
glob_imports: &mut PerNsGlobImports,
lookup: (LocalModuleId, Name),
def: PerNs,
import: Option<ImportType>,
import: Option<ImportOrExternCrate>,
) -> bool {
let mut changed = false;
@ -509,41 +582,22 @@ impl ItemScope {
match existing {
Entry::Vacant(entry) => {
match import {
Some(ImportType::Glob(_)) => {
Some(ImportOrExternCrate::Glob(_)) => {
glob_imports.types.insert(lookup.clone());
}
_ => _ = glob_imports.types.remove(&lookup),
}
let import = match import {
Some(ImportType::ExternCrate(extern_crate)) => {
Some(ImportOrExternCrate::ExternCrate(extern_crate))
}
Some(ImportType::Import(import)) => {
Some(ImportOrExternCrate::Import(import))
}
None | Some(ImportType::Glob(_)) => None,
};
let prev = std::mem::replace(&mut fld.import, import);
if let Some(import) = import {
self.use_imports_types.insert(
import,
match prev {
Some(ImportOrExternCrate::Import(import)) => {
ImportOrDef::Import(import)
}
Some(ImportOrExternCrate::ExternCrate(import)) => {
ImportOrDef::ExternCrate(import)
}
None => ImportOrDef::Def(fld.def),
},
);
self.use_imports_types
.insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
}
entry.insert(fld);
changed = true;
}
Entry::Occupied(mut entry) => {
match import {
Some(ImportType::Glob(..)) => {
Some(ImportOrExternCrate::Glob(..)) => {
// Multiple globs may import the same item and they may
// override visibility from previously resolved globs. This is
// currently handled by `DefCollector`, because we need to
@ -552,28 +606,11 @@ impl ItemScope {
}
_ => {
if glob_imports.types.remove(&lookup) {
let import = match import {
Some(ImportType::ExternCrate(extern_crate)) => {
Some(ImportOrExternCrate::ExternCrate(extern_crate))
}
Some(ImportType::Import(import)) => {
Some(ImportOrExternCrate::Import(import))
}
None | Some(ImportType::Glob(_)) => None,
};
let prev = std::mem::replace(&mut fld.import, import);
if let Some(import) = import {
self.use_imports_types.insert(
import,
match prev {
Some(ImportOrExternCrate::Import(import)) => {
ImportOrDef::Import(import)
}
Some(ImportOrExternCrate::ExternCrate(import)) => {
ImportOrDef::ExternCrate(import)
}
None => ImportOrDef::Def(fld.def),
},
prev.map_or(ImportOrDef::Def(fld.def), Into::into),
);
}
cov_mark::hit!(import_shadowed);
@ -591,44 +628,31 @@ impl ItemScope {
match existing {
Entry::Vacant(entry) => {
match import {
Some(ImportType::Glob(_)) => {
Some(ImportOrExternCrate::Glob(_)) => {
glob_imports.values.insert(lookup.clone());
}
_ => _ = glob_imports.values.remove(&lookup),
}
let import = match import {
Some(ImportType::Import(import)) => Some(import),
_ => None,
};
let import = import.and_then(ImportOrExternCrate::import_or_glob);
let prev = std::mem::replace(&mut fld.import, import);
if let Some(import) = import {
self.use_imports_values.insert(
import,
match prev {
Some(import) => ImportOrDef::Import(import),
None => ImportOrDef::Def(fld.def),
},
);
self.use_imports_values
.insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
}
entry.insert(fld);
changed = true;
}
Entry::Occupied(mut entry) if !matches!(import, Some(ImportType::Glob(..))) => {
Entry::Occupied(mut entry)
if !matches!(import, Some(ImportOrExternCrate::Glob(..))) =>
{
if glob_imports.values.remove(&lookup) {
cov_mark::hit!(import_shadowed);
let import = match import {
Some(ImportType::Import(import)) => Some(import),
_ => None,
};
let import = import.and_then(ImportOrExternCrate::import_or_glob);
let prev = std::mem::replace(&mut fld.import, import);
if let Some(import) = import {
self.use_imports_values.insert(
import,
match prev {
Some(import) => ImportOrDef::Import(import),
None => ImportOrDef::Def(fld.def),
},
);
self.use_imports_values
.insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
}
entry.insert(fld);
changed = true;
@ -643,43 +667,33 @@ impl ItemScope {
match existing {
Entry::Vacant(entry) => {
match import {
Some(ImportType::Glob(_)) => {
Some(ImportOrExternCrate::Glob(_)) => {
glob_imports.macros.insert(lookup.clone());
}
_ => _ = glob_imports.macros.remove(&lookup),
}
let import = match import {
Some(ImportType::Import(import)) => Some(import),
_ => None,
};
let import = import.and_then(ImportOrExternCrate::import_or_glob);
let prev = std::mem::replace(&mut fld.import, import);
if let Some(import) = import {
self.use_imports_macros.insert(
import,
match prev {
Some(import) => ImportOrDef::Import(import),
None => ImportOrDef::Def(fld.def.into()),
},
prev.map_or_else(|| ImportOrDef::Def(fld.def.into()), Into::into),
);
}
entry.insert(fld);
changed = true;
}
Entry::Occupied(mut entry) if !matches!(import, Some(ImportType::Glob(..))) => {
Entry::Occupied(mut entry)
if !matches!(import, Some(ImportOrExternCrate::Glob(..))) =>
{
if glob_imports.macros.remove(&lookup) {
cov_mark::hit!(import_shadowed);
let import = match import {
Some(ImportType::Import(import)) => Some(import),
_ => None,
};
let import = import.and_then(ImportOrExternCrate::import_or_glob);
let prev = std::mem::replace(&mut fld.import, import);
if let Some(import) = import {
self.use_imports_macros.insert(
import,
match prev {
Some(import) => ImportOrDef::Import(import),
None => ImportOrDef::Def(fld.def.into()),
},
prev.map_or_else(|| ImportOrDef::Def(fld.def.into()), Into::into),
);
}
entry.insert(fld);
@ -704,16 +718,27 @@ impl ItemScope {
.map(|def| &mut def.vis)
.chain(self.values.values_mut().map(|def| &mut def.vis))
.chain(self.unnamed_trait_imports.values_mut().map(|def| &mut def.vis))
.for_each(|vis| {
*vis = Visibility::Module(this_module, VisibilityExplicitness::Implicit)
.for_each(|vis| match vis {
&mut Visibility::Module(_, visibility_explicitness) => {
*vis = Visibility::Module(this_module, visibility_explicitness)
}
Visibility::Public => {
*vis = Visibility::Module(this_module, VisibilityExplicitness::Implicit)
}
});
for mac in self.macros.values_mut() {
if matches!(mac.def, MacroId::ProcMacroId(_) if mac.import.is_none()) {
continue;
}
mac.vis = Visibility::Module(this_module, VisibilityExplicitness::Implicit);
match mac.vis {
Visibility::Module(_, visibility_explicitness) => {
mac.vis = Visibility::Module(this_module, visibility_explicitness)
}
Visibility::Public => {
mac.vis = Visibility::Module(this_module, VisibilityExplicitness::Implicit)
}
}
}
}
@ -732,20 +757,25 @@ impl ItemScope {
buf.push_str(" t");
match import {
Some(ImportOrExternCrate::Import(_)) => buf.push('i'),
Some(ImportOrExternCrate::Glob(_)) => buf.push('g'),
Some(ImportOrExternCrate::ExternCrate(_)) => buf.push('e'),
None => (),
}
}
if let Some(Item { import, .. }) = def.values {
buf.push_str(" v");
if import.is_some() {
buf.push('i');
match import {
Some(ImportOrGlob::Import(_)) => buf.push('i'),
Some(ImportOrGlob::Glob(_)) => buf.push('g'),
None => (),
}
}
if let Some(Item { import, .. }) = def.macros {
buf.push_str(" m");
if import.is_some() {
buf.push('i');
match import {
Some(ImportOrGlob::Import(_)) => buf.push('i'),
Some(ImportOrGlob::Glob(_)) => buf.push('g'),
None => (),
}
}
if def.is_none() {
@ -828,7 +858,7 @@ impl PerNs {
match def {
ModuleDefId::ModuleId(_) => PerNs::types(def, v, import),
ModuleDefId::FunctionId(_) => {
PerNs::values(def, v, import.and_then(ImportOrExternCrate::into_import))
PerNs::values(def, v, import.and_then(ImportOrExternCrate::import_or_glob))
}
ModuleDefId::AdtId(adt) => match adt {
AdtId::UnionId(_) => PerNs::types(def, v, import),
@ -843,14 +873,14 @@ impl PerNs {
},
ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v, import),
ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => {
PerNs::values(def, v, import.and_then(ImportOrExternCrate::into_import))
PerNs::values(def, v, import.and_then(ImportOrExternCrate::import_or_glob))
}
ModuleDefId::TraitId(_) => PerNs::types(def, v, import),
ModuleDefId::TraitAliasId(_) => PerNs::types(def, v, import),
ModuleDefId::TypeAliasId(_) => PerNs::types(def, v, import),
ModuleDefId::BuiltinType(_) => PerNs::types(def, v, import),
ModuleDefId::MacroId(mac) => {
PerNs::macros(mac, v, import.and_then(ImportOrExternCrate::into_import))
PerNs::macros(mac, v, import.and_then(ImportOrExternCrate::import_or_glob))
}
}
}

View file

@ -372,6 +372,7 @@ language_item_table! {
DerefMut, sym::deref_mut, deref_mut_trait, Target::Trait, GenericRequirement::Exact(0);
DerefTarget, sym::deref_target, deref_target, Target::AssocTy, GenericRequirement::None;
Receiver, sym::receiver, receiver_trait, Target::Trait, GenericRequirement::None;
ReceiverTarget, sym::receiver_target, receiver_target, Target::AssocTy, GenericRequirement::None;
Fn, sym::fn_, fn_trait, Target::Trait, GenericRequirement::Exact(1);
FnMut, sym::fn_mut, fn_mut_trait, Target::Trait, GenericRequirement::Exact(1);

View file

@ -114,6 +114,9 @@ pub struct ImportPathConfig {
pub prefer_prelude: bool,
/// If true, prefer abs path (starting with `::`) where it is available.
pub prefer_absolute: bool,
/// If true, paths containing `#[unstable]` segments may be returned, but only if if there is no
/// stable path. This does not check, whether the item itself that is being imported is `#[unstable]`.
pub allow_unstable: bool,
}
#[derive(Debug)]
@ -910,6 +913,7 @@ pub enum AssocItemId {
ConstId(ConstId),
TypeAliasId(TypeAliasId),
}
// FIXME: not every function, ... is actually an assoc item. maybe we should make
// sure that you can only turn actual assoc items into AssocItemIds. This would
// require not implementing From, and instead having some checked way of

View file

@ -28,7 +28,7 @@ use triomphe::Arc;
use crate::{
attr::Attrs,
db::DefDatabase,
item_scope::{ImportId, ImportOrExternCrate, ImportType, PerNsGlobImports},
item_scope::{GlobId, ImportId, ImportOrExternCrate, PerNsGlobImports},
item_tree::{
self, AttrOwner, FieldsShape, FileItemTreeId, ImportKind, ItemTree, ItemTreeId,
ItemTreeNode, Macro2, MacroCall, MacroRules, Mod, ModItem, ModKind, TreeId, UseTreeKind,
@ -208,7 +208,7 @@ struct DefCollector<'a> {
def_map: DefMap,
// The dependencies of the current crate, including optional deps like `test`.
deps: FxHashMap<Name, Dependency>,
glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility, UseId)>>,
glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility, GlobId)>>,
unresolved_imports: Vec<ImportDirective>,
indeterminate_imports: Vec<(ImportDirective, PerNs)>,
unresolved_macros: Vec<MacroDirective>,
@ -524,11 +524,7 @@ impl DefCollector<'_> {
match per_ns.types {
Some(Item { def: ModuleDefId::ModuleId(m), import, .. }) => {
// FIXME: This should specifically look for a glob import somehow and record that here
self.def_map.prelude = Some((
m,
import.and_then(ImportOrExternCrate::into_import).map(|it| it.import),
));
self.def_map.prelude = Some((m, import.and_then(ImportOrExternCrate::use_)));
}
types => {
tracing::debug!(
@ -845,13 +841,14 @@ impl DefCollector<'_> {
def.values = None;
def.macros = None;
}
let imp = ImportType::Import(ImportId { import: id, idx: use_tree });
let imp = ImportOrExternCrate::Import(ImportId { use_: id, idx: use_tree });
tracing::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
self.update(module_id, &[(name.cloned(), def)], vis, Some(imp));
}
ImportSource { kind: ImportKind::Glob, id, is_prelude, .. } => {
ImportSource { kind: ImportKind::Glob, id, is_prelude, use_tree } => {
tracing::debug!("glob import: {:?}", import);
let glob = GlobId { use_: id, idx: use_tree };
match def.take_types() {
Some(ModuleDefId::ModuleId(m)) => {
if is_prelude {
@ -875,7 +872,12 @@ impl DefCollector<'_> {
.filter(|(_, res)| !res.is_none())
.collect::<Vec<_>>();
self.update(module_id, &items, vis, Some(ImportType::Glob(id)));
self.update(
module_id,
&items,
vis,
Some(ImportOrExternCrate::Glob(glob)),
);
} else {
// glob import from same crate => we do an initial
// import, and then need to propagate any further
@ -907,11 +909,16 @@ impl DefCollector<'_> {
.filter(|(_, res)| !res.is_none())
.collect::<Vec<_>>();
self.update(module_id, &items, vis, Some(ImportType::Glob(id)));
self.update(
module_id,
&items,
vis,
Some(ImportOrExternCrate::Glob(glob)),
);
// record the glob import in case we add further items
let glob = self.glob_imports.entry(m.local_id).or_default();
match glob.iter_mut().find(|(mid, _, _)| *mid == module_id) {
None => glob.push((module_id, vis, id)),
let glob_imports = self.glob_imports.entry(m.local_id).or_default();
match glob_imports.iter_mut().find(|(mid, _, _)| *mid == module_id) {
None => glob_imports.push((module_id, vis, glob)),
Some((_, old_vis, _)) => {
if let Some(new_vis) = old_vis.max(vis, &self.def_map) {
*old_vis = new_vis;
@ -944,7 +951,12 @@ impl DefCollector<'_> {
(Some(name), res)
})
.collect::<Vec<_>>();
self.update(module_id, &resolutions, vis, Some(ImportType::Glob(id)));
self.update(
module_id,
&resolutions,
vis,
Some(ImportOrExternCrate::Glob(glob)),
);
}
Some(d) => {
tracing::debug!("glob import {:?} from non-module/enum {:?}", import, d);
@ -964,7 +976,7 @@ impl DefCollector<'_> {
resolutions: &[(Option<Name>, PerNs)],
// Visibility this import will have
vis: Visibility,
import: Option<ImportType>,
import: Option<ImportOrExternCrate>,
) {
self.db.unwind_if_cancelled();
self.update_recursive(module_id, resolutions, vis, import, 0)
@ -978,7 +990,7 @@ impl DefCollector<'_> {
// All resolutions are imported with this visibility; the visibilities in
// the `PerNs` values are ignored and overwritten
vis: Visibility,
import: Option<ImportType>,
import: Option<ImportOrExternCrate>,
depth: usize,
) {
if GLOB_RECURSION_LIMIT.check(depth).is_err() {
@ -994,8 +1006,10 @@ impl DefCollector<'_> {
self.push_res_and_update_glob_vis(module_id, name, *res, vis, import);
}
None => {
let tr = match res.take_types() {
Some(ModuleDefId::TraitId(tr)) => tr,
let (tr, import) = match res.take_types_full() {
Some(Item { def: ModuleDefId::TraitId(tr), vis: _, import }) => {
(tr, import)
}
Some(other) => {
tracing::debug!("non-trait `_` import of {:?}", other);
continue;
@ -1021,7 +1035,11 @@ impl DefCollector<'_> {
if should_update {
changed = true;
self.def_map.modules[module_id].scope.push_unnamed_trait(tr, vis);
self.def_map.modules[module_id].scope.push_unnamed_trait(
tr,
vis,
import.and_then(ImportOrExternCrate::import),
);
}
}
}
@ -1043,13 +1061,13 @@ impl DefCollector<'_> {
.cloned()
.collect::<Vec<_>>();
for (glob_importing_module, glob_import_vis, use_) in glob_imports {
for (glob_importing_module, glob_import_vis, glob) in glob_imports {
let vis = glob_import_vis.min(vis, &self.def_map).unwrap_or(glob_import_vis);
self.update_recursive(
glob_importing_module,
resolutions,
vis,
Some(ImportType::Glob(use_)),
Some(ImportOrExternCrate::Glob(glob)),
depth + 1,
);
}
@ -1061,7 +1079,7 @@ impl DefCollector<'_> {
name: &Name,
mut defs: PerNs,
vis: Visibility,
def_import_type: Option<ImportType>,
def_import_type: Option<ImportOrExternCrate>,
) -> bool {
// `extern crate crate_name` things can be re-exported as `pub use crate_name`.
// But they cannot be re-exported as `pub use self::crate_name`, `pub use crate::crate_name`
@ -1074,10 +1092,10 @@ impl DefCollector<'_> {
let Some(ImportOrExternCrate::ExternCrate(_)) = def.import else {
return false;
};
let Some(ImportType::Import(id)) = def_import_type else {
let Some(ImportOrExternCrate::Import(id)) = def_import_type else {
return false;
};
let use_id = id.import.lookup(self.db).id;
let use_id = id.use_.lookup(self.db).id;
let item_tree = use_id.item_tree(self.db);
let use_kind = item_tree[use_id.value].use_tree.kind();
let UseTreeKind::Single { path, .. } = use_kind else {
@ -1100,7 +1118,7 @@ impl DefCollector<'_> {
let mut changed = false;
if let Some(ImportType::Glob(_)) = def_import_type {
if let Some(ImportOrExternCrate::Glob(_)) = def_import_type {
let prev_defs = self.def_map[module_id].scope.get(name);
// Multiple globs may import the same item and they may override visibility from
@ -1727,7 +1745,7 @@ impl ModCollector<'_, '_> {
),
)],
vis,
Some(ImportType::ExternCrate(id)),
Some(ImportOrExternCrate::ExternCrate(id)),
);
} else {
if let Some(name) = name {

View file

@ -4,7 +4,6 @@ use base_db::AnchoredPath;
use hir_expand::{name::Name, HirFileIdExt};
use limit::Limit;
use span::EditionedFileId;
use syntax::ToSmolStr as _;
use crate::{db::DefDatabase, HirFileId};
@ -35,7 +34,7 @@ impl ModDir {
let path = match attr_path {
None => {
let mut path = self.dir_path.clone();
path.push(&name.unescaped().display_no_db().to_smolstr());
path.push(name.as_str());
path
}
Some(attr_path) => {
@ -66,7 +65,7 @@ impl ModDir {
name: &Name,
attr_path: Option<&str>,
) -> Result<(EditionedFileId, bool, ModDir), Box<[String]>> {
let name = name.unescaped();
let name = name.as_str();
let mut candidate_files = ArrayVec::<_, 2>::new();
match attr_path {
@ -74,16 +73,8 @@ impl ModDir {
candidate_files.push(self.dir_path.join_attr(attr_path, self.root_non_dir_owner))
}
None => {
candidate_files.push(format!(
"{}{}.rs",
self.dir_path.0,
name.display(db.upcast())
));
candidate_files.push(format!(
"{}{}/mod.rs",
self.dir_path.0,
name.display(db.upcast())
));
candidate_files.push(format!("{}{}.rs", self.dir_path.0, name));
candidate_files.push(format!("{}{}/mod.rs", self.dir_path.0, name));
}
};
@ -97,7 +88,7 @@ impl ModDir {
let dir_path = if root_dir_owner {
DirPath::empty()
} else {
DirPath::new(format!("{}/", name.display(db.upcast())))
DirPath::new(format!("{}/", name))
};
if let Some(mod_dir) = self.child(dir_path, !root_dir_owner) {
return Ok((

View file

@ -103,8 +103,8 @@ mod a {
c: t
crate::a::b::c
A: v
b: t
A: vg
b: tg
"#]],
);
}
@ -256,8 +256,8 @@ pub enum Foo { Bar, Baz }
"#,
expect![[r#"
crate
Bar: t v
Baz: t v
Bar: tg vg
Baz: tg vg
"#]],
);
}
@ -421,10 +421,10 @@ pub struct NotExported;
"#,
expect![[r#"
crate
Exported: t v
PublicItem: t v
allowed_reexport: t
exported: t
Exported: tg vg
PublicItem: tg vg
allowed_reexport: tg
exported: tg
not_allowed_reexport1: _
not_allowed_reexport2: _
"#]],
@ -692,7 +692,7 @@ mod b {
b: t
crate::a
T: t v
T: t vg
crate::b
T: v

View file

@ -18,9 +18,9 @@ pub struct Baz;
"#,
expect![[r#"
crate
Baz: t v
Foo: t v
bar: t
Baz: tg vg
Foo: tg vg
bar: tg
foo: t
crate::foo
@ -53,20 +53,20 @@ pub use super::*;
"#,
expect![[r#"
crate
Baz: t v
Foo: t v
bar: t
Baz: tg vg
Foo: tg vg
bar: tg
foo: t
crate::foo
Baz: t v
Baz: tg vg
Foo: t v
bar: t
crate::foo::bar
Baz: t v
Foo: t v
bar: t
Foo: tg vg
bar: tg
"#]],
);
}
@ -91,20 +91,20 @@ pub use super::*;
",
expect![[r#"
crate
Baz: t v
bar: t
Baz: tg vg
bar: tg
foo: t
crate::foo
Baz: t v
Baz: tg vg
PrivateStructFoo: t v
bar: t
crate::foo::bar
Baz: t v
PrivateStructBar: t v
PrivateStructFoo: t v
bar: t
PrivateStructFoo: tg vg
bar: tg
"#]],
);
}
@ -130,9 +130,9 @@ pub(crate) struct PubCrateStruct;
",
expect![[r#"
crate
Foo: t
PubCrateStruct: t v
bar: t
Foo: tg
PubCrateStruct: tg vg
bar: tg
foo: t
crate::foo
@ -160,7 +160,7 @@ pub struct Baz;
"#,
expect![[r#"
crate
Baz: t v
Baz: tg vg
"#]],
);
}
@ -178,7 +178,7 @@ struct Foo;
"#,
expect![[r#"
crate
Baz: t v
Baz: tg vg
"#]],
);
}
@ -193,8 +193,8 @@ use self::Foo::*;
"#,
expect![[r#"
crate
Bar: t v
Baz: t v
Bar: tg vg
Baz: tg vg
Foo: t
"#]],
);
@ -210,8 +210,8 @@ use self::Foo::{*};
"#,
expect![[r#"
crate
Bar: t v
Baz: t v
Bar: tg vg
Baz: tg vg
Foo: t
"#]],
);
@ -359,7 +359,7 @@ use event::Event;
event: t
crate::event
Event: t v
Event: t vg
serenity: t
crate::event::serenity
@ -388,10 +388,10 @@ use reexport::*;
"#,
expect![[r#"
crate
Trait: t
Trait: tg
defs: t
function: v
makro: m
function: vg
makro: mg
reexport: t
crate::defs
@ -400,10 +400,10 @@ use reexport::*;
makro: m
crate::reexport
Trait: t
function: v
Trait: tg
function: vg
inner: t
makro: m
makro: mg
crate::reexport::inner
Trait: ti
@ -442,12 +442,12 @@ mod glob_target {
ShouldBePrivate: t v
crate::outer
ShouldBePrivate: t v
ShouldBePrivate: tg vg
inner_superglob: t
crate::outer::inner_superglob
ShouldBePrivate: t v
inner_superglob: t
ShouldBePrivate: tg vg
inner_superglob: tg
"#]],
);
}
@ -473,20 +473,20 @@ use reexport_2::*;
"#,
expect![[r#"
crate
Placeholder: t v
Placeholder: tg vg
libs: t
reexport_1: t
reexport_1: tg
reexport_2: t
crate::libs
Placeholder: t v
crate::reexport_2
Placeholder: t v
Placeholder: tg vg
reexport_1: t
crate::reexport_2::reexport_1
Placeholder: t v
Placeholder: tg vg
"#]],
);
}

View file

@ -97,9 +97,9 @@ macro_rules! structs {
bar: t
crate::bar
Bar: t
Foo: t
bar: t
Bar: tg
Foo: tg
bar: tg
"#]],
);
}
@ -130,9 +130,9 @@ macro_rules! structs {
bar: t
crate::bar
Bar: t
Foo: t
bar: t
Bar: tg
Foo: tg
bar: tg
"#]],
);
}
@ -169,9 +169,9 @@ macro_rules! inner {
bar: t
crate::bar
Bar: t
Foo: t
bar: t
Bar: tg
Foo: tg
bar: tg
"#]],
);
}
@ -794,7 +794,7 @@ pub trait Clone {}
"#,
expect![[r#"
crate
Clone: t m
Clone: tg mg
"#]],
);
}
@ -1075,9 +1075,9 @@ macro_rules! mbe {
"#,
expect![[r#"
crate
DummyTrait: m
attribute_macro: m
function_like_macro: m
DummyTrait: mg
attribute_macro: mg
function_like_macro: mg
"#]],
);
}

View file

@ -6,7 +6,7 @@
use bitflags::bitflags;
use crate::{
item_scope::{ImportId, ImportOrExternCrate, ItemInNs},
item_scope::{ImportId, ImportOrExternCrate, ImportOrGlob, ItemInNs},
visibility::Visibility,
MacroId, ModuleDefId,
};
@ -36,8 +36,8 @@ pub struct Item<Def, Import = ImportId> {
}
pub type TypesItem = Item<ModuleDefId, ImportOrExternCrate>;
pub type ValuesItem = Item<ModuleDefId>;
pub type MacrosItem = Item<MacroId>;
pub type ValuesItem = Item<ModuleDefId, ImportOrGlob>;
pub type MacrosItem = Item<MacroId, ImportOrGlob>;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct PerNs {
@ -59,7 +59,7 @@ impl PerNs {
PerNs { types: None, values: None, macros: None }
}
pub fn values(def: ModuleDefId, vis: Visibility, import: Option<ImportId>) -> PerNs {
pub fn values(def: ModuleDefId, vis: Visibility, import: Option<ImportOrGlob>) -> PerNs {
PerNs { types: None, values: Some(Item { def, vis, import }), macros: None }
}
@ -78,13 +78,13 @@ impl PerNs {
values: Some(Item {
def: values,
vis,
import: import.and_then(ImportOrExternCrate::into_import),
import: import.and_then(ImportOrExternCrate::import_or_glob),
}),
macros: None,
}
}
pub fn macros(def: MacroId, vis: Visibility, import: Option<ImportId>) -> PerNs {
pub fn macros(def: MacroId, vis: Visibility, import: Option<ImportOrGlob>) -> PerNs {
PerNs { types: None, values: None, macros: Some(Item { def, vis, import }) }
}
@ -108,7 +108,7 @@ impl PerNs {
self.values.map(|it| it.def)
}
pub fn take_values_import(self) -> Option<(ModuleDefId, Option<ImportId>)> {
pub fn take_values_import(self) -> Option<(ModuleDefId, Option<ImportOrGlob>)> {
self.values.map(|it| (it.def, it.import))
}
@ -116,7 +116,7 @@ impl PerNs {
self.macros.map(|it| it.def)
}
pub fn take_macros_import(self) -> Option<(MacroId, Option<ImportId>)> {
pub fn take_macros_import(self) -> Option<(MacroId, Option<ImportOrGlob>)> {
self.macros.map(|it| (it.def, it.import))
}
@ -159,14 +159,12 @@ impl PerNs {
.map(|it| (ItemInNs::Types(it.def), it.import))
.into_iter()
.chain(
self.values.map(|it| {
(ItemInNs::Values(it.def), it.import.map(ImportOrExternCrate::Import))
}),
self.values
.map(|it| (ItemInNs::Values(it.def), it.import.map(ImportOrExternCrate::from))),
)
.chain(
self.macros.map(|it| {
(ItemInNs::Macros(it.def), it.import.map(ImportOrExternCrate::Import))
}),
self.macros
.map(|it| (ItemInNs::Macros(it.def), it.import.map(ImportOrExternCrate::from))),
)
}
}

View file

@ -19,7 +19,7 @@ use crate::{
db::DefDatabase,
generics::{GenericParams, TypeOrConstParamData},
hir::{BindingId, ExprId, LabelId},
item_scope::{BuiltinShadowMode, ImportId, ImportOrExternCrate, BUILTIN_SCOPE},
item_scope::{BuiltinShadowMode, ImportOrExternCrate, ImportOrGlob, BUILTIN_SCOPE},
lang_item::LangItemTarget,
nameres::{DefMap, MacroSubNs, ResolvePathResultPrefixInfo},
path::{ModPath, Path, PathKind},
@ -107,7 +107,7 @@ pub enum TypeNs {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ResolveValueResult {
ValueNs(ValueNs, Option<ImportId>),
ValueNs(ValueNs, Option<ImportOrGlob>),
Partial(TypeNs, usize, Option<ImportOrExternCrate>),
}
@ -485,7 +485,7 @@ impl Resolver {
db: &dyn DefDatabase,
path: &ModPath,
expected_macro_kind: Option<MacroSubNs>,
) -> Option<(MacroId, Option<ImportId>)> {
) -> Option<(MacroId, Option<ImportOrGlob>)> {
let (item_map, module) = self.item_scope();
item_map
.resolve_path(db, module, path, BuiltinShadowMode::Other, expected_macro_kind)
@ -1014,7 +1014,7 @@ impl ModuleItemMap {
}
}
fn to_value_ns(per_ns: PerNs) -> Option<(ValueNs, Option<ImportId>)> {
fn to_value_ns(per_ns: PerNs) -> Option<(ValueNs, Option<ImportOrGlob>)> {
let (def, import) = per_ns.take_values_import()?;
let res = match def {
ModuleDefId::FunctionId(it) => ValueNs::FunctionId(it),