derive_codec_sv2 1.1.3

Derive macro for Sv2 binary format serializer and deserializer
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! # Procedural Macros for Automatic Serialization and Deserialization
//!
//! Provides procedural macros for deriving serialization and deserialization
//! traits on structs used in binary protocol communication. The macros `Encodable` and `Decodable`
//! generate implementations of encoding and decoding behaviors, making it simpler to work with
//! binary data by automatically handling field parsing, sizing, and transformation.
//!
//! ## Overview
//!
//! These macros parse struct definitions to produce code that supports efficient and type-safe
//! serialization and deserialization. Each field within a struct is processed based on its type and
//! associated generics, allowing for custom encoding schemes and alignment with protocol
//! requirements. Additionally, the macros enable flexible handling of lifetimes and static
//! references to ensure compatibility across different use cases.
//!
//! ## Available Macros
//!
//! - **`Encodable`**: Automatically implements encoding logic, converting a struct's fields into a
//!   binary format.
//!   - **Attributes**: `#[already_sized]` (optional) to specify that a struct's size is fixed at
//!     compile-time.
//!   - **Generated Traits**: `EncodableField` (field-by-field encoding) and `GetSize` (size
//!     calculation).
//!
//! - **`Decodable`**: Automatically implements decoding logic, allowing a struct to be
//!   reconstructed from binary data.
//!   - **Generated Methods**: `get_structure` (defines field structure) and `from_decoded_fields`
//!     (builds the struct from decoded fields).
//!
//! ## Internal Structure
//!
//! ### `is_already_sized`
//! Checks if the `#[already_sized]` attribute is present on the struct, allowing certain
//! optimizations in generated code for fixed-size structs.
//!
//! ### `get_struct_properties`
//! Parses and captures a struct’s name, generics, and field data, enabling custom encoding and
//! decoding functionality.
//!
//! ### Custom Implementations
//! The `Encodable` macro generates an `EncodableField` implementation by serializing each field,
//! while `Decodable` constructs the struct from binary data. Both macros provide support for
//! structs with or without lifetimes, ensuring versatility in applications that require efficient,
//! protocol-level data handling.
#![no_std]

extern crate alloc;
extern crate proc_macro;

use alloc::{
    format,
    string::{String, ToString},
    vec::Vec,
};
use core::iter::FromIterator;
use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};

// Reserved field names to avoid conflicts
const RESERVED_FIELDS: [&str; 2] = ["__decodable_internal_data", "__decodable_internal_offset"];

// Checks if a `TokenStream` contains a group with a bracket delimiter (`[]`),
// and further examines if the group has an identifier called `already_sized`.
//
// Iterates through the `TokenStream`, searching for a group of tokens
// that is delimited by square brackets (`[]`). Once a group is found, it looks inside
// the group for an identifier named `already_sized`. If such an identifier is found,
// the function returns `true`. Otherwise, it returns `false`.
//
// # Example
//
// ```ignore
// use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
// use quote::quote;
//
// let input: TokenStream = quote! {
//     [already_sized]
// };
//
// // Call the function to check if `already_sized` is present inside the bracket group.
// assert_eq!(is_already_sized(input), true);
//
// // Now let's try another TokenStream that doesn't contain the `already_sized` identifier.
// let input_without_already_sized: TokenStream = quote! {
//     [some_other_ident]
// };
//
// assert_eq!(is_already_sized(input_without_already_sized), false);
// ```
//
// In this example, the function successfully detects the presence of the `already_sized`
// identifier when it's wrapped inside brackets, and returns `true` accordingly.
fn is_already_sized(item: TokenStream) -> bool {
    let stream = item.into_iter();

    for next in stream {
        if let TokenTree::Group(g) = next.clone() {
            if g.delimiter() == proc_macro::Delimiter::Bracket {
                for t in g.stream().into_iter() {
                    if let TokenTree::Ident(i) = t {
                        if i.to_string() == "already_sized" {
                            return true;
                        }
                    }
                }
            }
        }
    }
    false
}

