1
Fork 0

Rollup merge of #114772 - fee1-dead-contrib:typed-did, r=b-naber

Add `{Local}ModDefId` to more strongly type DefIds`

Based on #110862 by `@Nilstrieb`
This commit is contained in:
Guillaume Gomez 2023-08-15 14:29:45 +02:00 committed by GitHub
commit f0987ab45b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 324 additions and 100 deletions

View file

@ -8,7 +8,7 @@ use rustc_attr as attr;
use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan}; use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_hir::{ItemKind, Node, PathSegment}; use rustc_hir::{ItemKind, Node, PathSegment};
use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor; use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor;
@ -1443,12 +1443,12 @@ pub(super) fn check_type_params_are_used<'tcx>(
} }
} }
pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let module = tcx.hir_module_items(module_def_id); let module = tcx.hir_module_items(module_def_id);
for id in module.items() { for id in module.items() {
check_item_type(tcx, id); check_item_type(tcx, id);
} }
if module_def_id == CRATE_DEF_ID { if module_def_id == LocalModDefId::CRATE_DEF_ID {
super::entry::check_for_entry_fn(tcx); super::entry::check_for_entry_fn(tcx);
} }
} }

View file

@ -5,7 +5,7 @@ use rustc_ast as ast;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed}; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
use rustc_hir::ItemKind; use rustc_hir::ItemKind;
use rustc_infer::infer::outlives::env::{OutlivesEnvironment, RegionBoundPairs}; use rustc_infer::infer::outlives::env::{OutlivesEnvironment, RegionBoundPairs};
@ -1854,7 +1854,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
} }
} }
fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) { fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalModDefId) {
let items = tcx.hir_module_items(module); let items = tcx.hir_module_items(module);
items.par_items(|item| tcx.ensure().check_well_formed(item.owner_id)); items.par_items(|item| tcx.ensure().check_well_formed(item.owner_id));
items.par_impl_items(|item| tcx.ensure().check_well_formed(item.owner_id)); items.par_impl_items(|item| tcx.ensure().check_well_formed(item.owner_id));

View file

@ -22,7 +22,7 @@ use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{GenericParamKind, Node}; use rustc_hir::{GenericParamKind, Node};
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
@ -48,7 +48,7 @@ mod type_of;
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// Main entry point // Main entry point
fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx }); tcx.hir().visit_item_likes_in_module(module_def_id, &mut CollectItemTypesVisitor { tcx });
} }

View file

@ -14,7 +14,7 @@ use min_specialization::check_min_specialization;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_errors::struct_span_err; use rustc_errors::struct_span_err;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::{LocalDefId, LocalModDefId};
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
use rustc_span::{Span, Symbol}; use rustc_span::{Span, Symbol};
@ -51,7 +51,7 @@ mod min_specialization;
/// impl<'a> Trait<Foo> for Bar { type X = &'a i32; } /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; }
/// // ^ 'a is unused and appears in assoc type, error /// // ^ 'a is unused and appears in assoc type, error
/// ``` /// ```
fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_impl_wf(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let min_specialization = tcx.features().min_specialization; let min_specialization = tcx.features().min_specialization;
let module = tcx.hir_module_items(module_def_id); let module = tcx.hir_module_items(module_def_id);
for id in module.items() { for id in module.items() {

View file

@ -19,7 +19,7 @@ use rustc_ast as ast;
use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::sync::join; use rustc_data_structures::sync::join;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::{LocalDefId, LocalModDefId};
use rustc_hir::intravisit as hir_visit; use rustc_hir::intravisit as hir_visit;
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
@ -338,7 +338,7 @@ crate::late_lint_methods!(impl_late_lint_pass, []);
pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
module_def_id: LocalDefId, module_def_id: LocalModDefId,
builtin_lints: T, builtin_lints: T,
) { ) {
let context = LateContext { let context = LateContext {
@ -369,7 +369,7 @@ pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>(
fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>( fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
module_def_id: LocalDefId, module_def_id: LocalModDefId,
context: LateContext<'tcx>, context: LateContext<'tcx>,
pass: T, pass: T,
) { ) {

View file

@ -90,7 +90,7 @@ use rustc_ast as ast;
use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage}; use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
use rustc_fluent_macro::fluent_messages; use rustc_fluent_macro::fluent_messages;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::{LocalDefId, LocalModDefId};
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::TyCtxt;
use rustc_session::lint::builtin::{ use rustc_session::lint::builtin::{
@ -145,7 +145,7 @@ pub fn provide(providers: &mut Providers) {
*providers = Providers { lint_mod, ..*providers }; *providers = Providers { lint_mod, ..*providers };
} }
fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new()); late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
} }

View file

@ -60,7 +60,7 @@ use crate::mir::mono::MonoItem;
use crate::ty::TyCtxt; use crate::ty::TyCtxt;
use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fingerprint::Fingerprint;
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE};
use rustc_hir::definitions::DefPathHash; use rustc_hir::definitions::DefPathHash;
use rustc_hir::{HirId, ItemLocalId, OwnerId}; use rustc_hir::{HirId, ItemLocalId, OwnerId};
use rustc_query_system::dep_graph::FingerprintStyle; use rustc_query_system::dep_graph::FingerprintStyle;
@ -387,3 +387,53 @@ impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for HirId {
} }
} }
} }
macro_rules! impl_for_typed_def_id {
($Name:ident, $LocalName:ident) => {
impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for $Name {
#[inline(always)]
fn fingerprint_style() -> FingerprintStyle {
FingerprintStyle::DefPathHash
}
#[inline(always)]
fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint {
self.to_def_id().to_fingerprint(tcx)
}
#[inline(always)]
fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String {
self.to_def_id().to_debug_str(tcx)
}
#[inline(always)]
fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> {
DefId::recover(tcx, dep_node).map($Name::new_unchecked)
}
}
impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for $LocalName {
#[inline(always)]
fn fingerprint_style() -> FingerprintStyle {
FingerprintStyle::DefPathHash
}
#[inline(always)]
fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint {
self.to_def_id().to_fingerprint(tcx)
}
#[inline(always)]
fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String {
self.to_def_id().to_debug_str(tcx)
}
#[inline(always)]
fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> {
LocalDefId::recover(tcx, dep_node).map($LocalName::new_unchecked)
}
}
};
}
impl_for_typed_def_id! { ModDefId, LocalModDefId }

