Skip to content

Commit 403c7fc

Browse files
authored
Rollup merge of rust-lang#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).
2 parents 8721ae8 + dc37dae commit 403c7fc

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

compiler/rustc_public/src/compiler_interface.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,14 @@ impl<'tcx> CompilerInterface<'tcx> {
249249
cx.def_name(did, trimmed)
250250
}
251251

252+
/// Returns the parent of the given `DefId`.
253+
pub(crate) fn def_parent(&self, def_id: DefId) -> Option<DefId> {
254+
let mut tables = self.tables.borrow_mut();
255+
let cx = &*self.cx.borrow();
256+
let did = tables[def_id];
257+
cx.def_parent(did).map(|did| tables.create_def_id(did))
258+
}
259+
252260
/// Return registered tool attributes with the given attribute name.
253261
///
254262
/// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool

compiler/rustc_public/src/crate_def.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ impl DefId {
2828
pub fn trimmed_name(&self) -> Symbol {
2929
with(|cx| cx.def_name(*self, true))
3030
}
31+
32+
/// Return the parent of this definition, or `None` if this is the root of a
33+
/// crate.
34+
pub fn parent(&self) -> Option<DefId> {
35+
with(|cx| cx.def_parent(*self))
36+
}
3137
}
3238

3339
/// A trait for retrieving information about a particular definition.

0 commit comments

Comments
 (0)