// Filters out attributes from a `TokenStream` that are prefixed with `#`.
//
// Removes all Rust attributes (e.g., `#[derive(...)]`, `#[cfg(...)]`)
// from the provided `TokenStream`, leaving behind only the core structure and
// its fields. This is useful in procedural macros when you want to manipulate
// the underlying data without the attributes.
//
// # Example
//
// ```ignore
// use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
// use quote::quote;
//
// let input: TokenStream = quote! {
//     #[derive(Debug, Clone)]
//     pub struct MyStruct {
//         pub field1: i32,
//         #[cfg(feature = "extra")]
//         pub field2: String,
//     }
// };
//
// let cleaned: TokenStream = remove_attributes(input);
//
// let expected_output: TokenStream = quote! {
//     pub struct MyStruct {
//         pub field1: i32,
//         pub field2: String,
//     }
// };
//
// assert_eq!(cleaned.to_string(), expected_output.to_string());
// ```
//
// In this example, the `#[derive(Debug, Clone)]` and `#[cfg(feature = "extra")]`
// attributes were removed, leaving just the plain `struct` with its fields.
fn remove_attributes(item: TokenStream) -> TokenStream {
    let stream = item.into_iter();
    let mut is_attribute = false;
    let mut result = Vec::new();

    for next in stream {
        match next.clone() {
            TokenTree::Punct(p) => {
                if p.to_string() == "#" {
                    is_attribute = true;
                } else {
                    result.push(next.clone());
                }
            }
            TokenTree::Group(g) => {
                if is_attribute {
                    continue;
                } else {
                    let delimiter = g.delimiter();
                    let cleaned_group = remove_attributes(g.stream());
                    let cleaned_group = TokenTree::Group(Group::new(delimiter, cleaned_group));
                    result.push(cleaned_group);
                }
            }
            _ => {
                is_attribute = false;
                result.push(next.clone());
            }
        }
    }

    TokenStream::from_iter(result)
}

// Represents the current state of the parser while processing a struct.
enum ParserState {
    // Indicates that the parser is processing the struct's name.
    Name,
    // Indicates that the parser is processing the struct's type.
    Type,
    // Indicates that the parser is inside the angle brackets for generics.
    //
    // The `usize` value represents the depth of nested generics
    Generics(usize),
}

// Represents a parsed struct, including its name, generics, and fields.
//
// # Examples
//
// ```ignore
// struct MyStruct<T> {
//     pub field1: i32,
//     pub field2: String,
// }
//
// let parsed = ParsedStruct {
//     name: "MyStruct".to_string(),
//     generics: "T".to_string(),
//     fields: vec![
//         ParsedField {
//             name: "field1".to_string(),
//             type_: "i32".to_string(),
//             generics: "".to_string(),
//         },
//         ParsedField {
//             name: "field2".to_string(),
//             type_: "String".to_string(),
//             generics: "".to_string(),
//         },
//     ],
// };
// ```
#[derive(Clone, Debug)]
struct ParsedStruct {
    // Name of the struct.
    pub name: String,
    // Generics associated with the struct, if any.
    pub generics: String,
    // List of fields within the struct.
    pub fields: Vec<ParsedField>,
}

// Represents a parsed field within a struct, including its name, type, and any associated generics.
//
// # Examples
//
// ```ignore
// // Given a struct field definition:
// // data: Option<T>,
//
// let field = ParsedField {
//     name: "data".to_string(),
//     type_: "Option".to_string(),
//     generics: "T".to_string(),
// };
// ```
#[derive(Clone, Debug)]
struct ParsedField {
    // Name of the field.
    name: String,
    // Span of the field name.
    span: Span,
    // Type of the field.
    type_: String,
    // Generics associated with the field, if any.
    generics: String,
}

struct MacroError {
    span: Span,
    message: String,
}

impl ParsedField {
    pub fn new() -> Self {
        ParsedField {
            name: "".to_string(),
            span: Span::call_site(),
            type_: "".to_string(),
            generics: "".to_string(),
        }
    }

    pub fn get_generics(&self) -> String {
        if self.generics == "<'decoder>" || self.generics.is_empty() {
            "".to_string()
        } else {
            format!("::{}", self.generics.clone())
        }
    }
    pub fn as_static(&self) -> String {
        if self.generics.is_empty() {
            "".to_string()
        } else {
            ".into_static()".to_string()
        }
    }