View file

@ -8,7 +8,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::svh::Svh; use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{par_for_each_in, DynSend, DynSync}; use rustc_data_structures::sync::{par_for_each_in, DynSend, DynSync};
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash}; use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::*; use rustc_hir::*;
@ -148,7 +148,7 @@ impl<'hir> Map<'hir> {
} }
#[inline] #[inline]
pub fn module_items(self, module: LocalDefId) -> impl Iterator<Item = ItemId> + 'hir { pub fn module_items(self, module: LocalModDefId) -> impl Iterator<Item = ItemId> + 'hir {
self.tcx.hir_module_items(module).items() self.tcx.hir_module_items(module).items()
} }
@ -169,8 +169,8 @@ impl<'hir> Map<'hir> {
} }
#[inline] #[inline]
pub fn local_def_id_to_hir_id(self, def_id: LocalDefId) -> HirId { pub fn local_def_id_to_hir_id(self, def_id: impl Into<LocalDefId>) -> HirId {
self.tcx.local_def_id_to_hir_id(def_id) self.tcx.local_def_id_to_hir_id(def_id.into())
} }
/// Do not call this function directly. The query should be called. /// Do not call this function directly. The query should be called.
@ -529,8 +529,8 @@ impl<'hir> Map<'hir> {
self.krate_attrs().iter().any(|attr| attr.has_name(sym::rustc_coherence_is_core)) self.krate_attrs().iter().any(|attr| attr.has_name(sym::rustc_coherence_is_core))
} }
pub fn get_module(self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { pub fn get_module(self, module: LocalModDefId) -> (&'hir Mod<'hir>, Span, HirId) {
let hir_id = HirId::make_owner(module); let hir_id = HirId::make_owner(module.to_local_def_id());
match self.tcx.hir_owner(hir_id.owner).map(|o| o.node) { match self.tcx.hir_owner(hir_id.owner).map(|o| o.node) {
Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => { Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
(m, span, hir_id) (m, span, hir_id)
@ -542,7 +542,7 @@ impl<'hir> Map<'hir> {
/// Walks the contents of the local crate. See also `visit_all_item_likes_in_crate`. /// Walks the contents of the local crate. See also `visit_all_item_likes_in_crate`.
pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) { pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID); let (top_mod, span, hir_id) = self.get_module(LocalModDefId::CRATE_DEF_ID);
visitor.visit_mod(top_mod, span, hir_id); visitor.visit_mod(top_mod, span, hir_id);
} }
@ -595,7 +595,7 @@ impl<'hir> Map<'hir> {
/// This method is the equivalent of `visit_all_item_likes_in_crate` but restricted to /// This method is the equivalent of `visit_all_item_likes_in_crate` but restricted to
/// item-likes in a single module. /// item-likes in a single module.
pub fn visit_item_likes_in_module<V>(self, module: LocalDefId, visitor: &mut V) pub fn visit_item_likes_in_module<V>(self, module: LocalModDefId, visitor: &mut V)
where where
V: Visitor<'hir>, V: Visitor<'hir>,
{ {
@ -618,17 +618,19 @@ impl<'hir> Map<'hir> {
} }
} }
pub fn for_each_module(self, mut f: impl FnMut(LocalDefId)) { pub fn for_each_module(self, mut f: impl FnMut(LocalModDefId)) {
let crate_items = self.tcx.hir_crate_items(()); let crate_items = self.tcx.hir_crate_items(());
for module in crate_items.submodules.iter() { for module in crate_items.submodules.iter() {
f(module.def_id) f(LocalModDefId::new_unchecked(module.def_id))
} }
} }
#[inline] #[inline]
pub fn par_for_each_module(self, f: impl Fn(LocalDefId) + DynSend + DynSync) { pub fn par_for_each_module(self, f: impl Fn(LocalModDefId) + DynSend + DynSync) {
let crate_items = self.tcx.hir_crate_items(()); let crate_items = self.tcx.hir_crate_items(());
par_for_each_in(&crate_items.submodules[..], |module| f(module.def_id)) par_for_each_in(&crate_items.submodules[..], |module| {
f(LocalModDefId::new_unchecked(module.def_id))
})
} }
/// Returns an iterator for the nodes in the ancestor tree of the `current_id` /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
@ -1324,7 +1326,7 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
} }
} }
pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems { pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModDefId) -> ModuleItems {
let mut collector = ItemCollector::new(tcx, false); let mut collector = ItemCollector::new(tcx, false);
let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id); let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id);

View file

