De-arc trait items query

This commit is contained in:
Lukas Wirth 2025-06-24 19:57:42 +02:00
parent 70cbf8332a
commit f25912c6f9
33 changed files with 110 additions and 107 deletions

View file

@ -25,7 +25,7 @@ use crate::{
import_map::ImportMap, import_map::ImportMap,
item_tree::{ItemTree, file_item_tree_query}, item_tree::{ItemTree, file_item_tree_query},
lang_item::{self, LangItem}, lang_item::{self, LangItem},
nameres::{assoc::TraitItems, crate_def_map, diagnostics::DefDiagnostics}, nameres::crate_def_map,
signatures::{ signatures::{
ConstSignature, EnumSignature, FunctionSignature, ImplSignature, StaticSignature, ConstSignature, EnumSignature, FunctionSignature, ImplSignature, StaticSignature,
StructSignature, TraitAliasSignature, TraitSignature, TypeAliasSignature, UnionSignature, StructSignature, TraitAliasSignature, TraitSignature, TypeAliasSignature, UnionSignature,
@ -119,13 +119,6 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + SourceDatabase {
id: VariantId, id: VariantId,
) -> (Arc<VariantFields>, Arc<ExpressionStoreSourceMap>); ) -> (Arc<VariantFields>, Arc<ExpressionStoreSourceMap>);
#[salsa::transparent]
#[salsa::invoke(TraitItems::trait_items_query)]
fn trait_items(&self, e: TraitId) -> Arc<TraitItems>;
#[salsa::invoke(TraitItems::trait_items_with_diagnostics_query)]
fn trait_items_with_diagnostics(&self, tr: TraitId) -> (Arc<TraitItems>, DefDiagnostics);
#[salsa::tracked] #[salsa::tracked]
fn variant_fields(&self, id: VariantId) -> Arc<VariantFields> { fn variant_fields(&self, id: VariantId) -> Arc<VariantFields> {
self.variant_fields_with_source_map(id).0 self.variant_fields_with_source_map(id).0

View file

@ -16,7 +16,7 @@ use crate::{
AssocItemId, AttrDefId, Complete, FxIndexMap, ModuleDefId, ModuleId, TraitId, AssocItemId, AttrDefId, Complete, FxIndexMap, ModuleDefId, ModuleId, TraitId,
db::DefDatabase, db::DefDatabase,
item_scope::{ImportOrExternCrate, ItemInNs}, item_scope::{ImportOrExternCrate, ItemInNs},
nameres::{DefMap, crate_def_map}, nameres::{DefMap, assoc::TraitItems, crate_def_map},
visibility::Visibility, visibility::Visibility,
}; };
@ -221,7 +221,7 @@ impl ImportMap {
trait_import_info: &ImportInfo, trait_import_info: &ImportInfo,
) { ) {
let _p = tracing::info_span!("collect_trait_assoc_items").entered(); let _p = tracing::info_span!("collect_trait_assoc_items").entered();
for &(ref assoc_item_name, item) in &db.trait_items(tr).items { for &(ref assoc_item_name, item) in &TraitItems::query(db, tr).items {
let module_def_id = match item { let module_def_id = match item {
AssocItemId::FunctionId(f) => ModuleDefId::from(f), AssocItemId::FunctionId(f) => ModuleDefId::from(f),
AssocItemId::ConstId(c) => ModuleDefId::from(c), AssocItemId::ConstId(c) => ModuleDefId::from(c),
@ -482,7 +482,7 @@ mod tests {
use expect_test::{Expect, expect}; use expect_test::{Expect, expect};
use test_fixture::WithFixture; use test_fixture::WithFixture;
use crate::{ItemContainerId, Lookup, test_db::TestDB}; use crate::{ItemContainerId, Lookup, nameres::assoc::TraitItems, test_db::TestDB};
use super::*; use super::*;
@ -580,7 +580,7 @@ mod tests {
let trait_info = dependency_imports.import_info_for(ItemInNs::Types(trait_id.into()))?; let trait_info = dependency_imports.import_info_for(ItemInNs::Types(trait_id.into()))?;
let trait_items = db.trait_items(trait_id); let trait_items = TraitItems::query(db, trait_id);
let (assoc_item_name, _) = trait_items let (assoc_item_name, _) = trait_items
.items .items
.iter() .iter()

View file

@ -9,8 +9,10 @@ use triomphe::Arc;
use crate::{ use crate::{
AdtId, AssocItemId, AttrDefId, Crate, EnumId, EnumVariantId, FunctionId, ImplId, ModuleDefId, AdtId, AssocItemId, AttrDefId, Crate, EnumId, EnumVariantId, FunctionId, ImplId, ModuleDefId,
StaticId, StructId, TraitId, TypeAliasId, UnionId, db::DefDatabase, expr_store::path::Path, StaticId, StructId, TraitId, TypeAliasId, UnionId,
nameres::crate_def_map, db::DefDatabase,
expr_store::path::Path,
nameres::{assoc::TraitItems, crate_def_map},
}; };
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@ -113,14 +115,16 @@ pub fn crate_lang_items(db: &dyn DefDatabase, krate: Crate) -> Option<Box<LangIt
match def { match def {
ModuleDefId::TraitId(trait_) => { ModuleDefId::TraitId(trait_) => {
lang_items.collect_lang_item(db, trait_, LangItemTarget::Trait); lang_items.collect_lang_item(db, trait_, LangItemTarget::Trait);
db.trait_items(trait_).items.iter().for_each(|&(_, assoc_id)| match assoc_id { TraitItems::query(db, trait_).items.iter().for_each(|&(_, assoc_id)| {
AssocItemId::FunctionId(f) => { match assoc_id {
lang_items.collect_lang_item(db, f, LangItemTarget::Function); AssocItemId::FunctionId(f) => {
lang_items.collect_lang_item(db, f, LangItemTarget::Function);
}
AssocItemId::TypeAliasId(alias) => {
lang_items.collect_lang_item(db, alias, LangItemTarget::TypeAlias)
}
AssocItemId::ConstId(_) => {}
} }
AssocItemId::TypeAliasId(alias) => {
lang_items.collect_lang_item(db, alias, LangItemTarget::TypeAlias)
}
AssocItemId::ConstId(_) => {}
}); });
} }
ModuleDefId::AdtId(AdtId::EnumId(e)) => { ModuleDefId::AdtId(AdtId::EnumId(e)) => {

View file

@ -89,7 +89,9 @@ use crate::{
db::DefDatabase, db::DefDatabase,
hir::generics::{LocalLifetimeParamId, LocalTypeOrConstParamId}, hir::generics::{LocalLifetimeParamId, LocalTypeOrConstParamId},
nameres::{ nameres::{
LocalDefMap, assoc::ImplItems, block_def_map, crate_def_map, crate_local_def_map, LocalDefMap,
assoc::{ImplItems, TraitItems},
block_def_map, crate_def_map, crate_local_def_map,
diagnostics::DefDiagnostics, diagnostics::DefDiagnostics,
}, },
signatures::{EnumVariants, InactiveEnumVariantCode, VariantFields}, signatures::{EnumVariants, InactiveEnumVariantCode, VariantFields},
@ -282,6 +284,13 @@ impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
pub type TraitLoc = ItemLoc<ast::Trait>; pub type TraitLoc = ItemLoc<ast::Trait>;
impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait); impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
impl TraitId {
#[inline]
pub fn trait_items(self, db: &dyn DefDatabase) -> &TraitItems {
TraitItems::query(db, self)
}
}
pub type TraitAliasLoc = ItemLoc<ast::TraitAlias>; pub type TraitAliasLoc = ItemLoc<ast::TraitAlias>;
impl_intern!(TraitAliasId, TraitAliasLoc, intern_trait_alias, lookup_intern_trait_alias); impl_intern!(TraitAliasId, TraitAliasLoc, intern_trait_alias, lookup_intern_trait_alias);

View file

@ -38,16 +38,18 @@ pub struct TraitItems {
pub macro_calls: ThinVec<(AstId<ast::Item>, MacroCallId)>, pub macro_calls: ThinVec<(AstId<ast::Item>, MacroCallId)>,
} }
#[salsa::tracked]
impl TraitItems { impl TraitItems {
#[inline] #[inline]
pub(crate) fn trait_items_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitItems> { pub(crate) fn query(db: &dyn DefDatabase, tr: TraitId) -> &TraitItems {
db.trait_items_with_diagnostics(tr).0 &Self::query_with_diagnostics(db, tr).0
} }
pub(crate) fn trait_items_with_diagnostics_query( #[salsa::tracked(returns(ref))]
pub fn query_with_diagnostics(
db: &dyn DefDatabase, db: &dyn DefDatabase,
tr: TraitId, tr: TraitId,
) -> (Arc<TraitItems>, DefDiagnostics) { ) -> (TraitItems, DefDiagnostics) {
let ItemLoc { container: module_id, id: ast_id } = tr.lookup(db); let ItemLoc { container: module_id, id: ast_id } = tr.lookup(db);
let collector = let collector =
@ -55,7 +57,7 @@ impl TraitItems {
let source = ast_id.with_value(collector.ast_id_map.get(ast_id.value)).to_node(db); let source = ast_id.with_value(collector.ast_id_map.get(ast_id.value)).to_node(db);
let (items, macro_calls, diagnostics) = collector.collect(source.assoc_item_list()); let (items, macro_calls, diagnostics) = collector.collect(source.assoc_item_list());
(Arc::new(TraitItems { macro_calls, items }), DefDiagnostics::new(diagnostics)) (TraitItems { macro_calls, items }, DefDiagnostics::new(diagnostics))
} }
pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ { pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {

View file

@ -41,6 +41,7 @@ use crate::{
macro_call_as_call_id, macro_call_as_call_id,
nameres::{ nameres::{
BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, ModuleData, ModuleOrigin, ResolveMode, BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, ModuleData, ModuleOrigin, ResolveMode,
assoc::TraitItems,
attr_resolution::{attr_macro_as_call_id, derive_macro_as_call_id}, attr_resolution::{attr_macro_as_call_id, derive_macro_as_call_id},
crate_def_map, crate_def_map,
diagnostics::DefDiagnostic, diagnostics::DefDiagnostic,
@ -1020,8 +1021,7 @@ impl<'db> DefCollector<'db> {
let resolutions = if true { let resolutions = if true {
vec![] vec![]
} else { } else {
self.db TraitItems::query(self.db, it)
.trait_items(it)
.items .items
.iter() .iter()
.map(|&(ref name, variant)| { .map(|&(ref name, variant)| {

View file

@ -24,8 +24,8 @@ use crate::{
item_scope::{BUILTIN_SCOPE, ImportOrExternCrate}, item_scope::{BUILTIN_SCOPE, ImportOrExternCrate},
item_tree::FieldsShape, item_tree::FieldsShape,
nameres::{ nameres::{
BlockInfo, BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, crate_def_map, BlockInfo, BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, assoc::TraitItems,
sub_namespace_match, crate_def_map, sub_namespace_match,
}, },
per_ns::PerNs, per_ns::PerNs,
visibility::{RawVisibility, Visibility}, visibility::{RawVisibility, Visibility},
@ -584,8 +584,11 @@ impl DefMap {
// now resulting in a cycle. // now resulting in a cycle.
// To properly implement this, trait item collection needs to be done in def map // To properly implement this, trait item collection needs to be done in def map
// collection... // collection...
let item = let item = if true {
if true { None } else { db.trait_items(t).assoc_item_by_name(segment) }; None
} else {
TraitItems::query(db, t).assoc_item_by_name(segment)
};
return match item { return match item {
Some(item) => ResolvePathResult::new( Some(item) => ResolvePathResult::new(
match item { match item {

View file

@ -208,7 +208,7 @@ pub(crate) fn deref_by_trait(
}; };
let trait_id = trait_id()?; let trait_id = trait_id()?;
let target = let target =
db.trait_items(trait_id).associated_type_by_name(&Name::new_symbol_root(sym::Target))?; trait_id.trait_items(db).associated_type_by_name(&Name::new_symbol_root(sym::Target))?;
let projection = { let projection = {
let b = TyBuilder::subst_for_def(db, trait_id, None); let b = TyBuilder::subst_for_def(db, trait_id, None);

View file

@ -315,9 +315,8 @@ impl chalk_solve::RustIrDatabase<Interner> for ChalkContext<'_> {
crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => { crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
if let Some((future_trait, future_output)) = if let Some((future_trait, future_output)) =
LangItem::Future.resolve_trait(self.db, self.krate).and_then(|trait_| { LangItem::Future.resolve_trait(self.db, self.krate).and_then(|trait_| {
let alias = self let alias = trait_
.db .trait_items(self.db)
.trait_items(trait_)
.associated_type_by_name(&Name::new_symbol_root(sym::Output))?; .associated_type_by_name(&Name::new_symbol_root(sym::Output))?;
Some((trait_, alias)) Some((trait_, alias))
}) })
@ -711,7 +710,7 @@ pub(crate) fn trait_datum_query(
}; };
let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars); let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
let associated_ty_ids = let associated_ty_ids =
db.trait_items(trait_).associated_types().map(to_assoc_type_id).collect(); trait_.trait_items(db).associated_types().map(to_assoc_type_id).collect();
let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses }; let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
let well_known = db.lang_attr(trait_.into()).and_then(well_known_trait_from_lang_item); let well_known = db.lang_attr(trait_.into()).and_then(well_known_trait_from_lang_item);
let trait_datum = TraitDatum { let trait_datum = TraitDatum {
@ -879,7 +878,7 @@ fn impl_def_datum(db: &dyn HirDatabase, krate: Crate, impl_id: hir_def::ImplId)
let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive }; let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive };
let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses }; let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses };
let trait_data = db.trait_items(trait_); let trait_data = trait_.trait_items(db);
let associated_ty_value_ids = impl_id let associated_ty_value_ids = impl_id
.impl_items(db) .impl_items(db)
.items .items
@ -931,8 +930,9 @@ fn type_alias_associated_ty_value(
.into_value_and_skipped_binders() .into_value_and_skipped_binders()
.0; // we don't return any assoc ty values if the impl'd trait can't be resolved .0; // we don't return any assoc ty values if the impl'd trait can't be resolved
let assoc_ty = db let assoc_ty = trait_ref
.trait_items(trait_ref.hir_trait_id()) .hir_trait_id()
.trait_items(db)
.associated_type_by_name(&type_alias_data.name) .associated_type_by_name(&type_alias_data.name)
.expect("assoc ty value should not exist"); // validated when building the impl data as well .expect("assoc ty value should not exist"); // validated when building the impl data as well
let (ty, binders) = db.ty(type_alias.into()).into_value_and_skipped_binders(); let (ty, binders) = db.ty(type_alias.into()).into_value_and_skipped_binders();

View file

@ -494,7 +494,7 @@ impl FilterMapNextChecker {
Some(next_function_id), Some(next_function_id),
match next_function_id.lookup(db).container { match next_function_id.lookup(db).container {
ItemContainerId::TraitId(iterator_trait_id) => { ItemContainerId::TraitId(iterator_trait_id) => {
let iterator_trait_items = &db.trait_items(iterator_trait_id).items; let iterator_trait_items = &iterator_trait_id.trait_items(db).items;
iterator_trait_items.iter().find_map(|(name, it)| match it { iterator_trait_items.iter().find_map(|(name, it)| match it {
&AssocItemId::FunctionId(id) if *name == sym::filter_map => Some(id), &AssocItemId::FunctionId(id) if *name == sym::filter_map => Some(id),
_ => None, _ => None,

View file

@ -1394,7 +1394,7 @@ impl HirDisplay for Ty {
let future_trait = let future_trait =
LangItem::Future.resolve_trait(db, body.module(db).krate()); LangItem::Future.resolve_trait(db, body.module(db).krate());
let output = future_trait.and_then(|t| { let output = future_trait.and_then(|t| {
db.trait_items(t) t.trait_items(db)
.associated_type_by_name(&Name::new_symbol_root(sym::Output)) .associated_type_by_name(&Name::new_symbol_root(sym::Output))
}); });
write!(f, "impl ")?; write!(f, "impl ")?;

View file

@ -101,7 +101,7 @@ where
// rustc checks for non-lifetime binders here, but we don't support HRTB yet // rustc checks for non-lifetime binders here, but we don't support HRTB yet
let trait_data = db.trait_items(trait_); let trait_data = trait_.trait_items(db);
for (_, assoc_item) in &trait_data.items { for (_, assoc_item) in &trait_data.items {
dyn_compatibility_violation_for_assoc_item(db, trait_, *assoc_item, cb)?; dyn_compatibility_violation_for_assoc_item(db, trait_, *assoc_item, cb)?;
} }
@ -164,7 +164,7 @@ fn predicates_reference_self(db: &dyn HirDatabase, trait_: TraitId) -> bool {
// Same as the above, `predicates_reference_self` // Same as the above, `predicates_reference_self`
fn bounds_reference_self(db: &dyn HirDatabase, trait_: TraitId) -> bool { fn bounds_reference_self(db: &dyn HirDatabase, trait_: TraitId) -> bool {
let trait_data = db.trait_items(trait_); let trait_data = trait_.trait_items(db);
trait_data trait_data
.items .items
.iter() .iter()

View file

@ -1813,7 +1813,7 @@ impl<'db> InferenceContext<'db> {
} }
fn resolve_output_on(&self, trait_: TraitId) -> Option<TypeAliasId> { fn resolve_output_on(&self, trait_: TraitId) -> Option<TypeAliasId> {
self.db.trait_items(trait_).associated_type_by_name(&Name::new_symbol_root(sym::Output)) trait_.trait_items(self.db).associated_type_by_name(&Name::new_symbol_root(sym::Output))
} }
fn resolve_lang_trait(&self, lang: LangItem) -> Option<TraitId> { fn resolve_lang_trait(&self, lang: LangItem) -> Option<TraitId> {

View file

@ -1210,9 +1210,8 @@ impl InferenceContext<'_> {
if let Some(deref_trait) = if let Some(deref_trait) =
self.resolve_lang_item(LangItem::DerefMut).and_then(|it| it.as_trait()) self.resolve_lang_item(LangItem::DerefMut).and_then(|it| it.as_trait())
{ {
if let Some(deref_fn) = self if let Some(deref_fn) = deref_trait
.db .trait_items(self.db)
.trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref_mut)) .method_by_name(&Name::new_symbol_root(sym::deref_mut))
{ {
break 'b deref_fn == f; break 'b deref_fn == f;

View file

@ -654,9 +654,8 @@ impl InferenceContext<'_> {
match op { match op {
UnaryOp::Deref => { UnaryOp::Deref => {
if let Some(deref_trait) = self.resolve_lang_trait(LangItem::Deref) { if let Some(deref_trait) = self.resolve_lang_trait(LangItem::Deref) {
if let Some(deref_fn) = self if let Some(deref_fn) = deref_trait
.db .trait_items(self.db)
.trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref)) .method_by_name(&Name::new_symbol_root(sym::deref))
{ {
// FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that // FIXME: this is wrong in multiple ways, subst is empty, and we emit it even for builtin deref (note that
@ -813,9 +812,8 @@ impl InferenceContext<'_> {
self.table.new_lifetime_var(), self.table.new_lifetime_var(),
)); ));
self.write_expr_adj(*base, adj.into_boxed_slice()); self.write_expr_adj(*base, adj.into_boxed_slice());
if let Some(func) = self if let Some(func) = index_trait
.db .trait_items(self.db)
.trait_items(index_trait)
.method_by_name(&Name::new_symbol_root(sym::index)) .method_by_name(&Name::new_symbol_root(sym::index))
{ {
let subst = TyBuilder::subst_for_def(self.db, index_trait, None); let subst = TyBuilder::subst_for_def(self.db, index_trait, None);
@ -1148,7 +1146,7 @@ impl InferenceContext<'_> {
let Some(trait_) = fn_x.get_id(self.db, self.table.trait_env.krate) else { let Some(trait_) = fn_x.get_id(self.db, self.table.trait_env.krate) else {
return; return;
}; };
let trait_data = self.db.trait_items(trait_); let trait_data = trait_.trait_items(self.db);
if let Some(func) = trait_data.method_by_name(&fn_x.method_name()) { if let Some(func) = trait_data.method_by_name(&fn_x.method_name()) {
let subst = TyBuilder::subst_for_def(self.db, trait_, None) let subst = TyBuilder::subst_for_def(self.db, trait_, None)
.push(callee_ty.clone()) .push(callee_ty.clone())
@ -1316,7 +1314,7 @@ impl InferenceContext<'_> {
let trait_func = lang_items_for_bin_op(op).and_then(|(name, lang_item)| { let trait_func = lang_items_for_bin_op(op).and_then(|(name, lang_item)| {
let trait_id = self.resolve_lang_item(lang_item)?.as_trait()?; let trait_id = self.resolve_lang_item(lang_item)?.as_trait()?;
let func = self.db.trait_items(trait_id).method_by_name(&name)?; let func = trait_id.trait_items(self.db).method_by_name(&name)?;
Some((trait_id, func)) Some((trait_id, func))
}); });
let (trait_, func) = match trait_func { let (trait_, func) = match trait_func {

View file

@ -129,9 +129,8 @@ impl InferenceContext<'_> {
if let Some(index_trait) = if let Some(index_trait) =
LangItem::IndexMut.resolve_trait(self.db, self.table.trait_env.krate) LangItem::IndexMut.resolve_trait(self.db, self.table.trait_env.krate)
{ {
if let Some(index_fn) = self if let Some(index_fn) = index_trait
.db .trait_items(self.db)
.trait_items(index_trait)
.method_by_name(&Name::new_symbol_root(sym::index_mut)) .method_by_name(&Name::new_symbol_root(sym::index_mut))
{ {
*f = index_fn; *f = index_fn;
@ -194,9 +193,8 @@ impl InferenceContext<'_> {
}); });
if is_mut_ptr { if is_mut_ptr {
mutability = Mutability::Not; mutability = Mutability::Not;
} else if let Some(deref_fn) = self } else if let Some(deref_fn) = deref_trait
.db .trait_items(self.db)
.trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref_mut)) .method_by_name(&Name::new_symbol_root(sym::deref_mut))
{ {
*f = deref_fn; *f = deref_fn;

View file

@ -278,7 +278,7 @@ impl InferenceContext<'_> {
) -> Option<(ValueNs, Substitution)> { ) -> Option<(ValueNs, Substitution)> {
let trait_ = trait_ref.hir_trait_id(); let trait_ = trait_ref.hir_trait_id();
let item = let item =
self.db.trait_items(trait_).items.iter().map(|(_name, id)| *id).find_map(|item| { trait_.trait_items(self.db).items.iter().map(|(_name, id)| *id).find_map(|item| {
match item { match item {
AssocItemId::FunctionId(func) => { AssocItemId::FunctionId(func) => {
if segment.name == &self.db.function_signature(func).name { if segment.name == &self.db.function_signature(func).name {

View file

@ -859,7 +859,7 @@ impl<'a> InferenceTable<'a> {
] { ] {
let krate = self.trait_env.krate; let krate = self.trait_env.krate;
let fn_trait = fn_trait_name.get_id(self.db, krate)?; let fn_trait = fn_trait_name.get_id(self.db, krate)?;
let trait_data = self.db.trait_items(fn_trait); let trait_data = fn_trait.trait_items(self.db);
let output_assoc_type = let output_assoc_type =
trait_data.associated_type_by_name(&Name::new_symbol_root(output_assoc_name))?; trait_data.associated_type_by_name(&Name::new_symbol_root(output_assoc_name))?;

View file

@ -891,8 +891,8 @@ pub fn callable_sig_from_fn_trait(
) -> Option<(FnTrait, CallableSig)> { ) -> Option<(FnTrait, CallableSig)> {
let krate = trait_env.krate; let krate = trait_env.krate;
let fn_once_trait = FnTrait::FnOnce.get_id(db, krate)?; let fn_once_trait = FnTrait::FnOnce.get_id(db, krate)?;
let output_assoc_type = db let output_assoc_type = fn_once_trait
.trait_items(fn_once_trait) .trait_items(db)
.associated_type_by_name(&Name::new_symbol_root(sym::Output))?; .associated_type_by_name(&Name::new_symbol_root(sym::Output))?;
let mut table = InferenceTable::new(db, trait_env.clone()); let mut table = InferenceTable::new(db, trait_env.clone());

View file

@ -805,7 +805,7 @@ fn named_associated_type_shorthand_candidates<R>(
) -> Option<R> { ) -> Option<R> {
let mut search = |t| { let mut search = |t| {
all_super_trait_refs(db, t, |t| { all_super_trait_refs(db, t, |t| {
let data = db.trait_items(t.hir_trait_id()); let data = t.hir_trait_id().trait_items(db);
for (name, assoc_id) in &data.items { for (name, assoc_id) in &data.items {
if let AssocItemId::TypeAliasId(alias) = assoc_id { if let AssocItemId::TypeAliasId(alias) = assoc_id {
@ -957,7 +957,7 @@ pub(crate) fn generic_predicates_for_param_query(
}; };
all_super_traits(db, tr).iter().any(|tr| { all_super_traits(db, tr).iter().any(|tr| {
db.trait_items(*tr).items.iter().any(|(name, item)| { tr.trait_items(db).items.iter().any(|(name, item)| {
matches!(item, AssocItemId::TypeAliasId(_)) && name == assoc_name matches!(item, AssocItemId::TypeAliasId(_)) && name == assoc_name
}) })
}) })

View file

@ -173,7 +173,7 @@ impl<'a, 'b> PathLoweringContext<'a, 'b> {
self.skip_resolved_segment(); self.skip_resolved_segment();
let segment = self.current_or_prev_segment; let segment = self.current_or_prev_segment;
let found = let found =
self.ctx.db.trait_items(trait_).associated_type_by_name(segment.name); trait_.trait_items(self.ctx.db).associated_type_by_name(segment.name);
match found { match found {
Some(associated_ty) => { Some(associated_ty) => {

View file

@ -1302,7 +1302,7 @@ fn iterate_trait_method_candidates(
// trait, but if we find out it doesn't, we'll skip the rest of the // trait, but if we find out it doesn't, we'll skip the rest of the
// iteration // iteration
let mut known_implemented = false; let mut known_implemented = false;
for &(_, item) in db.trait_items(t).items.iter() { for &(_, item) in t.trait_items(db).items.iter() {
// Don't pass a `visible_from_module` down to `is_valid_candidate`, // Don't pass a `visible_from_module` down to `is_valid_candidate`,
// since only inherent methods should be included into visibility checking. // since only inherent methods should be included into visibility checking.
let visible = let visible =
@ -1429,7 +1429,7 @@ fn iterate_inherent_methods(
) -> ControlFlow<()> { ) -> ControlFlow<()> {
let db = table.db; let db = table.db;
for t in traits { for t in traits {
let data = db.trait_items(t); let data = t.trait_items(db);
for &(_, item) in data.items.iter() { for &(_, item) in data.items.iter() {
// We don't pass `visible_from_module` as all trait items should be visible. // We don't pass `visible_from_module` as all trait items should be visible.
let visible = match is_valid_trait_method_candidate( let visible = match is_valid_trait_method_candidate(

View file

@ -657,12 +657,12 @@ impl Evaluator<'_> {
cached_ptr_size, cached_ptr_size,
cached_fn_trait_func: LangItem::Fn cached_fn_trait_func: LangItem::Fn
.resolve_trait(db, crate_id) .resolve_trait(db, crate_id)
.and_then(|x| db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call))), .and_then(|x| x.trait_items(db).method_by_name(&Name::new_symbol_root(sym::call))),
cached_fn_mut_trait_func: LangItem::FnMut.resolve_trait(db, crate_id).and_then(|x| { cached_fn_mut_trait_func: LangItem::FnMut.resolve_trait(db, crate_id).and_then(|x| {
db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call_mut)) x.trait_items(db).method_by_name(&Name::new_symbol_root(sym::call_mut))
}), }),
cached_fn_once_trait_func: LangItem::FnOnce.resolve_trait(db, crate_id).and_then(|x| { cached_fn_once_trait_func: LangItem::FnOnce.resolve_trait(db, crate_id).and_then(|x| {
db.trait_items(x).method_by_name(&Name::new_symbol_root(sym::call_once)) x.trait_items(db).method_by_name(&Name::new_symbol_root(sym::call_once))
}), }),
}) })
} }
@ -2808,7 +2808,7 @@ impl Evaluator<'_> {
) -> Result<()> { ) -> Result<()> {
let Some(drop_fn) = (|| { let Some(drop_fn) = (|| {
let drop_trait = LangItem::Drop.resolve_trait(self.db, self.crate_id)?; let drop_trait = LangItem::Drop.resolve_trait(self.db, self.crate_id)?;
self.db.trait_items(drop_trait).method_by_name(&Name::new_symbol_root(sym::drop)) drop_trait.trait_items(self.db).method_by_name(&Name::new_symbol_root(sym::drop))
})() else { })() else {
// in some tests we don't have drop trait in minicore, and // in some tests we don't have drop trait in minicore, and
// we can ignore drop in them. // we can ignore drop in them.
@ -2918,7 +2918,7 @@ pub fn render_const_using_debug_impl(
not_supported!("core::fmt::Debug not found"); not_supported!("core::fmt::Debug not found");
}; };
let Some(debug_fmt_fn) = let Some(debug_fmt_fn) =
db.trait_items(debug_trait).method_by_name(&Name::new_symbol_root(sym::fmt)) debug_trait.trait_items(db).method_by_name(&Name::new_symbol_root(sym::fmt))
else { else {
not_supported!("core::fmt::Debug::fmt not found"); not_supported!("core::fmt::Debug::fmt not found");
}; };

View file

@ -1257,9 +1257,8 @@ impl Evaluator<'_> {
args.push(IntervalAndTy::new(addr, field, self, locals)?); args.push(IntervalAndTy::new(addr, field, self, locals)?);
} }
if let Some(target) = LangItem::FnOnce.resolve_trait(self.db, self.crate_id) { if let Some(target) = LangItem::FnOnce.resolve_trait(self.db, self.crate_id) {
if let Some(def) = self if let Some(def) = target
.db .trait_items(self.db)
.trait_items(target)
.method_by_name(&Name::new_symbol_root(sym::call_once)) .method_by_name(&Name::new_symbol_root(sym::call_once))
{ {
self.exec_fn_trait( self.exec_fn_trait(

View file

@ -193,9 +193,8 @@ impl MirLowerCtx<'_> {
if let Some(deref_trait) = if let Some(deref_trait) =
self.resolve_lang_item(LangItem::DerefMut)?.as_trait() self.resolve_lang_item(LangItem::DerefMut)?.as_trait()
{ {
if let Some(deref_fn) = self if let Some(deref_fn) = deref_trait
.db .trait_items(self.db)
.trait_items(deref_trait)
.method_by_name(&Name::new_symbol_root(sym::deref_mut)) .method_by_name(&Name::new_symbol_root(sym::deref_mut))
{ {
break 'b deref_fn == f; break 'b deref_fn == f;
@ -347,9 +346,8 @@ impl MirLowerCtx<'_> {
.resolve_lang_item(trait_lang_item)? .resolve_lang_item(trait_lang_item)?
.as_trait() .as_trait()
.ok_or(MirLowerError::LangItemNotFound(trait_lang_item))?; .ok_or(MirLowerError::LangItemNotFound(trait_lang_item))?;
let deref_fn = self let deref_fn = deref_trait
.db .trait_items(self.db)
.trait_items(deref_trait)
.method_by_name(&trait_method_name) .method_by_name(&trait_method_name)
.ok_or(MirLowerError::LangItemNotFound(trait_lang_item))?; .ok_or(MirLowerError::LangItemNotFound(trait_lang_item))?;
let deref_fn_op = Operand::const_zst( let deref_fn_op = Operand::const_zst(

View file

@ -486,7 +486,7 @@ pub(crate) fn visit_module(
}); });
} }
ModuleDefId::TraitId(it) => { ModuleDefId::TraitId(it) => {
let trait_data = db.trait_items(it); let trait_data = it.trait_items(db);
for &(_, item) in trait_data.items.iter() { for &(_, item) in trait_data.items.iter() {
match item { match item {
AssocItemId::FunctionId(it) => cb(it.into()), AssocItemId::FunctionId(it) => cb(it.into()),

View file

@ -567,7 +567,7 @@ fn main() {
"ast_id_map_shim", "ast_id_map_shim",
"parse_shim", "parse_shim",
"real_span_map_shim", "real_span_map_shim",
"trait_items_with_diagnostics_shim", "query_with_diagnostics_",
"body_shim", "body_shim",
"body_with_source_map_shim", "body_with_source_map_shim",
"attrs_shim", "attrs_shim",
@ -674,7 +674,7 @@ fn main() {
"file_item_tree_query", "file_item_tree_query",
"real_span_map_shim", "real_span_map_shim",
"crate_local_def_map", "crate_local_def_map",
"trait_items_with_diagnostics_shim", "query_with_diagnostics_",
"body_with_source_map_shim", "body_with_source_map_shim",
"attrs_shim", "attrs_shim",
"body_shim", "body_shim",

View file

@ -218,7 +218,7 @@ pub(super) fn associated_type_by_name_including_super_traits(
name: &Name, name: &Name,
) -> Option<(TraitRef, TypeAliasId)> { ) -> Option<(TraitRef, TypeAliasId)> {
all_super_trait_refs(db, trait_ref, |t| { all_super_trait_refs(db, trait_ref, |t| {
let assoc_type = db.trait_items(t.hir_trait_id()).associated_type_by_name(name)?; let assoc_type = t.hir_trait_id().trait_items(db).associated_type_by_name(name)?;
Some((t, assoc_type)) Some((t, assoc_type))
}) })
} }

View file

@ -207,7 +207,7 @@ fn resolve_assoc_or_field(
// Doc paths in this context may only resolve to an item of this trait // Doc paths in this context may only resolve to an item of this trait
// (i.e. no items of its supertraits), so we need to handle them here // (i.e. no items of its supertraits), so we need to handle them here
// independently of others. // independently of others.
return db.trait_items(id).items.iter().find(|it| it.0 == name).map(|(_, assoc_id)| { return id.trait_items(db).items.iter().find(|it| it.0 == name).map(|(_, assoc_id)| {
let def = match *assoc_id { let def = match *assoc_id {
AssocItemId::FunctionId(it) => ModuleDef::Function(it.into()), AssocItemId::FunctionId(it) => ModuleDef::Function(it.into()),
AssocItemId::ConstId(it) => ModuleDef::Const(it.into()), AssocItemId::ConstId(it) => ModuleDef::Const(it.into()),

View file

@ -54,7 +54,7 @@ use hir_def::{
}, },
item_tree::ImportAlias, item_tree::ImportAlias,
layout::{self, ReprOptions, TargetDataLayout}, layout::{self, ReprOptions, TargetDataLayout},
nameres::{self, diagnostics::DefDiagnostic}, nameres::{self, assoc::TraitItems, diagnostics::DefDiagnostic},
per_ns::PerNs, per_ns::PerNs,
resolver::{HasResolver, Resolver}, resolver::{HasResolver, Resolver},
signatures::{ImplFlags, StaticFlags, TraitFlags, VariantFields}, signatures::{ImplFlags, StaticFlags, TraitFlags, VariantFields},
@ -649,7 +649,7 @@ impl Module {
acc.extend(def.diagnostics(db, style_lints)) acc.extend(def.diagnostics(db, style_lints))
} }
ModuleDef::Trait(t) => { ModuleDef::Trait(t) => {
for diag in db.trait_items_with_diagnostics(t.id).1.iter() { for diag in TraitItems::query_with_diagnostics(db, t.id).1.iter() {
emit_def_diagnostic(db, acc, diag, edition); emit_def_diagnostic(db, acc, diag, edition);
} }
@ -822,7 +822,7 @@ impl Module {
// Negative impls can't have items, don't emit missing items diagnostic for them // Negative impls can't have items, don't emit missing items diagnostic for them
if let (false, Some(trait_)) = (impl_is_negative, trait_) { if let (false, Some(trait_)) = (impl_is_negative, trait_) {
let items = &db.trait_items(trait_.into()).items; let items = &trait_.id.trait_items(db).items;
let required_items = items.iter().filter(|&(_, assoc)| match *assoc { let required_items = items.iter().filter(|&(_, assoc)| match *assoc {
AssocItemId::FunctionId(it) => !db.function_signature(it).has_body(), AssocItemId::FunctionId(it) => !db.function_signature(it).has_body(),
AssocItemId::ConstId(id) => !db.const_signature(id).has_body(), AssocItemId::ConstId(id) => !db.const_signature(id).has_body(),
@ -2883,7 +2883,7 @@ impl Trait {
} }
pub fn function(self, db: &dyn HirDatabase, name: impl PartialEq<Name>) -> Option<Function> { pub fn function(self, db: &dyn HirDatabase, name: impl PartialEq<Name>) -> Option<Function> {
db.trait_items(self.id).items.iter().find(|(n, _)| name == *n).and_then(|&(_, it)| match it self.id.trait_items(db).items.iter().find(|(n, _)| name == *n).and_then(|&(_, it)| match it
{ {
AssocItemId::FunctionId(id) => Some(Function { id }), AssocItemId::FunctionId(id) => Some(Function { id }),
_ => None, _ => None,
@ -2891,7 +2891,7 @@ impl Trait {
} }
pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> { pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
db.trait_items(self.id).items.iter().map(|(_name, it)| (*it).into()).collect() self.id.trait_items(db).items.iter().map(|(_name, it)| (*it).into()).collect()
} }
pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec<AssocItem> { pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
@ -2939,7 +2939,7 @@ impl Trait {
} }
fn all_macro_calls(&self, db: &dyn HirDatabase) -> Box<[(AstId<ast::Item>, MacroCallId)]> { fn all_macro_calls(&self, db: &dyn HirDatabase) -> Box<[(AstId<ast::Item>, MacroCallId)]> {
db.trait_items(self.id).macro_calls.to_vec().into_boxed_slice() self.id.trait_items(db).macro_calls.to_vec().into_boxed_slice()
} }
/// `#[rust_analyzer::completions(...)]` mode. /// `#[rust_analyzer::completions(...)]` mode.
@ -5000,7 +5000,7 @@ impl<'db> Type<'db> {
} }
let output_assoc_type = let output_assoc_type =
db.trait_items(trait_).associated_type_by_name(&Name::new_symbol_root(sym::Output))?; trait_.trait_items(db).associated_type_by_name(&Name::new_symbol_root(sym::Output))?;
self.normalize_trait_assoc_type(db, &[], output_assoc_type.into()) self.normalize_trait_assoc_type(db, &[], output_assoc_type.into())
} }
@ -5013,8 +5013,8 @@ impl<'db> Type<'db> {
/// This does **not** resolve `IntoIterator`, only `Iterator`. /// This does **not** resolve `IntoIterator`, only `Iterator`.
pub fn iterator_item(self, db: &'db dyn HirDatabase) -> Option<Type<'db>> { pub fn iterator_item(self, db: &'db dyn HirDatabase) -> Option<Type<'db>> {
let iterator_trait = LangItem::Iterator.resolve_trait(db, self.env.krate)?; let iterator_trait = LangItem::Iterator.resolve_trait(db, self.env.krate)?;
let iterator_item = db let iterator_item = iterator_trait
.trait_items(iterator_trait) .trait_items(db)
.associated_type_by_name(&Name::new_symbol_root(sym::Item))?; .associated_type_by_name(&Name::new_symbol_root(sym::Item))?;
self.normalize_trait_assoc_type(db, &[], iterator_item.into()) self.normalize_trait_assoc_type(db, &[], iterator_item.into())
} }
@ -5044,8 +5044,8 @@ impl<'db> Type<'db> {
return None; return None;
} }
let into_iter_assoc_type = db let into_iter_assoc_type = trait_
.trait_items(trait_) .trait_items(db)
.associated_type_by_name(&Name::new_symbol_root(sym::IntoIter))?; .associated_type_by_name(&Name::new_symbol_root(sym::IntoIter))?;
self.normalize_trait_assoc_type(db, &[], into_iter_assoc_type.into()) self.normalize_trait_assoc_type(db, &[], into_iter_assoc_type.into())
} }

View file

@ -35,7 +35,7 @@ pub(crate) trait ChildBySource {
impl ChildBySource for TraitId { impl ChildBySource for TraitId {
fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, file_id: HirFileId) { fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, file_id: HirFileId) {
let data = db.trait_items(*self); let data = self.trait_items(db);
data.macro_calls().filter(|(ast_id, _)| ast_id.file_id == file_id).for_each( data.macro_calls().filter(|(ast_id, _)| ast_id.file_id == file_id).for_each(
|(ast_id, call_id)| { |(ast_id, call_id)| {

View file

@ -1423,7 +1423,7 @@ impl<'db> SourceAnalyzer<'db> {
method_name: &Name, method_name: &Name,
) -> Option<(TraitId, FunctionId)> { ) -> Option<(TraitId, FunctionId)> {
let trait_id = lang_trait.resolve_trait(db, self.resolver.krate())?; let trait_id = lang_trait.resolve_trait(db, self.resolver.krate())?;
let fn_id = db.trait_items(trait_id).method_by_name(method_name)?; let fn_id = trait_id.trait_items(db).method_by_name(method_name)?;
Some((trait_id, fn_id)) Some((trait_id, fn_id))
} }
@ -1580,7 +1580,7 @@ fn resolve_hir_path_(
// within the trait's associated types. // within the trait's associated types.
if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) { if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
if let Some(type_alias_id) = if let Some(type_alias_id) =
db.trait_items(trait_id).associated_type_by_name(unresolved.name) trait_id.trait_items(db).associated_type_by_name(unresolved.name)
{ {
return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
} }
@ -1731,7 +1731,7 @@ fn resolve_hir_path_qualifier(
// within the trait's associated types. // within the trait's associated types.
if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) { if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
if let Some(type_alias_id) = if let Some(type_alias_id) =
db.trait_items(trait_id).associated_type_by_name(unresolved.name) trait_id.trait_items(db).associated_type_by_name(unresolved.name)
{ {
return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into())); return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
} }

View file

@ -334,7 +334,7 @@ impl<'a> SymbolCollector<'a> {
fn collect_from_trait(&mut self, trait_id: TraitId, trait_do_not_complete: Complete) { fn collect_from_trait(&mut self, trait_id: TraitId, trait_do_not_complete: Complete) {
let trait_data = self.db.trait_signature(trait_id); let trait_data = self.db.trait_signature(trait_id);
self.with_container_name(Some(trait_data.name.as_str().into()), |s| { self.with_container_name(Some(trait_data.name.as_str().into()), |s| {
for &(ref name, assoc_item_id) in &self.db.trait_items(trait_id).items { for &(ref name, assoc_item_id) in &trait_id.trait_items(self.db).items {
s.push_assoc_item(assoc_item_id, name, Some(trait_do_not_complete)); s.push_assoc_item(assoc_item_id, name, Some(trait_do_not_complete));
} }
}); });