embedded-command-macros 0.5.0

Macros for the embedded command crate family.
Documentation
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::collections::HashSet;

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Index, Type, Variant};

use crate::serac::BodyInfo;

fn get_repr<'a>(mut attrs: impl Iterator<Item = &'a Attribute>) -> Type {
    attrs
        .find(|&attr| attr.path().is_ident("repr"))
        .expect("Enum must have #[repr(...)] attribute.")
        .parse_args()
        .expect("#[repr(...) can only have one type.")
}

fn build_tags<'a>(variants: impl Iterator<Item = &'a &'a Variant>) -> Vec<TokenStream2> {
    let mut tags = Vec::new();
    let mut i = 0; // count up by one starting at any known tag
    let mut last_anchor = quote! { 0 };

    for variant in variants {
        if let Some((_, tag)) = &variant.discriminant {
            // a tag is provided, restart counter and update as last anchor
            let tokens = quote! { #tag };
            tags.push(tokens.clone());
            i = 0;
            last_anchor = tokens;
        } else {
            // a tag was not explicitly provided, we need to count up from last anchor
            let rendered_offset = Index::from(i);
            tags.push(quote! { #last_anchor + #rendered_offset });
        }
        i += 1;
    }

    tags
}

fn serialize_struct(s: DataStruct, info: &BodyInfo) -> TokenStream2 {
    let implementer = &info.ident;
    let path = &info.path;
    let (impl_generics, ty_generics, where_clause) = info.generics.split_for_impl();

    let types: Vec<_> = s.fields.iter().map(|field| &field.ty).collect();

    let (ser_body, deser_body) = match &s.fields {
        Fields::Unit => (quote! { Ok(()) }, quote! { Ok(Self) }),
        Fields::Unnamed(fields) => {
            let attr_tags: Vec<_> = fields
                .unnamed
                .iter()
                .enumerate()
                .map(|(i, _)| Index::from(i))
                .collect();

            (
                quote! {
                    #(
                        #path::SerializeIter::ser(&self.#attr_tags, dst)?;
                    )*

                    Ok(())
                },
                quote! {
                    Ok(
                        Self(
                            #(
                                <#types as #path::SerializeIter>::de(src)?,
                            )*
                        )
                    )
                },
            )
        }
        Fields::Named(fields) => {
            let attr_idents: Vec<_> = fields
                .named
                .iter()
                .map(|field| field.ident.as_ref().unwrap())
                .collect();

            (
                quote! {
                    #(
                        #path::SerializeIter::ser(&self.#attr_idents, dst)?;
                    )*

                    Ok(())
                },
                quote! {
                    Ok(
                        Self {
                            #(
                                #attr_idents: <#types as #path::SerializeIter>::de(src)?,
                            )*
                        }
                    )
                },
            )
        }
    };

    let (.., types) = size_of_struct(s, info);

    let where_clause = {
        let constraints = types.iter().map(|ty| {
            quote! { #ty: #path::SerializeIter }
        });

        match where_clause {
            Some(w) => quote! { #w #(#constraints,)* },
            None => quote! { where #(#constraints,)* },
        }
    };

    quote! {
        impl #impl_generics #path::SerializeIter for #implementer #ty_generics #where_clause {
            fn ser<'a>(&self, dst: &mut #path::Buf<impl Iterator<Item = &'a mut <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word>>) -> Result<(), #path::error::EndOfInput>
            where
                <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word: 'a,
            {
                #ser_body
            }

            fn de<'a>(src: &mut #path::Buf<impl Iterator<Item = &'a <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word>>) -> Result<Self, #path::error::Error>
            where
                <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word: 'a,
            {
                #deser_body
            }
        }
    }
}