    pub fn is_empty(&self) -> bool {
        self.name.is_empty() && self.type_.is_empty() && self.generics.is_empty()
    }
}

// Return `compile_error!(...)` tokens so the downstream crate gets a normal
// compiler error at the derive site instead of a proc-macro panic.
fn emit_compile_error(message: &str) -> TokenStream {
    emit_compile_error_at(Span::call_site(), message)
}

fn emit_compile_error_at(span: Span, message: &str) -> TokenStream {
    let mut inner = TokenStream::new();
    let mut literal = Literal::string(message);
    literal.set_span(span);
    inner.extend([TokenTree::Literal(literal)]);

    let mut group = Group::new(Delimiter::Parenthesis, inner);
    group.set_span(span);
    let mut bang = Punct::new('!', Spacing::Alone);
    bang.set_span(span);
    let mut semicolon = Punct::new(';', Spacing::Alone);
    semicolon.set_span(span);

    TokenStream::from_iter([
        TokenTree::Ident(Ident::new("compile_error", span)),
        TokenTree::Punct(bang),
        TokenTree::Group(group),
        TokenTree::Punct(semicolon),
    ])
}

fn parse_generated_tokens(result: &str) -> TokenStream {
    result.parse().unwrap_or_else(|err| {
        emit_compile_error(&format!(
            "derive_codec_sv2 generated invalid Rust tokens: {}",
            err
        ))
    })
}

// Extracts properties of a struct, including its name, generics, and fields.
//
// Processes a token stream, filtering out attributes and extracting
// core components such as the struct's name, generics, and fields. It expects the
// token stream to represent a struct declaration.
//
// # Examples
//
// ```ignore
// use quote::quote;
//
// struct MyStruct<T> {
//     field1: i32,
// }
//
// let tokens = quote! {struct MyStream<T> { field1: i32 }};
// let parsed_struct = get_struct_properties(tokens);
//
// assert_eq!(parsed_struct.name, "MyStruct");
// assert_eq!(parsed_struct.generics, "T");
// assert_eq!(parsed_struct.fields.len(), 1);
// assert_eq!(parsed_struct.fields[0].name, "field1");
// assert_eq!(parsed_struct.fields[0].type_, "i32");
// ```
//
// This example demonstrates how `get_struct_properties` identifies the struct's
// name, any generic parameters, and its fields, including types and generic parameters.
fn get_struct_properties(item: TokenStream) -> Result<ParsedStruct, MacroError> {
    let item = remove_attributes(item);
    let mut stream = item.into_iter();

    // Check if the stream is a struct
    loop {
        match stream.next() {
            Some(TokenTree::Ident(i)) if i.to_string() == "struct" => break,
            Some(_) => continue,
            None => {
                return Err(MacroError {
                    span: Span::call_site(),
                    message: "Expected a struct definition".to_string(),
                })
            }
        }
    }

    // Get the struct name
    let struct_name = match stream.next() {
        Some(TokenTree::Ident(i)) => i.to_string(),
        Some(token) => {
            return Err(MacroError {
                span: token.span(),
                message: format!("Expected a struct name, found '{}'", token),
            })
        }
        None => {
            return Err(MacroError {
                span: Span::call_site(),
                message: "Struct has no name".to_string(),
            })
        }
    };

    let mut struct_generics = "".to_string();
    let group: Vec<TokenTree>;

    // Get the struct generics if any
    loop {
        match stream.next() {
            Some(TokenTree::Group(g)) => {
                group = g.stream().into_iter().collect();
                break;
            }
            Some(TokenTree::Punct(p)) => {
                struct_generics = format!("{struct_generics}{p}");
            }
            Some(TokenTree::Ident(i)) => {
                struct_generics = format!("{struct_generics}{i}");
            }
            Some(token) => {
                return Err(MacroError {
                    span: token.span(),
                    message: format!(
                        "Struct '{}' has invalid tokens before its fields: '{}'",
                        struct_name, token
                    ),
                });
            }
            None => {
                return Err(MacroError {
                    span: Span::call_site(),
                    message: format!("Struct '{}' has no fields", struct_name),
                })
            }
        };
    }

    let fields = parse_struct_fields(group)?;

    Ok(ParsedStruct {
        name: struct_name,
        generics: struct_generics,
        fields,
    })
}