@ -11,7 +11,7 @@ use crate::ty::{EarlyBinder, ImplSubject, TyCtxt};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::{par_for_each_in, DynSend, DynSync}; use rustc_data_structures::sync::{par_for_each_in, DynSend, DynSync};
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
use rustc_hir::*; use rustc_hir::*;
use rustc_query_system::ich::StableHashingContext; use rustc_query_system::ich::StableHashingContext;
use rustc_span::{ExpnId, DUMMY_SP}; use rustc_span::{ExpnId, DUMMY_SP};
@ -101,22 +101,22 @@ impl<'tcx> TyCtxt<'tcx> {
map::Map { tcx: self } map::Map { tcx: self }
} }
pub fn parent_module(self, id: HirId) -> LocalDefId { pub fn parent_module(self, id: HirId) -> LocalModDefId {
if !id.is_owner() && self.def_kind(id.owner) == DefKind::Mod { if !id.is_owner() && self.def_kind(id.owner) == DefKind::Mod {
id.owner.def_id LocalModDefId::new_unchecked(id.owner.def_id)
} else { } else {
self.parent_module_from_def_id(id.owner.def_id) self.parent_module_from_def_id(id.owner.def_id)
} }
} }
pub fn parent_module_from_def_id(self, mut id: LocalDefId) -> LocalDefId { pub fn parent_module_from_def_id(self, mut id: LocalDefId) -> LocalModDefId {
while let Some(parent) = self.opt_local_parent(id) { while let Some(parent) = self.opt_local_parent(id) {
id = parent; id = parent;
if self.def_kind(id) == DefKind::Mod { if self.def_kind(id) == DefKind::Mod {
break; break;
} }
} }
id LocalModDefId::new_unchecked(id)
} }
pub fn impl_subject(self, def_id: DefId) -> EarlyBinder<ImplSubject<'tcx>> { pub fn impl_subject(self, def_id: DefId) -> EarlyBinder<ImplSubject<'tcx>> {

View file

@ -235,6 +235,7 @@ trivial! {
rustc_hir::def_id::DefId, rustc_hir::def_id::DefId,
rustc_hir::def_id::DefIndex, rustc_hir::def_id::DefIndex,
rustc_hir::def_id::LocalDefId, rustc_hir::def_id::LocalDefId,
rustc_hir::def_id::LocalModDefId,
rustc_hir::def::DefKind, rustc_hir::def::DefKind,
rustc_hir::Defaultness, rustc_hir::Defaultness,
rustc_hir::definitions::DefKey, rustc_hir::definitions::DefKey,

View file

@ -8,7 +8,7 @@ use crate::ty::fast_reject::SimplifiedType;
use crate::ty::layout::{TyAndLayout, ValidityRequirement}; use crate::ty::layout::{TyAndLayout, ValidityRequirement};
use crate::ty::{self, Ty, TyCtxt}; use crate::ty::{self, Ty, TyCtxt};
use crate::ty::{GenericArg, GenericArgsRef}; use crate::ty::{GenericArg, GenericArgsRef};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE};
use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_hir::hir_id::{HirId, OwnerId};
use rustc_query_system::query::{DefaultCacheSelector, SingleCacheSelector, VecCacheSelector}; use rustc_query_system::query::{DefaultCacheSelector, SingleCacheSelector, VecCacheSelector};
use rustc_span::symbol::{Ident, Symbol}; use rustc_span::symbol::{Ident, Symbol};
@ -175,6 +175,41 @@ impl AsLocalKey for DefId {
} }
} }
impl Key for LocalModDefId {
type CacheSelector = DefaultCacheSelector<Self>;
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
tcx.def_span(*self)
}
#[inline(always)]
fn key_as_def_id(&self) -> Option<DefId> {
Some(self.to_def_id())
}
}
impl Key for ModDefId {
type CacheSelector = DefaultCacheSelector<Self>;
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
tcx.def_span(*self)
}
#[inline(always)]
fn key_as_def_id(&self) -> Option<DefId> {
Some(self.to_def_id())
}
}
impl AsLocalKey for ModDefId {
type LocalKey = LocalModDefId;
#[inline(always)]
fn as_local_key(&self) -> Option<Self::LocalKey> {
self.as_local()
}
}
impl Key for SimplifiedType { impl Key for SimplifiedType {
type CacheSelector = DefaultCacheSelector<Self>; type CacheSelector = DefaultCacheSelector<Self>;

View file

@ -67,7 +67,7 @@ use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, DocLinkResMap}; use rustc_hir::def::{DefKind, DocLinkResMap};
use rustc_hir::def_id::{ use rustc_hir::def_id::{
CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LocalDefIdMap, LocalDefIdSet, CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LocalDefIdMap, LocalDefIdSet, LocalModDefId,
}; };
use rustc_hir::lang_items::{LangItem, LanguageItems}; use rustc_hir::lang_items::{LangItem, LanguageItems};
use rustc_hir::{Crate, ItemLocalId, TraitCandidate}; use rustc_hir::{Crate, ItemLocalId, TraitCandidate};
@ -167,7 +167,7 @@ rustc_queries! {
/// ///
/// This can be conveniently accessed by `tcx.hir().visit_item_likes_in_module`. /// This can be conveniently accessed by `tcx.hir().visit_item_likes_in_module`.
/// Avoid calling this query directly. /// Avoid calling this query directly.
query hir_module_items(key: LocalDefId) -> &'tcx rustc_middle::hir::ModuleItems { query hir_module_items(key: LocalModDefId) -> &'tcx rustc_middle::hir::ModuleItems {
arena_cache arena_cache
desc { |tcx| "getting HIR module items in `{}`", tcx.def_path_str(key) } desc { |tcx| "getting HIR module items in `{}`", tcx.def_path_str(key) }
cache_on_disk_if { true } cache_on_disk_if { true }
@ -896,7 +896,7 @@ rustc_queries! {
} }
/// Performs lint checking for the module. /// Performs lint checking for the module.
query lint_mod(key: LocalDefId) -> () { query lint_mod(key: LocalModDefId) -> () {
desc { |tcx| "linting {}", describe_as_module(key, tcx) } desc { |tcx| "linting {}", describe_as_module(key, tcx) }
} }
@ -905,35 +905,35 @@ rustc_queries! {
} }
/// Checks the attributes in the module. /// Checks the attributes in the module.
query check_mod_attrs(key: LocalDefId) -> () { query check_mod_attrs(key: LocalModDefId) -> () {
desc { |tcx| "checking attributes in {}", describe_as_module(key, tcx) } desc { |tcx| "checking attributes in {}", describe_as_module(key, tcx) }
} }
/// Checks for uses of unstable APIs in the module. /// Checks for uses of unstable APIs in the module.
query check_mod_unstable_api_usage(key: LocalDefId) -> () { query check_mod_unstable_api_usage(key: LocalModDefId) -> () {
desc { |tcx| "checking for unstable API usage in {}", describe_as_module(key, tcx) } desc { |tcx| "checking for unstable API usage in {}", describe_as_module(key, tcx) }
} }
/// Checks the const bodies in the module for illegal operations (e.g. `if` or `loop`). /// Checks the const bodies in the module for illegal operations (e.g. `if` or `loop`).
query check_mod_const_bodies(key: LocalDefId) -> () { query check_mod_const_bodies(key: LocalModDefId) -> () {
desc { |tcx| "checking consts in {}", describe_as_module(key, tcx) } desc { |tcx| "checking consts in {}", describe_as_module(key, tcx) }
} }
/// Checks the loops in the module. /// Checks the loops in the module.
query check_mod_loops(key: LocalDefId) -> () { query check_mod_loops(key: LocalModDefId) -> () {
desc { |tcx| "checking loops in {}", describe_as_module(key, tcx) } desc { |tcx| "checking loops in {}", describe_as_module(key, tcx) }
} }
query check_mod_naked_functions(key: LocalDefId) -> () { query check_mod_naked_functions(key: LocalModDefId) -> () {
desc { |tcx| "checking naked functions in {}", describe_as_module(key, tcx) } desc { |tcx| "checking naked functions in {}", describe_as_module(key, tcx) }
} }
query check_mod_item_types(key: LocalDefId) -> () { query check_mod_item_types(key: LocalModDefId) -> () {
desc { |tcx| "checking item types in {}", describe_as_module(key, tcx) } desc { |tcx| "checking item types in {}", describe_as_module(key, tcx) }
} }
query check_mod_privacy(key: LocalDefId) -> () { query check_mod_privacy(key: LocalModDefId) -> () {
desc { |tcx| "checking privacy in {}", describe_as_module(key, tcx) } desc { |tcx| "checking privacy in {}", describe_as_module(key.to_local_def_id(), tcx) }
} }
query check_liveness(key: LocalDefId) { query check_liveness(key: LocalDefId) {
@ -952,19 +952,19 @@ rustc_queries! {
desc { "finding live symbols in crate" } desc { "finding live symbols in crate" }
} }
query check_mod_deathness(key: LocalDefId) -> () { query check_mod_deathness(key: LocalModDefId) -> () {
desc { |tcx| "checking deathness of variables in {}", describe_as_module(key, tcx) } desc { |tcx| "checking deathness of variables in {}", describe_as_module(key, tcx) }
} }
query check_mod_impl_wf(key: LocalDefId) -> () { query check_mod_impl_wf(key: LocalModDefId) -> () {
desc { |tcx| "checking that impls are well-formed in {}", describe_as_module(key, tcx) } desc { |tcx| "checking that impls are well-formed in {}", describe_as_module(key, tcx) }
} }
query check_mod_type_wf(key: LocalDefId) -> () { query check_mod_type_wf(key: LocalModDefId) -> () {
desc { |tcx| "checking that types are well-formed in {}", describe_as_module(key, tcx) } desc { |tcx| "checking that types are well-formed in {}", describe_as_module(key, tcx) }
} }
query collect_mod_item_types(key: LocalDefId) -> () { query collect_mod_item_types(key: LocalModDefId) -> () {
desc { |tcx| "collecting item types in {}", describe_as_module(key, tcx) } desc { |tcx| "collecting item types in {}", describe_as_module(key, tcx) }
} }

View file

@ -545,6 +545,7 @@ macro_rules! define_feedable {
mod sealed { mod sealed {
use super::{DefId, LocalDefId, OwnerId}; use super::{DefId, LocalDefId, OwnerId};
use rustc_hir::def_id::{LocalModDefId, ModDefId};
/// An analogue of the `Into` trait that's intended only for query parameters. /// An analogue of the `Into` trait that's intended only for query parameters.
/// ///
@ -588,6 +589,27 @@ mod sealed {
self.to_def_id() self.to_def_id()
} }
} }
impl IntoQueryParam<DefId> for ModDefId {
#[inline(always)]
fn into_query_param(self) -> DefId {
self.to_def_id()
}
}
impl IntoQueryParam<DefId> for LocalModDefId {
#[inline(always)]
fn into_query_param(self) -> DefId {
self.to_def_id()
}
}
impl IntoQueryParam<LocalDefId> for LocalModDefId {
#[inline(always)]
fn into_query_param(self) -> LocalDefId {
self.into()
}
}
} }
pub use sealed::IntoQueryParam; pub use sealed::IntoQueryParam;

