Skip to content

Commit

Permalink
fix: Do not show safety hints for extern items lacking semantics
Browse files Browse the repository at this point in the history
  • Loading branch information
Veykril committed Feb 7, 2025
1 parent ca47cdd commit 88491b2
Show file tree
Hide file tree
Showing 10 changed files with 99 additions and 31 deletions.
7 changes: 4 additions & 3 deletions crates/hir-def/src/dyn_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ pub mod keys {

use crate::{
dyn_map::{DynMap, Policy},
BlockId, ConstId, EnumId, EnumVariantId, ExternCrateId, FieldId, FunctionId, ImplId,
LifetimeParamId, Macro2Id, MacroRulesId, ProcMacroId, StaticId, StructId, TraitAliasId,
TraitId, TypeAliasId, TypeOrConstParamId, UnionId, UseId,
BlockId, ConstId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId, FieldId, FunctionId,
ImplId, LifetimeParamId, Macro2Id, MacroRulesId, ProcMacroId, StaticId, StructId,
TraitAliasId, TraitId, TypeAliasId, TypeOrConstParamId, UnionId, UseId,
};

pub type Key<K, V> = crate::dyn_map::Key<AstPtr<K>, V, AstPtrPolicy<K, V>>;
Expand All @@ -44,6 +44,7 @@ pub mod keys {
pub const STATIC: Key<ast::Static, StaticId> = Key::new();
pub const TYPE_ALIAS: Key<ast::TypeAlias, TypeAliasId> = Key::new();
pub const IMPL: Key<ast::Impl, ImplId> = Key::new();
pub const EXTERN_BLOCK: Key<ast::ExternBlock, ExternBlockId> = Key::new();
pub const TRAIT: Key<ast::Trait, TraitId> = Key::new();
pub const TRAIT_ALIAS: Key<ast::TraitAlias, TraitAliasId> = Key::new();
pub const STRUCT: Key<ast::Struct, StructId> = Key::new();
Expand Down
18 changes: 16 additions & 2 deletions crates/hir-def/src/item_scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use crate::{
db::DefDatabase,
per_ns::{Item, MacrosItem, PerNs, TypesItem, ValuesItem},
visibility::{Visibility, VisibilityExplicitness},
AdtId, BuiltinType, ConstId, ExternCrateId, FxIndexMap, HasModule, ImplId, LocalModuleId,
Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
AdtId, BuiltinType, ConstId, ExternBlockId, ExternCrateId, FxIndexMap, HasModule, ImplId,
LocalModuleId, Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
};

#[derive(Debug, Default)]
Expand Down Expand Up @@ -158,6 +158,8 @@ pub struct ItemScope {
declarations: Vec<ModuleDefId>,

impls: Vec<ImplId>,
#[allow(clippy::box_collection)]
extern_blocks: Option<Box<Vec<ExternBlockId>>>,
unnamed_consts: Vec<ConstId>,
/// Traits imported via `use Trait as _;`.
unnamed_trait_imports: FxHashMap<TraitId, Item<()>>,
Expand Down Expand Up @@ -319,6 +321,10 @@ impl ItemScope {
self.extern_crate_decls.iter().copied()
}

pub fn extern_blocks(&self) -> impl Iterator<Item = ExternBlockId> + '_ {
self.extern_blocks.iter().flat_map(|it| it.iter()).copied()
}

pub fn use_decls(&self) -> impl ExactSizeIterator<Item = UseId> + '_ {
self.use_decls.iter().copied()
}
Expand Down Expand Up @@ -469,6 +475,10 @@ impl ItemScope {
self.impls.push(imp);
}

pub(crate) fn define_extern_block(&mut self, extern_block: ExternBlockId) {
self.extern_blocks.get_or_insert_default().push(extern_block);
}

pub(crate) fn define_extern_crate_decl(&mut self, extern_crate: ExternCrateId) {
self.extern_crate_decls.push(extern_crate);
}
Expand Down Expand Up @@ -806,7 +816,11 @@ impl ItemScope {
use_imports_types,
use_imports_macros,
macro_invocations,
extern_blocks,
} = self;
if let Some(it) = extern_blocks {
it.shrink_to_fit();
}
types.shrink_to_fit();
values.shrink_to_fit();
macros.shrink_to_fit();
Expand Down
24 changes: 14 additions & 10 deletions crates/hir-def/src/nameres/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1759,16 +1759,20 @@ impl ModCollector<'_, '_> {
);
}
}
ModItem::ExternBlock(block) => self.collect(
&self.item_tree[block].children,
ItemContainerId::ExternBlockId(
ExternBlockLoc {
container: module,
id: ItemTreeId::new(self.tree_id, block),
}
.intern(db),
),
),
ModItem::ExternBlock(block) => {
let extern_block_id = ExternBlockLoc {
container: module,
id: ItemTreeId::new(self.tree_id, block),
}
.intern(db);
self.def_collector.def_map.modules[self.module_id]
.scope
.define_extern_block(extern_block_id);
self.collect(
&self.item_tree[block].children,
ItemContainerId::ExternBlockId(extern_block_id),
)
}
ModItem::MacroCall(mac) => self.collect_macro_call(&self.item_tree[mac], container),
ModItem::MacroRules(id) => self.collect_macro_rules(id, module),
ModItem::Macro2(id) => self.collect_macro_def(id, module),
Expand Down
1 change: 1 addition & 0 deletions crates/hir/src/from_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ from_id![
(hir_def::LifetimeParamId, crate::LifetimeParam),
(hir_def::MacroId, crate::Macro),
(hir_def::ExternCrateId, crate::ExternCrateDecl),
(hir_def::ExternBlockId, crate::ExternBlock),
];