// Parses the fields of a struct, scanning tokens to identify field names, types, and generics.
//
// Processes tokens for each field in a struct, managing parser states
// (`ParserState::Name`, `ParserState::Type`, and `ParserState::Generics`) to accurately parse
// complex types and nested generics within struct definitions.
//
// # Examples
//
// ```ignore
// struct MyStruct<T> {
//     field1: i32,
// }
//
// let tokens = vec![/* TokenTree representing `id: i32` */];
// let parsed_fields = parse_struct_fields(tokens);
//
// assert_eq!(parsed_fields.len(), 1);
// assert_eq!(parsed_fields[0].name, "field1");
// assert_eq!(parsed_fields[0].type_, "i32");
// assert_eq!(parsed_fields[0].generics, "");
// ```
//
// This example shows how `parse_struct_fields` handles both a primitive field (`id`) and a
// generic field (`data`) within a struct, including parsing of generic parameters.
fn parse_struct_fields(group: Vec<TokenTree>) -> Result<Vec<ParsedField>, MacroError> {
    let mut fields = Vec::new();
    let mut field_ = ParsedField::new();
    let mut field_parser_state = ParserState::Name;
    let mut last_span = Span::call_site();
    for token in group {
        last_span = token.span();
        match (token, &field_parser_state) {
            (TokenTree::Ident(i), ParserState::Name) => {
                if i.to_string() == "pub" {
                    continue;
                } else {
                    field_.name = i.to_string();
                    field_.span = i.span();
                }
            }
            (TokenTree::Ident(i), ParserState::Type) => {
                field_.type_ = i.to_string();
            }
            (TokenTree::Ident(i), ParserState::Generics(_)) => {
                field_.generics = format!("{}{}", field_.generics, i);
            }
            (TokenTree::Punct(p), ParserState::Name) => {
                if p.to_string() == ":" {
                    field_parser_state = ParserState::Type
                } else {
                    return Err(MacroError {
                        span: p.span(),
                        message: format!("Unexpected token '{}' in parsing {:#?}", p, field_),
                    });
                }
            }
            (TokenTree::Punct(p), ParserState::Type) => match p.to_string().as_ref() {
                "," => {
                    field_parser_state = ParserState::Name;
                    fields.push(field_.clone());
                    field_ = ParsedField::new();
                }
                "<" => {
                    field_.generics = "<".to_string();
                    field_parser_state = ParserState::Generics(0);
                }
                _ => {
                    return Err(MacroError {
                        span: p.span(),
                        message: format!("Unexpected token '{}' in parsing {:#?}", p, field_),
                    })
                }
            },
            (TokenTree::Punct(p), ParserState::Generics(open_brackets)) => {
                match p.to_string().as_ref() {
                    "'" => {
                        field_.generics = format!("{}{}", field_.generics, p);
                    }
                    "<" => {
                        field_.generics = format!("{}{}", field_.generics, p);
                        field_parser_state = ParserState::Generics(open_brackets + 1);
                    }
                    ">" => {
                        field_.generics = format!("{}{}", field_.generics, p);
                        if open_brackets == &0 {
                            field_parser_state = ParserState::Type
                        } else {
                            field_parser_state = ParserState::Generics(open_brackets - 1);
                        }
                    }
                    _ => {
                        field_.generics = format!("{}{}", field_.generics, p);
                    }
                }
            }
            (token, _) => {
                return Err(MacroError {
                    span: token.span(),
                    message: format!("Unexpected token '{}' while parsing struct fields", token),
                });
            }
        }
    }

    if !field_.is_empty() {
        if field_.name.is_empty() || field_.type_.is_empty() {
            return Err(MacroError {
                span: last_span,
                message: format!(
                    "Incomplete field definition near '{}'; expected a named field like `name: Type`",
                    field_.name
                ),
            });
        }
        fields.push(field_);
    }

    Ok(fields)
}

