spl_discriminator_syn/
parser.rs

1//! Parser for the `syn` crate to parse the
2//! `#[discriminator_hash_input("...")]` attribute
3
4use {
5    crate::error::SplDiscriminateError,
6    syn::{
7        parse::{Parse, ParseStream},
8        token::Comma,
9        Attribute, LitStr,
10    },
11};
12
13/// Struct used for `syn` parsing of the hash_input attribute
14/// #[discriminator_hash_input("...")]
15struct HashInputValueParser {
16    value: LitStr,
17    _comma: Option<Comma>,
18}
19
20impl Parse for HashInputValueParser {
21    fn parse(input: ParseStream) -> syn::Result<Self> {
22        let value: LitStr = input.parse()?;
23        let _comma: Option<Comma> = input.parse().unwrap_or(None);
24        Ok(HashInputValueParser { value, _comma })
25    }
26}
27
28/// Parses the hash_input from the `#[discriminator_hash_input("...")]`
29/// attribute
30pub fn parse_hash_input(attrs: &[Attribute]) -> Result<String, SplDiscriminateError> {
31    match attrs
32        .iter()
33        .find(|a| a.path().is_ident("discriminator_hash_input"))
34    {
35        Some(attr) => {
36            let parsed_args = attr
37                .parse_args::<HashInputValueParser>()
38                .map_err(|_| SplDiscriminateError::HashInputAttributeParseError)?;
39            Ok(parsed_args.value.value())
40        }
41        None => Err(SplDiscriminateError::HashInputAttributeNotProvided),
42    }
43}