fn size_of_struct(s: DataStruct, info: &BodyInfo) -> (TokenStream2, HashSet<Type>) {
    let types: Vec<_> = s.fields.iter().map(|field| field.ty.clone()).collect();
    let path = &info.path;

    (
        if types.is_empty() {
            quote! { 0 }
        } else {
            quote! { #( <#types as #path::Size>::SIZE )+* }
        },
        HashSet::from_iter(types),
    )
}

fn serialize_enum(e: DataEnum, info: &BodyInfo, repr: Type) -> TokenStream2 {
    let implementer = &info.ident;
    let path = &info.path;
    let (impl_generics, ty_generics, where_clause) = info.generics.split_for_impl();
    let variants: Vec<_> = e.variants.iter().collect();

    let tags: Vec<_> = build_tags(variants.iter());
    let tag_consts: Vec<_> = variants
        .iter()
        .map(|variant| {
            let ident = &variant.ident;
            format_ident!(
                "{}_TAG",
                inflector::cases::screamingsnakecase::to_screaming_snake_case(&ident.to_string())
            )
        })
        .collect();

    let ser_arms: Vec<_> = variants
        .iter()
        .zip(tag_consts.iter())
        .map(|(variant, tag_const)| {
            let ident = &variant.ident;
            match &variant.fields {
                Fields::Unit => quote! {
                    #ident => #path::SerializeIter::ser(&#tag_const, dst)
                },
                Fields::Unnamed(fields) => {
                    let idents: Vec<_> = fields
                        .unnamed
                        .iter()
                        .enumerate()
                        .map(|(i, _field)| {
                            let ident = format_ident!("v{i}");

                            quote! { #ident }
                        })
                        .collect();

                    quote! {
                        #ident(#(#idents),*) => {
                            #path::SerializeIter::ser(&#tag_const, dst)?;
                            #(
                                #path::SerializeIter::ser(#idents, dst)?;
                            )*

                            Ok(())
                        }
                    }
                }
                Fields::Named(fields) => {
                    let idents: Vec<_> = fields
                        .named
                        .iter()
                        .map(|field| field.ident.as_ref().unwrap())
                        .collect();

                    quote! {
                        #ident{#(#idents),*} => {
                            #path::SerializeIter::ser(&#tag_const, dst)?;
                            #(
                                #path::SerializeIter::ser(#idents, dst)?;
                            )*

                            Ok(())
                        }
                    }
                }
            }
        })
        .collect();

    let deser_arms: Vec<_> = variants
        .iter()
        .map(|variant| {
            let ident = &variant.ident;
            match &variant.fields {
                Fields::Unit => quote! {
                    #ident
                },
                Fields::Unnamed(fields) => {
                    let types: Vec<_> = fields.unnamed.iter().map(|field| &field.ty).collect();
                    quote! {
                        #ident (
                            #(
                                <#types as #path::SerializeIter>::de(src)?,
                            )*
                        )
                    }
                }
                Fields::Named(fields) => {
                    let idents: Vec<_> = fields
                        .named
                        .iter()
                        .map(|field| field.ident.as_ref().unwrap())
                        .collect();
                    let types: Vec<_> = fields.named.iter().map(|field| &field.ty).collect();

                    quote! {
                        #ident {
                            #(
                                #idents: <#types as #path::SerializeIter>::de(src)?,
                            )*
                        }
                    }
                }
            }
        })
        .collect();

    let (.., types) = size_of_enum(e, info, repr.clone());

    let where_clause = {
        let constraints = types.iter().map(|ty| {
            quote! { #ty: #path::SerializeIter }
        });

        match where_clause {
            Some(w) => quote! { #w #(#constraints,)* },
            None => quote! { where #(#constraints,)* },
        }
    };

    quote! {
        impl #impl_generics #path::SerializeIter for #implementer #ty_generics #where_clause {
            fn ser<'a>(&self, dst: &mut #path::Buf<impl Iterator<Item = &'a mut <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word>>) -> Result<(), #path::error::EndOfInput>
            where
                <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word: 'a,
            {
                #(
                    const #tag_consts: #repr = #tags;
                )*

                match self {
                    #(
                        Self::#ser_arms,
                    )*
                }
            }

            fn de<'a>(src: &mut #path::Buf<impl Iterator<Item = &'a <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word>>) -> Result<Self, #path::error::Error>
            where
                <#path::encoding::vanilla::Vanilla as #path::encoding::Encoding>::Word: 'a,
            {
                #(
                    const #tag_consts: #repr = #tags;
                )*

                let tag = <#repr as #path::SerializeIter>::de(src)?;

                match tag {
                    #(
                        #tag_consts => Ok(Self::#deser_arms),
                    )*
                    _ => Err(#path::error::Error::Invalid)
                }
            }
        }
    }
}

fn size_of_enum(e: DataEnum, info: &BodyInfo, repr: Type) -> (TokenStream2, HashSet<Type>) {
    let mut types = HashSet::new();

    let path = &info.path;
    let sizes: Vec<_> = e
        .variants
        .iter()
        .filter_map(|variant| {
            if !variant.fields.is_empty() {
                let variant_types: Vec<_> = variant
                    .fields
                    .iter()
                    .map(|field| field.ty.clone())
                    .collect();

                types.extend(variant_types.iter().cloned());

                Some(quote! { #(<#variant_types as #path::Size>::SIZE)+* })
            } else {
                None
            }
        })
        .collect();

    (
        quote! {{
            let mut max = 0;

            #(
                if #sizes > max {
                    max = #sizes;
                }
            )*

            max + <#repr as #path::Size>::SIZE
        }},
        types,
    )
}

pub fn serialize_iter(item: TokenStream) -> TokenStream {
    let item: DeriveInput = syn::parse2(item.into()).unwrap();

    let info = BodyInfo {
        ident: item.ident,
        generics: item.generics,
        path: syn::parse2(quote! { serac }).unwrap(),
    };

    let implementation = match item.data {
        Data::Struct(s) => serialize_struct(s, &info),
        Data::Enum(e) => serialize_enum(e, &info, get_repr(item.attrs.iter())),
        _ => panic!("Vanilla serializer is only implemented for structs and enums."),
    };

    implementation.into()
}

pub fn impl_size(item: TokenStream) -> TokenStream {
    let item: DeriveInput = syn::parse2(item.into()).unwrap();

    let info = BodyInfo {
        ident: item.ident,
        generics: item.generics,
        path: syn::parse2(quote! { serac }).unwrap(),
    };

    let (size, types) = match item.data {
        Data::Struct(s) => size_of_struct(s, &info),
        Data::Enum(e) => size_of_enum(e, &info, get_repr(item.attrs.iter())),
        _ => panic!("Vanilla serializer is only implemented for structs and enums."),
    };

    let (impl_generics, ty_generics, where_clause) = info.generics.split_for_impl();

    let path = info.path;
    let ident = info.ident;

    let where_clause = {
        let constraints = types.iter().map(|ty| {
            quote! { #ty: #path::Size }
        });

        match where_clause {
            Some(w) => quote! { #w #(#constraints,)* },
            None => quote! { where #(#constraints,)* },
        }
    };

    quote! {
        unsafe impl #impl_generics #path::Size for #ident #ty_generics #where_clause {
            const SIZE: usize = #size;
        }
    }
    .into()
}