Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit bea09a2

Browse files
committed
Add path_def_id util
1 parent cc97592 commit bea09a2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

clippy_utils/src/lib.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,43 @@ pub fn path_to_local_id(expr: &Expr<'_>, id: HirId) -> bool {
497497
path_to_local(expr) == Some(id)
498498
}
499499

500+
pub trait MaybePath<'hir> {
501+
fn hir_id(&self) -> HirId;
502+
fn qpath_opt(&self) -> Option<&QPath<'hir>>;
503+
}
504+
505+
macro_rules! maybe_path {
506+
($ty:ident, $kind:ident) => {
507+
impl<'hir> MaybePath<'hir> for hir::$ty<'hir> {
508+
fn hir_id(&self) -> HirId {
509+
self.hir_id
510+
}
511+
fn qpath_opt(&self) -> Option<&QPath<'hir>> {
512+
match &self.kind {
513+
hir::$kind::Path(qpath) => Some(qpath),
514+
_ => None,
515+
}
516+
}
517+
}
518+
};
519+
}
520+
maybe_path!(Expr, ExprKind);
521+
maybe_path!(Pat, PatKind);
522+
maybe_path!(Ty, TyKind);
523+
524+
/// If `maybe_path` is a path node, resolves it, otherwise returns `Res::Err`
525+
pub fn path_res<'tcx>(cx: &LateContext<'_>, maybe_path: &impl MaybePath<'tcx>) -> Res {
526+
match maybe_path.qpath_opt() {
527+
None => Res::Err,
528+
Some(qpath) => cx.qpath_res(qpath, maybe_path.hir_id()),
529+
}
530+
}
531+
532+
/// If `maybe_path` is a path node which resolves to an item, retrieves the item ID
533+
pub fn path_def_id<'tcx>(cx: &LateContext<'_>, maybe_path: &impl MaybePath<'tcx>) -> Option<DefId> {
534+
path_res(cx, maybe_path).opt_def_id()
535+
}
536+
500537
/// Resolves a def path like `std::vec::Vec`.
501538
/// This function is expensive and should be used sparingly.
502539
pub fn def_path_res(cx: &LateContext<'_>, path: &[&str]) -> Res {

0 commit comments

Comments
 (0)