View file

@ -355,8 +355,8 @@ impl TyCtxt<'_> {
#[inline] #[inline]
#[track_caller] #[track_caller]
pub fn local_parent(self, id: LocalDefId) -> LocalDefId { pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
self.parent(id.to_def_id()).expect_local() self.parent(id.into().to_def_id()).expect_local()
} }
pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool { pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {

View file

@ -329,7 +329,8 @@ impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Const<'tcx> {
} }
// This is only used by query descriptions // This is only used by query descriptions
pub fn describe_as_module(def_id: LocalDefId, tcx: TyCtxt<'_>) -> String { pub fn describe_as_module(def_id: impl Into<LocalDefId>, tcx: TyCtxt<'_>) -> String {
let def_id = def_id.into();
if def_id.is_top_level_module() { if def_id.is_top_level_module() {
"top-level module".to_string() "top-level module".to_string()
} else { } else {

View file

@ -11,7 +11,7 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
use rustc_data_structures::sso::SsoHashSet; use rustc_data_structures::sso::SsoHashSet;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, DefKind, Namespace}; use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::def_id::{DefId, DefIdSet, ModDefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPathData, DefPathDataName, DisambiguatedDefPathData}; use rustc_hir::definitions::{DefKey, DefPathData, DefPathDataName, DisambiguatedDefPathData};
use rustc_hir::LangItem; use rustc_hir::LangItem;
use rustc_session::config::TrimmedDefPaths; use rustc_session::config::TrimmedDefPaths;
@ -326,7 +326,8 @@ pub trait PrettyPrinter<'tcx>:
{ {
this this
.tcx() .tcx()
.module_children(visible_parent) // FIXME(typed_def_id): Further propagate ModDefId
.module_children(ModDefId::new_unchecked(*visible_parent))
.iter() .iter()
.filter(|child| child.res.opt_def_id() == Some(def_id)) .filter(|child| child.res.opt_def_id() == Some(def_id))
.find(|child| child.vis.is_public() && child.ident.name != kw::Underscore) .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
@ -551,7 +552,8 @@ pub trait PrettyPrinter<'tcx>:
// that's public and whose identifier isn't `_`. // that's public and whose identifier isn't `_`.
let reexport = self let reexport = self
.tcx() .tcx()
.module_children(visible_parent) // FIXME(typed_def_id): Further propagate ModDefId
.module_children(ModDefId::new_unchecked(visible_parent))
.iter() .iter()
.filter(|child| child.res.opt_def_id() == Some(def_id)) .filter(|child| child.res.opt_def_id() == Some(def_id))
.find(|child| child.vis.is_public() && child.ident.name != kw::Underscore) .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)

View file

@ -10,7 +10,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{Applicability, IntoDiagnosticArg, MultiSpan}; use rustc_errors::{Applicability, IntoDiagnosticArg, MultiSpan};
use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::LocalModDefId;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{ use rustc_hir::{
self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID,
@ -2465,10 +2465,10 @@ fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>)
} }
} }
fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) }; let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor); tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
if module_def_id.is_top_level_module() { if module_def_id.to_local_def_id().is_top_level_module() {
check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None); check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs()); check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
} }

