@@ -497,6 +497,43 @@ pub fn path_to_local_id(expr: &Expr<'_>, id: HirId) -> bool {
497
497
path_to_local ( expr) == Some ( id)
498
498
}
499
499
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
+
500
537
/// Resolves a def path like `std::vec::Vec`.
501
538
/// This function is expensive and should be used sparingly.
502
539
pub fn def_path_res ( cx : & LateContext < ' _ > , path : & [ & str ] ) -> Res {
0 commit comments