impl From<AdtId> for Adt {
Expand Down
39 changes: 35 additions & 4 deletions crates/hir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ use hir_def::{
resolver::{HasResolver, Resolver},
type_ref::TypesSourceMap,
AdtId, AssocItemId, AssocItemLoc, AttrDefId, CallableDefId, ConstId, ConstParamId,
CrateRootModuleId, DefWithBodyId, EnumId, EnumVariantId, ExternCrateId, FunctionId,
GenericDefId, GenericParamId, HasModule, ImplId, InTypeConstId, ItemContainerId,
CrateRootModuleId, DefWithBodyId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId,
FunctionId, GenericDefId, GenericParamId, HasModule, ImplId, InTypeConstId, ItemContainerId,
LifetimeParamId, LocalFieldId, Lookup, MacroExpander, MacroId, ModuleId, StaticId, StructId,
SyntheticSyntax, TraitAliasId, TupleId, TypeAliasId, TypeOrConstParamId, TypeParamId, UnionId,
};
Expand Down Expand Up @@ -2327,6 +2327,13 @@ impl Function {
db.function_data(self.id).is_async()
}

pub fn extern_block(self, db: &dyn HirDatabase) -> Option<ExternBlock> {
match self.id.lookup(db.upcast()).container {
ItemContainerId::ExternBlockId(id) => Some(ExternBlock { id }),
_ => None,
}
}

pub fn returns_impl_future(self, db: &dyn HirDatabase) -> bool {
if self.is_async(db) {
return true;
Expand Down Expand Up @@ -2761,6 +2768,13 @@ impl Static {
Type::from_value_def(db, self.id)
}

pub fn extern_block(self, db: &dyn HirDatabase) -> Option<ExternBlock> {
match self.id.lookup(db.upcast()).container {
ItemContainerId::ExternBlockId(id) => Some(ExternBlock { id }),
_ => None,
}
}

/// Evaluate the static initializer.
pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst, ConstEvalError> {
db.const_eval(self.id.into(), Substitution::empty(Interner), None)
Expand Down Expand Up @@ -2928,6 +2942,17 @@ impl HasVisibility for TypeAlias {
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExternBlock {
pub(crate) id: ExternBlockId,
}

impl ExternBlock {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.module(db.upcast()) }
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StaticLifetime;

Expand Down Expand Up @@ -6180,9 +6205,15 @@ impl HasContainer for TraitAlias {
}
}

impl HasContainer for ExternBlock {
fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
ItemContainer::Module(Module { id: self.id.lookup(db.upcast()).container })
}
}

fn container_id_to_hir(c: ItemContainerId) -> ItemContainer {
match c {
ItemContainerId::ExternBlockId(_id) => ItemContainer::ExternBlock(),
ItemContainerId::ExternBlockId(id) => ItemContainer::ExternBlock(ExternBlock { id }),
ItemContainerId::ModuleId(id) => ItemContainer::Module(Module { id }),
ItemContainerId::ImplId(id) => ItemContainer::Impl(Impl { id }),
ItemContainerId::TraitId(id) => ItemContainer::Trait(Trait { id }),
Expand All @@ -6194,7 +6225,7 @@ pub enum ItemContainer {
Trait(Trait),
Impl(Impl),
Module(Module),
ExternBlock(),
ExternBlock(ExternBlock),
Crate(CrateId),
}

Expand Down
1 change: 1 addition & 0 deletions crates/hir/src/semantics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1998,6 +1998,7 @@ to_def_impls![
(crate::Adt, ast::Adt, adt_to_def),
(crate::ExternCrateDecl, ast::ExternCrate, extern_crate_to_def),
(crate::InlineAsmOperand, ast::AsmOperandNamed, asm_operand_to_def),
(crate::ExternBlock, ast::ExternBlock, extern_block_to_def),
(MacroCallId, ast::MacroCall, macro_call_to_macro_call),
];

Expand Down
3 changes: 3 additions & 0 deletions crates/hir/src/semantics/child_by_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ impl ChildBySource for ItemScope {
fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, file_id: HirFileId) {
self.declarations().for_each(|item| add_module_def(db, res, file_id, item));
self.impls().for_each(|imp| insert_item_loc(db, res, file_id, imp, keys::IMPL));
self.extern_blocks().for_each(|extern_block| {
insert_item_loc(db, res, file_id, extern_block, keys::EXTERN_BLOCK)
});
self.extern_crate_decls()
.for_each(|ext| insert_item_loc(db, res, file_id, ext, keys::EXTERN_CRATE));
self.use_decls().for_each(|ext| insert_item_loc(db, res, file_id, ext, keys::USE));
Expand Down
14 changes: 10 additions & 4 deletions crates/hir/src/semantics/source_to_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ use hir_def::{
DynMap,
},
hir::{BindingId, Expr, LabelId},
AdtId, BlockId, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, ExternCrateId,
FieldId, FunctionId, GenericDefId, GenericParamId, ImplId, LifetimeParamId, Lookup, MacroId,
ModuleId, StaticId, StructId, TraitAliasId, TraitId, TypeAliasId, TypeParamId, UnionId, UseId,
VariantId,
AdtId, BlockId, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, ExternBlockId,
ExternCrateId, FieldId, FunctionId, GenericDefId, GenericParamId, ImplId, LifetimeParamId,
Lookup, MacroId, ModuleId, StaticId, StructId, TraitAliasId, TraitId, TypeAliasId, TypeParamId,
UnionId, UseId, VariantId,
};
use hir_expand::{
attrs::AttrId, name::AsName, ExpansionInfo, HirFileId, HirFileIdExt, InMacroFile, MacroCallId,
Expand Down Expand Up @@ -308,6 +308,12 @@ impl SourceToDefCtx<'_, '_> {
) -> Option<ExternCrateId> {
self.to_def(src, keys::EXTERN_CRATE)
}
pub(super) fn extern_block_to_def(
&mut self,
src: InFile<&ast::ExternBlock>,
) -> Option<ExternBlockId> {
self.to_def(src, keys::EXTERN_BLOCK)
}
#[allow(dead_code)]
pub(super) fn use_to_def(&mut self, src: InFile<&ast::Use>) -> Option<UseId> {
self.to_def(src, keys::USE)
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-db/src/defs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl Definition {
ItemContainer::Trait(it) => Some(it.into()),
ItemContainer::Impl(it) => Some(it.into()),
ItemContainer::Module(it) => Some(it.into()),
ItemContainer::ExternBlock() | ItemContainer::Crate(_) => None,
ItemContainer::ExternBlock(_) | ItemContainer::Crate(_) => None,
}
}
match self {
Expand Down
21 changes: 14 additions & 7 deletions crates/ide/src/inlay_hints/extern_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{InlayHint, InlayHintsConfig};

pub(super) fn extern_block_hints(
acc: &mut Vec<InlayHint>,
FamousDefs(_sema, _): &FamousDefs<'_, '_>,
FamousDefs(sema, _): &FamousDefs<'_, '_>,
config: &InlayHintsConfig,
_file_id: EditionedFileId,
extern_block: ast::ExternBlock,
Expand All @@ -16,6 +16,9 @@ pub(super) fn extern_block_hints(
return None;
}
let abi = extern_block.abi()?;
if !sema.to_def(&extern_block).is_some() {
return None;
}
acc.push(InlayHint {
range: abi.syntax().text_range(),
position: crate::InlayHintPosition::Before,
Expand All @@ -33,7 +36,7 @@ pub(super) fn extern_block_hints(

pub(super) fn fn_hints(
acc: &mut Vec<InlayHint>,
FamousDefs(_sema, _): &FamousDefs<'_, '_>,
FamousDefs(sema, _): &FamousDefs<'_, '_>,
config: &InlayHintsConfig,
_file_id: EditionedFileId,
fn_: &ast::Fn,
Expand All @@ -43,14 +46,16 @@ pub(super) fn fn_hints(
if !implicit_unsafe {
return None;
}
let fn_ = fn_.fn_token()?;
acc.push(item_hint(config, extern_block, fn_));
let fn_token = fn_.fn_token()?;
if sema.to_def(fn_).is_some_and(|def| def.extern_block(sema.db).is_some()) {
acc.push(item_hint(config, extern_block, fn_token));
}
Some(())
}

pub(super) fn static_hints(
acc: &mut Vec<InlayHint>,
FamousDefs(_sema, _): &FamousDefs<'_, '_>,
FamousDefs(sema, _): &FamousDefs<'_, '_>,
config: &InlayHintsConfig,
_file_id: EditionedFileId,
static_: &ast::Static,
Expand All @@ -60,8 +65,10 @@ pub(super) fn static_hints(
if !implicit_unsafe {
return None;
}
let static_ = static_.static_token()?;
acc.push(item_hint(config, extern_block, static_));
let static_token = static_.static_token()?;
if sema.to_def(static_).is_some_and(|def| def.extern_block(sema.db).is_some()) {
acc.push(item_hint(config, extern_block, static_token));
}
Some(())
}

Expand Down

0 comments on commit 88491b2

Please sign in to comment.