Skip to main content

rs2_prot_macro/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::parse::{Parse, ParseStream};
4use syn::{parse_macro_input, Data, DeriveInput, Expr, Token};
5
6struct PacketAttribute {
7    key: syn::Ident,
8    value: Expr,
9}
10
11impl Parse for PacketAttribute {
12    fn parse(input: ParseStream) -> syn::Result<Self> {
13        let key: syn::Ident = input.parse()?;
14        let _: Token![=] = input.parse()?;
15        let value = input.parse()?;
16        Ok(PacketAttribute { key, value })
17    }
18}
19
20#[proc_macro_derive(Protocol, attributes(packet))]
21pub fn protocol_derive(input: TokenStream) -> TokenStream {
22    let ast = parse_macro_input!(input as DeriveInput);
23    let enum_name = &ast.ident;
24
25    let variants = match &ast.data {
26        Data::Enum(data_enum) => &data_enum.variants,
27        _ => panic!("Protocol derive macro can only be used on enums"),
28    };
29
30    let opcode_matches = variants.iter().map(|variant| {
31        let variant_name = &variant.ident;
32        let (opcode, _) = parse_packet_attributes(variant);
33
34        let opcode_expr = opcode
35            .unwrap_or_else(|| panic!("Variant {} must have an 'opcode' in its #[packet] attribute", variant_name));
36
37        quote! {
38            #enum_name::#variant_name => #opcode_expr,
39        }
40    });
41
42    let size_matches = variants.iter().map(|variant| {
43        let variant_name = &variant.ident;
44        let (_, size) = parse_packet_attributes(variant);
45
46        let size_expr = size
47            .unwrap_or_else(|| panic!("Variant {} must have a 'size' in its #[packet] attribute", variant_name));
48
49        quote! {
50            #enum_name::#variant_name => #size_expr,
51        }
52    });
53
54    let expanded = quote! {
55        impl #enum_name {
56            pub fn opcode(&self) -> i32 {
57                match self {
58                    #(#opcode_matches)*
59                }
60            }
61
62
63
64            pub fn size(&self) -> i32 {
65                match self {
66                    #(#size_matches)*
67                }
68            }
69        }
70    };
71
72    TokenStream::from(expanded)
73}
74
75/// Helper to find the `#[packet(...)]` attribute and parse its contents.
76/// Returns a tuple of (Option<Expr>, Option<Expr>) for (opcode, size).
77fn parse_packet_attributes(variant: &syn::Variant) -> (Option<Expr>, Option<Expr>) {
78    let mut opcode = None;
79    let mut size = None;
80
81    // Find the `#[packet(...)]` attribute.
82    let attribute = variant.attrs.iter()
83        .find(|attr| attr.path.is_ident("packet"))
84        .unwrap_or_else(|| panic!("Variant {} is missing the required #[packet(...)] attribute", variant.ident));
85
86    let parser = |input: ParseStream| {
87        syn::punctuated::Punctuated::<PacketAttribute, Token![,]>::parse_terminated(input)
88    };
89
90    let parsed_attrs = attribute.parse_args_with(parser)
91        .unwrap_or_else(|e| panic!("Failed to parse attributes for variant {}: {}", variant.ident, e));
92
93    // Find the 'opcode' and 'size' values from the parsed pairs.
94    for attr in parsed_attrs {
95        if attr.key == "opcode" {
96            opcode = Some(attr.value);
97        } else if attr.key == "size" {
98            size = Some(attr.value);
99        } else {
100            panic!("Unknown key in #[packet] attribute for variant {}: {}", variant.ident, attr.key);
101        }
102    }
103
104    (opcode, size)
105}