Skip to content

Commit 0d7abc8

Browse files
committed
Introduce assoc_parent
1 parent 96aca2b commit 0d7abc8

File tree

2 files changed

+11
-14
lines changed

2 files changed

+11
-14
lines changed

compiler/rustc_hir/src/def.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,10 @@ impl DefKind {
295295
}
296296
}
297297

298+
pub fn is_assoc(self) -> bool {
299+
matches!(self, DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy)
300+
}
301+
298302
/// This is a "module" in name resolution sense.
299303
#[inline]
300304
pub fn is_module_like(self) -> bool {

compiler/rustc_middle/src/ty/mod.rs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1988,29 +1988,22 @@ impl<'tcx> TyCtxt<'tcx> {
19881988
self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
19891989
}
19901990

1991+
/// If the given `DefId` is an associated item, returns the `DefId` of the parent trait or impl.
1992+
pub fn assoc_parent(self, def_id: DefId) -> Option<DefId> {
1993+
self.def_kind(def_id).is_assoc().then(|| self.parent(def_id))
1994+
}
1995+
19911996
/// If the given `DefId` describes an item belonging to a trait,
19921997
/// returns the `DefId` of the trait that the trait item belongs to;
19931998
/// otherwise, returns `None`.
19941999
pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
1995-
if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1996-
let parent = self.parent(def_id);
1997-
if let DefKind::Trait = self.def_kind(parent) {
1998-
return Some(parent);
1999-
}
2000-
}
2001-
None
2000+
self.assoc_parent(def_id).filter(|id| self.def_kind(id) == DefKind::Trait)
20022001
}
20032002

20042003
/// If the given `DefId` describes a method belonging to an impl, returns the
20052004
/// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
20062005
pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2007-
if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2008-
let parent = self.parent(def_id);
2009-
if let DefKind::Impl { .. } = self.def_kind(parent) {
2010-
return Some(parent);
2011-
}
2012-
}
2013-
None
2006+
self.assoc_parent(def_id).filter(|id| matches!(self.def_kind(id), DefKind::Impl { .. }))
20142007
}
20152008

20162009
pub fn is_exportable(self, def_id: DefId) -> bool {

0 commit comments

Comments
 (0)