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

`rust-analyzer` subtree update

Subtree update of `rust-analyzer` to 5e3e9c4e61.

Created using https://github.com/rust-lang/josh-sync.

r? `@ghost`
This commit is contained in:
bors 2025-12-08 19:24:45 +00:00
commit 37aa2135b5
151 changed files with 1486 additions and 1421 deletions

View file

@ -45,8 +45,8 @@ use syntax::{
use tt::{TextRange, TextSize};
use crate::{
AdtId, AstIdLoc, AttrDefId, FieldId, FunctionId, GenericDefId, HasModule, InternedModuleId,
LifetimeParamId, LocalFieldId, MacroId, TypeOrConstParamId, VariantId,
AdtId, AstIdLoc, AttrDefId, FieldId, FunctionId, GenericDefId, HasModule, LifetimeParamId,
LocalFieldId, MacroId, ModuleId, TypeOrConstParamId, VariantId,
db::DefDatabase,
hir::generics::{GenericParams, LocalLifetimeParamId, LocalTypeOrConstParamId},
nameres::ModuleOrigin,
@ -295,9 +295,8 @@ fn attrs_source(
) -> (InFile<ast::AnyHasAttrs>, Option<InFile<ast::Module>>, Crate) {
let (owner, krate) = match owner {
AttrDefId::ModuleId(id) => {
let id = id.loc(db);
let def_map = id.def_map(db);
let (definition, declaration) = match def_map[id.local_id].origin {
let (definition, declaration) = match def_map[id].origin {
ModuleOrigin::CrateRoot { definition } => {
let file = db.parse(definition).tree();
(InFile::new(definition.into(), ast::AnyHasAttrs::from(file)), None)
@ -318,7 +317,7 @@ fn attrs_source(
(block.with_value(definition.into()), None)
}
};
return (definition, declaration, id.krate);
return (definition, declaration, def_map.krate());
}
AttrDefId::AdtId(AdtId::StructId(it)) => attrs_from_ast_id_loc(db, it),
AttrDefId::AdtId(AdtId::UnionId(it)) => attrs_from_ast_id_loc(db, it),
@ -1201,14 +1200,14 @@ impl AttrFlags {
}
#[inline]
pub fn doc_keyword(db: &dyn DefDatabase, owner: InternedModuleId) -> Option<Symbol> {
pub fn doc_keyword(db: &dyn DefDatabase, owner: ModuleId) -> Option<Symbol> {
if !AttrFlags::query(db, AttrDefId::ModuleId(owner)).contains(AttrFlags::HAS_DOC_KEYWORD) {
return None;
}
return doc_keyword(db, owner);
#[salsa::tracked]
fn doc_keyword(db: &dyn DefDatabase, owner: InternedModuleId) -> Option<Symbol> {
fn doc_keyword(db: &dyn DefDatabase, owner: ModuleId) -> Option<Symbol> {
collect_attrs(db, AttrDefId::ModuleId(owner), |attr| {
if let Meta::TokenTree { path, tt } = attr
&& path.is1("doc")

View file

@ -8,13 +8,12 @@ use la_arena::ArenaMap;
use triomphe::Arc;
use crate::{
AssocItemId, AttrDefId, BlockId, BlockLoc, ConstId, ConstLoc, CrateRootModuleId, DefWithBodyId,
EnumId, EnumLoc, EnumVariantId, EnumVariantLoc, ExternBlockId, ExternBlockLoc, ExternCrateId,
ExternCrateLoc, FunctionId, FunctionLoc, GenericDefId, HasModule, ImplId, ImplLoc,
InternedModuleId, LocalFieldId, Macro2Id, Macro2Loc, MacroExpander, MacroId, MacroRulesId,
MacroRulesLoc, MacroRulesLocFlags, ProcMacroId, ProcMacroLoc, StaticId, StaticLoc, StructId,
StructLoc, TraitId, TraitLoc, TypeAliasId, TypeAliasLoc, UnionId, UnionLoc, UseId, UseLoc,
VariantId,
AssocItemId, AttrDefId, ConstId, ConstLoc, DefWithBodyId, EnumId, EnumLoc, EnumVariantId,
EnumVariantLoc, ExternBlockId, ExternBlockLoc, ExternCrateId, ExternCrateLoc, FunctionId,
FunctionLoc, GenericDefId, ImplId, ImplLoc, LocalFieldId, Macro2Id, Macro2Loc, MacroExpander,
MacroId, MacroRulesId, MacroRulesLoc, MacroRulesLocFlags, ProcMacroId, ProcMacroLoc, StaticId,
StaticLoc, StructId, StructLoc, TraitId, TraitLoc, TypeAliasId, TypeAliasLoc, UnionId,
UnionLoc, UseId, UseLoc, VariantId,
attrs::AttrFlags,
expr_store::{
Body, BodySourceMap, ExpressionStore, ExpressionStoreSourceMap, scope::ExprScopes,
@ -83,9 +82,6 @@ pub trait InternDatabase: RootQueryDb {
#[salsa::interned]
fn intern_macro_rules(&self, loc: MacroRulesLoc) -> MacroRulesId;
// endregion: items
#[salsa::interned]
fn intern_block(&self, loc: BlockLoc) -> BlockId;
}
#[query_group::query_group]
@ -276,8 +272,8 @@ fn include_macro_invoc(
}
fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: Crate) -> bool {
let root_module = CrateRootModuleId::from(crate_id).module(db);
let attrs = AttrFlags::query(db, AttrDefId::ModuleId(InternedModuleId::new(db, root_module)));
let root_module = crate_def_map(db, crate_id).root_module_id();
let attrs = AttrFlags::query(db, AttrDefId::ModuleId(root_module));
attrs.contains(AttrFlags::IS_NO_STD)
}
@ -298,7 +294,7 @@ fn macro_def(db: &dyn DefDatabase, id: MacroId) -> MacroDefId {
let loc: Macro2Loc = it.lookup(db);
MacroDefId {
krate: loc.container.krate,
krate: loc.container.krate(db),
kind: kind(loc.expander, loc.id.file_id, loc.id.value.upcast()),
local_inner: false,
allow_internal_unsafe: loc.allow_internal_unsafe,
@ -309,7 +305,7 @@ fn macro_def(db: &dyn DefDatabase, id: MacroId) -> MacroDefId {
let loc: MacroRulesLoc = it.lookup(db);
MacroDefId {
krate: loc.container.krate,
krate: loc.container.krate(db),
kind: kind(loc.expander, loc.id.file_id, loc.id.value.upcast()),
local_inner: loc.flags.contains(MacroRulesLocFlags::LOCAL_INNER),
allow_internal_unsafe: loc
@ -322,7 +318,7 @@ fn macro_def(db: &dyn DefDatabase, id: MacroId) -> MacroDefId {
let loc = it.lookup(db);
MacroDefId {
krate: loc.container.krate,
krate: loc.container.krate(db),
kind: MacroDefKind::ProcMacro(loc.id, loc.expander, loc.kind),
local_inner: false,
allow_internal_unsafe: false,

View file

@ -31,7 +31,7 @@ use triomphe::Arc;
use tt::TextRange;
use crate::{
AdtId, BlockId, BlockLoc, DefWithBodyId, FunctionId, GenericDefId, ImplId, MacroId,
AdtId, BlockId, BlockIdLt, DefWithBodyId, FunctionId, GenericDefId, ImplId, MacroId,
ModuleDefId, ModuleId, TraitId, TypeAliasId, UnresolvedMacro,
attrs::AttrFlags,
builtin_type::BuiltinUint,
@ -437,6 +437,7 @@ pub struct ExprCollector<'db> {
current_binding_owner: Option<ExprId>,
awaitable_context: Option<Awaitable>,
krate: base_db::Crate,
}
#[derive(Clone, Debug)]
@ -524,9 +525,10 @@ impl<'db> ExprCollector<'db> {
) -> ExprCollector<'_> {
let (def_map, local_def_map) = module.local_def_map(db);
let expander = Expander::new(db, current_file_id, def_map);
let krate = module.krate(db);
ExprCollector {
db,
cfg_options: module.krate().cfg_options(db),
cfg_options: krate.cfg_options(db),
module,
def_map,
local_def_map,
@ -540,12 +542,13 @@ impl<'db> ExprCollector<'db> {
awaitable_context: None,
current_block_legacy_macro_defs_count: FxHashMap::default(),
outer_impl_trait: false,
krate,
}
}
#[inline]
pub(crate) fn lang_items(&self) -> &'db LangItems {
self.lang_items.get_or_init(|| crate::lang_item::lang_items(self.db, self.module.krate))
self.lang_items.get_or_init(|| crate::lang_item::lang_items(self.db, self.def_map.krate()))
}
#[inline]
@ -1915,9 +1918,8 @@ impl<'db> ExprCollector<'db> {
T: ast::AstNode,
{
let macro_call_ptr = self.expander.in_file(syntax_ptr);
let module = self.module.local_id;
let block_call = self.def_map.modules[self.module.local_id].scope.macro_invoc(
let block_call = self.def_map.modules[self.module].scope.macro_invoc(
self.expander.in_file(self.expander.ast_id_map().ast_id_for_ptr(syntax_ptr)),
);
let res = match block_call {
@ -1929,7 +1931,7 @@ impl<'db> ExprCollector<'db> {
.resolve_path(
self.local_def_map,
self.db,
module,
self.module,
path,
crate::item_scope::BuiltinShadowMode::Other,
Some(MacroSubNs::Bang),
@ -1940,7 +1942,7 @@ impl<'db> ExprCollector<'db> {
self.expander.enter_expand(
self.db,
mcall,
self.module.krate(),
self.krate,
resolver,
&mut |ptr, call| {
_ = self.store.expansions.insert(ptr.map(|(it, _)| it), call);
@ -2058,7 +2060,8 @@ impl<'db> ExprCollector<'db> {
return;
};
let name = name.as_name();
let macro_id = self.def_map.modules[DefMap::ROOT].scope.get(&name).take_macros();
let macro_id =
self.def_map.modules[self.def_map.root].scope.get(&name).take_macros();
self.collect_macro_def(statements, macro_id);
}
ast::Stmt::Item(ast::Item::MacroRules(macro_)) => {
@ -2072,7 +2075,7 @@ impl<'db> ExprCollector<'db> {
let name = name.as_name();
let macro_defs_count =
self.current_block_legacy_macro_defs_count.entry(name.clone()).or_insert(0);
let macro_id = self.def_map.modules[DefMap::ROOT]
let macro_id = self.def_map.modules[self.def_map.root]
.scope
.get_legacy_macro(&name)
.and_then(|it| it.get(*macro_defs_count))
@ -2111,14 +2114,14 @@ impl<'db> ExprCollector<'db> {
) -> ExprId {
let block_id = self.expander.ast_id_map().ast_id_for_block(&block).map(|file_local_id| {
let ast_id = self.expander.in_file(file_local_id);
self.db.intern_block(BlockLoc { ast_id, module: self.module })
unsafe { BlockIdLt::new(self.db, ast_id, self.module).to_static() }
});
let (module, def_map) =
match block_id.map(|block_id| (block_def_map(self.db, block_id), block_id)) {
Some((def_map, block_id)) => {
self.store.block_scopes.push(block_id);
(def_map.module_id(DefMap::ROOT), def_map)
(def_map.root_module_id(), def_map)
}
None => (self.module, self.def_map),
};
@ -2201,7 +2204,7 @@ impl<'db> ExprCollector<'db> {
let (resolved, _) = self.def_map.resolve_path(
self.local_def_map,
self.db,
self.module.local_id,
self.module,
&name.clone().into(),
BuiltinShadowMode::Other,
None,
@ -3131,7 +3134,7 @@ impl<'db> ExprCollector<'db> {
let precision_expr = self.make_count(precision, argmap);
let width_expr = self.make_count(width, argmap);
if self.module.krate().workspace_data(self.db).is_atleast_187() {
if self.krate.workspace_data(self.db).is_atleast_187() {
// These need to match the constants in library/core/src/fmt/rt.rs.
let align = match alignment {
Some(FormatAlignment::Left) => 0,

View file

@ -32,14 +32,14 @@ fn def_map_at(#[rust_analyzer::rust_fixture] ra_fixture: &str) -> String {
let (db, position) = TestDB::with_position(ra_fixture);
let module = db.module_at_position(position);
module.def_map(&db).dump(&db)
salsa::plumbing::attach(&db, || module.def_map(&db).dump(&db))
}
fn check_block_scopes_at(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) {
let (db, position) = TestDB::with_position(ra_fixture);
let module = db.module_at_position(position);
let actual = module.def_map(&db).dump_block_scopes(&db);
let actual = salsa::plumbing::attach(&db, || format!("{module:#?}"));
expect.assert_eq(&actual);
}

View file

@ -189,10 +189,63 @@ fn f() {
}
"#,
expect![[r#"
BlockId(3801) in BlockRelativeModuleId { block: Some(BlockId(3800)), local_id: Idx::<ModuleData>(1) }
BlockId(3800) in BlockRelativeModuleId { block: None, local_id: Idx::<ModuleData>(0) }
crate scope
"#]],
ModuleIdLt {
[salsa id]: Id(3003),
krate: Crate(
Id(1c00),
),
block: Some(
BlockIdLt {
[salsa id]: Id(3c01),
ast_id: InFileWrapper {
file_id: FileId(
EditionedFileIdData {
editioned_file_id: EditionedFileId(
0,
Edition2024,
),
krate: Crate(
Id(1c00),
),
},
),
value: FileAstId::<syntax::ast::generated::nodes::BlockExpr>(ErasedFileAstId { kind: BlockExpr, index: 0, hash: F9BF }),
},
module: ModuleIdLt {
[salsa id]: Id(3002),
krate: Crate(
Id(1c00),
),
block: Some(
BlockIdLt {
[salsa id]: Id(3c00),
ast_id: InFileWrapper {
file_id: FileId(
EditionedFileIdData {
editioned_file_id: EditionedFileId(
0,
Edition2024,
),
krate: Crate(
Id(1c00),
),
},
),
value: FileAstId::<syntax::ast::generated::nodes::BlockExpr>(ErasedFileAstId { kind: BlockExpr, index: 0, hash: C181 }),
},
module: ModuleIdLt {
[salsa id]: Id(3000),
krate: Crate(
Id(1c00),
),
block: None,
},
},
),
},
},
),
}"#]],
);
}
@ -460,7 +513,7 @@ fn foo() {
}
#[test]
fn is_visible_from_same_def_map() {
fn is_visible_from_same_def_map_regression_9481() {
// Regression test for https://github.com/rust-lang/rust-analyzer/issues/9481
check_at(
r#"
@ -478,7 +531,6 @@ fn outer() {
- tests : type
(block scope)::tests
- name : _
- outer : value (glob)
crate

View file

@ -12,7 +12,7 @@ use intern::sym;
use rustc_hash::FxHashSet;
use crate::{
FindPathConfig, ModuleDefId, ModuleId,
FindPathConfig, ModuleDefId, ModuleIdLt,
db::DefDatabase,
item_scope::ItemInNs,
nameres::DefMap,
@ -24,7 +24,7 @@ use crate::{
pub fn find_path(
db: &dyn DefDatabase,
item: ItemInNs,
from: ModuleId,
from: ModuleIdLt<'_>,
mut prefix_kind: PrefixKind,
ignore_local_imports: bool,
mut cfg: FindPathConfig,
@ -39,20 +39,23 @@ pub fn find_path(
// within block modules, forcing a `self` or `crate` prefix will not allow using inner items, so
// default to plain paths.
let item_module = item.module(db)?;
if item_module.is_within_block() {
if item_module.block(db).is_some() {
prefix_kind = PrefixKind::Plain;
}
cfg.prefer_no_std = cfg.prefer_no_std || db.crate_supports_no_std(from.krate());
cfg.prefer_no_std = cfg.prefer_no_std || db.crate_supports_no_std(from.krate(db));
let from_def_map = from.def_map(db);
find_path_inner(
&FindPathCtx {
db,
prefix: prefix_kind,
cfg,
ignore_local_imports,
is_std_item: item_module.krate().data(db).origin.is_lang(),
is_std_item: item_module.krate(db).data(db).origin.is_lang(),
from,
from_def_map: from.def_map(db),
from_crate: from.krate(db),
crate_root: from_def_map.crate_root(db),
from_def_map,
fuel: Cell::new(FIND_PATH_FUEL),
},
item,
@ -99,12 +102,14 @@ struct FindPathCtx<'db> {
cfg: FindPathConfig,
ignore_local_imports: bool,
is_std_item: bool,
from: ModuleId,
from: ModuleIdLt<'db>,
from_crate: Crate,
crate_root: ModuleIdLt<'db>,
from_def_map: &'db DefMap,
fuel: Cell<usize>,
}
/// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId
/// Attempts to find a path to refer to the given `item` visible from the `from` ModuleIdLt<'_>
fn find_path_inner(ctx: &FindPathCtx<'_>, item: ItemInNs, max_len: usize) -> Option<ModPath> {
// - if the item is a module, jump straight to module search
if !ctx.is_std_item
@ -116,7 +121,7 @@ fn find_path_inner(ctx: &FindPathCtx<'_>, item: ItemInNs, max_len: usize) -> Opt
let may_be_in_scope = match ctx.prefix {
PrefixKind::Plain | PrefixKind::BySelf => true,
PrefixKind::ByCrate => ctx.from.is_crate_root(),
PrefixKind::ByCrate => ctx.crate_root == ctx.from,
};
if may_be_in_scope {
// - if the item is already in scope, return the name under which it is
@ -152,10 +157,10 @@ fn find_path_inner(ctx: &FindPathCtx<'_>, item: ItemInNs, max_len: usize) -> Opt
}
#[tracing::instrument(skip_all)]
fn find_path_for_module(
ctx: &FindPathCtx<'_>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleId)>,
module_id: ModuleId,
fn find_path_for_module<'db>(
ctx: &'db FindPathCtx<'db>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>,
module_id: ModuleIdLt<'db>,
maybe_extern: bool,
max_len: usize,
) -> Option<Choice> {
@ -163,8 +168,9 @@ fn find_path_for_module(
// recursive base case, we can't find a path of length 0
return None;
}
if let Some(crate_root) = module_id.as_crate_root() {
if !maybe_extern || crate_root == ctx.from.derive_crate_root() {
let module_crate_root = module_id.def_map(ctx.db).crate_root(ctx.db);
if module_crate_root == module_id {
if !maybe_extern || module_crate_root == ctx.crate_root {
// - if the item is the crate root, return `crate`
return Some(Choice {
path: ModPath::from_segments(PathKind::Crate, None),
@ -175,19 +181,19 @@ fn find_path_for_module(
}
// - otherwise if the item is the crate root of a dependency crate, return the name from the extern prelude
let root_local_def_map = ctx.from.derive_crate_root().local_def_map(ctx.db).1;
let root_local_def_map = ctx.crate_root.local_def_map(ctx.db).1;
// rev here so we prefer looking at renamed extern decls first
for (name, (def_id, _extern_crate)) in root_local_def_map.extern_prelude().rev() {
if crate_root != def_id {
if module_crate_root != def_id {
continue;
}
let name_already_occupied_in_type_ns = ctx
.from_def_map
.with_ancestor_maps(ctx.db, ctx.from.local_id, &mut |def_map, local_id| {
.with_ancestor_maps(ctx.db, ctx.from, &mut |def_map, local_id| {
def_map[local_id]
.scope
.type_(name)
.filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id.into()))
.filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id))
})
.is_some();
let kind = if name_already_occupied_in_type_ns {
@ -204,14 +210,14 @@ fn find_path_for_module(
let may_be_in_scope = match ctx.prefix {
PrefixKind::Plain | PrefixKind::BySelf => true,
PrefixKind::ByCrate => ctx.from.is_crate_root(),
PrefixKind::ByCrate => ctx.crate_root == ctx.from,
};
if may_be_in_scope {
let scope_name = find_in_scope(
ctx.db,
ctx.from_def_map,
ctx.from,
ItemInNs::Types(module_id.into()),
ItemInNs::Types(unsafe { module_id.to_static() }.into()),
ctx.ignore_local_imports,
);
if let Some(scope_name) = scope_name {
@ -226,7 +232,7 @@ fn find_path_for_module(
}
// - if the module can be referenced as self, super or crate, do that
if let Some(kind) = is_kw_kind_relative_to_from(ctx.from_def_map, module_id, ctx.from)
if let Some(kind) = is_kw_kind_relative_to_from(ctx.db, ctx.from_def_map, module_id, ctx.from)
&& (ctx.prefix != PrefixKind::ByCrate || kind == PathKind::Crate)
{
return Some(Choice {
@ -238,7 +244,7 @@ fn find_path_for_module(
}
// - if the module is in the prelude, return it by that path
let item = ItemInNs::Types(module_id.into());
let item = ItemInNs::Types(unsafe { module_id.to_static() }.into());
if let Some(choice) = find_in_prelude(ctx.db, ctx.from_def_map, item, ctx.from) {
return Some(choice);
}
@ -251,15 +257,15 @@ fn find_path_for_module(
best_choice
}
fn find_in_scope(
db: &dyn DefDatabase,
fn find_in_scope<'db>(
db: &'db dyn DefDatabase,
def_map: &DefMap,
from: ModuleId,
from: ModuleIdLt<'db>,
item: ItemInNs,
ignore_local_imports: bool,
) -> Option<Name> {
// FIXME: We could have multiple applicable names here, but we currently only return the first
def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
def_map.with_ancestor_maps(db, from, &mut |def_map, local_id| {
def_map[local_id].scope.names_of(item, |name, _, declared| {
(declared || !ignore_local_imports).then(|| name.clone())
})
@ -272,11 +278,11 @@ fn find_in_prelude(
db: &dyn DefDatabase,
local_def_map: &DefMap,
item: ItemInNs,
from: ModuleId,
from: ModuleIdLt<'_>,
) -> Option<Choice> {
let (prelude_module, _) = local_def_map.prelude()?;
let prelude_def_map = prelude_module.def_map(db);
let prelude_scope = &prelude_def_map[prelude_module.local_id].scope;
let prelude_scope = &prelude_def_map[prelude_module].scope;
let (name, vis, _declared) = prelude_scope.name_of(item)?;
if !vis.is_visible_from(db, from) {
return None;
@ -284,7 +290,7 @@ fn find_in_prelude(
// Check if the name is in current scope and it points to the same def.
let found_and_same_def =
local_def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
local_def_map.with_ancestor_maps(db, from, &mut |def_map, local_id| {
let per_ns = def_map[local_id].scope.get(name);
let same_def = match item {
ItemInNs::Types(it) => per_ns.take_types()? == it,
@ -302,22 +308,21 @@ fn find_in_prelude(
}
fn is_kw_kind_relative_to_from(
db: &dyn DefDatabase,
def_map: &DefMap,
item: ModuleId,
from: ModuleId,
item: ModuleIdLt<'_>,
from: ModuleIdLt<'_>,
) -> Option<PathKind> {
if item.krate != from.krate || item.is_within_block() || from.is_within_block() {
if item.krate(db) != from.krate(db) || item.block(db).is_some() || from.block(db).is_some() {
return None;
}
let item = item.local_id;
let from = from.local_id;
if item == from {
// - if the item is the module we're in, use `self`
Some(PathKind::SELF)
} else if let Some(parent_id) = def_map[from].parent {
if item == parent_id {
// - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
Some(if parent_id == DefMap::ROOT { PathKind::Crate } else { PathKind::Super(1) })
Some(if parent_id == def_map.root { PathKind::Crate } else { PathKind::Super(1) })
} else {
None
}
@ -327,9 +332,9 @@ fn is_kw_kind_relative_to_from(
}
#[tracing::instrument(skip_all)]
fn calculate_best_path(
ctx: &FindPathCtx<'_>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleId)>,
fn calculate_best_path<'db>(
ctx: &'db FindPathCtx<'db>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>,
item: ItemInNs,
max_len: usize,
best_choice: &mut Option<Choice>,
@ -340,13 +345,13 @@ fn calculate_best_path(
tracing::warn!(
"ran out of fuel while searching for a path for item {item:?} of krate {:?} from krate {:?}",
item.krate(ctx.db),
ctx.from.krate()
ctx.from_crate
);
return;
}
ctx.fuel.set(fuel - 1);
if item.krate(ctx.db) == Some(ctx.from.krate) {
if item.krate(ctx.db) == Some(ctx.from_crate) {
// Item was defined in the same crate that wants to import it. It cannot be found in any
// dependency in this case.
calculate_best_path_local(ctx, visited_modules, item, max_len, best_choice)
@ -361,20 +366,20 @@ fn calculate_best_path(
// too (unless we can't name it at all). It could *also* be (re)exported by the same crate
// that wants to import it here, but we always prefer to use the external path here.
ctx.from.krate.data(ctx.db).dependencies.iter().for_each(|dep| {
ctx.from_crate.data(ctx.db).dependencies.iter().for_each(|dep| {
find_in_dep(ctx, visited_modules, item, max_len, best_choice, dep.crate_id)
});
}
}
fn find_in_sysroot(
ctx: &FindPathCtx<'_>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleId)>,
fn find_in_sysroot<'db>(
ctx: &'db FindPathCtx<'db>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>,
item: ItemInNs,
max_len: usize,
best_choice: &mut Option<Choice>,
) {
let dependencies = &ctx.from.krate.data(ctx.db).dependencies;
let dependencies = &ctx.from_crate.data(ctx.db).dependencies;
let mut search = |lang, best_choice: &mut _| {
if let Some(dep) = dependencies.iter().filter(|it| it.is_sysroot()).find(|dep| {
match dep.crate_id.data(ctx.db).origin {
@ -413,9 +418,9 @@ fn find_in_sysroot(
});
}
fn find_in_dep(
ctx: &FindPathCtx<'_>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleId)>,
fn find_in_dep<'db>(
ctx: &'db FindPathCtx<'db>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>,
item: ItemInNs,
max_len: usize,
best_choice: &mut Option<Choice>,
@ -456,34 +461,27 @@ fn find_in_dep(
}
}
fn calculate_best_path_local(
ctx: &FindPathCtx<'_>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleId)>,
fn calculate_best_path_local<'db>(
ctx: &'db FindPathCtx<'db>,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>,
item: ItemInNs,
max_len: usize,
best_choice: &mut Option<Choice>,
) {
// FIXME: cache the `find_local_import_locations` output?
find_local_import_locations(
ctx.db,
item,
ctx.from,
ctx.from_def_map,
visited_modules,
|visited_modules, name, module_id| {
// we are looking for paths of length up to best_path_len, any longer will make it be
// less optimal. The -1 is due to us pushing name onto it afterwards.
if let Some(choice) = find_path_for_module(
ctx,
visited_modules,
module_id,
false,
best_choice.as_ref().map_or(max_len, |it| it.path.len()) - 1,
) {
Choice::try_select(best_choice, choice, ctx.cfg.prefer_prelude, name.clone());
}
},
);
find_local_import_locations(ctx, item, visited_modules, |visited_modules, name, module_id| {
// we are looking for paths of length up to best_path_len, any longer will make it be
// less optimal. The -1 is due to us pushing name onto it afterwards.
if let Some(choice) = find_path_for_module(
ctx,
visited_modules,
module_id,
false,
best_choice.as_ref().map_or(max_len, |it| it.path.len()) - 1,
) {
Choice::try_select(best_choice, choice, ctx.cfg.prefer_prelude, name.clone());
}
});
}
#[derive(Debug)]
@ -560,15 +558,14 @@ fn path_kind_len(kind: PathKind) -> usize {
}
/// Finds locations in `from.krate` from which `item` can be imported by `from`.
fn find_local_import_locations(
db: &dyn DefDatabase,
fn find_local_import_locations<'db>(
ctx: &'db FindPathCtx<'db>,
item: ItemInNs,
from: ModuleId,
def_map: &DefMap,
visited_modules: &mut FxHashSet<(ItemInNs, ModuleId)>,
mut cb: impl FnMut(&mut FxHashSet<(ItemInNs, ModuleId)>, &Name, ModuleId),
visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>,
mut cb: impl FnMut(&mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, &Name, ModuleIdLt<'db>),
) {
let _p = tracing::info_span!("find_local_import_locations").entered();
let db = ctx.db;
// `from` can import anything below `from` with visibility of at least `from`, and anything
// above `from` with any visibility. That means we do not need to descend into private siblings
@ -576,15 +573,16 @@ fn find_local_import_locations(
// Compute the initial worklist. We start with all direct child modules of `from` as well as all
// of its (recursive) parent modules.
let mut worklist = def_map[from.local_id]
let mut worklist = ctx.from_def_map[ctx.from]
.children
.values()
.map(|&child| def_map.module_id(child))
.chain(iter::successors(from.containing_module(db), |m| m.containing_module(db)))
.copied()
.chain(iter::successors(ctx.from.containing_module(db), |m| m.containing_module(db)))
.zip(iter::repeat(false))
.collect::<Vec<_>>();
let def_map = def_map.crate_root().def_map(db);
let def_map =
if ctx.crate_root == ctx.from { ctx.from_def_map } else { ctx.crate_root.def_map(db) };
let mut block_def_map;
let mut cursor = 0;
@ -595,17 +593,17 @@ fn find_local_import_locations(
continue;
}
*processed = true;
let data = if module.block.is_some() {
let data = if module.block(db).is_some() {
// Re-query the block's DefMap
block_def_map = module.def_map(db);
&block_def_map[module.local_id]
&block_def_map[module]
} else {
// Reuse the root DefMap
&def_map[module.local_id]
&def_map[module]
};
if let Some((name, vis, declared)) = data.scope.name_of(item)
&& vis.is_visible_from(db, from)
&& vis.is_visible_from(db, ctx.from)
{
let is_pub_or_explicit = match vis {
Visibility::Module(_, VisibilityExplicitness::Explicit) => {
@ -632,7 +630,7 @@ fn find_local_import_locations(
// Descend into all modules visible from `from`.
for (module, vis) in data.scope.modules_in_scope() {
if module.krate != from.krate {
if module.krate(db) != ctx.from.krate(db) {
// We don't need to look at modules from other crates as our item has to be in the
// current crate
continue;
@ -641,7 +639,7 @@ fn find_local_import_locations(
continue;
}
if vis.is_visible_from(db, from) {
if vis.is_visible_from(db, ctx.from) {
worklist.push((module, false));
}
}
@ -694,7 +692,7 @@ mod tests {
.resolve_path(
local_def_map,
&db,
module.local_id,
module,
&mod_path,
crate::item_scope::BuiltinShadowMode::Module,
None,

View file

@ -13,11 +13,11 @@ use stdx::format_to;
use triomphe::Arc;
use crate::{
AssocItemId, AttrDefId, Complete, FxIndexMap, InternedModuleId, ModuleDefId, ModuleId, TraitId,
AssocItemId, AttrDefId, Complete, FxIndexMap, ModuleDefId, ModuleId, TraitId,
attrs::AttrFlags,
db::DefDatabase,
item_scope::{ImportOrExternCrate, ItemInNs},
nameres::{DefMap, assoc::TraitItems, crate_def_map},
nameres::{assoc::TraitItems, crate_def_map},
visibility::Visibility,
};
@ -134,7 +134,7 @@ impl ImportMap {
let mut map = FxIndexMap::default();
// We look only into modules that are public(ly reexported), starting with the crate root.
let root = def_map.module_id(DefMap::ROOT);
let root = def_map.root_module_id();
let mut worklist = vec![root];
let mut visited = FxHashSet::default();
@ -142,13 +142,11 @@ impl ImportMap {
if !visited.insert(module) {
continue;
}
let ext_def_map;
let mod_data = if module.krate == krate {
&def_map[module.local_id]
let mod_data = if module.krate(db) == krate {
&def_map[module]
} else {
// The crate might reexport a module defined in another crate.
ext_def_map = module.def_map(db);
&ext_def_map[module.local_id]
&module.def_map(db)[module]
};
let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
@ -167,9 +165,7 @@ impl ImportMap {
} else {
match item {
ItemInNs::Types(id) | ItemInNs::Values(id) => match id {
ModuleDefId::ModuleId(it) => {
Some(AttrDefId::ModuleId(InternedModuleId::new(db, it)))
}
ModuleDefId::ModuleId(it) => Some(AttrDefId::ModuleId(it)),
ModuleDefId::FunctionId(it) => Some(it.into()),
ModuleDefId::AdtId(it) => Some(it.into()),
ModuleDefId::EnumVariantId(it) => Some(it.into()),
@ -500,7 +496,7 @@ mod tests {
use expect_test::{Expect, expect};
use test_fixture::WithFixture;
use crate::{ItemContainerId, Lookup, nameres::assoc::TraitItems, test_db::TestDB};
use crate::{ItemContainerId, Lookup, ModuleIdLt, nameres::assoc::TraitItems, test_db::TestDB};
use super::*;
@ -632,17 +628,16 @@ mod tests {
expect.assert_eq(&actual)
}
fn render_path(db: &dyn DefDatabase, info: &ImportInfo) -> String {
let mut module = info.container;
fn render_path<'db>(db: &'db dyn DefDatabase, info: &ImportInfo) -> String {
let mut module: ModuleIdLt<'db> = info.container;
let mut segments = vec![&info.name];
let def_map = module.def_map(db);
assert!(def_map.block_id().is_none(), "block local items should not be in `ImportMap`");
while let Some(parent) = module.containing_module(db) {
let parent_data = &def_map[parent.local_id];
let (name, _) =
parent_data.children.iter().find(|(_, id)| **id == module.local_id).unwrap();
let parent_data = &def_map[parent];
let (name, _) = parent_data.children.iter().find(|(_, id)| **id == module).unwrap();
segments.push(name);
module = parent;
}

View file

@ -17,7 +17,7 @@ use thin_vec::ThinVec;
use crate::{
AdtId, BuiltinType, ConstId, ExternBlockId, ExternCrateId, FxIndexMap, HasModule, ImplId,
LocalModuleId, Lookup, MacroCallStyles, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
Lookup, MacroCallStyles, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
db::DefDatabase,
per_ns::{Item, MacrosItem, PerNs, TypesItem, ValuesItem},
visibility::Visibility,
@ -25,9 +25,9 @@ use crate::{
#[derive(Debug, Default)]
pub struct PerNsGlobImports {
types: FxHashSet<(LocalModuleId, Name)>,
values: FxHashSet<(LocalModuleId, Name)>,
macros: FxHashSet<(LocalModuleId, Name)>,
types: FxHashSet<(ModuleId, Name)>,
values: FxHashSet<(ModuleId, Name)>,
macros: FxHashSet<(ModuleId, Name)>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
@ -133,13 +133,13 @@ pub struct GlobId {
}
impl PerNsGlobImports {
pub(crate) fn contains_type(&self, module_id: LocalModuleId, name: Name) -> bool {
pub(crate) fn contains_type(&self, module_id: ModuleId, name: Name) -> bool {
self.types.contains(&(module_id, name))
}
pub(crate) fn contains_value(&self, module_id: LocalModuleId, name: Name) -> bool {
pub(crate) fn contains_value(&self, module_id: ModuleId, name: Name) -> bool {
self.values.contains(&(module_id, name))
}
pub(crate) fn contains_macro(&self, module_id: LocalModuleId, name: Name) -> bool {
pub(crate) fn contains_macro(&self, module_id: ModuleId, name: Name) -> bool {
self.macros.contains(&(module_id, name))
}
}
@ -261,14 +261,12 @@ impl ItemScope {
pub fn fully_resolve_import(&self, db: &dyn DefDatabase, mut import: ImportId) -> PerNs {
let mut res = PerNs::none();
let mut def_map;
let mut scope = self;
while let Some(&m) = scope.use_imports_macros.get(&ImportOrExternCrate::Import(import)) {
match m {
ImportOrDef::Import(i) => {
let module_id = i.use_.lookup(db).container;
def_map = module_id.def_map(db);
scope = &def_map[module_id.local_id].scope;
scope = &module_id.def_map(db)[module_id].scope;
import = i;
}
ImportOrDef::Def(ModuleDefId::MacroId(def)) => {
@ -283,8 +281,7 @@ impl ItemScope {
match m {
ImportOrDef::Import(i) => {
let module_id = i.use_.lookup(db).container;
def_map = module_id.def_map(db);
scope = &def_map[module_id.local_id].scope;
scope = &module_id.def_map(db)[module_id].scope;
import = i;
}
ImportOrDef::Def(def) => {
@ -299,8 +296,7 @@ impl ItemScope {
match m {
ImportOrDef::Import(i) => {
let module_id = i.use_.lookup(db).container;
def_map = module_id.def_map(db);
scope = &def_map[module_id.local_id].scope;
scope = &module_id.def_map(db)[module_id].scope;
import = i;
}
ImportOrDef::Def(def) => {
@ -578,7 +574,7 @@ impl ItemScope {
pub(crate) fn push_res_with_import(
&mut self,
glob_imports: &mut PerNsGlobImports,
lookup: (LocalModuleId, Name),
lookup: (ModuleId, Name),
def: PerNs,
import: Option<ImportOrExternCrate>,
) -> bool {
@ -922,10 +918,7 @@ impl ItemInNs {
/// Returns the crate defining this item (or `None` if `self` is built-in).
pub fn krate(&self, db: &dyn DefDatabase) -> Option<Crate> {
match self {
ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db).map(|m| m.krate),
ItemInNs::Macros(id) => Some(id.module(db).krate),
}
self.module(db).map(|module_id| module_id.krate(db))
}
pub fn module(&self, db: &dyn DefDatabase) -> Option<ModuleId> {

View file

@ -58,7 +58,7 @@ use syntax::{SyntaxKind, ast, match_ast};
use thin_vec::ThinVec;
use triomphe::Arc;
use crate::{BlockId, Lookup, db::DefDatabase};
use crate::{BlockId, db::DefDatabase};
pub(crate) use crate::item_tree::{
attrs::*,
@ -150,10 +150,10 @@ pub(crate) fn block_item_tree_query(db: &dyn DefDatabase, block: BlockId) -> Arc
let _p = tracing::info_span!("block_item_tree_query", ?block).entered();
static EMPTY: OnceLock<Arc<ItemTree>> = OnceLock::new();
let loc = block.lookup(db);
let block = loc.ast_id.to_node(db);
let ast_id = block.ast_id(db);
let block = ast_id.to_node(db);
let ctx = lower::Ctx::new(db, loc.ast_id.file_id);
let ctx = lower::Ctx::new(db, ast_id.file_id);
let mut item_tree = ctx.lower_block(&block);
let ItemTree { top_level, top_attrs, attrs, vis, big_data, small_data } = &item_tree;
if small_data.is_empty()

View file

@ -111,11 +111,12 @@ pub fn lang_items(db: &dyn DefDatabase, start_crate: Crate) -> LangItems {
// while nameres.
//
// See https://github.com/rust-lang/rust-analyzer/pull/20475 for details.
for (_, (krate, _)) in crate_local_def_map(db, start_crate).local(db).extern_prelude() {
for (_, (module, _)) in crate_local_def_map(db, start_crate).local(db).extern_prelude() {
// Some crates declares themselves as extern crate like `extern crate self as core`.
// Ignore these to prevent cycles.
if krate.krate != start_crate {
result.merge_prefer_self(lang_items(db, krate.krate));
let krate = module.krate(db);
if krate != start_crate {
result.merge_prefer_self(lang_items(db, krate));
}
}

View file

@ -71,7 +71,6 @@ use hir_expand::{
name::Name,
proc_macro::{CustomProcMacroExpander, ProcMacroKind},
};
use la_arena::Idx;
use nameres::DefMap;
use span::{AstIdNode, Edition, FileAstId, SyntaxContext};
use stdx::impl_from;
@ -412,181 +411,111 @@ pub enum MacroExpander {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ProcMacroLoc {
pub container: CrateRootModuleId,
pub container: ModuleId,
pub id: AstId<ast::Fn>,
pub expander: CustomProcMacroExpander,
pub kind: ProcMacroKind,
pub edition: Edition,
}
impl_intern!(ProcMacroId, ProcMacroLoc, intern_proc_macro, lookup_intern_proc_macro);
impl_loc!(ProcMacroLoc, id: Fn, container: CrateRootModuleId);
impl_loc!(ProcMacroLoc, id: Fn, container: ModuleId);
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct BlockLoc {
#[salsa_macros::tracked(debug)]
#[derive(PartialOrd, Ord)]
pub struct BlockIdLt<'db> {
pub ast_id: AstId<ast::BlockExpr>,
/// The containing module.
pub module: ModuleId,
pub module: ModuleIdLt<'db>,
}
impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
pub type BlockId = BlockIdLt<'static>;
/// A `ModuleId` that is always a crate's root module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CrateRootModuleId {
krate: Crate,
impl BlockIdLt<'_> {
/// # Safety
///
/// The caller must ensure that the `ModuleId` is not leaked outside of query computations.
pub unsafe fn to_static(self) -> BlockId {
unsafe { std::mem::transmute(self) }
}
}
impl CrateRootModuleId {
pub fn def_map(self, db: &dyn DefDatabase) -> &DefMap {
crate_def_map(db, self.krate)
}
pub(crate) fn local_def_map(self, db: &dyn DefDatabase) -> (&DefMap, &LocalDefMap) {
let def_map = crate_local_def_map(db, self.krate);
(def_map.def_map(db), def_map.local(db))
}
pub fn krate(self) -> Crate {
self.krate
impl BlockId {
/// # Safety
///
/// The caller must ensure that the `BlockId` comes from the given database.
pub unsafe fn to_db<'db>(self, _db: &'db dyn DefDatabase) -> BlockIdLt<'db> {
unsafe { std::mem::transmute(self) }
}
}
impl HasModule for CrateRootModuleId {
#[inline]
fn module(&self, _db: &dyn DefDatabase) -> ModuleId {
ModuleId { krate: self.krate, block: None, local_id: DefMap::ROOT }
}
#[inline]
fn krate(&self, _db: &dyn DefDatabase) -> Crate {
self.krate
}
}
impl PartialEq<ModuleId> for CrateRootModuleId {
fn eq(&self, other: &ModuleId) -> bool {
other.block.is_none() && other.local_id == DefMap::ROOT && self.krate == other.krate
}
}
impl PartialEq<CrateRootModuleId> for ModuleId {
fn eq(&self, other: &CrateRootModuleId) -> bool {
other == self
}
}
impl From<CrateRootModuleId> for ModuleId {
fn from(CrateRootModuleId { krate }: CrateRootModuleId) -> Self {
ModuleId { krate, block: None, local_id: DefMap::ROOT }
}
}
impl From<CrateRootModuleId> for ModuleDefId {
fn from(value: CrateRootModuleId) -> Self {
ModuleDefId::ModuleId(value.into())
}
}
impl From<Crate> for CrateRootModuleId {
fn from(krate: Crate) -> Self {
CrateRootModuleId { krate }
}
}
impl TryFrom<ModuleId> for CrateRootModuleId {
type Error = ();
fn try_from(ModuleId { krate, block, local_id }: ModuleId) -> Result<Self, Self::Error> {
if block.is_none() && local_id == DefMap::ROOT {
Ok(CrateRootModuleId { krate })
} else {
Err(())
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ModuleId {
krate: Crate,
#[salsa_macros::tracked(debug)]
#[derive(PartialOrd, Ord)]
pub struct ModuleIdLt<'db> {
/// The crate this module belongs to.
pub krate: Crate,
/// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
/// `BlockId` of that block expression. If `None`, this module is part of the crate-level
/// `DefMap` of `krate`.
block: Option<BlockId>,
/// The module's ID in its originating `DefMap`.
pub local_id: LocalModuleId,
pub block: Option<BlockIdLt<'db>>,
}
pub type ModuleId = ModuleIdLt<'static>;
impl ModuleId {
pub fn def_map(self, db: &dyn DefDatabase) -> &DefMap {
match self.block {
impl<'db> ModuleIdLt<'db> {
/// # Safety
///
/// The caller must ensure that the `ModuleId` is not leaked outside of query computations.
pub unsafe fn to_static(self) -> ModuleId {
unsafe { std::mem::transmute(self) }
}
pub fn def_map(self, db: &'db dyn DefDatabase) -> &'db DefMap {
match self.block(db) {
Some(block) => block_def_map(db, block),
None => crate_def_map(db, self.krate),
None => crate_def_map(db, self.krate(db)),
}
}
pub(crate) fn local_def_map(self, db: &dyn DefDatabase) -> (&DefMap, &LocalDefMap) {
match self.block {
pub(crate) fn local_def_map(self, db: &'db dyn DefDatabase) -> (&'db DefMap, &'db LocalDefMap) {
match self.block(db) {
Some(block) => (block_def_map(db, block), self.only_local_def_map(db)),
None => {
let def_map = crate_local_def_map(db, self.krate);
let def_map = crate_local_def_map(db, self.krate(db));
(def_map.def_map(db), def_map.local(db))
}
}
}
pub(crate) fn only_local_def_map(self, db: &dyn DefDatabase) -> &LocalDefMap {
crate_local_def_map(db, self.krate).local(db)
pub(crate) fn only_local_def_map(self, db: &'db dyn DefDatabase) -> &'db LocalDefMap {
crate_local_def_map(db, self.krate(db)).local(db)
}
pub fn crate_def_map(self, db: &dyn DefDatabase) -> &DefMap {
crate_def_map(db, self.krate)
pub fn crate_def_map(self, db: &'db dyn DefDatabase) -> &'db DefMap {
crate_def_map(db, self.krate(db))
}
pub fn krate(self) -> Crate {
self.krate
}
pub fn name(self, db: &dyn DefDatabase) -> Option<Name> {
pub fn name(self, db: &'db dyn DefDatabase) -> Option<Name> {
let def_map = self.def_map(db);
let parent = def_map[self.local_id].parent?;
let parent = def_map[self].parent?;
def_map[parent].children.iter().find_map(|(name, module_id)| {
if *module_id == self.local_id { Some(name.clone()) } else { None }
if *module_id == self { Some(name.clone()) } else { None }
})
}
/// Returns the module containing `self`, either the parent `mod`, or the module (or block) containing
/// the block, if `self` corresponds to a block expression.
pub fn containing_module(self, db: &dyn DefDatabase) -> Option<ModuleId> {
self.def_map(db).containing_module(self.local_id)
pub fn containing_module(self, db: &'db dyn DefDatabase) -> Option<ModuleIdLt<'db>> {
self.def_map(db).containing_module(self)
}
pub fn containing_block(self) -> Option<BlockId> {
self.block
pub fn is_block_module(self, db: &'db dyn DefDatabase) -> bool {
self.block(db).is_some() && self.def_map(db).root_module_id() == self
}
}
pub fn is_block_module(self) -> bool {
self.block.is_some() && self.local_id == DefMap::ROOT
}
pub fn is_within_block(self) -> bool {
self.block.is_some()
}
/// Returns the [`CrateRootModuleId`] for this module if it is the crate root module.
pub fn as_crate_root(&self) -> Option<CrateRootModuleId> {
if self.local_id == DefMap::ROOT && self.block.is_none() {
Some(CrateRootModuleId { krate: self.krate })
} else {
None
}
}
/// Returns the [`CrateRootModuleId`] for this module.
pub fn derive_crate_root(&self) -> CrateRootModuleId {
CrateRootModuleId { krate: self.krate }
}
/// Whether this module represents the crate root module
pub fn is_crate_root(&self) -> bool {
self.local_id == DefMap::ROOT && self.block.is_none()
impl ModuleId {
/// # Safety
///
/// The caller must ensure that the `ModuleId` comes from the given database.
pub unsafe fn to_db<'db>(self, _db: &'db dyn DefDatabase) -> ModuleIdLt<'db> {
unsafe { std::mem::transmute(self) }
}
}
@ -597,9 +526,6 @@ impl HasModule for ModuleId {
}
}
/// An ID of a module, **local** to a `DefMap`.
pub type LocalModuleId = Idx<nameres::ModuleData>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Update)]
pub struct FieldId {
// FIXME: Store this as an erased `salsa::Id` to save space
@ -682,7 +608,7 @@ pub struct LifetimeParamId {
pub local_id: LocalLifetimeParamId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa_macros::Supertype)]
pub enum ItemContainerId {
ExternBlockId(ExternBlockId),
ModuleId(ModuleId),
@ -956,16 +882,9 @@ impl CallableDefId {
}
}
// FIXME: We probably should use this in more places.
/// This is used to avoid interning the whole `AttrDefId`, so we intern just modules and not everything.
#[salsa_macros::interned(debug, no_lifetime)]
pub struct InternedModuleId {
pub loc: ModuleId,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, salsa_macros::Supertype)]
pub enum AttrDefId {
ModuleId(InternedModuleId),
ModuleId(ModuleId),
AdtId(AdtId),
FunctionId(FunctionId),
EnumVariantId(EnumVariantId),
@ -1058,7 +977,7 @@ pub trait HasModule {
#[inline]
#[doc(alias = "crate")]
fn krate(&self, db: &dyn DefDatabase) -> Crate {
self.module(db).krate
self.module(db).krate(db)
}
}
@ -1162,7 +1081,7 @@ impl HasModule for Macro2Id {
impl HasModule for ProcMacroId {
#[inline]
fn module(&self, db: &dyn DefDatabase) -> ModuleId {
self.lookup(db).container.into()
self.lookup(db).container
}
}
@ -1235,7 +1154,7 @@ impl HasModule for GenericDefId {
impl HasModule for AttrDefId {
fn module(&self, db: &dyn DefDatabase) -> ModuleId {
match self {
AttrDefId::ModuleId(it) => it.loc(db),
AttrDefId::ModuleId(it) => *it,
AttrDefId::AdtId(it) => it.module(db),
AttrDefId::FunctionId(it) => it.module(db),
AttrDefId::EnumVariantId(it) => it.module(db),

View file

@ -35,9 +35,9 @@ macro_rules! f {
};
}
struct#0:MacroRules[BE8F, 0]@58..64#14336# MyTraitMap2#0:MacroCall[BE8F, 0]@31..42#ROOT2024# {#0:MacroRules[BE8F, 0]@72..73#14336#
map#0:MacroRules[BE8F, 0]@86..89#14336#:#0:MacroRules[BE8F, 0]@89..90#14336# #0:MacroRules[BE8F, 0]@89..90#14336#::#0:MacroRules[BE8F, 0]@91..93#14336#std#0:MacroRules[BE8F, 0]@93..96#14336#::#0:MacroRules[BE8F, 0]@96..98#14336#collections#0:MacroRules[BE8F, 0]@98..109#14336#::#0:MacroRules[BE8F, 0]@109..111#14336#HashSet#0:MacroRules[BE8F, 0]@111..118#14336#<#0:MacroRules[BE8F, 0]@118..119#14336#(#0:MacroRules[BE8F, 0]@119..120#14336#)#0:MacroRules[BE8F, 0]@120..121#14336#>#0:MacroRules[BE8F, 0]@121..122#14336#,#0:MacroRules[BE8F, 0]@122..123#14336#
}#0:MacroRules[BE8F, 0]@132..133#14336#
struct#0:MacroRules[BE8F, 0]@58..64#15360# MyTraitMap2#0:MacroCall[BE8F, 0]@31..42#ROOT2024# {#0:MacroRules[BE8F, 0]@72..73#15360#
map#0:MacroRules[BE8F, 0]@86..89#15360#:#0:MacroRules[BE8F, 0]@89..90#15360# #0:MacroRules[BE8F, 0]@89..90#15360#::#0:MacroRules[BE8F, 0]@91..93#15360#std#0:MacroRules[BE8F, 0]@93..96#15360#::#0:MacroRules[BE8F, 0]@96..98#15360#collections#0:MacroRules[BE8F, 0]@98..109#15360#::#0:MacroRules[BE8F, 0]@109..111#15360#HashSet#0:MacroRules[BE8F, 0]@111..118#15360#<#0:MacroRules[BE8F, 0]@118..119#15360#(#0:MacroRules[BE8F, 0]@119..120#15360#)#0:MacroRules[BE8F, 0]@120..121#15360#>#0:MacroRules[BE8F, 0]@121..122#15360#,#0:MacroRules[BE8F, 0]@122..123#15360#
}#0:MacroRules[BE8F, 0]@132..133#15360#
"#]],
);
}
@ -197,7 +197,7 @@ macro_rules! mk_struct {
#[macro_use]
mod foo;
struct#1:MacroRules[DB0C, 0]@59..65#14336# Foo#0:MacroCall[DB0C, 0]@32..35#ROOT2024#(#1:MacroRules[DB0C, 0]@70..71#14336#u32#0:MacroCall[DB0C, 0]@41..44#ROOT2024#)#1:MacroRules[DB0C, 0]@74..75#14336#;#1:MacroRules[DB0C, 0]@75..76#14336#
struct#1:MacroRules[DB0C, 0]@59..65#15360# Foo#0:MacroCall[DB0C, 0]@32..35#ROOT2024#(#1:MacroRules[DB0C, 0]@70..71#15360#u32#0:MacroCall[DB0C, 0]@41..44#ROOT2024#)#1:MacroRules[DB0C, 0]@74..75#15360#;#1:MacroRules[DB0C, 0]@75..76#15360#
"#]],
);
}
@ -423,10 +423,10 @@ m! { foo, bar }
macro_rules! m {
($($i:ident),*) => ( impl Bar { $(fn $i() {})* } );
}
impl#\14336# Bar#\14336# {#\14336#
fn#\14336# foo#\ROOT2024#(#\14336#)#\14336# {#\14336#}#\14336#
fn#\14336# bar#\ROOT2024#(#\14336#)#\14336# {#\14336#}#\14336#
}#\14336#
impl#\15360# Bar#\15360# {#\15360#
fn#\15360# foo#\ROOT2024#(#\15360#)#\15360# {#\15360#}#\15360#
fn#\15360# bar#\ROOT2024#(#\15360#)#\15360# {#\15360#}#\15360#
}#\15360#
"#]],
);
}

View file

@ -131,8 +131,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
let db = TestDB::with_files_extra_proc_macros(ra_fixture, extra_proc_macros);
let krate = db.fetch_test_crate();
let def_map = crate_def_map(&db, krate);
let local_id = DefMap::ROOT;
let source = def_map[local_id].definition_source(&db);
let source = def_map[def_map.root].definition_source(&db);
let source_file = match source.value {
ModuleSource::SourceFile(it) => it,
ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
@ -209,7 +208,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
expanded_text.replace_range(range, &text);
}
for decl_id in def_map[local_id].scope.declarations() {
for decl_id in def_map[def_map.root].scope.declarations() {
// FIXME: I'm sure there's already better way to do this
let src = match decl_id {
ModuleDefId::AdtId(AdtId::StructId(struct_id)) => {
@ -260,7 +259,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
}
}
for impl_id in def_map[local_id].scope.impls() {
for impl_id in def_map[def_map.root].scope.impls() {
let src = impl_id.lookup(&db).source(&db);
if let Some(macro_file) = src.file_id.macro_file()
&& let MacroKind::DeriveBuiltIn | MacroKind::Derive = macro_file.kind(&db)

View file

@ -341,3 +341,22 @@ struct Foo;
#[helper_should_be_ignored] struct Foo;"#]],
);
}
#[test]
fn attribute_macro_stripping_with_cfg() {
check(
r#"
//- proc_macros: generate_suffixed_type
#[cfg(all())]
#[proc_macros::generate_suffixed_type]
struct S;
"#,
expect![[r#"
#[cfg(all())]
#[proc_macros::generate_suffixed_type]
struct S;
struct S;
struct SSuffix;"#]],
);
}

View file

@ -58,7 +58,7 @@ pub mod proc_macro;
#[cfg(test)]
mod tests;
use std::ops::Deref;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use base_db::Crate;
use hir_expand::{
@ -67,7 +67,6 @@ use hir_expand::{
};
use intern::Symbol;
use itertools::Itertools;
use la_arena::Arena;
use rustc_hash::{FxHashMap, FxHashSet};
use span::{Edition, FileAstId, FileId, ROOT_ERASED_FILE_AST_ID};
use stdx::format_to;
@ -76,8 +75,8 @@ use triomphe::Arc;
use tt::TextRange;
use crate::{
AstId, BlockId, BlockLoc, CrateRootModuleId, ExternCrateId, FunctionId, FxIndexMap,
LocalModuleId, Lookup, MacroCallStyles, MacroExpander, MacroId, ModuleId, ProcMacroId, UseId,
AstId, BlockId, BlockIdLt, ExternCrateId, FunctionId, FxIndexMap, Lookup, MacroCallStyles,
MacroExpander, MacroId, ModuleId, ModuleIdLt, ProcMacroId, UseId,
db::DefDatabase,
item_scope::{BuiltinShadowMode, ItemScope},
item_tree::TreeId,
@ -109,7 +108,7 @@ pub struct LocalDefMap {
// FIXME: There are probably some other things that could be here, but this is less severe and you
// need to be careful with things that block def maps also have.
/// The extern prelude which contains all root modules of external crates that are in scope.
extern_prelude: FxIndexMap<Name, (CrateRootModuleId, Option<ExternCrateId>)>,
extern_prelude: FxIndexMap<Name, (ModuleId, Option<ExternCrateId>)>,
}
impl std::hash::Hash for LocalDefMap {
@ -135,8 +134,7 @@ impl LocalDefMap {
pub(crate) fn extern_prelude(
&self,
) -> impl DoubleEndedIterator<Item = (&Name, (CrateRootModuleId, Option<ExternCrateId>))> + '_
{
) -> impl DoubleEndedIterator<Item = (&Name, (ModuleId, Option<ExternCrateId>))> + '_ {
self.extern_prelude.iter().map(|(name, &def)| (name, def))
}
}
@ -157,8 +155,9 @@ pub struct DefMap {
/// When this is a block def map, this will hold the block id of the block and module that
/// contains this block.
block: Option<BlockInfo>,
pub root: ModuleId,
/// The modules and their data declared in this crate.
pub modules: Arena<ModuleData>,
pub modules: ModulesMap,
/// The prelude module for this crate. This either comes from an import
/// marked with the `prelude_import` attribute, or (in the normal case) from
/// a dependency (`std` or `core`).
@ -245,33 +244,22 @@ struct BlockInfo {
/// The `BlockId` this `DefMap` was created from.
block: BlockId,
/// The containing module.
parent: BlockRelativeModuleId,
parent: ModuleId,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
struct BlockRelativeModuleId {
block: Option<BlockId>,
local_id: LocalModuleId,
}
impl BlockRelativeModuleId {
fn def_map(self, db: &dyn DefDatabase, krate: Crate) -> &DefMap {
self.into_module(krate).def_map(db)
}
fn into_module(self, krate: Crate) -> ModuleId {
ModuleId { krate, block: self.block, local_id: self.local_id }
}
fn is_block_module(self) -> bool {
self.block.is_some() && self.local_id == DefMap::ROOT
}
}
impl std::ops::Index<LocalModuleId> for DefMap {
impl std::ops::Index<ModuleIdLt<'_>> for DefMap {
type Output = ModuleData;
fn index(&self, id: LocalModuleId) -> &ModuleData {
&self.modules[id]
fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData {
self.modules
.get(&unsafe { id.to_static() })
.unwrap_or_else(|| panic!("ModuleId not found in ModulesMap {:#?}: {id:#?}", self.root))
}
}
impl std::ops::IndexMut<ModuleId> for DefMap {
fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData {
&mut self.modules[id]
}
}
@ -358,8 +346,8 @@ pub struct ModuleData {
/// Parent module in the same `DefMap`.
///
/// [`None`] for block modules because they are always its `DefMap`'s root.
pub parent: Option<LocalModuleId>,
pub children: FxIndexMap<Name, LocalModuleId>,
pub parent: Option<ModuleId>,
pub children: FxIndexMap<Name, ModuleId>,
pub scope: ItemScope,
}
@ -392,11 +380,19 @@ pub(crate) fn crate_local_def_map(db: &dyn DefDatabase, crate_id: Crate) -> DefM
.entered();
let root_file_id = crate_id.root_file_id(db);
let module_data =
ModuleData::new(ModuleOrigin::CrateRoot { definition: root_file_id }, Visibility::Public);
let module_data = ModuleData::new(
ModuleOrigin::CrateRoot { definition: root_file_id },
Visibility::Public,
None,
);
let def_map =
DefMap::empty(crate_id, Arc::new(DefMapCrateData::new(krate.edition)), module_data, None);
let def_map = DefMap::empty(
db,
crate_id,
Arc::new(DefMapCrateData::new(krate.edition)),
module_data,
None,
);
let (def_map, local_def_map) =
collector::collect_defs(db, def_map, TreeId::new(root_file_id.into(), None), None);
@ -404,25 +400,23 @@ pub(crate) fn crate_local_def_map(db: &dyn DefDatabase, crate_id: Crate) -> DefM
}
#[salsa_macros::tracked(returns(ref))]
pub fn block_def_map(db: &dyn DefDatabase, block_id: BlockId) -> DefMap {
let BlockLoc { ast_id, module } = block_id.lookup(db);
pub fn block_def_map<'db>(db: &'db dyn DefDatabase, block_id: BlockIdLt<'db>) -> DefMap {
let block_id = unsafe { block_id.to_static() };
let ast_id = block_id.ast_id(db);
let module = unsafe { block_id.module(db).to_static() };
let visibility = Visibility::Module(
ModuleId { krate: module.krate, local_id: DefMap::ROOT, block: module.block },
VisibilityExplicitness::Implicit,
);
let visibility = Visibility::Module(module, VisibilityExplicitness::Implicit);
let module_data =
ModuleData::new(ModuleOrigin::BlockExpr { block: ast_id, id: block_id }, visibility);
ModuleData::new(ModuleOrigin::BlockExpr { block: ast_id, id: block_id }, visibility, None);
let local_def_map = crate_local_def_map(db, module.krate);
let krate = module.krate(db);
let local_def_map = crate_local_def_map(db, krate);
let def_map = DefMap::empty(
module.krate,
db,
krate,
local_def_map.def_map(db).data.clone(),
module_data,
Some(BlockInfo {
block: block_id,
parent: BlockRelativeModuleId { block: module.block, local_id: module.local_id },
}),
Some(BlockInfo { block: block_id, parent: module }),
);
let (def_map, _) = collector::collect_defs(
@ -435,25 +429,24 @@ pub fn block_def_map(db: &dyn DefDatabase, block_id: BlockId) -> DefMap {
}
impl DefMap {
/// The module id of a crate or block root.
pub const ROOT: LocalModuleId = LocalModuleId::from_raw(la_arena::RawIdx::from_u32(0));
pub fn edition(&self) -> Edition {
self.data.edition
}
fn empty(
db: &dyn DefDatabase,
krate: Crate,
crate_data: Arc<DefMapCrateData>,
module_data: ModuleData,
block: Option<BlockInfo>,
) -> DefMap {
let mut modules: Arena<ModuleData> = Arena::default();
let root = modules.alloc(module_data);
assert_eq!(root, Self::ROOT);
let mut modules = ModulesMap::new();
let root = unsafe { ModuleIdLt::new(db, krate, block.map(|it| it.block)).to_static() };
modules.insert(root, module_data);
DefMap {
block,
root,
modules,
krate,
prelude: None,
@ -471,6 +464,7 @@ impl DefMap {
diagnostics,
modules,
derive_helpers_in_scope,
root: _,
block: _,
krate: _,
prelude: _,
@ -495,7 +489,7 @@ impl DefMap {
&'a self,
db: &'a dyn DefDatabase,
file_id: FileId,
) -> impl Iterator<Item = LocalModuleId> + 'a {
) -> impl Iterator<Item = ModuleId> + 'a {
self.modules
.iter()
.filter(move |(_id, data)| {
@ -504,7 +498,7 @@ impl DefMap {
.map(|(id, _data)| id)
}
pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
pub fn modules(&self) -> impl Iterator<Item = (ModuleId, &ModuleData)> + '_ {
self.modules.iter()
}
@ -543,40 +537,32 @@ impl DefMap {
self.krate
}
pub fn module_id(&self, local_id: LocalModuleId) -> ModuleId {
let block = self.block.map(|b| b.block);
ModuleId { krate: self.krate, local_id, block }
}
pub fn crate_root(&self) -> CrateRootModuleId {
CrateRootModuleId { krate: self.krate }
#[inline]
pub fn crate_root(&self, db: &dyn DefDatabase) -> ModuleId {
match self.block {
Some(_) => crate_def_map(db, self.krate()).root,
None => self.root,
}
}
/// This is the same as [`Self::crate_root`] for crate def maps, but for block def maps, it
/// returns the root block module.
pub fn root_module_id(&self) -> ModuleId {
self.module_id(Self::ROOT)
self.root
}
/// If this `DefMap` is for a block expression, returns the module containing the block (which
/// might again be a block, or a module inside a block).
pub fn parent(&self) -> Option<ModuleId> {
let BlockRelativeModuleId { block, local_id } = self.block?.parent;
Some(ModuleId { krate: self.krate, block, local_id })
Some(self.block?.parent)
}
/// Returns the module containing `local_mod`, either the parent `mod`, or the module (or block) containing
/// the block, if `self` corresponds to a block expression.
pub fn containing_module(&self, local_mod: LocalModuleId) -> Option<ModuleId> {
pub fn containing_module(&self, local_mod: ModuleIdLt<'_>) -> Option<ModuleId> {
match self[local_mod].parent {
Some(parent) => Some(self.module_id(parent)),
None => {
self.block.map(
|BlockInfo { parent: BlockRelativeModuleId { block, local_id }, .. }| {
ModuleId { krate: self.krate, block, local_id }
},
)
}
Some(parent) => Some(parent),
None => self.block.map(|BlockInfo { parent, .. }| parent),
}
}
@ -594,30 +580,21 @@ impl DefMap {
// even), as this should be a great debugging aid.
pub fn dump(&self, db: &dyn DefDatabase) -> String {
let mut buf = String::new();
let mut arc;
let mut current_map = self;
while let Some(block) = current_map.block {
go(&mut buf, db, current_map, "(block scope)", Self::ROOT);
go(&mut buf, db, current_map, "(block scope)", current_map.root);
buf.push('\n');
arc = block.parent.def_map(db, self.krate);
current_map = arc;
current_map = block.parent.def_map(db);
}
go(&mut buf, db, current_map, "crate", Self::ROOT);
go(&mut buf, db, current_map, "crate", current_map.root);
return buf;
fn go(
buf: &mut String,
db: &dyn DefDatabase,
map: &DefMap,
path: &str,
module: LocalModuleId,
) {
fn go(buf: &mut String, db: &dyn DefDatabase, map: &DefMap, path: &str, module: ModuleId) {
format_to!(buf, "{}\n", path);
map.modules[module].scope.dump(db, buf);
map[module].scope.dump(db, buf);
for (name, child) in
map.modules[module].children.iter().sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
for (name, child) in map[module].children.iter().sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
{
let path = format!("{path}::{}", name.display(db, Edition::LATEST));
buf.push('\n');
@ -625,20 +602,6 @@ impl DefMap {
}
}
}
pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
let mut buf = String::new();
let mut arc;
let mut current_map = self;
while let Some(block) = current_map.block {
format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
arc = block.parent.def_map(db, self.krate);
current_map = arc;
}
format_to!(buf, "crate scope\n");
buf
}
}
impl DefMap {
@ -658,7 +621,7 @@ impl DefMap {
&self,
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
original_module: LocalModuleId,
original_module: ModuleId,
path: &ModPath,
shadow: BuiltinShadowMode,
expected_macro_subns: Option<MacroSubNs>,
@ -681,7 +644,7 @@ impl DefMap {
&self,
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
original_module: LocalModuleId,
original_module: ModuleId,
path: &ModPath,
shadow: BuiltinShadowMode,
) -> (PerNs, Option<usize>, ResolvePathResultPrefixInfo) {
@ -701,19 +664,19 @@ impl DefMap {
///
/// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
/// `None`, iteration continues.
pub(crate) fn with_ancestor_maps<T>(
pub(crate) fn with_ancestor_maps<'db, T>(
&self,
db: &dyn DefDatabase,
local_mod: LocalModuleId,
f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
db: &'db dyn DefDatabase,
local_mod: ModuleIdLt<'db>,
f: &mut dyn FnMut(&DefMap, ModuleIdLt<'db>) -> Option<T>,
) -> Option<T> {
if let Some(it) = f(self, local_mod) {
return Some(it);
}
let mut block = self.block;
while let Some(block_info) = block {
let parent = block_info.parent.def_map(db, self.krate);
if let Some(it) = f(parent, block_info.parent.local_id) {
let parent = block_info.parent.def_map(db);
if let Some(it) = f(parent, block_info.parent) {
return Some(it);
}
block = parent.block;
@ -724,11 +687,15 @@ impl DefMap {
}
impl ModuleData {
pub(crate) fn new(origin: ModuleOrigin, visibility: Visibility) -> Self {
pub(crate) fn new(
origin: ModuleOrigin,
visibility: Visibility,
parent: Option<ModuleId>,
) -> Self {
ModuleData {
origin,
visibility,
parent: None,
parent,
children: Default::default(),
scope: ItemScope::default(),
}
@ -852,3 +819,55 @@ fn sub_namespace_match(
None => true,
}
}
/// A newtype wrapper around `FxHashMap<ModuleId, ModuleData>` that implements `IndexMut`.
#[derive(Debug, PartialEq, Eq)]
pub struct ModulesMap {
inner: FxIndexMap<ModuleId, ModuleData>,
}
impl ModulesMap {
fn new() -> Self {
Self { inner: FxIndexMap::default() }
}
fn iter(&self) -> impl Iterator<Item = (ModuleId, &ModuleData)> + '_ {
self.inner.iter().map(|(&k, v)| (k, v))
}
fn iter_mut(&mut self) -> impl Iterator<Item = (ModuleId, &mut ModuleData)> + '_ {
self.inner.iter_mut().map(|(&k, v)| (k, v))
}
}
impl Deref for ModulesMap {
type Target = FxIndexMap<ModuleId, ModuleData>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for ModulesMap {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl Index<ModuleIdLt<'_>> for ModulesMap {
type Output = ModuleData;
fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData {
self.inner
.get(&unsafe { id.to_static() })
.unwrap_or_else(|| panic!("ModuleId not found in ModulesMap: {id:#?}"))
}
}
impl IndexMut<ModuleId> for ModulesMap {
fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData {
self.inner
.get_mut(&id)
.unwrap_or_else(|| panic!("ModuleId not found in ModulesMap: {id:#?}"))
}
}

View file

@ -165,7 +165,7 @@ impl<'a> AssocItemCollector<'a> {
local_def_map,
ast_id_map: db.ast_id_map(file_id),
span_map: db.span_map(file_id),
cfg_options: module_id.krate.cfg_options(db),
cfg_options: module_id.krate(db).cfg_options(db),
file_id,
container,
items: Vec::new(),
@ -197,7 +197,7 @@ impl<'a> AssocItemCollector<'a> {
AttrsOrCfg::Enabled { attrs } => attrs,
AttrsOrCfg::CfgDisabled(cfg) => {
self.diagnostics.push(DefDiagnostic::unconfigured_code(
self.module_id.local_id,
self.module_id,
InFile::new(self.file_id, ast_id.erase()),
cfg.0,
self.cfg_options.clone(),
@ -213,7 +213,7 @@ impl<'a> AssocItemCollector<'a> {
match self.def_map.resolve_attr_macro(
self.local_def_map,
self.db,
self.module_id.local_id,
self.module_id,
ast_id_with_path,
attr,
attr_id,
@ -226,9 +226,9 @@ impl<'a> AssocItemCollector<'a> {
// crate failed), skip expansion like we would if it was
// disabled. This is analogous to the handling in
// `DefCollector::collect_macros`.
if let Some(err) = exp.as_expand_error(self.module_id.krate) {
if let Some(err) = exp.as_expand_error(self.module_id.krate(self.db)) {
self.diagnostics.push(DefDiagnostic::macro_error(
self.module_id.local_id,
self.module_id,
ast_id,
(*attr.path).clone(),
err,
@ -244,7 +244,7 @@ impl<'a> AssocItemCollector<'a> {
Ok(_) => (),
Err(_) => {
self.diagnostics.push(DefDiagnostic::unresolved_macro_call(
self.module_id.local_id,
self.module_id,
MacroCallKind::Attr {
ast_id,
attr_args: None,
@ -307,7 +307,7 @@ impl<'a> AssocItemCollector<'a> {
.resolve_path(
self.local_def_map,
self.db,
self.module_id.local_id,
self.module_id,
path,
crate::item_scope::BuiltinShadowMode::Other,
Some(MacroSubNs::Bang),
@ -322,7 +322,7 @@ impl<'a> AssocItemCollector<'a> {
&path,
ctxt,
ExpandTo::Items,
self.module_id.krate(),
self.module_id.krate(self.db),
resolver,
&mut |ptr, call_id| {
self.macro_calls.push((ptr.map(|(_, it)| it.upcast()), call_id))
@ -338,7 +338,7 @@ impl<'a> AssocItemCollector<'a> {
},
Err(_) => {
self.diagnostics.push(DefDiagnostic::unresolved_macro_call(
self.module_id.local_id,
self.module_id,
MacroCallKind::FnLike {
ast_id,
expand_to: ExpandTo::Items,

View file

@ -12,7 +12,7 @@ use syntax::ast;
use triomphe::Arc;
use crate::{
AstIdWithPath, LocalModuleId, MacroId, UnresolvedMacro,
AstIdWithPath, MacroId, ModuleId, UnresolvedMacro,
db::DefDatabase,
item_scope::BuiltinShadowMode,
nameres::{LocalDefMap, path_resolution::ResolveMode},
@ -33,7 +33,7 @@ impl DefMap {
&self,
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
original_module: LocalModuleId,
original_module: ModuleId,
ast_id: AstIdWithPath<ast::Item>,
attr: &Attr,
attr_id: AttrId,

View file

@ -3,7 +3,7 @@
//! `DefCollector::collect` contains the fixed-point iteration loop which
//! resolves imports and expands macros.
use std::{cmp::Ordering, iter, mem};
use std::{iter, mem};
use base_db::{BuiltDependency, Crate, CrateOrigin, LangCrateOrigin};
use cfg::{CfgAtom, CfgExpr, CfgOptions};
@ -27,12 +27,11 @@ use syntax::ast;
use triomphe::Arc;
use crate::{
AdtId, AssocItemId, AstId, AstIdWithPath, ConstLoc, CrateRootModuleId, EnumLoc, ExternBlockLoc,
ExternCrateId, ExternCrateLoc, FunctionId, FunctionLoc, FxIndexMap, ImplLoc, Intern,
ItemContainerId, LocalModuleId, Lookup, Macro2Id, Macro2Loc, MacroExpander, MacroId,
MacroRulesId, MacroRulesLoc, MacroRulesLocFlags, ModuleDefId, ModuleId, ProcMacroId,
ProcMacroLoc, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc, UnresolvedMacro, UseId,
UseLoc,
AdtId, AssocItemId, AstId, AstIdWithPath, ConstLoc, EnumLoc, ExternBlockLoc, ExternCrateId,
ExternCrateLoc, FunctionId, FunctionLoc, FxIndexMap, ImplLoc, Intern, ItemContainerId, Lookup,
Macro2Id, Macro2Loc, MacroExpander, MacroId, MacroRulesId, MacroRulesLoc, MacroRulesLocFlags,
ModuleDefId, ModuleId, ProcMacroId, ProcMacroLoc, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc,
UnionLoc, UnresolvedMacro, UseId, UseLoc,
db::DefDatabase,
item_scope::{GlobId, ImportId, ImportOrExternCrate, PerNsGlobImports},
item_tree::{
@ -177,14 +176,14 @@ impl Import {
#[derive(Debug, Eq, PartialEq)]
struct ImportDirective {
/// The module this import directive is in.
module_id: LocalModuleId,
module_id: ModuleId,
import: Import,
status: PartialResolvedImport,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct MacroDirective<'db> {
module_id: LocalModuleId,
module_id: ModuleId,
depth: usize,
kind: MacroDirectiveKind<'db>,
container: ItemContainerId,
@ -224,7 +223,7 @@ struct DefCollector<'db> {
crate_local_def_map: Option<&'db LocalDefMap>,
// The dependencies of the current crate, including optional deps like `test`.
deps: FxIndexMap<Name, BuiltDependency>,
glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility, GlobId)>>,
glob_imports: FxHashMap<ModuleId, Vec<(ModuleId, Visibility, GlobId)>>,
unresolved_imports: Vec<ImportDirective>,
indeterminate_imports: Vec<(ImportDirective, PerNs)>,
unresolved_macros: Vec<MacroDirective<'db>>,
@ -232,7 +231,7 @@ struct DefCollector<'db> {
// resolve. When we emit diagnostics for unresolved imports, we only do so if the import
// doesn't start with an unresolved crate's name.
unresolved_extern_crates: FxHashSet<Name>,
mod_dirs: FxHashMap<LocalModuleId, ModDir>,
mod_dirs: FxHashMap<ModuleId, ModDir>,
cfg_options: &'db CfgOptions,
/// List of procedural macros defined by this crate. This is read from the dynamic library
/// built by the build system, and is the list of proc-macros we can actually expand. It is
@ -337,9 +336,14 @@ impl<'db> DefCollector<'db> {
continue;
}
self.local_def_map
.extern_prelude
.insert(name.clone(), (CrateRootModuleId { krate: dep.crate_id }, None));
// This eagerly draws a dependency edge between the crate def maps even if the
// things the crates are not used. This is not great, but at the same time we would
// like to compute our dependency def maps in parallel here anyways in the future
// which will have the same effect.
self.local_def_map.extern_prelude.insert(
name.clone(),
(crate_def_map(self.db, dep.crate_id).root_module_id(), None),
);
}
}
@ -349,10 +353,11 @@ impl<'db> DefCollector<'db> {
return;
}
let module_id = self.def_map.root;
ModCollector {
def_collector: self,
macro_depth: 0,
module_id: DefMap::ROOT,
module_id,
tree_id: TreeId::new(file_id.into(), None),
item_tree,
mod_dir: ModDir::root(),
@ -367,10 +372,11 @@ impl<'db> DefCollector<'db> {
if is_cfg_enabled {
self.inject_prelude();
let module_id = self.def_map.root;
ModCollector {
def_collector: self,
macro_depth: 0,
module_id: DefMap::ROOT,
module_id,
tree_id,
item_tree,
mod_dir: ModDir::root(),
@ -433,7 +439,8 @@ impl<'db> DefCollector<'db> {
// Additionally, while the proc macro entry points must be `pub`, they are not publicly
// exported in type/value namespace. This function reduces the visibility of all items
// in the crate root that aren't proc macros.
let root = &mut self.def_map.modules[DefMap::ROOT];
let module_id = self.def_map.root_module_id();
let root = &mut self.def_map.modules[module_id];
root.scope.censor_non_proc_macros(self.def_map.krate);
}
}
@ -537,7 +544,7 @@ impl<'db> DefCollector<'db> {
let (per_ns, _) = self.def_map.resolve_path(
self.crate_local_def_map.unwrap_or(&self.local_def_map),
self.db,
DefMap::ROOT,
self.def_map.root_module_id(),
&path,
BuiltinShadowMode::Other,
None,
@ -592,7 +599,7 @@ impl<'db> DefCollector<'db> {
};
let proc_macro_id = ProcMacroLoc {
container: self.def_map.crate_root(),
container: self.def_map.root_module_id(),
id: ast_id,
expander,
kind,
@ -636,7 +643,7 @@ impl<'db> DefCollector<'db> {
/// ```
fn define_macro_rules(
&mut self,
module_id: LocalModuleId,
module_id: ModuleId,
name: Name,
macro_: MacroRulesId,
export: bool,
@ -648,7 +655,7 @@ impl<'db> DefCollector<'db> {
// In Rust, `#[macro_export]` macros are unconditionally visible at the
// crate root, even if the parent modules is **not** visible.
if export {
let module_id = DefMap::ROOT;
let module_id = self.def_map.root;
self.def_map.modules[module_id].scope.declare(macro_.into());
self.update(
module_id,
@ -666,7 +673,7 @@ impl<'db> DefCollector<'db> {
/// the definition of current module.
/// And also, `macro_use` on a module will import all legacy macros visible inside to
/// current legacy scope, with possible shadowing.
fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, mac: MacroId) {
fn define_legacy_macro(&mut self, module_id: ModuleId, name: Name, mac: MacroId) {
// Always shadowing
self.def_map.modules[module_id].scope.define_legacy_macro(name, mac);
}
@ -676,7 +683,7 @@ impl<'db> DefCollector<'db> {
/// The scoped of macro 2.0 macro is equal to normal function
fn define_macro_def(
&mut self,
module_id: LocalModuleId,
module_id: ModuleId,
name: Name,
macro_: Macro2Id,
vis: &RawVisibility,
@ -705,7 +712,7 @@ impl<'db> DefCollector<'db> {
/// A proc macro is similar to normal macro scope, but it would not visible in legacy textual scoped.
/// And unconditionally exported.
fn define_proc_macro(&mut self, name: Name, macro_: ProcMacroId) {
let module_id = DefMap::ROOT;
let module_id = self.def_map.root;
self.def_map.modules[module_id].scope.declare(macro_.into());
self.update(
module_id,
@ -730,7 +737,7 @@ impl<'db> DefCollector<'db> {
let def_map = crate_def_map(self.db, krate);
// `#[macro_use]` brings macros into macro_use prelude. Yes, even non-`macro_rules!`
// macros.
let root_scope = &def_map[DefMap::ROOT].scope;
let root_scope = &def_map[def_map.root].scope;
match names {
Some(names) => {
for name in names {
@ -803,7 +810,7 @@ impl<'db> DefCollector<'db> {
res
}
fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
fn resolve_import(&self, module_id: ModuleId, import: &Import) -> PartialResolvedImport {
let _p = tracing::info_span!("resolve_import", import_path = %import.path.display(self.db, Edition::LATEST))
.entered();
tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.data.edition);
@ -916,11 +923,10 @@ impl<'db> DefCollector<'db> {
// implementation seems to work the same though.
cov_mark::hit!(std_prelude);
self.def_map.prelude = Some((m, Some(id)));
} else if m.krate != self.def_map.krate {
} else if m.krate(self.db) != self.def_map.krate {
cov_mark::hit!(glob_across_crates);
// glob import from other crate => we can just import everything once
let item_map = m.def_map(self.db);
let scope = &item_map[m.local_id].scope;
let scope = &m.def_map(self.db)[m].scope;
// Module scoped macros is included
let items = scope
@ -942,12 +948,10 @@ impl<'db> DefCollector<'db> {
// glob import from same crate => we do an initial
// import, and then need to propagate any further
// additions
let def_map;
let scope = if m.block == self.def_map.block_id() {
&self.def_map[m.local_id].scope
let scope = if m.block(self.db) == self.def_map.block_id() {
&self.def_map[m].scope
} else {
def_map = m.def_map(self.db);
&def_map[m.local_id].scope
&m.def_map(self.db)[m].scope
};
// Module scoped macros is included
@ -976,11 +980,12 @@ impl<'db> DefCollector<'db> {
Some(ImportOrExternCrate::Glob(glob)),
);
// record the glob import in case we add further items
let glob_imports = self.glob_imports.entry(m.local_id).or_default();
let glob_imports = self.glob_imports.entry(m).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) {
if let Some(new_vis) = old_vis.max(self.db, vis, &self.def_map)
{
*old_vis = new_vis;
}
}
@ -1056,20 +1061,19 @@ impl<'db> DefCollector<'db> {
fn update(
&mut self,
// The module for which `resolutions` have been resolve
module_id: LocalModuleId,
module_id: ModuleId,
resolutions: &[(Option<Name>, PerNs)],
// Visibility this import will have
vis: Visibility,
import: Option<ImportOrExternCrate>,
) {
self.db.unwind_if_revision_cancelled();
self.update_recursive(module_id, resolutions, vis, import, 0)
}
fn update_recursive(
&mut self,
// The module for which `resolutions` have been resolved.
module_id: LocalModuleId,
module_id: ModuleId,
resolutions: &[(Option<Name>, PerNs)],
// All resolutions are imported with this visibility; the visibilities in
// the `PerNs` values are ignored and overwritten
@ -1104,7 +1108,7 @@ impl<'db> DefCollector<'db> {
let should_update = match old_vis {
None => true,
Some(old_vis) => {
let max_vis = old_vis.max(vis, &self.def_map).unwrap_or_else(|| {
let max_vis = old_vis.max(self.db, vis, &self.def_map).unwrap_or_else(|| {
panic!("`Tr as _` imports with unrelated visibilities {old_vis:?} and {vis:?} (trait {tr:?})");
});
@ -1146,7 +1150,7 @@ impl<'db> DefCollector<'db> {
.collect::<Vec<_>>();
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);
let vis = glob_import_vis.min(self.db, vis, &self.def_map).unwrap_or(glob_import_vis);
self.update_recursive(
glob_importing_module,
resolutions,
@ -1159,20 +1163,20 @@ impl<'db> DefCollector<'db> {
fn push_res_and_update_glob_vis(
&mut self,
module_id: LocalModuleId,
module_id: ModuleId,
name: &Name,
mut defs: PerNs,
vis: Visibility,
def_import_type: Option<ImportOrExternCrate>,
) -> bool {
if let Some(def) = defs.types.as_mut() {
def.vis = def.vis.min(vis, &self.def_map).unwrap_or(vis);
def.vis = def.vis.min(self.db, vis, &self.def_map).unwrap_or(vis);
}
if let Some(def) = defs.values.as_mut() {
def.vis = def.vis.min(vis, &self.def_map).unwrap_or(vis);
def.vis = def.vis.min(self.db, vis, &self.def_map).unwrap_or(vis);
}
if let Some(def) = defs.macros.as_mut() {
def.vis = def.vis.min(vis, &self.def_map).unwrap_or(vis);
def.vis = def.vis.min(self.db, vis, &self.def_map).unwrap_or(vis);
}
let mut changed = false;
@ -1188,7 +1192,7 @@ impl<'db> DefCollector<'db> {
&& def.def == prev_def.def
&& self.from_glob_import.contains_type(module_id, name.clone())
&& def.vis != prev_def.vis
&& def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis)
&& def.vis.max(self.db, prev_def.vis, &self.def_map) == Some(def.vis)
{
changed = true;
// This import is being handled here, don't pass it down to
@ -1202,7 +1206,7 @@ impl<'db> DefCollector<'db> {
&& def.def == prev_def.def
&& self.from_glob_import.contains_value(module_id, name.clone())
&& def.vis != prev_def.vis
&& def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis)
&& def.vis.max(self.db, prev_def.vis, &self.def_map) == Some(def.vis)
{
changed = true;
// See comment above.
@ -1215,7 +1219,7 @@ impl<'db> DefCollector<'db> {
&& def.def == prev_def.def
&& self.from_glob_import.contains_macro(module_id, name.clone())
&& def.vis != prev_def.vis
&& def.vis.max(prev_def.vis, &self.def_map) == Some(def.vis)
&& def.vis.max(self.db, prev_def.vis, &self.def_map) == Some(def.vis)
{
changed = true;
// See comment above.
@ -1555,7 +1559,7 @@ impl<'db> DefCollector<'db> {
fn collect_macro_expansion(
&mut self,
module_id: LocalModuleId,
module_id: ModuleId,
macro_call_id: MacroCallId,
depth: usize,
container: ItemContainerId,
@ -1713,7 +1717,7 @@ impl<'db> DefCollector<'db> {
struct ModCollector<'a, 'db> {
def_collector: &'a mut DefCollector<'db>,
macro_depth: usize,
module_id: LocalModuleId,
module_id: ModuleId,
tree_id: TreeId,
item_tree: &'db ItemTree,
mod_dir: ModDir,
@ -1721,14 +1725,13 @@ struct ModCollector<'a, 'db> {
impl ModCollector<'_, '_> {
fn collect_in_top_module(&mut self, items: &[ModItemId]) {
let module = self.def_collector.def_map.module_id(self.module_id);
self.collect(items, module.into())
self.collect(items, self.module_id.into())
}
fn collect(&mut self, items: &[ModItemId], container: ItemContainerId) {
let krate = self.def_collector.def_map.krate;
let is_crate_root =
self.module_id == DefMap::ROOT && self.def_collector.def_map.block.is_none();
let is_crate_root = self.module_id == self.def_collector.def_map.root
&& self.def_collector.def_map.block.is_none();
// Note: don't assert that inserted value is fresh: it's simply not true
// for macros.
@ -1737,10 +1740,10 @@ impl ModCollector<'_, '_> {
// Prelude module is always considered to be `#[macro_use]`.
if let Some((prelude_module, _use)) = self.def_collector.def_map.prelude {
// Don't insert macros from the prelude into blocks, as they can be shadowed by other macros.
if prelude_module.krate != krate && is_crate_root {
if is_crate_root && prelude_module.krate(self.def_collector.db) != krate {
cov_mark::hit!(prelude_is_macro_use);
self.def_collector.import_macros_from_extern_crate(
prelude_module.krate,
prelude_module.krate(self.def_collector.db),
None,
None,
);
@ -1781,7 +1784,6 @@ impl ModCollector<'_, '_> {
return;
}
let module = self.def_collector.def_map.module_id(module_id);
let def_map = &mut self.def_collector.def_map;
let local_def_map =
self.def_collector.crate_local_def_map.unwrap_or(&self.def_collector.local_def_map);
@ -1789,9 +1791,11 @@ impl ModCollector<'_, '_> {
match item {
ModItemId::Mod(m) => self.collect_module(m, attrs),
ModItemId::Use(item_tree_id) => {
let id =
UseLoc { container: module, id: InFile::new(self.file_id(), item_tree_id) }
.intern(db);
let id = UseLoc {
container: module_id,
id: InFile::new(self.file_id(), item_tree_id),
}
.intern(db);
let is_prelude = attrs.by_key(sym::prelude_import).exists();
Import::from_use(self.item_tree, item_tree_id, id, is_prelude, |import| {
self.def_collector.unresolved_imports.push(ImportDirective {
@ -1806,7 +1810,7 @@ impl ModCollector<'_, '_> {
&self.item_tree[item_tree_id];
let id = ExternCrateLoc {
container: module,
container: module_id,
id: InFile::new(self.tree_id.file_id(), item_tree_id),
}
.intern(db);
@ -1815,12 +1819,12 @@ impl ModCollector<'_, '_> {
let is_self = *name == sym::self_;
let resolved = if is_self {
cov_mark::hit!(extern_crate_self_as);
Some(def_map.crate_root())
Some(def_map.crate_root(db))
} else {
self.def_collector
.deps
.get(name)
.map(|dep| CrateRootModuleId { krate: dep.crate_id })
.map(|dep| crate_def_map(db, dep.crate_id).root_module_id())
};
let name = match alias {
@ -1845,7 +1849,7 @@ impl ModCollector<'_, '_> {
self.process_macro_use_extern_crate(
id,
attrs.by_key(sym::macro_use).attrs(),
resolved.krate,
resolved.krate(self.def_collector.db),
);
}
}
@ -1877,7 +1881,7 @@ impl ModCollector<'_, '_> {
}
ModItemId::ExternBlock(block) => {
let extern_block_id = ExternBlockLoc {
container: module,
container: module_id,
id: InFile::new(self.file_id(), block),
}
.intern(db);
@ -1890,11 +1894,11 @@ impl ModCollector<'_, '_> {
)
}
ModItemId::MacroCall(mac) => self.collect_macro_call(mac, container),
ModItemId::MacroRules(id) => self.collect_macro_rules(id, module),
ModItemId::Macro2(id) => self.collect_macro_def(id, module),
ModItemId::MacroRules(id) => self.collect_macro_rules(id, module_id),
ModItemId::Macro2(id) => self.collect_macro_def(id, module_id),
ModItemId::Impl(imp) => {
let impl_id =
ImplLoc { container: module, id: InFile::new(self.file_id(), imp) }
ImplLoc { container: module_id, id: InFile::new(self.file_id(), imp) }
.intern(db);
self.def_collector.def_map.modules[self.module_id].scope.define_impl(impl_id)
}
@ -1908,7 +1912,7 @@ impl ModCollector<'_, '_> {
if self.def_collector.def_map.block.is_none()
&& self.def_collector.is_proc_macro
&& self.module_id == DefMap::ROOT
&& self.module_id == self.def_collector.def_map.root
&& let Some(proc_macro) = attrs.parse_proc_macro_decl(&it.name)
{
self.def_collector.export_proc_macro(
@ -1926,7 +1930,7 @@ impl ModCollector<'_, '_> {
let vis = resolve_vis(def_map, local_def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
StructLoc { container: module, id: InFile::new(self.file_id(), id) }
StructLoc { container: module_id, id: InFile::new(self.file_id(), id) }
.intern(db)
.into(),
&it.name,
@ -1940,7 +1944,7 @@ impl ModCollector<'_, '_> {
let vis = resolve_vis(def_map, local_def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
UnionLoc { container: module, id: InFile::new(self.file_id(), id) }
UnionLoc { container: module_id, id: InFile::new(self.file_id(), id) }
.intern(db)
.into(),
&it.name,
@ -1950,9 +1954,11 @@ impl ModCollector<'_, '_> {
}
ModItemId::Enum(id) => {
let it = &self.item_tree[id];
let enum_ =
EnumLoc { container: module, id: InFile::new(self.tree_id.file_id(), id) }
.intern(db);
let enum_ = EnumLoc {
container: module_id,
id: InFile::new(self.tree_id.file_id(), id),
}
.intern(db);
let vis = resolve_vis(def_map, local_def_map, &self.item_tree[it.visibility]);
update_def(self.def_collector, enum_.into(), &it.name, vis, false);
@ -1997,7 +2003,7 @@ impl ModCollector<'_, '_> {
let vis = resolve_vis(def_map, local_def_map, &self.item_tree[it.visibility]);
update_def(
self.def_collector,
TraitLoc { container: module, id: InFile::new(self.file_id(), id) }
TraitLoc { container: module_id, id: InFile::new(self.file_id(), id) }
.intern(db)
.into(),
&it.name,
@ -2172,9 +2178,10 @@ impl ModCollector<'_, '_> {
declaration: FileAstId<ast::Module>,
definition: Option<(EditionedFileId, bool)>,
visibility: &crate::visibility::RawVisibility,
) -> LocalModuleId {
let def_map = &mut self.def_collector.def_map;
let vis = def_map
) -> ModuleId {
let vis = self
.def_collector
.def_map
.resolve_visibility(
self.def_collector.crate_local_def_map.unwrap_or(&self.def_collector.local_def_map),
self.def_collector.db,
@ -2195,21 +2202,25 @@ impl ModCollector<'_, '_> {
},
};
let module = unsafe {
crate::ModuleIdLt::new(
self.def_collector.db,
self.def_collector.def_map.krate,
self.def_collector.def_map.block_id(),
)
.to_static()
};
let def_map = &mut self.def_collector.def_map;
let modules = &mut def_map.modules;
let res = modules.alloc(ModuleData::new(origin, vis));
modules[res].parent = Some(self.module_id);
if let Some((target, source)) = Self::borrow_modules(modules.as_mut(), res, self.module_id)
{
for (name, macs) in source.scope.legacy_macros() {
for &mac in macs {
target.scope.define_legacy_macro(name.clone(), mac);
}
let mut data = ModuleData::new(origin, vis, Some(self.module_id));
for (name, macs) in modules[self.module_id].scope.legacy_macros() {
for &mac in macs {
data.scope.define_legacy_macro(name.clone(), mac);
}
}
modules[self.module_id].children.insert(name.clone(), res);
modules[self.module_id].children.insert(name.clone(), module);
modules.insert(module, data);
let module = def_map.module_id(res);
let def = ModuleDefId::from(module);
def_map.modules[self.module_id].scope.declare(def);
@ -2219,7 +2230,7 @@ impl ModCollector<'_, '_> {
vis,
None,
);
res
module
}
/// Resolves attributes on an item.
@ -2516,12 +2527,10 @@ impl ModCollector<'_, '_> {
});
}
fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
let Some((source, target)) = Self::borrow_modules(
self.def_collector.def_map.modules.as_mut(),
module_id,
self.module_id,
) else {
fn import_all_legacy_macros(&mut self, module_id: ModuleId) {
let [Some(source), Some(target)] =
self.def_collector.def_map.modules.get_disjoint_mut([&module_id, &self.module_id])
else {
return;
};
@ -2532,29 +2541,6 @@ impl ModCollector<'_, '_> {
}
}
/// Mutably borrow two modules at once, retu
fn borrow_modules(
modules: &mut [ModuleData],
a: LocalModuleId,
b: LocalModuleId,
) -> Option<(&mut ModuleData, &mut ModuleData)> {
let a = a.into_raw().into_u32() as usize;
let b = b.into_raw().into_u32() as usize;
let (a, b) = match a.cmp(&b) {
Ordering::Equal => return None,
Ordering::Less => {
let (prefix, b) = modules.split_at_mut(b);
(&mut prefix[a], &mut b[0])
}
Ordering::Greater => {
let (prefix, a) = modules.split_at_mut(a);
(&mut a[0], &mut prefix[b])
}
};
Some((a, b))
}
fn emit_unconfigured_diagnostic(&mut self, ast_id: ErasedAstId, cfg: &CfgExpr) {
self.def_collector.def_map.diagnostics.push(DefDiagnostic::unconfigured_code(
self.module_id,
@ -2574,48 +2560,15 @@ impl ModCollector<'_, '_> {
mod tests {
use test_fixture::WithFixture;
use crate::{nameres::DefMapCrateData, test_db::TestDB};
use crate::test_db::TestDB;
use super::*;
fn do_collect_defs(db: &dyn DefDatabase, def_map: DefMap) -> DefMap {
let mut collector = DefCollector {
db,
def_map,
local_def_map: LocalDefMap::default(),
crate_local_def_map: None,
deps: FxIndexMap::default(),
glob_imports: FxHashMap::default(),
unresolved_imports: Vec::new(),
indeterminate_imports: Vec::new(),
unresolved_macros: Vec::new(),
mod_dirs: FxHashMap::default(),
cfg_options: &CfgOptions::default(),
proc_macros: Default::default(),
from_glob_import: Default::default(),
skip_attrs: Default::default(),
prev_active_attrs: Default::default(),
is_proc_macro: false,
unresolved_extern_crates: Default::default(),
};
collector.seed_with_top_level();
collector.collect();
collector.def_map
}
fn do_resolve(not_ra_fixture: &str) -> DefMap {
let (db, file_id) = TestDB::with_single_file(not_ra_fixture);
fn do_resolve(not_ra_fixture: &str) {
let (db, _) = TestDB::with_single_file(not_ra_fixture);
let krate = db.test_crate();
let edition = krate.data(&db).edition;
let module_origin = ModuleOrigin::CrateRoot { definition: file_id };
let def_map = DefMap::empty(
krate,
Arc::new(DefMapCrateData::new(edition)),
ModuleData::new(module_origin, Visibility::Public),
None,
);
do_collect_defs(&db, def_map)
crate_def_map(&db, krate);
}
#[test]

View file

@ -7,7 +7,7 @@ use hir_expand::{ErasedAstId, ExpandErrorKind, MacroCallKind, attrs::AttrId, mod
use la_arena::Idx;
use syntax::ast;
use crate::{AstId, nameres::LocalModuleId};
use crate::{AstId, nameres::ModuleId};
#[derive(Debug, PartialEq, Eq)]
pub enum DefDiagnosticKind {
@ -43,13 +43,13 @@ impl DefDiagnostics {
#[derive(Debug, PartialEq, Eq)]
pub struct DefDiagnostic {
pub in_module: LocalModuleId,
pub in_module: ModuleId,
pub kind: DefDiagnosticKind,
}
impl DefDiagnostic {
pub(super) fn unresolved_module(
container: LocalModuleId,
container: ModuleId,
declaration: AstId<ast::Module>,
candidates: Box<[String]>,
) -> Self {
@ -60,7 +60,7 @@ impl DefDiagnostic {
}
pub(super) fn unresolved_extern_crate(
container: LocalModuleId,
container: ModuleId,
declaration: AstId<ast::ExternCrate>,
) -> Self {
Self {
@ -70,7 +70,7 @@ impl DefDiagnostic {
}
pub(super) fn unresolved_import(
container: LocalModuleId,
container: ModuleId,
id: AstId<ast::Use>,
index: Idx<ast::UseTree>,
) -> Self {
@ -78,7 +78,7 @@ impl DefDiagnostic {
}
pub fn macro_error(
container: LocalModuleId,
container: ModuleId,
ast: AstId<ast::Item>,
path: ModPath,
err: ExpandErrorKind,
@ -87,7 +87,7 @@ impl DefDiagnostic {
}
pub fn unconfigured_code(
container: LocalModuleId,
container: ModuleId,
ast_id: ErasedAstId,
cfg: CfgExpr,
opts: CfgOptions,
@ -100,33 +100,26 @@ impl DefDiagnostic {
// FIXME: Whats the difference between this and unresolved_proc_macro
pub(crate) fn unresolved_macro_call(
container: LocalModuleId,
container: ModuleId,
ast: MacroCallKind,
path: ModPath,
) -> Self {
Self { in_module: container, kind: DefDiagnosticKind::UnresolvedMacroCall { ast, path } }
}
pub(super) fn unimplemented_builtin_macro(
container: LocalModuleId,
ast: AstId<ast::Macro>,
) -> Self {
pub(super) fn unimplemented_builtin_macro(container: ModuleId, ast: AstId<ast::Macro>) -> Self {
Self { in_module: container, kind: DefDiagnosticKind::UnimplementedBuiltinMacro { ast } }
}
pub(super) fn invalid_derive_target(
container: LocalModuleId,
container: ModuleId,
ast: AstId<ast::Item>,
id: AttrId,
) -> Self {
Self { in_module: container, kind: DefDiagnosticKind::InvalidDeriveTarget { ast, id } }
}
pub(super) fn malformed_derive(
container: LocalModuleId,
ast: AstId<ast::Adt>,
id: AttrId,
) -> Self {
pub(super) fn malformed_derive(container: ModuleId, ast: AstId<ast::Adt>, id: AttrId) -> Self {
Self { in_module: container, kind: DefDiagnosticKind::MalformedDerive { ast, id } }
}
}

View file

@ -19,7 +19,7 @@ use span::Edition;
use stdx::TupleExt;
use crate::{
AdtId, LocalModuleId, ModuleDefId,
AdtId, ModuleDefId, ModuleId,
db::DefDatabase,
item_scope::{BUILTIN_SCOPE, ImportOrExternCrate},
item_tree::FieldsShape,
@ -97,7 +97,7 @@ impl DefMap {
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
// module to import to
original_module: LocalModuleId,
original_module: ModuleId,
// pub(path)
// ^^^^ this
visibility: &RawVisibility,
@ -130,8 +130,8 @@ impl DefMap {
// DefMap they're written in, so we restrict them when that happens.
if let Visibility::Module(m, mv) = vis {
// ...unless we're resolving visibility for an associated item in an impl.
if self.block_id() != m.block && !within_impl {
vis = Visibility::Module(self.module_id(Self::ROOT), mv);
if self.block_id() != m.block(db) && !within_impl {
vis = Visibility::Module(self.root, mv);
tracing::debug!(
"visibility {:?} points outside DefMap, adjusting to {:?}",
m,
@ -142,7 +142,7 @@ impl DefMap {
vis
}
RawVisibility::PubSelf(explicitness) => {
Visibility::Module(self.module_id(original_module), *explicitness)
Visibility::Module(original_module, *explicitness)
}
RawVisibility::Public => Visibility::Public,
RawVisibility::PubCrate => Visibility::PubCrate(self.krate),
@ -158,7 +158,7 @@ impl DefMap {
db: &dyn DefDatabase,
mode: ResolveMode,
// module to import to
mut original_module: LocalModuleId,
mut original_module: ModuleId,
path: &ModPath,
shadow: BuiltinShadowMode,
// Pass `MacroSubNs` if we know we're resolving macro names and which kind of macro we're
@ -198,17 +198,17 @@ impl DefMap {
loop {
match current_map.block {
Some(block) if original_module == Self::ROOT => {
Some(block) if original_module == current_map.root => {
// Block modules "inherit" names from its parent module.
original_module = block.parent.local_id;
current_map = block.parent.def_map(db, current_map.krate);
original_module = block.parent;
current_map = block.parent.def_map(db);
}
// Proper (non-block) modules, including those in block `DefMap`s, don't.
_ => {
if original_module != Self::ROOT && current_map.block.is_some() {
if original_module != current_map.root && current_map.block.is_some() {
// A module inside a block. Do not resolve items declared in upper blocks, but we do need to get
// the prelude items (which are not inserted into blocks because they can be overridden there).
original_module = Self::ROOT;
original_module = current_map.root;
current_map = crate_def_map(db, self.krate);
let new = current_map.resolve_path_fp_in_all_preludes(
@ -245,7 +245,7 @@ impl DefMap {
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
mode: ResolveMode,
original_module: LocalModuleId,
original_module: ModuleId,
path: &ModPath,
shadow: BuiltinShadowMode,
expected_macro_subns: Option<MacroSubNs>,
@ -255,15 +255,15 @@ impl DefMap {
PathKind::DollarCrate(krate) => {
if krate == self.krate {
cov_mark::hit!(macro_dollar_crate_self);
PerNs::types(self.crate_root().into(), Visibility::Public, None)
PerNs::types(self.crate_root(db).into(), Visibility::Public, None)
} else {
let def_map = crate_def_map(db, krate);
let module = def_map.module_id(Self::ROOT);
let module = def_map.root;
cov_mark::hit!(macro_dollar_crate_other);
PerNs::types(module.into(), Visibility::Public, None)
}
}
PathKind::Crate => PerNs::types(self.crate_root().into(), Visibility::Public, None),
PathKind::Crate => PerNs::types(self.crate_root(db).into(), Visibility::Public, None),
// plain import or absolute path in 2015: crate-relative with
// fallback to extern prelude (with the simplification in
// rust-lang/rust#57745)
@ -310,14 +310,10 @@ impl DefMap {
}
PathKind::Super(lvl) => {
let mut local_id = original_module;
let mut ext;
let mut def_map = self;
// Adjust `local_id` to `self`, i.e. the nearest non-block module.
if def_map.module_id(local_id).is_block_module() {
(ext, local_id) = adjust_to_nearest_non_block_module(db, def_map, local_id);
def_map = ext;
}
(def_map, local_id) = adjust_to_nearest_non_block_module(db, def_map, local_id);
// Go up the module tree but skip block modules as `super` always refers to the
// nearest non-block module.
@ -325,12 +321,8 @@ impl DefMap {
// Loop invariant: at the beginning of each loop, `local_id` must refer to a
// non-block module.
if let Some(parent) = def_map.modules[local_id].parent {
local_id = parent;
if def_map.module_id(local_id).is_block_module() {
(ext, local_id) =
adjust_to_nearest_non_block_module(db, def_map, local_id);
def_map = ext;
}
(def_map, local_id) =
adjust_to_nearest_non_block_module(db, def_map, parent);
} else {
stdx::always!(def_map.block.is_none());
tracing::debug!("super path in root module");
@ -338,9 +330,6 @@ impl DefMap {
}
}
let module = def_map.module_id(local_id);
stdx::never!(module.is_block_module());
if self.block != def_map.block {
// If we have a different `DefMap` from `self` (the original `DefMap` we started
// with), resolve the remaining path segments in that `DefMap`.
@ -358,7 +347,7 @@ impl DefMap {
);
}
PerNs::types(module.into(), Visibility::Public, None)
PerNs::types(local_id.into(), Visibility::Public, None)
}
PathKind::Abs => match self.resolve_path_abs(local_def_map, &mut segments, path) {
Either::Left(it) => it,
@ -385,7 +374,7 @@ impl DefMap {
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
mode: ResolveMode,
original_module: LocalModuleId,
original_module: ModuleId,
path: &ModPath,
shadow: BuiltinShadowMode,
) -> ResolvePathResult {
@ -467,7 +456,7 @@ impl DefMap {
mut curr_per_ns: PerNs,
path: &ModPath,
shadow: BuiltinShadowMode,
original_module: LocalModuleId,
original_module: ModuleId,
) -> ResolvePathResult {
while let Some((i, segment)) = segments.next() {
let curr = match curr_per_ns.take_types_full() {
@ -485,7 +474,7 @@ impl DefMap {
curr_per_ns = match curr.def {
ModuleDefId::ModuleId(module) => {
if module.krate != self.krate {
if module.krate(db) != self.krate {
// FIXME: Inefficient
let path = ModPath::from_segments(
PathKind::SELF,
@ -501,7 +490,7 @@ impl DefMap {
LocalDefMap::EMPTY,
db,
mode,
module.local_id,
module,
&path,
shadow,
None,
@ -518,11 +507,11 @@ impl DefMap {
}
let def_map;
let module_data = if module.block == self.block_id() {
&self[module.local_id]
let module_data = if module.block(db) == self.block_id() {
&self[module]
} else {
def_map = module.def_map(db);
&def_map[module.local_id]
&def_map[module]
};
// Since it is a qualified path here, it should not contains legacy macros
@ -649,7 +638,7 @@ impl DefMap {
&self,
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
module: LocalModuleId,
module: ModuleId,
name: &Name,
shadow: BuiltinShadowMode,
expected_macro_subns: Option<MacroSubNs>,
@ -684,7 +673,7 @@ impl DefMap {
};
let extern_prelude = || {
if self.block.is_some() && module == DefMap::ROOT {
if self.block.is_some() && module == self.root {
// Don't resolve extern prelude in pseudo-modules of blocks, because
// they might been shadowed by local names.
return PerNs::none();
@ -693,7 +682,7 @@ impl DefMap {
};
let macro_use_prelude = || self.resolve_in_macro_use_prelude(name);
let prelude = || {
if self.block.is_some() && module == DefMap::ROOT {
if self.block.is_some() && module == self.root {
return PerNs::none();
}
self.resolve_in_prelude(db, name)
@ -746,18 +735,18 @@ impl DefMap {
&self,
local_def_map: &LocalDefMap,
db: &dyn DefDatabase,
module: LocalModuleId,
module: ModuleId,
name: &Name,
) -> PerNs {
let from_crate_root = match self.block {
Some(_) => {
let def_map = self.crate_root().def_map(db);
def_map[Self::ROOT].scope.get(name)
let def_map = self.crate_root(db).def_map(db);
def_map[def_map.root].scope.get(name)
}
None => self[Self::ROOT].scope.get(name),
None => self[self.root].scope.get(name),
};
let from_extern_prelude = || {
if self.block.is_some() && module == DefMap::ROOT {
if self.block.is_some() && module == self.root {
// Don't resolve extern prelude in pseudo-module of a block.
return PerNs::none();
}
@ -770,14 +759,14 @@ impl DefMap {
fn resolve_in_prelude(&self, db: &dyn DefDatabase, name: &Name) -> PerNs {
if let Some((prelude, _use)) = self.prelude {
let keep;
let def_map = if prelude.krate == self.krate {
let def_map = if prelude.krate(db) == self.krate {
self
} else {
// Extend lifetime
keep = prelude.def_map(db);
keep
};
def_map[prelude.local_id].scope.get(name)
def_map[prelude].scope.get(name)
} else {
PerNs::none()
}
@ -785,23 +774,23 @@ impl DefMap {
}
/// Given a block module, returns its nearest non-block module and the `DefMap` it belongs to.
#[inline]
fn adjust_to_nearest_non_block_module<'db>(
db: &'db dyn DefDatabase,
def_map: &'db DefMap,
mut local_id: LocalModuleId,
) -> (&'db DefMap, LocalModuleId) {
// INVARIANT: `local_id` in `def_map` must be a block module.
stdx::always!(def_map.module_id(local_id).is_block_module());
// This needs to be a local variable due to our mighty lifetime.
let mut def_map = def_map;
loop {
let BlockInfo { parent, .. } = def_map.block.expect("block module without parent module");
def_map = parent.def_map(db, def_map.krate);
local_id = parent.local_id;
if !parent.is_block_module() {
mut def_map: &'db DefMap,
mut local_id: ModuleId,
) -> (&'db DefMap, ModuleId) {
if def_map.root_module_id() != local_id {
// if we aren't the root, we are either not a block module, or a non-block module inside a
// block def map.
return (def_map, local_id);
}
while let Some(BlockInfo { parent, .. }) = def_map.block {
def_map = parent.def_map(db);
local_id = parent;
if def_map.root_module_id() != local_id {
return (def_map, local_id);
}
}
(def_map, local_id)
}

View file

@ -63,7 +63,7 @@ pub const BAZ: u32 = 0;
let all_crates_before = db.all_crates();
{
// Add a dependency a -> b.
// Add dependencies: c -> b, b -> a.
let mut new_crate_graph = CrateGraphBuilder::default();
let mut add_crate = |crate_name, root_file_idx: usize| {
@ -111,10 +111,13 @@ pub const BAZ: u32 = 0;
crate_def_map(&db, krate);
}
},
&[("crate_local_def_map", 1)],
// `c` gets invalidated as its dependency `b` changed
// `b` gets invalidated due to its new dependency edge to `a`
&[("crate_local_def_map", 2)],
expect![[r#"
[
"crate_local_def_map",
"crate_local_def_map",
]
"#]],
);
@ -280,20 +283,20 @@ fn f() { foo }
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"crate_local_def_map",
"proc_macros_for_crate_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"macro_def_shim",
"file_item_tree_query",
"ast_id_map_shim",
@ -404,32 +407,32 @@ pub struct S {}
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"decl_macro_expander_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"macro_def_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_macro_expansion_shim",
"macro_arg_shim",
"decl_macro_expander_shim",
"macro_def_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_macro_expansion_shim",
"macro_arg_shim",
"crate_local_def_map",
"proc_macros_for_crate_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"decl_macro_expander_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_shim",
"real_span_map_shim",
"macro_def_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_macro_expansion_shim",
"macro_arg_shim",
"decl_macro_expander_shim",
"macro_def_shim",
"file_item_tree_query",
"ast_id_map_shim",
"parse_macro_expansion_shim",
"macro_arg_shim",
"macro_def_shim",
"file_item_tree_query",
"ast_id_map_shim",
@ -509,7 +512,8 @@ m!(Z);
&db,
|| {
let crate_def_map = crate_def_map(&db, krate);
let (_, module_data) = crate_def_map.modules.iter().last().unwrap();
let module_data = &crate_def_map
[crate_def_map.modules_for_file(&db, pos.file_id.file_id(&db)).next().unwrap()];
assert_eq!(module_data.scope.resolutions().count(), 4);
},
&[("file_item_tree_query", 6), ("parse_macro_expansion_shim", 3)],
@ -558,7 +562,8 @@ m!(Z);
&db,
|| {
let crate_def_map = crate_def_map(&db, krate);
let (_, module_data) = crate_def_map.modules.iter().last().unwrap();
let module_data = &crate_def_map
[crate_def_map.modules_for_file(&db, pos.file_id.file_id(&db)).next().unwrap()];
assert_eq!(module_data.scope.resolutions().count(), 4);
},
&[("file_item_tree_query", 1), ("parse_macro_expansion_shim", 0)],

View file

@ -784,7 +784,7 @@ macro_rules! foo {
pub use core::clone::Clone;
"#,
|map| assert_eq!(map.modules[DefMap::ROOT].scope.impls().len(), 1),
|map| assert_eq!(map.modules[map.root].scope.impls().len(), 1),
);
}
@ -806,7 +806,7 @@ pub macro Copy {}
#[rustc_builtin_macro]
pub macro Clone {}
"#,
|map| assert_eq!(map.modules[DefMap::ROOT].scope.impls().len(), 2),
|map| assert_eq!(map.modules[map.root].scope.impls().len(), 2),
);
}
@ -849,7 +849,7 @@ pub macro derive($item:item) {}
#[rustc_builtin_macro]
pub macro Clone {}
"#,
|map| assert_eq!(map.modules[DefMap::ROOT].scope.impls().len(), 1),
|map| assert_eq!(map.modules[map.root].scope.impls().len(), 1),
);
}
@ -1502,7 +1502,7 @@ fn proc_attr(a: TokenStream, b: TokenStream) -> TokenStream { a }
let krate = *db.all_crates().last().expect("no crate graph present");
let def_map = crate_def_map(&db, krate);
let root_module = &def_map[DefMap::ROOT].scope;
let root_module = &def_map[def_map.root].scope;
assert!(
root_module.legacy_macros().count() == 0,
"`#[macro_use]` shouldn't bring macros into textual macro scope",
@ -1609,7 +1609,7 @@ macro_rules! derive { () => {} }
#[derive(Clone)]
struct S;
"#,
|map| assert_eq!(map.modules[DefMap::ROOT].scope.impls().len(), 1),
|map| assert_eq!(map.modules[map.root].scope.impls().len(), 1),
);
}

View file

@ -16,11 +16,11 @@ use syntax::ast::HasName;
use triomphe::Arc;
use crate::{
AdtId, AstIdLoc, ConstId, ConstParamId, CrateRootModuleId, DefWithBodyId, EnumId,
EnumVariantId, ExternBlockId, ExternCrateId, FunctionId, FxIndexMap, GenericDefId,
GenericParamId, HasModule, ImplId, ItemContainerId, LifetimeParamId, LocalModuleId, Lookup,
Macro2Id, MacroId, MacroRulesId, ModuleDefId, ModuleId, ProcMacroId, StaticId, StructId,
TraitId, TypeAliasId, TypeOrConstParamId, TypeParamId, UseId, VariantId,
AdtId, AstIdLoc, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, ExternBlockId,
ExternCrateId, FunctionId, FxIndexMap, GenericDefId, GenericParamId, HasModule, ImplId,
ItemContainerId, LifetimeParamId, Lookup, Macro2Id, MacroId, MacroRulesId, ModuleDefId,
ModuleId, ProcMacroId, StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId,
TypeParamId, UseId, VariantId,
builtin_type::BuiltinType,
db::DefDatabase,
expr_store::{
@ -55,7 +55,7 @@ pub struct Resolver<'db> {
struct ModuleItemMap<'db> {
def_map: &'db DefMap,
local_def_map: &'db LocalDefMap,
module_id: LocalModuleId,
module_id: ModuleId,
}
impl fmt::Debug for ModuleItemMap<'_> {
@ -608,14 +608,14 @@ impl<'db> Resolver<'db> {
},
);
local_def_map.extern_prelude().for_each(|(name, (def, _extern_crate))| {
res.add(name, ScopeDef::ModuleDef(ModuleDefId::ModuleId(def.into())));
res.add(name, ScopeDef::ModuleDef(ModuleDefId::ModuleId(def)));
});
BUILTIN_SCOPE.iter().for_each(|(name, &def)| {
res.add_per_ns(name, def);
});
if let Some((prelude, _use)) = def_map.prelude() {
let prelude_def_map = prelude.def_map(db);
for (name, def) in prelude_def_map[prelude.local_id].scope.entries() {
for (name, def) in prelude_def_map[prelude].scope.entries() {
res.add_per_ns(name, def)
}
}
@ -647,7 +647,7 @@ impl<'db> Resolver<'db> {
self.module_scope
.local_def_map
.extern_prelude()
.map(|(name, module_id)| (name.clone(), module_id.0.into()))
.map(|(name, module_id)| (name.clone(), module_id.0))
}
pub fn traits_in_scope(&self, db: &dyn DefDatabase) -> FxHashSet<TraitId> {
@ -674,7 +674,7 @@ impl<'db> Resolver<'db> {
// Fill in the prelude traits
if let Some((prelude, _use)) = self.module_scope.def_map.prelude() {
let prelude_def_map = prelude.def_map(db);
traits.extend(prelude_def_map[prelude.local_id].scope.traits());
traits.extend(prelude_def_map[prelude].scope.traits());
}
// Fill in module visible traits
traits.extend(self.module_scope.def_map[self.module_scope.module_id].scope.traits());
@ -691,8 +691,7 @@ impl<'db> Resolver<'db> {
}
pub fn module(&self) -> ModuleId {
let (def_map, _, local_id) = self.item_scope_();
def_map.module_id(local_id)
self.item_scope_().2
}
pub fn item_scope(&self) -> &ItemScope {
@ -882,11 +881,11 @@ impl<'db> Resolver<'db> {
}));
if let Some(block) = expr_scopes.block(scope_id) {
let def_map = block_def_map(db, block);
let local_def_map = block.lookup(db).module.only_local_def_map(db);
let local_def_map = block.module(db).only_local_def_map(db);
resolver.scopes.push(Scope::BlockScope(ModuleItemMap {
def_map,
local_def_map,
module_id: DefMap::ROOT,
module_id: def_map.root,
}));
// FIXME: This adds as many module scopes as there are blocks, but resolving in each
// already traverses all parents, so this is O(n²). I think we could only store the
@ -985,7 +984,7 @@ impl<'db> Resolver<'db> {
}
/// The innermost block scope that contains items or the module scope that contains this resolver.
fn item_scope_(&self) -> (&DefMap, &LocalDefMap, LocalModuleId) {
fn item_scope_(&self) -> (&DefMap, &LocalDefMap, ModuleId) {
self.scopes()
.find_map(|scope| match scope {
Scope::BlockScope(m) => Some((m.def_map, m.local_def_map, m.module_id)),
@ -1088,10 +1087,10 @@ fn resolver_for_scope_<'db>(
for scope in scope_chain.into_iter().rev() {
if let Some(block) = scopes.block(scope) {
let def_map = block_def_map(db, block);
let local_def_map = block.lookup(db).module.only_local_def_map(db);
let local_def_map = block.module(db).only_local_def_map(db);
// Using `DefMap::ROOT` is okay here since inside modules other than the root,
// there can't directly be expressions.
r = r.push_block_scope(def_map, local_def_map, DefMap::ROOT);
r = r.push_block_scope(def_map, local_def_map, def_map.root);
// FIXME: This adds as many module scopes as there are blocks, but resolving in each
// already traverses all parents, so this is O(n²). I think we could only store the
// innermost module scope instead?
@ -1124,7 +1123,7 @@ impl<'db> Resolver<'db> {
self,
def_map: &'db DefMap,
local_def_map: &'db LocalDefMap,
module_id: LocalModuleId,
module_id: ModuleId,
) -> Resolver<'db> {
self.push_scope(Scope::BlockScope(ModuleItemMap { def_map, local_def_map, module_id }))
}
@ -1284,9 +1283,9 @@ pub trait HasResolver: Copy {
impl HasResolver for ModuleId {
fn resolver(self, db: &dyn DefDatabase) -> Resolver<'_> {
let (mut def_map, local_def_map) = self.local_def_map(db);
let mut module_id = self.local_id;
let mut module_id = self;
if !self.is_within_block() {
if self.block(db).is_none() {
return Resolver {
scopes: vec![],
module_scope: ModuleItemMap { def_map, local_def_map, module_id },
@ -1296,9 +1295,9 @@ impl HasResolver for ModuleId {
let mut modules: SmallVec<[_; 1]> = smallvec![];
while let Some(parent) = def_map.parent() {
let block_def_map = mem::replace(&mut def_map, parent.def_map(db));
let block_module_id = mem::replace(&mut module_id, parent.local_id);
let block_module_id = mem::replace(&mut module_id, parent);
modules.push((block_def_map, block_module_id));
if !parent.is_within_block() {
if parent.block(db).is_none() {
break;
}
}
@ -1313,16 +1312,6 @@ impl HasResolver for ModuleId {
}
}
impl HasResolver for CrateRootModuleId {
fn resolver(self, db: &dyn DefDatabase) -> Resolver<'_> {
let (def_map, local_def_map) = self.local_def_map(db);
Resolver {
scopes: vec![],
module_scope: ModuleItemMap { def_map, local_def_map, module_id: DefMap::ROOT },
}
}
}
impl HasResolver for TraitId {
fn resolver(self, db: &dyn DefDatabase) -> Resolver<'_> {
lookup_resolver(db, self).push_generic_params_scope(db, self.into())

View file

@ -860,7 +860,7 @@ fn lower_fields<Field: ast::HasAttrs + ast::HasVisibility>(
mut field_name: impl FnMut(usize, &Field) -> Name,
override_visibility: Option<Option<ast::Visibility>>,
) -> Option<(Arena<FieldData>, ExpressionStore, ExpressionStoreSourceMap)> {
let cfg_options = module.krate.cfg_options(db);
let cfg_options = module.krate(db).cfg_options(db);
let mut col = ExprCollector::new(db, module, fields.file_id);
let override_visibility = override_visibility.map(|vis| {
LazyCell::new(|| {
@ -938,7 +938,7 @@ impl EnumVariants {
let ast_id_map = db.ast_id_map(source.file_id);
let mut diagnostics = ThinVec::new();
let cfg_options = loc.container.krate.cfg_options(db);
let cfg_options = loc.container.krate(db).cfg_options(db);
let mut index = 0;
let Some(variants) = source.value.variant_list() else {
return (EnumVariants { variants: Box::default() }, None);

View file

@ -148,7 +148,7 @@ impl HasChildSource<LocalFieldId> for VariantId {
let mut map = ArenaMap::new();
match &src.value {
ast::StructKind::Tuple(fl) => {
let cfg_options = container.krate.cfg_options(db);
let cfg_options = container.krate(db).cfg_options(db);
let mut idx = 0;
for fd in fl.fields() {
let enabled = AttrFlags::is_cfg_enabled_for(&fd, cfg_options).is_ok();
@ -163,7 +163,7 @@ impl HasChildSource<LocalFieldId> for VariantId {
}
}
ast::StructKind::Record(fl) => {
let cfg_options = container.krate.cfg_options(db);
let cfg_options = container.krate(db).cfg_options(db);
let mut idx = 0;
for fd in fl.fields() {
let enabled = AttrFlags::is_cfg_enabled_for(&fd, cfg_options).is_ok();

View file

@ -13,7 +13,7 @@ use syntax::{AstNode, algo, ast};
use triomphe::Arc;
use crate::{
LocalModuleId, Lookup, ModuleDefId, ModuleId,
Lookup, ModuleDefId, ModuleId,
db::DefDatabase,
nameres::{DefMap, ModuleSource, block_def_map, crate_def_map},
src::HasSource,
@ -154,7 +154,7 @@ impl TestDB {
let crate_def_map = crate_def_map(self, krate);
for (local_id, data) in crate_def_map.modules() {
if data.origin.file_id().map(|file_id| file_id.file_id(self)) == Some(file_id) {
return crate_def_map.module_id(local_id);
return local_id;
}
}
}
@ -168,7 +168,7 @@ impl TestDB {
def_map = match self.block_at_position(def_map, position) {
Some(it) => it,
None => return def_map.module_id(module),
None => return module,
};
loop {
let new_map = self.block_at_position(def_map, position);
@ -178,16 +178,16 @@ impl TestDB {
}
_ => {
// FIXME: handle `mod` inside block expression
return def_map.module_id(DefMap::ROOT);
return def_map.root;
}
}
}
}
/// Finds the smallest/innermost module in `def_map` containing `position`.
fn mod_at_position(&self, def_map: &DefMap, position: FilePosition) -> LocalModuleId {
fn mod_at_position(&self, def_map: &DefMap, position: FilePosition) -> ModuleId {
let mut size = None;
let mut res = DefMap::ROOT;
let mut res = def_map.root;
for (module, data) in def_map.modules() {
let src = data.definition_source(self);
// We're not comparing the `base_db::EditionedFileId`, but rather the VFS `FileId`, because

View file

@ -9,7 +9,7 @@ use syntax::ast::{self, HasVisibility};
use triomphe::Arc;
use crate::{
AssocItemId, HasModule, ItemContainerId, LocalFieldId, LocalModuleId, ModuleId, TraitId,
AssocItemId, HasModule, ItemContainerId, LocalFieldId, ModuleId, ModuleIdLt, TraitId,
VariantId, db::DefDatabase, nameres::DefMap, resolver::HasResolver, src::HasSource,
};
@ -41,10 +41,14 @@ impl Visibility {
}
#[tracing::instrument(skip_all)]
pub fn is_visible_from(self, db: &dyn DefDatabase, from_module: ModuleId) -> bool {
pub fn is_visible_from<'db>(
self,
db: &'db dyn DefDatabase,
from_module: ModuleIdLt<'db>,
) -> bool {
let to_module = match self {
Visibility::Module(m, _) => m,
Visibility::PubCrate(krate) => return from_module.krate == krate,
Visibility::Module(m, _) => unsafe { m.to_db(db) },
Visibility::PubCrate(krate) => return from_module.krate(db) == krate,
Visibility::Public => return true,
};
if from_module == to_module {
@ -52,43 +56,50 @@ impl Visibility {
return true;
}
// if they're not in the same crate, it can't be visible
if from_module.krate != to_module.krate {
if from_module.krate(db) != to_module.krate(db) {
return false;
}
let def_map = from_module.def_map(db);
Self::is_visible_from_def_map_(db, def_map, to_module, from_module.local_id)
Self::is_visible_from_def_map_(db, def_map, to_module, from_module)
}
pub(crate) fn is_visible_from_def_map(
pub(crate) fn is_visible_from_def_map<'db>(
self,
db: &dyn DefDatabase,
def_map: &DefMap,
from_module: LocalModuleId,
db: &'db dyn DefDatabase,
def_map: &'db DefMap,
from_module: ModuleIdLt<'db>,
) -> bool {
if cfg!(debug_assertions) {
_ = def_map.modules[from_module];
}
let to_module = match self {
Visibility::Module(m, _) => m,
Visibility::PubCrate(krate) => return def_map.krate() == krate,
Visibility::PubCrate(krate) => return from_module.krate(db) == krate,
Visibility::Public => return true,
};
if from_module == to_module {
// if the modules are the same, visibility is trivially satisfied
return true;
}
// if they're not in the same crate, it can't be visible
if def_map.krate() != to_module.krate {
if def_map.krate() != to_module.krate(db) {
return false;
}
if from_module == to_module.local_id && def_map.block_id() == to_module.block {
if from_module == to_module && def_map.block_id() == to_module.block(db) {
// if the modules are the same, visibility is trivially satisfied
return true;
}
Self::is_visible_from_def_map_(db, def_map, to_module, from_module)
}
fn is_visible_from_def_map_(
db: &dyn DefDatabase,
def_map: &DefMap,
mut to_module: ModuleId,
mut from_module: LocalModuleId,
fn is_visible_from_def_map_<'db>(
db: &'db dyn DefDatabase,
def_map: &'db DefMap,
mut to_module: ModuleIdLt<'db>,
mut from_module: ModuleIdLt<'db>,
) -> bool {
debug_assert_eq!(to_module.krate, def_map.krate());
debug_assert_eq!(to_module.krate(db), def_map.krate());
// `to_module` might be the root module of a block expression. Those have the same
// visibility as the containing module (even though no items are directly nameable from
// there, getting this right is important for method resolution).
@ -98,7 +109,7 @@ impl Visibility {
// currently computing, so we must not call the `def_map` query for it.
let def_map_block = def_map.block_id();
loop {
match (to_module.block, def_map_block) {
match (to_module.block(db), def_map_block) {
// `to_module` is not a block, so there is no parent def map to use.
(None, _) => (),
// `to_module` is at `def_map`'s block, no need to move further.
@ -117,7 +128,7 @@ impl Visibility {
let mut def_map = def_map;
let mut parent_arc;
loop {
if def_map.module_id(from_module) == to_module {
if from_module == to_module {
return true;
}
match def_map[from_module].parent {
@ -127,7 +138,7 @@ impl Visibility {
Some(module) => {
parent_arc = module.def_map(db);
def_map = parent_arc;
from_module = module.local_id;
from_module = module;
}
// Reached the root module, nothing left to check.
None => return false,
@ -141,7 +152,12 @@ impl Visibility {
///
/// If there is no subset relation between `self` and `other`, returns `None` (ie. they're only
/// visible in unrelated modules).
pub(crate) fn max(self, other: Visibility, def_map: &DefMap) -> Option<Visibility> {
pub(crate) fn max(
self,
db: &dyn DefDatabase,
other: Visibility,
def_map: &DefMap,
) -> Option<Visibility> {
match (self, other) {
(_, Visibility::Public) | (Visibility::Public, _) => Some(Visibility::Public),
(Visibility::PubCrate(krate), Visibility::PubCrate(krateb)) => {
@ -153,11 +169,7 @@ impl Visibility {
}
(Visibility::Module(mod_, _), Visibility::PubCrate(krate))
| (Visibility::PubCrate(krate), Visibility::Module(mod_, _)) => {
if mod_.krate == krate {
Some(Visibility::PubCrate(krate))
} else {
None
}
if mod_.krate(db) == krate { Some(Visibility::PubCrate(krate)) } else { None }
}
(Visibility::Module(mod_a, expl_a), Visibility::Module(mod_b, expl_b)) => {
if mod_a == mod_b {
@ -175,26 +187,24 @@ impl Visibility {
));
}
if mod_a.krate() != def_map.krate() || mod_b.krate() != def_map.krate() {
if mod_a.krate(db) != def_map.krate() || mod_b.krate(db) != def_map.krate() {
return None;
}
let def_block = def_map.block_id();
if mod_a.containing_block() != def_block || mod_b.containing_block() != def_block {
if mod_a.block(db) != def_block || mod_b.block(db) != def_block {
return None;
}
let mut a_ancestors =
iter::successors(Some(mod_a.local_id), |&m| def_map[m].parent);
let mut a_ancestors = iter::successors(Some(mod_a), |&m| def_map[m].parent);
if a_ancestors.any(|m| m == mod_b.local_id) {
if a_ancestors.any(|m| m == mod_b) {
// B is above A
return Some(Visibility::Module(mod_b, expl_b));
}
let mut b_ancestors =
iter::successors(Some(mod_b.local_id), |&m| def_map[m].parent);
if b_ancestors.any(|m| m == mod_a.local_id) {
let mut b_ancestors = iter::successors(Some(mod_b), |&m| def_map[m].parent);
if b_ancestors.any(|m| m == mod_a) {
// A is above B
return Some(Visibility::Module(mod_a, expl_a));
}
@ -208,7 +218,12 @@ impl Visibility {
///
/// If there is no subset relation between `self` and `other`, returns `None` (ie. they're only
/// visible in unrelated modules).
pub(crate) fn min(self, other: Visibility, def_map: &DefMap) -> Option<Visibility> {
pub(crate) fn min(
self,
db: &dyn DefDatabase,
other: Visibility,
def_map: &DefMap,
) -> Option<Visibility> {
match (self, other) {
(vis, Visibility::Public) | (Visibility::Public, vis) => Some(vis),
(Visibility::PubCrate(krate), Visibility::PubCrate(krateb)) => {
@ -220,10 +235,10 @@ impl Visibility {
}
(Visibility::Module(mod_, exp), Visibility::PubCrate(krate))
| (Visibility::PubCrate(krate), Visibility::Module(mod_, exp)) => {
if mod_.krate == krate { Some(Visibility::Module(mod_, exp)) } else { None }
if mod_.krate(db) == krate { Some(Visibility::Module(mod_, exp)) } else { None }
}
(Visibility::Module(mod_a, expl_a), Visibility::Module(mod_b, expl_b)) => {
if mod_a == mod_b {
if mod_a.krate(db) != mod_b.krate(db) {
// Most module visibilities are `pub(self)`, and assuming no errors
// this will be the common and thus fast path.
return Some(Visibility::Module(
@ -238,26 +253,24 @@ impl Visibility {
));
}
if mod_a.krate() != def_map.krate() || mod_b.krate() != def_map.krate() {
if mod_a.krate(db) != def_map.krate() || mod_b.krate(db) != def_map.krate() {
return None;
}
let def_block = def_map.block_id();
if mod_a.containing_block() != def_block || mod_b.containing_block() != def_block {
if mod_a.block(db) != def_block || mod_b.block(db) != def_block {
return None;
}
let mut a_ancestors =
iter::successors(Some(mod_a.local_id), |&m| def_map[m].parent);
let mut a_ancestors = iter::successors(Some(mod_a), |&m| def_map[m].parent);
if a_ancestors.any(|m| m == mod_b.local_id) {
if a_ancestors.any(|m| m == mod_b) {
// B is above A
return Some(Visibility::Module(mod_a, expl_a));
}
let mut b_ancestors =
iter::successors(Some(mod_b.local_id), |&m| def_map[m].parent);
if b_ancestors.any(|m| m == mod_a.local_id) {
let mut b_ancestors = iter::successors(Some(mod_b), |&m| def_map[m].parent);
if b_ancestors.any(|m| m == mod_a) {
// A is above B
return Some(Visibility::Module(mod_b, expl_b));
}

View file

@ -7,7 +7,7 @@ use crate::{ExpandResult, MacroCallId, MacroCallKind, db::ExpandDatabase, name,
use super::quote;
macro_rules! register_builtin {
($(($name:ident, $variant:ident) => $expand:ident),* ) => {
($(($name:ident, $variant:ident) => $expand:ident),* $(,)? ) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinAttrExpander {
$($variant),*
@ -65,7 +65,8 @@ register_builtin! {
(derive_const, DeriveConst) => derive_expand,
(global_allocator, GlobalAllocator) => dummy_attr_expand,
(test, Test) => dummy_gate_test_expand,
(test_case, TestCase) => dummy_gate_test_expand
(test_case, TestCase) => dummy_gate_test_expand,
(define_opaque, DefineOpaque) => dummy_attr_expand,
}
pub fn find_builtin_attr(ident: &name::Name) -> Option<BuiltinAttrExpander> {

View file

@ -162,25 +162,19 @@ fn macro_input_callback(
}
}
Meta::TokenTree { path, tt } => {
if path.segments.len() != 1
if path.is1("cfg") {
let cfg_expr = CfgExpr::parse_from_ast(
&mut TokenTreeChildren::new(&tt).peekable(),
);
if cfg_options().check(&cfg_expr) == Some(false) {
return ControlFlow::Break(ItemIsCfgedOut);
}
strip_current_attr = true;
} else if path.segments.len() != 1
|| !is_item_tree_filtered_attr(path.segments[0].text())
{
strip_current_attr = should_strip_attr();
}
if path.segments.len() == 1 {
let name = path.segments[0].text();
if name == "cfg" {
let cfg_expr = CfgExpr::parse_from_ast(
&mut TokenTreeChildren::new(&tt).peekable(),
);
if cfg_options().check(&cfg_expr) == Some(false) {
return ControlFlow::Break(ItemIsCfgedOut);
}
strip_current_attr = true;
}
}
}
Meta::Path { path } => {
if path.segments.len() != 1

View file

@ -126,7 +126,7 @@ fn eval_goal(db: &TestDB, file_id: EditionedFileId) -> Result<Const<'_>, ConstEv
let interner = DbInterner::new_no_crate(db);
let module_id = db.module_for_file(file_id.file_id(db));
let def_map = module_id.def_map(db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
let const_id = scope
.declarations()
.find_map(|x| match x {

View file

@ -164,7 +164,7 @@ impl<'a> DeclValidator<'a> {
else {
return;
};
let module_data = &module_id.def_map(self.db)[module_id.local_id];
let module_data = &module_id.def_map(self.db)[module_id];
let Some(module_src) = module_data.declaration_source(self.db) else {
return;
};

View file

@ -113,7 +113,7 @@ impl<'a, 'db> MatchCheckCtx<'a, 'db> {
/// Returns whether the given ADT is from another crate declared `#[non_exhaustive]`.
fn is_foreign_non_exhaustive(&self, adt: hir_def::AdtId) -> bool {
let is_local = adt.krate(self.db) == self.module.krate();
let is_local = adt.krate(self.db) == self.module.krate(self.db);
!is_local && AttrFlags::query(self.db, adt.into()).contains(AttrFlags::NON_EXHAUSTIVE)
}

View file

@ -165,7 +165,7 @@ impl<'db> UnsafeVisitor<'db> {
DefWithBodyId::FunctionId(func) => TargetFeatures::from_fn(db, func),
_ => TargetFeatures::default(),
};
let krate = resolver.module().krate();
let krate = resolver.krate();
let edition = krate.data(db).edition;
let target_feature_is_safe = match &krate.workspace_data(db).target {
Ok(target) => target_feature_is_safe_in_target(target),

View file

@ -18,7 +18,6 @@ use hir_def::{
item_scope::ItemInNs,
item_tree::FieldsShape,
lang_item::LangItems,
nameres::DefMap,
signatures::VariantFields,
type_ref::{
ConstRef, LifetimeRef, LifetimeRefId, TraitBoundModifier, TypeBound, TypeRef, TypeRefId,
@ -310,7 +309,7 @@ pub trait HirDisplay<'db> {
allow_opaque: bool,
) -> Result<String, DisplaySourceCodeError> {
let mut result = String::new();
let interner = DbInterner::new_with(db, module_id.krate());
let interner = DbInterner::new_with(db, module_id.krate(db));
match self.hir_fmt(&mut HirFormatter {
db,
interner,
@ -321,7 +320,7 @@ pub trait HirDisplay<'db> {
entity_limit: None,
omit_verbose_types: false,
closure_style: ClosureStyle::ImplFn,
display_target: DisplayTarget::from_crate(db, module_id.krate()),
display_target: DisplayTarget::from_crate(db, module_id.krate(db)),
display_kind: DisplayKind::SourceCode { target_module_id: module_id, allow_opaque },
show_container_bounds: false,
display_lifetimes: DisplayLifetime::OnlyNamedOrStatic,
@ -1516,7 +1515,7 @@ impl<'db> HirDisplay<'db> for Ty<'db> {
_ => false,
})
.collect::<Vec<_>>();
let krate = param.id.parent().module(db).krate();
let krate = param.id.parent().module(db).krate(db);
write_bounds_like_dyn_trait_with_prefix(
f,
"impl",
@ -2031,13 +2030,14 @@ pub fn write_visibility<'db>(
Visibility::PubCrate(_) => write!(f, "pub(crate) "),
Visibility::Module(vis_id, _) => {
let def_map = module_id.def_map(f.db);
let root_module_id = def_map.module_id(DefMap::ROOT);
let root_module_id = def_map.root_module_id();
if vis_id == module_id {
// pub(self) or omitted
Ok(())
} else if root_module_id == vis_id && !root_module_id.is_within_block() {
} else if root_module_id == vis_id && root_module_id.block(f.db).is_none() {
write!(f, "pub(crate) ")
} else if module_id.containing_module(f.db) == Some(vis_id) && !vis_id.is_block_module()
} else if module_id.containing_module(f.db) == Some(vis_id)
&& !vis_id.is_block_module(f.db)
{
write!(f, "pub(super) ")
} else {

View file

@ -25,12 +25,12 @@ fn has_destructor(interner: DbInterner<'_>, adt: AdtId) -> bool {
let Some(drop_trait) = interner.lang_items().Drop else {
return false;
};
let impls = match module.containing_block() {
let impls = match module.block(db) {
Some(block) => match TraitImpls::for_block(db, block) {
Some(it) => &**it,
None => return false,
},
None => TraitImpls::for_crate(db, module.krate()),
None => TraitImpls::for_crate(db, module.krate(db)),
};
!impls.for_trait_and_self_ty(drop_trait, &SimplifiedType::Adt(adt.into())).is_empty()
}

View file

@ -3,9 +3,9 @@
use std::ops::ControlFlow;
use hir_def::{
AssocItemId, ConstId, CrateRootModuleId, FunctionId, GenericDefId, HasModule, TraitId,
TypeAliasId, TypeOrConstParamId, TypeParamId, hir::generics::LocalTypeOrConstParamId,
signatures::TraitFlags,
AssocItemId, ConstId, FunctionId, GenericDefId, HasModule, TraitId, TypeAliasId,
TypeOrConstParamId, TypeParamId, hir::generics::LocalTypeOrConstParamId,
nameres::crate_def_map, signatures::TraitFlags,
};
use rustc_hash::FxHashSet;
use rustc_type_ir::{
@ -130,7 +130,7 @@ pub fn dyn_compatibility_of_trait_query(
}
pub fn generics_require_sized_self(db: &dyn HirDatabase, def: GenericDefId) -> bool {
let krate = def.module(db).krate();
let krate = def.module(db).krate(db);
let interner = DbInterner::new_with(db, krate);
let Some(sized) = interner.lang_items().Sized else {
return false;
@ -295,7 +295,7 @@ where
})
}
AssocItemId::TypeAliasId(it) => {
let def_map = CrateRootModuleId::from(trait_.krate(db)).def_map(db);
let def_map = crate_def_map(db, trait_.krate(db));
if def_map.is_unstable_feature_enabled(&intern::sym::generic_associated_type_extended) {
ControlFlow::Continue(())
} else {
@ -402,7 +402,7 @@ fn receiver_is_dispatchable<'db>(
let sig = sig.instantiate_identity();
let module = trait_.module(db);
let interner = DbInterner::new_with(db, module.krate());
let interner = DbInterner::new_with(db, module.krate(db));
let self_param_id = TypeParamId::from_unchecked(TypeOrConstParamId {
parent: trait_.into(),
local_id: LocalTypeOrConstParamId::from_raw(la_arena::RawIdx::from_u32(0)),

View file

@ -35,7 +35,7 @@ fn check_dyn_compatibility<'a>(
for (trait_id, name) in file_ids.into_iter().flat_map(|file_id| {
let module_id = db.module_for_file(file_id.file_id(&db));
let def_map = module_id.def_map(&db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
scope
.declarations()
.filter_map(|def| {

View file

@ -653,19 +653,16 @@ impl<'db> InferenceResult<'db> {
}
pub fn type_of_expr_with_adjust(&self, id: ExprId) -> Option<Ty<'db>> {
match self.expr_adjustments.get(&id).and_then(|adjustments| {
adjustments
.iter()
.filter(|adj| {
// https://github.com/rust-lang/rust/blob/67819923ac8ea353aaa775303f4c3aacbf41d010/compiler/rustc_mir_build/src/thir/cx/expr.rs#L140
!matches!(
adj,
Adjustment {
kind: Adjust::NeverToAny,
target,
} if target.is_never()
)
})
.next_back()
adjustments.iter().rfind(|adj| {
// https://github.com/rust-lang/rust/blob/67819923ac8ea353aaa775303f4c3aacbf41d010/compiler/rustc_mir_build/src/thir/cx/expr.rs#L140
!matches!(
adj,
Adjustment {
kind: Adjust::NeverToAny,
target,
} if target.is_never()
)
})
}) {
Some(adjustment) => Some(adjustment.target),
None => self.type_of_expr.get(id).copied(),

View file

@ -47,7 +47,7 @@ impl<'db> HirPlace<'db> {
|_, _, _| {
unreachable!("Closure field only happens in MIR");
},
ctx.owner.module(ctx.db).krate(),
ctx.owner.module(ctx.db).krate(ctx.db),
);
}
ty
@ -149,7 +149,7 @@ impl<'db> CapturedItem<'db> {
}
}
}
if is_raw_identifier(&result, owner.module(db).krate().data(db).edition) {
if is_raw_identifier(&result, owner.module(db).krate(db).data(db).edition) {
result.insert_str(0, "r#");
}
result
@ -843,7 +843,7 @@ impl<'db> InferenceContext<'_, 'db> {
|_, _, _| {
unreachable!("Closure field only happens in MIR");
},
self.owner.module(self.db).krate(),
self.owner.module(self.db).krate(self.db),
);
if ty.is_raw_ptr() || ty.is_union() {
capture.kind = CaptureKind::ByRef(BorrowKind::Shared);

View file

@ -45,7 +45,7 @@ fn eval_goal(
.find_map(|file_id| {
let module_id = db.module_for_file(file_id.file_id(&db));
let def_map = module_id.def_map(&db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
let adt_or_type_alias_id = scope.declarations().find_map(|x| match x {
hir_def::ModuleDefId::AdtId(x) => {
let name = match x {
@ -118,7 +118,7 @@ fn eval_expr(
crate::attach_db(&db, || {
let module_id = db.module_for_file(file_id.file_id(&db));
let def_map = module_id.def_map(&db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
let function_id = scope
.declarations()
.find_map(|x| match x {

View file

@ -1755,13 +1755,12 @@ pub(crate) fn trait_environment_query<'db>(
def: GenericDefId,
) -> ParamEnv<'db> {
let module = def.module(db);
let interner = DbInterner::new_with(db, module.krate());
let interner = DbInterner::new_with(db, module.krate(db));
let predicates = GenericPredicates::query_all(db, def);
let clauses = rustc_type_ir::elaborate::elaborate(interner, predicates.iter_identity_copied());
let clauses = Clauses::new_from_iter(interner, clauses);
// FIXME: We should normalize projections here, like rustc does.
ParamEnv { clauses }
}
@ -2280,7 +2279,7 @@ pub(crate) fn associated_type_by_name_including_super_traits<'db>(
name: &Name,
) -> Option<(TraitRef<'db>, TypeAliasId)> {
let module = trait_ref.def_id.0.module(db);
let interner = DbInterner::new_with(db, module.krate());
let interner = DbInterner::new_with(db, module.krate(db));
rustc_type_ir::elaborate::supertraits(interner, Binder::dummy(trait_ref)).find_map(|t| {
let trait_id = t.as_ref().skip_binder().def_id.0;
let assoc_type = trait_id.trait_items(db).associated_type_by_name(name)?;

View file

@ -13,8 +13,8 @@ use tracing::{debug, instrument};
use base_db::Crate;
use hir_def::{
AssocItemId, BlockId, ConstId, FunctionId, GenericParamId, HasModule, ImplId, ItemContainerId,
ModuleId, TraitId,
AssocItemId, BlockIdLt, ConstId, FunctionId, GenericParamId, HasModule, ImplId,
ItemContainerId, ModuleId, TraitId,
attrs::AttrFlags,
expr_store::path::GenericArgs as HirGenericArgs,
hir::ExprId,
@ -558,9 +558,9 @@ pub struct InherentImpls {
}
#[salsa::tracked]
impl InherentImpls {
impl<'db> InherentImpls {
#[salsa::tracked(returns(ref))]
pub fn for_crate(db: &dyn HirDatabase, krate: Crate) -> Self {
pub fn for_crate(db: &'db dyn HirDatabase, krate: Crate) -> Self {
let _p = tracing::info_span!("inherent_impls_in_crate_query", ?krate).entered();
let crate_def_map = crate_def_map(db, krate);
@ -569,7 +569,7 @@ impl InherentImpls {
}
#[salsa::tracked(returns(ref))]
pub fn for_block(db: &dyn HirDatabase, block: BlockId) -> Option<Box<Self>> {
pub fn for_block(db: &'db dyn HirDatabase, block: BlockIdLt<'db>) -> Option<Box<Self>> {
let _p = tracing::info_span!("inherent_impls_in_block_query").entered();
let block_def_map = block_def_map(db, block);
@ -627,13 +627,13 @@ impl InherentImpls {
self.map.get(self_ty).map(|it| &**it).unwrap_or_default()
}
pub fn for_each_crate_and_block(
db: &dyn HirDatabase,
pub fn for_each_crate_and_block<'db>(
db: &'db dyn HirDatabase,
krate: Crate,
block: Option<BlockId>,
block: Option<BlockIdLt<'db>>,
for_each: &mut dyn FnMut(&InherentImpls),
) {
let blocks = std::iter::successors(block, |block| block.loc(db).module.containing_block());
let blocks = std::iter::successors(block, |block| block.module(db).block(db));
blocks.filter_map(|block| Self::for_block(db, block).as_deref()).for_each(&mut *for_each);
for_each(Self::for_crate(db, krate));
}
@ -670,9 +670,9 @@ pub struct TraitImpls {
}
#[salsa::tracked]
impl TraitImpls {
impl<'db> TraitImpls {
#[salsa::tracked(returns(ref))]
pub fn for_crate(db: &dyn HirDatabase, krate: Crate) -> Arc<Self> {
pub fn for_crate(db: &'db dyn HirDatabase, krate: Crate) -> Arc<Self> {
let _p = tracing::info_span!("inherent_impls_in_crate_query", ?krate).entered();
let crate_def_map = crate_def_map(db, krate);
@ -681,7 +681,7 @@ impl TraitImpls {
}
#[salsa::tracked(returns(ref))]
pub fn for_block(db: &dyn HirDatabase, block: BlockId) -> Option<Box<Self>> {
pub fn for_block(db: &'db dyn HirDatabase, block: BlockIdLt<'db>) -> Option<Box<Self>> {
let _p = tracing::info_span!("inherent_impls_in_block_query").entered();
let block_def_map = block_def_map(db, block);
@ -690,7 +690,7 @@ impl TraitImpls {
}
#[salsa::tracked(returns(ref))]
pub fn for_crate_and_deps(db: &dyn HirDatabase, krate: Crate) -> Box<[Arc<Self>]> {
pub fn for_crate_and_deps(db: &'db dyn HirDatabase, krate: Crate) -> Box<[Arc<Self>]> {
krate.transitive_deps(db).iter().map(|&dep| Self::for_crate(db, dep).clone()).collect()
}
}
@ -792,23 +792,23 @@ impl TraitImpls {
}
}
pub fn for_each_crate_and_block(
db: &dyn HirDatabase,
pub fn for_each_crate_and_block<'db>(
db: &'db dyn HirDatabase,
krate: Crate,
block: Option<BlockId>,
block: Option<BlockIdLt<'db>>,
for_each: &mut dyn FnMut(&TraitImpls),
) {
let blocks = std::iter::successors(block, |block| block.loc(db).module.containing_block());
let blocks = std::iter::successors(block, |block| block.module(db).block(db));
blocks.filter_map(|block| Self::for_block(db, block).as_deref()).for_each(&mut *for_each);
Self::for_crate_and_deps(db, krate).iter().map(|it| &**it).for_each(for_each);
}
/// Like [`Self::for_each_crate_and_block()`], but takes in account two blocks, one for a trait and one for a self type.
pub fn for_each_crate_and_block_trait_and_type(
db: &dyn HirDatabase,
pub fn for_each_crate_and_block_trait_and_type<'db>(
db: &'db dyn HirDatabase,
krate: Crate,
type_block: Option<BlockId>,
trait_block: Option<BlockId>,
type_block: Option<BlockIdLt<'db>>,
trait_block: Option<BlockIdLt<'db>>,
for_each: &mut dyn FnMut(&TraitImpls),
) {
let in_self_and_deps = TraitImpls::for_crate_and_deps(db, krate);
@ -819,10 +819,11 @@ impl TraitImpls {
// that means there can't be duplicate impls; if they meet, we stop the search of the deeper block.
// This breaks when they are equal (both will stop immediately), therefore we handle this case
// specifically.
let blocks_iter = |block: Option<BlockId>| {
std::iter::successors(block, |block| block.loc(db).module.containing_block())
let blocks_iter = |block: Option<BlockIdLt<'db>>| {
std::iter::successors(block, |block| block.module(db).block(db))
};
let for_each_block = |current_block: Option<BlockId>, other_block: Option<BlockId>| {
let for_each_block = |current_block: Option<BlockIdLt<'db>>,
other_block: Option<BlockIdLt<'db>>| {
blocks_iter(current_block)
.take_while(move |&block| {
other_block.is_none_or(|other_block| other_block != block)

View file

@ -980,8 +980,8 @@ impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> {
};
InherentImpls::for_each_crate_and_block(
self.db(),
module.krate(),
module.containing_block(),
module.krate(self.db()),
module.block(self.db()),
&mut |impls| {
for &impl_def_id in impls.for_self_ty(self_ty) {
self.assemble_inherent_impl_probe(impl_def_id, receiver_steps);

View file

@ -97,7 +97,7 @@ pub fn borrowck_query<'db>(
) -> Result<Arc<[BorrowckResult<'db>]>, MirLowerError<'db>> {
let _p = tracing::info_span!("borrowck_query").entered();
let module = def.module(db);
let interner = DbInterner::new_with(db, module.krate());
let interner = DbInterner::new_with(db, module.krate(db));
let env = db.trait_environment_for_body(def);
let mut res = vec![];
// This calculates opaques defining scope which is a bit costly therefore is put outside `all_mir_bodies()`.
@ -148,7 +148,7 @@ fn moved_out_of_ref<'db>(
infcx,
ty,
make_fetch_closure_field(db),
body.owner.module(db).krate(),
body.owner.module(db).krate(db),
);
}
if is_dereference_of_ref
@ -244,7 +244,7 @@ fn partially_moved<'db>(
infcx,
ty,
make_fetch_closure_field(db),
body.owner.module(db).krate(),
body.owner.module(db).krate(db),
);
}
if !infcx.type_is_copy_modulo_regions(env, ty) && !ty.references_non_lt_error() {
@ -397,7 +397,7 @@ fn place_case<'db>(
infcx,
ty,
make_fetch_closure_field(db),
body.owner.module(db).krate(),
body.owner.module(db).krate(db),
);
}
if is_part_of { ProjectionCase::DirectPart } else { ProjectionCase::Direct }

View file

@ -635,7 +635,7 @@ impl<'db> Evaluator<'db> {
trait_env: Option<ParamEnvAndCrate<'db>>,
) -> Result<'db, Evaluator<'db>> {
let module = owner.module(db);
let crate_id = module.krate();
let crate_id = module.krate(db);
let target_data_layout = match db.target_data_layout(crate_id) {
Ok(target_data_layout) => target_data_layout,
Err(e) => return Err(MirEvalError::TargetDataLayoutNotAvailable(e)),

View file

@ -20,7 +20,7 @@ fn eval_main(db: &TestDB, file_id: EditionedFileId) -> Result<(String, String),
let interner = DbInterner::new_no_crate(db);
let module_id = db.module_for_file(file_id.file_id(db));
let def_map = module_id.def_map(db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
let func_id = scope
.declarations()
.find_map(|x| match x {
@ -90,7 +90,7 @@ fn check_pass_and_stdio(
line_index(range.end())
)
};
let krate = db.module_for_file(file_id.file_id(&db)).krate();
let krate = db.module_for_file(file_id.file_id(&db)).krate(&db);
e.pretty_print(
&mut err,
&db,

View file

@ -9,7 +9,7 @@ fn lower_mir(#[rust_analyzer::rust_fixture] ra_fixture: &str) {
let file_id = *file_ids.last().unwrap();
let module_id = db.module_for_file(file_id.file_id(&db));
let def_map = module_id.def_map(&db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
let funcs = scope.declarations().filter_map(|x| match x {
hir_def::ModuleDefId::FunctionId(it) => Some(it),
_ => None,

View file

@ -690,15 +690,10 @@ impl<'db> inherent::AdtDef<DbInterner<'db>> for AdtDef {
interner: DbInterner<'db>,
sizedness: SizedTraitKind,
) -> Option<EarlyBinder<DbInterner<'db>, Ty<'db>>> {
if self.is_struct() {
let tail_ty = self.all_field_tys(interner).skip_binder().into_iter().last()?;
let constraint_ty = sizedness_constraint_for_ty(interner, sizedness, tail_ty)?;
Some(EarlyBinder::bind(constraint_ty))
} else {
None
}
let tail_ty = self.struct_tail_ty(interner)?;
tail_ty
.map_bound(|tail_ty| sizedness_constraint_for_ty(interner, sizedness, tail_ty))
.transpose()
}
fn destructor(
@ -1694,7 +1689,7 @@ impl<'db> Interner for DbInterner<'db> {
mut f: impl FnMut(Self::ImplId),
) {
let krate = self.krate.expect("trait solving requires setting `DbInterner::krate`");
let trait_block = trait_def_id.0.loc(self.db).container.containing_block();
let trait_block = trait_def_id.0.loc(self.db).container.block(self.db);
let mut consider_impls_for_simplified_type = |simp: SimplifiedType| {
let type_block = simp.def().and_then(|def_id| {
let module = match def_id {
@ -1713,7 +1708,7 @@ impl<'db> Interner for DbInterner<'db> {
| SolverDefId::EnumVariantId(_)
| SolverDefId::Ctor(_) => return None,
};
module.containing_block()
module.block(self.db)
});
TraitImpls::for_each_crate_and_block_trait_and_type(
self.db,
@ -1828,7 +1823,7 @@ impl<'db> Interner for DbInterner<'db> {
fn for_each_blanket_impl(self, trait_def_id: Self::TraitId, mut f: impl FnMut(Self::ImplId)) {
let Some(krate) = self.krate else { return };
let block = trait_def_id.0.loc(self.db).container.containing_block();
let block = trait_def_id.0.loc(self.db).container.block(self.db);
TraitImpls::for_each_crate_and_block(self.db, krate, block, &mut |impls| {
for &impl_ in impls.blanket_impls(trait_def_id.0) {

View file

@ -656,7 +656,7 @@ impl<'db> Ty<'db> {
}
TyKind::Coroutine(coroutine_id, _args) => {
let InternedCoroutine(owner, _) = coroutine_id.0.loc(db);
let krate = owner.module(db).krate();
let krate = owner.module(db).krate(db);
if let Some(future_trait) = hir_def::lang_item::lang_items(db, krate).Future {
// This is only used by type walking.
// Parameters will be walked outside, and projection predicate is not used.

View file

@ -422,12 +422,10 @@ pub fn sizedness_constraint_for_ty<'db>(
.next_back()
.and_then(|ty| sizedness_constraint_for_ty(interner, sizedness, ty)),
Adt(adt, args) => {
let tail_ty =
EarlyBinder::bind(adt.all_field_tys(interner).skip_binder().into_iter().last()?)
.instantiate(interner, args);
Adt(adt, args) => adt.struct_tail_ty(interner).and_then(|tail_ty| {
let tail_ty = tail_ty.instantiate(interner, args);
sizedness_constraint_for_ty(interner, sizedness, tail_ty)
}
}),
Placeholder(..) | Bound(..) | Infer(..) => {
panic!("unexpected type `{ty:?}` in sizedness_constraint_for_ty")

View file

@ -118,7 +118,7 @@ pub(crate) fn tait_hidden_types<'db>(
let loc = type_alias.loc(db);
let module = loc.module(db);
let interner = DbInterner::new_with(db, module.krate());
let interner = DbInterner::new_with(db, module.krate(db));
let infcx = interner.infer_ctxt().build(TypingMode::non_body_analysis());
let mut ocx = ObligationCtxt::new(&infcx);
let cause = ObligationCause::dummy();

View file

@ -148,7 +148,7 @@ pub(crate) fn specializes(
// `#[allow_internal_unstable(specialization)]`, but `#[allow_internal_unstable]`
// is an internal feature, std is not using it for specialization nor is likely to
// ever use it, and we don't have the span information necessary to replicate that.
let def_map = crate_def_map(db, module.krate());
let def_map = crate_def_map(db, module.krate(db));
if !def_map.is_unstable_feature_enabled(&sym::specialization)
&& !def_map.is_unstable_feature_enabled(&sym::min_specialization)
{

View file

@ -138,9 +138,9 @@ impl TestDB {
let file_id = file_id.into();
for &krate in self.relevant_crates(file_id).iter() {
let crate_def_map = crate_def_map(self, krate);
for (local_id, data) in crate_def_map.modules() {
for (module_id, data) in crate_def_map.modules() {
if data.origin.file_id().map(|file_id| file_id.file_id(self)) == Some(file_id) {
return Some(crate_def_map.module_id(local_id));
return Some(module_id);
}
}
}

View file

@ -16,7 +16,7 @@ mod traits;
use base_db::{Crate, SourceDatabase};
use expect_test::Expect;
use hir_def::{
AssocItemId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleDefId, SyntheticSyntax,
AssocItemId, DefWithBodyId, HasModule, Lookup, ModuleDefId, ModuleId, SyntheticSyntax,
db::DefDatabase,
expr_store::{Body, BodySourceMap},
hir::{ExprId, Pat, PatId},
@ -114,7 +114,7 @@ fn check_impl(
None => continue,
};
let def_map = module.def_map(&db);
visit_module(&db, def_map, module.local_id, &mut |it| {
visit_module(&db, def_map, module, &mut |it| {
let def = match it {
ModuleDefId::FunctionId(it) => it.into(),
ModuleDefId::EnumVariantId(it) => it.into(),
@ -122,7 +122,7 @@ fn check_impl(
ModuleDefId::StaticId(it) => it.into(),
_ => return,
};
defs.push((def, module.krate()))
defs.push((def, module.krate(&db)))
});
}
defs.sort_by_key(|(def, _)| match def {
@ -412,7 +412,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
let def_map = module.def_map(&db);
let mut defs: Vec<(DefWithBodyId, Crate)> = Vec::new();
visit_module(&db, def_map, module.local_id, &mut |it| {
visit_module(&db, def_map, module, &mut |it| {
let def = match it {
ModuleDefId::FunctionId(it) => it.into(),
ModuleDefId::EnumVariantId(it) => it.into(),
@ -420,7 +420,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
ModuleDefId::StaticId(it) => it.into(),
_ => return,
};
defs.push((def, module.krate()))
defs.push((def, module.krate(&db)))
});
defs.sort_by_key(|(def, _)| match def {
DefWithBodyId::FunctionId(it) => {
@ -454,7 +454,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
pub(crate) fn visit_module(
db: &TestDB,
crate_def_map: &DefMap,
module_id: LocalModuleId,
module_id: ModuleId,
cb: &mut dyn FnMut(ModuleDefId),
) {
visit_scope(db, crate_def_map, &crate_def_map[module_id].scope, cb);
@ -517,7 +517,7 @@ pub(crate) fn visit_module(
}
}
}
ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it, cb),
_ => (),
}
}
@ -593,7 +593,7 @@ fn salsa_bug() {
crate::attach_db(&db, || {
let module = db.module_for_file(pos.file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
visit_module(&db, crate_def_map, module.local_id, &mut |def| {
visit_module(&db, crate_def_map, module, &mut |def| {
InferenceResult::for_body(
&db,
match def {
@ -637,7 +637,7 @@ fn salsa_bug() {
crate::attach_db(&db, || {
let module = db.module_for_file(pos.file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
visit_module(&db, crate_def_map, module.local_id, &mut |def| {
visit_module(&db, crate_def_map, module, &mut |def| {
InferenceResult::for_body(
&db,
match def {

View file

@ -24,7 +24,7 @@ fn check_closure_captures(#[rust_analyzer::rust_fixture] ra_fixture: &str, expec
let def_map = module.def_map(&db);
let mut defs = Vec::new();
visit_module(&db, def_map, module.local_id, &mut |it| defs.push(it));
visit_module(&db, def_map, module, &mut |it| defs.push(it));
let mut captures_info = Vec::new();
for def in defs {
@ -75,7 +75,7 @@ fn check_closure_captures(#[rust_analyzer::rust_fixture] ra_fixture: &str, expec
let capture_ty = capture
.ty
.skip_binder()
.display_test(db, DisplayTarget::from_crate(db, module.krate()))
.display_test(db, DisplayTarget::from_crate(db, module.krate(db)))
.to_string();
let spans = capture
.spans()

View file

@ -22,7 +22,7 @@ fn foo() -> i32 {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
visit_module(&db, crate_def_map, module.local_id, &mut |def| {
visit_module(&db, crate_def_map, module, &mut |def| {
if let ModuleDefId::FunctionId(it) = def {
InferenceResult::for_body(&db, it.into());
}
@ -66,7 +66,7 @@ fn foo() -> i32 {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
visit_module(&db, crate_def_map, module.local_id, &mut |def| {
visit_module(&db, crate_def_map, module, &mut |def| {
if let ModuleDefId::FunctionId(it) = def {
InferenceResult::for_body(&db, it.into());
}
@ -109,7 +109,7 @@ fn baz() -> i32 {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
visit_module(&db, crate_def_map, module.local_id, &mut |def| {
visit_module(&db, crate_def_map, module, &mut |def| {
if let ModuleDefId::FunctionId(it) = def {
InferenceResult::for_body(&db, it.into());
}
@ -178,7 +178,7 @@ fn baz() -> i32 {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
visit_module(&db, crate_def_map, module.local_id, &mut |def| {
visit_module(&db, crate_def_map, module, &mut |def| {
if let ModuleDefId::FunctionId(it) = def {
InferenceResult::for_body(&db, it.into());
}
@ -232,7 +232,7 @@ $0",
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -268,7 +268,7 @@ pub struct NewStruct {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -303,7 +303,7 @@ $0",
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -340,7 +340,7 @@ pub enum SomeEnum {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -375,7 +375,7 @@ $0",
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -409,7 +409,7 @@ fn bar() -> f32 {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -448,7 +448,7 @@ $0",
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -490,7 +490,7 @@ impl SomeStruct {
|| {
let module = db.module_for_file(pos.file_id.file_id(&db));
let _crate_def_map = module.def_map(&db);
TraitImpls::for_crate(&db, module.krate());
TraitImpls::for_crate(&db, module.krate(&db));
},
&[("TraitImpls::for_crate_", 1)],
expect_test::expect![[r#"
@ -546,7 +546,7 @@ fn main() {
let module = db.module_for_file(file_id.file_id(&db));
let crate_def_map = module.def_map(&db);
let mut defs: Vec<DefWithBodyId> = vec![];
visit_module(&db, crate_def_map, module.local_id, &mut |it| {
visit_module(&db, crate_def_map, module, &mut |it| {
let def = match it {
ModuleDefId::FunctionId(it) => it.into(),
ModuleDefId::EnumVariantId(it) => it.into(),
@ -643,7 +643,7 @@ fn main() {
let crate_def_map = module.def_map(&db);
let mut defs: Vec<DefWithBodyId> = vec![];
visit_module(&db, crate_def_map, module.local_id, &mut |it| {
visit_module(&db, crate_def_map, module, &mut |it| {
let def = match it {
ModuleDefId::FunctionId(it) => it.into(),
ModuleDefId::EnumVariantId(it) => it.into(),

View file

@ -2229,3 +2229,32 @@ fn test(x: *mut u8) {
"#,
);
}
#[test]
fn unsized_struct() {
check_types(
r#"
//- minicore: sized, phantom_data
use core::marker::PhantomData;
const UI_DEV_CREATE: Ioctl = Ioctl(PhantomData);
struct Ioctl<T: ?Sized = NoArgs>(PhantomData<T>);
struct NoArgs([u8]);
impl<T> Ioctl<T> {
fn ioctl(self) {}
}
impl Ioctl<NoArgs> {
fn ioctl(self) -> u32 { 0 }
}
fn main() {
UI_DEV_CREATE.ioctl();
// ^^^^^^^^^^^^^^^^^^^^^ u32
}
"#,
);
}

View file

@ -207,10 +207,10 @@ pub fn is_inherent_impl_coherent(db: &dyn HirDatabase, def_map: &DefMap, impl_id
| TyKind::Uint(_)
| TyKind::Float(_) => def_map.is_rustc_coherence_is_core(),
TyKind::Adt(adt_def, _) => adt_def.def_id().0.module(db).krate() == def_map.krate(),
TyKind::Adt(adt_def, _) => adt_def.def_id().0.module(db).krate(db) == def_map.krate(),
TyKind::Dynamic(it, _) => it
.principal_def_id()
.is_some_and(|trait_id| trait_id.0.module(db).krate() == def_map.krate()),
.is_some_and(|trait_id| trait_id.0.module(db).krate(db) == def_map.krate()),
_ => true,
};
@ -283,12 +283,12 @@ pub fn check_orphan_rules<'db>(db: &'db dyn HirDatabase, impl_: ImplId) -> bool
return true;
};
let local_crate = impl_.lookup(db).container.krate();
let local_crate = impl_.lookup(db).container.krate(db);
let is_local = |tgt_crate| tgt_crate == local_crate;
let trait_ref = impl_trait.instantiate_identity();
let trait_id = trait_ref.def_id.0;
if is_local(trait_id.module(db).krate()) {
if is_local(trait_id.module(db).krate(db)) {
// trait to be implemented is local
return true;
}
@ -322,10 +322,10 @@ pub fn check_orphan_rules<'db>(db: &'db dyn HirDatabase, impl_: ImplId) -> bool
// FIXME: param coverage
// - No uncovered type parameters `P1..=Pn` may appear in `T0..Ti`` (excluding `Ti`)
let is_not_orphan = trait_ref.args.types().any(|ty| match unwrap_fundamental(ty).kind() {
TyKind::Adt(adt_def, _) => is_local(adt_def.def_id().0.module(db).krate()),
TyKind::Adt(adt_def, _) => is_local(adt_def.def_id().0.module(db).krate(db)),
TyKind::Error(_) => true,
TyKind::Dynamic(it, _) => {
it.principal_def_id().is_some_and(|trait_id| is_local(trait_id.0.module(db).krate()))
it.principal_def_id().is_some_and(|trait_id| is_local(trait_id.0.module(db).krate(db)))
}
_ => false,
});

View file

@ -874,7 +874,7 @@ struct FixedPoint<T, U, V>(&'static FixedPoint<(), T, U>, V);
let mut defs: Vec<GenericDefId> = Vec::new();
let module = db.module_for_file_opt(file_id.file_id(&db)).unwrap();
let def_map = module.def_map(&db);
crate::tests::visit_module(&db, def_map, module.local_id, &mut |it| {
crate::tests::visit_module(&db, def_map, module, &mut |it| {
defs.push(match it {
ModuleDefId::FunctionId(it) => it.into(),
ModuleDefId::AdtId(it) => it.into(),

View file

@ -3,8 +3,7 @@
use cfg::CfgExpr;
use either::Either;
use hir_def::{
AssocItemId, AttrDefId, FieldId, InternedModuleId, LifetimeParamId, ModuleDefId,
TypeOrConstParamId,
AssocItemId, AttrDefId, FieldId, LifetimeParamId, ModuleDefId, TypeOrConstParamId,
attrs::{AttrFlags, Docs, IsInnerDoc},
expr_store::path::Path,
item_scope::ItemInNs,
@ -213,8 +212,8 @@ impl_has_attrs_enum![TypeParam, ConstParam, LifetimeParam for GenericParam];
impl HasAttrs for Module {
#[inline]
fn attr_id(self, db: &dyn HirDatabase) -> AttrsOwner {
AttrsOwner::AttrDef(AttrDefId::ModuleId(InternedModuleId::new(db, self.id)))
fn attr_id(self, _: &dyn HirDatabase) -> AttrsOwner {
AttrsOwner::AttrDef(AttrDefId::ModuleId(self.id))
}
}
@ -243,7 +242,7 @@ impl HasAttrs for AssocItem {
impl HasAttrs for crate::Crate {
#[inline]
fn attr_id(self, db: &dyn HirDatabase) -> AttrsOwner {
self.root_module().attr_id(db)
self.root_module(db).attr_id(db)
}
}
@ -274,7 +273,6 @@ fn resolve_doc_path_on_(
) -> Option<DocLinkDef> {
let resolver = match attr_id {
AttrsOwner::AttrDef(AttrDefId::ModuleId(it)) => {
let it = it.loc(db);
if is_inner_doc.yes() {
it.resolver(db)
} else if let Some(parent) = Module::from(it).parent(db) {

View file

@ -35,23 +35,23 @@ impl Module {
/// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
pub fn definition_source(self, db: &dyn HirDatabase) -> InFile<ModuleSource> {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].definition_source(db)
def_map[self.id].definition_source(db)
}
/// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
pub fn definition_source_range(self, db: &dyn HirDatabase) -> InFile<TextRange> {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].definition_source_range(db)
def_map[self.id].definition_source_range(db)
}
pub fn definition_source_file_id(self, db: &dyn HirDatabase) -> HirFileId {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].definition_source_file_id()
def_map[self.id].definition_source_file_id()
}
pub fn is_mod_rs(self, db: &dyn HirDatabase) -> bool {
let def_map = self.id.def_map(db);
match def_map[self.id.local_id].origin {
match def_map[self.id].origin {
ModuleOrigin::File { is_mod_rs, .. } => is_mod_rs,
_ => false,
}
@ -59,7 +59,7 @@ impl Module {
pub fn as_source_file_id(self, db: &dyn HirDatabase) -> Option<EditionedFileId> {
let def_map = self.id.def_map(db);
match def_map[self.id.local_id].origin {
match def_map[self.id].origin {
ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition, .. } => {
Some(definition)
}
@ -69,21 +69,21 @@ impl Module {
pub fn is_inline(self, db: &dyn HirDatabase) -> bool {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].origin.is_inline()
def_map[self.id].origin.is_inline()
}
/// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
/// `None` for the crate root.
pub fn declaration_source(self, db: &dyn HirDatabase) -> Option<InFile<ast::Module>> {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].declaration_source(db)
def_map[self.id].declaration_source(db)
}
/// Returns a text range which declares this module, either a `mod foo;` or a `mod foo {}`.
/// `None` for the crate root.
pub fn declaration_source_range(self, db: &dyn HirDatabase) -> Option<InFile<TextRange>> {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].declaration_source_range(db)
def_map[self.id].declaration_source_range(db)
}
}

View file

@ -48,11 +48,11 @@ use arrayvec::ArrayVec;
use base_db::{CrateDisplayName, CrateOrigin, LangCrateOrigin};
use either::Either;
use hir_def::{
AdtId, AssocItemId, AssocItemLoc, CallableDefId, ConstId, ConstParamId, CrateRootModuleId,
DefWithBodyId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId, FunctionId, GenericDefId,
GenericParamId, HasModule, ImplId, InternedModuleId, ItemContainerId, LifetimeParamId,
LocalFieldId, Lookup, MacroExpander, MacroId, StaticId, StructId, SyntheticSyntax, TupleId,
TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId,
AdtId, AssocItemId, AssocItemLoc, CallableDefId, ConstId, ConstParamId, DefWithBodyId, EnumId,
EnumVariantId, ExternBlockId, ExternCrateId, FunctionId, GenericDefId, GenericParamId,
HasModule, ImplId, ItemContainerId, LifetimeParamId, LocalFieldId, Lookup, MacroExpander,
MacroId, StaticId, StructId, SyntheticSyntax, TupleId, TypeAliasId, TypeOrConstParamId,
TypeParamId, UnionId,
attrs::AttrFlags,
expr_store::{ExpressionStoreDiagnostics, ExpressionStoreSourceMap},
hir::{
@ -117,8 +117,8 @@ pub use crate::{
diagnostics::*,
has_source::HasSource,
semantics::{
PathResolution, PathResolutionPerNs, Semantics, SemanticsImpl, SemanticsScope, TypeInfo,
VisibleTraits,
LintAttr, PathResolution, PathResolutionPerNs, Semantics, SemanticsImpl, SemanticsScope,
TypeInfo, VisibleTraits,
},
};
@ -258,13 +258,13 @@ impl Crate {
.flatten()
}
pub fn root_module(self) -> Module {
Module { id: CrateRootModuleId::from(self.id).into() }
pub fn root_module(self, db: &dyn HirDatabase) -> Module {
Module { id: crate_def_map(db, self.id).root_module_id() }
}
pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
let def_map = crate_def_map(db, self.id);
def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
def_map.modules().map(|(id, _)| id.into()).collect()
}
pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
@ -520,7 +520,7 @@ impl ModuleDef {
impl HasCrate for ModuleDef {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
match self.module(db) {
Some(module) => module.krate(),
Some(module) => module.krate(db),
None => Crate::core(db).unwrap_or_else(|| db.all_crates()[0].into()),
}
}
@ -550,29 +550,29 @@ impl Module {
}
/// Returns the crate this module is part of.
pub fn krate(self) -> Crate {
Crate { id: self.id.krate() }
pub fn krate(self, db: &dyn HirDatabase) -> Crate {
Crate { id: self.id.krate(db) }
}
/// Topmost parent of this module. Every module has a `crate_root`, but some
/// might be missing `krate`. This can happen if a module's file is not included
/// in the module tree of any target in `Cargo.toml`.
pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
let def_map = crate_def_map(db, self.id.krate());
Module { id: def_map.crate_root().into() }
let def_map = crate_def_map(db, self.id.krate(db));
Module { id: def_map.crate_root(db) }
}
pub fn is_crate_root(self) -> bool {
DefMap::ROOT == self.id.local_id
pub fn is_crate_root(self, db: &dyn HirDatabase) -> bool {
self.crate_root(db) == self
}
/// Iterates over all child modules.
pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
let def_map = self.id.def_map(db);
let children = def_map[self.id.local_id]
let children = def_map[self.id]
.children
.values()
.map(|module_id| Module { id: def_map.module_id(*module_id) })
.map(|module_id| Module { id: *module_id })
.collect::<Vec<_>>();
children.into_iter()
}
@ -580,17 +580,17 @@ impl Module {
/// Finds a parent module.
pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
let def_map = self.id.def_map(db);
let parent_id = def_map.containing_module(self.id.local_id)?;
let parent_id = def_map.containing_module(self.id)?;
Some(Module { id: parent_id })
}
/// Finds nearest non-block ancestor `Module` (`self` included).
pub fn nearest_non_block_module(self, db: &dyn HirDatabase) -> Module {
let mut id = self.id;
while id.is_block_module() {
while id.is_block_module(db) {
id = id.containing_module(db).expect("block without parent module");
}
Module { id }
Module { id: unsafe { id.to_static() } }
}
pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
@ -609,7 +609,7 @@ impl Module {
db: &dyn HirDatabase,
visible_from: Option<Module>,
) -> Vec<(Name, ScopeDef)> {
self.id.def_map(db)[self.id.local_id]
self.id.def_map(db)[self.id]
.scope
.entries()
.filter_map(|(name, def)| {
@ -646,19 +646,19 @@ impl Module {
style_lints: bool,
) {
let _p = tracing::info_span!("diagnostics", name = ?self.name(db)).entered();
let edition = self.id.krate().data(db).edition;
let edition = self.id.krate(db).data(db).edition;
let def_map = self.id.def_map(db);
for diag in def_map.diagnostics() {
if diag.in_module != self.id.local_id {
if diag.in_module != self.id {
// FIXME: This is accidentally quadratic.
continue;
}
emit_def_diagnostic(db, acc, diag, edition, def_map.krate());
}
if !self.id.is_block_module() {
if !self.id.is_block_module(db) {
// These are reported by the body of block modules
let scope = &def_map[self.id.local_id].scope;
let scope = &def_map[self.id].scope;
scope.all_macro_calls().for_each(|it| macro_call_diagnostics(db, it, acc));
}
@ -666,7 +666,7 @@ impl Module {
match def {
ModuleDef::Module(m) => {
// Only add diagnostics from inline modules
if def_map[m.id.local_id].origin.is_inline() {
if def_map[m.id].origin.is_inline() {
m.diagnostics(db, acc, style_lints)
}
acc.extend(def.diagnostics(db, style_lints))
@ -765,7 +765,7 @@ impl Module {
}
self.legacy_macros(db).into_iter().for_each(|m| emit_macro_def_diagnostics(db, acc, m));
let interner = DbInterner::new_with(db, self.id.krate());
let interner = DbInterner::new_with(db, self.id.krate(db));
let infcx = interner.infer_ctxt().build(TypingMode::non_body_analysis());
let mut impl_assoc_items_scratch = vec![];
@ -790,7 +790,7 @@ impl Module {
let ast_id_map = db.ast_id_map(file_id);
for diag in impl_def.id.impl_items_with_diagnostics(db).1.iter() {
emit_def_diagnostic(db, acc, diag, edition, loc.container.krate());
emit_def_diagnostic(db, acc, diag, edition, loc.container.krate(db));
}
if impl_signature.target_trait.is_none()
@ -939,7 +939,7 @@ impl Module {
pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
let def_map = self.id.def_map(db);
let scope = &def_map[self.id.local_id].scope;
let scope = &def_map[self.id].scope;
scope
.declarations()
.map(ModuleDef::from)
@ -949,13 +949,13 @@ impl Module {
pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
let def_map = self.id.def_map(db);
let scope = &def_map[self.id.local_id].scope;
let scope = &def_map[self.id].scope;
scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
}
pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
let def_map = self.id.def_map(db);
def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
def_map[self.id].scope.impls().map(Impl::from).collect()
}
/// Finds a path that can be used to refer to the given item from within
@ -990,7 +990,7 @@ impl Module {
#[inline]
pub fn doc_keyword(self, db: &dyn HirDatabase) -> Option<Symbol> {
AttrFlags::doc_keyword(db, InternedModuleId::new(db, self.id))
AttrFlags::doc_keyword(db, self.id)
}
/// Whether it has `#[path = "..."]` attribute.
@ -1196,7 +1196,7 @@ fn precise_macro_call_location(
impl HasVisibility for Module {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let def_map = self.id.def_map(db);
let module_data = &def_map[self.id.local_id];
let module_data = &def_map[self.id];
module_data.visibility
}
}
@ -1541,7 +1541,7 @@ impl Enum {
pub fn variant_body_ty<'db>(self, db: &'db dyn HirDatabase) -> Type<'db> {
let interner = DbInterner::new_no_crate(db);
Type::new_for_crate(
self.id.lookup(db).container.krate(),
self.id.lookup(db).container.krate(db),
match EnumSignature::variant_body_type(db, self.id) {
layout::IntegerType::Pointer(sign) => match sign {
true => Ty::new_int(interner, rustc_type_ir::IntTy::Isize),
@ -1927,7 +1927,7 @@ impl DefWithBody {
pub fn debug_mir(self, db: &dyn HirDatabase) -> String {
let body = db.mir_body(self.id());
match body {
Ok(body) => body.pretty_print(db, self.module(db).krate().to_display_target(db)),
Ok(body) => body.pretty_print(db, self.module(db).krate(db).to_display_target(db)),
Err(e) => format!("error:\n{e:?}"),
}
}
@ -1938,7 +1938,7 @@ impl DefWithBody {
acc: &mut Vec<AnyDiagnostic<'db>>,
style_lints: bool,
) {
let krate = self.module(db).id.krate();
let krate = self.module(db).id.krate(db);
let (body, source_map) = db.body_with_source_map(self.into());
let sig_source_map = match self {
@ -1952,7 +1952,7 @@ impl DefWithBody {
};
for (_, def_map) in body.blocks(db) {
Module { id: def_map.module_id(DefMap::ROOT) }.diagnostics(db, acc, style_lints);
Module { id: def_map.root_module_id() }.diagnostics(db, acc, style_lints);
}
expr_store_diagnostics(db, acc, &source_map);
@ -2398,7 +2398,7 @@ impl Function {
/// is this a `fn main` or a function with an `export_name` of `main`?
pub fn is_main(self, db: &dyn HirDatabase) -> bool {
self.exported_main(db)
|| self.module(db).is_crate_root() && db.function_signature(self.id).name == sym::main
|| self.module(db).is_crate_root(db) && db.function_signature(self.id).name == sym::main
}
/// Is this a function with an `export_name` of `main`?
@ -2475,7 +2475,7 @@ impl Function {
GenericArgs::new_from_iter(interner, []),
ParamEnvAndCrate {
param_env: db.trait_environment(self.id.into()),
krate: self.id.module(db).krate(),
krate: self.id.module(db).krate(db),
},
)?;
let (result, output) = interpret_mir(db, body, false, None)?;
@ -2657,7 +2657,7 @@ impl ExternCrateDecl {
pub fn resolved_crate(self, db: &dyn HirDatabase) -> Option<Crate> {
let loc = self.id.lookup(db);
let krate = loc.container.krate();
let krate = loc.container.krate(db);
let name = self.name(db);
if name == sym::self_ {
Some(krate.into())
@ -3239,8 +3239,8 @@ impl ItemInNs {
/// Returns the crate defining this item (or `None` if `self` is built-in).
pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
match self {
ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
ItemInNs::Macros(id) => Some(id.module(db).krate()),
ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate(db)),
ItemInNs::Macros(id) => Some(id.module(db).krate(db)),
}
}
@ -4323,7 +4323,7 @@ impl Impl {
}
pub fn all_in_module(db: &dyn HirDatabase, module: Module) -> Vec<Impl> {
module.id.def_map(db)[module.id.local_id].scope.impls().map(Into::into).collect()
module.id.def_map(db)[module.id].scope.impls().map(Into::into).collect()
}
/// **Note:** This is an **approximation** that strives to give the *human-perceived notion* of an "impl for type",
@ -4348,15 +4348,13 @@ impl Impl {
if let Some(module) = method_resolution::simplified_type_module(db, &simplified_ty) {
InherentImpls::for_each_crate_and_block(
db,
module.krate(),
module.containing_block(),
module.krate(db),
module.block(db),
&mut |impls| extend_with_impls(impls.for_self_ty(&simplified_ty)),
);
std::iter::successors(module.containing_block(), |block| {
block.loc(db).module.containing_block()
})
.filter_map(|block| TraitImpls::for_block(db, block).as_deref())
.for_each(|impls| impls.for_self_ty(&simplified_ty, &mut extend_with_impls));
std::iter::successors(module.block(db), |block| block.module(db).block(db))
.filter_map(|block| TraitImpls::for_block(db, block).as_deref())
.for_each(|impls| impls.for_self_ty(&simplified_ty, &mut extend_with_impls));
for &krate in &**db.all_crates() {
TraitImpls::for_crate(db, krate)
.for_self_ty(&simplified_ty, &mut extend_with_impls);
@ -4376,10 +4374,10 @@ impl Impl {
let mut handle_impls = |impls: &TraitImpls| {
impls.for_trait(trait_.id, |impls| all.extend(impls.iter().copied().map(Impl::from)));
};
for krate in module.krate().transitive_rev_deps(db) {
for krate in module.krate(db).transitive_rev_deps(db) {
handle_impls(TraitImpls::for_crate(db, krate));
}
if let Some(block) = module.containing_block()
if let Some(block) = module.block(db)
&& let Some(impls) = TraitImpls::for_block(db, block)
{
handle_impls(impls);
@ -4431,7 +4429,7 @@ impl Impl {
MacroCallKind::Derive { ast_id, derive_attr_index, derive_index, .. } => {
let module_id = self.id.lookup(db).container;
(
crate_def_map(db, module_id.krate())[module_id.local_id]
module_id.def_map(db)[module_id]
.scope
.derive_macro_invoc(ast_id, derive_attr_index)?,
derive_index,
@ -5329,8 +5327,8 @@ impl<'db> Type<'db> {
if let Some(module) = method_resolution::simplified_type_module(db, &simplified_type) {
InherentImpls::for_each_crate_and_block(
db,
module.krate(),
module.containing_block(),
module.krate(db),
module.block(db),
&mut |impls| {
handle_impls(impls.for_self_ty(&simplified_type));
},
@ -5466,7 +5464,7 @@ impl<'db> Type<'db> {
f: impl FnOnce(&MethodResolutionContext<'_, 'db>) -> R,
) -> R {
let module = resolver.module();
let interner = DbInterner::new_with(db, module.krate());
let interner = DbInterner::new_with(db, module.krate(db));
let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
let unstable_features =
MethodResolutionUnstableFeatures::from_def_map(resolver.top_level_def_map());
@ -6140,12 +6138,12 @@ impl ScopeDef {
pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
match self {
ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate(db)),
ScopeDef::GenericParam(it) => Some(it.module(db).krate(db)),
ScopeDef::ImplSelfType(_) => None,
ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
ScopeDef::Local(it) => Some(it.module(db).krate()),
ScopeDef::Label(it) => Some(it.module(db).krate()),
ScopeDef::AdtSelfType(it) => Some(it.module(db).krate(db)),
ScopeDef::Local(it) => Some(it.module(db).krate(db)),
ScopeDef::Label(it) => Some(it.module(db).krate(db)),
ScopeDef::Unknown => None,
}
}
@ -6205,61 +6203,61 @@ pub trait HasCrate {
impl<T: hir_def::HasModule> HasCrate for T {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate().into()
self.module(db).krate(db).into()
}
}
impl HasCrate for AssocItem {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Struct {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Union {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Enum {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Field {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.parent_def(db).module(db).krate()
self.parent_def(db).module(db).krate(db)
}
}
impl HasCrate for Variant {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Function {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Const {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for TypeAlias {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
@ -6271,37 +6269,37 @@ impl HasCrate for Type<'_> {
impl HasCrate for Macro {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Trait {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Static {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Adt {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Impl {
fn krate(&self, db: &dyn HirDatabase) -> Crate {
self.module(db).krate()
self.module(db).krate(db)
}
}
impl HasCrate for Module {
fn krate(&self, _: &dyn HirDatabase) -> Crate {
Module::krate(*self)
fn krate(&self, db: &dyn HirDatabase) -> Crate {
Module::krate(*self, db)
}
}
@ -6319,8 +6317,8 @@ impl HasContainer for Module {
fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
// FIXME: handle block expressions as modules (their parent is in a different DefMap)
let def_map = self.id.def_map(db);
match def_map[self.id.local_id].parent {
Some(parent_id) => ItemContainer::Module(Module { id: def_map.module_id(parent_id) }),
match def_map[self.id].parent {
Some(parent_id) => ItemContainer::Module(Module { id: parent_id }),
None => ItemContainer::Crate(def_map.krate().into()),
}
}
@ -6479,7 +6477,7 @@ pub fn resolve_absolute_path<'a, I: Iterator<Item = Symbol> + Clone + 'a>(
.filter_map(|&krate| {
let segments = segments.clone();
let mut def_map = crate_def_map(db, krate);
let mut module = &def_map[DefMap::ROOT];
let mut module = &def_map[def_map.root_module_id()];
let mut segments = segments.with_position().peekable();
while let Some((_, segment)) = segments.next_if(|&(position, _)| {
!matches!(position, itertools::Position::Last | itertools::Position::Only)
@ -6493,7 +6491,7 @@ pub fn resolve_absolute_path<'a, I: Iterator<Item = Symbol> + Clone + 'a>(
_ => None,
})?;
def_map = res.def_map(db);
module = &def_map[res.local_id];
module = &def_map[res];
}
let (_, item_name) = segments.next()?;
let res = module.scope.get(&Name::new_symbol_root(item_name));

View file

@ -39,8 +39,8 @@ use smallvec::{SmallVec, smallvec};
use span::{FileId, SyntaxContext};
use stdx::{TupleExt, always};
use syntax::{
AstNode, AstToken, Direction, SyntaxKind, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange,
TextSize,
AstNode, AstToken, Direction, SmolStr, SmolStrBuilder, SyntaxElement, SyntaxKind, SyntaxNode,
SyntaxNodePtr, SyntaxToken, T, TextRange, TextSize,
algo::skip_trivia_token,
ast::{self, HasAttrs as _, HasGenericParams},
};
@ -174,6 +174,15 @@ impl<'db, DB: ?Sized> ops::Deref for Semantics<'db, DB> {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LintAttr {
Allow,
Expect,
Warn,
Deny,
Forbid,
}
// Note: while this variant of `Semantics<'_, _>` might seem unused, as it does not
// find actual use within the rust-analyzer project itself, it exists to enable the use
// within e.g. tracked salsa functions in third-party crates that build upon `ra_ap_hir`.
@ -254,6 +263,59 @@ impl<DB: HirDatabase + ?Sized> Semantics<'_, DB> {
.filter_map(ast::NameLike::cast)
}
pub fn lint_attrs(
&self,
krate: Crate,
item: ast::AnyHasAttrs,
) -> impl Iterator<Item = (LintAttr, SmolStr)> {
let mut cfg_options = None;
let cfg_options = || *cfg_options.get_or_insert_with(|| krate.id.cfg_options(self.db));
let mut result = Vec::new();
hir_expand::attrs::expand_cfg_attr::<Infallible>(
ast::attrs_including_inner(&item),
cfg_options,
|attr, _, _, _| {
let hir_expand::attrs::Meta::TokenTree { path, tt } = attr else {
return ControlFlow::Continue(());
};
if path.segments.len() != 1 {
return ControlFlow::Continue(());
}
let lint_attr = match path.segments[0].text() {
"allow" => LintAttr::Allow,
"expect" => LintAttr::Expect,
"warn" => LintAttr::Warn,
"deny" => LintAttr::Deny,
"forbid" => LintAttr::Forbid,
_ => return ControlFlow::Continue(()),
};
let mut lint = SmolStrBuilder::new();
for token in
tt.syntax().children_with_tokens().filter_map(SyntaxElement::into_token)
{
match token.kind() {
T![:] | T![::] => lint.push_str(token.text()),
kind if kind.is_any_identifier() => lint.push_str(token.text()),
T![,] => {
let lint = mem::replace(&mut lint, SmolStrBuilder::new()).finish();
if !lint.is_empty() {
result.push((lint_attr, lint));
}
}
_ => {}
}
}
let lint = lint.finish();
if !lint.is_empty() {
result.push((lint_attr, lint));
}
ControlFlow::Continue(())
},
);
result.into_iter()
}
pub fn resolve_range_pat(&self, range_pat: &ast::RangePat) -> Option<Struct> {
self.imp.resolve_range_pat(range_pat).map(Struct::from)
}
@ -380,13 +442,13 @@ impl<'db> SemanticsImpl<'db> {
/// If not crate is found for the file, try to return the last crate in topological order.
pub fn first_crate(&self, file: FileId) -> Option<Crate> {
match self.file_to_module_defs(file).next() {
Some(module) => Some(module.krate()),
Some(module) => Some(module.krate(self.db)),
None => self.db.all_crates().last().copied().map(Into::into),
}
}
pub fn attach_first_edition_opt(&self, file: FileId) -> Option<EditionedFileId> {
let krate = self.file_to_module_defs(file).next()?.krate();
let krate = self.file_to_module_defs(file).next()?.krate(self.db);
Some(EditionedFileId::new(self.db, file, krate.edition(self.db), krate.id))
}
@ -416,8 +478,8 @@ impl<'db> SemanticsImpl<'db> {
match file_id {
HirFileId::FileId(file_id) => {
let module = self.file_to_module_defs(file_id.file_id(self.db)).next()?;
let def_map = crate_def_map(self.db, module.krate().id);
match def_map[module.id.local_id].origin {
let def_map = crate_def_map(self.db, module.krate(self.db).id);
match def_map[module.id].origin {
ModuleOrigin::CrateRoot { .. } => None,
ModuleOrigin::File { declaration, declaration_tree_id, .. } => {
let file_id = declaration_tree_id.file_id();
@ -443,7 +505,7 @@ impl<'db> SemanticsImpl<'db> {
/// the `SyntaxNode` of the *definition* file, not of the *declaration*.
pub fn module_definition_node(&self, module: Module) -> InFile<SyntaxNode> {
let def_map = module.id.def_map(self.db);
let definition = def_map[module.id.local_id].origin.definition_source(self.db);
let definition = def_map[module.id].origin.definition_source(self.db);
let definition = definition.map(|it| it.node());
let root_node = find_root(&definition.value);
self.cache(root_node, definition.file_id);
@ -472,7 +534,7 @@ impl<'db> SemanticsImpl<'db> {
let file_id = self.find_file(attr.syntax()).file_id;
let krate = match file_id {
HirFileId::FileId(file_id) => {
self.file_to_module_defs(file_id.file_id(self.db)).next()?.krate().id
self.file_to_module_defs(file_id.file_id(self.db)).next()?.krate(self.db).id
}
HirFileId::MacroFile(macro_file) => self.db.lookup_intern_macro_call(macro_file).krate,
};

View file

@ -20,7 +20,6 @@ use hir_def::{
},
hir::generics::GenericParams,
item_scope::ItemScope,
nameres::DefMap,
src::{HasChildSource, HasSource},
};
@ -87,7 +86,7 @@ impl ChildBySource for ImplId {
impl ChildBySource for ModuleId {
fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, file_id: HirFileId) {
let def_map = self.def_map(db);
let module_data = &def_map[self.local_id];
let module_data = &def_map[*self];
module_data.scope.child_by_source_to(db, res, file_id);
}
}
@ -226,8 +225,8 @@ impl ChildBySource for DefWithBodyId {
for (block, def_map) in body.blocks(db) {
// All block expressions are merged into the same map, because they logically all add
// inner items to the containing `DefWithBodyId`.
def_map[DefMap::ROOT].scope.child_by_source_to(db, res, file_id);
res[keys::BLOCK].insert(block.lookup(db).ast_id.to_ptr(db), block);
def_map[def_map.root].scope.child_by_source_to(db, res, file_id);
res[keys::BLOCK].insert(block.ast_id(db).to_ptr(db), block);
}
}
}

View file

@ -183,11 +183,7 @@ impl SourceToDefCtx<'_, '_> {
// Note: `mod` declarations in block modules cannot be supported here
let crate_def_map = crate_def_map(self.db, crate_id);
let n_mods = mods.len();
let modules = |file| {
crate_def_map
.modules_for_file(self.db, file)
.map(|local_id| crate_def_map.module_id(local_id))
};
let modules = |file| crate_def_map.modules_for_file(self.db, file);
mods.extend(modules(file));
if mods.len() == n_mods {
mods.extend(
@ -239,8 +235,8 @@ impl SourceToDefCtx<'_, '_> {
let child_name = src.value.name()?.as_name();
let def_map = parent_module.def_map(self.db);
let &child_id = def_map[parent_module.local_id].children.get(&child_name)?;
Some(def_map.module_id(child_id))
let &child_id = def_map[parent_module].children.get(&child_name)?;
Some(child_id)
}
pub(super) fn source_file_to_def(&mut self, src: InFile<&ast::SourceFile>) -> Option<ModuleId> {

View file

@ -255,7 +255,7 @@ impl<'a> SymbolCollector<'a> {
};
let def_map = module_id.def_map(self.db);
let scope = &def_map[module_id.local_id].scope;
let scope = &def_map[module_id].scope;
for impl_id in scope.impls() {
self.collect_from_impl(impl_id);
@ -329,10 +329,7 @@ impl<'a> SymbolCollector<'a> {
// Descend into the blocks and enqueue collection of all modules within.
for (_, def_map) in body.blocks(self.db) {
for (id, _) in def_map.modules() {
self.work.push(SymbolCollectorWork {
module_id: def_map.module_id(id),
parent: name.clone(),
});
self.work.push(SymbolCollectorWork { module_id: id, parent: name.clone() });
}
}
}
@ -451,7 +448,7 @@ impl<'a> SymbolCollector<'a> {
fn push_module(&mut self, module_id: ModuleId, name: &Name) {
let def_map = module_id.def_map(self.db);
let module_data = &def_map[module_id.local_id];
let module_data = &def_map[module_id];
let Some(declaration) = module_data.origin.declaration() else { return };
let module = declaration.to_node(self.db);
let Some(name_node) = module.name() else { return };

View file

@ -762,7 +762,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>(
.filter(|_| should_continue())
.map(|params| {
let tys: Vec<Type<'_>> = params.iter().map(|it| it.ty(db)).collect();
let tuple_ty = Type::new_tuple(module.krate().into(), &tys);
let tuple_ty = Type::new_tuple(module.krate(db).into(), &tys);
let expr = Expr::Tuple { ty: tuple_ty.clone(), params };
lookup.insert(tuple_ty, iter::once(expr.clone()));

View file

@ -130,7 +130,7 @@ fn add_missing_impl_members_inner(
if let IgnoreAssocItems::DocHiddenAttrPresent = ignore_items {
// Relax condition for local crates.
let db = ctx.db();
if trait_.module(db).krate().origin(db).is_local() {
if trait_.module(db).krate(db).origin(db).is_local() {
ign_item = IgnoreAssocItems::No;
}
}

View file

@ -92,24 +92,25 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
bool,
bool,
) = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr, self_ty.as_ref()) {
let is_non_exhaustive = enum_def.is_non_exhaustive(ctx.db(), module.krate());
let is_non_exhaustive = enum_def.is_non_exhaustive(ctx.db(), module.krate(ctx.db()));
let variants = enum_def.variants(ctx.db());
let has_hidden_variants =
variants.iter().any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
let has_hidden_variants = variants
.iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate(ctx.db())));
let missing_pats = variants
.into_iter()
.filter_map(|variant| {
Some((
build_pat(ctx, &make, module, variant, cfg)?,
variant.should_be_hidden(ctx.db(), module.krate()),
variant.should_be_hidden(ctx.db(), module.krate(ctx.db())),
))
})
.filter(|(variant_pat, _)| is_variant_missing(&top_lvl_pats, variant_pat));
let option_enum = FamousDefs(&ctx.sema, module.krate()).core_option_Option();
let option_enum = FamousDefs(&ctx.sema, module.krate(ctx.db())).core_option_Option();
let missing_pats: Box<dyn Iterator<Item = _>> = if matches!(enum_def, ExtendedEnum::Enum { enum_: e, .. } if Some(e) == option_enum)
{
// Match `Some` variant first.
@ -120,8 +121,9 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
};
(missing_pats.peekable(), is_non_exhaustive, has_hidden_variants)
} else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr, self_ty.as_ref()) {
let is_non_exhaustive =
enum_defs.iter().any(|enum_def| enum_def.is_non_exhaustive(ctx.db(), module.krate()));
let is_non_exhaustive = enum_defs
.iter()
.any(|enum_def| enum_def.is_non_exhaustive(ctx.db(), module.krate(ctx.db())));
let mut n_arms = 1;
let variants_of_enums: Vec<Vec<ExtendedVariant>> = enum_defs
@ -145,7 +147,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
let has_hidden_variants = variants_of_enums
.iter()
.flatten()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate(ctx.db())));
let missing_pats = variants_of_enums
.into_iter()
@ -154,7 +156,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
.map(|variants| {
let is_hidden = variants
.iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate(ctx.db())));
let patterns = variants
.into_iter()
.filter_map(|variant| build_pat(ctx, &make, module, variant, cfg));
@ -170,15 +172,16 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
} else if let Some((enum_def, len)) =
resolve_array_of_enum_def(&ctx.sema, &expr, self_ty.as_ref())
{
let is_non_exhaustive = enum_def.is_non_exhaustive(ctx.db(), module.krate());
let is_non_exhaustive = enum_def.is_non_exhaustive(ctx.db(), module.krate(ctx.db()));
let variants = enum_def.variants(ctx.db());
if len.pow(variants.len() as u32) > 256 {
return None;
}
let has_hidden_variants =
variants.iter().any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
let has_hidden_variants = variants
.iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate(ctx.db())));
let variants_of_enums = vec![variants; len];
@ -189,7 +192,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
.map(|variants| {
let is_hidden = variants
.iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate(ctx.db())));
let patterns = variants
.into_iter()
.filter_map(|variant| build_pat(ctx, &make, module, variant, cfg));
@ -401,7 +404,7 @@ impl ExtendedVariant {
fn should_be_hidden(self, db: &RootDatabase, krate: Crate) -> bool {
match self {
ExtendedVariant::Variant { variant: var, .. } => {
var.attrs(db).is_doc_hidden() && var.module(db).krate() != krate
var.attrs(db).is_doc_hidden() && var.module(db).krate(db) != krate
}
_ => false,
}
@ -424,7 +427,7 @@ impl ExtendedEnum {
fn is_non_exhaustive(&self, db: &RootDatabase, krate: Crate) -> bool {
match self {
ExtendedEnum::Enum { enum_: e, .. } => {
e.attrs(db).is_non_exhaustive() && e.module(db).krate() != krate
e.attrs(db).is_non_exhaustive() && e.module(db).krate(db) != krate
}
_ => false,
}
@ -502,7 +505,7 @@ fn build_pat(
let db = ctx.db();
match var {
ExtendedVariant::Variant { variant: var, use_self } => {
let edition = module.krate().edition(db);
let edition = module.krate(db).edition(db);
let path = if use_self {
make::path_from_segments(
[

View file

@ -260,7 +260,7 @@ fn validate_method_call_expr(
let receiver = method_call.receiver()?;
let it_type = sema.type_of_expr(&receiver)?.adjusted();
let module = sema.scope(receiver.syntax())?.module();
let krate = module.krate();
let krate = module.krate(ctx.db());
let iter_trait = FamousDefs(sema, krate).core_iter_Iterator()?;
it_type.impls_trait(sema.db, iter_trait, &[]).then_some((name_ref, arg_expr))

View file

@ -114,7 +114,8 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
proposed_imports.sort_by_key(|import| {
Reverse(relevance_score(ctx, import, expected.as_ref(), current_module.as_ref()))
});
let edition = current_module.map(|it| it.krate().edition(ctx.db())).unwrap_or(Edition::CURRENT);
let edition =
current_module.map(|it| it.krate(ctx.db()).edition(ctx.db())).unwrap_or(Edition::CURRENT);
let group_label = group_label(import_assets.import_candidate());
for import in proposed_imports {
@ -316,11 +317,11 @@ fn module_distance_heuristic(db: &dyn HirDatabase, current: &Module, item: &Modu
let distinct_length = current_path.len() + item_path.len() - 2 * prefix_length;
// cost of importing from another crate
let crate_boundary_cost = if current.krate() == item.krate() {
let crate_boundary_cost = if current.krate(db) == item.krate(db) {
0
} else if item.krate().origin(db).is_local() {
} else if item.krate(db).origin(db).is_local() {
2
} else if item.krate().is_builtin(db) {
} else if item.krate(db).is_builtin(db) {
3
} else {
4

View file

@ -329,7 +329,7 @@ fn augment_references_with_imports(
) -> Vec<FileReferenceWithImport> {
let mut visited_modules = FxHashSet::default();
let edition = target_module.krate().edition(ctx.db());
let edition = target_module.krate(ctx.db()).edition(ctx.db());
references
.into_iter()
.filter_map(|FileReference { range, name, .. }| {
@ -345,8 +345,9 @@ fn augment_references_with_imports(
ImportScope::find_insert_use_container(name.syntax(), &ctx.sema).and_then(
|import_scope| {
let cfg =
ctx.config.find_path_config(ctx.sema.is_nightly(target_module.krate()));
let cfg = ctx.config.find_path_config(
ctx.sema.is_nightly(target_module.krate(ctx.sema.db)),
);
let path = ref_module
.find_use_path(
ctx.sema.db,

View file

@ -150,7 +150,7 @@ fn impls_core_iter(sema: &hir::Semantics<'_, ide_db::RootDatabase>, iterable: &a
let module = sema.scope(iterable.syntax())?.module();
let krate = module.krate();
let krate = module.krate(sema.db);
let iter_trait = FamousDefs(sema, krate).core_iter_Iterator()?;
cov_mark::hit!(test_already_impls_iterator);
Some(it_typ.impls_trait(sema.db, iter_trait, &[]))

View file

@ -64,7 +64,7 @@ pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_>
let tail_expr = from_fn.body()?.tail_expr()?;
if resolve_target_trait(&ctx.sema, &impl_)?
!= FamousDefs(&ctx.sema, module.krate()).core_convert_From()?
!= FamousDefs(&ctx.sema, module.krate(ctx.db())).core_convert_From()?
{
return None;
}

View file

@ -39,11 +39,11 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) -
let module = ctx.sema.scope(impl_.syntax())?.module();
let trait_ = resolve_target_trait(&ctx.sema, &impl_)?;
if trait_ != FamousDefs(&ctx.sema, module.krate()).core_convert_Into()? {
if trait_ != FamousDefs(&ctx.sema, module.krate(ctx.db())).core_convert_Into()? {
return None;
}
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
let src_type_path = {
let src_type_path = src_type.syntax().descendants().find_map(ast::Path::cast)?;
@ -53,7 +53,7 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) -
};
mod_path_to_ast(
&module.find_path(ctx.db(), src_type_def, cfg)?,
module.krate().edition(ctx.db()),
module.krate(ctx.db()).edition(ctx.db()),
)
};

View file

@ -186,7 +186,7 @@ fn impls_core_iter(sema: &hir::Semantics<'_, ide_db::RootDatabase>, iterable: &a
let module = sema.scope(iterable.syntax())?.module();
let krate = module.krate();
let krate = module.krate(sema.db);
let iter_trait = FamousDefs(sema, krate).core_iter_Iterator()?;
cov_mark::hit!(test_already_impls_iterator);
Some(it_typ.impls_trait(sema.db, iter_trait, &[]))
@ -214,7 +214,7 @@ fn validate_method_call_expr(
let it_type = sema.type_of_expr(&receiver)?.adjusted();
let module = sema.scope(receiver.syntax())?.module();
let krate = module.krate();
let krate = module.krate(ctx.db());
let iter_trait = FamousDefs(sema, krate).core_iter_Iterator()?;
it_type.impls_trait(sema.db, iter_trait, &[]).then_some((expr, receiver))

View file

@ -199,7 +199,8 @@ fn augment_references_with_imports(
{
visited_modules.insert(ref_module);
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(ref_module.krate()));
let cfg =
ctx.config.find_path_config(ctx.sema.is_nightly(ref_module.krate(ctx.sema.db)));
let import_scope =
ImportScope::find_insert_use_container(new_name.syntax(), &ctx.sema);
let path = ref_module
@ -211,7 +212,10 @@ fn augment_references_with_imports(
)
.map(|mod_path| {
make::path_concat(
mod_path_to_ast(&mod_path, target_module.krate().edition(ctx.db())),
mod_path_to_ast(
&mod_path,
target_module.krate(ctx.db()).edition(ctx.db()),
),
make::path_from_text(struct_name),
)
});

View file

@ -88,13 +88,14 @@ fn collect_data(ident_pat: ast::IdentPat, ctx: &AssistContext<'_>) -> Option<Str
let hir::Adt::Struct(struct_type) = ty.strip_references().as_adt()? else { return None };
let module = ctx.sema.scope(ident_pat.syntax())?.module();
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.db())));
let struct_def = hir::ModuleDef::from(struct_type);
let kind = struct_type.kind(ctx.db());
let struct_def_path = module.find_path(ctx.db(), struct_def, cfg)?;
let is_non_exhaustive = struct_def.attrs(ctx.db())?.is_non_exhaustive();
let is_foreign_crate = struct_def.module(ctx.db()).is_some_and(|m| m.krate() != module.krate());
let is_foreign_crate =
struct_def.module(ctx.db()).is_some_and(|m| m.krate(ctx.db()) != module.krate(ctx.db()));
let fields = struct_type.fields(ctx.db());
let n_fields = fields.len();
@ -148,7 +149,7 @@ fn collect_data(ident_pat: ast::IdentPat, ctx: &AssistContext<'_>) -> Option<Str
names_in_scope,
need_record_field_name,
is_ref,
edition: module.krate().edition(ctx.db()),
edition: module.krate(ctx.db()).edition(ctx.db()),
})
}

View file

@ -152,8 +152,10 @@ fn build_expanded_import(
(false, current_module)
} else {
match get_export_visibility_kind(&use_item) {
VisibilityKind::Pub => (true, current_module.krate().root_module()),
VisibilityKind::PubCrate => (false, current_module.krate().root_module()),
VisibilityKind::Pub => (true, current_module.krate(ctx.db()).root_module(ctx.db())),
VisibilityKind::PubCrate => {
(false, current_module.krate(ctx.db()).root_module(ctx.db()))
}
_ => (false, current_module),
}
};
@ -167,7 +169,7 @@ fn build_expanded_import(
let names_to_import = find_names_to_import(filtered_defs, imported_defs);
let expanded = make::use_tree_list(names_to_import.iter().map(|n| {
let path = make::ext::ident_path(
&n.display(ctx.db(), current_module.krate().edition(ctx.db())).to_string(),
&n.display(ctx.db(), current_module.krate(ctx.db()).edition(ctx.db())).to_string(),
);
make::use_tree(path, None, None, false)
}))

View file

@ -206,10 +206,11 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
{
let scope = builder.make_import_scope_mut(scope);
let control_flow_enum =
FamousDefs(&ctx.sema, module.krate()).core_ops_ControlFlow();
FamousDefs(&ctx.sema, module.krate(ctx.db())).core_ops_ControlFlow();
if let Some(control_flow_enum) = control_flow_enum {
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let cfg =
ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
let mod_path = module.find_use_path(
ctx.sema.db,
ModuleDef::from(control_flow_enum),

View file

@ -400,7 +400,8 @@ fn process_references(
let segment = builder.make_mut(segment);
let scope_node = builder.make_syntax_mut(scope_node);
if !visited_modules.contains(&module) {
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let cfg =
ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
let mod_path = module.find_use_path(
ctx.sema.db,
*enum_module_def,

View file

@ -59,7 +59,7 @@ fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext<'_>)
let (vis_owner, target, target_file, target_name) = target_data_for_def(ctx.db(), def)?;
let missing_visibility = if current_module.krate() == target_module.krate() {
let missing_visibility = if current_module.krate(ctx.db()) == target_module.krate(ctx.db()) {
make::visibility_pub_crate()
} else {
make::visibility_pub()
@ -70,7 +70,7 @@ fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext<'_>)
Some(name) => {
format!(
"Change visibility of {} to {missing_visibility}",
name.display(ctx.db(), current_module.krate().edition(ctx.db()))
name.display(ctx.db(), current_module.krate(ctx.db()).edition(ctx.db()))
)
}
};

View file

@ -75,7 +75,7 @@ fn existing_default_impl(
) -> Option<()> {
let variant = sema.to_def(variant)?;
let enum_ = variant.parent_enum(sema.db);
let krate = enum_.module(sema.db).krate();
let krate = enum_.module(sema.db).krate(sema.db);
let default_trait = FamousDefs(sema, krate).core_default_Default()?;
let enum_type = enum_.ty(sema.db);

View file

@ -137,7 +137,7 @@ fn is_default_implemented(ctx: &AssistContext<'_>, impl_: &Impl) -> bool {
};
let ty = impl_def.self_ty(db);
let krate = impl_def.module(db).krate();
let krate = impl_def.module(db).krate(ctx.db());
let default = FamousDefs(&ctx.sema, krate).core_default_Default();
let default_trait = match default {
Some(value) => value,

View file

@ -57,7 +57,7 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
let strukt_name = strukt.name()?;
let current_module = ctx.sema.scope(strukt.syntax())?.module();
let current_edition = current_module.krate().edition(ctx.db());
let current_edition = current_module.krate(ctx.db()).edition(ctx.db());
let (field_name, field_ty, target) = match ctx.find_node_at_offset::<ast::RecordField>() {
Some(field) => {

View file

@ -124,7 +124,7 @@ impl Field {
let db = ctx.sema.db;
let module = ctx.sema.file_to_module_def(ctx.vfs_file_id())?;
let edition = module.krate().edition(ctx.db());
let edition = module.krate(ctx.db()).edition(ctx.db());
let (name, range, ty) = match f {
Either::Left(f) => {

View file

@ -57,8 +57,8 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
};
let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.db())));
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate(ctx.db()))?;
let trait_path = module.find_path(ctx.db(), ModuleDef::Trait(trait_), cfg)?;
let field_type = field.ty()?;
@ -77,7 +77,7 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
field_name.syntax(),
deref_type_to_generate,
trait_path,
module.krate().edition(ctx.db()),
module.krate(ctx.db()).edition(ctx.db()),
)
},
)
@ -99,8 +99,8 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
};
let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate(ctx.db()))?;
let trait_path = module.find_path(ctx.db(), ModuleDef::Trait(trait_), cfg)?;
let field_type = field.ty()?;
@ -118,7 +118,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
field_list_index,
deref_type_to_generate,
trait_path,
module.krate().edition(ctx.db()),
module.krate(ctx.db()).edition(ctx.db()),
)
},
)
@ -163,7 +163,7 @@ fn existing_deref_impl(
strukt: &ast::Struct,
) -> Option<DerefType> {
let strukt = sema.to_def(strukt)?;
let krate = strukt.module(sema.db).krate();
let krate = strukt.module(sema.db).krate(sema.db);
let deref_trait = FamousDefs(sema, krate).core_ops_Deref()?;
let deref_mut_trait = FamousDefs(sema, krate).core_ops_DerefMut()?;

View file

@ -121,7 +121,7 @@ fn existing_from_impl(
) -> Option<()> {
let db = sema.db;
let variant = sema.to_def(variant)?;
let krate = variant.module(db).krate();
let krate = variant.module(db).krate(db);
let from_trait = FamousDefs(sema, krate).core_convert_From()?;
let interner = DbInterner::new_with(db, krate.base());
use hir::next_solver::infer::DbInternerInferExt;

View file

@ -71,7 +71,7 @@ fn gen_fn(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
fn_target_info(ctx, path, &call, fn_name)?;
if let Some(m) = target_module
&& !is_editable_crate(m.krate(), ctx.db())
&& !is_editable_crate(m.krate(ctx.db()), ctx.db())
{
return None;
}
@ -143,7 +143,7 @@ fn gen_method(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let adt = receiver_ty.as_adt()?;
let target_module = adt.module(ctx.sema.db);
if !is_editable_crate(target_module.krate(), ctx.db()) {
if !is_editable_crate(target_module.krate(ctx.db()), ctx.db()) {
return None;
}
@ -241,7 +241,7 @@ impl FunctionBuilder {
) -> Option<Self> {
let target_module =
target_module.or_else(|| ctx.sema.scope(target.syntax()).map(|it| it.module()))?;
let target_edition = target_module.krate().edition(ctx.db());
let target_edition = target_module.krate(ctx.db()).edition(ctx.db());
let current_module = ctx.sema.scope(call.syntax())?.module();
let visibility = calculate_necessary_visibility(current_module, target_module, ctx);
@ -311,7 +311,7 @@ impl FunctionBuilder {
target_module: Module,
target: GeneratedFunctionTarget,
) -> Option<Self> {
let target_edition = target_module.krate().edition(ctx.db());
let target_edition = target_module.krate(ctx.db()).edition(ctx.db());
let current_module = ctx.sema.scope(call.syntax())?.module();
let visibility = calculate_necessary_visibility(current_module, target_module, ctx);
@ -546,7 +546,7 @@ fn assoc_fn_target_info(
let current_module = ctx.sema.scope(call.syntax())?.module();
let module = adt.module(ctx.sema.db);
let target_module = if current_module == module { None } else { Some(module) };
if current_module.krate() != module.krate() {
if current_module.krate(ctx.db()) != module.krate(ctx.db()) {
return None;
}
let (impl_, file) = get_adt_source(ctx, &adt, fn_name)?;
@ -1149,7 +1149,10 @@ fn fn_arg_type(
convert_reference_type(ty.strip_references(), ctx.db(), famous_defs)
.map(|conversion| {
conversion
.convert_type(ctx.db(), target_module.krate().to_display_target(ctx.db()))
.convert_type(
ctx.db(),
target_module.krate(ctx.db()).to_display_target(ctx.db()),
)
.to_string()
})
.or_else(|| ty.display_source_code(ctx.db(), target_module.into(), true).ok())
@ -1235,7 +1238,7 @@ fn calculate_necessary_visibility(
let current_module = current_module.nearest_non_block_module(db);
let target_module = target_module.nearest_non_block_module(db);
if target_module.krate() != current_module.krate() {
if target_module.krate(ctx.db()) != current_module.krate(ctx.db()) {
Visibility::Pub
} else if current_module.path_to_root(db).contains(&target_module) {
Visibility::None

View file

@ -77,14 +77,16 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(current_module.krate()));
let cfg = ctx
.config
.find_path_config(ctx.sema.is_nightly(current_module.krate(ctx.sema.db)));
let type_path = current_module.find_path(
ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?,
cfg,
)?;
let edition = current_module.krate().edition(ctx.db());
let edition = current_module.krate(ctx.db()).edition(ctx.db());
let expr = use_trivial_constructor(
ctx.sema.db,

View file

@ -178,7 +178,7 @@ fn make_constructors(
types: &[ast::Type],
) -> Vec<Option<ast::Expr>> {
let (db, sema) = (ctx.db(), &ctx.sema);
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
types
.iter()
.map(|ty| {
@ -187,7 +187,7 @@ fn make_constructors(
return Some(make::expr_tuple([]).into());
}
let item_in_ns = ModuleDef::Adt(ty.as_adt()?).into();
let edition = module.krate().edition(db);
let edition = module.krate(db).edition(db);
let ty_path = module.find_path(db, item_for_path_search(db, item_in_ns)?, cfg)?;

View file

@ -110,7 +110,7 @@ pub(crate) fn inline_into_callers(acc: &mut Assists, ctx: &AssistContext<'_>) ->
let mut inline_refs_for_file = |file_id: EditionedFileId, refs: Vec<FileReference>| {
let file_id = file_id.file_id(ctx.db());
builder.edit_file(file_id);
let call_krate = ctx.sema.file_to_module_def(file_id).map(|it| it.krate());
let call_krate = ctx.sema.file_to_module_def(file_id).map(|it| it.krate(ctx.db()));
let count = refs.len();
// The collects are required as we are otherwise iterating while mutating 🙅‍♀️🙅‍♂️
let (name_refs, name_refs_use) = split_refs_and_uses(builder, refs, Some);
@ -196,7 +196,7 @@ pub(crate) fn inline_call(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
let name_ref: ast::NameRef = ctx.find_node_at_offset()?;
let call_info = CallInfo::from_name_ref(
name_ref.clone(),
ctx.sema.file_to_module_def(ctx.vfs_file_id())?.krate().into(),
ctx.sema.file_to_module_def(ctx.vfs_file_id())?.krate(ctx.db()).into(),
)?;
let (function, label) = match &call_info.node {
ast::CallableExpr::Call(call) => {

View file

@ -38,7 +38,7 @@ use crate::{AssistContext, AssistId, Assists};
pub(crate) fn inline_macro(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let unexpanded = ctx.find_node_at_offset::<ast::MacroCall>()?;
let macro_call = ctx.sema.to_def(&unexpanded)?;
let target_crate_id = ctx.sema.file_to_module_def(ctx.vfs_file_id())?.krate().into();
let target_crate_id = ctx.sema.file_to_module_def(ctx.vfs_file_id())?.krate(ctx.db()).into();
let text_range = unexpanded.syntax().text_range();
acc.add(

View file

@ -42,10 +42,10 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) ->
let resolved_call = ctx.sema.resolve_method_call(&call)?;
let current_module = ctx.sema.scope(call.syntax())?.module();
let current_edition = current_module.krate().edition(ctx.db());
let current_edition = current_module.krate(ctx.db()).edition(ctx.db());
let target_module_def = ModuleDef::from(resolved_call);
let item_in_ns = ItemInNs::from(target_module_def);
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(current_module.krate()));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(current_module.krate(ctx.sema.db)));
let receiver_path = current_module.find_path(
ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?,

View file

@ -82,7 +82,7 @@ pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
proposed_imports.dedup_by(|a, b| a.import_path == b.import_path);
let current_edition =
current_module.map(|it| it.krate().edition(ctx.db())).unwrap_or(Edition::CURRENT);
current_module.map(|it| it.krate(ctx.db()).edition(ctx.db())).unwrap_or(Edition::CURRENT);
// prioritize more relevant imports
proposed_imports.sort_by_key(|import| {
Reverse(super::auto_import::relevance_score(

View file

@ -69,7 +69,7 @@ pub(crate) fn replace_derive_with_manual_impl(
let args = attr.token_tree()?;
let current_module = ctx.sema.scope(adt.syntax())?.module();
let current_crate = current_module.krate();
let current_crate = current_module.krate(ctx.db());
let current_edition = current_crate.edition(ctx.db());
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(current_crate));
@ -193,7 +193,7 @@ fn impl_def_from_trait(
let target_scope = sema.scope(annotated_name.syntax())?;
// Keep assoc items of local crates even if they have #[doc(hidden)] attr.
let ignore_items = if trait_.module(sema.db).krate().origin(sema.db).is_local() {
let ignore_items = if trait_.module(sema.db).krate(sema.db).origin(sema.db).is_local() {
IgnoreAssocItems::No
} else {
IgnoreAssocItems::DocHiddenAttrPresent

View file

@ -58,7 +58,7 @@ pub(crate) fn replace_qualified_name_with_use(
let path_to_qualifier = starts_with_name_ref
.then(|| {
let mod_ = ctx.sema.scope(original_path.syntax())?.module();
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(mod_.krate()));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(mod_.krate(ctx.sema.db)));
mod_.find_use_path(ctx.sema.db, module, ctx.config.insert_use.prefix_kind, cfg)
})
.flatten();

View file

@ -55,7 +55,7 @@ pub(crate) fn term_search(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
path.gen_source_code(
&scope,
&mut formatter,
ctx.config.find_path_config(ctx.sema.is_nightly(scope.module().krate())),
ctx.config.find_path_config(ctx.sema.is_nightly(scope.module().krate(ctx.sema.db))),
scope.krate().to_display_target(ctx.db()),
)
.ok()

View file

@ -132,7 +132,7 @@ pub(crate) fn desugar_async_into_impl_future(
let scope = ctx.sema.scope(function.syntax())?;
let module = scope.module();
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate()));
let cfg = ctx.config.find_path_config(ctx.sema.is_nightly(module.krate(ctx.sema.db)));
let future_trait = FamousDefs(&ctx.sema, scope.krate()).core_future_Future()?;
let trait_path = module.find_path(ctx.db(), ModuleDef::Trait(future_trait), cfg)?;
let edition = scope.krate().edition(ctx.db());

View file

@ -190,7 +190,7 @@ impl Completions {
path_ctx: &PathCompletionCtx<'_>,
) {
ctx.process_all_names(&mut |name, res, doc_aliases| match res {
ScopeDef::ModuleDef(hir::ModuleDef::Module(m)) if m.is_crate_root() => {
ScopeDef::ModuleDef(hir::ModuleDef::Module(m)) if m.is_crate_root(ctx.db) => {
self.add_module(ctx, path_ctx, m, name, doc_aliases);
}
_ => (),

Some files were not shown because too many files have changed in this diff Show more