xref: /linux/rust/macros/helpers.rs (revision 12d5fc96ebbb3b948861805b32a4c3a96105ccd9)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 use proc_macro2::TokenStream;
4 use quote::ToTokens;
5 use syn::{
6     parse::{
7         Parse,
8         ParseStream, //
9     },
10     Attribute,
11     Error,
12     LitStr,
13     Result, //
14 };
15 
16 /// A string literal that is required to have ASCII value only.
17 pub(crate) struct AsciiLitStr(LitStr);
18 
19 impl Parse for AsciiLitStr {
20     fn parse(input: ParseStream<'_>) -> Result<Self> {
21         let s: LitStr = input.parse()?;
22         if !s.value().is_ascii() {
23             return Err(Error::new_spanned(s, "expected ASCII-only string literal"));
24         }
25         Ok(Self(s))
26     }
27 }
28 
29 impl ToTokens for AsciiLitStr {
30     fn to_tokens(&self, ts: &mut TokenStream) {
31         self.0.to_tokens(ts);
32     }
33 }
34 
35 impl AsciiLitStr {
36     pub(crate) fn value(&self) -> String {
37         self.0.value()
38     }
39 }
40 
41 /// Obtain all `#[cfg]` attributes.
42 pub(crate) fn gather_cfg_attrs(attr: &[Attribute]) -> impl Iterator<Item = &Attribute> + '_ {
43     attr.iter().filter(|a| a.path().is_ident("cfg"))
44 }
45