View file

@ -9,7 +9,7 @@
use rustc_attr as attr; use rustc_attr as attr;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::{LocalDefId, LocalModDefId};
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
@ -55,7 +55,7 @@ impl NonConstExpr {
} }
} }
fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_const_bodies(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let mut vis = CheckConstVisitor::new(tcx); let mut vis = CheckConstVisitor::new(tcx);
tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis); tcx.hir().visit_item_likes_in_module(module_def_id, &mut vis);
} }

View file

@ -8,7 +8,7 @@ use rustc_data_structures::unord::UnordSet;
use rustc_errors::MultiSpan; use rustc_errors::MultiSpan;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{Node, PatKind, TyKind}; use rustc_hir::{Node, PatKind, TyKind};
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
@ -944,7 +944,7 @@ impl<'tcx> DeadVisitor<'tcx> {
} }
} }
fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) { fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(()); let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits }; let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
@ -969,7 +969,7 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
if !live_symbols.contains(&item.owner_id.def_id) { if !live_symbols.contains(&item.owner_id.def_id) {
let parent = tcx.local_parent(item.owner_id.def_id); let parent = tcx.local_parent(item.owner_id.def_id);
if parent != module && !live_symbols.contains(&parent) { if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
// We already have diagnosed something. // We already have diagnosed something.
continue; continue;
} }

View file

@ -1,7 +1,7 @@
use Context::*; use Context::*;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::LocalModDefId;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{Destination, Movability, Node}; use rustc_hir::{Destination, Movability, Node};
use rustc_middle::hir::map::Map; use rustc_middle::hir::map::Map;
@ -34,7 +34,7 @@ struct CheckLoopVisitor<'a, 'hir> {
cx: Context, cx: Context,
} }
fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
tcx.hir().visit_item_likes_in_module( tcx.hir().visit_item_likes_in_module(
module_def_id, module_def_id,
&mut CheckLoopVisitor { sess: &tcx.sess, hir_map: tcx.hir(), cx: Normal }, &mut CheckLoopVisitor { sess: &tcx.sess, hir_map: tcx.hir(), cx: Normal },

View file

@ -3,7 +3,7 @@
use rustc_ast::InlineAsmOptions; use rustc_ast::InlineAsmOptions;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::{LocalDefId, LocalModDefId};
use rustc_hir::intravisit::Visitor; use rustc_hir::intravisit::Visitor;
use rustc_hir::{ExprKind, InlineAsmOperand, StmtKind}; use rustc_hir::{ExprKind, InlineAsmOperand, StmtKind};
use rustc_middle::query::Providers; use rustc_middle::query::Providers;
@ -23,7 +23,7 @@ pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers { check_mod_naked_functions, ..*providers }; *providers = Providers { check_mod_naked_functions, ..*providers };
} }
fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let items = tcx.hir_module_items(module_def_id); let items = tcx.hir_module_items(module_def_id);
for def_id in items.definitions() { for def_id in items.definitions() {
if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) { if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {

View file

@ -9,7 +9,7 @@ use rustc_attr::{
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_hir::def_id::{LocalDefId, LocalModDefId, CRATE_DEF_ID};
use rustc_hir::hir_id::CRATE_HIR_ID; use rustc_hir::hir_id::CRATE_HIR_ID;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant}; use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant};
@ -682,7 +682,7 @@ fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
/// Cross-references the feature names of unstable APIs with enabled /// Cross-references the feature names of unstable APIs with enabled
/// features and possibly prints errors. /// features and possibly prints errors.
fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }); tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
} }

