aboutsummaryrefslogtreecommitdiff
path: root/macros/src/injectable_macro_args.rs
blob: 43f8e117cb072fd1f5b1304e8cb8b626f377d292 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{braced, Ident, LitBool, Token, TypePath};

use crate::util::iterator_ext::IteratorExt;

pub const INJECTABLE_MACRO_FLAGS: &[&str] = &["no_doc_hidden"];

pub struct InjectableMacroFlag
{
    pub flag: Ident,
    pub is_on: LitBool,
}

impl Parse for InjectableMacroFlag
{
    fn parse(input: ParseStream) -> syn::Result<Self>
    {
        let input_forked = input.fork();

        let flag: Ident = input_forked.parse()?;

        let flag_str = flag.to_string();

        if !INJECTABLE_MACRO_FLAGS.contains(&flag_str.as_str()) {
            return Err(input.error(format!(
                "Unknown flag '{}'. Expected one of [ {} ]",
                flag_str,
                INJECTABLE_MACRO_FLAGS.join(",")
            )));
        }

        input.parse::<Ident>()?;

        input.parse::<Token![=]>()?;

        let is_on: LitBool = input.parse()?;

        Ok(Self { flag, is_on })
    }
}

pub struct InjectableMacroArgs
{
    pub interface: Option<TypePath>,
    pub flags: Punctuated<InjectableMacroFlag, Token![,]>,
}

impl Parse for InjectableMacroArgs
{
    fn parse(input: ParseStream) -> syn::Result<Self>
    {
        let interface = input.parse::<TypePath>().ok();

        if interface.is_some() {
            let comma_input_lookahead = input.lookahead1();

            if !comma_input_lookahead.peek(Token![,]) {
                return Ok(Self {
                    interface,
                    flags: Punctuated::new(),
                });
            }

            input.parse::<Token![,]>()?;
        }

        if input.is_empty() {
            return Ok(Self {
                interface,
                flags: Punctuated::new(),
            });
        }

        let braced_content;

        braced!(braced_content in input);

        let flags = braced_content.parse_terminated(InjectableMacroFlag::parse)?;

        let flag_names = flags
            .iter()
            .map(|flag| flag.flag.to_string())
            .collect::<Vec<_>>();

        if let Some(dupe_flag_name) = flag_names.iter().find_duplicate() {
            return Err(input.error(format!("Duplicate flag '{}'", dupe_flag_name)));
        }

        Ok(Self { interface, flags })
    }
}