/// Derives the `Decodable` trait, generating implementations for deserializing a struct from a
/// byte stream, including its structure, field decoding, and a method for creating a static
/// version.
///
/// This procedural macro generates the `Decodable` trait for a struct, which allows it to be
/// decoded from a binary stream, with support for handling fields of different types and
/// nested generics. The macro also includes implementations for `from_decoded_fields`,
/// `get_structure`, and methods to return a static version of the struct.
///
/// # Example
///
/// Given a struct:
///
/// ```ignore
/// struct Test {
///     a: u32,
///     b: u8,
///     c: U24,
/// }
/// ```
///
/// Using `#[derive(Decodable)]` on `Test` generates the following implementations:
///
/// ```ignore
/// mod impl_parse_decodable_test {
///     use ::binary_sv2::{
///             decodable::{DecodableField, FieldMarker},
///             Decodable, Error, SizeHint,
///     };
///     use super::*;
///
///     struct Test {
///         a: u32,
///         b: u8,
///         c: U24,
///     }
///
///     impl<'decoder> Decodable<'decoder> for Test {
///         fn get_structure(__decodable_internal_data: &[u8]) -> Result<Vec<FieldMarker>, Error> {
///             let mut fields = Vec::new();
///             let mut __decodable_internal_offset = 0;
///
///             let a: Vec<FieldMarker> = u32::get_structure(&__decodable_internal_data[__decodable_internal_offset..])?;
///             __decodable_internal_offset += a.size_hint_(&__decodable_internal_data, __decodable_internal_offset)?;
///             let a = a.try_into()?;
///             fields.push(a);
///
///             let b: Vec<FieldMarker> = u8::get_structure(&__decodable_internal_data[__decodable_internal_offset..])?;
///             __decodable_internal_offset += b.size_hint_(&__decodable_internal_data, __decodable_internal_offset)?;
///             let b = b.try_into()?;
///             fields.push(b);
///
///             let c: Vec<FieldMarker> = U24::get_structure(&__decodable_internal_data[__decodable_internal_offset..])?;
///             __decodable_internal_offset += c.size_hint_(&__decodable_internal_data, __decodable_internal_offset)?;
///             let c = c.try_into()?;
///             fields.push(c);
///
///             Ok(fields)
///         }
///
///         fn from_decoded_fields(mut __decodable_internal_data: Vec<DecodableField<'decoder>>) -> Result<Self, Error> {
///             Ok(Self {
///                 c: U24::from_decoded_fields(
///                     __decodable_internal_data.pop().ok_or(Error::NoDecodableFieldPassed)?.into(),
///                 )?,
///                 b: u8::from_decoded_fields(
///                     __decodable_internal_data.pop().ok_or(Error::NoDecodableFieldPassed)?.into(),
///                 )?,
///                 a: u32::from_decoded_fields(
///                     __decodable_internal_data.pop().ok_or(Error::NoDecodableFieldPassed)?.into(),
///                 )?,
///             })
///         }
///     }
///
///     impl Test {
///         pub fn into_static(self) -> Test {
///             Test {
///                 a: self.a.clone(),
///                 b: self.b.clone(),
///                 c: self.c.clone(),
///             }
///         }
///     }
///
///     impl Test {
///         pub fn as_static(&self) -> Test {
///             Test {
///                 a: self.a.clone(),
///                 b: self.b.clone(),
///                 c: self.c.clone(),
///             }
///         }
///     }
/// }
/// ```
///
/// This generated code enables `Test` to be decoded from a binary stream, defines how each
/// field should be parsed, and provides `into_static` and `as_static` methods to facilitate
/// ownership and lifetime management of decoded fields in the struct.
#[proc_macro_derive(Decodable)]
pub fn decodable(item: TokenStream) -> TokenStream {
    let parsed_struct = match get_struct_properties(item) {
        Ok(parsed_struct) => parsed_struct,
        Err(err) => return emit_compile_error_at(err.span, &err.message),
    };
    let data_ident = RESERVED_FIELDS[0];
    let offset_ident = RESERVED_FIELDS[1];

    for field in &parsed_struct.fields {
        if RESERVED_FIELDS.contains(&field.name.as_str()) {
            return emit_compile_error_at(field.span, &format!(
                "Field name '{}' is reserved and cannot be used in struct '{}'. Rename it to avoid conflicts.",
                field.name, parsed_struct.name
            ));
        }
    }

    let mut derive_fields = String::new();

    for f in parsed_struct.fields.clone() {
        let field = format!(
            "
            if {offset} > {data}.len() {{
                return Err(Error::OutOfBound);
            }}

            let {name}: Vec<FieldMarker> = {ty}{generics}::get_structure(& {data}[{offset}..])?;

            let __size = {name}.size_hint_(&{data}, {offset})?;
            {offset} = ({offset}.checked_add(__size)
                .ok_or(Error::OutOfBound)?) ;

            let {name} = {name}.try_into()?;
            fields.push({name});
            ",
            name = f.name,
            ty = f.type_,
            generics = f.get_generics(),
            data = data_ident,
            offset = offset_ident
        );
        derive_fields.push_str(&field)
    }

    let mut derive_static_fields = String::new();
    for f in parsed_struct.fields.clone() {
        let field = format!(
            "
            {}: self.{}.clone(){},
            ",
            f.name,
            f.name,
            f.as_static(),
        );
        derive_static_fields.push_str(&field)
    }

    let mut derive_decoded_fields = String::new();
    let mut fields = parsed_struct.fields.clone();

    // Reverse the fields as they are popped out from the end of the vector but we want to pop out
    // from the front
    fields.reverse();

    // Create Struct from fields
    for f in fields.clone() {
        let field = format!(
            "
            {}: {}{}::from_decoded_fields({}.pop().ok_or(Error::NoDecodableFieldPassed)?.into())?,
            ",
            f.name,
            f.type_,
            f.get_generics(),
            data_ident
        );
        derive_decoded_fields.push_str(&field)
    }

    let impl_generics = if !parsed_struct.generics.is_empty() {
        parsed_struct.clone().generics
    } else {
        "<'decoder>".to_string()
    };

    let result = format!(
        "mod impl_parse_decodable_{} {{

    use ::binary_sv2::{{decodable::DecodableField, decodable::FieldMarker, Decodable, Error, SizeHint}};
    use super::*;

    impl{} Decodable<'decoder> for {}{} {{
        fn get_structure({}: &[u8]) -> Result<Vec<FieldMarker>, Error> {{
            let mut fields = Vec::new();
            let mut {} = 0;
            {}
            Ok(fields)
        }}

        fn from_decoded_fields(mut {}: Vec<DecodableField<'decoder>>) -> Result<Self, Error> {{
            Ok(Self {{
                {}
            }})
        }}
    }}

    impl{} {}{} {{
        pub fn into_static(self) -> {}{} {{
            {} {{
                {}
            }}
        }}
    }}
    impl{} {}{} {{
        pub fn as_static(&self) -> {}{} {{
            {} {{
                {}
            }}
        }}
    }}
    }}",
        // imports
        parsed_struct.name.to_lowercase(),
        // derive decodable
        impl_generics,
        parsed_struct.name,
        parsed_struct.generics,
        data_ident,
        offset_ident,
        derive_fields,
        data_ident,
        derive_decoded_fields,
        // impl into_static
        impl_generics,
        parsed_struct.name,
        parsed_struct.generics,
        parsed_struct.name,
        get_static_generics(&parsed_struct.generics),
        parsed_struct.name,
        derive_static_fields,
        // impl into_static
        impl_generics,
        parsed_struct.name,
        parsed_struct.generics,
        parsed_struct.name,
        get_static_generics(&parsed_struct.generics),
        parsed_struct.name,
        derive_static_fields,

    );

    parse_generated_tokens(&result)
}

