From 99049b3aa80a9aa75fed0acf29956508778df371 Mon Sep 17 00:00:00 2001 From: Jacob Greenfield Date: Tue, 15 Jul 2025 21:52:43 -0400 Subject: [PATCH] Add `DefId::parent()` accessor in `rustc_public` --- compiler/rustc_public/src/compiler_interface.rs | 8 ++++++++ compiler/rustc_public/src/crate_def.rs | 6 ++++++ compiler/rustc_public_bridge/src/context/impls.rs | 5 +++++ 3 files changed, 19 insertions(+) diff --git a/compiler/rustc_public/src/compiler_interface.rs b/compiler/rustc_public/src/compiler_interface.rs index b17d31f2b91a..2cb1157a5c25 100644 --- a/compiler/rustc_public/src/compiler_interface.rs +++ b/compiler/rustc_public/src/compiler_interface.rs @@ -249,6 +249,14 @@ pub(crate) fn def_name(&self, def_id: DefId, trimmed: bool) -> Symbol { cx.def_name(did, trimmed) } + /// Returns the parent of the given `DefId`. + pub(crate) fn def_parent(&self, def_id: DefId) -> Option { + 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 diff --git a/compiler/rustc_public/src/crate_def.rs b/compiler/rustc_public/src/crate_def.rs index 75228135e4cb..7ab123544e3b 100644 --- a/compiler/rustc_public/src/crate_def.rs +++ b/compiler/rustc_public/src/crate_def.rs @@ -29,6 +29,12 @@ pub fn name(&self) -> Symbol { 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 { + with(|cx| cx.def_parent(*self)) + } } /// A trait for retrieving information about a particular definition. diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 25be9e7b3041..cbb00d64e096 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -268,6 +268,11 @@ pub fn def_name(&self, def_id: DefId, trimmed: bool) -> String { } } + /// Returns the parent of the given `DefId`. + pub fn def_parent(&self, def_id: DefId) -> Option { + self.tcx.opt_parent(def_id) + } + /// Return registered tool attributes with the given attribute name. /// /// FIXME(jdonszelmann): may panic on non-tool attributes. After more attribute work, non-tool