about summary refs log tree commit diff
path: root/compiler/rustc_attr_data_structures/src
diff options
context:
space:
mode:
authorMatthias Krüger <476013+matthiaskrgr@users.noreply.github.com>2025-03-09 10:34:52 +0100
committerGitHub <noreply@github.com>2025-03-09 10:34:52 +0100
commitd88752a4b50b892fd10577980391efd3395ac715 (patch)
treec968104861765508430ec7fc05f8ffe763c77528 /compiler/rustc_attr_data_structures/src
parentbfa1a62fd4ef118a5263807a2cb260c6d612b116 (diff)
parent4203e9c56d8aa6cdfe5f5a60bd510917b84188c7 (diff)
downloadrust-d88752a4b50b892fd10577980391efd3395ac715.tar.gz
rust-d88752a4b50b892fd10577980391efd3395ac715.zip
Rollup merge of #138160 - jdonszelmann:move-find-attr2, r=oli-obk
depend more on attr_data_structures and move find_attr! there

r?  ``@oli-obk``

This should be an easy one. It just moves some imports around. This is necessary for other changes that I'm working on not to have import cycles. However, it's an easy one to just merge on its own.
Diffstat (limited to 'compiler/rustc_attr_data_structures/src')
-rw-r--r--compiler/rustc_attr_data_structures/src/lib.rs44
1 files changed, 44 insertions, 0 deletions
diff --git a/compiler/rustc_attr_data_structures/src/lib.rs b/compiler/rustc_attr_data_structures/src/lib.rs
index d90be4bd5fe..be00d1c10e0 100644
--- a/compiler/rustc_attr_data_structures/src/lib.rs
+++ b/compiler/rustc_attr_data_structures/src/lib.rs
@@ -148,3 +148,47 @@ print_tup!(A B C D E F G H);
 print_skip!(Span, ());
 print_disp!(Symbol, u16, bool, NonZero<u32>);
 print_debug!(UintTy, IntTy, Align, AttrStyle, CommentKind, Transparency);
+
+/// Finds attributes in sequences of attributes by pattern matching.
+///
+/// A little like `matches` but for attributes.
+///
+/// ```rust,ignore (illustrative)
+/// // finds the repr attribute
+/// if let Some(r) = find_attr!(attrs, AttributeKind::Repr(r) => r) {
+///
+/// }
+///
+/// // checks if one has matched
+/// if find_attr!(attrs, AttributeKind::Repr(_)) {
+///
+/// }
+/// ```
+///
+/// Often this requires you to first end up with a list of attributes.
+/// A common way to get those is through `tcx.get_all_attrs(did)`
+#[macro_export]
+macro_rules! find_attr {
+    ($attributes_list: expr, $pattern: pat $(if $guard: expr)?) => {{
+        $crate::find_attr!($attributes_list, $pattern $(if $guard)? => ()).is_some()
+    }};
+
+    ($attributes_list: expr, $pattern: pat $(if $guard: expr)? => $e: expr) => {{
+        fn check_attribute_iterator<'a>(_: &'_ impl IntoIterator<Item = &'a rustc_hir::Attribute>) {}
+        check_attribute_iterator(&$attributes_list);
+
+        let find_attribute = |iter| {
+            for i in $attributes_list {
+                match i {
+                    rustc_hir::Attribute::Parsed($pattern) $(if $guard)? => {
+                        return Some($e);
+                    }
+                    _ => {}
+                }
+            }
+
+            None
+        };
+        find_attribute($attributes_list)
+    }};
+}