fn get_static_generics(gen: &str) -> &str {
    if gen.is_empty() {
        gen
    } else {
        "<'static>"
    }
}

/// Derives the `Encodable` trait, generating implementations for serializing a struct into an
/// encoded format, including methods for field serialization, calculating the encoded size,
/// and handling cases where the struct is already sized.
///
/// This procedural macro generates the `Encodable` trait for a struct, allowing each field
/// to be converted into an `EncodableField`, with support for recursive field encoding.
/// The macro also includes an implementation of the `GetSize` trait to calculate the
/// encoded size of the struct, depending on the `already_sized` attribute.
///
/// # Example
///
/// Given a struct:
///
/// ```ignore
/// struct Test {
///     a: u32,
///     b: u8,
///     c: U24,
/// }
/// ```
///
/// Using `#[derive(Encodable)]` on `Test` generates the following implementations:
///
/// ```ignore
/// mod impl_parse_encodable_test {
///     use ::binary_sv2::{encodable::EncodableField, GetSize};
///     extern crate alloc;
///     use alloc::vec::Vec;
///
///     struct Test {
///         a: u32,
///         b: u8,
///         c: U24,
///     }
///
///     impl<'decoder> From<Test> for EncodableField<'decoder> {
///         fn from(v: Test) -> Self {
///             let mut fields: Vec<EncodableField> = Vec::new();
///
///             let val = v.a;
///             fields.push(val.into());
///
///             let val = v.b;
///             fields.push(val.into());
///
///             let val = v.c;
///             fields.push(val.into());
///
///             Self::Struct(fields)
///         }
///     }
///
///     impl<'decoder> GetSize for Test {
///         fn get_size(&self) -> usize {
///             let mut size = 0;
///
///             size += self.a.get_size();
///             size += self.b.get_size();
///             size += self.c.get_size();
///
///             size
///         }
///     }
/// }
/// ```
///
/// This generated code enables `Test` to be serialized into an encoded format, defines
/// how each field should be converted, and calculates the total encoded size of the struct,
/// depending on whether it is marked as `already_sized`.
#[proc_macro_derive(Encodable, attributes(already_sized))]
pub fn encodable(item: TokenStream) -> TokenStream {
    let is_already_sized = is_already_sized(item.clone());
    let parsed_struct = match get_struct_properties(item) {
        Ok(parsed_struct) => parsed_struct,
        Err(err) => return emit_compile_error_at(err.span, &err.message),
    };
    let fields = parsed_struct.fields.clone();

    let mut field_into_decoded_field = String::new();

    // Create DecodableField from fields
    for f in fields.clone() {
        let field = format!(
            "
            let val = v.{};
            fields.push(val.into());
            ",
            f.name
        );
        field_into_decoded_field.push_str(&field)
    }

    let mut sizes = String::new();

    for f in fields {
        let field = format!(
            "
            size += self.{}.get_size();
            ",
            f.name
        );
        sizes.push_str(&field)
    }
    let impl_generics = if !parsed_struct.generics.is_empty() {
        parsed_struct.clone().generics
    } else {
        "<'decoder>".to_string()
    };

    let get_size = if is_already_sized {
        String::new()
    } else {
        format!(
            "
            impl{} ::binary_sv2::GetSize for {}{} {{
                fn get_size(&self) -> usize {{
                    let mut size = 0;
                    {}
                    size
                }}
            }}
            ",
            impl_generics, parsed_struct.name, parsed_struct.generics, sizes
        )
    };

    let result = format!(
        "mod impl_parse_encodable_{} {{

    use ::binary_sv2::{{encodable::EncodableField, GetSize}};
    use super::{};
    extern crate alloc;
    use alloc::vec::Vec;

    impl{} From<{}{}> for ::binary_sv2::EncodableField<'decoder> {{
        fn from(v: {}{}) -> Self {{
            let mut fields: Vec<EncodableField> = Vec::new();
            {}
            Self::Struct(fields)
        }}
    }}

    {}

    }}",
        // imports
        parsed_struct.name.to_lowercase(),
        parsed_struct.name,
        // impl From<Struct> for DecodableField
        impl_generics,
        parsed_struct.name,
        parsed_struct.generics,
        parsed_struct.name,
        parsed_struct.generics,
        field_into_decoded_field,
        // impl get_size
        get_size,
    );

    parse_generated_tokens(&result)
}