Deduplicate

This commit is contained in:
Lukas Wirth 2024-01-15 10:58:05 +01:00
parent d80d2fcae0
commit 2d72ec71ec
13 changed files with 83 additions and 96 deletions

View file

@ -18,27 +18,21 @@ use super::*;
pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBodyId) -> String { pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBodyId) -> String {
let header = match owner { let header = match owner {
DefWithBodyId::FunctionId(it) => { DefWithBodyId::FunctionId(it) => {
let item_tree_id = it.lookup(db).id; it.lookup(db).id.resolved(db, |it| format!("fn {} = ", it.name.display(db.upcast())))
format!(
"fn {}",
item_tree_id.item_tree(db)[item_tree_id.value].name.display(db.upcast())
)
} }
DefWithBodyId::StaticId(it) => { DefWithBodyId::StaticId(it) => it
let item_tree_id = it.lookup(db).id; .lookup(db)
.id
.resolved(db, |it| format!("static {} = ", it.name.display(db.upcast()))),
DefWithBodyId::ConstId(it) => it.lookup(db).id.resolved(db, |it| {
format!( format!(
"static {} = ", "const {} = ",
item_tree_id.item_tree(db)[item_tree_id.value].name.display(db.upcast()) match &it.name {
)
}
DefWithBodyId::ConstId(it) => {
let item_tree_id = it.lookup(db).id;
let name = match &item_tree_id.item_tree(db)[item_tree_id.value].name {
Some(name) => name.display(db.upcast()).to_string(), Some(name) => name.display(db.upcast()).to_string(),
None => "_".to_string(), None => "_".to_string(),
};
format!("const {name} = ")
} }
)
}),
DefWithBodyId::InTypeConstId(_) => format!("In type const = "), DefWithBodyId::InTypeConstId(_) => format!("In type const = "),
DefWithBodyId::VariantId(it) => { DefWithBodyId::VariantId(it) => {
let loc = it.lookup(db); let loc = it.lookup(db);

View file

@ -204,15 +204,18 @@ impl ChildBySource for VariantId {
} }
impl ChildBySource for EnumId { impl ChildBySource for EnumId {
fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, _: HirFileId) { fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, file_id: HirFileId) {
let loc = &self.lookup(db); let loc = &self.lookup(db);
if file_id != loc.id.file_id() {
return;
}
let tree = loc.id.item_tree(db); let tree = loc.id.item_tree(db);
let ast_id_map = db.ast_id_map(loc.id.file_id()); let ast_id_map = db.ast_id_map(loc.id.file_id());
let root = db.parse_or_expand(loc.id.file_id()); let root = db.parse_or_expand(loc.id.file_id());
db.enum_data(*self).variants.iter().for_each(|&(variant, _)| { db.enum_data(*self).variants.iter().for_each(|&(variant, _)| {
res[keys::VARIANT].insert( res[keys::ENUM_VARIANT].insert(
ast_id_map.get(tree[variant.lookup(db).id.value].ast_id).to_node(&root), ast_id_map.get(tree[variant.lookup(db).id.value].ast_id).to_node(&root),
variant, variant,
); );

View file

@ -298,7 +298,7 @@ impl EnumData {
Arc::new(EnumData { Arc::new(EnumData {
name: enum_.name.clone(), name: enum_.name.clone(),
variants: loc.container.def_map(db)[loc.container.local_id].scope.enums[&e] variants: loc.container.def_map(db).enum_definitions[&e]
.iter() .iter()
.map(|&id| (id, item_tree[id.lookup(db).id.value].name.clone())) .map(|&id| (id, item_tree[id.lookup(db).id.value].name.clone()))
.collect(), .collect(),
@ -332,7 +332,7 @@ impl EnumVariantData {
pub(crate) fn enum_variant_data_with_diagnostics_query( pub(crate) fn enum_variant_data_with_diagnostics_query(
db: &dyn DefDatabase, db: &dyn DefDatabase,
e: EnumVariantId, e: EnumVariantId,
) -> (Arc<EnumVariantData>, Arc<[DefDiagnostic]>) { ) -> (Arc<EnumVariantData>, Option<Arc<Box<[DefDiagnostic]>>>) {
let loc = e.lookup(db); let loc = e.lookup(db);
let krate = loc.container.krate; let krate = loc.container.krate;
let item_tree = loc.id.item_tree(db); let item_tree = loc.id.item_tree(db);
@ -355,7 +355,11 @@ impl EnumVariantData {
name: variant.name.clone(), name: variant.name.clone(),
variant_data: Arc::new(var_data), variant_data: Arc::new(var_data),
}), }),
field_diagnostics.into(), if field_diagnostics.is_empty() {
None
} else {
Some(Arc::new(field_diagnostics.into_boxed_slice()))
},
) )
} }
} }

View file

@ -140,7 +140,7 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + Upcast<dyn ExpandDataba
fn enum_variant_data_with_diagnostics( fn enum_variant_data_with_diagnostics(
&self, &self,
id: EnumVariantId, id: EnumVariantId,
) -> (Arc<EnumVariantData>, Arc<[DefDiagnostic]>); ) -> (Arc<EnumVariantData>, Option<Arc<Box<[DefDiagnostic]>>>);
#[salsa::invoke(ImplData::impl_data_query)] #[salsa::invoke(ImplData::impl_data_query)]
fn impl_data(&self, e: ImplId) -> Arc<ImplData>; fn impl_data(&self, e: ImplId) -> Arc<ImplData>;

View file

@ -28,7 +28,7 @@ pub const ENUM: Key<ast::Enum, EnumId> = Key::new();
pub const EXTERN_CRATE: Key<ast::ExternCrate, ExternCrateId> = Key::new(); pub const EXTERN_CRATE: Key<ast::ExternCrate, ExternCrateId> = Key::new();
pub const USE: Key<ast::Use, UseId> = Key::new(); pub const USE: Key<ast::Use, UseId> = Key::new();
pub const VARIANT: Key<ast::Variant, EnumVariantId> = Key::new(); pub const ENUM_VARIANT: Key<ast::Variant, EnumVariantId> = Key::new();
pub const TUPLE_FIELD: Key<ast::TupleField, FieldId> = Key::new(); pub const TUPLE_FIELD: Key<ast::TupleField, FieldId> = Key::new();
pub const RECORD_FIELD: Key<ast::RecordField, FieldId> = Key::new(); pub const RECORD_FIELD: Key<ast::RecordField, FieldId> = Key::new();
pub const TYPE_PARAM: Key<ast::TypeParam, TypeOrConstParamId> = Key::new(); pub const TYPE_PARAM: Key<ast::TypeParam, TypeOrConstParamId> = Key::new();

View file

@ -18,8 +18,8 @@ use crate::{
db::DefDatabase, db::DefDatabase,
per_ns::PerNs, per_ns::PerNs,
visibility::{Visibility, VisibilityExplicity}, visibility::{Visibility, VisibilityExplicity},
AdtId, BuiltinType, ConstId, EnumId, EnumVariantId, ExternCrateId, HasModule, ImplId, AdtId, BuiltinType, ConstId, ExternCrateId, HasModule, ImplId, LocalModuleId, Lookup, MacroId,
LocalModuleId, Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId, ModuleDefId, ModuleId, TraitId, UseId,
}; };
#[derive(Debug, Default)] #[derive(Debug, Default)]
@ -79,7 +79,6 @@ pub struct ItemScope {
/// declared. /// declared.
declarations: Vec<ModuleDefId>, declarations: Vec<ModuleDefId>,
pub enums: FxHashMap<EnumId, Box<[EnumVariantId]>>,
impls: Vec<ImplId>, impls: Vec<ImplId>,
unnamed_consts: Vec<ConstId>, unnamed_consts: Vec<ConstId>,
/// Traits imported via `use Trait as _;`. /// Traits imported via `use Trait as _;`.
@ -719,7 +718,6 @@ impl ItemScope {
use_imports_types, use_imports_types,
use_imports_macros, use_imports_macros,
macro_invocations, macro_invocations,
enums,
} = self; } = self;
types.shrink_to_fit(); types.shrink_to_fit();
values.shrink_to_fit(); values.shrink_to_fit();
@ -738,7 +736,6 @@ impl ItemScope {
extern_crate_decls.shrink_to_fit(); extern_crate_decls.shrink_to_fit();
use_decls.shrink_to_fit(); use_decls.shrink_to_fit();
macro_invocations.shrink_to_fit(); macro_invocations.shrink_to_fit();
enums.shrink_to_fit();
} }
} }

View file

@ -445,6 +445,13 @@ impl<N> ItemTreeId<N> {
pub fn item_tree(self, db: &dyn DefDatabase) -> Arc<ItemTree> { pub fn item_tree(self, db: &dyn DefDatabase) -> Arc<ItemTree> {
self.tree.item_tree(db) self.tree.item_tree(db)
} }
pub fn resolved<R>(self, db: &dyn DefDatabase, cb: impl FnOnce(&N) -> R) -> R
where
ItemTree: Index<FileItemTreeId<N>, Output = N>,
{
cb(&self.tree.item_tree(db)[self.value])
}
} }
impl<N> Copy for ItemTreeId<N> {} impl<N> Copy for ItemTreeId<N> {}

View file

@ -125,7 +125,7 @@ impl LangItems {
} }
ModuleDefId::AdtId(AdtId::EnumId(e)) => { ModuleDefId::AdtId(AdtId::EnumId(e)) => {
lang_items.collect_lang_item(db, e, LangItemTarget::EnumId); lang_items.collect_lang_item(db, e, LangItemTarget::EnumId);
module_data.scope.enums[&e].iter().for_each(|&id| { crate_def_map.enum_definitions[&e].iter().for_each(|&id| {
lang_items.collect_lang_item(db, id, LangItemTarget::EnumVariant); lang_items.collect_lang_item(db, id, LangItemTarget::EnumVariant);
}); });
} }

View file

@ -80,8 +80,8 @@ use crate::{
path::ModPath, path::ModPath,
per_ns::PerNs, per_ns::PerNs,
visibility::{Visibility, VisibilityExplicity}, visibility::{Visibility, VisibilityExplicity},
AstId, BlockId, BlockLoc, CrateRootModuleId, ExternCrateId, FunctionId, LocalModuleId, Lookup, AstId, BlockId, BlockLoc, CrateRootModuleId, EnumId, EnumVariantId, ExternCrateId, FunctionId,
MacroExpander, MacroId, ModuleId, ProcMacroId, UseId, LocalModuleId, Lookup, MacroExpander, MacroId, ModuleId, ProcMacroId, UseId,
}; };
/// Contains the results of (early) name resolution. /// Contains the results of (early) name resolution.
@ -113,6 +113,7 @@ pub struct DefMap {
/// this contains all kinds of macro, not just `macro_rules!` macro. /// this contains all kinds of macro, not just `macro_rules!` macro.
/// ExternCrateId being None implies it being imported from the general prelude import. /// ExternCrateId being None implies it being imported from the general prelude import.
macro_use_prelude: FxHashMap<Name, (MacroId, Option<ExternCrateId>)>, macro_use_prelude: FxHashMap<Name, (MacroId, Option<ExternCrateId>)>,
pub(crate) enum_definitions: FxHashMap<EnumId, Box<[EnumVariantId]>>,
/// Tracks which custom derives are in scope for an item, to allow resolution of derive helper /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
/// attributes. /// attributes.
@ -370,6 +371,7 @@ impl DefMap {
macro_use_prelude: FxHashMap::default(), macro_use_prelude: FxHashMap::default(),
derive_helpers_in_scope: FxHashMap::default(), derive_helpers_in_scope: FxHashMap::default(),
diagnostics: Vec::new(), diagnostics: Vec::new(),
enum_definitions: FxHashMap::default(),
data: Arc::new(DefMapCrateData { data: Arc::new(DefMapCrateData {
extern_prelude: FxHashMap::default(), extern_prelude: FxHashMap::default(),
exported_derives: FxHashMap::default(), exported_derives: FxHashMap::default(),
@ -612,12 +614,14 @@ impl DefMap {
krate: _, krate: _,
prelude: _, prelude: _,
data: _, data: _,
enum_definitions,
} = self; } = self;
macro_use_prelude.shrink_to_fit(); macro_use_prelude.shrink_to_fit();
diagnostics.shrink_to_fit(); diagnostics.shrink_to_fit();
modules.shrink_to_fit(); modules.shrink_to_fit();
derive_helpers_in_scope.shrink_to_fit(); derive_helpers_in_scope.shrink_to_fit();
enum_definitions.shrink_to_fit();
for (_, module) in modules.iter_mut() { for (_, module) in modules.iter_mut() {
module.children.shrink_to_fit(); module.children.shrink_to_fit();
module.scope.shrink_to_fit(); module.scope.shrink_to_fit();

View file

@ -980,35 +980,26 @@ impl DefCollector<'_> {
cov_mark::hit!(glob_enum); cov_mark::hit!(glob_enum);
// glob import from enum => just import all the variants // glob import from enum => just import all the variants
// We need to check if the def map the enum is from is us, then we can't // We need to check if the def map the enum is from is us, if it is we can't
// call the def-map query since we are currently constructing it! // call the def-map query since we are currently constructing it!
let loc = e.lookup(self.db); let loc = e.lookup(self.db);
let tree = loc.id.item_tree(self.db); let tree = loc.id.item_tree(self.db);
let current_def_map = self.def_map.krate == loc.container.krate let current_def_map = self.def_map.krate == loc.container.krate
&& self.def_map.block_id() == loc.container.block; && self.def_map.block_id() == loc.container.block;
let def_map;
let resolutions = if current_def_map { let resolutions = if current_def_map {
self.def_map.modules[loc.container.local_id].scope.enums[&e] &self.def_map.enum_definitions[&e]
.iter()
.map(|&variant| {
let name = tree[variant.lookup(self.db).id.value].name.clone();
let res =
PerNs::both(variant.into(), variant.into(), vis, None);
(Some(name), res)
})
.collect::<Vec<_>>()
} else { } else {
loc.container.def_map(self.db).modules[loc.container.local_id] def_map = loc.container.def_map(self.db);
.scope &def_map.enum_definitions[&e]
.enums[&e] }
.iter() .iter()
.map(|&variant| { .map(|&variant| {
let name = tree[variant.lookup(self.db).id.value].name.clone(); let name = tree[variant.lookup(self.db).id.value].name.clone();
let res = let res = PerNs::both(variant.into(), variant.into(), vis, None);
PerNs::both(variant.into(), variant.into(), vis, None);
(Some(name), res) (Some(name), res)
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>();
};
self.update(module_id, &resolutions, vis, Some(ImportType::Glob(id))); self.update(module_id, &resolutions, vis, Some(ImportType::Glob(id)));
} }
Some(d) => { Some(d) => {
@ -1749,10 +1740,7 @@ impl ModCollector<'_, '_> {
) )
}) })
.collect(); .collect();
self.def_collector.def_map.modules[module_id] self.def_collector.def_map.enum_definitions.insert(enum_, variants);
.scope
.enums
.insert(enum_, variants);
} }
ModItem::Const(id) => { ModItem::Const(id) => {
let it = &self.item_tree[id]; let it = &self.item_tree[id];

View file

@ -360,25 +360,13 @@ impl DefMap {
let tree = loc.id.item_tree(db); let tree = loc.id.item_tree(db);
let current_def_map = let current_def_map =
self.krate == loc.container.krate && self.block_id() == loc.container.block; self.krate == loc.container.krate && self.block_id() == loc.container.block;
let def_map;
let res = if current_def_map { let res = if current_def_map {
self.modules[loc.container.local_id].scope.enums[&e].iter().find_map( &self.enum_definitions[&e]
|&variant| {
let variant_data = &tree[variant.lookup(db).id.value];
(variant_data.name == *segment).then(|| match variant_data.fields {
Fields::Record(_) => {
PerNs::types(variant.into(), Visibility::Public, None)
}
Fields::Tuple(_) | Fields::Unit => PerNs::both(
variant.into(),
variant.into(),
Visibility::Public,
None,
),
})
},
)
} else { } else {
loc.container.def_map(db).modules[loc.container.local_id].scope.enums[&e] def_map = loc.container.def_map(db);
&def_map.enum_definitions[&e]
}
.iter() .iter()
.find_map(|&variant| { .find_map(|&variant| {
let variant_data = &tree[variant.lookup(db).id.value]; let variant_data = &tree[variant.lookup(db).id.value];
@ -393,8 +381,7 @@ impl DefMap {
None, None,
), ),
}) })
}) });
};
match res { match res {
Some(res) => res, Some(res) => res,
None => { None => {

View file

@ -584,12 +584,15 @@ impl Module {
Adt::Enum(e) => { Adt::Enum(e) => {
for v in e.variants(db) { for v in e.variants(db) {
acc.extend(ModuleDef::Variant(v).diagnostics(db)); acc.extend(ModuleDef::Variant(v).diagnostics(db));
for diag in db.enum_variant_data_with_diagnostics(v.id).1.iter() { if let Some(diags) = &db.enum_variant_data_with_diagnostics(v.id).1
{
for diag in &***diags {
emit_def_diagnostic(db, acc, diag); emit_def_diagnostic(db, acc, diag);
} }
} }
} }
} }
}
acc.extend(def.diagnostics(db)) acc.extend(def.diagnostics(db))
} }
ModuleDef::Macro(m) => emit_macro_def_diagnostics(db, acc, m), ModuleDef::Macro(m) => emit_macro_def_diagnostics(db, acc, m),

View file

@ -201,7 +201,7 @@ impl SourceToDefCtx<'_, '_> {
&mut self, &mut self,
src: InFile<ast::Variant>, src: InFile<ast::Variant>,
) -> Option<EnumVariantId> { ) -> Option<EnumVariantId> {
self.to_def(src, keys::VARIANT) self.to_def(src, keys::ENUM_VARIANT)
} }
pub(super) fn extern_crate_to_def( pub(super) fn extern_crate_to_def(
&mut self, &mut self,