gel-protogen 0.1.2

Macros to make parsing and serializing of PostgreSQL-like protocols easier.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/// Performs a first-pass parse on a struct, filling out some additional
/// metadata that makes the jobs of further macro passes much simpler.
///
/// This macro takes a `next` parameter which allows you to funnel the
/// structured data from the macro into the next macro.
///
/// This is a "push-down automation" and refers to how metadata and parsed
/// information are "pushed down" through the macro’s recursive structure. Each
/// level of the macro adds its own layer of processing and metadata
/// accumulation, eventually leading to the final output.
///
/// It begins by extracting and analyzing the fields of the `struct`, capturing
/// associated metadata such as attributes and types. This macro takes a `next`
/// parameter, which is another macro to be invoked after the current one
/// completes its task, allowing for a seamless chaining of macros where each
/// one builds upon the results of the previous.
///
/// The macro first makes some initial classifications of the fields based on
/// their types, then processes presence or absence of values, and finally
/// handles missing documentation.
///
/// As it processes each field, the macro recursively calls itself, accumulating
/// metadata and updating the state.
///
/// Once all fields have been processed, the macro enters the final stage, where
/// it reconstructs an enriched `struct`-like data blob using the accumulated
/// metadata. It then passes this enriched `struct` to the `next` macro for
/// further processing.
#[doc(hidden)]
#[macro_export]
macro_rules! struct_elaborate {
    (
        $next:ident $( ($($next_args:tt)*) )? =>
        $( #[ $sdoc:meta ] )*
        struct $name:ident <$lt:lifetime> $(: $super:ident)? {
            $(
                $( #[ doc = $fdoc:literal ] )* $field:ident :
                    $ty:ty
                    $( = $value:literal)?
            ),*
            $(,)?
        }
    ) => {
        // paste! is necessary here because it allows us to re-interpret a "ty"
        // as an explicit type pattern below.
        $crate::paste!($crate::struct_elaborate!(__builder_type__
            fields($(
                [
                    // Note that we double the type so we can re-use some output
                    // patterns in `__builder_type__`
                    type( $ty )( $ty ),
                    value($($value)?),
                    docs($($fdoc)*),
                    name($field),
                ]
            )*)
            // Accumulator for field data.
            accum()
            // Save the original struct parts so we can build the remainder of
            // the struct at the end.
            original($next $( ($($next_args)*) )?
                => $(#[$sdoc])* struct $name <$lt> $(: $super)? {})
        ););
    };

    // End of push-down automation - jumps to `__finalize__`
    (__builder_type__ fields() accum($($faccum:tt)*) original($($original:tt)*)) => {
        $crate::struct_elaborate!(__finalize__ accum($($faccum)*) original($($original)*));
    };

    // Translate 'len' to Length (with auto value).
    (__builder_type__ fields([type(len)(len), value(), $($rest:tt)*] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder_docs__ fields([type($crate::prelude::Length), value(auto=auto), $($rest)*] $($frest)*) $($srest)*);
    };
    // Translate 'len' to Length (with a value present).
    (__builder_type__ fields([type(len)(len), value($($value:tt)+), $($rest:tt)*] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder_docs__ fields([type($crate::prelude::Length), value(value=($($value)*)), $($rest)*] $($frest)*) $($srest)*);
    };
    // Translate fixed-size arrays to FixedArray.
    (__builder_type__ fields([type([$elem:ty; $len:literal])($ty:ty), $($rest:tt)*] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder_value__ fields([type([$elem;$len]), $($rest)*] $($frest)*) $($srest)*);
    };

    // Fallback for other types - variable sized
    (__builder_type__ fields([type($ty:ty)($ty2:ty), $($rest:tt)*] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder_value__ fields([type($ty), $($rest)*] $($frest)*) $($srest)*);
    };

    // Next, mark the presence or absence of a value
    (__builder_value__ fields([
        type($ty:ty), value(), $($rest:tt)*
    ] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder_docs__ fields([type($ty), value(no_value=no_value), $($rest)*] $($frest)*) $($srest)*);
    };
    (__builder_value__ fields([
        type($ty:ty), value($($value:tt)+), $($rest:tt)*
    ] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder_docs__ fields([type($ty), value(value=($($value)*)), $($rest)*] $($frest)*) $($srest)*);
    };

    // Next, handle missing docs by generating a stand-in.
    (__builder_docs__ fields([
        type($ty:ty), value($($value:tt)*), docs(), name($field:ident), $($rest:tt)*
    ] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder__ fields([type($ty), value($($value)*), docs(concat!("`", stringify!($field), "` field.")), name($field), $($rest)*] $($frest)*) $($srest)*);
    };
    (__builder_docs__ fields([
        type($ty:ty), value($($value:tt)*), docs($($fdoc:literal)+), $($rest:tt)*
    ] $($frest:tt)*) $($srest:tt)*) => {
        $crate::struct_elaborate!(__builder__ fields([type($ty), value($($value)*), docs(concat!($($fdoc)+)), $($rest)*] $($frest)*) $($srest)*);
    };


    // Push down the field to the accumulator
    (__builder__ fields([
        type($ty:ty), value($($value:tt)*), docs($fdoc:expr), name($field:ident), $($rest:tt)*
    ] $($frest:tt)*) accum($($faccum:tt)*) original($($original:tt)*)) => {
        $crate::struct_elaborate!(__builder_type__ fields($($frest)*) accum(
            $($faccum)*
            {
                name($field),
                type($ty),
                value($($value)*),
                docs($fdoc),
            },
        ) original($($original)*));
    };

    // Write the final "elaborated" struct into a call to the `next` macro.
    (__finalize__
        accum($($accum:tt)*) original($next:ident $( ($($next_args:tt)*) )? =>
        $( #[ $sdoc:meta ] )* struct $name:ident <$lt:lifetime> $(: $super:ident)? {})
    ) => {
        $next ! (
            $( $($next_args)* , )?
            struct $name <$lt> {
                super($($super)?),
                docs($($sdoc),*),
                fields(
                    $($accum)*
                ),
            }
        );
    }
}

/// Generates a protocol definition from a Rust-like DSL.
///
/// LIMITATION: Enums must appear after structs.
///
/// ```nocompile
/// struct Foo {
///     bar: u8,
///     baz: u16 = 123,
/// }
///
/// #[repr(u8)]
/// enum MyEnum {
///     A = 1,
///     B = 2,
/// }
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! __protocol {
    (
        $( $( #[ doc = $sdoc:literal ] )*
            struct $name:ident <$lt:lifetime> $(: $super:ident)? { $($struct:tt)+ }
        )+
        $(  #[repr($repr:ty)] $( #[ doc = $edoc:literal ] )*
            enum $ename:ident { $($(#[$default:meta])? $emname:ident = $emvalue:literal),+ $(,)? }
        )*
    ) => {
        use $crate::protocol_builder;
        #[allow(unused)]
        use $crate::prelude::*;

        $(
            $crate::paste!(
                $crate::struct_elaborate!(protocol_builder(__struct__) => $( #[ doc = $sdoc ] )* struct $name <$lt> $(: $super)? { $($struct)+ } );
                $crate::struct_elaborate!(protocol_builder(__meta__) => $( #[ doc = $sdoc ] )* struct $name <$lt> $(: $super)? { $($struct)+ } );
                $crate::struct_elaborate!(protocol_builder(__builder__) => $( #[ doc = $sdoc ] )* struct $name <$lt> $(: $super)? { $($struct)+ } );
            );
        )+

        $(
            $crate::paste!(
                $(#[doc = $edoc])*
                #[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
                #[repr($repr)]
                pub enum $ename {
                    $($(#[$default])? $emname = $emvalue),+
                }

                impl $crate::prelude::EnumMeta for $ename {
                    const VALUES: &'static [(&'static str, usize)] = &[
                        $((stringify!($emname), $emvalue as _)),+
                    ];
                }

                $crate::declare_type!(DataType, $ename, flags=[enum], {
                });

                impl<'a> $crate::prelude::DecoderFor<'a, $ename> for $ename {
                    fn decode_for(buf: &mut &'a [u8]) -> Result<Self, ParseError> {
                        let repr = <$repr as $crate::prelude::DecoderFor<$repr>>::decode_for(buf)?;

                        match repr {
                            $(
                                $emvalue => Ok($ename::$emname),
                            )+
                            _ => Err(ParseError::InvalidData(stringify!($ename), repr as usize)),
                        }
                    }
                }

                impl $crate::prelude::EncoderFor<$ename> for $ename {
                    fn encode_for(&self, buf: &mut $crate::BufWriter<'_>) {
                        <$repr as $crate::prelude::EncoderFor<$repr>>::encode_for(&(*self as $repr), buf);
                    }
                }

                impl $crate::prelude::EncoderFor<$ename> for &'_ $ename {
                    fn encode_for(&self, buf: &mut $crate::BufWriter<'_>) {
                        <$repr as $crate::prelude::EncoderFor<$repr>>::encode_for(&(**self as $repr), buf);
                    }
                }
            );
        )*
    };
}

#[doc(inline)]
pub use __protocol as protocol;

/// Simple conditional macro to check whether values are present.
#[macro_export]
#[doc(hidden)]
macro_rules! r#if {
    (__is_empty__ [] {$($true:tt)*} else {$($false:tt)*}) => {
        $($true)*
    };
    (__is_empty__ [$($x:tt)+] {$($true:tt)*} else {$($false:tt)*}) => {
        $($false)*
    };
    (__has__ [$($x:tt)+] {$($true:tt)*}) => {
        $($true)*
    };
    (__has__ [] {$($true:tt)*}) => {
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! make_static {
    (type=$ty:ty) => { $crate::type_mapper::map_types!(match $ty {
        _T<'a> => _T<'static>,
        _T<'a, _T2> => _T<'static, recurse!(_T2)>,
        _T<'a, _T2, _T3> => _T<'static, recurse!(_T2), recurse!(_T3)>,
        _T<_T2> => _T<recurse!(_T2)>,
        _T<_T2, _T3> => _T<recurse!(_T2), recurse!(_T3)>,
        _T => _T,
    }) };
}

#[doc(hidden)]
#[macro_export]
macro_rules! protocol_builder {
    (__struct__, struct $name:ident <$lt:lifetime> {
        super($($super:ident)?),
        docs($($sdoc:meta),*),
        fields($({
            name($field:ident),
            type($type:ty),
            value($(value = ($value:expr))? $(no_value = $no_value:ident)? $(auto = $auto:ident)?),
            docs($fdoc:expr),
            $($rest:tt)*
        },)*),
    }) => {
        $crate::paste!(
            $( #[$sdoc] )?
            #[doc = concat!("\n\nAvailable fields: \n\n" $(
                , " - [`", stringify!($field), "`](Self::", stringify!($field), "()): ", $fdoc,
                $( "  (value = `", stringify!($value), "`)", )?
                "\n\n"
            )* )]
            #[derive(Copy, Clone, Default)]
            pub struct $name<$lt> {
                pub(crate) buf: &$lt [u8],
                $(
                    $field: $type,
                )*
            }

            impl PartialEq for $name<'_> {
                fn eq(&self, other: &Self) -> bool {
                    self.buf.eq(other.buf)
                }
            }

            impl Eq for $name<'_> {}

            impl std::fmt::Debug for $name<'_> {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    let mut s = f.debug_struct(stringify!($name));
                    $(
                        s.field(stringify!($field), &self.$field);
                    )*
                    s.finish()
                }
            }

            impl AsRef<[u8]> for $name<'_> {
                fn as_ref(&self) -> &[u8] {
                    self.buf.as_ref()
                }
            }

            #[allow(unused)]
            impl <'a> $name<'a> {
                /// Checks the constant values for this struct to determine whether
                /// this message matches.
                #[inline]
                pub const fn is_buffer(buf: &'a [u8]) -> bool {
                    <Self as $crate::prelude::StructMeta>::FIELDS.matches_field_constants(buf)
                }

                /// Creates a new instance of this struct from a given buffer.
                #[inline]
                pub fn new(mut buf: &'a [u8]) -> Result<Self, ParseError> {
                    let res = <$name<'a> as $crate::prelude::DecoderFor<$name<'a>>>::decode_for(&mut buf);
                    if buf.len() > 0 {
                        return Err(ParseError::TooLong(buf.len()));
                    }
                    res
                }

                $(
                    #[doc = $fdoc]
                    pub fn $field(&self) -> $type {
                        self.$field
                    }
                )*

                pub fn to_vec(self) -> Vec<u8> {
                    self.buf.to_vec()
                }
            }
        );
    };

    (__meta__, struct $name:ident <$lt:lifetime> {
        super($($super:ident)?),
        docs($($sdoc:meta),*),
        fields($({
            name($field:ident),
            type($type:ty),
            value($(value = ($value:expr))? $(no_value = $no_value:ident)? $(auto = $auto:ident)?),
            docs($fdoc:expr),
            $($rest:tt)*
        },)*),
    }) => {
        $crate::paste!(
            #[allow(unused)]
            #[allow(non_camel_case_types)]
            #[derive(Eq, PartialEq)]
            #[repr(u8)]
            enum [<$name Fields>] {
                $(
                    $field,
                )*
            }

            /// Implements a trait containing the fields of the struct, allowing
            /// us to compute some useful things.
            impl <$lt> $crate::prelude::StructMeta for $name<$lt> {
                const FIELDS: $crate::prelude::StructFields = $crate::prelude::StructFields::new(&
                    $crate::prelude::StructFieldComputed::new([
                        $(
                            $crate::prelude::StructField {
                                name: stringify!($field),
                                meta: &(<$type as DataType>::META),
                                value: $crate::r#if!(__is_empty__ [$($value)?] { None } else { Some($($value)? as usize) }),
                            },
                        )*
                    ]));

                type Struct<'__struct> = $name<'__struct>;

                fn new<'__next_lifetime>(buf: &'__next_lifetime [u8]) -> Result<Self::Struct<'__next_lifetime>, ParseError> {
                    Self::Struct::<'__next_lifetime>::new(buf)
                }

                fn to_vec(&self) -> Vec<u8> {
                    self.buf.to_vec()
                }
            }

            /// Implements a trait indicating that the struct has a fixed size.
            /// This needs to be a trait-generic rather than and associated
            /// constant for us to use elsewhere.
            impl $crate::prelude::StructAttributeFixedSize<{<$name<'_> as $crate::prelude::StructMeta>::IS_FIXED_SIZE}> for $name<'_> {
            }

            /// Implements a trait indicating that the struct has a length field.
            impl $crate::prelude::StructAttributeHasLengthField<{<$name<'_> as $crate::prelude::StructMeta>::HAS_LENGTH_FIELD}> for $name<'_> {
            }

            /// Implements a trait indicating that the struct has a field count.
            impl $crate::prelude::StructAttributeFieldCount<{<$name<'_> as $crate::prelude::StructMeta>::FIELD_COUNT}> for $name<'_> {
            }

            $crate::declare_type!(DataType, $name<'a>, builder: [<$name Builder>], flags=[struct], {});

            impl<'a> $crate::prelude::DecoderFor<'a, $name<'a>> for $name<'a> {
                fn decode_for(buf: &mut &'a [u8]) -> Result<Self, ParseError> {
                    let mut new = $name::default();
                    let start_buf = *buf;
                    $(
                        new.$field = <$type as $crate::prelude::DecoderFor<$type>>::decode_for(buf)?;
                    )*
                    new.buf = start_buf;
                    Ok(new)
                }
            }

            impl<'a> $crate::prelude::EncoderFor<$name<'static>> for $name<'a> {
                fn encode_for(&self, buf: &mut $crate::BufWriter<'_>) {
                    buf.write(&self.buf);
                }
            }
        );
    };

    (__struct_builder__, $( #[$sdoc:meta] )? struct $orig_name:ident $name:ident<$lt:lifetime> $($use_default:ident)? ($(
        (
            docs($sfdoc:expr)
            name($sfield:ident)
            type($stype:ty)
            generic($sgeneric:ident)
            no_value($sno_value:ident)
        )
    )*)
    fields($({
        name($field:ident),
        type($type:ty),
        value($(value = ($value:expr))? $(no_value = $no_value:ident)? $(auto = $auto:ident)?),
        docs($fdoc:expr)
    },)*),
     ) => {
        #[derive(Debug, Default)]
        pub struct $name<$($sgeneric = $crate::make_static!(type=$stype)),*> where $(
            $sgeneric: $crate::prelude::EncoderFor<$crate::make_static!(type=$stype)>,
        )* {
        // Because of how macros may expand in the context of struct
        // fields, we need to do a * repeat, then a ? repeat and
        // somehow use $no_value in the remainder of the pattern.
        $(
            #[doc = $sfdoc]
            pub $sfield: $sgeneric,
        )*
        }

        impl <$($sgeneric),*> $crate::prelude::BuilderFor for $name<$($sgeneric),*> where $(
            $sgeneric: $crate::prelude::EncoderFor<$crate::make_static!(type=$stype)>,
        )* {
            type Message = $orig_name<'static>;
        }

        impl <$($sgeneric),*> $crate::prelude::EncoderFor<$orig_name<'static>> for $name<$($sgeneric),*> where $(
            $sgeneric: $crate::prelude::EncoderFor<$crate::make_static!(type=$stype)>,
        )* {
            fn encode_for(&self, buf: &mut $crate::BufWriter<'_>) {
                #[allow(unused)]
                let value = self;
                $(
                    $crate::r#if!(__is_empty__ [$($value)?] {
                        $crate::r#if!(__is_empty__ [$($auto)?] {
                            // value is no_value (present in builder)
                            $crate::prelude::EncoderFor::<$crate::make_static!(type=$type)>::encode_for(&value.$field, buf);
                        } else {
                            // value is auto (not present in builder)
                            let auto_offset = buf.size();
                            $crate::prelude::EncoderFor::<$crate::make_static!(type=$type)>::encode_for(&<$type as Default>::default(), buf);
                        });
                    } else {
                        // value is set, not present in builder
                        <$type as DataType>::encode_usize(buf, $($value)? as usize);
                    });
                )*

                $(
                    $crate::r#if!(__has__ [$($auto)?] {
                        let len = (buf.size() - auto_offset) as u32;
                        buf.write_rewind(auto_offset, &len.to_be_bytes());
                    });
                )*
            }
        }

        impl <$($sgeneric),*> $crate::prelude::EncoderFor<$orig_name<'static>> for &'_ $name<$($sgeneric),*> where $(
            $sgeneric: $crate::prelude::EncoderFor<$crate::make_static!(type=$stype)>,
        )* {
            fn encode_for(&self, buf: &mut $crate::BufWriter<'_>) {
                <$name<$($sgeneric),*> as $crate::prelude::EncoderFor<$orig_name<'static>>>::encode_for(self, buf);
            }
        }
    };

    (__builder__, struct $name:ident <$lt:lifetime> {
        super($($super:ident)?),
        docs($($sdoc:meta),*),
        fields($({
            name($field:ident),
            type($type:ty),
            value($(value = ($value:expr))? $(no_value = $no_value:ident)? $(auto = $auto:ident)?),
            docs($fdoc:expr),
            $($rest:tt)*
        },)*),
    }) => {
        $crate::paste!(
            $crate::r#if!(__is_empty__ [$($($no_value)?)*] {
                $crate::protocol_builder!(__struct_builder__, $( #[$sdoc] )? struct $name [<$name Builder>]<$lt> __use_default_to_construct
                    ()
                    fields($({
                        name($field),
                        type($type),
                        value($(value = ($value))? $(no_value = $no_value)? $(auto = $auto)?),
                        docs($fdoc)
                    },)*),
                );
            } else {
                $crate::protocol_builder!(__struct_builder__, $( #[$sdoc] )? struct $name [<$name Builder>]<$lt>
                    // Because of how macros may expand in the context of struct
                    // fields, we need to do a * repeat, then a ? repeat and
                    // somehow use $no_value in the remainder of the pattern.
                    ($($(
                        (
                            docs($fdoc)
                            name($field)
                            type($type)
                            generic([<$field:upper>])
                            no_value($no_value)
                        )
                    )?)*) fields($({
                        name($field),
                        type($type),
                        value($(value = ($value))? $(no_value = $no_value)? $(auto = $auto)?),
                        docs($fdoc)
                    },)*),
                );
            });
        );
    };
}

#[cfg(test)]
mod tests {
    use crate::prelude::StructAttributeHasLengthField;
    use pretty_assertions::assert_eq;

    mod fixed_only {
        use super::*;

        crate::protocol!(
            struct FixedOnly<'a> {
                a: u8,
            }
        );

        static_assertions::assert_impl_any!(FixedOnly::<'static>: StructAttributeHasLengthField<false>);
        static_assertions::assert_not_impl_any!(FixedOnly::<'static>: StructAttributeHasLengthField<true>);

        static_assertions::assert_impl_all!(FixedOnly<'static>: DecoderFor<'static, FixedOnly<'static>>, EncoderFor<FixedOnly<'static>>);
    }

    mod fixed_only_value {
        crate::protocol!(
            struct FixedOnlyValue <'a> {
                a: u8 = 1,
            }
        );
    }

    mod mixed {
        crate::protocol!(
            struct Mixed <'a> {
                a: u8 = 1,
                s: ZTString<'a>,
            }
        );
    }

    mod docs {
        crate::protocol!(
            /// Docs
            struct Docs <'a> {
                /// Docs
                a: u8 = 1,
                /// Docs
                s: ZTString<'a>,
            }
        );
    }

    mod length {
        use super::*;

        crate::protocol!(
            struct WithLength<'a> {
                a: u8,
                l: len,
            }
        );

        static_assertions::assert_impl_any!(WithLength::<'static>: StructAttributeHasLengthField<true>);
        static_assertions::assert_not_impl_any!(WithLength::<'static>: StructAttributeHasLengthField<false>);
    }

    mod array {
        crate::protocol!(
            struct StaticArray<'a> {
                a: u8,
                l: [u8; 4],
            }
        );
    }

    mod string {
        crate::protocol!(
            struct HasLString<'a> {
                s: LString<'a>,
            }
        );
    }

    mod has_enum {
        crate::protocol!(
            struct HasEnum<'a> {
                e: MyEnum,
            }

            #[repr(u8)]
            enum MyEnum {
                #[default]
                A = 1,
                B = 2,
            }
        );
    }

    macro_rules! assert_stringify {
        (($($struct:tt)*), ($($expected:tt)*)) => {
            $crate::struct_elaborate!(assert_stringify(__internal__ ($($expected)*)) => $($struct)*);
        };
        (__internal__ ($($expected:tt)*), $($struct:tt)*) => {
            // We don't want whitespace to impact this comparison
            if stringify!($($struct)*).replace(char::is_whitespace, "") != stringify!($($expected)*).replace(char::is_whitespace, "") {
                assert_eq!(stringify!($($struct)*), stringify!($($expected)*));
            }
        };
    }

    #[test]
    fn empty_struct() {
        assert_stringify!((struct Foo <'a> {}), (struct Foo <'a> { super (), docs(), fields(), }));
    }

    #[test]
    fn fixed_size_fields() {
        assert_stringify!((struct Foo<'a>  {
                    a: u8,
                    b: u8,
                }), (struct Foo<'a>
        {
            super (),
            docs(),
            fields({
                name(a), type (u8), value(no_value = no_value),
                docs(concat!("`", stringify! (a), "` field.")),
            },
            {
                name(b), type (u8), value(no_value = no_value),
                docs(concat!("`", stringify! (b), "` field.")),
            },),
        }));
    }

    #[test]
    fn mixed_fields() {
        assert_stringify!((struct Foo<'a> {
                    a: u8,
                    l: len,
                    s: ZTString,
                    c: i16,
                    d: [u8; 4],
                    e: ZTArray<ZTString>,
                }), (struct Foo<'a>
        {
            super (),
            docs(),
            fields({
                name(a), type (u8), value(no_value = no_value),
                docs(concat!("`", stringify! (a), "` field.")),
            },
            {
                name(l), type ($crate::prelude::Length),
                value(auto = auto), docs(concat!("`", stringify! (l), "` field.")),
            },
            {
                name(s), type (ZTString),
                value(no_value = no_value),
                docs(concat!("`", stringify! (s), "` field.")),
            },
            {
                name(c), type (i16), value(no_value = no_value),
                docs(concat!("`", stringify! (c), "` field.")),
            },
            {
                name(d), type ([u8; 4]),
                value(no_value = no_value),
                docs(concat!("`", stringify! (d), "` field.")),
            },
            {
                name(e), type (ZTArray<ZTString>),
                value(no_value = no_value),
                docs(concat!("`", stringify! (e), "` field.")),
            },
        ),
        }));
    }
}