View file

@ -20,7 +20,7 @@ use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
use rustc_fluent_macro::fluent_messages; use rustc_fluent_macro::fluent_messages;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, CRATE_DEF_ID};
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{AssocItemKind, ForeignItemKind, HirIdSet, ItemId, Node, PatKind}; use rustc_hir::{AssocItemKind, ForeignItemKind, HirIdSet, ItemId, Node, PatKind};
use rustc_middle::bug; use rustc_middle::bug;
@ -382,8 +382,9 @@ impl VisibilityLike for EffectiveVisibility {
) -> Self { ) -> Self {
let effective_vis = let effective_vis =
find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| { find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
let private_vis = let private_vis = ty::Visibility::Restricted(
ty::Visibility::Restricted(find.tcx.parent_module_from_def_id(def_id)); find.tcx.parent_module_from_def_id(def_id).to_local_def_id(),
);
EffectiveVisibility::from_vis(private_vis) EffectiveVisibility::from_vis(private_vis)
}); });
@ -412,7 +413,7 @@ struct EmbargoVisitor<'tcx> {
/// pub macro m() { /// pub macro m() {
/// n::p::f() /// n::p::f()
/// } /// }
macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>, macro_reachable: FxHashSet<(LocalModDefId, LocalModDefId)>,
/// Preliminary pass for marking all underlying types of `impl Trait`s as reachable. /// Preliminary pass for marking all underlying types of `impl Trait`s as reachable.
impl_trait_pass: bool, impl_trait_pass: bool,
/// Has something changed in the level map? /// Has something changed in the level map?
@ -449,7 +450,9 @@ impl<'tcx> EmbargoVisitor<'tcx> {
max_vis: Option<ty::Visibility>, max_vis: Option<ty::Visibility>,
level: Level, level: Level,
) { ) {
let private_vis = ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id)); // FIXME(typed_def_id): Make `Visibility::Restricted` use a `LocalModDefId` by default.
let private_vis =
ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id).into());
if max_vis != Some(private_vis) { if max_vis != Some(private_vis) {
self.changed |= self.effective_visibilities.update( self.changed |= self.effective_visibilities.update(
def_id, def_id,
@ -508,6 +511,8 @@ impl<'tcx> EmbargoVisitor<'tcx> {
// The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252). // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
return; return;
} }
// FIXME(typed_def_id): Introduce checked constructors that check def_kind.
let macro_module_def_id = LocalModDefId::new_unchecked(macro_module_def_id);
if self.effective_visibilities.public_at_level(local_def_id).is_none() { if self.effective_visibilities.public_at_level(local_def_id).is_none() {
return; return;
@ -519,10 +524,10 @@ impl<'tcx> EmbargoVisitor<'tcx> {
loop { loop {
let changed_reachability = let changed_reachability =
self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev); self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
if changed_reachability || module_def_id == CRATE_DEF_ID { if changed_reachability || module_def_id == LocalModDefId::CRATE_DEF_ID {
break; break;
} }
module_def_id = self.tcx.local_parent(module_def_id); module_def_id = LocalModDefId::new_unchecked(self.tcx.local_parent(module_def_id));
} }
} }
@ -530,8 +535,8 @@ impl<'tcx> EmbargoVisitor<'tcx> {
/// module. Returns `true` if the level has changed. /// module. Returns `true` if the level has changed.
fn update_macro_reachable( fn update_macro_reachable(
&mut self, &mut self,
module_def_id: LocalDefId, module_def_id: LocalModDefId,
defining_mod: LocalDefId, defining_mod: LocalModDefId,
macro_ev: EffectiveVisibility, macro_ev: EffectiveVisibility,
) -> bool { ) -> bool {
if self.macro_reachable.insert((module_def_id, defining_mod)) { if self.macro_reachable.insert((module_def_id, defining_mod)) {
@ -544,8 +549,8 @@ impl<'tcx> EmbargoVisitor<'tcx> {
fn update_macro_reachable_mod( fn update_macro_reachable_mod(
&mut self, &mut self,
module_def_id: LocalDefId, module_def_id: LocalModDefId,
defining_mod: LocalDefId, defining_mod: LocalModDefId,
macro_ev: EffectiveVisibility, macro_ev: EffectiveVisibility,
) { ) {
let module = self.tcx.hir().get_module(module_def_id).0; let module = self.tcx.hir().get_module(module_def_id).0;
@ -560,7 +565,7 @@ impl<'tcx> EmbargoVisitor<'tcx> {
macro_ev, macro_ev,
); );
} }
for child in self.tcx.module_children_local(module_def_id) { for child in self.tcx.module_children_local(module_def_id.to_local_def_id()) {
// FIXME: Use module children for the logic above too. // FIXME: Use module children for the logic above too.
if !child.reexport_chain.is_empty() if !child.reexport_chain.is_empty()
&& child.vis.is_accessible_from(defining_mod, self.tcx) && child.vis.is_accessible_from(defining_mod, self.tcx)
@ -577,7 +582,7 @@ impl<'tcx> EmbargoVisitor<'tcx> {
def_id: LocalDefId, def_id: LocalDefId,
def_kind: DefKind, def_kind: DefKind,
vis: ty::Visibility, vis: ty::Visibility,
module: LocalDefId, module: LocalModDefId,
macro_ev: EffectiveVisibility, macro_ev: EffectiveVisibility,
) { ) {
self.update(def_id, macro_ev, Level::Reachable); self.update(def_id, macro_ev, Level::Reachable);
@ -608,7 +613,11 @@ impl<'tcx> EmbargoVisitor<'tcx> {
// the module, however may be reachable. // the module, however may be reachable.
DefKind::Mod => { DefKind::Mod => {
if vis.is_accessible_from(module, self.tcx) { if vis.is_accessible_from(module, self.tcx) {
self.update_macro_reachable(def_id, module, macro_ev); self.update_macro_reachable(
LocalModDefId::new_unchecked(def_id),
module,
macro_ev,
);
} }
} }
@ -892,7 +901,7 @@ fn vis_to_string<'tcx>(def_id: LocalDefId, vis: ty::Visibility, tcx: TyCtxt<'tcx
ty::Visibility::Restricted(restricted_id) => { ty::Visibility::Restricted(restricted_id) => {
if restricted_id.is_top_level_module() { if restricted_id.is_top_level_module() {
"pub(crate)".to_string() "pub(crate)".to_string()
} else if restricted_id == tcx.parent_module_from_def_id(def_id) { } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
"pub(self)".to_string() "pub(self)".to_string()
} else { } else {
format!("pub({})", tcx.item_name(restricted_id.to_def_id())) format!("pub({})", tcx.item_name(restricted_id.to_def_id()))
@ -1800,7 +1809,7 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> {
let vis_descr = match vis { let vis_descr = match vis {
ty::Visibility::Public => "public", ty::Visibility::Public => "public",
ty::Visibility::Restricted(vis_def_id) => { ty::Visibility::Restricted(vis_def_id) => {
if vis_def_id == self.tcx.parent_module(hir_id) { if vis_def_id == self.tcx.parent_module(hir_id).to_local_def_id() {
"private" "private"
} else if vis_def_id.is_top_level_module() { } else if vis_def_id.is_top_level_module() {
"crate-private" "crate-private"
@ -2196,7 +2205,7 @@ fn local_visibility(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Visibility {
kind: hir::ItemKind::Use(_, hir::UseKind::ListStem) kind: hir::ItemKind::Use(_, hir::UseKind::ListStem)
| hir::ItemKind::OpaqueTy(..), | hir::ItemKind::OpaqueTy(..),
.. ..
}) => ty::Visibility::Restricted(tcx.parent_module(hir_id)), }) => ty::Visibility::Restricted(tcx.parent_module(hir_id).to_local_def_id()),
// Visibilities of trait impl items are inherited from their traits // Visibilities of trait impl items are inherited from their traits
// and are not filled in resolve. // and are not filled in resolve.
Node::ImplItem(impl_item) => { Node::ImplItem(impl_item) => {
@ -2224,18 +2233,25 @@ fn local_visibility(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Visibility {
} }
} }
fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
// Check privacy of names not checked in previous compilation stages. // Check privacy of names not checked in previous compilation stages.
let mut visitor = let mut visitor = NamePrivacyVisitor {
NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id }; tcx,
maybe_typeck_results: None,
current_item: module_def_id.to_local_def_id(),
};
let (module, span, hir_id) = tcx.hir().get_module(module_def_id); let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
intravisit::walk_mod(&mut visitor, module, hir_id); intravisit::walk_mod(&mut visitor, module, hir_id);
// Check privacy of explicitly written types and traits as well as // Check privacy of explicitly written types and traits as well as
// inferred types of expressions and patterns. // inferred types of expressions and patterns.
let mut visitor = let mut visitor = TypePrivacyVisitor {
TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span }; tcx,
maybe_typeck_results: None,
current_item: module_def_id.to_local_def_id(),
span,
};
intravisit::walk_mod(&mut visitor, module, hir_id); intravisit::walk_mod(&mut visitor, module, hir_id);
} }

View file

@ -28,10 +28,16 @@ impl CrateNum {
CrateNum::from_usize(x) CrateNum::from_usize(x)
} }
// FIXME(typed_def_id): Replace this with `as_mod_def_id`.
#[inline] #[inline]
pub fn as_def_id(self) -> DefId { pub fn as_def_id(self) -> DefId {
DefId { krate: self, index: CRATE_DEF_INDEX } DefId { krate: self, index: CRATE_DEF_INDEX }
} }
#[inline]
pub fn as_mod_def_id(self) -> ModDefId {
ModDefId::new_unchecked(DefId { krate: self, index: CRATE_DEF_INDEX })
}
} }
impl fmt::Display for CrateNum { impl fmt::Display for CrateNum {
@ -485,3 +491,92 @@ impl<CTX: HashStableContext> ToStableHashKey<CTX> for CrateNum {
self.as_def_id().to_stable_hash_key(hcx) self.as_def_id().to_stable_hash_key(hcx)
} }
} }
macro_rules! typed_def_id {
($Name:ident, $LocalName:ident) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
pub struct $Name(DefId);
impl $Name {
pub const fn new_unchecked(def_id: DefId) -> Self {
Self(def_id)
}
pub fn to_def_id(self) -> DefId {
self.into()
}
pub fn is_local(self) -> bool {
self.0.is_local()
}
pub fn as_local(self) -> Option<$LocalName> {
self.0.as_local().map($LocalName::new_unchecked)
}
}
impl From<$LocalName> for $Name {
fn from(local: $LocalName) -> Self {
Self(local.0.to_def_id())
}
}
impl From<$Name> for DefId {
fn from(typed: $Name) -> Self {
typed.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
pub struct $LocalName(LocalDefId);
impl !Ord for $LocalName {}
impl !PartialOrd for $LocalName {}
impl $LocalName {
pub const fn new_unchecked(def_id: LocalDefId) -> Self {
Self(def_id)
}
pub fn to_def_id(self) -> DefId {
self.0.into()
}
pub fn to_local_def_id(self) -> LocalDefId {
self.0
}
}
impl From<$LocalName> for LocalDefId {
fn from(typed: $LocalName) -> Self {
typed.0
}
}
impl From<$LocalName> for DefId {
fn from(typed: $LocalName) -> Self {
typed.0.into()
}
}
};
}
// N.B.: when adding new typed `DefId`s update the corresponding trait impls in
// `rustc_middle::dep_graph::def_node` for `DepNodeParams`.
typed_def_id! { ModDefId, LocalModDefId }
impl LocalModDefId {
pub const CRATE_DEF_ID: Self = Self::new_unchecked(CRATE_DEF_ID);
}
impl ModDefId {
pub fn is_top_level_module(self) -> bool {
self.0.is_top_level_module()
}
}
impl LocalModDefId {
pub fn is_top_level_module(self) -> bool {
self.0.is_top_level_module()
}
}

View file

@ -9,7 +9,7 @@ use rustc_ast as ast;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId}; use rustc_hir::def_id::{DefId, DefIdSet, LocalModDefId};
use rustc_hir::Mutability; use rustc_hir::Mutability;
use rustc_metadata::creader::{CStore, LoadedMacro}; use rustc_metadata::creader::{CStore, LoadedMacro};
use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::fast_reject::SimplifiedType;
@ -138,7 +138,7 @@ pub(crate) fn try_inline(
pub(crate) fn try_inline_glob( pub(crate) fn try_inline_glob(
cx: &mut DocContext<'_>, cx: &mut DocContext<'_>,
res: Res, res: Res,
current_mod: LocalDefId, current_mod: LocalModDefId,
visited: &mut DefIdSet, visited: &mut DefIdSet,
inlined_names: &mut FxHashSet<(ItemType, Symbol)>, inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
import: &hir::Item<'_>, import: &hir::Item<'_>,
@ -154,7 +154,7 @@ pub(crate) fn try_inline_glob(
// reexported by the glob, e.g. because they are shadowed by something else. // reexported by the glob, e.g. because they are shadowed by something else.
let reexports = cx let reexports = cx
.tcx .tcx
.module_children_local(current_mod) .module_children_local(current_mod.to_local_def_id())
.iter() .iter()
.filter(|child| !child.reexport_chain.is_empty()) .filter(|child| !child.reexport_chain.is_empty())
.filter_map(|child| child.res.opt_def_id()) .filter_map(|child| child.res.opt_def_id())

View file

@ -1551,7 +1551,7 @@ fn first_non_private<'tcx>(
} }
[parent, leaf] if parent.ident.name == kw::Super => { [parent, leaf] if parent.ident.name == kw::Super => {
let parent_mod = cx.tcx.parent_module(hir_id); let parent_mod = cx.tcx.parent_module(hir_id);
if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod) { if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
(super_parent, leaf.ident) (super_parent, leaf.ident)
} else { } else {
// If we can't find the parent of the parent, then the parent is already the crate. // If we can't find the parent of the parent, then the parent is already the crate.
@ -2828,7 +2828,7 @@ fn clean_use_statement_inner<'tcx>(
// The parent of the module in which this import resides. This // The parent of the module in which this import resides. This
// is the same as `current_mod` if that's already the top // is the same as `current_mod` if that's already the top
// level module. // level module.
let parent_mod = cx.tcx.parent_module_from_def_id(current_mod); let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
// This checks if the import can be seen from a higher level module. // This checks if the import can be seen from a higher level module.
// In other words, it checks if the visibility is the equivalent of // In other words, it checks if the visibility is the equivalent of

View file

@ -83,7 +83,7 @@ use rustc_ast::Attribute;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::unhash::UnhashMap; use rustc_data_structures::unhash::UnhashMap;
use rustc_hir::def::{DefKind, Res}; use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, LOCAL_CRATE};
use rustc_hir::hir_id::{HirIdMap, HirIdSet}; use rustc_hir::hir_id::{HirIdMap, HirIdSet};
use rustc_hir::intravisit::{walk_expr, FnKind, Visitor}; use rustc_hir::intravisit::{walk_expr, FnKind, Visitor};
use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk}; use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk};
@ -2370,11 +2370,11 @@ pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
false false
} }
static TEST_ITEM_NAMES_CACHE: OnceLock<Mutex<FxHashMap<LocalDefId, Vec<Symbol>>>> = OnceLock::new(); static TEST_ITEM_NAMES_CACHE: OnceLock<Mutex<FxHashMap<LocalModDefId, Vec<Symbol>>>> = OnceLock::new();
fn with_test_item_names(tcx: TyCtxt<'_>, module: LocalDefId, f: impl Fn(&[Symbol]) -> bool) -> bool { fn with_test_item_names(tcx: TyCtxt<'_>, module: LocalModDefId, f: impl Fn(&[Symbol]) -> bool) -> bool {
let cache = TEST_ITEM_NAMES_CACHE.get_or_init(|| Mutex::new(FxHashMap::default())); let cache = TEST_ITEM_NAMES_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
let mut map: MutexGuard<'_, FxHashMap<LocalDefId, Vec<Symbol>>> = cache.lock().unwrap(); let mut map: MutexGuard<'_, FxHashMap<LocalModDefId, Vec<Symbol>>> = cache.lock().unwrap();
let value = map.entry(module); let value = map.entry(module);
match value { match value {
Entry::Occupied(entry) => f(entry.get()), Entry::Occupied(entry) => f(entry.get()),