Rollup merge of #144000 - jacob-greenfield:stable-defid-parent, r=celinval

Add `DefId::parent()` accessor for `rustc_public`

Adds a `parent()` method to `DefId` (the `rustc_pub` version) which exposes the parent path, ie. `foo::bar::baz` -> `foo::bar`.

This is useful for organizing/grouping definitions into a tree, and is probably simpler and less brittle than attempting to parse the fully-qualified name into path components (e.g. especially when handling path components with qualified generic parameters).
This commit is contained in:
Stuart Cook 2025-11-29 21:12:25 +11:00 committed by GitHub
commit 3a0187ec5d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 209 additions and 0 deletions

View file

@ -249,6 +249,14 @@ impl<'tcx> CompilerInterface<'tcx> {
cx.def_name(did, trimmed)
}
/// Returns the parent of the given `DefId`.
pub(crate) fn def_parent(&self, def_id: DefId) -> Option<DefId> {
let mut tables = self.tables.borrow_mut();
let cx = &*self.cx.borrow();
let did = tables[def_id];
cx.def_parent(did).map(|did| tables.create_def_id(did))
}
/// Return registered tool attributes with the given attribute name.
///
/// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool

View file

@ -28,6 +28,12 @@ impl DefId {
pub fn trimmed_name(&self) -> Symbol {
with(|cx| cx.def_name(*self, true))
}
/// Return the parent of this definition, or `None` if this is the root of a
/// crate.
pub fn parent(&self) -> Option<DefId> {
with(|cx| cx.def_parent(*self))
}
}
/// A trait for retrieving information about a particular definition.