Files
aho_corasick
anyhow
drone_config
drone_core
drone_core_macros
drone_ctypes
drone_macros_core
futures
futures_channel
futures_core
futures_io
futures_macro
futures_sink
futures_task
futures_util
if_chain
inflector
cases
camelcase
case
classcase
kebabcase
pascalcase
screamingsnakecase
sentencecase
snakecase
tablecase
titlecase
traincase
numbers
deordinalize
ordinalize
string
constants
deconstantize
demodulize
pluralize
singularize
suffix
foreignkey
lazy_static
memchr
pin_project_lite
pin_utils
proc_macro2
proc_macro_hack
proc_macro_nested
quote
regex
regex_syntax
serde
serde_derive
syn
toml
typenum
unicode_xid
  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
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use drone_macros_core::{unkeywordize, CfgCond, CfgCondExt};
use inflector::Inflector;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
    braced,
    parse::{Parse, ParseStream, Result},
    parse_macro_input, Attribute, Ident, Path, Token,
};

const MACRO_PREFIX: &str = "periph_";
const STRUCT_SUFFIX: &str = "Periph";

struct Input {
    macro_attrs: Vec<Attribute>,
    macro_ident: Ident,
    struct_attrs: Vec<Attribute>,
    struct_ident: Ident,
    root_path: Path,
    macro_root_path: Option<Path>,
    blocks: Vec<Block>,
}

struct Block {
    ident: Ident,
    regs: Vec<Reg>,
}

struct Reg {
    features: CfgCond,
    ident: Ident,
    fields: Vec<Field>,
}

struct Field {
    features: CfgCond,
    ident: Ident,
}

impl Parse for Input {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let macro_attrs = input.call(Attribute::parse_outer)?;
        input.parse::<Token![pub]>()?;
        input.parse::<Token![macro]>()?;
        let macro_ident = input.parse::<Ident>()?;
        if !macro_ident.to_string().starts_with(MACRO_PREFIX) {
            return Err(
                input.error(format!("Expected an ident which starts with `{}`", MACRO_PREFIX))
            );
        }
        input.parse::<Token![;]>()?;
        let struct_attrs = input.call(Attribute::parse_outer)?;
        input.parse::<Token![pub]>()?;
        input.parse::<Token![struct]>()?;
        let struct_ident = input.parse::<Ident>()?;
        if !struct_ident.to_string().ends_with(STRUCT_SUFFIX) {
            return Err(
                input.error(format!("Expected an ident which ends with `{}`", STRUCT_SUFFIX))
            );
        }
        input.parse::<Token![;]>()?;
        let root_path = input.parse()?;
        input.parse::<Token![;]>()?;
        input.parse::<Token![crate]>()?;
        let macro_root_path = if input.peek(Token![;]) {
            input.parse::<Token![;]>()?;
            None
        } else {
            let path = input.parse()?;
            input.parse::<Token![;]>()?;
            Some(path)
        };
        let mut blocks = Vec::new();
        while !input.is_empty() {
            blocks.push(input.parse()?);
        }
        Ok(Self {
            macro_attrs,
            macro_ident,
            struct_attrs,
            struct_ident,
            root_path,
            macro_root_path,
            blocks,
        })
    }
}

impl Parse for Block {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let ident = input.parse()?;
        let content;
        braced!(content in input);
        let mut regs = Vec::new();
        while !content.is_empty() {
            regs.push(content.parse()?);
        }
        Ok(Self { ident, regs })
    }
}

impl Parse for Reg {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let features = input.parse()?;
        let ident = input.parse()?;
        let mut fields = Vec::new();
        if input.peek(Token![;]) {
            input.parse::<Token![;]>()?;
        } else {
            let content;
            braced!(content in input);
            while !content.is_empty() {
                fields.push(content.parse()?);
            }
        }
        Ok(Self { features, ident, fields })
    }
}

impl Parse for Field {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let features = input.parse()?;
        let ident = input.parse()?;
        input.parse::<Token![;]>()?;
        Ok(Self { features, ident })
    }
}

pub fn proc_macro(input: TokenStream) -> TokenStream {
    let Input {
        macro_attrs,
        macro_ident,
        struct_attrs,
        struct_ident,
        root_path,
        macro_root_path,
        blocks,
    } = &parse_macro_input!(input);
    let mut tokens = Vec::new();
    let mut periph_tokens = Vec::new();
    let mut macro_tokens = Vec::new();
    for Block { ident: block_ident, regs } in blocks {
        let block_snk = block_ident.to_string().to_snake_case();
        let block_ident = format_ident!("{}", unkeywordize(&block_snk));
        for Reg { features: reg_features, ident: reg_ident, fields } in regs {
            let reg_snk = reg_ident.to_string().to_snake_case();
            let reg_ident = format_ident!("{}", unkeywordize(&reg_snk));
            let block_reg_snk = format_ident!("{}_{}", block_snk, reg_snk);
            let reg_attrs = reg_features.attrs();
            if fields.is_empty() {
                periph_tokens.push(quote! {
                    #[allow(missing_docs)]
                    #reg_attrs
                    pub #block_reg_snk: #root_path::#block_ident::#reg_ident::Reg<
                        ::drone_core::reg::tag::Srt,
                    >
                });
                macro_tokens
                    .push((reg_features.clone(), quote!(#block_reg_snk: $reg.#block_reg_snk)));
            } else {
                for Field { features: field_features, ident: field_ident } in fields {
                    let field_snk = field_ident.to_string().to_snake_case();
                    let field_psc = format_ident!("{}", field_ident.to_string().to_pascal_case());
                    let field_ident = format_ident!("{}", unkeywordize(&field_snk));
                    let block_reg_field_snk =
                        format_ident!("{}_{}_{}", block_snk, reg_snk, field_snk);
                    let mut features = CfgCond::default();
                    features.add_clause(&reg_features);
                    features.add_clause(&field_features);
                    let field_attrs = features.attrs();
                    periph_tokens.push(quote! {
                        #[allow(missing_docs)]
                        #field_attrs
                        pub #block_reg_field_snk: #root_path::#block_ident::#reg_ident::#field_psc<
                            ::drone_core::reg::tag::Srt,
                        >
                    });
                    macro_tokens.push((
                        features,
                        quote!(#block_reg_field_snk: $reg.#block_reg_snk.#field_ident),
                    ));
                }
            }
        }
    }
    for (features, macro_tokens) in macro_tokens.as_slice().transpose() {
        let attrs = features.attrs();
        let macro_root_path = macro_root_path.iter();
        tokens.push(quote! {
            #attrs
            #(#macro_attrs)*
            #[macro_export]
            macro_rules! #macro_ident {
                ($reg:ident) => {
                    $crate#(#macro_root_path)*::#struct_ident {
                        #(#macro_tokens,)*
                    }
                };
            }
        });
    }
    let expanded = quote! {
        #(#struct_attrs)*
        pub struct #struct_ident {
            #(#periph_tokens,)*
        }

        #(#tokens)*
    };
    expanded.into()
}